@woven-canvas/vue 0.1.12 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/build/index.js +17300 -26566
  2. package/build/index.umd.cjs +71 -71
  3. package/package.json +13 -11
@@ -1,44 +1,6 @@
1
- (function(V,d){typeof exports=="object"&&typeof module<"u"?d(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],d):(V=typeof globalThis<"u"?globalThis:V||self,d(V.Vue={},V.Vue))})(this,function(V,d){"use strict";var v5=Object.defineProperty;var k5=(V,d,ao)=>d in V?v5(V,d,{enumerable:!0,configurable:!0,writable:!0,value:ao}):V[d]=ao;var x=(V,d,ao)=>k5(V,typeof d!="symbol"?d+"":d,ao);var Ir,ro,oo,jn,Ws,Hs,Zs,Wt,Ue,Ks,Nr;const ao=(t,e)=>e.some(n=>t instanceof n);let xp,Tp;function xS(){return xp||(xp=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function TS(){return Tp||(Tp=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const Vu=new WeakMap,Fu=new WeakMap,pl=new WeakMap;function MS(t){const e=new Promise((n,r)=>{const o=()=>{t.removeEventListener("success",s),t.removeEventListener("error",i)},s=()=>{n(es(t.result)),o()},i=()=>{r(t.error),o()};t.addEventListener("success",s),t.addEventListener("error",i)});return pl.set(e,t),e}function AS(t){if(Vu.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)});Vu.set(t,e)}let ju={get(t,e,n){if(t instanceof IDBTransaction){if(e==="done")return Vu.get(t);if(e==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return es(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 Mp(t){ju=t(ju)}function IS(t){return TS().includes(t)?function(...e){return t.apply(Uu(this),e),es(this.request)}:function(...e){return es(t.apply(Uu(this),e))}}function NS(t){return typeof t=="function"?IS(t):(t instanceof IDBTransaction&&AS(t),ao(t,xS())?new Proxy(t,ju):t)}function es(t){if(t instanceof IDBRequest)return MS(t);if(Fu.has(t))return Fu.get(t);const e=NS(t);return e!==t&&(Fu.set(t,e),pl.set(e,t)),e}const Uu=t=>pl.get(t);function Ap(t,e,{blocked:n,upgrade:r,blocking:o,terminated:s}={}){const i=indexedDB.open(t,e),a=es(i);return r&&i.addEventListener("upgradeneeded",l=>{r(es(i.result),l.oldVersion,l.newVersion,es(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 BS=["get","getKey","getAll","getAllKeys","count"],PS=["put","add","delete","clear"],Wu=new Map;function Ip(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(Wu.get(e))return Wu.get(e);const n=e.replace(/FromIndex$/,""),r=e!==n,o=PS.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(o||BS.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 Wu.set(e,s),s}Mp(t=>({...t,get:(e,n,r)=>Ip(e,n)||t.get(e,n,r),has:(e,n)=>!!Ip(e,n)||t.has(e,n)}));const OS=["continue","continuePrimaryKey","advance"],Np={},Hu=new WeakMap,Bp=new WeakMap,DS={get(t,e){if(!OS.includes(e))return t[e];let n=Np[e];return n||(n=Np[e]=function(...r){Hu.set(this,Bp.get(this)[e](...r))}),n}};async function*RS(...t){let e=this;if(e instanceof IDBCursor||(e=await e.openCursor(...t)),!e)return;e=e;const n=new Proxy(e,DS);for(Bp.set(n,e),pl.set(n,Uu(e));e;)yield n,e=await(Hu.get(n)||e.continue()),Hu.delete(n)}function Pp(t,e){return e===Symbol.asyncIterator&&ao(t,[IDBIndex,IDBObjectStore,IDBCursor])||e==="iterate"&&ao(t,[IDBIndex,IDBObjectStore])}Mp(t=>({...t,get(e,n,r){return Pp(e,n)?RS:t.get(e,n,r)},has(e,n){return Pp(e,n)||t.has(e,n)}}));var sn=Symbol.for("__woven_ecs_schema_default__"),Br=class{},zS=new Set(["string","number","boolean","binary"]);function Op(t,e){const n=t.def.type;if(!zS.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 $S=class extends Br{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 Br{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}},LS=class extends Br{constructor(){super(...arguments);x(this,"def",{type:"boolean"})}default(e){return this.def.default=e,this}[sn](){return this.def.default??!1}},VS=class extends Br{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)}},FS=class extends Br{constructor(e,n){super();x(this,"def");Op(e,"array"),this.def={type:"array",elementDef:e.def,maxLength:n}}default(e){return this.def.default=e,this}[sn](){return this.def.default??[]}},jS=class extends Br{constructor(e,n){super();x(this,"def");x(this,"elementBuilder");Op(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)}},US=class extends Br{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)}},WS=class extends Br{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]}},HS=class extends Br{constructor(){super(...arguments);x(this,"def",{type:"ref"})}[sn](){return null}},C={string:()=>new $S,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 LS,binary:()=>new VS,enum:t=>new WS(t),array:(t,e)=>new FS(t,e),tuple:(t,e)=>new jS(t,e),buffer:t=>new US(t),ref:()=>new HS},Pr=class{constructor(t){x(this,"fieldDef");this.fieldDef=t}getDefaultValue(){return this.fieldDef.schemaDefault}};function Gs(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 ZS(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 KS(t){return t!=="float32"&&t!=="float64"}var YS=class extends Pr{constructor(e){super(e);x(this,"useAtomics");this.useAtomics=KS(e.btype)}initializeStorage(e,n){const r=Gs(this.fieldDef.btype),o=new n(e*r),s=ZS(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}},qS=512,GS=256,Dp=new TextEncoder,Rp=new TextDecoder;function zp(t){switch(t.type){case"number":return Gs(t.btype);case"boolean":return 1;case"string":{const e=t.maxLength||qS;return Math.ceil((e+4)/4)*4}case"binary":{const e=t.maxLength||GS;return Math.ceil((e+4)/4)*4}}}function ml(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 $p=(Ir=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=zp(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+Ir.LENGTH_BYTES,s=[];switch(this.elementDef.type){case"number":{const i=ml(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(Rp.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+Ir.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=ml(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=Dp.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+Ir.LENGTH_BYTES;switch(this.elementDef.type){case"number":{const i=ml(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 Rp.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+Ir.LENGTH_BYTES;switch(this.elementDef.type){case"number":{const a=ml(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=Dp.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(Ir,"LENGTH_BYTES",4),Ir),JS=class extends Pr{initializeStorage(t,e){const n=zp(this.fieldDef.elementDef),r=this.fieldDef.maxLength*n+$p.LENGTH_BYTES,o=Math.ceil(r/8)*8,s=new e(t*o),i=new $p(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)}},XS=256,Lp=(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),QS=class extends Pr{initializeStorage(t,e){const r=(this.fieldDef.maxLength||XS)+Lp.LENGTH_BYTES,o=new e(t*r),s=new Lp(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)}},eE=class extends Pr{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 tE(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 nE=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=Gs(r.btype),this.capacity=e,this.bufferSize=o,this.elementsPerEntry=n/this.bytesPerElement,this.numberTypedArray=tE(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}},rE=class extends Pr{initializeStorage(t,e){const n=Gs(this.fieldDef.elementDef.btype),r=this.fieldDef.size*n,o=Math.ceil(r/8)*8,s=new e(t*o),i=new nE(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??[])}},oE=class extends Pr{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)}},ur=4294967295,Vp=33554431,Fp=25;function jp(t,e){return t&Vp|e<<Fp}function sE(t){return t&Vp}function iE(t){return t>>>Fp}function Zu(t,e,n=!0){if(t===ur)return null;const r=sE(t),o=iE(t);return n&&!e.has(r)||e.getGeneration(r)!==o?null:r}var aE=class extends Pr{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(ur),{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=Zu(l,s);return l!==ur&&c===null&&Atomics.store(i,a,ur),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=Zu(l,s);return l!==ur&&c===null&&Atomics.store(i,a,ur),c},set:i=>{const a=r[n],l=o();if(i===null||i===ur)Atomics.store(a,l,ur);else{const c=s.getGeneration(i);Atomics.store(a,l,jp(i,c))}}})}setValue(e,n,r){if(r===null||r===ur)Atomics.store(e,n,ur);else{const o=this.entityBuffer.getGeneration(r);Atomics.store(e,n,jp(r,o))}}},lE=512,cE=new TextEncoder,uE=new TextDecoder,Up=(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 uE.decode(c)}set(e,n){const r=e*this.bytesPerString,o=cE.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),dE=class extends Pr{initializeStorage(t,e){const r=(this.fieldDef.maxLength||lE)+Up.LENGTH_BYTES,o=new e(t*r),s=new Up(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)}},fE=512,hE=256,pE=new TextEncoder,mE=new TextDecoder;function Wp(t){switch(t.type){case"number":return Gs(t.btype);case"boolean":return 1;case"string":{const e=t.maxLength||fE;return Math.ceil((e+4)/4)*4}case"binary":{const e=t.maxLength||hE;return Math.ceil((e+4)/4)*4}}}function gE(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 yE=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=Wp(r),this.capacity=e,this.elementDef=r,this.tupleLength=o,r.type==="number"){const s=Gs(r.btype);this.elementsPerEntry=n/s,this.numberTypedArray=gE(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(mE.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=pE.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}},wE=class extends Pr{initializeStorage(t,e){const n=Wp(this.fieldDef.elementDef),r=this.fieldDef.length*n,o=Math.ceil(r/8)*8,s=new e(t*o),i=new yE(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)}},vE=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer,kE={string:dE,number:YS,boolean:eE,binary:QS,array:JS,tuple:wE,buffer:rE,enum:oE},Js=4294967295,Xs=0,Ku=Symbol.for("__woven_ecs_def_id_counter__");function Hp(){const t=globalThis;return t[Ku]||(t[Ku]={value:0}),t[Ku]}var bE=(jn=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 jn(e.schema,e.isSingleton)}static fromTransfer(e,n,r,o){const s=new jn(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,vE);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 aE(e,this.entityBuffer);const n=kE[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,Xs,s)}}initializeMasters(){if(this._buffer===null)throw new Error("Component buffers not initialized");for(let e=0;e<jn.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<jn.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)%jn.POOL_SIZE,n.entityId=e,n.view}write(e){var o;const n=this.writablePool[this.writePoolIndex];this.writePoolIndex=(this.writePoolIndex+1)%jn.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(jn,"POOL_SIZE",8),jn),Zp=class{constructor(t,e=!1){x(this,"_defId");x(this,"schema");x(this,"isSingleton");this._defId=Hp().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 Kp(t){return new Zp(t,!1)}var SE=class{constructor(t){x(this,"_defId");x(this,"schema");x(this,"isSingleton",!0);this._defId=Hp().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(Xs)}write(t){return this._getInstance(t).write(Xs)}copy(t,e){this._getInstance(t).copy(Xs,e)}patch(t,e){this._getInstance(t).patch(Xs,e)}snapshot(t){return this._getInstance(t).snapshot(Xs)}default(){const t={};for(const[e,n]of Object.entries(this.schema))t[e]=n[sn]();return t}},EE=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer,Le={ADDED:1,REMOVED:2,CHANGED:4,COMPONENT_ADDED:8,COMPONENT_REMOVED:16},CE=8,Yu=4,qu=0,_E=class kS{constructor(e){x(this,"buffer");x(this,"headerView");x(this,"dataView");x(this,"maxEvents");x(this,"reusableSet",new Set);this.maxEvents=e;const n=Yu+e*CE;this.buffer=new EE(n),this.headerView=new Uint32Array(this.buffer,0,1),this.dataView=new Uint32Array(this.buffer,Yu),Atomics.store(this.headerView,qu,0)}static fromTransfer(e,n){const r=Object.create(kS.prototype);return r.buffer=e,r.headerView=new Uint32Array(e,0,1),r.dataView=new Uint32Array(e,Yu),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,qu,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,qu)}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}}},xE=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}},Gu=Symbol.for("__woven_ecs_build_query__");function gl(t){return new Uint8Array(t)}function Zi(t,e){const n=Math.floor(e/8),r=e%8;n<t.length&&(t[n]|=1<<r)}var Yp=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=gl(n),this.withoutMask=gl(n),this.anyMask=gl(n),this.trackingMask=gl(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)Zi(this.withMask,this._getComponentId(e));return this}without(...t){for(const e of t)Zi(this.withoutMask,this._getComponentId(e));return this}any(...t){for(const e of t)Zi(this.anyMask,this._getComponentId(e));return this}tracking(...t){for(const e of t){const n=this._getComponentId(e);Zi(this.withMask,n),Zi(this.trackingMask,n)}return this}[Gu](){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 xE(this.trackingMask,this.withMask,this.withoutMask,this.anyMask,t,e,n,r)}},qp=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer,dr=0,co=1,Qs=4294967295,Gp=class{constructor(t){x(this,"denseBuffer");x(this,"sparseBuffer");x(this,"dense");x(this,"sparse");x(this,"maxEntities");this.maxEntities=t,this.denseBuffer=new qp((co+t)*4),this.dense=new Uint32Array(this.denseBuffer),this.dense[dr]=0,this.sparseBuffer=new qp(t*4),this.sparse=new Uint32Array(this.sparseBuffer),this.sparse.fill(Qs)}get count(){return this.dense[dr]}add(t){const e=this.sparse;if(e[t]!==Qs)return;const n=this.dense,r=n[dr];if(r>=this.maxEntities)throw new Error("QueryCache is full");n[co+r]=t,e[t]=r,n[dr]=r+1}remove(t){const e=this.sparse,n=e[t];if(n===Qs)return;const r=this.dense,s=r[dr]-1;if(n!==s){const i=r[co+s];r[co+n]=i,e[i]=n}e[t]=Qs,r[dr]=s}has(t){return this.sparse[t]!==Qs}clear(){const t=this.dense[dr];for(let e=0;e<t;e++){const n=this.dense[co+e];this.sparse[n]=Qs}this.dense[dr]=0}toArray(){const t=this.dense[dr],e=new Array(t);for(let n=0;n<t;n++)e[n]=this.dense[co+n];return e}getDenseView(){const t=this.dense[dr];return this.dense.subarray(co,co+t)}},TE=class{constructor(t,e){x(this,"cache");x(this,"lastIndex",0);x(this,"masks");this.masks=e,this.cache=new Gp(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)}}}},ME=(Ws=class{constructor(e){x(this,"builder");x(this,"instances",{});x(this,"id");this.builder=e,this.id=`current_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=new Yp(e.componentCount,e),i=this.builder(o)[Gu]();return r=new TE(e,i),this.instances[n]=r,r}current(e){return this._getInstance(e).current(e)}},x(Ws,"queryCounter",0),Ws);function AE(t){return new ME(t)}var Jp=new Map;function IE(t){const e=t._defId;let n=Jp.get(e);return n||(n=AE(r=>r.with(t)),Jp.set(e,n)),n}function Bt(t){const e=t.pool.get();return t.entityBuffer.create(e),t.eventBuffer.pushAdded(e),e}function fr(t,e,n,r,o=!0){const s=n._getInstance(t),i=IE(n),a=s.buffer[r],l=[];for(const c of i.current(t))Zu(a[c],t.entityBuffer,o)===e&&l.push(c);return l}function it(t,e){t.entityBuffer.has(e)&&(t.eventBuffer.pushRemoved(e),t.entityBuffer.markDead(e))}function Q(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 Ge(t){return t.resources}function NE(t,e){return t.entityBuffer.has(e)}var BE=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 T=0;T<m;T++){const B=(h+T)%r*2,Z=f+T>=l,M=Atomics.load(s,B),F=Atomics.load(s,B+1),q=F&255,ue=e.has(M),se=v[M];if(q===Le.REMOVED){if(!c&&ue&&e.remove(M),Z)if(se===b){const j=g.indexOf(M);j!==-1&&(g[j]=g[g.length-1],g.length--),v[M]=S}else if(se===k&&ue){const j=w.indexOf(M);j!==-1&&(w[j]=w[w.length-1],w.length--),v[M]=S,y.push(M)}else!se&&ue&&(v[M]=S,y.push(M))}else if(q===Le.ADDED){const j=o.matches(M,n);!c&&!ue&&j&&e.add(M),Z&&!se&&!ue&&j&&(v[M]=b,g.push(M))}else if(q===Le.COMPONENT_ADDED||q===Le.COMPONENT_REMOVED){const ee=o.has(M)&&o.matches(M,n);c||(ee&&!ue?e.add(M):!ee&&ue&&e.remove(M)),Z&&!se&&(!ue&&ee?(v[M]=b,g.push(M)):ue&&!ee&&(v[M]=S,y.push(M)))}else if(q===Le.CHANGED&&E&&Z&&!se&&ue){const j=F>>16&65535,ee=j>>3,fe=j&7;ee<_.length&&_[ee]&1<<fe&&(v[M]=k,w.push(M))}}}},Ju=[],PE=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 Gp(t.maxEntities)),this.reader=new BE(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 Ju;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 Ju;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:Ju}},OE=(Hs=class{constructor(e){x(this,"builder");x(this,"instances",{});x(this,"id");this.builder=e,this.id=`query_${Hs.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 PE(e,o),this.instances[n]=r,r}_getMasks(e){const n=new Yp(e.componentCount,e);return this.builder(n)[Gu]()}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(Hs,"queryCounter",0),Hs);function ie(t){return new OE(t)}var Xp=(Zs=class{constructor(){x(this,"id");this.id=Zs.systemCounter++}},x(Zs,"systemCounter",0),Zs),DE=class extends Xp{constructor(e){super();x(this,"type","main");x(this,"execute");this.execute=e}},RE=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer,zE=(Wt=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 RE(o),this.view=new Uint8Array(this.buffer)}static fromTransfer(e,n){const r=Object.create(Wt.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)&Wt.GENERATION_MASK)>>Wt.GENERATION_SHIFT)+1&127;for(let l=0;l<o;l++)Atomics.store(r,n+l,0);Atomics.store(r,n,Wt.ALIVE_FLAG|a<<Wt.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)&Wt.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)&Wt.ALIVE_FLAG)!==0}getGeneration(e){const n=e*this.bytesPerEntity;return(Atomics.load(this.view,n)&Wt.GENERATION_MASK)>>Wt.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(Wt,"ALIVE_FLAG",1),x(Wt,"GENERATION_MASK",254),x(Wt,"GENERATION_SHIFT",1),Wt),$E=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer;function LE(t){return t===0?-1:31-Math.clz32(t&-t)}var VE=(Ue=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 $E((n+1)*4),o=new Int32Array(r);for(let i=Ue.DATA_OFFSET;i<n+Ue.DATA_OFFSET;i++)o[i]=-1;const s=e%32;if(s!==0){const i=n-1+Ue.DATA_OFFSET,a=(1<<s)-1;o[i]=a}return o[Ue.HINT_INDEX]=0,new Ue(r,n,e)}static fromTransfer(e,n,r){return new Ue(e,n,r)}getBuffer(){return this.buffer}getBucketCount(){return this.bucketCount}getSize(){return this.size}free(e){const n=(e>>5)+Ue.DATA_OFFSET,r=1<<(e&31);Atomics.or(this.view,n,r);const o=Atomics.load(this.view,Ue.HINT_INDEX),s=n-Ue.DATA_OFFSET;(o===-1||s<o)&&Atomics.store(this.view,Ue.HINT_INDEX,s)}get(){for(let e=0;e<this.bucketCount*2;e++){let n=Atomics.load(this.view,Ue.HINT_INDEX);n===-1&&(n=0);for(let r=0;r<this.bucketCount;r++){const o=(n+r)%this.bucketCount+Ue.DATA_OFFSET,s=Atomics.load(this.view,o);if(s===0)continue;const i=LE(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-Ue.DATA_OFFSET),(o-Ue.DATA_OFFSET<<5)+i}}throw Atomics.store(this.view,Ue.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+Ue.DATA_OFFSET;if(Atomics.load(this.view,r)!==0){Atomics.store(this.view,Ue.HINT_INDEX,r-Ue.DATA_OFFSET);return}}Atomics.store(this.view,Ue.HINT_INDEX,-1)}},x(Ue,"HINT_INDEX",0),x(Ue,"DATA_OFFSET",1),Ue),Qp=3,FE=.75,jE=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>Qp&&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>FE;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<Qp){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()}},UE=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()}},em={high:2,medium:1,low:0},WE=(Ks=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 UE(r);const a=new _E(s),l=new zE(o,i),c={};for(const u of e){const f=bE.fromDef(u);f.initialize(this.componentIndex++,o,a,l),c[u._defId]=f,this.componentIdToDef.set(this.componentIndex-1,u)}this.worldId=Ks.worldCounter++,this.history=new jE(s),this.context={entityBuffer:l,eventBuffer:a,components:c,maxEntities:o,maxEvents:s,componentCount:i,pool:VE.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 Xp?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)=>em[h.priority]-em[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(Ks,"worldCounter",0),Ks),an={ECS:1,History:2,Persistence:3,Websocket:4},HE=1;function tm(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 Xu(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=ZE(c,l??null,i.migrations);u.changed&&(n||(n={...t}),n[r]={...u.data,_exists:!0,_version:u.version})}return n??t}function ZE(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 Qu(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(!Qu(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=>Qu(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 nm(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 KE=1e3;async function rm(t,e,n){const r=await Ap(t,1,{upgrade(o){o.objectStoreNames.contains(e)||o.createObjectStore(e)}});return new YE(r,e,n)}var YE=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)??KE}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)}},qE=1e3/30,GE=1e3,JE=(Nr=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 rm(`${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:HE,...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?qE:GE}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=Xu(n,this.componentsByName),o=Xu(this.offlineBuffer,this.componentsByName),s=nm(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=Nr.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=Nr.MIN_RECONNECT_DELAY}catch{this.reconnectDelay=Math.min(this.reconnectDelay*2,Nr.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=nm(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(Nr,"MIN_RECONNECT_DELAY",500),x(Nr,"MAX_RECONNECT_DELAY",1e4),Nr),Gt=class extends Zp{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&&tm(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 Gt(t,e)}var kt=class extends SE{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&&tm(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 Ki(t,e){return new kt(t,e)}var me=Kp({id:C.string().max(36)}),ed="SINGLETON";function XE(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];Qu(s,i)||(n[o]=i,r=!0)}return r?n:null}var QE=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=ed:(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=XE(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!==ed&&!this.stableIdToEntity.has(a)){const l=Bt(e);Q(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===ed){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):Q(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(){}},eC=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}},tC=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 rm(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=Xu(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()}},om=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 QE({components:t,singletons:e}),this.adapters.push(this.ecsAdapter),this.options.persistence&&(this.persistenceAdapter=new tC({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 eC({components:t,singletons:e,commitCheckpointAfterFrames:n.commitCheckpointAfterFrames,maxHistoryStackSize:n.maxHistoryStackSize}),this.adapters.push(this.historyAdapter)}this.options.websocket&&(this.websocketAdapter=new JE({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,Or=2,Dr=3,vn=4,kn=5,hr=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[Or],e[Dr]],t.c=e=>[e[vn],e[kn]],t.thickness=e=>e[hr],t.isCollinear=e=>{const n=(e[yn]-e[vn])*(e[Dr]-e[kn])-(e[Or]-e[vn])*(e[wn]-e[kn]);return Math.abs(n)<1e-8},t.computeCenter=e=>{const n=e[yn],r=e[wn],o=e[Or],s=e[Dr],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[Or],i=e[Dr],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=nC(e,n);let h=Math.atan2(o-n[1],r-n[0]);h=ts(h);let p=h+f*(u?-1:1);return p=ts(p),{center:n,radius:c,clockwise:u,arcAngle:f,startAngle:h,endAngle:p}},t.inArcAngle=(e,n,r,o)=>(e=ts(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[hr]/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[hr]/2,u=(0,t.a)(e),f=(0,t.b)(e),h=(0,t.c)(e);if(td(n,u)||td(n,f)||td(n,h))return!0;const p=s-c,m=s+c;if(!rC(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=im(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[hr]/2,h=a-f,p=a+f;for(const m of[p,h]){const g=sm(i,m,n),y=sm(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 im(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=ts(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[hr]/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[Or]=o,e[Dr]=s,e[vn]=i,e[kn]=a,e[hr]=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[Or]=n,e[Dr]=r},t.setC=(e,n,r)=>{e[vn]=n,e[kn]=r},t.setThickness=(e,n)=>{e[hr]=n},t.setFromPoints=(e,n,r,o,s)=>{e[yn]=n[0],e[wn]=n[1],e[Or]=r[0],e[Dr]=r[1],e[vn]=o[0],e[kn]=o[1],e[hr]=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[hr];e[yn]=o[0],e[wn]=o[1],e[Or]=s[0],e[Dr]=s[1],e[vn]=i[0],e[kn]=i[1],e[hr]=a}})(Re||(Re={}));function ts(t){for(;t<0;)t+=2*Math.PI;for(;t>=2*Math.PI;)t-=2*Math.PI;return t}function nC(t,e){const n=t[yn],r=t[wn],o=t[Or],s=t[Dr],i=t[vn],a=t[kn],l=ts(Math.atan2(r-e[1],n-e[0])),c=ts(Math.atan2(s-e[1],o-e[0])),u=ts(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 td(t,e){return e[0]>=t[0]&&e[0]<=t[2]&&e[1]>=t[1]&&e[1]<=t[3]}function sm(t,e,n){const r=n[0]-t[0],o=n[1]-t[1];return r*r+o*o<=e*e}function rC(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 im(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 at=0,lt=1,Pt=2,Ot=3,pr=4,pt;(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[at],e[lt]],t.pointB=e=>[e[Pt],e[Ot]],t.radius=e=>e[pr],t.center=e=>[(e[at]+e[Pt])/2,(e[lt]+e[Ot])/2],t.length=e=>{const n=e[Pt]-e[at],r=e[Ot]-e[lt];return Math.hypot(n,r)},t.bounds=e=>{const n=e[pr];return[Math.min(e[at],e[Pt])-n,Math.min(e[lt],e[Ot])-n,Math.max(e[at],e[Pt])+n,Math.max(e[lt],e[Ot])+n]},t.getExtrema=e=>{const n=e[at],r=e[lt],o=e[Pt],s=e[Ot],i=e[pr];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[at],e[lt],e[Pt],e[Ot],n[0],n[1]);return[e[at]+r*(e[Pt]-e[at]),e[lt]+r*(e[Ot]-e[lt])]},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[pr],t.intersectsAabb=(e,n)=>{const r=e[pr],o=(0,t.bounds)(e);if(!ne.intersects(o,n))return!1;const s=e[Pt]-e[at],i=e[Ot]-e[lt],a=s*s+i*i;if(a===0)return ne.distanceToPoint(n,[e[at],e[lt]])<=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[at]+u*s,h=e[lt]+u*i;if(ne.distanceToPoint(n,[f,h])<=r)return!0}return!1},t.intersectsCapsule=(e,n)=>(0,t.segmentToSegmentDistance)(e[at],e[lt],e[Pt],e[Ot],n[at],n[lt],n[Pt],n[Ot])<=e[pr]+n[pr],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,T=n+k*u,I=s+E*f,B=i+E*h;return Math.hypot(I-_,B-T)},t.set=(e,n,r,o,s,i)=>{e[at]=n,e[lt]=r,e[Pt]=o,e[Ot]=s,e[pr]=i},t.copy=(e,n)=>{e[at]=n[at],e[lt]=n[lt],e[Pt]=n[Pt],e[Ot]=n[Ot],e[pr]=n[pr]},t.translate=(e,n)=>{e[at]+=n[0],e[lt]+=n[1],e[Pt]+=n[0],e[Ot]+=n[1]},t.trim=(e,n,r)=>{const o=e[at],s=e[lt],i=e[Pt],a=e[Ot],l=i-o,c=a-s;e[at]=o+n*l,e[lt]=s+n*c,e[Pt]=o+r*l,e[Ot]=s+r*c}})(pt||(pt={}));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 G=0,J=1,mt;(t=>{t.getCenter=(e,n,r)=>{r[G]=e[G]+n[G]/2,r[J]=e[J]+n[J]/2},t.getCorners=(e,n,r,o)=>{const s=n[G]/2,i=n[J]/2,a=e[G]+s,l=e[J]+i,c=Math.cos(r),u=Math.sin(r);o[0][G]=a+-s*c- -i*u,o[0][J]=l+-s*u+-i*c,o[1][G]=a+s*c- -i*u,o[1][J]=l+s*u+-i*c,o[2][G]=a+s*c-i*u,o[2][J]=l+s*u+i*c,o[3][G]=a+-s*c-i*u,o[3][J]=l+-s*u+i*c},t.getAabb=(e,n,r,o)=>{const s=n[G]/2,i=n[J]/2,a=e[G]+s,l=e[J]+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[G]-.5)*n[G],(o[J]-.5)*n[J]];$.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[G],l=n[J],c=e[G]+a/2,u=e[J]+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[G]/2,i=n[J]/2,a=e[G]+s,l=e[J]+i,c=o[G]-a,u=o[J]-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[G]/2,c=n[J]/2,u=e[G]+l,f=e[J]+c,h=Math.cos(r),p=Math.sin(r);i[0][G]=o[0],i[0][J]=o[1],i[1][G]=o[2],i[1][J]=o[1],i[2][G]=o[2],i[2][J]=o[3],i[3][G]=o[0],i[3][J]=o[3],s[0][G]=u+-l*h- -c*p,s[0][J]=f+-l*p+-c*h,s[1][G]=u+l*h- -c*p,s[1][J]=f+l*p+-c*h,s[2][G]=u+l*h-c*p,s[2][J]=f+l*p+c*h,s[3][G]=u+-l*h-c*p,s[3][J]=f+-l*p+c*h;const m=s[1][G]-s[0][G],g=s[1][J]-s[0][J],y=Math.sqrt(m*m+g*g);y>0&&(a[0][G]=-g/y,a[0][J]=m/y);const w=s[2][G]-s[1][G],v=s[2][J]-s[1][J],b=Math.sqrt(w*w+v*v);return b>0&&(a[1][G]=-v/b,a[1][J]=w/b),!(yl(i,s,1,0)||yl(i,s,0,1)||yl(i,s,a[0][G],a[0][J])||yl(i,s,a[1][G],a[1][J]))},t.setCenter=(e,n,r)=>{e[G]=r[G]-n[G]/2,e[J]=r[J]-n[J]/2},t.translate=(e,n)=>{e[G]+=n[G],e[J]+=n[J]},t.scaleBy=(e,n,r)=>{const o=e[G]+n[G]/2,s=e[J]+n[J]/2;n[G]*=r,n[J]*=r,e[G]=o-n[G]/2,e[J]=s-n[J]/2},t.scaleAround=(e,n,r,o)=>{const s=e[G]+n[G]/2,i=e[J]+n[J]/2,a=r[G]+(s-r[G])*o,l=r[J]+(i-r[J])*o;n[G]*=o,n[J]*=o,e[G]=a-n[G]/2,e[J]=l-n[J]/2},t.rotateAround=(e,n,r,o,s)=>{const i=e[G]+n[G]/2,a=e[J]+n[J]/2,l=i-o[G],c=a-o[J],u=Math.cos(s),f=Math.sin(s),h=o[G]+l*u-c*f,p=o[J]+l*f+c*u;return e[G]=h-n[G]/2,e[J]=p-n[J]/2,r+s},t.boundPoints=(e,n,r,o)=>{if(o.length===0)return;if(r===0){let b=o[0][G],S=o[0][J],k=b,E=S;for(let _=1;_<o.length;_++){const T=o[_][G],I=o[_][J];T<b&&(b=T),I<S&&(S=I),T>k&&(k=T),I>E&&(E=I)}e[G]=b,e[J]=S,n[G]=k-b,n[J]=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[G]*s-b[J]*i,k=b[G]*i+b[J]*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[G]=w-p/2,e[J]=v-m/2,n[G]=p,n[J]=m}})(mt||(mt={}));function yl(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 Rr=0,zr=1,uo=2,fo=3,bt;(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[Rr],n[zr]],t.direction=n=>[n[uo],n[fo]],t.set=(n,r,o,s,i)=>{n[Rr]=r,n[zr]=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[Rr]=r[0],n[zr]=r[1]},t.setDirection=(n,r)=>{n[uo]=r[0],n[fo]=r[1]},t.pointAt=(n,r)=>[n[Rr]+n[uo]*r,n[zr]+n[fo]*r],t.intersectSegment=(n,r,o)=>{const s=n[Rr],i=n[zr],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 oC(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[Rr],i=n[zr],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)=>{mt.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}})(bt||(bt={}));function oC(t,e,n){const r=t[Rr],o=t[zr],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]?am(t,e,n,0):s===0&&e[0]===n[0]&&r===e[0]?am(t,e,n,1):null}function am(t,e,n,r){const o=r===0?t[Rr]:t[zr],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[Rr],t[zr]],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 nd=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%nd;return n<0?n+nd:n},t.normalizeAngleSigned=e=>{const n=(0,t.normalizeAngle)(e);return n>Math.PI?n-nd: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 ei extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class lm extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const cm={};function ho(t){return cm}function um(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 rd(t,e){return typeof e=="bigint"?e.toString():e}function od(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function sd(t){return t==null}function id(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function sC(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 dm=Symbol("evaluating");function Oe(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==dm)return r===void 0&&(r=dm,r=n()),r},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function ns(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 fm(t){return JSON.stringify(t)}function iC(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const hm="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function wl(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const aC=od(()=>{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 ti(t){if(wl(t)===!1)return!1;const e=t.constructor;if(e===void 0||typeof e!="function")return!0;const n=e.prototype;return!(wl(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function pm(t){return ti(t)?{...t}:Array.isArray(t)?[...t]:t}const lC=new Set(["string","number","symbol"]);function vl(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 cC(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const uC={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 dC(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 ns(this,"shape",i),i},checks:[]});return mo(t,s)}function fC(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 ns(this,"shape",i),i},checks:[]});return mo(t,s)}function hC(t,e){if(!ti(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 ns(this,"shape",s),s}});return mo(t,o)}function pC(t,e){if(!ti(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 ns(this,"shape",r),r}});return mo(t,n)}function mC(t,e){const n=po(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return ns(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:[]});return mo(t,n)}function gC(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 ns(this,"shape",l),l},checks:[]});return mo(e,i)}function yC(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 ns(this,"shape",s),s}});return mo(e,r)}function ni(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 rs(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function kl(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=kl((i=(s=(o=t.inst)==null?void 0:o._zod.def)==null?void 0:s.error)==null?void 0:i.call(s,t))??kl((a=e==null?void 0:e.error)==null?void 0:a.call(e,t))??kl((l=n.customError)==null?void 0:l.call(n,t))??kl((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 ad(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Yi(...t){const[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}const mm=(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,rd,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},gm=N("$ZodError",mm),bl=N("$ZodError",mm,{Parent:Error});function wC(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 vC(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 Sl=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 ei;if(i.issues.length){const a=new((o==null?void 0:o.Err)??t)(i.issues.map(l=>go(l,s,ho())));throw hm(a,o==null?void 0:o.callee),a}return i.value},ym=Sl(bl),El=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 hm(a,o==null?void 0:o.callee),a}return i.value},wm=El(bl),Cl=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 ei;return s.issues.length?{success:!1,error:new(t??gm)(s.issues.map(i=>go(i,o,ho())))}:{success:!0,data:s.value}},kC=Cl(bl),_l=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}},bC=_l(bl),SC=t=>(e,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Sl(t)(e,n,o)},EC=t=>(e,n,r)=>Sl(t)(e,n,r),CC=t=>async(e,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return El(t)(e,n,o)},_C=t=>async(e,n,r)=>El(t)(e,n,r),xC=t=>(e,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Cl(t)(e,n,o)},TC=t=>(e,n,r)=>Cl(t)(e,n,r),MC=t=>async(e,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return _l(t)(e,n,o)},AC=t=>async(e,n,r)=>_l(t)(e,n,r),IC=/^[cC][^\s-]{8,}$/,NC=/^[0-9a-z]+$/,BC=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,PC=/^[0-9a-vA-V]{20}$/,OC=/^[A-Za-z0-9]{27}$/,DC=/^[a-zA-Z0-9_-]{21}$/,RC=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,zC=/^([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})$/,vm=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)$/,$C=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,LC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function VC(){return new RegExp(LC,"u")}const 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])$/,jC=/^(([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}|:))$/,UC=/^((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])$/,WC=/^(([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])$/,HC=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,km=/^[A-Za-z0-9_-]*$/,ZC=/^\+[1-9]\d{6,14}$/,bm="(?:(?:\\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])))",KC=new RegExp(`^${bm}$`);function Sm(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 YC(t){return new RegExp(`^${Sm(t)}$`)}function qC(t){const e=Sm({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(`^${bm}T(?:${r})$`)}const GC=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}$`)},JC=/^-?\d+$/,Em=/^-?\d+(?:\.\d+)?$/,XC=/^(?:true|false)$/i,QC=/^[^A-Z]*$/,e_=/^[^a-z]*$/,ln=N("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Cm={number:"number",bigint:"bigint",object:"date"},_m=N("$ZodCheckLessThan",(t,e)=>{ln.init(t,e);const n=Cm[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})}}),xm=N("$ZodCheckGreaterThan",(t,e)=>{ln.init(t,e);const n=Cm[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})}}),t_=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):sC(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})}}),n_=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]=uC[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=JC)}),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})}}),r_=N("$ZodCheckMaxLength",(t,e)=>{var n;ln.init(t,e),(n=t._zod.def).when??(n.when=r=>{const o=r.value;return!sd(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=ad(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),o_=N("$ZodCheckMinLength",(t,e)=>{var n;ln.init(t,e),(n=t._zod.def).when??(n.when=r=>{const o=r.value;return!sd(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=ad(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),s_=N("$ZodCheckLengthEquals",(t,e)=>{var n;ln.init(t,e),(n=t._zod.def).when??(n.when=r=>{const o=r.value;return!sd(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=ad(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})}}),xl=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=()=>{})}),i_=N("$ZodCheckRegex",(t,e)=>{xl.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})}}),a_=N("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=QC),xl.init(t,e)}),l_=N("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=e_),xl.init(t,e)}),c_=N("$ZodCheckIncludes",(t,e)=>{ln.init(t,e);const n=vl(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})}}),u_=N("$ZodCheckStartsWith",(t,e)=>{ln.init(t,e);const n=new RegExp(`^${vl(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})}}),d_=N("$ZodCheckEndsWith",(t,e)=>{ln.init(t,e);const n=new RegExp(`.*${vl(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})}}),f_=N("$ZodCheckOverwrite",(t,e)=>{ln.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class h_{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
- `).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 p_={major:4,minor:3,patch:6},We=N("$ZodType",(t,e)=>{var o;var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=p_;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=ni(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 ei;if(f||m instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await m,a.issues.length!==p&&(u||(u=ni(a,p)))});else{if(a.issues.length===p)continue;u||(u=ni(a,p))}}return f?f.then(()=>a):a},i=(a,l,c)=>{if(ni(a))return a.aborted=!0,a;const u=s(l,r,c);if(u instanceof Promise){if(c.async===!1)throw new ei;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 ei;return c.then(u=>s(u,r,l))}return s(c,r,l)}}Oe(t,"~standard",()=>({validate:s=>{var i;try{const a=kC(t,s);return a.success?{value:a.data}:{issues:(i=a.error)==null?void 0:i.issues}}catch{return bC(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}))}),ld=N("$ZodString",(t,e)=>{var n;We.init(t,e),t._zod.pattern=[...((n=t==null?void 0:t._zod.bag)==null?void 0:n.patterns)??[]].pop()??GC(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}}),Je=N("$ZodStringFormat",(t,e)=>{xl.init(t,e),ld.init(t,e)}),m_=N("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=zC),Je.init(t,e)}),g_=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=vm(r))}else e.pattern??(e.pattern=vm());Je.init(t,e)}),y_=N("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=$C),Je.init(t,e)}),w_=N("$ZodURL",(t,e)=>{Je.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})}}}),v_=N("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=VC()),Je.init(t,e)}),k_=N("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=DC),Je.init(t,e)}),b_=N("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=IC),Je.init(t,e)}),S_=N("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=NC),Je.init(t,e)}),E_=N("$ZodULID",(t,e)=>{e.pattern??(e.pattern=BC),Je.init(t,e)}),C_=N("$ZodXID",(t,e)=>{e.pattern??(e.pattern=PC),Je.init(t,e)}),__=N("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=OC),Je.init(t,e)}),x_=N("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=qC(e)),Je.init(t,e)}),T_=N("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=KC),Je.init(t,e)}),M_=N("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=YC(e)),Je.init(t,e)}),A_=N("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=RC),Je.init(t,e)}),I_=N("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=FC),Je.init(t,e),t._zod.bag.format="ipv4"}),N_=N("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=jC),Je.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})}}}),B_=N("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=UC),Je.init(t,e)}),P_=N("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=WC),Je.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 Tm(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const O_=N("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=HC),Je.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{Tm(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function D_(t){if(!km.test(t))return!1;const e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Tm(n)}const R_=N("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=km),Je.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{D_(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),z_=N("$ZodE164",(t,e)=>{e.pattern??(e.pattern=ZC),Je.init(t,e)});function $_(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 L_=N("$ZodJWT",(t,e)=>{Je.init(t,e),t._zod.check=n=>{$_(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),Mm=N("$ZodNumber",(t,e)=>{We.init(t,e),t._zod.pattern=t._zod.bag.pattern??Em,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}}),V_=N("$ZodNumberFormat",(t,e)=>{n_.init(t,e),Mm.init(t,e)}),F_=N("$ZodBoolean",(t,e)=>{We.init(t,e),t._zod.pattern=XC,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}}),j_=N("$ZodUnknown",(t,e)=>{We.init(t,e),t._zod.parse=n=>n}),U_=N("$ZodNever",(t,e)=>{We.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function Am(t,e,n){t.issues.length&&e.issues.push(...rs(n,t.issues)),e.value[n]=t.value}const W_=N("$ZodArray",(t,e)=>{We.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=>Am(c,n,i))):Am(l,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function Tl(t,e,n,r,o){if(t.issues.length){if(o&&!(n in r))return;e.issues.push(...rs(n,t.issues))}t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function Im(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=cC(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Nm(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=>Tl(p,n,f,e,u))):Tl(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 H_=N("$ZodObject",(t,e)=>{We.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=od(()=>Im(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=wl,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=>Tl(y,a,h,c,m))):Tl(g,a,h,c,m)}return s?Nm(u,c,a,l,r.value,t):u.length?Promise.all(u).then(()=>a):a}}),Z_=N("$ZodObjectJIT",(t,e)=>{H_.init(t,e);const n=t._zod.parse,r=od(()=>Im(e)),o=h=>{var b;const p=new h_(["shape","payload","ctx"]),m=r.value,g=S=>{const k=fm(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=fm(S),_=h[S],T=((b=_==null?void 0:_._zod)==null?void 0:b.optout)==="optional";p.write(`const ${k} = ${g(S)};`),T?p.write(`
4
- if (${k}.issues.length) {
5
- if (${E} in input) {
6
- payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
7
- ...iss,
8
- path: iss.path ? [${E}, ...iss.path] : [${E}]
9
- })));
10
- }
11
- }
12
-
13
- if (${k}.value === undefined) {
14
- if (${E} in input) {
15
- newResult[${E}] = undefined;
16
- }
17
- } else {
18
- newResult[${E}] = ${k}.value;
19
- }
20
-
21
- `):p.write(`
22
- if (${k}.issues.length) {
23
- payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
24
- ...iss,
25
- path: iss.path ? [${E}, ...iss.path] : [${E}]
26
- })));
27
- }
28
-
29
- if (${k}.value === undefined) {
30
- if (${E} in input) {
31
- newResult[${E}] = undefined;
32
- }
33
- } else {
34
- newResult[${E}] = ${k}.value;
35
- }
36
-
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=wl,a=!cm.jitless,c=a&&aC.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?Nm([],m,h,p,f,t):h):n(h,p):(h.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),h)}});function Bm(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=>!ni(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 K_=N("$ZodUnion",(t,e)=>{We.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=>id(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=>Bm(l,o,t,s)):Bm(a,o,t,s)}}),Y_=N("$ZodIntersection",(t,e)=>{We.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])=>Pm(n,l,c)):Pm(n,s,i)}});function cd(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(ti(t)&&ti(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=cd(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=cd(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 Pm(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}),ni(t))return t;const i=cd(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 Om=N("$ZodTuple",(t,e)=>{We.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=>Ml(h,r,c))):Ml(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=>Ml(p,r,c))):Ml(h,r,c)}}return i.length?Promise.all(i).then(()=>r):r}});function Ml(t,e,n){t.issues.length&&e.issues.push(...rs(n,t.issues)),e.value[n]=t.value}const q_=N("$ZodRecord",(t,e)=>{We.init(t,e),t._zod.parse=(n,r)=>{const o=n.value;if(!ti(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(...rs(c,f.issues)),n.value[c]=f.value})):(u.issues.length&&n.issues.push(...rs(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"&&Em.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(...rs(a,f.issues)),n.value[l.value]=f.value})):(u.issues.length&&n.issues.push(...rs(a,u.issues)),n.value[l.value]=u.value)}}return s.length?Promise.all(s).then(()=>n):n}}),G_=N("$ZodEnum",(t,e)=>{We.init(t,e);const n=um(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(o=>lC.has(typeof o)).map(o=>typeof o=="string"?vl(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}}),J_=N("$ZodTransform",(t,e)=>{We.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new lm(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 ei;return n.value=o,n}});function Dm(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}const Rm=N("$ZodOptional",(t,e)=>{We.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(`^(${id(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=>Dm(s,n.value)):Dm(o,n.value)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),X_=N("$ZodExactOptional",(t,e)=>{Rm.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)}),Q_=N("$ZodNullable",(t,e)=>{We.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(`^(${id(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)}),ex=N("$ZodDefault",(t,e)=>{We.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=>zm(s,e)):zm(o,e)}});function zm(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const tx=N("$ZodPrefault",(t,e)=>{We.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))}),nx=N("$ZodNonOptional",(t,e)=>{We.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=>$m(s,t)):$m(o,t)}});function $m(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 rx=N("$ZodCatch",(t,e)=>{We.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)}}),ox=N("$ZodPipe",(t,e)=>{We.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=>Al(i,e.in,r)):Al(s,e.in,r)}const o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Al(s,e.out,r)):Al(o,e.out,r)}});function Al(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},n)}const sx=N("$ZodReadonly",(t,e)=>{We.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(Lm):Lm(o)}});function Lm(t){return t.value=Object.freeze(t.value),t}const ix=N("$ZodFunction",(t,e)=>(We.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?ym(t._def.input,r):r,s=Reflect.apply(n,this,o);return t._def.output?ym(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 wm(t._def.input,r):r,s=await Reflect.apply(n,this,o);return t._def.output?await wm(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 Om({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)),ax=N("$ZodCustom",(t,e)=>{ln.init(t,e),We.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=>Vm(s,n,r,t));Vm(o,n,r,t)}});function Vm(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(Yi(o))}}var Fm;class lx{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 cx(){return new lx}(Fm=globalThis).__zod_globalRegistry??(Fm.__zod_globalRegistry=cx());const qi=globalThis.__zod_globalRegistry;function ux(t,e){return new t({type:"string",...re(e)})}function dx(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...re(e)})}function jm(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...re(e)})}function fx(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...re(e)})}function hx(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...re(e)})}function px(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...re(e)})}function mx(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...re(e)})}function gx(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...re(e)})}function yx(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...re(e)})}function wx(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...re(e)})}function vx(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...re(e)})}function kx(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...re(e)})}function bx(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...re(e)})}function Sx(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...re(e)})}function Ex(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...re(e)})}function Cx(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...re(e)})}function _x(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...re(e)})}function xx(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...re(e)})}function Tx(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...re(e)})}function Mx(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...re(e)})}function Ax(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...re(e)})}function Ix(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...re(e)})}function Nx(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...re(e)})}function Bx(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...re(e)})}function Px(t,e){return new t({type:"string",format:"date",check:"string_format",...re(e)})}function Ox(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...re(e)})}function Dx(t,e){return new t({type:"string",format:"duration",check:"string_format",...re(e)})}function Rx(t,e){return new t({type:"number",checks:[],...re(e)})}function zx(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...re(e)})}function $x(t,e){return new t({type:"boolean",...re(e)})}function Lx(t){return new t({type:"unknown"})}function Vx(t,e){return new t({type:"never",...re(e)})}function Um(t,e){return new _m({check:"less_than",...re(e),value:t,inclusive:!1})}function ud(t,e){return new _m({check:"less_than",...re(e),value:t,inclusive:!0})}function Wm(t,e){return new xm({check:"greater_than",...re(e),value:t,inclusive:!1})}function dd(t,e){return new xm({check:"greater_than",...re(e),value:t,inclusive:!0})}function Hm(t,e){return new t_({check:"multiple_of",...re(e),value:t})}function Zm(t,e){return new r_({check:"max_length",...re(e),maximum:t})}function Il(t,e){return new o_({check:"min_length",...re(e),minimum:t})}function Km(t,e){return new s_({check:"length_equals",...re(e),length:t})}function Fx(t,e){return new i_({check:"string_format",format:"regex",...re(e),pattern:t})}function jx(t){return new a_({check:"string_format",format:"lowercase",...re(t)})}function Ux(t){return new l_({check:"string_format",format:"uppercase",...re(t)})}function Wx(t,e){return new c_({check:"string_format",format:"includes",...re(e),includes:t})}function Hx(t,e){return new u_({check:"string_format",format:"starts_with",...re(e),prefix:t})}function Zx(t,e){return new d_({check:"string_format",format:"ends_with",...re(e),suffix:t})}function ri(t){return new f_({check:"overwrite",tx:t})}function Kx(t){return ri(e=>e.normalize(t))}function Yx(){return ri(t=>t.trim())}function qx(){return ri(t=>t.toLowerCase())}function Gx(){return ri(t=>t.toUpperCase())}function Jx(){return ri(t=>iC(t))}function Xx(t,e,n){return new t({type:"array",element:e,...re(n)})}function Qx(t,e,n){const r=re(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function eT(t,e,n){return new t({type:"custom",check:"custom",fn:e,...re(n)})}function tT(t){const e=nT(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Yi(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(Yi(o))}},t(n.value,n)));return e}function nT(t,e){const n=new ln({check:"custom",...re(e)});return n._zod.check=t,n}function Ym(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)??qi,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 qm(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
-
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 Gm(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:Nl(e,"input",t.processors),output:Nl(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 rT=(t,e={})=>n=>{const r=Ym({...n,processors:e});return rt(t,r),qm(r,t),Gm(r,t)},Nl=(t,e,n={})=>r=>{const{libraryOptions:o,target:s}=r??{},i=Ym({...o??{},target:s,io:e,processors:n});return rt(t,i),qm(i,t),Gm(i,t)},oT={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},sT=(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=oT[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}))])}},iT=(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)},aT=(t,e,n,r)=>{n.type="boolean"},lT=(t,e,n,r)=>{n.not={}},cT=(t,e,n,r)=>{},uT=(t,e,n,r)=>{const o=t._zod.def,s=um(o.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},dT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},fT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},hT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},pT=(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"]})},mT=(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)},gT=(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},yT=(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},wT=(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)},vT=(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)}},kT=(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"}]},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},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,n.default=JSON.parse(JSON.stringify(o.defaultValue))},ET=(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)))},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;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i},_T=(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},xT=(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},Jm=(t,e,n,r)=>{const o=t._zod.def;rt(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType},TT=N("ZodISODateTime",(t,e)=>{x_.init(t,e),et.init(t,e)});function MT(t){return Bx(TT,t)}const AT=N("ZodISODate",(t,e)=>{T_.init(t,e),et.init(t,e)});function IT(t){return Px(AT,t)}const NT=N("ZodISOTime",(t,e)=>{M_.init(t,e),et.init(t,e)});function BT(t){return Ox(NT,t)}const PT=N("ZodISODuration",(t,e)=>{A_.init(t,e),et.init(t,e)});function OT(t){return Dx(PT,t)}const Tn=N("ZodError",(t,e)=>{gm.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>vC(t,n)},flatten:{value:n=>wC(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,rd,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,rd,2)}},isEmpty:{get(){return t.issues.length===0}}})},{Parent:Error}),DT=Sl(Tn),RT=El(Tn),zT=Cl(Tn),$T=_l(Tn),LT=SC(Tn),VT=EC(Tn),FT=CC(Tn),jT=_C(Tn),UT=xC(Tn),WT=TC(Tn),HT=MC(Tn),ZT=AC(Tn),Xe=N("ZodType",(t,e)=>(We.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:Nl(t,"input"),output:Nl(t,"output")}}),t.toJSONSchema=rT(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)=>DT(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>zT(t,n,r),t.parseAsync=async(n,r)=>RT(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>$T(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>LT(t,n,r),t.decode=(n,r)=>VT(t,n,r),t.encodeAsync=async(n,r)=>FT(t,n,r),t.decodeAsync=async(n,r)=>jT(t,n,r),t.safeEncode=(n,r)=>UT(t,n,r),t.safeDecode=(n,r)=>WT(t,n,r),t.safeEncodeAsync=async(n,r)=>HT(t,n,r),t.safeDecodeAsync=async(n,r)=>ZT(t,n,r),t.refine=(n,r)=>t.check(jM(n,r)),t.superRefine=n=>t.check(UM(n)),t.overwrite=n=>t.check(ri(n)),t.optional=()=>rg(t),t.exactOptional=()=>MM(t),t.nullable=()=>og(t),t.nullish=()=>rg(og(t)),t.nonoptional=n=>OM(t,n),t.array=()=>Mn(t),t.or=n=>vM([t,n]),t.and=n=>bM(t,n),t.transform=n=>ig(t,xM(n)),t.default=n=>NM(t,n),t.prefault=n=>PM(t,n),t.catch=n=>RM(t,n),t.pipe=n=>ig(t,n),t.readonly=()=>LM(t),t.describe=n=>{const r=t.clone();return qi.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){var n;return(n=qi.get(t))==null?void 0:n.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return qi.get(t);const r=t.clone();return qi.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t.apply=n=>n(t),t)),Xm=N("_ZodString",(t,e)=>{ld.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(r,o,s)=>sT(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(Fx(...r)),t.includes=(...r)=>t.check(Wx(...r)),t.startsWith=(...r)=>t.check(Hx(...r)),t.endsWith=(...r)=>t.check(Zx(...r)),t.min=(...r)=>t.check(Il(...r)),t.max=(...r)=>t.check(Zm(...r)),t.length=(...r)=>t.check(Km(...r)),t.nonempty=(...r)=>t.check(Il(1,...r)),t.lowercase=r=>t.check(jx(r)),t.uppercase=r=>t.check(Ux(r)),t.trim=()=>t.check(Yx()),t.normalize=(...r)=>t.check(Kx(...r)),t.toLowerCase=()=>t.check(qx()),t.toUpperCase=()=>t.check(Gx()),t.slugify=()=>t.check(Jx())}),KT=N("ZodString",(t,e)=>{ld.init(t,e),Xm.init(t,e),t.email=n=>t.check(dx(YT,n)),t.url=n=>t.check(gx(qT,n)),t.jwt=n=>t.check(Nx(uM,n)),t.emoji=n=>t.check(yx(GT,n)),t.guid=n=>t.check(jm(Qm,n)),t.uuid=n=>t.check(fx(Bl,n)),t.uuidv4=n=>t.check(hx(Bl,n)),t.uuidv6=n=>t.check(px(Bl,n)),t.uuidv7=n=>t.check(mx(Bl,n)),t.nanoid=n=>t.check(wx(JT,n)),t.guid=n=>t.check(jm(Qm,n)),t.cuid=n=>t.check(vx(XT,n)),t.cuid2=n=>t.check(kx(QT,n)),t.ulid=n=>t.check(bx(eM,n)),t.base64=n=>t.check(Mx(aM,n)),t.base64url=n=>t.check(Ax(lM,n)),t.xid=n=>t.check(Sx(tM,n)),t.ksuid=n=>t.check(Ex(nM,n)),t.ipv4=n=>t.check(Cx(rM,n)),t.ipv6=n=>t.check(_x(oM,n)),t.cidrv4=n=>t.check(xx(sM,n)),t.cidrv6=n=>t.check(Tx(iM,n)),t.e164=n=>t.check(Ix(cM,n)),t.datetime=n=>t.check(MT(n)),t.date=n=>t.check(IT(n)),t.time=n=>t.check(BT(n)),t.duration=n=>t.check(OT(n))});function St(t){return ux(KT,t)}const et=N("ZodStringFormat",(t,e)=>{Je.init(t,e),Xm.init(t,e)}),YT=N("ZodEmail",(t,e)=>{y_.init(t,e),et.init(t,e)}),Qm=N("ZodGUID",(t,e)=>{m_.init(t,e),et.init(t,e)}),Bl=N("ZodUUID",(t,e)=>{g_.init(t,e),et.init(t,e)}),qT=N("ZodURL",(t,e)=>{w_.init(t,e),et.init(t,e)}),GT=N("ZodEmoji",(t,e)=>{v_.init(t,e),et.init(t,e)}),JT=N("ZodNanoID",(t,e)=>{k_.init(t,e),et.init(t,e)}),XT=N("ZodCUID",(t,e)=>{b_.init(t,e),et.init(t,e)}),QT=N("ZodCUID2",(t,e)=>{S_.init(t,e),et.init(t,e)}),eM=N("ZodULID",(t,e)=>{E_.init(t,e),et.init(t,e)}),tM=N("ZodXID",(t,e)=>{C_.init(t,e),et.init(t,e)}),nM=N("ZodKSUID",(t,e)=>{__.init(t,e),et.init(t,e)}),rM=N("ZodIPv4",(t,e)=>{I_.init(t,e),et.init(t,e)}),oM=N("ZodIPv6",(t,e)=>{N_.init(t,e),et.init(t,e)}),sM=N("ZodCIDRv4",(t,e)=>{B_.init(t,e),et.init(t,e)}),iM=N("ZodCIDRv6",(t,e)=>{P_.init(t,e),et.init(t,e)}),aM=N("ZodBase64",(t,e)=>{O_.init(t,e),et.init(t,e)}),lM=N("ZodBase64URL",(t,e)=>{R_.init(t,e),et.init(t,e)}),cM=N("ZodE164",(t,e)=>{z_.init(t,e),et.init(t,e)}),uM=N("ZodJWT",(t,e)=>{L_.init(t,e),et.init(t,e)}),eg=N("ZodNumber",(t,e)=>{Mm.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(r,o,s)=>iT(t,r,o),t.gt=(r,o)=>t.check(Wm(r,o)),t.gte=(r,o)=>t.check(dd(r,o)),t.min=(r,o)=>t.check(dd(r,o)),t.lt=(r,o)=>t.check(Um(r,o)),t.lte=(r,o)=>t.check(ud(r,o)),t.max=(r,o)=>t.check(ud(r,o)),t.int=r=>t.check(tg(r)),t.safe=r=>t.check(tg(r)),t.positive=r=>t.check(Wm(0,r)),t.nonnegative=r=>t.check(dd(0,r)),t.negative=r=>t.check(Um(0,r)),t.nonpositive=r=>t.check(ud(0,r)),t.multipleOf=(r,o)=>t.check(Hm(r,o)),t.step=(r,o)=>t.check(Hm(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 Xt(t){return Rx(eg,t)}const dM=N("ZodNumberFormat",(t,e)=>{V_.init(t,e),eg.init(t,e)});function tg(t){return zx(dM,t)}const fM=N("ZodBoolean",(t,e)=>{F_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>aT(t,n,r)});function cn(t){return $x(fM,t)}const hM=N("ZodUnknown",(t,e)=>{j_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>cT()});function Pl(){return Lx(hM)}const pM=N("ZodNever",(t,e)=>{U_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>lT(t,n,r)});function mM(t){return Vx(pM,t)}const gM=N("ZodArray",(t,e)=>{W_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>pT(t,n,r,o),t.element=e.element,t.min=(n,r)=>t.check(Il(n,r)),t.nonempty=n=>t.check(Il(1,n)),t.max=(n,r)=>t.check(Zm(n,r)),t.length=(n,r)=>t.check(Km(n,r)),t.unwrap=()=>t.element});function Mn(t,e){return Xx(gM,t,e)}const yM=N("ZodObject",(t,e)=>{Z_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>mT(t,n,r,o),Oe(t,"shape",()=>e.shape),t.keyof=()=>hd(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Pl()}),t.loose=()=>t.clone({...t._zod.def,catchall:Pl()}),t.strict=()=>t.clone({...t._zod.def,catchall:mM()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>hC(t,n),t.safeExtend=n=>pC(t,n),t.merge=n=>mC(t,n),t.pick=n=>dC(t,n),t.omit=n=>fC(t,n),t.partial=(...n)=>gC(ng,t,n[0]),t.required=(...n)=>yC(sg,t,n[0])});function Un(t,e){const n={type:"object",shape:t??{},...re(e)};return new yM(n)}const wM=N("ZodUnion",(t,e)=>{K_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>gT(t,n,r,o),t.options=e.options});function vM(t,e){return new wM({type:"union",options:t,...re(e)})}const kM=N("ZodIntersection",(t,e)=>{Y_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>yT(t,n,r,o)});function bM(t,e){return new kM({type:"intersection",left:t,right:e})}const SM=N("ZodTuple",(t,e)=>{Om.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>wT(t,n,r,o),t.rest=n=>t.clone({...t._zod.def,rest:n})});function Ol(t,e,n){const r=e instanceof We,o=r?n:e,s=r?e:null;return new SM({type:"tuple",items:t,rest:s,...re(o)})}const EM=N("ZodRecord",(t,e)=>{q_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>vT(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType});function CM(t,e,n){return new EM({type:"record",keyType:t,valueType:e,...re(n)})}const fd=N("ZodEnum",(t,e)=>{G_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(r,o,s)=>uT(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 fd({...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 fd({...e,checks:[],...re(o),entries:s})}});function hd(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new fd({type:"enum",entries:n,...re(e)})}const _M=N("ZodTransform",(t,e)=>{J_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>hT(t,n),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new lm(t.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(Yi(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(Yi(i))}};const o=e.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function xM(t){return new _M({type:"transform",transform:t})}const ng=N("ZodOptional",(t,e)=>{Rm.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Jm(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function rg(t){return new ng({type:"optional",innerType:t})}const TM=N("ZodExactOptional",(t,e)=>{X_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Jm(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function MM(t){return new TM({type:"optional",innerType:t})}const AM=N("ZodNullable",(t,e)=>{Q_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>kT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function og(t){return new AM({type:"nullable",innerType:t})}const IM=N("ZodDefault",(t,e)=>{ex.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.removeDefault=t.unwrap});function NM(t,e){return new IM({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():pm(e)}})}const BM=N("ZodPrefault",(t,e)=>{tx.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ET(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function PM(t,e){return new BM({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():pm(e)}})}const sg=N("ZodNonOptional",(t,e)=>{nx.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 OM(t,e){return new sg({type:"nonoptional",innerType:t,...re(e)})}const DM=N("ZodCatch",(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,t.removeCatch=t.unwrap});function RM(t,e){return new DM({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const zM=N("ZodPipe",(t,e)=>{ox.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>_T(t,n,r,o),t.in=e.in,t.out=e.out});function ig(t,e){return new zM({type:"pipe",in:t,out:e})}const $M=N("ZodReadonly",(t,e)=>{sx.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>xT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function LM(t){return new $M({type:"readonly",innerType:t})}const VM=N("ZodFunction",(t,e)=>{ix.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>fT(t,n)});function FM(t){return new VM({type:"function",input:Array.isArray(t==null?void 0:t.input)?Ol(t==null?void 0:t.input):(t==null?void 0:t.input)??Mn(Pl()),output:(t==null?void 0:t.output)??Pl()})}const ag=N("ZodCustom",(t,e)=>{ax.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>dT(t,n)});function An(t,e){return Qx(ag,()=>!0,e)}function jM(t,e={}){return eT(ag,t,e)}function UM(t){return tT(t)}function WM(t){const e=HM(t.chars),n=ZM(e,t.firstPositive,t.mostPositive,t.mostNegative),r=t.jitterRange??Math.floor(Math.pow(e.length,3)/5),o=KM(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 HM(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 ZM(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 KM(t,e){const n={};for(let r=0;r<100&&(n[r]=Math.pow(e,r),!(n[r]>t));r++);return n}var pd=null;function lg(){return pd||(pd=WM({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 md(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+Dl(t.slice(1),"positive",e):n===e.mostNegative?yo(n,e.firstNegative,e)+1+Dl(t.slice(1),"negative",e):n>=e.firstPositive?yo(n,e.firstPositive,e)+2:yo(n,e.firstNegative,e)+2}function Dl(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+Dl(t.slice(1),e,n):r===n.mostNegative&&e==="negative"?yo(r,n.mostPositive,n)+1+Dl(t.slice(1),e,n):e==="positive"?yo(r,n.mostNegative,n)+2:yo(r,n.mostPositive,n)+2}function Rl(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 YM(t,e,n){let[r,o]=Rl(t,e,"end",n.first),s=gd(r,o,n);s===1&&(r=r.padEnd(r.length+1,n.first),s=n.length);const i=dg(Math.floor(s/2),n);return yd(r,i,n)}function gd(t,e,n){const[r,o]=Rl(t,e,"end",n.first).sort(),s=cg(o,r,n);return qM(s,n)}function yd(t,e,n){const r=n.length,[o,s]=Rl(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 cg(t,e,n,r=!0){const o=n.length,[s,i]=Rl(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 ug(t,e){return yd(t,e.byCode[1],e)}function wd(t,e){return cg(t,e.byCode[1],e,!1)}function dg(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 qM(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 GM(t){return t.firstPositive+t.byCode[0]}function JM(t,e){return md(t,e)===t.length}function fg(t,e){zl(t,e)}function zl(t,e){const n=mg(t,e),r=md(n,e);if(r>t.length)throw new Error("invalid order key length: "+t);return t.slice(0,r)}function hg(t,e){if(!JM(t,e))throw new Error("invalid integer length: "+t)}function pg(t,e){hg(t,e);const[n,r]=gg(t,e);if(r.split("").some(i=>i!==e.byCode[e.length-1])){const i=ug(r,e);return n+i}const s=QM(n,e);return yg(s,"lower",e)}function XM(t,e){hg(t,e);const[n,r]=gg(t,e);if(r.split("").some(i=>i!==e.byCode[0])){const i=wd(r,e);return n+i}const s=eA(n,e);return yg(s,"upper",e)}function mg(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 gg(t,e){const n=mg(t,e),r=t.slice(n.length);return[n,r]}function QM(t,e){const n=t>=e.firstPositive,r=ug(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 eA(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 wd(o,e)}return!n&&r?t+e.mostPositive:wd(t,e)}function yg(t,e,n){const r=md(t,n),o=e==="upper"?n.byCode[n.length-1]:n.byCode[0];return t+o.repeat(r-t.length)}function wg(t,e){const n=dg(Math.floor(Math.random()*e.jitterRange),e);return yd(t,n,e)}function tA(t,e,n){const r=t.padEnd(t.length+e,n.first);return wg(r,n)}function nA(t,e,n){const r=zl(t,n),o=pg(r,n);let s=0;if(e!==null){const a=gd(t,e,n);a<n.jitterRange+1&&(s=Math.max(s,vg(a,n)))}const i=gd(t,o,n);return i<n.jitterRange+1&&(s=Math.max(s,vg(i,n))),s}function vg(t,e){const n=e.jitterRange-t,r=Object.entries(e.paddingDict).find(([o,s])=>s>n);return r?parseInt(r[0]):0}function rA(t,e,n=lg()){if(t!==null&&fg(t,n),e!==null&&fg(e,n),t===null&&e===null)return GM(n);if(t===null){const r=zl(e,n);return XM(r,n)}if(e===null){const r=zl(t,n);return pg(r,n)}if(t>=e)throw new Error(t+" >= "+e);return YM(t,e,n)}function $l(t,e,n=lg()){const r=rA(t,e,n),o=nA(r,e,n);return o?tA(r,o,n):wg(r,n)}function oA(){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 sA(){const t=oA();if(t.__xstate__)return t.__xstate__}const iA=t=>{if(typeof window>"u")return;const e=sA();e&&e.register(t)};class kg{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 bg=".",aA="",Sg="",lA="#",cA="*",Eg="xstate.init",uA="xstate.error",vd="xstate.stop";function dA(t,e){return{type:`xstate.after.${t}.${e}`}}function kd(t,e){return{type:`xstate.done.state.${t}`,output:e}}function fA(t,e){return{type:`xstate.done.actor.${t}`,output:e,actorId:t}}function Cg(t,e){return{type:`xstate.error.actor.${t}`,error:e,actorId:t}}function _g(t){return{type:Eg,input:t}}function mr(t){setTimeout(()=>{throw t})}const hA=typeof Symbol=="function"&&Symbol.observable||"@@observable";function xg(t,e){const n=Tg(t),r=Tg(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?xg(n[o],r[o]):!1)}function bd(t){if(Ig(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 Tg(t){if(GA(t))return t.value;if(typeof t!="string")return t;const e=bd(t);return pA(e)}function pA(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 Mg(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 Ag(t){return Ig(t)?t:[t]}function wo(t){return t===void 0?[]:Ag(t)}function Sd(t,e,n,r){return typeof t=="function"?t({context:e,event:n,self:r}):t}function Ig(t){return Array.isArray(t)}function mA(t){return t.type.startsWith("xstate.error.actor")}function oi(t){return Ag(t).map(e=>typeof e>"u"||typeof e=="string"?{target:e}:e)}function Ng(t){if(!(t===void 0||t===aA))return wo(t)}function Ed(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 Bg(t,e){return`${e}.${t}`}function Cd(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 gA(t,e){if(e===t||e===cA)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 Pg(t,e){return`${t.sessionId}.${e}`}let yA=0;function wA(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=Pg(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=Pg(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:${yA++}`,_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=Ed(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 _d=!1;const xd=1;let un=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const vA={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class kA{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 kg(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={...vA,...n},{clock:o,logger:s,parent:i,syncSnapshot:a,id:l,systemId:c,inspect:u}=r;this.system=i?i.system:wA(this,{clock:o,logger:s}),u&&!i&&this.system.inspect(Ed(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){mr(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=_d;try{_d=!0,f.exec(f.info,f.params)}finally{_d=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){mr(a)}break;case"done":for(const i of this.observers)try{(s=i.next)==null||s.call(i,e)}catch(a){mr(a)}this._stopProcedure(),this._complete(),this._doneEvent=fA(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=Ed(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){mr(i)}break;case"error":{const i=this._snapshot.error;if(!o.error)mr(i);else try{o.error(i)}catch(a){mr(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=_g(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===vd&&(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:vd}),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){mr(r)}this.observers.clear(),this.eventListeners.clear()}_reportError(e){if(!this.observers.size){this._parent||mr(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){mr(s)}}this.observers.clear(),this.eventListeners.clear(),n&&mr(e)}_error(e){this._stopProcedure(),this._reportError(e),this._parent&&this.system._relay(this,this._parent,Cg(this.id,e))}_stopProcedure(){return this._processingStatus!==un.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new kg(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:iA)(this)}toJSON(){return{xstate$$type:xd,id:this.id}}getPersistedSnapshot(e){return this.logic.getPersistedSnapshot(this._snapshot,e)}[hA](){return this}getSnapshot(){return this._snapshot}}function Gi(t,...[e]){return new kA(t,e)}function bA(t,e,n,r,{sendId:o}){const s=typeof o=="function"?o(n,r):o;return[e,{sendId:s},void 0]}function SA(t,e){t.defer(()=>{t.system.scheduler.cancel(t.self,e.sendId)})}function Td(t){function e(n,r){}return e.type="xstate.cancel",e.sendId=t,e.resolve=bA,e.execute=SA,e}function EA(t,e,n,r,{id:o,systemId:s,src:i,input:a,syncSnapshot:l}){const c=typeof i=="string"?Cd(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=Gi(c,{id:u,src:i,parent:t.self,syncSnapshot:l,systemId:s,input:h})),[as(e,{children:{...e.children,[u]:f}}),{id:o,systemId:s,actorRef:f,src:i,input:h},void 0]}function CA(t,{actorRef:e}){e&&t.defer(()=>{e._processingStatus!==un.Stopped&&e.start()})}function Md(...[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=EA,s.execute=CA,s}function _A(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]),[as(e,{children:a}),i,void 0]}function Og(t,e){const n=e.getSnapshot();if(n&&"children"in n)for(const r of Object.values(n.children))Og(t,r);t.system._unregister(e)}function xA(t,e){if(e){if(Og(t,e),e._processingStatus!==un.Running){t.stopChild(e);return}t.defer(()=>{t.stopChild(e)})}}function Ll(t){function e(n,r){}return e.type="xstate.stopChild",e.actorRef=t,e.resolve=_A,e.execute=xA,e}function TA(t,{context:e,event:n},{guards:r}){return!si(r[0],e,n,t)}function ss(t){function e(n,r){return!1}return e.check=TA,e.guards=[t],e}function MA(t,{context:e,event:n},{guards:r}){return r.every(o=>si(o,e,n,t))}function Ji(t){function e(n,r){return!1}return e.check=MA,e.guards=t,e}function si(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 si(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 Ad(t){return t.type==="atomic"||t.type==="final"}function ii(t){return Object.values(t.states).filter(e=>e.type!=="history")}function Xi(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 Vl(t){const e=new Set(t),n=Rg(e);for(const r of e)if(r.type==="compound"&&(!n.get(r)||!n.get(r).length))Lg(r).forEach(o=>e.add(o));else if(r.type==="parallel"){for(const o of ii(r))if(o.type!=="history"&&!e.has(o)){const s=Lg(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 Dg(t,e){const n=e.get(t);if(!n)return{};if(t.type==="compound"){const o=n[0];if(o){if(Ad(o))return o.key}else return{}}const r={};for(const o of n)r[o.key]=Dg(o,e);return r}function Rg(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 zg(t,e){const n=Vl(e);return Dg(t,Rg(n))}function Id(t,e){return e.type==="compound"?ii(e).some(n=>n.type==="final"&&t.has(n)):e.type==="parallel"?ii(e).every(n=>Id(t,n)):e.type==="final"}const Fl=t=>t[0]===lA;function AA(t,e){return t.transitions.get(e)||[...t.transitions.keys()].filter(r=>gA(e,r)).sort((r,o)=>o.length-r.length).flatMap(r=>t.transitions.get(r))}function IA(t){const e=t.config.after;if(!e)return[];const n=o=>{const s=dA(o,t.id),i=s.type;return t.entry.push(Hl(s,{id:i,delay:o})),t.exit.push(Td(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=Ng(n.target),o=n.reenter??!1,s=OA(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 NA(t){const e=new Map;if(t.config.on)for(const n of Object.keys(t.config.on)){if(n===Sg)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const r=t.config.on[n];e.set(n,oi(r).map(o=>vo(t,n,o)))}if(t.config.onDone){const n=`xstate.done.state.${t.id}`;e.set(n,oi(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,oi(n.onDone).map(o=>vo(t,r,o)))}if(n.onError){const r=`xstate.error.actor.${n.id}`;e.set(r,oi(n.onError).map(o=>vo(t,r,o)))}if(n.onSnapshot){const r=`xstate.snapshot.${n.id}`;e.set(r,oi(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 BA(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 PA(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 OA(t,e){if(e!==void 0)return e.map(n=>{if(typeof n!="string")return n;if(Fl(n))return t.machine.getStateNodeById(n);const r=n[0]===bg;if(r&&!t.parent)return jl(t,n.slice(1));const o=r?t.key+n:n;if(t.parent)try{return jl(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 $g(t){const e=Ng(t.config.target);return e?{target:e.map(n=>typeof n=="string"?jl(t.parent,n):n)}:t.parent.initial}function is(t){return t.type==="history"}function Lg(t){const e=Vg(t);for(const n of e)for(const r of Xi(n,t))e.add(r);return e}function Vg(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 ii(r))n(o)}}return n(t),e}function ai(t,e){if(Fl(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 jl(t,e){if(typeof e=="string"&&Fl(e))try{return t.machine.getStateNodeById(e)}catch{}const n=bd(e).slice();let r=t;for(;n.length;){const o=n.shift();if(!o.length)break;r=ai(r,o)}return r}function Ul(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=>ai(t,o)).filter(Boolean);return[t.machine.root,t].concat(r,n.reduce((o,s)=>{const i=ai(t,s);if(!i)return o;const a=Ul(i,e[s]);return o.concat(a)},[]))}function DA(t,e,n,r){const s=ai(t,e).next(n,r);return!s||!s.length?t.next(n,r):s}function RA(t,e,n,r){const o=Object.keys(e),s=ai(t,o[0]),i=Nd(s,e[o[0]],n,r);return!i||!i.length?t.next(n,r):i}function zA(t,e,n,r){const o=[];for(const s of Object.keys(e)){const i=e[s];if(!i)continue;const a=ai(t,s),l=Nd(a,i,n,r);l&&o.push(...l)}return o.length?o:t.next(n,r)}function Nd(t,e,n,r){return typeof e=="string"?DA(t,e,n,r):Object.keys(e).length===1?RA(t,e,n,r):zA(t,e,n,r)}function $A(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 LA(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 Fg(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(LA(Pd([o],e,n),Pd([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 VA(t){const[e,...n]=t;for(const r of Xi(e,void 0))if(n.every(o=>ko(o,r)))return r}function Bd(t,e){if(!t.target)return[];const n=new Set;for(const r of t.target)if(is(r))if(e[r.id])for(const o of e[r.id])n.add(o);else for(const o of Bd($g(r),e))n.add(o);else n.add(r);return[...n]}function jg(t,e){const n=Bd(t,e);if(!n)return;if(!t.reenter&&n.every(o=>o===t.source||ko(o,t.source)))return t.source;const r=VA(n.concat(t.source));if(r)return r;if(!t.reenter)return t.source.machine.root}function Pd(t,e,n){var o;const r=new Set;for(const s of t)if((o=s.target)!=null&&o.length){const i=jg(s,n);s.reenter&&s.source===i&&r.add(i);for(const a of e)ko(a,i)&&r.add(a)}return[...r]}function FA(t,e){if(t.length!==e.size)return!1;for(const n of t)if(!e.has(n))return!1;return!0}function jA(t,e,n,r,o){return Od([{target:[...Vg(t)],source:t,reenter:!0,actions:[],eventType:null,toJSON:null}],e,n,r,!0,o)}function Od(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=Fg(t,l,c);let f=e;o||([f,c]=ZA(f,r,n,u,l,c,s,n.actionExecutor)),f=ci(f,r,n,u.flatMap(p=>p.actions),s,void 0),f=WA(f,r,n,u,l,s,c,o);const h=[...l];f.status==="done"&&(f=ci(f,r,n,h.sort((p,m)=>m.order-p.order).flatMap(p=>p.exit),s,void 0));try{return c===e.historyValue&&FA(e._nodes,l)?[f,i]:[as(f,{_nodes:h,historyValue:c}),i]}catch(p){throw p}}finally{n.actionExecutor=a}}function UA(t,e,n,r,o){if(r.output===void 0)return;const s=kd(o.id,o.output!==void 0&&o.parent?Sd(o.output,t.context,e,n.self):void 0);return Sd(r.output,t.context,s,n.self)}function WA(t,e,n,r,o,s,i,a){let l=t;const c=new Set,u=new Set;HA(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(Md(m.src,{...m,syncSnapshot:!!m.onSnapshot}));if(u.has(h)){const m=h.initial.actions;p.push(...m)}if(l=ci(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(kd(m.id,h.output!==void 0?Sd(h.output,l.context,e,n.self):void 0));(g==null?void 0:g.type)==="parallel"&&!f.has(g)&&Id(o,g);)f.add(g),s.push(kd(g.id)),y=g,g=g.parent;if(g)continue;l=as(l,{status:"done",output:UA(l,e,n,l.machine.root,y)})}}return l}function HA(t,e,n,r){for(const o of t){const s=jg(o,e);for(const a of o.target||[])!is(a)&&(o.source!==a||o.source!==s||o.reenter)&&(r.add(a),n.add(a)),li(a,e,n,r);const i=Bd(o,e);for(const a of i){const l=Xi(a,s);(s==null?void 0:s.type)==="parallel"&&l.push(s),Ug(r,e,n,l,!o.source.parent&&o.reenter?void 0:s)}}}function li(t,e,n,r){var o;if(is(t))if(e[t.id]){const s=e[t.id];for(const i of s)r.add(i),li(i,e,n,r);for(const i of s)Dd(i,t.parent,r,e,n)}else{const s=$g(t);for(const i of s.target)r.add(i),s===((o=t.parent)==null?void 0:o.initial)&&n.add(t.parent),li(i,e,n,r);for(const i of s.target)Dd(i,t.parent,r,e,n)}else if(t.type==="compound"){const[s]=t.initial.target;is(s)||(r.add(s),n.add(s)),li(s,e,n,r),Dd(s,t,r,e,n)}else if(t.type==="parallel")for(const s of ii(t).filter(i=>!is(i)))[...r].some(i=>ko(i,s))||(is(s)||(r.add(s),n.add(s)),li(s,e,n,r))}function Ug(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 ii(s).filter(a=>!is(a)))[...t].some(a=>ko(a,i))||(t.add(i),li(i,e,n,t))}function Dd(t,e,n,r,o){Ug(n,r,o,Xi(t,e))}function ZA(t,e,n,r,o,s,i,a){let l=t;const c=Pd(r,o,s);c.sort((f,h)=>h.order-f.order);let u;for(const f of c)for(const h of $A(f)){let p;h.history==="deep"?p=m=>Ad(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=ci(l,e,n,[...f.exit,...f.invoke.map(h=>Ll(h.id))],i,void 0),o.delete(f);return[l,u||s]}function KA(t,e){return t.implementations.actions[e]}function Wg(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:KA(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=Wg(a,e,n,y,o,s))}return a}function ci(t,e,n,r,o,s){const i=s?[]:void 0,a=Wg(t,e,n,r,{internalQueue:o,deferredActorIds:s},i);return i==null||i.forEach(([l,c])=>{l.retryResolve(n,a,c)}),a}function Rd(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===vd)return o=as(Hg(o,e,n),{status:"stopped"}),i([o,[]],e,[]),{snapshot:o,microsteps:s};let a=e;if(a.type!==Eg){const c=a,u=mA(c),f=Zg(c,o);if(u&&!f.length)return o=as(t,{status:"error",error:c.error}),i([o,[]],c,[]),{snapshot:o,microsteps:s};const h=Od(f,t,n,a,!1,r);o=h[0],i(h,c,f)}let l=!0;for(;o.status==="active";){let c=l?YA(o,a):[];const u=c.length?o:void 0;if(!c.length){if(!r.length)break;a=r.shift(),c=Zg(a,o)}const f=Od(c,o,n,a,!1,r);o=f[0],l=o!==u,i(f,a,c)}return o.status!=="active"&&Hg(o,a,n),{snapshot:o,microsteps:s}}function Hg(t,e,n){return ci(t,e,n,Object.values(t.children).map(r=>Ll(r)),[],void 0)}function Zg(t,e){return e.machine.getTransitionData(e,t)}function YA(t,e){const n=new Set,r=t._nodes.filter(Ad);for(const o of r)e:for(const s of[o].concat(Xi(o,void 0)))if(s.always){for(const i of s.always)if(i.guard===void 0||si(i.guard,t.context,e,t)){n.add(i);break e}}return Fg(Array.from(n),new Set(t._nodes),t.historyValue)}function qA(t,e){const n=Vl(Ul(t,e));return zg(t,[...n])}function GA(t){return!!t&&typeof t=="object"&&"machine"in t&&"value"in t}const JA=function(e){return xg(e,this.value)},XA=function(e){return this.tags.has(e)},QA=function(e){const n=this.machine.getTransitionData(this,e);return!!(n!=null&&n.length)&&n.some(r=>r.target!==void 0||r.actions.length)},eI=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)}},tI=function(){return this._nodes.reduce((e,n)=>(n.meta!==void 0&&(e[n.id]=n.meta),e),{})};function Wl(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:zg(e.root,t._nodes),tags:new Set(t._nodes.flatMap(n=>n.tags)),children:t.children,historyValue:t.historyValue||{},matches:JA,hasTag:XA,can:QA,getMeta:tI,toJSON:eI}}function as(t,e={}){return Wl({...t,...e},t.machine)}function nI(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 rI(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:Kg(i),children:p,historyValue:nI(h.historyValue)}}function Kg(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:xd,id:r.id};else{const o=Kg(r);o!==r&&(e??(e=Array.isArray(t)?t.slice():{...t}),e[n]=o)}}return e??t}function oI(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 sI(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 Hl(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=oI,n.execute=sI,n}function iI(t,{machine:e,context:n},r,o){const s=(i,a)=>{if(typeof i=="string"){const l=Cd(e,i);if(!l)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const c=Gi(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 Gi(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 aI(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:iI(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[as(e,{context:l,children:Object.keys(s).length?{...e.children,...s}:e.children}),void 0,void 0]}function He(t){function e(n,r){}return e.type="xstate.assign",e.assignment=t,e.resolve=aI,e}const Yg=new WeakMap;function ui(t,e,n){let r=Yg.get(t);return r?e in r||(r[e]=n()):(r={[e]:n()},Yg.set(t,r)),r[e]}const lI={},Qi=t=>typeof t=="string"?{type:t}:typeof t=="function"?"resolve"in t?{type:t.type}:{type:t.name}:t;class Zl{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(bg),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?Mg(this.config.states,(r,o)=>new Zl(r,{_parent:this,_key:o,_machine:this.machine})):lI,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=NA(this),this.config.always&&(this.always=oi(this.config.always).map(e=>vo(this,Sg,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(Qi),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(e=>`#${e.id}`),source:`#${this.id}`,actions:this.initial.actions.map(Qi),eventType:null})}:void 0,history:this.history,states:Mg(this.states,e=>e.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(e=>({...e,actions:e.actions.map(Qi)})),entry:this.entry.map(Qi),exit:this.exit.map(Qi),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 ui(this,"invoke",()=>wo(this.config.invoke).map((e,n)=>{const{src:r,systemId:o}=e,s=e.id??Bg(this.id,n),i=typeof r=="string"?r:`xstate.invoke.${Bg(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 ui(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 ui(this,"delayedTransitions",()=>IA(this))}get initial(){return ui(this,"initial",()=>PA(this,this.config.initial))}next(e,n){const r=n.type,o=[];let s;const i=ui(this,`candidates-${r}`,()=>AA(this,r));for(const a of i){const{guard:l}=a,c=e.context;let u=!1;try{u=!l||si(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 ui(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 cI="#";class zd{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 Zl(e,{_key:this.id,_machine:this}),this.root._initialize(),BA(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 zd(this.config,{actions:{...n,...e.actions},guards:{...r,...e.guards},actors:{...o,...e.actors},delays:{...s,...e.delays}})}resolveState(e){const n=qA(this.root,e.value),r=Vl(Ul(this.root,n));return Wl({_nodes:[...r],context:e.context||{},children:{},status:Id(r,this.root)?"done":e.status||"active",output:e.output,error:e.error,historyValue:e.historyValue},this)}transition(e,n,r){return Rd(e,n,r,[]).snapshot}microstep(e,n,r){return Rd(e,n,r,[]).microsteps.map(([o])=>o)}getTransitionData(e,n){return Nd(this.root,e.value,e,n)||[]}_getPreInitialState(e,n,r){const{context:o}=this.config,s=Wl({context:typeof o!="function"&&o?o:{},_nodes:[this.root],children:{},status:"active"},this);return typeof o=="function"?ci(s,n,e,[He(({spawn:a,event:l,self:c})=>o({spawn:a,input:l.input,self:c}))],r,void 0):s}getInitialSnapshot(e,n){const r=_g(n),o=[],s=this._getPreInitialState(e,r,o),[i]=jA(this.root,s,e,r,o),{snapshot:a}=Rd(i,r,e,o);return a}start(e){Object.values(e.children).forEach(n=>{n.getSnapshot().status==="active"&&n.start()})}getStateNodeById(e){const n=bd(e),r=n.slice(1),o=Fl(n[0])?n[0].slice(cI.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 jl(s,r)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(e,n){return rI(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"?Cd(this,m):m;if(!g)return;const y=Gi(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 Zl)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=Wl({...e,children:r,_nodes:Array.from(Vl(Ul(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===xd){f[p]=h[m.id];continue}u(m,h)}}}}return u(l.context,r),l}}function uI(t,e,n,r,{event:o}){const s=typeof o=="function"?o(n,r):o;return[e,{event:s},void 0]}function dI(t,{event:e}){t.defer(()=>t.emit(e))}function qg(t){function e(n,r){}return e.type="xstate.emit",e.event=t,e.resolve=uI,e.execute=dI,e}let $d=function(t){return t.Parent="#_parent",t.Internal="#_internal",t}({});function fI(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===$d.Parent?p=t.self._parent:h===$d.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 hI(t,e,n){typeof n.to=="string"&&(n.to=e.children[n.to])}function pI(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===uA?Cg(t.self.id,r.data):r)})}function Ld(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=fI,r.retryResolve=hI,r.execute=pI,r}function mI(t,e){return Ld($d.Parent,t,e)}function gI(t,e,n,r,{collect:o}){const s=[],i=function(l){s.push(l)};return i.assign=(...a)=>{s.push(He(...a))},i.cancel=(...a)=>{s.push(Td(...a))},i.raise=(...a)=>{s.push(Hl(...a))},i.sendTo=(...a)=>{s.push(Ld(...a))},i.sendParent=(...a)=>{s.push(mI(...a))},i.spawnChild=(...a)=>{s.push(Md(...a))},i.stopChild=(...a)=>{s.push(Ll(...a))},i.emit=(...a)=>{s.push(qg(...a))},o({context:n.context,event:n.event,enqueue:i,check:a=>si(a,e.context,n.event,e),self:t.self,system:t.system},r),[e,void 0,s]}function yI(t){function e(n,r){}return e.type="xstate.enqueueActions",e.collect=t,e.resolve=gI,e}function wI(t,e,n,r,{value:o,label:s}){return[e,{value:typeof o=="function"?o(n,r):o,label:s},void 0]}function vI({logger:t},{value:e,label:n}){n?t(n,e):t(e)}function kI(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=wI,n.execute=vI,n}function bI(t,e){return new zd(t,e)}function SI(t){const e=Gi(t);return{self:e,defer:()=>{},id:"",logger:()=>{},sessionId:"",stopChild:()=>{},system:e.system,emit:()=>{},actionExecutor:()=>{}}}function $r({schemas:t,actors:e,actions:n,guards:r,delays:o}){return{assign:He,sendTo:Ld,raise:Hl,log:kI,cancel:Td,stopChild:Ll,enqueueActions:yI,emit:qg,spawnChild:Md,createStateConfig:s=>s,createAction:s=>s,createMachine:s=>bI({...s,schemas:t},{actors:e,actions:n,guards:r,delays:o}),extend:s=>$r({schemas:t,actors:e,actions:{...n,...s.actions},guards:{...r,...s.guards},delays:{...o,...s.delays}})}}function EI(t,e,n){const r=[],o=SI(t);return o.actionExecutor=i=>{r.push(i)},[t.transition(e,n,o),r]}var CI=Object.defineProperty,Gg=(t,e)=>{for(var n in e)CI(t,n,{get:e[n],enumerable:!0})},Jg={};Gg(Jg,{Aabb:()=>Ve,Asset:()=>cs,Block:()=>A,Color:()=>In,Connector:()=>Ze,Edited:()=>Lr,Held:()=>Rt,HitGeometry:()=>Te,Hovered:()=>bo,Image:()=>ea,MAX_HIT_ARCS:()=>Yl,MAX_HIT_CAPSULES:()=>di,Opacity:()=>ct,Pointer:()=>Ct,PointerButton:()=>bn,PointerType:()=>Vr,ScaleWithZoom:()=>So,Shape:()=>Hn,StrokeKind:()=>zt,Text:()=>yt,UploadState:()=>gr,User:()=>Eo,VerticalAlign:()=>us,addPointerSample:()=>Gl});function _I(){const t=["#f43f5e","#ec4899","#a855f7","#6366f1","#3b82f6","#0ea5e9","#14b8a6","#22c55e","#eab308","#f97316"];return t[Math.floor(Math.random()*t.length)]}var Xg=Un({userId:St().max(36).default(()=>crypto.randomUUID()),sessionId:St().max(36).default(()=>crypto.randomUUID()),color:St().max(7).default(_I),name:St().max(100).default("Anonymous"),avatar:St().max(500).default("")});function ls(t,e){return t.resources.pluginResources[e]}var xI=Un({enabled:cn().default(!0),strict:cn().default(!1),colWidth:Xt().nonnegative().default(20),rowHeight:Xt().nonnegative().default(20),snapAngleRad:Xt().nonnegative().default(Math.PI/36),shiftSnapAngleRad:Xt().nonnegative().default(Math.PI/12)}),TI=Un({leftMouseTool:St().max(32).default("select"),middleMouseTool:St().max(32).default("hand"),rightMouseTool:St().max(32).default("menu"),wheelTool:St().max(32).default("scroll"),modWheelTool:St().max(32).default("zoom")}),MI=Un({plugins:Mn(An()).default([]),maxEntities:Xt().default(5e3),user:An().default({}),grid:An().default({}),blockDefs:Mn(An()).default([]),keybinds:Mn(An()).default([]),cursors:CM(St(),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()});Un({command:St(),key:Xt(),mod:cn().optional(),shift:cn().optional()}),Un({makeSvg:FM({input:Ol([Xt()]),output:St()}),hotspot:Ol([Xt(),Xt()]),rotationOffset:Xt()});var ot={Default:"default",Scale:"scale",Text:"text",Free:"free",GroupOnly:"groupOnly"},gt={Top:"top",Center:"center",Bottom:"bottom"},Wn={Left:"left",Center:"center",Right:"right",Justify:"justify"},Qg=Un({canEdit:cn().default(!1),removeWhenTextEmpty:cn().default(!1)}),ey=Un({enabled:cn().default(!0),terminals:Mn(Ol([Xt(),Xt()])).default([[.5,0],[.5,1],[.5,.5],[0,.5],[1,.5]])}),AI=hd(["background","content","overlay"]),Vd=Un({tag:St(),stratum:AI.default("content"),editOptions:Qg.default(Qg.parse({})),components:Mn(An()).default([]),resizeMode:hd([ot.Scale,ot.Text,ot.Free,ot.GroupOnly]).default(ot.Scale),canRotate:cn().default(!0),canScale:cn().default(!0),connectors:ey.default(ey.parse({}))}),II=[[0,0],[0,0],[0,0],[0,0]],NI=[[0,0],[0,0],[0,0],[0,0]],BI=[[0,0],[0,0]],PI={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(""),resizeMode:C.enum(ot).default(ot.Default)},OI=class extends Gt{constructor(){super({name:"block",sync:"document"},PI)}getCenter(t,e,n){const{position:r,size:o}=this.read(t,e),s=n??[0,0];return mt.getCenter(r,o,s),s}setCenter(t,e,n){const r=this.write(t,e);mt.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 mt.getCorners(r,o,s,i),i}containsPoint(t,e,n){const{position:r,size:o,rotateZ:s}=this.read(t,e);return mt.containsPoint(r,o,s,n)}translate(t,e,n){const r=this.write(t,e);mt.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=mt.rotateAround(o.position,o.size,o.rotateZ,n,r)}scaleBy(t,e,n){const r=this.write(t,e);mt.scaleBy(r.position,r.size,n)}scaleAround(t,e,n,r){const o=this.write(t,e);mt.scaleAround(o.position,o.size,n,r)}intersectsAabb(t,e,n){const{position:r,size:o,rotateZ:s}=this.read(t,e);return mt.intersectsAabb(r,o,s,n,NI,II,BI)}worldToUv(t,e,n){const{position:r,size:o,rotateZ:s,flip:i}=this.read(t,e),a=mt.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 mt.uvToWorld(r,o,s,a)}getUvToWorldMatrix(t,e,n){const{position:r,size:o,rotateZ:s,flip:i}=this.read(t,e);mt.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 OI,ty=0,ny=1,ry=2,oy=3,DI={value:C.tuple(C.float32(),4).default([0,0,0,0])},RI=class extends Gt{constructor(){super({name:"aabb"},DI)}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=A.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[ty],o[0][1]=r[ny],o[1][0]=r[ry],o[1][1]=r[ny],o[2][0]=r[ry],o[2][1]=r[oy],o[3][0]=r[ty],o[3][1]=r[oy],o}applyPadding(t,e,n){const{value:r}=this.write(t,e);ne.pad(r,n)}},Ve=new RI,gr={Pending:"pending",Uploading:"uploading",Complete:"complete",Failed:"failed"},cs=Qe({name:"asset",sync:"document",excludeFromHistory:["uploadState"]},{identifier:C.string().max(512).default(""),uploadState:C.enum(gr).default(gr.Pending)}),zI={red:C.uint8().default(0),green:C.uint8().default(0),blue:C.uint8().default(0),alpha:C.uint8().default(255)},$I=class extends Gt{constructor(){super({name:"color",sync:"document"},zI)}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 $I,Ze=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])}),Lr=Qe({name:"edited"},{}),Rt=Qe({name:"held",sync:"ephemeral"},{sessionId:C.string().max(36).default("")}),Et=[1,0,0,1,0,0],di=64,Kl=5,Yl=2,ql=7,LI={hitCapsules:C.buffer(C.float32()).size(di*Kl),capsuleCount:C.uint16().default(0),hitArcs:C.buffer(C.float32()).size(Yl*ql),arcCount:C.uint16().default(0)},VI=class extends Gt{constructor(){super({name:"hitHeometry"},LI)}getCapsuleAt(t,e,n){const r=this.read(t,e),o=n*Kl;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*Kl;for(let i=0;i<Kl;i++)o.hitCapsules[s+i]=r[i]}getArcAt(t,e,n){const r=this.read(t,e),o=n*ql;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*ql;for(let i=0;i<ql;i++)o.hitArcs[s+i]=r[i]}containsPointWorld(t,e,n){const r=this.read(t,e);A.getUvToWorldMatrix(t,e,Et);for(let o=0;o<r.arcCount;o++){const s=this.getArcAt(t,e,o),i=[s[0],s[1]];ze.transformPoint(Et,i);const a=[s[2],s[3]];ze.transformPoint(Et,a);const l=[s[4],s[5]];ze.transformPoint(Et,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(Et,i);const a=[s[2],s[3]];ze.transformPoint(Et,a);const l=s[4],c=pt.create(i[0],i[1],a[0],a[1],l);if(pt.containsPoint(c,n))return!0}return!1}intersectsAabbWorld(t,e,n){const r=this.read(t,e);A.getUvToWorldMatrix(t,e,Et);for(let o=0;o<r.arcCount;o++){const s=this.getArcAt(t,e,o),i=[s[0],s[1]];ze.transformPoint(Et,i);const a=[s[2],s[3]];ze.transformPoint(Et,a);const l=[s[4],s[5]];ze.transformPoint(Et,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(Et,i);const a=[s[2],s[3]];ze.transformPoint(Et,a);const l=s[4],c=pt.create(i[0],i[1],a[0],a[1],l);if(pt.intersectsAabb(c,n))return!0}return!1}getExtremaWorld(t,e){const n=this.read(t,e),r=[];A.getUvToWorldMatrix(t,e,Et);for(let o=0;o<n.capsuleCount;o++){const s=this.getCapsuleAt(t,e,o),i=[s[0],s[1]];ze.transformPoint(Et,i);const a=[s[2],s[3]];ze.transformPoint(Et,a);const l=s[4],c=pt.create(i[0],i[1],a[0],a[1],l);r.push(...pt.getExtrema(c))}for(let o=0;o<n.arcCount;o++){const s=this.getArcAt(t,e,o),i=[s[0],s[1]];ze.transformPoint(Et,i);const a=[s[2],s[3]];ze.transformPoint(Et,a);const l=[s[4],s[5]];ze.transformPoint(Et,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>=di){console.warn(`HitGeometry: Max capsules (${di}) 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>=Yl){console.warn(`HitGeometry: Max arcs (${Yl}) 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}},Te=new VI,bo=Qe({name:"hovered"},{}),ea=Qe({name:"image",sync:"document"},{width:C.uint16().default(0),height:C.uint16().default(0),alt:C.string().max(256).default("")}),ct=Qe({name:"opacity"},{value:C.uint8().default(255)}),bn={None:"none",Left:"left",Middle:"middle",Right:"right",Back:"back",Forward:"forward"},Vr={Mouse:"mouse",Pen:"pen",Touch:"touch"},Fr=6,FI={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(Vr).default(Vr.Mouse),pressure:C.float32().default(0),obscured:C.boolean().default(!1),_prevPositions:C.array(C.float32(),Fr*2),_prevTimes:C.array(C.float32(),Fr),_sampleCount:C.int32().default(0),_velocity:C.tuple(C.float32(),2).default([0,0])},jI=class extends Gt{constructor(){super({name:"pointer"},FI)}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 Vr.Pen;case"touch":return Vr.Touch;default:return Vr.Mouse}}},Ct=new jI;function Gl(t,e,n){const r=t._sampleCount%Fr,o=t._prevTimes[r]||0;if(Math.abs(o-n)<.001)return;t.position=e,t._sampleCount++;const s=t._sampleCount%Fr;t._prevPositions[s*2]=e[0],t._prevPositions[s*2+1]=e[1],t._prevTimes[s]=n;const i=Math.min(t._sampleCount,Fr);if(i<=1){t._velocity=[0,0];return}const a=S=>(S%Fr+Fr)%Fr,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,T=-_;if(T>5*l)continue;const I=Math.exp(-T/l),B=t._prevPositions[k*2]||0,L=t._prevPositions[k*2+1]||0;u+=I,f+=I*_,h+=I*_*_,p+=I*B,m+=I*L,g+=I*_*B,y+=I*_*L}const w=u*h-f*f;if(Math.abs(w)<=c){const S=t._sampleCount%Fr,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),T=(t._prevPositions[S*2+1]||0)-(t._prevPositions[k*2+1]||0);t._velocity=[_/E,T/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])}),zt={Solid:"solid",Dashed:"dashed",None:"none"},Hn=Qe({name:"shape",sync:"document"},{kind:C.string().default("rectangle"),strokeKind:C.enum(zt).default(zt.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)}),yt=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(Wn).default(Wn.Left)}),Eo=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])}),us=Qe({name:"verticalAlign",sync:"document"},{value:C.enum(gt).default(gt.Top)}),UI="core",Fd={background:0,content:1,overlay:2},sy={};Gg(sy,{Camera:()=>we,Controls:()=>ut,Cursor:()=>Nn,Frame:()=>fi,Grid:()=>Ht,Intersect:()=>ds,Key:()=>dn,Keyboard:()=>Sn,Mouse:()=>Bn,RankBounds:()=>Zn,ScaleWithZoomState:()=>Wd,Screen:()=>_t,clearBits:()=>fs,codeToIndex:()=>O,setBit:()=>ta});var WI={width:C.float64().default(0),height:C.float64().default(0),left:C.float64().default(0),top:C.float64().default(0)},HI=class extends kt{constructor(){super({name:"screen"},WI)}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 HI,ZI={top:C.float64().default(0),left:C.float64().default(0),zoom:C.float64().default(1),canSeeBlocks:C.boolean().default(!0),lastSeenBlock:C.ref()},KI=class extends kt{constructor(){super({name:"camera",sync:"local"},ZI)}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 KI,YI={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("")},qI=class extends kt{constructor(){super({name:"controls"},YI)}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}},ut=new qI,GI={cursorKind:C.string().max(64).default("select"),rotation:C.float64().default(0),contextCursorKind:C.string().max(64).default(""),contextRotation:C.float64().default(0)},JI=class extends kt{constructor(){super({name:"cursor"},GI)}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}},Nn=new JI,fi=Ki({name:"frame"},{number:C.uint32().default(0),delta:C.float64().default(0),time:C.float64().default(0),lastTime:C.float64().default(0)}),XI={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)},QI=class extends kt{constructor(){super({name:"grid"},XI)}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}},Ht=new QI,e2={entity1:C.ref(),entity2:C.ref(),entity3:C.ref(),entity4:C.ref(),entity5:C.ref()},t2=class extends kt{constructor(){super({name:"intersect"},e2)}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}},ds=new t2,jd=32,n2={keysDown:C.buffer(C.uint8()).size(jd),keysDownTrigger:C.buffer(C.uint8()).size(jd),keysUpTrigger:C.buffer(C.uint8()).size(jd),shiftDown:C.boolean().default(!1),altDown:C.boolean().default(!1),modDown:C.boolean().default(!1)};function Ud(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 r2=class extends kt{constructor(){super({name:"keyboard"},n2)}isKeyDown(t,e){return Ud(this.read(t).keysDown,e)}isKeyDownTrigger(t,e){return Ud(this.read(t).keysDownTrigger,e)}isKeyUpTrigger(t,e){return Ud(this.read(t).keysUpTrigger,e)}reset(t){const e=this.write(t);fs(e.keysDown),fs(e.keysDownTrigger),fs(e.keysUpTrigger),e.shiftDown=!1,e.altDown=!1,e.modDown=!1}},Sn=new r2;function ta(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 fs(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},o2={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)},s2=class extends kt{constructor(){super({name:"mouse"},o2)}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 s2,i2={minRank:C.string().max(36).default(""),maxRank:C.string().max(36).default("")},a2=class extends kt{constructor(){super({name:"rankBounds"},i2)}genNext(t){const e=this.write(t),n=$l(e.maxRank||null,null);return e.maxRank=n,e.minRank||(e.minRank=n),n}genPrev(t){const e=this.write(t),n=$l(null,e.minRank||null);return e.minRank=n,e.maxRank||(e.maxRank=n),n}genBetween(t,e){return $l(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 a2,Wd=Ki({name:"scaleWithZoomState"},{lastZoom:C.float64().default(1)}),hi=Kp({name:C.string().max(128)}),iy=new WeakMap;function Hd(t){const{editor:e}=Ge(t);let n=iy.get(e);return n||(n=new Map,iy.set(e,n)),n}var Zd=ie(t=>t.with(hi));function pe(t){return{name:t,spawn(e,n){const r=Bt(e);return Q(e,r,hi,{name:t}),Hd(e).set(r,n),r},*iter(e){const n=Hd(e);for(const r of Zd.current(e))if(hi.read(e,r).name===t){const s=n.get(r);yield{eid:r,payload:s}}},didSpawnLastFrame(e){for(const n of Zd.removed(e))if(hi.read(e,n).name===t)return!0;return!1}}}function l2(t){const e=Hd(t);for(const n of Zd.current(t))e.delete(n),it(t,n)}function he(t,e,n){for(const{payload:r}of e.iter(t))n(t,r)}var Kd=pe("undo"),Jl=pe("redo"),ay=pe("reset-keyboard"),c2=0;function Se(t,e){return{_system:new DE(e),phase:t.phase,priority:t.priority??c2}}var u2=Se({phase:"capture"},t=>{const e=Sn.read(t),{editor:n}=Ge(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);Q(t,s,hi,{name:r.command});break}}}),d2=Se({phase:"input",priority:100},t=>{const e=performance.now(),n=fi._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)}),na=new WeakMap;function f2(t){if(na.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"})}};na.set(t,e),t.addEventListener("keydown",e.onKeyDown),t.addEventListener("keyup",e.onKeyUp),t.addEventListener("blur",e.onBlur)}function h2(t){const e=na.get(t);e&&(t.removeEventListener("keydown",e.onKeyDown),t.removeEventListener("keyup",e.onKeyUp),t.removeEventListener("blur",e.onBlur),na.delete(t))}var p2=Se({phase:"input"},t=>{const e=Ge(t),n=na.get(e.domElement);if(!n)return;he(t,ay,()=>{Sn.reset(t)});const r=n.eventsBuffer.length>0,o=Sn.read(t),s=!ly(o.keysDownTrigger)||!ly(o.keysUpTrigger);if(!r&&!s)return;const i=Sn.write(t);fs(i.keysDownTrigger),fs(i.keysUpTrigger);for(const a of n.eventsBuffer){if(a.type==="blur"){fs(i.keysDown),i.shiftDown=!1,i.altDown=!1,i.modDown=!1;continue}const l=O[a.code];l!==void 0&&(a.type==="keydown"?(m2(i.keysDown,l)||ta(i.keysDownTrigger,l,!0),ta(i.keysDown,l,!0)):a.type==="keyup"&&(ta(i.keysDown,l,!1),ta(i.keysUpTrigger,l,!0)),i.shiftDown=a.shiftKey,i.altDown=a.altKey,i.modDown=a.ctrlKey||a.metaKey)}n.eventsBuffer.length=0});function m2(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 ly(t){for(let e=0;e<t.length;e++)if(t[e]!==0)return!1;return!0}var ra=new WeakMap;function g2(t){if(ra.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"})}};ra.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 y2(t){const e=ra.get(t);e&&(window.removeEventListener("mousemove",e.onMouseMove),t.removeEventListener("wheel",e.onWheel),t.removeEventListener("mouseenter",e.onMouseEnter),t.removeEventListener("mouseleave",e.onMouseLeave),ra.delete(t))}var w2=Se({phase:"input"},t=>{const e=Ge(t),n=ra.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=_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=v2(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 v2(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 oa=new WeakMap;function k2(t){if(oa.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})}};oa.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 b2(t){const e=oa.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),oa.delete(t))}var S2=Se({phase:"input"},t=>{const e=Ge(t),{domElement:n}=e,r=oa.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);Q(t,l,Ct,{pointerId:i.pointerId,position:a,downPosition:a,downFrame:r.frameCount,button:Ct.getButton(i.button),pointerType:Ct.getType(i.pointerType),pressure:i.pressure,obscured:i.target!==n});const c=Ct.write(t,l);Gl(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=Ct.write(t,a);Gl(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=Ct.write(t,a);Gl(c,l,s),it(t,a),r.pointerEntityMap.delete(i.pointerId);break}}r.eventsBuffer.length=0}),sa=new WeakMap;function E2(t){if(sa.has(t))return;const e={needsUpdate:!1,resizeObserver:new ResizeObserver(()=>{e.needsUpdate=!0}),onScroll:()=>{e.needsUpdate=!0}};sa.set(t,e),e.resizeObserver.observe(t),window.addEventListener("scroll",e.onScroll,!0)}function C2(t){const e=sa.get(t);e&&(e.resizeObserver.disconnect(),window.removeEventListener("scroll",e.onScroll,!0),sa.delete(t))}var _2=Se({phase:"input"},t=>{const e=Ge(t),{domElement:n}=e,r=sa.get(n);if(!r||(fi.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}),x2=ie(t=>t.tracking(Nn));function T2(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 M2=Se({phase:"render",priority:-100},t=>{const e=x2.changed(t),n=fi.read(t);if(e.length===0&&n.number!==1)return;const{cursorKind:r,rotation:o}=Nn.getEffective(t);if(!r){document.body.style.cursor="default";return}const{editor:s}=Ge(t),i=T2(s.cursors,r,o);document.body.style.cursor=i});function A2(t){const{editor:e}=Ge(t);return e.blockDefs}function Kn(t,e){return A2(t)[e]??Vd.parse({tag:e})}function cy(t,e){return Kn(t,e).editOptions.canEdit}function ia(t,e){const n=A.read(t,e);return n.resizeMode!==ot.Default?n.resizeMode:Kn(t,n.tag).resizeMode}function uy(t,e,n){if(R(t,e,Te)){const r=Te.getExtremaWorld(t,e);ne.setFromPoints(n,r)}else{const r=A.getCorners(t,e);ne.setFromPoints(n,r)}}function Yd(t,e){if(!R(t,e,Rt))return!1;const{sessionId:n}=Ge(t),r=Rt.read(t,e);return r.sessionId!==""&&r.sessionId!==n}var dy=ie(t=>t.with(A,Ve));function fy(t,e,n){const r=[],o=dy.current(t);for(const s of o)if(Ve.containsPoint(t,s,e)){if(R(t,s,Te)){if(!Te.containsPointWorld(t,s,e))continue}else if(!A.containsPoint(t,s,e))continue;r.push(s)}return N2(t,r)}function I2(t,e,n){const r=[],o=n??dy.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,Te)?Te.intersectsAabbWorld(t,s,e)&&r.push(s):A.intersectsAabb(t,s,e)&&r.push(s)}}return r}function N2(t,e){return e.sort((n,r)=>{const o=A.read(t,n),s=A.read(t,r),i=Kn(t,o.tag).stratum,a=Kn(t,s.tag).stratum,l=Fd[i],c=Fd[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 pi=[1,0,0,1,0,0];function B2(t,e,n){const r=[],o=pt.bounds(e);for(const s of n){const i=Ve.read(t,s);ne.intersects(o,i.value)&&(R(t,s,Te)?P2(t,s,e)&&r.push(s):pt.intersectsAabb(e,i.value)&&r.push(s))}return r}function P2(t,e,n){const r=Te.read(t,e);A.getUvToWorldMatrix(t,e,pi);for(let o=0;o<r.arcCount;o++){const s=Te.getArcAt(t,e,o),i=[s[0],s[1]];ze.transformPoint(pi,i);const a=[s[2],s[3]];ze.transformPoint(pi,a);const l=[s[4],s[5]];ze.transformPoint(pi,l);const c=s[6],u=Re.create(i[0],i[1],a[0],a[1],l[0],l[1],c),f=pt.pointA(n),h=pt.pointB(n);if(Re.intersectsCapsule(u,f,h,pt.radius(n)))return!0}for(let o=0;o<r.capsuleCount;o++){const s=Te.getCapsuleAt(t,e,o),i=[s[0],s[1]];ze.transformPoint(pi,i);const a=[s[2],s[3]];ze.transformPoint(pi,a);const l=s[4],c=pt.create(i[0],i[1],a[0],a[1],l);if(pt.intersectsCapsule(n,c))return!0}return!1}var O2=ie(t=>t.with(Eo));function D2(t){const e=Ge(t).sessionId;for(const n of O2.current(t))if(Eo.read(t,n).sessionId===e)return n;return null}var hy=ie(t=>t.tracking(Ct)),R2=Se({phase:"render",priority:-100},t=>{if(Bn.didMove(t)){const i=Bn.read(t);py(t,i.position);return}if(hy.changed(t).length===0)return;const n=hy.current(t);let r=null,o=Number.MAX_SAFE_INTEGER;for(const i of n){const a=Ct.read(t,i);a.pointerId<o&&(o=a.pointerId,r=i)}const s=Ct.read(t,r);py(t,s.position)});function py(t,e){const n=D2(t);if(n===null)return;const r=Eo.write(t,n);r.position=we.toWorld(t,e)}var my=ie(t=>t.tracking(A)),gy=ie(t=>t.tracking(Te)),yy=ie(t=>t.with(Rt).tracking(Rt)),z2=ie(t=>t.with(bo)),$2=ie(t=>t.with(Ct));function wy(t){for(const e of z2.current(t))R(t,e,bo)&&mn(t,e,bo)}function L2(t,e){for(const n of e)return Yd(t,n)?void 0:n}function V2(t,e){const r=ut.read(t).leftMouseTool==="select";if(wy(t),!r)return;const o=L2(t,e);o!==void 0&&Q(t,o,bo,{})}function F2(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 aa=new Set,la=new Set,j2=Se({phase:"capture",priority:100},t=>{aa.clear();for(const m of my.added(t))aa.add(m);for(const m of gy.added(t))aa.add(m);la.clear();for(const m of my.changed(t))la.add(m);for(const m of gy.changed(t))la.add(m);for(const m of aa){R(t,m,Ve)||Q(t,m,Ve,{value:[0,0,0,0]});const g=Ve.write(t,m);uy(t,m,g.value)}for(const m of la){const g=Ve.write(t,m);uy(t,m,g.value)}const e=Bn.didMove(t),n=Bn.didLeave(t),r=Bn.didScroll(t),o=aa.size>0||la.size>0,s=yy.added(t),i=yy.removed(t),a=s.length>0||i.length>0;if(!e&&!n&&!r&&!o&&!a)return;if(n){ds.clear(t),wy(t);return}const l=Bn.getPosition(t),c=we.toWorld(t,l),u=fy(t,c),f=ds.getAll(t),h=!F2(u,f);h&&ds.setAll(t,u),!($2.current(t).length>0)&&(h||a)&&V2(t,u)}),U2=ie(t=>t.with(me,A)),W2=Se({phase:"input",priority:100},t=>{const e=U2.added(t);for(const n of e){const r=A.read(t,n);if(r.rank===""){const o=A.write(t,n);o.rank=Zn.genNext(t)}else Zn.add(t,r.rank)}}),H2=ie(t=>t.tracking(we)),Z2=ie(t=>t.with(me,A,Ve)),K2=ie(t=>t.with(me,A,Ve)),Y2=[0,0,0,0],q2=Se({phase:"render",priority:90},t=>{if(H2.changed(t).length===0&&K2.addedOrRemoved(t).length===0)return;const e=we.read(t),n=we.getAabb(t,Y2);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 Z2.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}),vy=ie(t=>t.with(A).tracking(So)),Xl=[0,0],Ql=[0,0],G2=Se({phase:"render",priority:100},t=>{const e=we.read(t),n=Wd.read(t);if(!Dt.approxEqual(e.zoom,n.lastZoom)){for(const o of vy.current(t))ky(t,o,e.zoom);Wd.write(t).lastZoom=e.zoom}for(const o of vy.addedOrChanged(t))ky(t,o,e.zoom)});function ky(t,e,n){const r=A.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];Xl[0]=o.startSize[0]*i,Xl[1]=o.startSize[1]*a,$.copy(Ql,o.startSize),$.sub(Ql,Xl),$.multiply(Ql,o.anchor),$.copy(r.position,o.startPosition),$.add(r.position,Ql),$.copy(r.size,Xl)}var J2={name:UI,singletons:Object.values(sy).filter(t=>t instanceof kt),components:Object.values(Jg).filter(t=>t instanceof Gt),blockDefs:[{tag:"sticky-note",components:[In,yt,us],editOptions:{canEdit:!0}},{tag:"text",components:[yt],resizeMode:ot.Text,editOptions:{canEdit:!0,removeWhenTextEmpty:!0}},{tag:"image",components:[ea,cs],resizeMode:ot.Scale},{tag:"shape",components:[Hn,yt,us],resizeMode:ot.Free,editOptions:{canEdit:!0}}],systems:[d2,W2,p2,w2,_2,S2,j2,u2,G2,q2,M2,R2],setup(t){const{domElement:e}=Ge(t);f2(e),g2(e),E2(e),k2(e)},teardown(t){const{domElement:e}=Ge(t);h2(e),y2(e),C2(e),b2(e)}},X2=Un({name:St(),displayName:St(),url:St(),previewImage:St().optional(),selectable:cn().default(!0),weights:Mn(Xt()).default([400,700]),italics:cn().default(!0)}),Q2=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 eN(t){return typeof t=="function"?t({}):t}function tN(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 by=["input","capture","update","render"];function nN(t){const e=new Map;for(const r of by)e.set(r,[]);for(const r of t)e.get(r.phase).push(r);const n=[];for(const r of by){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 rN=class{constructor(e,n){this.cursors={},this.blockDefs={},this.fonts=[],this.components=[],this.singletons=[];const r=MI.parse(n??{}),{plugins:o,maxEntities:s}=r,i=Xg.parse(r.user??{});this.userData=i,this.gridOptions=xI.parse(r.grid??{}),this.controlsOptions=TI.parse(r.controls??{});const a=o.map(eN),l=tN([J2,...a]),c=[hi,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=Vd.parse(k);f[E.tag]=E}for(const k of l)if(k.blockDefs)for(const E of k.blockDefs){const _=Vd.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 Q2;const p=[...r.fonts];if(!r.omitPluginFonts)for(const k of l)k.fonts&&p.push(...k.fonts);this.fonts=p.map(k=>X2.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 WE(c,{maxEntities:s,resources:b});const S=[];for(const k of l)k.systems&&S.push(...k.systems);S.push(...r.systems),this.systemBatches=nN(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),Ht.copy(this.ctx,this.gridOptions),ut.copy(this.ctx,this.controlsOptions),this.nextTick(e=>{const n=Bt(e);Q(e,n,me,{id:crypto.randomUUID()}),Q(e,n,Eo,{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,l2(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 oN(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]=EI(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 sN=class extends kt{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=oN(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 Co(t,e){return new sN(t,e)}function iN(t){const e=fi.read(t);return{type:"frame",ctx:t,delta:e.delta,frameNumber:e.number,time:e.time}}function aN(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 Sy(t){const e=[],n=Bn.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 lN=3,cN=30,ec=ie(t=>t.tracking(Ct)),Ey=new Map;function uN(t){const e=t.readerId;let n=Ey.get(e);return n||(n={prevPositions:new Map,prevModifiers:{shiftDown:!1,altDown:!1,modDown:!1},prevCamera:{left:0,top:0,zoom:1}},Ey.set(e,n)),n}function jr(t,e,n={}){if(e.length===0)return[];const{includeFrameEvent:r=!1,clickMoveThreshold:o=lN,clickFrameThreshold:s=cN}=n,i=uN(t),a=fi.read(t).number,l=[],c=Sn.read(t),u={shiftDown:c.shiftDown,altDown:c.altDown,modDown:c.modDown},f=we.read(t),h=B=>{const L=Ct.read(t,B);return e.includes(L.button)},p=(B,L)=>{const Z=Ct.read(t,L),M=[Z.position[0],Z.position[1]],F=we.toWorld(t,M),q=fy(t,F);return{type:B,ctx:t,screenPosition:M,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:L,intersects:q}},m=ec.added(t),g=ec.removed(t),y=ec.changed(t),w=ec.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 B=k[0],L=Ct.read(t,B);L.obscured||(l.push(p("pointerDown",B)),i.prevPositions.set(B,[L.position[0],L.position[1]]))}if(b.length>0&&k.length===0){const B=b[0],L=Ct.read(t,B);l.push(p("pointerUp",B));const Z=i.prevPositions.get(B);if(Z){const M=[L.position[0],L.position[1]],F=$.distance(Z,M),q=a-L.downFrame;F<o&&q<s&&l.push(p("click",B)),i.prevPositions.delete(B)}}const T=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||T||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 qd;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(qd||(qd={}));const Y=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 Y.undefined;case"string":return Y.string;case"number":return isNaN(t)?Y.nan:Y.number;case"boolean":return Y.boolean;case"function":return Y.function;case"bigint":return Y.bigint;case"symbol":return Y.symbol;case"object":return Array.isArray(t)?Y.array:t===null?Y.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Y.promise:typeof Map<"u"&&t instanceof Map?Y.map:typeof Set<"u"&&t instanceof Set?Y.set:typeof Date<"u"&&t instanceof Date?Y.date:Y.object;default:return Y.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"]),dN=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 mi=(t,e)=>{let n;switch(t.code){case z.invalid_type:t.received===Y.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 Cy=mi;function fN(t){Cy=t}function tc(){return Cy}const nc=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}},hN=[];function H(t,e){const n=tc(),r=nc({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===mi?void 0:mi].filter(o=>!!o)});t.common.issues.push(r)}class Zt{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 Zt.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"}),gi=t=>({status:"dirty",value:t}),Qt=t=>({status:"valid",value:t}),Gd=t=>t.status==="aborted",Jd=t=>t.status==="dirty",hs=t=>t.status==="valid",ca=t=>typeof Promise<"u"&&t instanceof Promise;function rc(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 _y(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 ua,da;class yr{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 xy=(t,e)=>{if(hs(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 Zt,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(ca(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 xy(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 hs(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=>hs(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(ca(o)?o:Promise.resolve(o));return xy(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 Gn({schema:this,typeName:ce.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 vr.create(this,this._def)}nullable(){return Mo.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return qn.create(this)}promise(){return ki.create(this,this._def)}or(e){return ma.create([this,e],this._def)}and(e){return ga.create(this,e,this._def)}transform(e){return new Gn({...ge(this._def),schema:this,typeName:ce.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new ba({...ge(this._def),innerType:this,defaultValue:n,typeName:ce.ZodDefault})}brand(){return new ef({typeName:ce.ZodBranded,type:this,...ge(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new Sa({...ge(this._def),innerType:this,catchValue:n,typeName:ce.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Ea.create(this,e)}readonly(){return Ca.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const pN=/^c[^\s-]{8,}$/i,mN=/^[0-9a-z]+$/,gN=/^[0-9A-HJKMNP-TV-Z]{26}$/i,yN=/^[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,wN=/^[a-z0-9_-]{21}$/i,vN=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,kN=/^[-+]?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)?)??$/,bN=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,SN="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Xd;const EN=/^(?:(?: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])$/,CN=/^(?:(?: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])$/,_N=/^(([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]))$/,xN=/^(([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])$/,TN=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,MN=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ty="((\\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])))",AN=new RegExp(`^${Ty}$`);function My(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 IN(t){return new RegExp(`^${My(t)}$`)}function Ay(t){let e=`${Ty}T${My(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 NN(t,e){return!!((e==="v4"||!e)&&EN.test(t)||(e==="v6"||!e)&&_N.test(t))}function BN(t,e){if(!vN.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 PN(t,e){return!!((e==="v4"||!e)&&CN.test(t)||(e==="v6"||!e)&&xN.test(t))}class Yn extends ve{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Y.string){const s=this._getOrReturnCtx(e);return H(s,{code:z.invalid_type,expected:Y.string,received:s.parsedType}),de}const r=new Zt;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")bN.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")Xd||(Xd=new RegExp(SN,"u")),Xd.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")yN.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")wN.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")pN.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")mN.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")gN.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"?Ay(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"?AN.test(e.data)||(o=this._getOrReturnCtx(e,o),H(o,{code:z.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?IN(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"?kN.test(e.data)||(o=this._getOrReturnCtx(e,o),H(o,{validation:"duration",code:z.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?NN(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"?BN(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"?PN(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"?TN.test(e.data)||(o=this._getOrReturnCtx(e,o),H(o,{validation:"base64",code:z.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?MN.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 Yn({...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 Yn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Yn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Yn({...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}}Yn.create=t=>{var e;return new Yn({checks:[],typeName:ce.ZodString,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...ge(t)})};function ON(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 _o 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)!==Y.number){const s=this._getOrReturnCtx(e);return H(s,{code:z.invalid_type,expected:Y.number,received:s.parsedType}),de}let r;const o=new Zt;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"?ON(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 _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]})}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)}}_o.create=t=>new _o({checks:[],typeName:ce.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...ge(t)});class xo 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)!==Y.bigint)return this._getInvalidInput(e);let r;const o=new Zt;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:Y.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 xo({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:te.toString(o)}]})}_addCheck(e){return new xo({...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}}xo.create=t=>{var e;return new xo({checks:[],typeName:ce.ZodBigInt,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...ge(t)})};class fa extends ve{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Y.boolean){const r=this._getOrReturnCtx(e);return H(r,{code:z.invalid_type,expected:Y.boolean,received:r.parsedType}),de}return Qt(e.data)}}fa.create=t=>new fa({typeName:ce.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...ge(t)});class ps extends ve{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Y.date){const s=this._getOrReturnCtx(e);return H(s,{code:z.invalid_type,expected:Y.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 Zt;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 ps({...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}}ps.create=t=>new ps({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:ce.ZodDate,...ge(t)});class oc extends ve{_parse(e){if(this._getType(e)!==Y.symbol){const r=this._getOrReturnCtx(e);return H(r,{code:z.invalid_type,expected:Y.symbol,received:r.parsedType}),de}return Qt(e.data)}}oc.create=t=>new oc({typeName:ce.ZodSymbol,...ge(t)});class ha extends ve{_parse(e){if(this._getType(e)!==Y.undefined){const r=this._getOrReturnCtx(e);return H(r,{code:z.invalid_type,expected:Y.undefined,received:r.parsedType}),de}return Qt(e.data)}}ha.create=t=>new ha({typeName:ce.ZodUndefined,...ge(t)});class pa extends ve{_parse(e){if(this._getType(e)!==Y.null){const r=this._getOrReturnCtx(e);return H(r,{code:z.invalid_type,expected:Y.null,received:r.parsedType}),de}return Qt(e.data)}}pa.create=t=>new pa({typeName:ce.ZodNull,...ge(t)});class yi extends ve{constructor(){super(...arguments),this._any=!0}_parse(e){return Qt(e.data)}}yi.create=t=>new yi({typeName:ce.ZodAny,...ge(t)});class ms extends ve{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Qt(e.data)}}ms.create=t=>new ms({typeName:ce.ZodUnknown,...ge(t)});class Wr extends ve{_parse(e){const n=this._getOrReturnCtx(e);return H(n,{code:z.invalid_type,expected:Y.never,received:n.parsedType}),de}}Wr.create=t=>new Wr({typeName:ce.ZodNever,...ge(t)});class sc extends ve{_parse(e){if(this._getType(e)!==Y.undefined){const r=this._getOrReturnCtx(e);return H(r,{code:z.invalid_type,expected:Y.void,received:r.parsedType}),de}return Qt(e.data)}}sc.create=t=>new sc({typeName:ce.ZodVoid,...ge(t)});class qn extends ve{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==Y.array)return H(n,{code:z.invalid_type,expected:Y.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 yr(n,i,n.path,a)))).then(i=>Zt.mergeArray(r,i));const s=[...n.data].map((i,a)=>o.type._parseSync(new yr(n,i,n.path,a)));return Zt.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new qn({...this._def,minLength:{value:e,message:te.toString(n)}})}max(e,n){return new qn({...this._def,maxLength:{value:e,message:te.toString(n)}})}length(e,n){return new qn({...this._def,exactLength:{value:e,message:te.toString(n)}})}nonempty(e){return this.min(1,e)}}qn.create=(t,e)=>new qn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ce.ZodArray,...ge(e)});function wi(t){if(t instanceof tt){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=vr.create(wi(r))}return new tt({...t._def,shape:()=>e})}else return t instanceof qn?new qn({...t._def,type:wi(t.element)}):t instanceof vr?vr.create(wi(t.unwrap())):t instanceof Mo?Mo.create(wi(t.unwrap())):t instanceof wr?wr.create(t.items.map(e=>wi(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)!==Y.object){const c=this._getOrReturnCtx(e);return H(c,{code:z.invalid_type,expected:Y.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 yr(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 yr(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=>Zt.mergeObjectSync(r,c)):Zt.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:ce.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 wi(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 vr;)s=s._def.innerType;n[r]=s}}),new tt({...this._def,shape:()=>n})}keyof(){return Iy(Ee.objectKeys(this.shape))}}tt.create=(t,e)=>new tt({shape:()=>t,unknownKeys:"strip",catchall:Wr.create(),typeName:ce.ZodObject,...ge(e)}),tt.strictCreate=(t,e)=>new tt({shape:()=>t,unknownKeys:"strict",catchall:Wr.create(),typeName:ce.ZodObject,...ge(e)}),tt.lazycreate=(t,e)=>new tt({shape:t,unknownKeys:"strip",catchall:Wr.create(),typeName:ce.ZodObject,...ge(e)});class ma 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}}ma.create=(t,e)=>new ma({options:t,typeName:ce.ZodUnion,...ge(e)});const Hr=t=>t instanceof wa?Hr(t.schema):t instanceof Gn?Hr(t.innerType()):t instanceof va?[t.value]:t instanceof To?t.options:t instanceof ka?Ee.objectValues(t.enum):t instanceof ba?Hr(t._def.innerType):t instanceof ha?[void 0]:t instanceof pa?[null]:t instanceof vr?[void 0,...Hr(t.unwrap())]:t instanceof Mo?[null,...Hr(t.unwrap())]:t instanceof ef||t instanceof Ca?Hr(t.unwrap()):t instanceof Sa?Hr(t._def.innerType):[];class ic extends ve{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==Y.object)return H(n,{code:z.invalid_type,expected:Y.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 ic({typeName:ce.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...ge(r)})}}function Qd(t,e){const n=Ur(t),r=Ur(e);if(t===e)return{valid:!0,data:t};if(n===Y.object&&r===Y.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=Qd(t[a],e[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}else if(n===Y.array&&r===Y.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=Qd(i,a);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===Y.date&&r===Y.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class ga extends ve{_parse(e){const{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(Gd(s)||Gd(i))return de;const a=Qd(s.value,i.value);return a.valid?((Jd(s)||Jd(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}))}}ga.create=(t,e,n)=>new ga({left:t,right:e,typeName:ce.ZodIntersection,...ge(n)});class wr extends ve{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Y.array)return H(r,{code:z.invalid_type,expected:Y.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 yr(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>Zt.mergeArray(n,i)):Zt.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new wr({...this._def,rest:e})}}wr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new wr({items:t,typeName:ce.ZodTuple,rest:null,...ge(e)})};class ya 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!==Y.object)return H(r,{code:z.invalid_type,expected:Y.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 yr(r,a,r.path,a)),value:i._parse(new yr(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?Zt.mergeObjectAsync(n,o):Zt.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof ve?new ya({keyType:e,valueType:n,typeName:ce.ZodRecord,...ge(r)}):new ya({keyType:Yn.create(),valueType:e,typeName:ce.ZodRecord,...ge(n)})}}class ac 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!==Y.map)return H(r,{code:z.invalid_type,expected:Y.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 yr(r,a,r.path,[c,"key"])),value:s._parse(new yr(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}}}}ac.create=(t,e,n)=>new ac({valueType:e,keyType:t,typeName:ce.ZodMap,...ge(n)});class gs extends ve{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Y.set)return H(r,{code:z.invalid_type,expected:Y.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 yr(r,l,r.path,c)));return r.common.async?Promise.all(a).then(l=>i(l)):i(a)}min(e,n){return new gs({...this._def,minSize:{value:e,message:te.toString(n)}})}max(e,n){return new gs({...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)}}gs.create=(t,e)=>new gs({valueType:t,minSize:null,maxSize:null,typeName:ce.ZodSet,...ge(e)});class vi extends ve{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==Y.function)return H(n,{code:z.invalid_type,expected:Y.function,received:n.parsedType}),de;function r(a,l){return nc({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,tc(),mi].filter(c=>!!c),issueData:{code:z.invalid_arguments,argumentsError:l}})}function o(a,l){return nc({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,tc(),mi].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 ki){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 vi({...this._def,args:wr.create(e).rest(ms.create())})}returns(e){return new vi({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new vi({args:e||wr.create([]).rest(ms.create()),returns:n||ms.create(),typeName:ce.ZodFunction,...ge(r)})}}class wa 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})}}wa.create=(t,e)=>new wa({getter:t,typeName:ce.ZodLazy,...ge(e)});class va 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}}va.create=(t,e)=>new va({value:t,typeName:ce.ZodLiteral,...ge(e)});function Iy(t,e){return new To({values:t,typeName:ce.ZodEnum,...ge(e)})}class To extends ve{constructor(){super(...arguments),ua.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(rc(this,ua)||_y(this,ua,new Set(this._def.values)),!rc(this,ua).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 To.create(e,{...this._def,...n})}exclude(e,n=this._def){return To.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}}ua=new WeakMap,To.create=Iy;class ka extends ve{constructor(){super(...arguments),da.set(this,void 0)}_parse(e){const n=Ee.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==Y.string&&r.parsedType!==Y.number){const o=Ee.objectValues(n);return H(r,{expected:Ee.joinValues(o),received:r.parsedType,code:z.invalid_type}),de}if(rc(this,da)||_y(this,da,new Set(Ee.getValidEnumValues(this._def.values))),!rc(this,da).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}}da=new WeakMap,ka.create=(t,e)=>new ka({values:t,typeName:ce.ZodNativeEnum,...ge(e)});class ki extends ve{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==Y.promise&&n.common.async===!1)return H(n,{code:z.invalid_type,expected:Y.promise,received:n.parsedType}),de;const r=n.parsedType===Y.promise?n.data:Promise.resolve(n.data);return Qt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}ki.create=(t,e)=>new ki({type:t,typeName:ce.ZodPromise,...ge(e)});class Gn extends ve{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ce.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"?gi(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"?gi(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(!hs(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=>hs(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):i);Ee.assertNever(o)}}Gn.create=(t,e,n)=>new Gn({schema:t,typeName:ce.ZodEffects,effect:e,...ge(n)}),Gn.createWithPreprocess=(t,e,n)=>new Gn({schema:e,effect:{type:"preprocess",transform:t},typeName:ce.ZodEffects,...ge(n)});class vr extends ve{_parse(e){return this._getType(e)===Y.undefined?Qt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}vr.create=(t,e)=>new vr({innerType:t,typeName:ce.ZodOptional,...ge(e)});class Mo extends ve{_parse(e){return this._getType(e)===Y.null?Qt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Mo.create=(t,e)=>new Mo({innerType:t,typeName:ce.ZodNullable,...ge(e)});class ba extends ve{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===Y.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}ba.create=(t,e)=>new ba({innerType:t,typeName:ce.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ge(e)});class Sa 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 ca(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}}Sa.create=(t,e)=>new Sa({innerType:t,typeName:ce.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ge(e)});class lc extends ve{_parse(e){if(this._getType(e)!==Y.nan){const r=this._getOrReturnCtx(e);return H(r,{code:z.invalid_type,expected:Y.nan,received:r.parsedType}),de}return{status:"valid",value:e.data}}}lc.create=t=>new lc({typeName:ce.ZodNaN,...ge(t)});const DN=Symbol("zod_brand");class ef 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 Ea 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(),gi(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 Ea({in:e,out:n,typeName:ce.ZodPipeline})}}class Ca extends ve{_parse(e){const n=this._def.innerType._parse(e),r=o=>(hs(o)&&(o.value=Object.freeze(o.value)),o);return ca(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}}Ca.create=(t,e)=>new Ca({innerType:t,typeName:ce.ZodReadonly,...ge(e)});function Ny(t,e){const n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function By(t,e={},n){return t?yi.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=Ny(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=Ny(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})}}):yi.create()}const RN={object:tt.lazycreate};var ce;(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"})(ce||(ce={}));const zN=(t,e={message:`Input not instance of ${t.name}`})=>By(n=>n instanceof t,e),Py=Yn.create,Oy=_o.create,$N=lc.create,LN=xo.create,Dy=fa.create,VN=ps.create,FN=oc.create,jN=ha.create,UN=pa.create,WN=yi.create,HN=ms.create,ZN=Wr.create,KN=sc.create,YN=qn.create,qN=tt.create,GN=tt.strictCreate,JN=ma.create,XN=ic.create,QN=ga.create,eB=wr.create,tB=ya.create,nB=ac.create,rB=gs.create,oB=vi.create,sB=wa.create,iB=va.create,aB=To.create,lB=ka.create,cB=ki.create,Ry=Gn.create,uB=vr.create,dB=Mo.create,fB=Gn.createWithPreprocess,hB=Ea.create;var Zr=Object.freeze({__proto__:null,defaultErrorMap:mi,setErrorMap:fN,getErrorMap:tc,makeIssue:nc,EMPTY_PATH:hN,addIssueToContext:H,ParseStatus:Zt,INVALID:de,DIRTY:gi,OK:Qt,isAborted:Gd,isDirty:Jd,isValid:hs,isAsync:ca,get util(){return Ee},get objectUtil(){return qd},ZodParsedType:Y,getParsedType:Ur,ZodType:ve,datetimeRegex:Ay,ZodString:Yn,ZodNumber:_o,ZodBigInt:xo,ZodBoolean:fa,ZodDate:ps,ZodSymbol:oc,ZodUndefined:ha,ZodNull:pa,ZodAny:yi,ZodUnknown:ms,ZodNever:Wr,ZodVoid:sc,ZodArray:qn,ZodObject:tt,ZodUnion:ma,ZodDiscriminatedUnion:ic,ZodIntersection:ga,ZodTuple:wr,ZodRecord:ya,ZodMap:ac,ZodSet:gs,ZodFunction:vi,ZodLazy:wa,ZodLiteral:va,ZodEnum:To,ZodNativeEnum:ka,ZodPromise:ki,ZodEffects:Gn,ZodTransformer:Gn,ZodOptional:vr,ZodNullable:Mo,ZodDefault:ba,ZodCatch:Sa,ZodNaN:lc,BRAND:DN,ZodBranded:ef,ZodPipeline:Ea,ZodReadonly:Ca,custom:By,Schema:ve,ZodSchema:ve,late:RN,get ZodFirstPartyTypeKind(){return ce},coerce:{string:t=>Yn.create({...t,coerce:!0}),number:t=>_o.create({...t,coerce:!0}),boolean:t=>fa.create({...t,coerce:!0}),bigint:t=>xo.create({...t,coerce:!0}),date:t=>ps.create({...t,coerce:!0})},any:WN,array:YN,bigint:LN,boolean:Dy,date:VN,discriminatedUnion:XN,effect:Ry,enum:aB,function:oB,instanceof:zN,intersection:QN,lazy:sB,literal:iB,map:nB,nan:$N,nativeEnum:lB,never:ZN,null:UN,nullable:dB,number:Oy,object:qN,oboolean:()=>Dy().optional(),onumber:()=>Oy().optional(),optional:uB,ostring:()=>Py().optional(),pipeline:hB,preprocess:fB,promise:cB,record:tB,set:rB,strictObject:GN,string:Py,symbol:FN,transformer:Ry,tuple:eB,undefined:jN,union:JN,unknown:HN,void:KN,NEVER:de,ZodIssueCode:z,quotelessJson:dN,ZodError:En}),pB=Object.defineProperty,bi=(t,e)=>{for(var n in e)pB(t,n,{get:e[n],enumerable:!0})},_a=pe("drag-block"),mB=pe("remove-block"),tf=pe("remove-selected"),zy=pe("bring-forward-selected"),$y=pe("send-backward-selected"),Ly=pe("clone-entities"),nf=pe("unclone-entities"),cc=pe("set-cursor"),Vy=pe("cut"),Fy=pe("copy"),jy=pe("paste"),rf=pe("select-block"),gB=pe("deselect-block"),Uy=pe("toggle-select"),Si=pe("deselect-all"),Wy=pe("select-all"),Hy=pe("add-selection-box"),Zy=pe("update-selection-box"),Ky=pe("remove-selection-box"),Yy=pe("add-held"),qy=pe("remove-held"),Gy=pe("add-transform-box"),of=pe("update-transform-box"),Jy=pe("hide-transform-box"),Xy=pe("show-transform-box"),sf=pe("remove-transform-box"),Qy=pe("start-transform-box-edit"),yB=pe("end-transform-box-edit"),e0={};bi(e0,{DragStart:()=>wt,EditAfterPlacing:()=>xa,Selected:()=>xt,SelectionBox:()=>uc,TransformBox:()=>en,TransformHandle:()=>Ke});var wt=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)}),xa=Qe({name:"editAfterPlacing"},{}),xt=Qe({name:"selected"},{}),uc=Qe({name:"selectionBox"},{}),en=Qe({name:"transformBox"},{}),wB=`
1
+ (function(P,at){typeof exports=="object"&&typeof module<"u"?at(exports,require("@woven-ecs/canvas-store"),require("@woven-canvas/core"),require("@woven-canvas/math"),require("vue")):typeof define=="function"&&define.amd?define(["exports","@woven-ecs/canvas-store","@woven-canvas/core","@woven-canvas/math","vue"],at):(P=typeof globalThis<"u"?globalThis:P||self,at(P.Vue={},P.canvasStore,P.core,P.math,P.Vue))})(this,function(P,at,h,E,d){"use strict";var le;(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})(le||(le={}));var Wa;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Wa||(Wa={}));const F=le.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),en=t=>{switch(typeof t){case"undefined":return F.undefined;case"string":return F.string;case"number":return isNaN(t)?F.nan:F.number;case"boolean":return F.boolean;case"function":return F.function;case"bigint":return F.bigint;case"symbol":return F.symbol;case"object":return Array.isArray(t)?F.array:t===null?F.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?F.promise:typeof Map<"u"&&t instanceof Map?F.map:typeof Set<"u"&&t instanceof Set?F.set:typeof Date<"u"&&t instanceof Date?F.date:F.object;default:return F.unknown}},O=le.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"]),Gk=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class lt 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 lt))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,le.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()}}lt.create=t=>new lt(t);const $r=(t,e)=>{let n;switch(t.code){case O.invalid_type:t.received===F.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case O.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,le.jsonStringifyReplacer)}`;break;case O.unrecognized_keys:n=`Unrecognized key(s) in object: ${le.joinValues(t.keys,", ")}`;break;case O.invalid_union:n="Invalid input";break;case O.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${le.joinValues(t.options)}`;break;case O.invalid_enum_value:n=`Invalid enum value. Expected ${le.joinValues(t.options)}, received '${t.received}'`;break;case O.invalid_arguments:n="Invalid function arguments";break;case O.invalid_return_type:n="Invalid function return type";break;case O.invalid_date:n="Invalid date";break;case O.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}"`:le.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case O.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 O.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 O.custom:n="Invalid input";break;case O.invalid_intersection_types:n="Intersection results could not be merged";break;case O.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case O.not_finite:n="Number must be finite";break;default:n=e.defaultError,le.assertNever(t)}return{message:n}};let uu=$r;function Yk(t){uu=t}function Vs(){return uu}const Ls=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}},Xk=[];function z(t,e){const n=Vs(),r=Ls({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===$r?void 0:$r].filter(o=>!!o)});t.common.issues.push(r)}class Ue{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 ee;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 Ue.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 ee;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 ee=Object.freeze({status:"aborted"}),Vr=t=>({status:"dirty",value:t}),Ge=t=>({status:"valid",value:t}),Za=t=>t.status==="aborted",Ua=t=>t.status==="dirty",Yn=t=>t.status==="valid",_o=t=>typeof Promise<"u"&&t instanceof Promise;function Fs(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 fu(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 W;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(W||(W={}));var Eo,To;class Vt{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 hu=(t,e)=>{if(Yn(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 lt(t.common.issues);return this._error=n,this._error}}};function ne(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}}let oe=class{get description(){return this._def.description}_getType(e){return en(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:en(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ue,ctx:{common:e.parent.common,data:e.data,parsedType:en(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(_o(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:en(e)},s=this._parseSync({data:e,path:o.path,parent:o});return hu(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:en(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:o});return Yn(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=>Yn(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:en(e)},o=this._parse({data:e,path:r.path,parent:r}),s=await(_o(o)?o:Promise.resolve(o));return hu(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:O.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 xt({schema:this,typeName:Q.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 Ft.create(this,this._def)}nullable(){return wn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return er.create(this)}promise(){return Hr.create(this,this._def)}or(e){return Oo.create([this,e],this._def)}and(e){return Io.create(this,e,this._def)}transform(e){return new xt({...ne(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new Vo({...ne(this._def),innerType:this,defaultValue:n,typeName:Q.ZodDefault})}brand(){return new qa({typeName:Q.ZodBranded,type:this,...ne(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new Lo({...ne(this._def),innerType:this,catchValue:n,typeName:Q.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Fo.create(this,e)}readonly(){return jo.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Qk=/^c[^\s-]{8,}$/i,ew=/^[0-9a-z]+$/,tw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,nw=/^[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,rw=/^[a-z0-9_-]{21}$/i,ow=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,sw=/^[-+]?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)?)??$/,iw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ka;const lw=/^(?:(?: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])$/,cw=/^(?:(?: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])$/,dw=/^(([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]))$/,uw=/^(([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])$/,fw=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,hw=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,pu="((\\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])))",pw=new RegExp(`^${pu}$`);function mu(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 mw(t){return new RegExp(`^${mu(t)}$`)}function gu(t){let e=`${pu}T${mu(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 gw(t,e){return!!((e==="v4"||!e)&&lw.test(t)||(e==="v6"||!e)&&dw.test(t))}function yw(t,e){if(!ow.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 kw(t,e){return!!((e==="v4"||!e)&&cw.test(t)||(e==="v6"||!e)&&uw.test(t))}class Ct extends oe{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==F.string){const s=this._getOrReturnCtx(e);return z(s,{code:O.invalid_type,expected:F.string,received:s.parsedType}),ee}const r=new Ue;let o;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),z(o,{code:O.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),z(o,{code:O.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?z(o,{code:O.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&z(o,{code:O.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")iw.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"email",code:O.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Ka||(Ka=new RegExp(aw,"u")),Ka.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"emoji",code:O.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")nw.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"uuid",code:O.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")rw.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"nanoid",code:O.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Qk.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"cuid",code:O.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")ew.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"cuid2",code:O.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")tw.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"ulid",code:O.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),z(o,{validation:"url",code:O.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),z(o,{validation:"regex",code:O.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),z(o,{code:O.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),z(o,{code:O.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),z(o,{code:O.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?gu(s).test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{code:O.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?pw.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{code:O.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?mw(s).test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{code:O.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?sw.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"duration",code:O.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?gw(e.data,s.version)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"ip",code:O.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?yw(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"jwt",code:O.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?kw(e.data,s.version)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"cidr",code:O.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?fw.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"base64",code:O.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?hw.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"base64url",code:O.invalid_string,message:s.message}),r.dirty()):le.assertNever(s);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:O.invalid_string,...W.errToObj(r)})}_addCheck(e){return new Ct({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...W.errToObj(e)})}url(e){return this._addCheck({kind:"url",...W.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...W.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...W.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...W.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...W.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...W.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...W.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...W.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...W.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...W.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...W.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...W.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,...W.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,...W.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...W.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...W.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n==null?void 0:n.position,...W.errToObj(n==null?void 0:n.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...W.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...W.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...W.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...W.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...W.errToObj(n)})}nonempty(e){return this.min(1,W.errToObj(e))}trim(){return new Ct({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ct({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ct({...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}}Ct.create=t=>{var e;return new Ct({checks:[],typeName:Q.ZodString,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...ne(t)})};function ww(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)}let Mo=class au extends oe{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)!==F.number){const s=this._getOrReturnCtx(e);return z(s,{code:O.invalid_type,expected:F.number,received:s.parsedType}),ee}let r;const o=new Ue;for(const s of this._def.checks)s.kind==="int"?le.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),z(r,{code:O.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),z(r,{code:O.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),z(r,{code:O.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?ww(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),z(r,{code:O.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),z(r,{code:O.not_finite,message:s.message}),o.dirty()):le.assertNever(s);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,W.toString(n))}gt(e,n){return this.setLimit("min",e,!1,W.toString(n))}lte(e,n){return this.setLimit("max",e,!0,W.toString(n))}lt(e,n){return this.setLimit("max",e,!1,W.toString(n))}setLimit(e,n,r,o){return new au({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:W.toString(o)}]})}_addCheck(e){return new au({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:W.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:W.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:W.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:W.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:W.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:W.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"&&le.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)}};Mo.create=t=>new Mo({checks:[],typeName:Q.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...ne(t)});class kn extends oe{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)!==F.bigint)return this._getInvalidInput(e);let r;const o=new Ue;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),z(r,{code:O.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),z(r,{code:O.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),z(r,{code:O.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):le.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return z(n,{code:O.invalid_type,expected:F.bigint,received:n.parsedType}),ee}gte(e,n){return this.setLimit("min",e,!0,W.toString(n))}gt(e,n){return this.setLimit("min",e,!1,W.toString(n))}lte(e,n){return this.setLimit("max",e,!0,W.toString(n))}lt(e,n){return this.setLimit("max",e,!1,W.toString(n))}setLimit(e,n,r,o){return new kn({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:W.toString(o)}]})}_addCheck(e){return new kn({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:W.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:W.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}}kn.create=t=>{var e;return new kn({checks:[],typeName:Q.ZodBigInt,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...ne(t)})};class Ao extends oe{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==F.boolean){const r=this._getOrReturnCtx(e);return z(r,{code:O.invalid_type,expected:F.boolean,received:r.parsedType}),ee}return Ge(e.data)}}Ao.create=t=>new Ao({typeName:Q.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...ne(t)});class Xn extends oe{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==F.date){const s=this._getOrReturnCtx(e);return z(s,{code:O.invalid_type,expected:F.date,received:s.parsedType}),ee}if(isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return z(s,{code:O.invalid_date}),ee}const r=new Ue;let o;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),z(o,{code:O.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),z(o,{code:O.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):le.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Xn({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:W.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:W.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}}Xn.create=t=>new Xn({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:Q.ZodDate,...ne(t)});class js extends oe{_parse(e){if(this._getType(e)!==F.symbol){const r=this._getOrReturnCtx(e);return z(r,{code:O.invalid_type,expected:F.symbol,received:r.parsedType}),ee}return Ge(e.data)}}js.create=t=>new js({typeName:Q.ZodSymbol,...ne(t)});class No extends oe{_parse(e){if(this._getType(e)!==F.undefined){const r=this._getOrReturnCtx(e);return z(r,{code:O.invalid_type,expected:F.undefined,received:r.parsedType}),ee}return Ge(e.data)}}No.create=t=>new No({typeName:Q.ZodUndefined,...ne(t)});class Bo extends oe{_parse(e){if(this._getType(e)!==F.null){const r=this._getOrReturnCtx(e);return z(r,{code:O.invalid_type,expected:F.null,received:r.parsedType}),ee}return Ge(e.data)}}Bo.create=t=>new Bo({typeName:Q.ZodNull,...ne(t)});class Lr extends oe{constructor(){super(...arguments),this._any=!0}_parse(e){return Ge(e.data)}}Lr.create=t=>new Lr({typeName:Q.ZodAny,...ne(t)});let Qn=class extends oe{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ge(e.data)}};Qn.create=t=>new Qn({typeName:Q.ZodUnknown,...ne(t)});let tn=class extends oe{_parse(e){const n=this._getOrReturnCtx(e);return z(n,{code:O.invalid_type,expected:F.never,received:n.parsedType}),ee}};tn.create=t=>new tn({typeName:Q.ZodNever,...ne(t)});class Hs extends oe{_parse(e){if(this._getType(e)!==F.undefined){const r=this._getOrReturnCtx(e);return z(r,{code:O.invalid_type,expected:F.void,received:r.parsedType}),ee}return Ge(e.data)}}Hs.create=t=>new Hs({typeName:Q.ZodVoid,...ne(t)});let er=class Ha extends oe{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==F.array)return z(n,{code:O.invalid_type,expected:F.array,received:n.parsedType}),ee;if(o.exactLength!==null){const i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(z(n,{code:i?O.too_big:O.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&&(z(n,{code:O.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&&(z(n,{code:O.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 Vt(n,i,n.path,a)))).then(i=>Ue.mergeArray(r,i));const s=[...n.data].map((i,a)=>o.type._parseSync(new Vt(n,i,n.path,a)));return Ue.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new Ha({...this._def,minLength:{value:e,message:W.toString(n)}})}max(e,n){return new Ha({...this._def,maxLength:{value:e,message:W.toString(n)}})}length(e,n){return new Ha({...this._def,exactLength:{value:e,message:W.toString(n)}})}nonempty(e){return this.min(1,e)}};er.create=(t,e)=>new er({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...ne(e)});function Fr(t){if(t instanceof ft){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=Ft.create(Fr(r))}return new ft({...t._def,shape:()=>e})}else return t instanceof er?new er({...t._def,type:Fr(t.element)}):t instanceof Ft?Ft.create(Fr(t.unwrap())):t instanceof wn?wn.create(Fr(t.unwrap())):t instanceof Lt?Lt.create(t.items.map(e=>Fr(e))):t}let ft=class $t extends oe{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=le.objectKeys(e);return this._cached={shape:e,keys:n}}_parse(e){if(this._getType(e)!==F.object){const c=this._getOrReturnCtx(e);return z(c,{code:O.invalid_type,expected:F.object,received:c.parsedType}),ee}const{status:r,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof tn&&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 Vt(o,f,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof tn){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&&(z(o,{code:O.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 Vt(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,p=await u.value;c.push({key:f,value:p,alwaysSet:u.alwaysSet})}return c}).then(c=>Ue.mergeObjectSync(r,c)):Ue.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return W.errToObj,new $t({...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=W.errToObj(e).message)!==null&&a!==void 0?a:l}:{message:l}}}:{}})}strip(){return new $t({...this._def,unknownKeys:"strip"})}passthrough(){return new $t({...this._def,unknownKeys:"passthrough"})}extend(e){return new $t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new $t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Q.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new $t({...this._def,catchall:e})}pick(e){const n={};return le.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new $t({...this._def,shape:()=>n})}omit(e){const n={};return le.objectKeys(this.shape).forEach(r=>{e[r]||(n[r]=this.shape[r])}),new $t({...this._def,shape:()=>n})}deepPartial(){return Fr(this)}partial(e){const n={};return le.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}),new $t({...this._def,shape:()=>n})}required(e){const n={};return le.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Ft;)s=s._def.innerType;n[r]=s}}),new $t({...this._def,shape:()=>n})}keyof(){return yu(le.objectKeys(this.shape))}};ft.create=(t,e)=>new ft({shape:()=>t,unknownKeys:"strip",catchall:tn.create(),typeName:Q.ZodObject,...ne(e)}),ft.strictCreate=(t,e)=>new ft({shape:()=>t,unknownKeys:"strict",catchall:tn.create(),typeName:Q.ZodObject,...ne(e)}),ft.lazycreate=(t,e)=>new ft({shape:t,unknownKeys:"strip",catchall:tn.create(),typeName:Q.ZodObject,...ne(e)});let Oo=class extends oe{_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 lt(a.ctx.common.issues));return z(n,{code:O.invalid_union,unionErrors:i}),ee}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 lt(l));return z(n,{code:O.invalid_union,unionErrors:a}),ee}}get options(){return this._def.options}};Oo.create=(t,e)=>new Oo({options:t,typeName:Q.ZodUnion,...ne(e)});const nn=t=>t instanceof Ro?nn(t.schema):t instanceof xt?nn(t.innerType()):t instanceof Do?[t.value]:t instanceof zo?t.options:t instanceof $o?le.objectValues(t.enum):t instanceof Vo?nn(t._def.innerType):t instanceof No?[void 0]:t instanceof Bo?[null]:t instanceof Ft?[void 0,...nn(t.unwrap())]:t instanceof wn?[null,...nn(t.unwrap())]:t instanceof qa||t instanceof jo?nn(t.unwrap()):t instanceof Lo?nn(t._def.innerType):[];class Ws extends oe{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==F.object)return z(n,{code:O.invalid_type,expected:F.object,received:n.parsedType}),ee;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}):(z(n,{code:O.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),ee)}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=nn(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 Ws({typeName:Q.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...ne(r)})}}function Ja(t,e){const n=en(t),r=en(e);if(t===e)return{valid:!0,data:t};if(n===F.object&&r===F.object){const o=le.objectKeys(e),s=le.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(const a of s){const l=Ja(t[a],e[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}else if(n===F.array&&r===F.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=Ja(i,a);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===F.date&&r===F.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}let Io=class extends oe{_parse(e){const{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(Za(s)||Za(i))return ee;const a=Ja(s.value,i.value);return a.valid?((Ua(s)||Ua(i))&&n.dirty(),{status:n.value,value:a.data}):(z(r,{code:O.invalid_intersection_types}),ee)};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}))}};Io.create=(t,e,n)=>new Io({left:t,right:e,typeName:Q.ZodIntersection,...ne(n)});class Lt extends oe{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==F.array)return z(r,{code:O.invalid_type,expected:F.array,received:r.parsedType}),ee;if(r.data.length<this._def.items.length)return z(r,{code:O.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ee;!this._def.rest&&r.data.length>this._def.items.length&&(z(r,{code:O.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 Vt(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>Ue.mergeArray(n,i)):Ue.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new Lt({...this._def,rest:e})}}Lt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Lt({items:t,typeName:Q.ZodTuple,rest:null,...ne(e)})};class Po extends oe{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!==F.object)return z(r,{code:O.invalid_type,expected:F.object,received:r.parsedType}),ee;const o=[],s=this._def.keyType,i=this._def.valueType;for(const a in r.data)o.push({key:s._parse(new Vt(r,a,r.path,a)),value:i._parse(new Vt(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?Ue.mergeObjectAsync(n,o):Ue.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof oe?new Po({keyType:e,valueType:n,typeName:Q.ZodRecord,...ne(r)}):new Po({keyType:Ct.create(),valueType:e,typeName:Q.ZodRecord,...ne(n)})}}class Zs extends oe{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!==F.map)return z(r,{code:O.invalid_type,expected:F.map,received:r.parsedType}),ee;const o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,l],c)=>({key:o._parse(new Vt(r,a,r.path,[c,"key"])),value:s._parse(new Vt(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 ee;(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 ee;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}}}}Zs.create=(t,e,n)=>new Zs({valueType:e,keyType:t,typeName:Q.ZodMap,...ne(n)});class tr extends oe{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==F.set)return z(r,{code:O.invalid_type,expected:F.set,received:r.parsedType}),ee;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(z(r,{code:O.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&&(z(r,{code:O.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 ee;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 Vt(r,l,r.path,c)));return r.common.async?Promise.all(a).then(l=>i(l)):i(a)}min(e,n){return new tr({...this._def,minSize:{value:e,message:W.toString(n)}})}max(e,n){return new tr({...this._def,maxSize:{value:e,message:W.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}tr.create=(t,e)=>new tr({valueType:t,minSize:null,maxSize:null,typeName:Q.ZodSet,...ne(e)});class jr extends oe{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==F.function)return z(n,{code:O.invalid_type,expected:F.function,received:n.parsedType}),ee;function r(a,l){return Ls({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Vs(),$r].filter(c=>!!c),issueData:{code:O.invalid_arguments,argumentsError:l}})}function o(a,l){return Ls({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Vs(),$r].filter(c=>!!c),issueData:{code:O.invalid_return_type,returnTypeError:l}})}const s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Hr){const a=this;return Ge(async function(...l){const c=new lt([]),u=await a._def.args.parseAsync(l,s).catch(m=>{throw c.addIssue(r(l,m)),c}),f=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(f,s).catch(m=>{throw c.addIssue(o(f,m)),c})})}else{const a=this;return Ge(function(...l){const c=a._def.args.safeParse(l,s);if(!c.success)throw new lt([r(l,c.error)]);const u=Reflect.apply(i,this,c.data),f=a._def.returns.safeParse(u,s);if(!f.success)throw new lt([o(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new jr({...this._def,args:Lt.create(e).rest(Qn.create())})}returns(e){return new jr({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new jr({args:e||Lt.create([]).rest(Qn.create()),returns:n||Qn.create(),typeName:Q.ZodFunction,...ne(r)})}}class Ro extends oe{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})}}Ro.create=(t,e)=>new Ro({getter:t,typeName:Q.ZodLazy,...ne(e)});class Do extends oe{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return z(n,{received:n.data,code:O.invalid_literal,expected:this._def.value}),ee}return{status:"valid",value:e.data}}get value(){return this._def.value}}Do.create=(t,e)=>new Do({value:t,typeName:Q.ZodLiteral,...ne(e)});function yu(t,e){return new zo({values:t,typeName:Q.ZodEnum,...ne(e)})}let zo=class lu extends oe{constructor(){super(...arguments),Eo.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),r=this._def.values;return z(n,{expected:le.joinValues(r),received:n.parsedType,code:O.invalid_type}),ee}if(Fs(this,Eo)||fu(this,Eo,new Set(this._def.values)),!Fs(this,Eo).has(e.data)){const n=this._getOrReturnCtx(e),r=this._def.values;return z(n,{received:n.data,code:O.invalid_enum_value,options:r}),ee}return Ge(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 lu.create(e,{...this._def,...n})}exclude(e,n=this._def){return lu.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Eo=new WeakMap,zo.create=yu;class $o extends oe{constructor(){super(...arguments),To.set(this,void 0)}_parse(e){const n=le.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==F.string&&r.parsedType!==F.number){const o=le.objectValues(n);return z(r,{expected:le.joinValues(o),received:r.parsedType,code:O.invalid_type}),ee}if(Fs(this,To)||fu(this,To,new Set(le.getValidEnumValues(this._def.values))),!Fs(this,To).has(e.data)){const o=le.objectValues(n);return z(r,{received:r.data,code:O.invalid_enum_value,options:o}),ee}return Ge(e.data)}get enum(){return this._def.values}}To=new WeakMap,$o.create=(t,e)=>new $o({values:t,typeName:Q.ZodNativeEnum,...ne(e)});class Hr extends oe{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==F.promise&&n.common.async===!1)return z(n,{code:O.invalid_type,expected:F.promise,received:n.parsedType}),ee;const r=n.parsedType===F.promise?n.data:Promise.resolve(n.data);return Ge(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Hr.create=(t,e)=>new Hr({type:t,typeName:Q.ZodPromise,...ne(e)});class xt extends oe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Q.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=>{z(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 ee;const l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?ee:l.status==="dirty"||n.value==="dirty"?Vr(l.value):l});{if(n.value==="aborted")return ee;const a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?ee:a.status==="dirty"||n.value==="dirty"?Vr(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"?ee:(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"?ee:(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(!Yn(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=>Yn(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):i);le.assertNever(o)}}xt.create=(t,e,n)=>new xt({schema:t,typeName:Q.ZodEffects,effect:e,...ne(n)}),xt.createWithPreprocess=(t,e,n)=>new xt({schema:e,effect:{type:"preprocess",transform:t},typeName:Q.ZodEffects,...ne(n)});let Ft=class extends oe{_parse(e){return this._getType(e)===F.undefined?Ge(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ft.create=(t,e)=>new Ft({innerType:t,typeName:Q.ZodOptional,...ne(e)});let wn=class extends oe{_parse(e){return this._getType(e)===F.null?Ge(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};wn.create=(t,e)=>new wn({innerType:t,typeName:Q.ZodNullable,...ne(e)});let Vo=class extends oe{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===F.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Vo.create=(t,e)=>new Vo({innerType:t,typeName:Q.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ne(e)});let Lo=class extends oe{_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 _o(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new lt(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new lt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Lo.create=(t,e)=>new Lo({innerType:t,typeName:Q.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ne(e)});class Us extends oe{_parse(e){if(this._getType(e)!==F.nan){const r=this._getOrReturnCtx(e);return z(r,{code:O.invalid_type,expected:F.nan,received:r.parsedType}),ee}return{status:"valid",value:e.data}}}Us.create=t=>new Us({typeName:Q.ZodNaN,...ne(t)});const vw=Symbol("zod_brand");class qa extends oe{_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 Fo extends oe{_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"?ee:s.status==="dirty"?(n.dirty(),Vr(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"?ee: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 Fo({in:e,out:n,typeName:Q.ZodPipeline})}}let jo=class extends oe{_parse(e){const n=this._def.innerType._parse(e),r=o=>(Yn(o)&&(o.value=Object.freeze(o.value)),o);return _o(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};jo.create=(t,e)=>new jo({innerType:t,typeName:Q.ZodReadonly,...ne(e)});function ku(t,e){const n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function wu(t,e={},n){return t?Lr.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=ku(e,r),p=(u=(c=f.fatal)!==null&&c!==void 0?c:n)!==null&&u!==void 0?u:!0;o.addIssue({code:"custom",...f,fatal:p})}});if(!a){const l=ku(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})}}):Lr.create()}const bw={object:ft.lazycreate};var Q;(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"})(Q||(Q={}));const Sw=(t,e={message:`Input not instance of ${t.name}`})=>wu(n=>n instanceof t,e),vu=Ct.create,bu=Mo.create,Cw=Us.create,xw=kn.create,Su=Ao.create,_w=Xn.create,Ew=js.create,Tw=No.create,Mw=Bo.create,Aw=Lr.create,Nw=Qn.create,Bw=tn.create,Ow=Hs.create,Iw=er.create,Pw=ft.create,Rw=ft.strictCreate,Dw=Oo.create,zw=Ws.create,$w=Io.create,Vw=Lt.create,Lw=Po.create,Fw=Zs.create,jw=tr.create,Hw=jr.create,Ww=Ro.create,Zw=Do.create,Uw=zo.create,Kw=$o.create,Jw=Hr.create,Cu=xt.create,qw=Ft.create,Gw=wn.create,Yw=xt.createWithPreprocess,Xw=Fo.create;var rn=Object.freeze({__proto__:null,defaultErrorMap:$r,setErrorMap:Yk,getErrorMap:Vs,makeIssue:Ls,EMPTY_PATH:Xk,addIssueToContext:z,ParseStatus:Ue,INVALID:ee,DIRTY:Vr,OK:Ge,isAborted:Za,isDirty:Ua,isValid:Yn,isAsync:_o,get util(){return le},get objectUtil(){return Wa},ZodParsedType:F,getParsedType:en,ZodType:oe,datetimeRegex:gu,ZodString:Ct,ZodNumber:Mo,ZodBigInt:kn,ZodBoolean:Ao,ZodDate:Xn,ZodSymbol:js,ZodUndefined:No,ZodNull:Bo,ZodAny:Lr,ZodUnknown:Qn,ZodNever:tn,ZodVoid:Hs,ZodArray:er,ZodObject:ft,ZodUnion:Oo,ZodDiscriminatedUnion:Ws,ZodIntersection:Io,ZodTuple:Lt,ZodRecord:Po,ZodMap:Zs,ZodSet:tr,ZodFunction:jr,ZodLazy:Ro,ZodLiteral:Do,ZodEnum:zo,ZodNativeEnum:$o,ZodPromise:Hr,ZodEffects:xt,ZodTransformer:xt,ZodOptional:Ft,ZodNullable:wn,ZodDefault:Vo,ZodCatch:Lo,ZodNaN:Us,BRAND:vw,ZodBranded:qa,ZodPipeline:Fo,ZodReadonly:jo,custom:wu,Schema:oe,ZodSchema:oe,late:bw,get ZodFirstPartyTypeKind(){return Q},coerce:{string:t=>Ct.create({...t,coerce:!0}),number:t=>Mo.create({...t,coerce:!0}),boolean:t=>Ao.create({...t,coerce:!0}),bigint:t=>kn.create({...t,coerce:!0}),date:t=>Xn.create({...t,coerce:!0})},any:Aw,array:Iw,bigint:xw,boolean:Su,date:_w,discriminatedUnion:zw,effect:Cu,enum:Uw,function:Hw,instanceof:Sw,intersection:$w,lazy:Ww,literal:Zw,map:Fw,nan:Cw,nativeEnum:Kw,never:Bw,null:Mw,nullable:Gw,number:bu,object:Pw,oboolean:()=>Su().optional(),onumber:()=>bu().optional(),optional:qw,ostring:()=>vu().optional(),pipeline:Xw,preprocess:Yw,promise:Jw,record:Lw,set:jw,strictObject:Rw,string:vu,symbol:Ew,transformer:Cu,tuple:Vw,undefined:Tw,union:Dw,unknown:Nw,void:Ow,NEVER:ee,ZodIssueCode:O,quotelessJson:Gk,ZodError:lt});function Qw(){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 e1(){const t=Qw();if(t.__xstate__)return t.__xstate__}const t1=t=>{if(typeof window>"u")return;const e=e1();e&&e.register(t)};class xu{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 _u=".",n1="",Eu="",r1="#",o1="*",Tu="xstate.init",s1="xstate.error",Ga="xstate.stop";function i1(t,e){return{type:`xstate.after.${t}.${e}`}}function Ya(t,e){return{type:`xstate.done.state.${t}`,output:e}}function a1(t,e){return{type:`xstate.done.actor.${t}`,output:e,actorId:t}}function Mu(t,e){return{type:`xstate.error.actor.${t}`,error:e,actorId:t}}function Au(t){return{type:Tu,input:t}}function jt(t){setTimeout(()=>{throw t})}const l1=typeof Symbol=="function"&&Symbol.observable||"@@observable";function Nu(t,e){const n=Bu(t),r=Bu(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?Nu(n[o],r[o]):!1)}function Xa(t){if(Pu(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 Bu(t){if(Z1(t))return t.value;if(typeof t!="string")return t;const e=Xa(t);return c1(e)}function c1(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 Ou(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 Iu(t){return Pu(t)?t:[t]}function vn(t){return t===void 0?[]:Iu(t)}function Qa(t,e,n,r){return typeof t=="function"?t({context:e,event:n,self:r}):t}function Pu(t){return Array.isArray(t)}function d1(t){return t.type.startsWith("xstate.error.actor")}function Wr(t){return Iu(t).map(e=>typeof e>"u"||typeof e=="string"?{target:e}:e)}function Ru(t){if(!(t===void 0||t===n1))return vn(t)}function el(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 Du(t,e){return`${e}.${t}`}function tl(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 u1(t,e){if(e===t||e===o1)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 zu(t,e){return`${t.sessionId}.${e}`}let f1=0;function h1(t,e){const n=new Map,r=new Map,o=new WeakMap,s=new Set,i={},{clock:a,logger:l}=e,c={schedule:(p,m,g,y,k=Math.random().toString(36).slice(2))=>{const w={source:p,target:m,event:g,delay:y,id:k,startedAt:Date.now()},v=zu(p,k);f._snapshot._scheduledEvents[v]=w;const b=a.setTimeout(()=>{delete i[v],delete f._snapshot._scheduledEvents[v],f._relay(p,m,g)},y);i[v]=b},cancel:(p,m)=>{const g=zu(p,m),y=i[g];delete i[g],delete f._snapshot._scheduledEvents[g],y!==void 0&&a.clearTimeout(y)},cancelAll:p=>{for(const m in f._snapshot._scheduledEvents){const g=f._snapshot._scheduledEvents[m];g.source===p&&c.cancel(p,g.id)}}},u=p=>{if(!s.size)return;const m={...p,rootId:t.sessionId};s.forEach(g=>{var y;return(y=g.next)==null?void 0:y.call(g,m)})},f={_snapshot:{_scheduledEvents:((e==null?void 0:e.snapshot)&&e.snapshot.scheduler)??{}},_bookId:()=>`x:${f1++}`,_register:(p,m)=>(n.set(p,m),p),_unregister:p=>{n.delete(p.sessionId);const m=o.get(p);m!==void 0&&(r.delete(m),o.delete(p))},get:p=>r.get(p),getAll:()=>Object.fromEntries(r.entries()),_set:(p,m)=>{const g=r.get(p);if(g&&g!==m)throw new Error(`Actor with system ID '${p}' already exists.`);r.set(p,m),o.set(m,p)},inspect:p=>{const m=el(p);return s.add(m),{unsubscribe(){s.delete(m)}}},_sendInspectionEvent:u,_relay:(p,m,g)=>{f._sendInspectionEvent({type:"@xstate.event",sourceRef:p,actorRef:m,event:g}),m._send(g)},scheduler:c,getSnapshot:()=>({_scheduledEvents:{...f._snapshot._scheduledEvents}}),start:()=>{const p=f._snapshot._scheduledEvents;f._snapshot._scheduledEvents={};for(const m in p){const{source:g,target:y,event:k,delay:w,id:v}=p[m];c.schedule(g,y,k,w,v)}},_clock:a,_logger:l};return f}let nl=!1;const rl=1;let rt=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const p1={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class m1{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 xu(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=rt.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={...p1,...n},{clock:o,logger:s,parent:i,syncSnapshot:a,id:l,systemId:c,inspect:u}=r;this.system=i?i.system:h1(this,{clock:o,logger:s}),u&&!i&&this.system.inspect(el(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 p=this.eventListeners.get(f.type),m=this.eventListeners.get("*");if(!p&&!m)return;const g=[...p?p.values():[],...m?m.values():[]];for(const y of g)try{y(f)}catch(k){jt(k)}},actionExecutor:f=>{const p=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:f.type,params:f.params}}),!f.exec)return;const m=nl;try{nl=!0,f.exec(f.info,f.params)}finally{nl=m}};this._processingStatus===rt.Running?p():this._deferred.push(p)}},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){jt(a)}break;case"done":for(const i of this.observers)try{(s=i.next)==null||s.call(i,e)}catch(a){jt(a)}this._stopProcedure(),this._complete(),this._doneEvent=a1(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=el(e,n,r);if(this._processingStatus!==rt.Stopped)this.observers.add(o);else switch(this._snapshot.status){case"done":try{(s=o.complete)==null||s.call(o)}catch(i){jt(i)}break;case"error":{const i=this._snapshot.error;if(!o.error)jt(i);else try{o.error(i)}catch(a){jt(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===rt.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=rt.Running;const e=Au(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===Ga&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===rt.Stopped?this:(this.mailbox.clear(),this._processingStatus===rt.NotStarted?(this._processingStatus=rt.Stopped,this):(this.mailbox.enqueue({type:Ga}),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){jt(r)}this.observers.clear(),this.eventListeners.clear()}_reportError(e){if(!this.observers.size){this._parent||jt(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){jt(s)}}this.observers.clear(),this.eventListeners.clear(),n&&jt(e)}_error(e){this._stopProcedure(),this._reportError(e),this._parent&&this.system._relay(this,this._parent,Mu(this.id,e))}_stopProcedure(){return this._processingStatus!==rt.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new xu(this._process.bind(this)),this._processingStatus=rt.Stopped,this.system._unregister(this),this)}_send(e){this._processingStatus!==rt.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:t1)(this)}toJSON(){return{xstate$$type:rl,id:this.id}}getPersistedSnapshot(e){return this.logic.getPersistedSnapshot(this._snapshot,e)}[l1](){return this}getSnapshot(){return this._snapshot}}function Ks(t,...[e]){return new m1(t,e)}function g1(t,e,n,r,{sendId:o}){const s=typeof o=="function"?o(n,r):o;return[e,{sendId:s},void 0]}function y1(t,e){t.defer(()=>{t.system.scheduler.cancel(t.self,e.sendId)})}function ol(t){function e(n,r){}return e.type="xstate.cancel",e.sendId=t,e.resolve=g1,e.execute=y1,e}function k1(t,e,n,r,{id:o,systemId:s,src:i,input:a,syncSnapshot:l}){const c=typeof i=="string"?tl(e.machine,i):i,u=typeof o=="function"?o(n):o;let f,p;return c&&(p=typeof a=="function"?a({context:e.context,event:n.event,self:t.self}):a,f=Ks(c,{id:u,src:i,parent:t.self,syncSnapshot:l,systemId:s,input:p})),[or(e,{children:{...e.children,[u]:f}}),{id:o,systemId:s,actorRef:f,src:i,input:p},void 0]}function w1(t,{actorRef:e}){e&&t.defer(()=>{e._processingStatus!==rt.Stopped&&e.start()})}function sl(...[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=k1,s.execute=w1,s}function v1(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]),[or(e,{children:a}),i,void 0]}function $u(t,e){const n=e.getSnapshot();if(n&&"children"in n)for(const r of Object.values(n.children))$u(t,r);t.system._unregister(e)}function b1(t,e){if(e){if($u(t,e),e._processingStatus!==rt.Running){t.stopChild(e);return}t.defer(()=>{t.stopChild(e)})}}function Js(t){function e(n,r){}return e.type="xstate.stopChild",e.actorRef=t,e.resolve=v1,e.execute=b1,e}function S1(t,{context:e,event:n},{guards:r}){return!Zr(r[0],e,n,t)}function nr(t){function e(n,r){return!1}return e.check=S1,e.guards=[t],e}function C1(t,{context:e,event:n},{guards:r}){return r.every(o=>Zr(o,e,n,t))}function Ho(t){function e(n,r){return!1}return e.check=C1,e.guards=t,e}function Zr(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 Zr(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 il(t){return t.type==="atomic"||t.type==="final"}function Ur(t){return Object.values(t.states).filter(e=>e.type!=="history")}function Wo(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 qs(t){const e=new Set(t),n=Lu(e);for(const r of e)if(r.type==="compound"&&(!n.get(r)||!n.get(r).length))Hu(r).forEach(o=>e.add(o));else if(r.type==="parallel"){for(const o of Ur(r))if(o.type!=="history"&&!e.has(o)){const s=Hu(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 Vu(t,e){const n=e.get(t);if(!n)return{};if(t.type==="compound"){const o=n[0];if(o){if(il(o))return o.key}else return{}}const r={};for(const o of n)r[o.key]=Vu(o,e);return r}function Lu(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 Fu(t,e){const n=qs(e);return Vu(t,Lu(n))}function al(t,e){return e.type==="compound"?Ur(e).some(n=>n.type==="final"&&t.has(n)):e.type==="parallel"?Ur(e).every(n=>al(t,n)):e.type==="final"}const Gs=t=>t[0]===r1;function x1(t,e){return t.transitions.get(e)||[...t.transitions.keys()].filter(r=>u1(e,r)).sort((r,o)=>o.length-r.length).flatMap(r=>t.transitions.get(r))}function _1(t){const e=t.config.after;if(!e)return[];const n=o=>{const s=i1(o,t.id),i=s.type;return t.entry.push(ei(s,{id:i,delay:o})),t.exit.push(ol(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 vn(i).map(c=>({...c,event:l,delay:a}))}).map(o=>{const{delay:s}=o;return{...bn(t,o.event,o),delay:s}})}function bn(t,e,n){const r=Ru(n.target),o=n.reenter??!1,s=A1(t,r),i={...n,actions:vn(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 E1(t){const e=new Map;if(t.config.on)for(const n of Object.keys(t.config.on)){if(n===Eu)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const r=t.config.on[n];e.set(n,Wr(r).map(o=>bn(t,n,o)))}if(t.config.onDone){const n=`xstate.done.state.${t.id}`;e.set(n,Wr(t.config.onDone).map(r=>bn(t,n,r)))}for(const n of t.invoke){if(n.onDone){const r=`xstate.done.actor.${n.id}`;e.set(r,Wr(n.onDone).map(o=>bn(t,r,o)))}if(n.onError){const r=`xstate.error.actor.${n.id}`;e.set(r,Wr(n.onError).map(o=>bn(t,r,o)))}if(n.onSnapshot){const r=`xstate.snapshot.${n.id}`;e.set(r,Wr(n.onSnapshot).map(o=>bn(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 T1(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(bn(t,"xstate.route",l))}o.states&&n(o.states)})};n(t.states),e.length>0&&t.transitions.set("xstate.route",e)}function M1(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"?[]:vn(e.actions),eventType:null,reenter:!1,target:n?[n]:[],toJSON:()=>({...r,source:`#${t.id}`,target:n?[`#${n.id}`]:[]})};return r}function A1(t,e){if(e!==void 0)return e.map(n=>{if(typeof n!="string")return n;if(Gs(n))return t.machine.getStateNodeById(n);const r=n[0]===_u;if(r&&!t.parent)return Ys(t,n.slice(1));const o=r?t.key+n:n;if(t.parent)try{return Ys(t.parent,o)}catch(s){throw new Error(`Invalid transition definition for state node '${t.id}':
2
+ ${s.message}`)}else throw new Error(`Invalid target: "${n}" is not a valid target from the root node. Did you mean ".${n}"?`)})}function ju(t){const e=Ru(t.config.target);return e?{target:e.map(n=>typeof n=="string"?Ys(t.parent,n):n)}:t.parent.initial}function rr(t){return t.type==="history"}function Hu(t){const e=Wu(t);for(const n of e)for(const r of Wo(n,t))e.add(r);return e}function Wu(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 Ur(r))n(o)}}return n(t),e}function Kr(t,e){if(Gs(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 Ys(t,e){if(typeof e=="string"&&Gs(e))try{return t.machine.getStateNodeById(e)}catch{}const n=Xa(e).slice();let r=t;for(;n.length;){const o=n.shift();if(!o.length)break;r=Kr(r,o)}return r}function Xs(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=>Kr(t,o)).filter(Boolean);return[t.machine.root,t].concat(r,n.reduce((o,s)=>{const i=Kr(t,s);if(!i)return o;const a=Xs(i,e[s]);return o.concat(a)},[]))}function N1(t,e,n,r){const s=Kr(t,e).next(n,r);return!s||!s.length?t.next(n,r):s}function B1(t,e,n,r){const o=Object.keys(e),s=Kr(t,o[0]),i=ll(s,e[o[0]],n,r);return!i||!i.length?t.next(n,r):i}function O1(t,e,n,r){const o=[];for(const s of Object.keys(e)){const i=e[s];if(!i)continue;const a=Kr(t,s),l=ll(a,i,n,r);l&&o.push(...l)}return o.length?o:t.next(n,r)}function ll(t,e,n,r){return typeof e=="string"?N1(t,e,n,r):Object.keys(e).length===1?B1(t,e,n,r):O1(t,e,n,r)}function I1(t){return Object.keys(t.states).map(e=>t.states[e]).filter(e=>e.type==="history")}function Sn(t,e){let n=t;for(;n.parent&&n.parent!==e;)n=n.parent;return n.parent===e}function P1(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 Zu(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(P1(dl([o],e,n),dl([a],e,n)))if(Sn(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 R1(t){const[e,...n]=t;for(const r of Wo(e,void 0))if(n.every(o=>Sn(o,r)))return r}function cl(t,e){if(!t.target)return[];const n=new Set;for(const r of t.target)if(rr(r))if(e[r.id])for(const o of e[r.id])n.add(o);else for(const o of cl(ju(r),e))n.add(o);else n.add(r);return[...n]}function Uu(t,e){const n=cl(t,e);if(!n)return;if(!t.reenter&&n.every(o=>o===t.source||Sn(o,t.source)))return t.source;const r=R1(n.concat(t.source));if(r)return r;if(!t.reenter)return t.source.machine.root}function dl(t,e,n){var o;const r=new Set;for(const s of t)if((o=s.target)!=null&&o.length){const i=Uu(s,n);s.reenter&&s.source===i&&r.add(i);for(const a of e)Sn(a,i)&&r.add(a)}return[...r]}function D1(t,e){if(t.length!==e.size)return!1;for(const n of t)if(!e.has(n))return!1;return!0}function z1(t,e,n,r,o){return ul([{target:[...Wu(t)],source:t,reenter:!0,actions:[],eventType:null,toJSON:null}],e,n,r,!0,o)}function ul(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=Zu(t,l,c);let f=e;o||([f,c]=F1(f,r,n,u,l,c,s,n.actionExecutor)),f=qr(f,r,n,u.flatMap(m=>m.actions),s,void 0),f=V1(f,r,n,u,l,s,c,o);const p=[...l];f.status==="done"&&(f=qr(f,r,n,p.sort((m,g)=>g.order-m.order).flatMap(m=>m.exit),s,void 0));try{return c===e.historyValue&&D1(e._nodes,l)?[f,i]:[or(f,{_nodes:p,historyValue:c}),i]}catch(m){throw m}}finally{n.actionExecutor=a}}function $1(t,e,n,r,o){if(r.output===void 0)return;const s=Ya(o.id,o.output!==void 0&&o.parent?Qa(o.output,t.context,e,n.self):void 0);return Qa(r.output,t.context,s,n.self)}function V1(t,e,n,r,o,s,i,a){let l=t;const c=new Set,u=new Set;L1(r,i,u,c),a&&u.add(t.machine.root);const f=new Set;for(const p of[...c].sort((m,g)=>m.order-g.order)){o.add(p);const m=[];m.push(...p.entry);for(const g of p.invoke)m.push(sl(g.src,{...g,syncSnapshot:!!g.onSnapshot}));if(u.has(p)){const g=p.initial.actions;m.push(...g)}if(l=qr(l,e,n,m,s,p.invoke.map(g=>g.id)),p.type==="final"){const g=p.parent;let y=(g==null?void 0:g.type)==="parallel"?g:g==null?void 0:g.parent,k=y||p;for((g==null?void 0:g.type)==="compound"&&s.push(Ya(g.id,p.output!==void 0?Qa(p.output,l.context,e,n.self):void 0));(y==null?void 0:y.type)==="parallel"&&!f.has(y)&&al(o,y);)f.add(y),s.push(Ya(y.id)),k=y,y=y.parent;if(y)continue;l=or(l,{status:"done",output:$1(l,e,n,l.machine.root,k)})}}return l}function L1(t,e,n,r){for(const o of t){const s=Uu(o,e);for(const a of o.target||[])!rr(a)&&(o.source!==a||o.source!==s||o.reenter)&&(r.add(a),n.add(a)),Jr(a,e,n,r);const i=cl(o,e);for(const a of i){const l=Wo(a,s);(s==null?void 0:s.type)==="parallel"&&l.push(s),Ku(r,e,n,l,!o.source.parent&&o.reenter?void 0:s)}}}function Jr(t,e,n,r){var o;if(rr(t))if(e[t.id]){const s=e[t.id];for(const i of s)r.add(i),Jr(i,e,n,r);for(const i of s)fl(i,t.parent,r,e,n)}else{const s=ju(t);for(const i of s.target)r.add(i),s===((o=t.parent)==null?void 0:o.initial)&&n.add(t.parent),Jr(i,e,n,r);for(const i of s.target)fl(i,t.parent,r,e,n)}else if(t.type==="compound"){const[s]=t.initial.target;rr(s)||(r.add(s),n.add(s)),Jr(s,e,n,r),fl(s,t,r,e,n)}else if(t.type==="parallel")for(const s of Ur(t).filter(i=>!rr(i)))[...r].some(i=>Sn(i,s))||(rr(s)||(r.add(s),n.add(s)),Jr(s,e,n,r))}function Ku(t,e,n,r,o){for(const s of r)if((!o||Sn(s,o))&&t.add(s),s.type==="parallel")for(const i of Ur(s).filter(a=>!rr(a)))[...t].some(a=>Sn(a,i))||(t.add(i),Jr(i,e,n,t))}function fl(t,e,n,r,o){Ku(n,r,o,Wo(t,e))}function F1(t,e,n,r,o,s,i,a){let l=t;const c=dl(r,o,s);c.sort((f,p)=>p.order-f.order);let u;for(const f of c)for(const p of I1(f)){let m;p.history==="deep"?m=g=>il(g)&&Sn(g,f):m=g=>g.parent===f,u??(u={...s}),u[p.id]=Array.from(o).filter(m)}for(const f of c)l=qr(l,e,n,[...f.exit,...f.invoke.map(p=>Js(p.id))],i,void 0),o.delete(f);return[l,u||s]}function j1(t,e){return t.implementations.actions[e]}function Ju(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:j1(i,typeof l=="string"?l:l.type),f={context:a.context,event:e,self:n.self,system:n.system},p=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:p,exec:u});continue}const m=u,[g,y,k]=m.resolve(n,a,f,p,u,o);a=g,"retryResolve"in m&&(s==null||s.push([m,y])),"execute"in m&&n.actionExecutor({type:m.type,info:f,params:y,exec:m.execute.bind(null,n,y)}),k&&(a=Ju(a,e,n,k,o,s))}return a}function qr(t,e,n,r,o,s){const i=s?[]:void 0,a=Ju(t,e,n,r,{internalQueue:o,deferredActorIds:s},i);return i==null||i.forEach(([l,c])=>{l.retryResolve(n,a,c)}),a}function hl(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===Ga)return o=or(qu(o,e,n),{status:"stopped"}),i([o,[]],e,[]),{snapshot:o,microsteps:s};let a=e;if(a.type!==Tu){const c=a,u=d1(c),f=Gu(c,o);if(u&&!f.length)return o=or(t,{status:"error",error:c.error}),i([o,[]],c,[]),{snapshot:o,microsteps:s};const p=ul(f,t,n,a,!1,r);o=p[0],i(p,c,f)}let l=!0;for(;o.status==="active";){let c=l?H1(o,a):[];const u=c.length?o:void 0;if(!c.length){if(!r.length)break;a=r.shift(),c=Gu(a,o)}const f=ul(c,o,n,a,!1,r);o=f[0],l=o!==u,i(f,a,c)}return o.status!=="active"&&qu(o,a,n),{snapshot:o,microsteps:s}}function qu(t,e,n){return qr(t,e,n,Object.values(t.children).map(r=>Js(r)),[],void 0)}function Gu(t,e){return e.machine.getTransitionData(e,t)}function H1(t,e){const n=new Set,r=t._nodes.filter(il);for(const o of r)e:for(const s of[o].concat(Wo(o,void 0)))if(s.always){for(const i of s.always)if(i.guard===void 0||Zr(i.guard,t.context,e,t)){n.add(i);break e}}return Zu(Array.from(n),new Set(t._nodes),t.historyValue)}function W1(t,e){const n=qs(Xs(t,e));return Fu(t,[...n])}function Z1(t){return!!t&&typeof t=="object"&&"machine"in t&&"value"in t}const U1=function(e){return Nu(e,this.value)},K1=function(e){return this.tags.has(e)},J1=function(e){const n=this.machine.getTransitionData(this,e);return!!(n!=null&&n.length)&&n.some(r=>r.target!==void 0||r.actions.length)},q1=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)}},G1=function(){return this._nodes.reduce((e,n)=>(n.meta!==void 0&&(e[n.id]=n.meta),e),{})};function Qs(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:Fu(e.root,t._nodes),tags:new Set(t._nodes.flatMap(n=>n.tags)),children:t.children,historyValue:t.historyValue||{},matches:U1,hasTag:K1,can:J1,getMeta:G1,toJSON:q1}}function or(t,e={}){return Qs({...t,...e},t.machine)}function Y1(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 X1(t,e){const{_nodes:n,tags:r,machine:o,children:s,context:i,can:a,hasTag:l,matches:c,getMeta:u,toJSON:f,...p}=t,m={};for(const y in s){const k=s[y];m[y]={snapshot:k.getPersistedSnapshot(e),src:k.src,systemId:k.systemId,syncSnapshot:k._syncSnapshot}}return{...p,context:Yu(i),children:m,historyValue:Y1(p.historyValue)}}function Yu(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:rl,id:r.id};else{const o=Yu(r);o!==r&&(e??(e=Array.isArray(t)?t.slice():{...t}),e[n]=o)}}return e??t}function Q1(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 ev(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 ei(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=Q1,n.execute=ev,n}function tv(t,{machine:e,context:n},r,o){const s=(i,a)=>{if(typeof i=="string"){const l=tl(e,i);if(!l)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const c=Ks(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 Ks(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!==rt.Stopped&&l.start()}),l}}function nv(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:tv(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[or(e,{context:l,children:Object.keys(s).length?{...e.children,...s}:e.children}),void 0,void 0]}function we(t){function e(n,r){}return e.type="xstate.assign",e.assignment=t,e.resolve=nv,e}const Xu=new WeakMap;function Gr(t,e,n){let r=Xu.get(t);return r?e in r||(r[e]=n()):(r={[e]:n()},Xu.set(t,r)),r[e]}const rv={},Zo=t=>typeof t=="string"?{type:t}:typeof t=="function"?"resolve"in t?{type:t.type}:{type:t.name}:t;class ti{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(_u),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?Ou(this.config.states,(r,o)=>new ti(r,{_parent:this,_key:o,_machine:this.machine})):rv,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=vn(this.config.entry).slice(),this.exit=vn(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=vn(e.tags).slice()}_initialize(){this.transitions=E1(this),this.config.always&&(this.always=Wr(this.config.always).map(e=>bn(this,Eu,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(Zo),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(e=>`#${e.id}`),source:`#${this.id}`,actions:this.initial.actions.map(Zo),eventType:null})}:void 0,history:this.history,states:Ou(this.states,e=>e.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(e=>({...e,actions:e.actions.map(Zo)})),entry:this.entry.map(Zo),exit:this.exit.map(Zo),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 Gr(this,"invoke",()=>vn(this.config.invoke).map((e,n)=>{const{src:r,systemId:o}=e,s=e.id??Du(this.id,n),i=typeof r=="string"?r:`xstate.invoke.${Du(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 Gr(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 Gr(this,"delayedTransitions",()=>_1(this))}get initial(){return Gr(this,"initial",()=>M1(this,this.config.initial))}next(e,n){const r=n.type,o=[];let s;const i=Gr(this,`candidates-${r}`,()=>x1(this,r));for(const a of i){const{guard:l}=a,c=e.context;let u=!1;try{u=!l||Zr(l,c,n,e)}catch(f){const p=typeof l=="string"?l:typeof l=="object"?l.type:void 0;throw new Error(`Unable to evaluate guard ${p?`'${p}' `:""}in transition for event '${r}' in state node '${this.id}':
3
+ ${f.message}`)}if(u){o.push(...a.actions),s=a;break}}return s?[s]:void 0}get events(){return Gr(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 ov="#";class pl{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 ti(e,{_key:this.id,_machine:this}),this.root._initialize(),T1(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 pl(this.config,{actions:{...n,...e.actions},guards:{...r,...e.guards},actors:{...o,...e.actors},delays:{...s,...e.delays}})}resolveState(e){const n=W1(this.root,e.value),r=qs(Xs(this.root,n));return Qs({_nodes:[...r],context:e.context||{},children:{},status:al(r,this.root)?"done":e.status||"active",output:e.output,error:e.error,historyValue:e.historyValue},this)}transition(e,n,r){return hl(e,n,r,[]).snapshot}microstep(e,n,r){return hl(e,n,r,[]).microsteps.map(([o])=>o)}getTransitionData(e,n){return ll(this.root,e.value,e,n)||[]}_getPreInitialState(e,n,r){const{context:o}=this.config,s=Qs({context:typeof o!="function"&&o?o:{},_nodes:[this.root],children:{},status:"active"},this);return typeof o=="function"?qr(s,n,e,[we(({spawn:a,event:l,self:c})=>o({spawn:a,input:l.input,self:c}))],r,void 0):s}getInitialSnapshot(e,n){const r=Au(n),o=[],s=this._getPreInitialState(e,r,o),[i]=z1(this.root,s,e,r,o),{snapshot:a}=hl(i,r,e,o);return a}start(e){Object.values(e.children).forEach(n=>{n.getSnapshot().status==="active"&&n.start()})}getStateNodeById(e){const n=Xa(e),r=n.slice(1),o=Gs(n[0])?n[0].slice(ov.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 Ys(s,r)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(e,n){return X1(e,n)}restoreSnapshot(e,n){const r={},o=e.children;Object.keys(o).forEach(f=>{const p=o[f],m=p.snapshot,g=p.src,y=typeof g=="string"?tl(this,g):g;if(!y)return;const k=Ks(y,{id:f,parent:n.self,syncSnapshot:p.syncSnapshot,snapshot:m,src:g,systemId:p.systemId});r[f]=k});function s(f,p){if(p instanceof ti)return p;try{return f.machine.getStateNodeById(p.id)}catch{}}function i(f,p){if(!p||typeof p!="object")return{};const m={};for(const g in p){const y=p[g];for(const k of y){const w=s(f,k);w&&(m[g]??(m[g]=[]),m[g].push(w))}}return m}const a=i(this.root,e.historyValue),l=Qs({...e,children:r,_nodes:Array.from(qs(Xs(this.root,e.value))),historyValue:a},this),c=new Set;function u(f,p){if(!c.has(f)){c.add(f);for(const m in f){const g=f[m];if(g&&typeof g=="object"){if("xstate$$type"in g&&g.xstate$$type===rl){f[m]=p[g.id];continue}u(g,p)}}}}return u(l.context,r),l}}function sv(t,e,n,r,{event:o}){const s=typeof o=="function"?o(n,r):o;return[e,{event:s},void 0]}function iv(t,{event:e}){t.defer(()=>t.emit(e))}function Qu(t){function e(n,r){}return e.type="xstate.emit",e.event=t,e.resolve=sv,e.execute=iv,e}let ml=function(t){return t.Parent="#_parent",t.Internal="#_internal",t}({});function av(t,e,n,r,{to:o,event:s,id:i,delay:a},l){var g;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 y=c&&c[a];f=typeof y=="function"?y(n,r):y}else f=typeof a=="function"?a(n,r):a;const p=typeof o=="function"?o(n,r):o;let m;if(typeof p=="string"){if(p===ml.Parent?m=t.self._parent:p===ml.Internal?m=t.self:p.startsWith("#_")?m=e.children[p.slice(2)]:m=(g=l.deferredActorIds)!=null&&g.includes(p)?p:e.children[p],!m)throw new Error(`Unable to send event to actor '${p}' from machine '${e.machine.id}'.`)}else m=p||t.self;return[e,{to:m,targetId:typeof p=="string"?p:void 0,event:u,id:i,delay:f},void 0]}function lv(t,e,n){typeof n.to=="string"&&(n.to=e.children[n.to])}function cv(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===s1?Mu(t.self.id,r.data):r)})}function gl(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=av,r.retryResolve=lv,r.execute=cv,r}function dv(t,e){return gl(ml.Parent,t,e)}function uv(t,e,n,r,{collect:o}){const s=[],i=function(l){s.push(l)};return i.assign=(...a)=>{s.push(we(...a))},i.cancel=(...a)=>{s.push(ol(...a))},i.raise=(...a)=>{s.push(ei(...a))},i.sendTo=(...a)=>{s.push(gl(...a))},i.sendParent=(...a)=>{s.push(dv(...a))},i.spawnChild=(...a)=>{s.push(sl(...a))},i.stopChild=(...a)=>{s.push(Js(...a))},i.emit=(...a)=>{s.push(Qu(...a))},o({context:n.context,event:n.event,enqueue:i,check:a=>Zr(a,e.context,n.event,e),self:t.self,system:t.system},r),[e,void 0,s]}function fv(t){function e(n,r){}return e.type="xstate.enqueueActions",e.collect=t,e.resolve=uv,e}function hv(t,e,n,r,{value:o,label:s}){return[e,{value:typeof o=="function"?o(n,r):o,label:s},void 0]}function pv({logger:t},{value:e,label:n}){n?t(n,e):t(e)}function mv(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=hv,n.execute=pv,n}function gv(t,e){return new pl(t,e)}function on({schemas:t,actors:e,actions:n,guards:r,delays:o}){return{assign:we,sendTo:gl,raise:ei,log:mv,cancel:ol,stopChild:Js,enqueueActions:fv,emit:Qu,spawnChild:sl,createStateConfig:s=>s,createAction:s=>s,createMachine:s=>gv({...s,schemas:t},{actors:e,actions:n,guards:r,delays:o}),extend:s=>on({schemas:t,actors:e,actions:{...n,...s.actions},guards:{...r,...s.guards},delays:{...o,...s.delays}})}}var yv=Object.defineProperty,Yr=(t,e)=>{for(var n in e)yv(t,n,{get:e[n],enumerable:!0})},Uo=h.defineCommand("drag-block"),kv=h.defineCommand("remove-block"),yl=h.defineCommand("remove-selected");h.defineCommand("duplicate-selected");var ef=h.defineCommand("bring-forward-selected"),tf=h.defineCommand("send-backward-selected"),nf=h.defineCommand("clone-entities"),kl=h.defineCommand("unclone-entities"),ni=h.defineCommand("set-cursor"),rf=h.defineCommand("cut"),of=h.defineCommand("copy"),sf=h.defineCommand("paste"),wl=h.defineCommand("select-block"),wv=h.defineCommand("deselect-block"),af=h.defineCommand("toggle-select"),Xr=h.defineCommand("deselect-all"),lf=h.defineCommand("select-all"),cf=h.defineCommand("add-selection-box"),df=h.defineCommand("update-selection-box"),uf=h.defineCommand("remove-selection-box"),ff=h.defineCommand("add-held"),hf=h.defineCommand("remove-held"),pf=h.defineCommand("add-transform-box"),vl=h.defineCommand("update-transform-box"),mf=h.defineCommand("hide-transform-box"),gf=h.defineCommand("show-transform-box"),bl=h.defineCommand("remove-transform-box"),yf=h.defineCommand("start-transform-box-edit"),vv=h.defineCommand("end-transform-box-edit"),kf={};Yr(kf,{DragStart:()=>Ae,EditAfterPlacing:()=>Ko,Selected:()=>Ie,SelectionBox:()=>ri,TransformBox:()=>Ye,TransformHandle:()=>ve});var Ae=h.defineCanvasComponent({name:"dragStart"},{position:h.field.tuple(h.field.float64(),2).default([0,0]),size:h.field.tuple(h.field.float64(),2).default([0,0]),rotateZ:h.field.float64().default(0),flip:h.field.tuple(h.field.boolean(),2).default([!1,!1]),fontSize:h.field.float64().default(16)}),Ko=h.defineCanvasComponent({name:"editAfterPlacing"},{}),Ie=h.defineCanvasComponent({name:"selected"},{}),ri=h.defineCanvasComponent({name:"selectionBox"},{}),Ye=h.defineCanvasComponent({name:"transformBox"},{}),bv=`
42
4
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 33.94 33.94">
43
5
  <g fill="none" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="2">
44
6
  <path d="M25.46,14.14l2.83,2.83-2.83,2.83"/>
@@ -50,7 +12,7 @@ ${f.message}`)}if(u){o.push(...a.actions),s=a;break}}return s?[s]:void 0}get eve
50
12
  <path d="M19.8,8.49l-2.83-2.83-2.83,2.83"/>
51
13
  <path d="M16.97,5.66v15.14"/>
52
14
  </g>
53
- </svg>`;function dc(t){return`
15
+ </svg>`;function oi(t){return`
54
16
  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"
55
17
  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
56
18
  <g transform="rotate(${t*180/Math.PI} 12 12)">
@@ -58,7 +20,7 @@ ${f.message}`)}if(u){o.push(...a.actions),s=a;break}}return s?[s]:void 0}get eve
58
20
  <path d="M8 17l4 4l4 -4"/>
59
21
  <path d="M12 3l0 18"/>
60
22
  </g>
61
- </svg>`}function fc(t){return`
23
+ </svg>`}function si(t){return`
62
24
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="-10 -10 34 34"
63
25
  fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2">
64
26
  <g transform="rotate(${t*180/Math.PI} 8 8)">
@@ -66,19 +28,57 @@ ${f.message}`)}if(u){o.push(...a.actions),s=a;break}}return s?[s]:void 0}get eve
66
28
  <path d="M14.61,1l4,4-4,4"/>
67
29
  <path d="M18.61,5h-6.02c-4.19,0-7.59,3.4-7.59,7.59v6.17"/>
68
30
  </g>
69
- </svg>`}var vB={drag:{makeSvg:()=>wB,hotspot:[12,12],rotationOffset:0},ns:{makeSvg:dc,hotspot:[12,12],rotationOffset:0},ew:{makeSvg:dc,hotspot:[12,12],rotationOffset:Math.PI/2},nwse:{makeSvg:dc,hotspot:[12,12],rotationOffset:-Math.PI/4},nesw:{makeSvg:dc,hotspot:[12,12],rotationOffset:Math.PI/4},rotateNW:{makeSvg:fc,hotspot:[16,16],rotationOffset:0},rotateNE:{makeSvg:fc,hotspot:[16,16],rotationOffset:Math.PI/2},rotateSW:{makeSvg:fc,hotspot:[16,16],rotationOffset:-Math.PI/2},rotateSE:{makeSvg:fc,hotspot:[16,16],rotationOffset:-Math.PI}},_e={Idle:"idle",Pointing:"pointing",Dragging:"dragging",SelectionBoxPointing:"selectionBoxPointing",SelectionBoxDragging:"selectionBoxDragging"},Jn={None:"none",Idle:"idle",Editing:"editing"},Xn={Scale:"scale",Stretch:"stretch",Rotate:"rotate"},Pn={Idle:"idle",Waiting:"waiting",Scrolling:"scrolling"},t0=Zr.object({enabled:Zr.boolean().default(!0),edgeSizePx:Zr.number().default(10),edgeScrollSpeedPxPerFrame:Zr.number().default(15),edgeScrollDelayMs:Zr.number().default(250)}),kB=Zr.object({edgeScrolling:t0.default(t0.parse({}))}),Ke=Qe({name:"transformHandle"},{kind:C.string().max(16).default(Xn.Scale),vectorX:C.int8().default(0),vectorY:C.int8().default(0),transformBox:C.ref(),cursorKind:C.string().max(16).default("drag")}),n0="selection";function bB(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]=SB(t,a)}return r}function SB(t,e){return e==null||!R(t,e,me)?null:me.read(t,e).id}function EB(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 CB(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 _B=ie(t=>t.with(xt));ie(t=>t.with(A));function Ei(t,e){if(R(t,e,xt)||Yd(t,e))return;const{sessionId:n}=Ge(t);Q(t,e,xt,{}),R(t,e,Rt)||Q(t,e,Rt,{sessionId:n})}function Ta(t,e){R(t,e,xt)&&(mn(t,e,xt),mn(t,e,Rt))}function r0(t){for(const e of _B.current(t))Ta(t,e)}function xB(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 TB=class{constructor(t){this.seed=typeof t=="string"?xB(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 af(t,e){const n=t+e,r=new TB(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 o0={};bi(o0,{Clipboard:()=>Ma,ScrollEdgesStateSingleton:()=>lf,SelectionStateSingleton:()=>Qn,TransformBoxStateSingleton:()=>cf});var MB={count:C.uint32().default(0),center:C.tuple(C.float64(),2).default([0,0])},hc=new WeakMap,AB=class extends kt{constructor(){super({name:"clipboard"},MB)}setEntities(t,e){const{editor:n}=Ge(t);hc.set(n,e)}getEntities(t){const{editor:e}=Ge(t);return hc.get(e)??[]}clearEntities(t){const{editor:e}=Ge(t);hc.delete(e)}hasContent(t){const{editor:e}=Ge(t),n=hc.get(e);return n!==void 0&&n.length>0}},Ma=new AB,lf=Co("scrollEdgesState",{state:C.enum(Pn).default(Pn.Idle),edgeEnterStartTime:C.float64().default(0)}),Qn=Co("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()}),cf=Co("transformBoxState",{state:C.string().max(32).default(Jn.None),transformBoxId:C.ref()}),s0={};bi(s0,{hoverCursorSystem:()=>NB,scrollEdgesSystem:()=>PB,transformBoxSystem:()=>RB});var uf=ie(t=>t.with(bo,Ke).tracking(bo)),IB=ie(t=>t.with(A,en).tracking(A)),NB=Se({phase:"capture"},t=>{const e=uf.added(t),n=uf.removed(t),r=uf.current(t),o=IB.changed(t);if(r.length===0&&n.length>0){Nn.clearContextCursor(t);return}if((e.length>0||o.length>0)&&r.length>0){const i=r[0],a=Ke.read(t,i);if(a.transformBox===null)return;const l=A.read(t,a.transformBox),c=Nn.read(t);(a.cursorKind!==c.contextCursorKind||l.rotateZ!==c.contextRotation)&&Nn.setContextCursor(t,a.cursorKind,l.rotateZ)}});function pc(t){return ls(t,n0).edgeScrolling}var BB=$r({guards:{isPointerNearEdge:({event:t})=>{const{edgeSizePx:e}=pc(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}=pc(e.ctx);return performance.now()-t.edgeEnterStartTime>=n}},actions:{setEdgeEnterStartTime:He({edgeEnterStartTime:()=>performance.now()}),moveCamera:({event:t})=>{const{edgeSizePx:e,edgeScrollSpeedPxPerFrame:n}=pc(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:He({edgeEnterStartTime:0})}}).createMachine({id:"scrollEdges",initial:Pn.Idle,context:{edgeEnterStartTime:0},states:{[Pn.Idle]:{entry:"resetContext",on:{pointerMove:{guard:"isPointerNearEdge",target:Pn.Waiting}}},[Pn.Waiting]:{entry:"setEdgeEnterStartTime",on:{pointerMove:{guard:ss("isPointerNearEdge"),target:Pn.Idle},frame:{guard:"isEdgeScrollDelayPassed",target:Pn.Scrolling}}},[Pn.Scrolling]:{on:{frame:[{guard:ss("isPointerNearEdge"),target:Pn.Idle},{actions:"moveCamera"}]}}}}),PB=Se({phase:"capture"},t=>{if(!pc(t).enabled)return;const e=Qn.read(t).state;if(e!==_e.Dragging&&e!==_e.SelectionBoxDragging)return;const n=lf.read(t).state,r=n===Pn.Waiting||n===Pn.Scrolling,o=ut.getButtons(t,"select"),s=jr(t,o,{includeFrameEvent:r});s.length!==0&&lf.run(t,BB,s)}),mc=ie(t=>t.with(A).tracking(xt)),OB=$r({guards:{isSelectionEditable:({event:t})=>DB(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],Ke),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];return ia(t.ctx,e)!==ot.GroupOnly},hasEditAfterPlacing:({event:t})=>t.type!=="selectionChanged"||t.selectedEntityIds.length!==1?!1:R(t.ctx,t.selectedEntityIds[0],xa)},actions:{addTransformBox:He(({context:t,event:e},n)=>{t.transformBoxId!==null&&sf.spawn(e.ctx,{transformBoxId:t.transformBoxId});const r=Bt(e.ctx);return Gy.spawn(e.ctx,{transformBoxId:r,skipHandles:n==null?void 0:n.skipHandles}),{transformBoxId:r}}),updateTransformBox:({context:t,event:e})=>{t.transformBoxId!==null&&of.spawn(e.ctx,{transformBoxId:t.transformBoxId})},hideTransformBox:({context:t,event:e})=>{t.transformBoxId!==null&&Jy.spawn(e.ctx,{transformBoxId:t.transformBoxId})},showTransformBox:({context:t,event:e})=>{t.transformBoxId!==null&&Xy.spawn(e.ctx,{transformBoxId:t.transformBoxId})},removeTransformBox:({context:t,event:e})=>{t.transformBoxId!==null&&sf.spawn(e.ctx,{transformBoxId:t.transformBoxId})},clearTransformBoxId:He({transformBoxId:()=>null}),startTransformBoxEdit:({context:t,event:e})=>{t.transformBoxId!==null&&Qy.spawn(e.ctx,{transformBoxId:t.transformBoxId})},removeEditAfterPlacing:({event:t})=>{if(t.type==="selectionChanged")for(const e of t.selectedEntityIds)R(t.ctx,e,xa)&&mn(t.ctx,e,xa)}}}).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:ss("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([ss("isOverTransformBox"),ss("isOverTransformHandle")]),target:Jn.None},selectionChanged:{target:Jn.None,actions:Hl(({event:t})=>t)}}}}});function DB(t){const e=mc.current(t);if(e.length!==1)return!1;const n=e[0],r=A.read(t,n);return cy(t,r.tag)}var RB=Se({phase:"capture"},t=>{const e=[],n=mc.added(t),r=mc.removed(t);if(n.length>0||r.length>0){const i=[...mc.current(t)],a={type:"selectionChanged",ctx:t,selectedEntityIds:i};e.push(a)}const o=ut.getButtons(t,"select"),s=jr(t,o);e.push(...s),e.length!==0&&cf.run(t,OB,e)}),i0={};bi(i0,{transformBoxSystem:()=>FB});var gc=ie(t=>t.with(A,xt)),zB=ie(t=>t.with(A,Lr)),$B="a",LB="b",a0="c",VB="d",FB=Se({phase:"update",priority:-100},t=>{he(t,sf,(e,{transformBoxId:n})=>{jB(e,n)}),he(t,Gy,(e,{transformBoxId:n,skipHandles:r})=>{UB(e,n,r)}),he(t,of,(e,{transformBoxId:n})=>{df(e,n)}),he(t,Jy,(e,{transformBoxId:n})=>{HB(e,n)}),he(t,Xy,(e,{transformBoxId:n})=>{ZB(e,n)}),he(t,Qy,(e,{transformBoxId:n})=>{KB(e,n)}),he(t,yB,ff)});function jB(t,e){if(!R(t,e,en)){ff(t);return}const n=fr(t,e,Ke,"transformBox");for(const r of n)it(t,r);it(t,e),ff(t)}function UB(t,e,n){Q(t,e,A,{tag:"transform-box",position:[0,0],size:[0,0],rotateZ:0,rank:$B}),Q(t,e,en,{}),Q(t,e,wt,{position:[0,0],size:[0,0],rotateZ:0,fontSize:16}),n||df(t,e)}function df(t,e){if(!NE(t,e))return;const n=gc.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,mt.boundPoints(i.position,i.size,r,s),!(Qn.read(t).state===_e.Dragging)){if(R(t,e,wt)){const c=wt.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=R(t,c,yt)?yt.read(t,c).fontSizePx:16;if(!R(t,c,wt))Q(t,c,wt,{position:u.position,size:u.size,rotateZ:u.rotateZ,flip:u.flip,fontSize:f});else{const h=wt.write(t,c);h.position=u.position,h.size=u.size,h.rotateZ=u.rotateZ,h.flip=u.flip,h.fontSize=f}}}WB(t,e)}function WB(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=gc.current(t);let w=ot.Scale;y.length===1?w=ia(t,y[0]):y.length>1&&y.every(F=>ia(t,F)===ot.Free)&&(w=ot.Free);const v=y.every(M=>{const F=A.read(t,M);return Kn(t,F.tag).canRotate}),b=y.every(M=>{const F=A.read(t,M);return Kn(t,F.tag).canScale});let S;switch(w){case"scale":case"text":S=Xn.Scale;break;case"free":S=Xn.Stretch;break;default:S=Xn.Scale;break}const k=we.read(t),E=l*k.zoom,_=c*k.zoom,T=Math.min(E,_),I=15;for(let M=0;M<2;M++)for(let F=0;F<2;F++)M+F!==1&&T<I/2||M+F===1&&_<I||(b&&m.push({tag:"transform-handle",kind:S,vectorX:M*2-1,vectorY:F*2-1,left:i+l*M-f/2,top:a+c*F-f/2,width:f,height:f,rotateZ:s,rank:VB,cursorKind:M+F===1?"nesw":"nwse",scaleMultiplier:[1,1],anchor:[.5,.5]}),v&&m.push({tag:"transform-rotate",kind:Xn.Rotate,vectorX:M*2-1,vectorY:F*2-1,left:i+M*l-(1-M)*h,top:a+F*c-(1-F)*h,width:h,height:h,rotateZ:s,rank:LB,cursorKind:g[M+F*2],scaleMultiplier:[.5,.5],anchor:[1-M,1-F]}));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:a0,cursorKind:"ns",scaleMultiplier:[0,1],anchor:[.5,.5]});if(b||w===ot.Text)for(let M=0;M<2;M++)m.push({tag:"transform-edge",kind:w===ot.Text?Xn.Stretch:S,vectorX:M*2-1,vectorY:0,left:i+l*M-p/2,top:a,width:p,height:c,rotateZ:s,rank:a0,cursorKind:"ew",scaleMultiplier:[1,0],anchor:[.5,.5]});const B=fr(t,e,Ke,"transformBox"),L=new Map;for(const M of B){const F=Ke.read(t,M),q=`${F.kind}-${F.vectorX}-${F.vectorY}`;L.set(q,M)}const Z=new Set;for(const M of m){const F=`${M.kind}-${M.vectorX}-${M.vectorY}`;let q=L.get(F);const ue=[M.left+M.width/2,M.top+M.height/2],se=$.clone(ue);$.rotateAround(se,u,s);const j=se[0]-M.width/2,ee=se[1]-M.height/2;q||(q=Bt(t),Q(t,q,A),Q(t,q,Ke),Q(t,q,wt),Q(t,q,So));const fe=A.write(t,q);fe.tag=M.tag,fe.position=[j,ee],fe.size=[M.width,M.height],fe.rotateZ=M.rotateZ,fe.rank=M.rank;const Me=Ke.write(t,q);Me.transformBox=e,Me.kind=M.kind,Me.vectorX=M.vectorX,Me.vectorY=M.vectorY,Me.cursorKind=M.cursorKind;const Ce=wt.write(t,q);Ce.position=[j,ee],Ce.size=[M.width,M.height],Ce.rotateZ=M.rotateZ;const qe=So.write(t,q);qe.startPosition=[j,ee],qe.startSize=[M.width,M.height],$.copy(qe.scaleMultiplier,M.scaleMultiplier),$.copy(qe.anchor,M.anchor),Z.add(q)}for(const M of B)Z.has(M)||it(t,M)}function HB(t,e){if(!R(t,e,en))return;if(!R(t,e,ct))Q(t,e,ct,{value:0});else{const r=ct.write(t,e);r.value=0}const n=fr(t,e,Ke,"transformBox");for(const r of n)if(!R(t,r,ct))Q(t,r,ct,{value:0});else{const o=ct.write(t,r);o.value=0}}function ZB(t,e){if(!R(t,e,en))return;const n=gc.current(t);if(n.length===0||n.length===1&&ia(t,n[0])===ot.GroupOnly)return;R(t,e,ct)&&mn(t,e,ct);const r=fr(t,e,Ke,"transformBox");for(const o of r)R(t,o,ct)&&mn(t,o,ct);df(t,e)}function KB(t,e){if(R(t,e,en)){const n=fr(t,e,Ke,"transformBox");for(const r of n)it(t,r)}for(const n of gc.current(t))R(t,n,Lr)||Q(t,n,Lr,{})}function ff(t){for(const e of zB.current(t))R(t,e,Lr)&&mn(t,e,Lr)}var l0={};bi(l0,{selectSystem:()=>JB});var YB=4,c0=ie(t=>t.with(A,xt,me)),qB=ie(t=>t.with(A,Lr)),GB=$r({guards:{isThresholdReached:({context:t,event:e})=>$.distance(t.pointingStartClient,e.screenPosition)>=YB,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?!Yd(e,n):!0},hasEditedBlocks:({event:t})=>qB.current(t.ctx).length>0},actions:{setPointingStart:He({pointingStartClient:({event:t})=>t.screenPosition,pointingStartWorld:({event:t})=>t.worldPosition}),setDragStart:He({dragStart:({event:t})=>t.worldPosition}),addHeldToDragged:({context:t,event:e})=>{t.draggedEntity!==null&&Yy.spawn(e.ctx,{entityId:t.draggedEntity})},removeHeldFromDragged:({context:t,event:e})=>{t.draggedEntity!==null&&qy.spawn(e.ctx,{entityId:t.draggedEntity})},setDragCursor:({event:t,context:e})=>{if(e.draggedEntity)if(R(t.ctx,e.draggedEntity,Ke)){const n=Ke.read(t.ctx,e.draggedEntity),r=n.transformBox!==null?A.read(t.ctx,n.transformBox):void 0;cc.spawn(t.ctx,{contextCursorKind:n.cursorKind,contextRotation:(r==null?void 0:r.rotateZ)??0})}else cc.spawn(t.ctx,{contextCursorKind:"drag",contextRotation:0})},unsetDragCursor:({event:t})=>{cc.spawn(t.ctx,{contextCursorKind:""})},setDraggedEntity:He({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&&(_a.spawn(e.ctx,{entityId:t.draggedEntity,position:t.draggedEntityStart}),t.isCloning&&nf.spawn(e.ctx,{entityIds:[t.draggedEntity],seed:t.cloneGeneratorSeed}))},resetContext:He({dragStart:()=>[0,0],pointingStartClient:()=>[0,0],pointingStartWorld:()=>[0,0],draggedEntityStart:()=>[0,0],draggedEntity:()=>null,cloneGeneratorSeed:()=>crypto.randomUUID(),isCloning:()=>!1}),createSelectionBox:({event:t})=>{Hy.spawn(t.ctx,void 0)},removeSelectionBox:({event:t})=>{Ky.spawn(t.ctx,void 0)},updateDragged:He({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=Ht.snapX(n,r),o=Ht.snapY(n,o)),_a.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(c0.current(n)):[t.draggedEntity];Ly.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(c0.current(n)):[t.draggedEntity];nf.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]);Zy.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?Uy.spawn(e,{entityId:n}):rf.spawn(e,{entityId:n,deselectOthers:!0}))},selectDragged:({context:t,event:e})=>{t.draggedEntity!==null&&R(e.ctx,t.draggedEntity,me)&&rf.spawn(e.ctx,{entityId:t.draggedEntity,deselectOthers:!0})},deselectAllIfShiftNotDown:({event:t})=>{t.shiftDown||Si.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,Ke)||Si.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",ss("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}}}}}),JB=Se({phase:"capture",priority:100},t=>{let e=ut.getButtons(t,"select");Qn.read(t).state===_e.Dragging&&e.length===0&&(e=["left"]);const r=jr(t,e);r.length!==0&&Qn.run(t,GB,r)}),u0={};bi(u0,{blockSystem:()=>XB,dragHandlerSystem:()=>oP,selectSystem:()=>dP});var Ci=ie(t=>t.with(A,xt)),d0=ie(t=>t.with(A,me)),XB=Se({phase:"update"},t=>{he(t,_a,(e,{entityId:n,position:r})=>{if(!R(e,n,A))return;const o=A.write(e,n);o.position=r}),he(t,rf,(e,{entityId:n,deselectOthers:r})=>{r&&hf(e),Ei(e,n)}),he(t,gB,(e,{entityId:n})=>{Ta(e,n)}),he(t,Uy,(e,{entityId:n})=>{R(e,n,xt)?Ta(e,n):Ei(e,n)}),he(t,Si,hf),he(t,Yy,(e,{entityId:n})=>{if(!R(e,n,me)||R(e,n,Rt))return;const{sessionId:r}=Ge(e);Q(e,n,Rt,{sessionId:r})}),he(t,qy,(e,{entityId:n})=>{R(e,n,xt)||R(e,n,Rt)&&mn(e,n,Rt)}),he(t,Wy,e=>{for(const n of d0.current(e))Ei(e,n)}),he(t,mB,(e,{entityId:n})=>{it(e,n)}),he(t,tf,e=>{for(const n of Ci.current(e))it(e,n)}),he(t,zy,QB),he(t,$y,eP),he(t,cc,(e,n)=>{n.cursorKind!==void 0&&Nn.setCursor(e,n.cursorKind,n.rotation??0),n.contextCursorKind!==void 0&&Nn.setContextCursor(e,n.contextCursorKind,n.contextRotation??0),n.contextCursorKind===""&&Nn.clearContextCursor(e)}),he(t,Fy,e=>{f0(e)}),he(t,Vy,e=>{f0(e);for(const n of Ci.current(e))it(e,n)}),he(t,jy,(e,n)=>{tP(e,n==null?void 0:n.position)}),he(t,Ly,(e,{entityIds:n,offset:r,seed:o})=>{nP(e,n,r,o)}),he(t,nf,(e,{entityIds:n,seed:r})=>{rP(e,n,r)})});function hf(t){for(const e of Ci.current(t))Ta(t,e)}function QB(t){const e=[...Ci.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=Zn.genNext(t)}}}function eP(t){const e=[...Ci.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=Zn.genPrev(t)}}}function f0(t){const e=[...Ci.current(t)];if(e.length===0)return;const{componentsById:n}=Ge(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=bB(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)}}Ma.setEntities(t,o);const l=Ma.write(t);l.count=o.length,l.center=ne.center(s)}function tP(t,e){const n=Ma.getEntities(t);if(n.length===0)return;const{componentsById:r}=Ge(t),o=new Map([...r].filter(([,h])=>h.sync==="document")),s=Ma.read(t),i=me._getComponentId(t),a=A._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),Ht.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});hf(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),Q(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=EB(w.schema);if(b.length>0){for(const S of b)delete v[S];f.push({entityId:p,componentDef:w,componentData:y})}Q(t,p,w,v)}Ei(t,p)}for(const{entityId:h,componentDef:p,componentData:m}of f)CB(t,h,p,m,u)}function nP(t,e,n,r){const{componentsById:o}=Ge(t),s=new Map([...o].filter(([,c])=>c.sync==="document")),i=me._getComponentId(t),a=A._getComponentId(t),l=new Map;for(const c of e){if(!R(t,c,me))continue;const u=me.read(t,c),f=af(u.id,r),h=Bt(t);l.set(c,h),Q(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)}Q(t,h,m,g)}}h0(t,l)}function rP(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(af(a.id,n))}const o=[];for(const i of d0.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(af(c,n)===a){s.set(i,l);break}}}h0(t,s);for(const i of o)it(t,i)}function h0(t,e){for(const[n,r]of e){for(const o of fr(t,n,Ze,"startBlock"))Ze.write(t,o).startBlock=r;for(const o of fr(t,n,Ze,"endBlock"))Ze.write(t,o).endBlock=r}}var pf=ie(t=>t.with(A,xt)),p0=ie(t=>t.with(A,en,wt)),oP=Se({phase:"update"},t=>{he(t,_a,(e,{entityId:n,position:r})=>{if(R(e,n,en)){sP(e,n,r);return}if(R(e,n,Ke)){iP(e,n,r);return}})});function sP(t,e,n){const r=wt.read(t,e),o=n[0]-r.position[0],s=n[1]-r.position[1];for(const i of pf.current(t)){if(!R(t,i,wt))continue;const a=wt.read(t,i),l=A.write(t,i);l.position=[a.position[0]+o,a.position[1]+s],Ht.snapPosition(t,l.position)}}function iP(t,e,n){const r=Ke.read(t,e);r.kind===Xn.Rotate?aP(t,e,n):r.kind===Xn.Scale?m0(t,e,n,!0):r.kind===Xn.Stretch&&m0(t,e,n,!1)}function aP(t,e,n){const r=p0.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=$.angleTo(i,l),u=wt.read(t,o),f=Ke.read(t,e),h=$.angle([s.size[0]*f.vectorX,s.size[1]*f.vectorY])+u.rotateZ;let p=c-h;const m=Ht.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 pf.current(t)){if(!R(t,w,wt))continue;const v=wt.read(t,w),b=A.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&&Ht.snapPosition(t,b.position)}}function m0(t,e,n,r){const o=p0.current(t);if(o.length===0){console.warn("No transform box found for scaling");return}const s=o[0],i=wt.read(t,s),a=Ke.read(t,e),l=A.read(t,e),c=[n[0]+l.size[0]/2,n[1]+l.size[1]/2];Ht.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,T=Ht.read(t),I=$.create(y*S,w*k);$.rotate(I,u),$.scale(I,.5);const B=$.clone(p);$.add(B,I);const L=[E,_];for(const Z of pf.current(t)){if(!R(t,Z,wt))continue;const M=wt.read(t,Z),F=A.write(t,Z),q=$.clone(M.position);$.add(q,[M.size[0]/2,M.size[1]/2]);const ue=$.clone(q);$.sub(ue,f),$.rotate(ue,-u),$.multiply(ue,L),v&&(ue[0]=-ue[0]),b&&(ue[1]=-ue[1]),$.rotate(ue,u);const se=$.clone(B);$.add(se,ue);const j=$.clone(M.size);$.multiply(j,L);const ee=ia(t,Z)===ot.Text;if(T.strict)if(ee&&r){j[1]=Math.max(T.rowHeight,Ht.snapY(t,j[1]));const fe=M.size[0]/M.size[1];j[0]=j[1]*fe}else Ht.snapSize(t,j);if($.copy(F.position,se),$.sub(F.position,[j[0]/2,j[1]/2]),T.strict&&Ht.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,yt)){const fe=a.kind===Xn.Stretch,Me=yt.write(t,Z);if(fe)Me.constrainWidth=!0;else{const Ce=M.size[1]>0?j[1]/M.size[1]:1;Me.fontSizePx=M.fontSize*Ce}}F.flip=[v!==M.flip[0],b!==M.flip[1]]}}var lP=ie(t=>t.with(A,xt)),g0=ie(t=>t.with(A,uc)),cP=ie(t=>t.with(A,me,Ve)),uP="z",dP=Se({phase:"update"},t=>{he(t,Hy,e=>{const n=Bt(e);Q(e,n,A,{tag:"selection-box",position:[0,0],size:[0,0],rotateZ:0,rank:uP}),Q(e,n,uc,{})}),he(t,Zy,(e,{bounds:n,deselectOthers:r})=>{const o=g0.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=I2(e,n,cP.current(e));if(r)for(const h of lP.current(e))!f.includes(h)&&Ta(e,h);for(const h of f)Ei(e,h)}),he(t,Ky,e=>{const n=g0.current(e);if(n.length===0){console.warn("Can't remove selection box: not found");return}const r=n[0];it(e,r)})}),yc=t=>Object.values(t).filter(e=>typeof e=="object"&&e!==null&&"_system"in e&&"phase"in e);function fP(t={}){return{name:n0,resources:kB.parse(t),components:Object.values(e0).filter(e=>e instanceof Gt),singletons:Object.values(o0).filter(e=>e instanceof kt),blockDefs:[{tag:"selection-box",stratum:"overlay",canRotate:!1,canScale:!1,components:[uc]},{tag:"transform-box",stratum:"overlay",canRotate:!1,canScale:!1,components:[en]},{tag:"transform-handle",stratum:"overlay",canRotate:!1,canScale:!1,components:[Ke]},{tag:"transform-edge",stratum:"overlay",canRotate:!1,canScale:!1,components:[Ke]},{tag:"transform-rotate",stratum:"overlay",canRotate:!1,canScale:!1,components:[Ke]}],systems:[...yc(l0),...yc(s0),...yc(u0),...yc(i0)],keybinds:[{command:Vy.name,key:dn.X,mod:!0},{command:Fy.name,key:dn.C,mod:!0},{command:jy.name,key:dn.V,mod:!0},{command:tf.name,key:dn.Delete},{command:Wy.name,key:dn.A,mod:!0},{command:zy.name,key:dn.BracketRight},{command:$y.name,key:dn.BracketLeft}],cursors:vB}}var hP=Object.defineProperty,y0=(t,e)=>{for(var n in e)hP(t,n,{get:e[n],enumerable:!0})},w0={};y0(w0,{ArcArrow:()=>xe,ArrowHandle:()=>tr,ArrowTerminal:()=>Aa,ElbowArrow:()=>Pe});var pP="arrows",v0="zzzzz",mP=24,k0=50,mf=4,gP=4,gf=24,Ao=24,b0=40,er={Idle:"idle",Pointing:"pointing",Dragging:"dragging"},_i={None:"none",Idle:"idle"},$e={Start:"start",Middle:"middle",End:"end"},De={None:"none",V:"v",Delta:"delta",Circle:"circle",Diamond:"diamond"},ys={Arc:"arc",Elbow:"elbow"},wc=0,vc=1,kc=2,bc=3,Sc=4,Ec=5,yf=6,yP={value:C.tuple(C.float64(),7).default([0,0,.5,.5,1,1,mf]),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 Gt{constructor(){super({name:"arcArrow",sync:"document"},yP)}getA(t,e){const{value:n}=this.read(t,e);return[n[wc],n[vc]]}getB(t,e){const{value:n}=this.read(t,e);return[n[kc],n[bc]]}getC(t,e){const{value:n}=this.read(t,e);return[n[Sc],n[Ec]]}getThickness(t,e){const{value:n}=this.read(t,e);return n[yf]}setA(t,e,n){const{value:r}=this.write(t,e);r[wc]=n[0],r[vc]=n[1]}setB(t,e,n){const{value:r}=this.write(t,e);r[kc]=n[0],r[bc]=n[1]}setC(t,e,n){const{value:r}=this.write(t,e);r[Sc]=n[0],r[Ec]=n[1]}setThickness(t,e,n){const{value:r}=this.write(t,e);r[yf]=n}getWorldArc(t,e){const{value:n}=this.read(t,e),r=A.uvToWorld(t,e,[n[wc],n[vc]]),o=A.uvToWorld(t,e,[n[kc],n[bc]]),s=A.uvToWorld(t,e,[n[Sc],n[Ec]]);return[r[0],r[1],o[0],o[1],s[0],s[1],n[yf]]}getWorldPoints(t,e){const{value:n}=this.read(t,e);return{a:A.uvToWorld(t,e,[n[wc],n[vc]]),b:A.uvToWorld(t,e,[n[kc],n[bc]]),c:A.uvToWorld(t,e,[n[Sc],n[Ec]])}}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 wP,tr=Qe({name:"arrowHandle"},{kind:C.enum($e).default($e.Start),arrowEntity:C.ref()}),Aa=Qe({name:"arrowTerminal"},{blockEntity:C.ref(),terminalIndex:C.uint8().default(0)}),vP={points:C.buffer(C.float64()).size(gf*2),pointCount:C.uint8().default(0),thickness:C.float32().default(mf),startArrowHead:C.enum(De).default(De.None),endArrowHead:C.enum(De).default(De.V),trimStart:C.float64().default(0),trimEnd:C.float64().default(1)},kP=class extends Gt{constructor(){super({name:"elbowArrow",sync:"document"},vP)}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>gf)throw new Error(`ElbowArrow points exceed capacity of ${gf}`);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}},Pe=new kP,S0={};y0(S0,{ArrowDrawState:()=>wf,ArrowTransformState:()=>E0});var wf=Co("arrowDrawState",{state:C.string().max(16).default(er.Idle),activeArrow:C.ref(),kind:C.enum(ys).default(ys.Elbow),pointingStartClient:C.tuple(C.int32(),2).default([0,0]),pointingStartWorld:C.tuple(C.float64(),2).default([0,0])}),E0=Co("arrowTransformState",{state:C.string().max(16).default(_i.None),activeArrow:C.ref()}),C0=pe("arrows-add-arrow"),_0=pe("arrows-remove-arrow"),x0=pe("arrows-add-or-update-transform-handles"),T0=pe("arrows-remove-transform-handles"),M0=pe("arrows-hide-transform-handles"),A0=pe("arrows-show-transform-handles"),bP=$r({guards:{isThresholdReached:({context:t,event:e})=>$.distance(t.pointingStartClient,e.screenPosition)>=gP},actions:{setPointingStart:He({pointingStartClient:({event:t})=>[t.screenPosition[0],t.screenPosition[1]],pointingStartWorld:({event:t})=>[t.worldPosition[0],t.worldPosition[1]]}),resetContext:He({pointingStartClient:()=>[0,0],pointingStartWorld:()=>[0,0],activeArrow:()=>null}),addArrow:He({activeArrow:({context:t,event:e})=>{const n=t.kind,r=t.pointingStartWorld,o=Bt(e.ctx);return C0.spawn(e.ctx,{entityId:o,position:r,kind:n}),o}}),removeArrow:He({activeArrow:({context:t,event:e})=>(t.activeArrow&&_0.spawn(e.ctx,{entityId:t.activeArrow}),null)}),exitArrowControl:({event:t})=>{const e=ut.write(t.ctx);e.leftMouseTool="select";const n=Nn.write(t.ctx);n.cursorKind="select"},deselectAll:({event:t})=>{Si.spawn(t.ctx)}}}).createMachine({id:"arrowDraw",initial:er.Idle,context:{activeArrow:null,kind:ys.Elbow,pointingStartClient:[0,0],pointingStartWorld:[0,0]},states:{[er.Idle]:{entry:"resetContext",on:{pointerDown:[{actions:"deselectAll",target:er.Pointing}]}},[er.Pointing]:{entry:"setPointingStart",on:{pointerMove:{guard:"isThresholdReached",target:er.Dragging},pointerUp:{target:er.Idle},cancel:{target:er.Idle}}},[er.Dragging]:{entry:"addArrow",exit:"exitArrowControl",on:{pointerUp:{target:er.Idle},cancel:{actions:"removeArrow",target:er.Idle}}}}}),SP=Se({phase:"capture",priority:100},t=>{const e=ut.getButtons(t,"arc-arrow","elbow-arrow");if(e.length===0)return;const n=jr(t,e);if(n.length===0)return;const r=ut.read(t).leftMouseTool,o=wf.write(t);o.kind=r==="elbow-arrow"?ys.Elbow:ys.Arc,wf.run(t,bP,n)}),vf=ie(t=>t.with(A).tracking(xt)),EP=$r({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:He({activeArrow:({event:t})=>!("selectedEntities"in t)||t.selectedEntities.length===0?null:t.selectedEntities[0]}),addOrUpdateTransformHandles:({context:t,event:e})=>{t.activeArrow&&x0.spawn(e.ctx,{arrowEntityId:t.activeArrow})},removeTransformHandles:({event:t})=>{T0.spawn(t.ctx,{})},hideTransformHandles:({event:t})=>{M0.spawn(t.ctx,{})},showTransformHandles:({event:t})=>{A0.spawn(t.ctx,{})}}}).createMachine({id:"arrowTransform",initial:_i.None,context:{activeArrow:null},states:{[_i.None]:{entry:"removeTransformHandles",on:{selectionChanged:[{guard:"selectingSingleArrow",actions:"setActiveArrow",target:_i.Idle}]}},[_i.Idle]:{entry:"addOrUpdateTransformHandles",on:{selectionChanged:[{guard:ss("selectingSingleArrow"),target:_i.None},{actions:["setActiveArrow","addOrUpdateTransformHandles"]}],pointerDown:{actions:"hideTransformHandles"},pointerUp:{actions:"showTransformHandles"}}}}}),CP=Se({phase:"capture",priority:99},t=>{const e=_P(t);e.length!==0&&E0.run(t,EP,e)});function _P(t){const e=[],n=vf.added(t),r=vf.removed(t);if(n.length>0||r.length>0){const i=[...vf.current(t)];e.push({type:"selectionChanged",ctx:t,selectedEntities:i})}const o=ut.getButtons(t,"select"),s=jr(t,o);return e.push(...s),e}var xP=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 TP(t,e,n,r,o,s,i){return new MP(t,e,n,s,i).calculate(r,o)}var MP=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=Ia(bt.origin(n),bt.origin(r)):o=this.routeBlockToBlock(t,e,n,r)}else t&&!e?this.isPointInsideBlockMargin(this.localEnd,t)?o=Ia(bt.origin(n),this.localEnd):o=this.routeBlockToPoint(t,n,this.localEnd):!t&&e?this.isPointInsideBlockMargin(this.localStart,e)?o=Ia(this.localStart,bt.origin(r)):o=this.routeBlockToPoint(e,r,this.localStart).reverse():o=Ia(bt.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 mt.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),BP(o,s);const i=PP(o,s),a=Cc(n,i),l=Cc(r,i),c=bt.origin(n),u=bt.origin(r);if(a===null||l===null)return console.warn("[routeBlockToBlock] Failed to add start or end node to graph"),[c,u];const f=P0(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),AP(h),I0(h),IP(h),h}routeBlockToPoint(t,e,n){const r=bt.origin(e),o=bt.direction(e),s=_c(r,n);if(o[0]===s[0]&&o[1]===s[1])return Ia(r,n);const i=this.getBlockAabb(t);ne.pad(i,this.padding);const a=bt.fromPoints(n,[-s[0],-s[1]]),l=bt.intersectAabb(a,i);l.length===0&&ne.expand(i,n);const c=ne.corners(i),u=N0(c),f=Cc(a,u),h=Cc(e,u);if(h===null||f===null)return[r,n];const p=P0(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),I0(m),m}calculateRay(t,e,n){let r;return n?r=this.exitClosestSide(t,n).direction:r=_c(t,e),bt.fromPoints(t,r)}exitClosestSide(t,e){const n=A.read(this.ctx,e),r=A.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=bt.fromPoints(s,g),w=bt.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=_c(t,this.localEnd),g=c.find(y=>y.direction[0]===m[0]&&y.direction[1]===m[1]);if(g)return g}return u}};function Ia(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=_c(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 AP(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 I0(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 IP(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=NP(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 NP(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0])>0?"left":"right"}function BP(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 N0(t){const e=t.map((n,r)=>({id:r,connections:[],distances:{},coords:n}));return B0(e,0),B0(e,1),e}function B0(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 PP(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 N0(a)}function Cc(t,e){const n=bt.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=bt.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 P0(t,e,n){const r={},o={},s=new xP;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 _c(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 O0(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 OP(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 DP(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 D0=20,RP=ie(t=>t.tracking(xe,Ze)),zP=ie(t=>t.tracking(Pe,Ze)),$P=Se({phase:"update",priority:-10},t=>{for(const e of RP.addedOrChanged(t))LP(t,e);for(const e of zP.addedOrChanged(t))VP(t,e)});function LP(t,e){R(t,e,Te)||Q(t,e,Te,{});const n=xe.read(t,e),r=Re.clone(n.value);r[6]=Math.max(r[6],D0),Te.clear(t,e),Te.addArc(t,e,r),FP(t,e)}function VP(t,e){R(t,e,Te)||Q(t,e,Te,{});const n=Pe.read(t,e),r=Math.max(n.thickness,D0),o=Pe.getPoints(t,e),s=Te.write(t,e),i=Math.min(o.length-1,di);s.capsuleCount=i,s.arcCount=0;for(let a=0;a<i;a++){const l=o[a],c=o[a+1],u=pt.create(l[0],l[1],c[0],c[1],r/2);Te.setCapsuleAt(t,e,a,u)}jP(t,e)}function FP(t,e){const n=Ze.read(t,e),r=xe.getWorldArc(t,e),{a:o,c:s}=xe.getWorldPoints(t,e);let i=R0(t,n.startBlock,r,o),a=R0(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=Te.read(t,e);for(let u=0;u<c.arcCount;u++){const f=Te.getArcAt(t,e,u);Re.trim(f,i,1-a),Te.setArcAt(t,e,u,f)}}function R0(t,e,n,r){if(!e)return 0;const o=A.getCorners(t,e),s=Re.intersectRect(n,o);if(s.length===0)return 0;const i=O0(s,r);return i?Re.pointToParametric(n,i)??0:0}function jP(t,e){const n=Ze.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=z0(t,n.startBlock,s,a),u=z0(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=Te.getCapsuleAt(t,e,0);pt.trim(h,c,1),Te.setCapsuleAt(t,e,0,h);const p=o-1,m=Te.getCapsuleAt(t,e,p);pt.trim(m,0,1-u),Te.setCapsuleAt(t,e,p,m)}function z0(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=UP(n,r,h,p);m&&s.push(m)}if(s.length===0)return 0;const i=O0(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 UP(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 xc=ie(t=>t.with(tr,A)),WP=ie(t=>t.with(me,Ve).tracking(A)),$0=ie(t=>t.with(Aa,A)),HP=Se({phase:"update"},t=>{he(t,C0,(e,{entityId:n,position:r,kind:o})=>{KP(e,n,r,o)}),he(t,_0,(e,{entityId:n})=>{YP(e,n)}),he(t,x0,(e,{arrowEntityId:n})=>{kf(e,n)}),he(t,T0,e=>{QP(e)}),he(t,M0,e=>{bf(e)}),he(t,A0,e=>{eO(e)}),he(t,_a,(e,{entityId:n,position:r})=>{qP(e,n,r)}),ZP(t)});function ZP(t){const e=WP.addedOrChangedOrRemoved(t);if(e.length===0)return;const n=new Set;for(const r of e){const o=fr(t,r,Ze,"startBlock",!1);for(const i of o)n.has(i)||(n.add(i),L0(t,i));const s=fr(t,r,Ze,"endBlock",!1);for(const i of s)n.has(i)||(n.add(i),L0(t,i))}}function L0(t,e){const n=Ze.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=A.uvToWorld(t,n.startBlock,n.startBlockUv),Sf(t,e,$e.Start,s)),n.endBlock!==null&&(i=A.uvToWorld(t,n.endBlock,n.endBlockUv),Sf(t,e,$e.End,i))}else if(R(t,e,Pe)){if(n.startBlock!==null){const r=A.uvToWorld(t,n.startBlock,n.startBlockUv);Ef(t,e,$e.Start,r)}if(n.endBlock!==null){const r=A.uvToWorld(t,n.endBlock,n.endBlockUv);Ef(t,e,$e.End,r)}}}function KP(t,e,n,r){const o=mf,s=r===ys.Elbow?"elbow-arrow":"arc-arrow",a=ds.getAll(t).find(h=>R(t,h,me)&&Cf(t,h))??null;let l=n,c=[0,0];if(a!==null){const h=_f(t,a,n);h!==null?(l=h.position,c=h.uv):(l=A.uvToWorld(t,a,[.5,.5]),c=[.5,.5])}Q(t,e,A,{tag:s,rank:Zn.genNext(t),position:l,size:[o,o]}),Q(t,e,me,{id:crypto.randomUUID()}),r===ys.Arc?Q(t,e,xe,{value:[0,0,.5,.5,1,1,o],startArrowHead:De.None,endArrowHead:De.V}):Q(t,e,Pe,{points:[0,0,.5,0,.5,1,1,1],pointCount:4,thickness:o,startArrowHead:De.None,endArrowHead:De.V}),Q(t,e,Ze,{startBlock:a,startBlockUv:c}),Ei(t,e);const f=kf(t,e).find(h=>tr.read(t,h).kind===$e.End);if(f){const h=A.read(t,f),p=Qn.write(t);p.state=_e.Dragging,p.draggedEntity=f,p.dragStart=l,p.draggedEntityStart=[h.position[0],h.position[1]],bf(t)}}function YP(t,e){it(t,e)}function qP(t,e,n){R(t,e,xe)?GP(t,e):R(t,e,Pe)?JP(t,e):R(t,e,tr)&&XP(t,e,n)}function GP(t,e){const n=Ze.read(t,e);if(n.startBlock!==null){const{a:r}=xe.getWorldPoints(t,e);Na(t,e,$e.Start,r)}if(n.endBlock!==null){const{c:r}=xe.getWorldPoints(t,e);Na(t,e,$e.End,r)}}function JP(t,e){const n=Ze.read(t,e);if(n.startBlock!==null){const r=Pe.getStartWorld(t,e);Na(t,e,$e.Start,r)}if(n.endBlock!==null){const r=Pe.getEndWorld(t,e);Na(t,e,$e.End,r)}}function XP(t,e,n){const r=tr.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=sO(t,o,r.kind,i);a!==null&&(i=a)}R(t,o,xe)?Sf(t,o,r.kind,i):R(t,o,Pe)&&Ef(t,o,r.kind,i),r.kind!==$e.Middle&&Na(t,o,r.kind,i)}function kf(t,e){const n=mP,r=[$e.Start,$e.End];R(t,e,xe)&&r.push($e.Middle);const o=Array.from(xc.current(t)),s=new Map;for(const l of o){const c=tr.read(t,l);s.set(c.kind,l)}const i=new Set;for(const l of r){const c=tO(t,e,l),u=c[0]-n/2,f=c[1]-n/2;let h=s.get(l);h||(h=Bt(t),Q(t,h,tr),Q(t,h,A),Q(t,h,So),Q(t,h,Ke,{kind:"arrow"}));const p=tr.write(t,h);p.kind=l,p.arrowEntity=e;const m=A.write(t,h);m.tag="arrow-handle",m.rank=v0,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)||it(t,l);const a=Qn.read(t);return a.state===_e.Dragging&&a.draggedEntity!==null&&R(t,a.draggedEntity,tr)&&bf(t),Array.from(i)}function QP(t){for(const e of xc.current(t))it(t,e);Tc(t)}function bf(t){for(const e of xc.current(t))if(!R(t,e,ct))Q(t,e,ct,{value:0});else{const n=ct.write(t,e);n.value=0}}function eO(t){const e=xc.current(t);for(const n of e)R(t,n,ct)&&mn(t,n,ct);if(e.length>0){const n=tr.read(t,e[0]);n.arrowEntity&&kf(t,n.arrowEntity)}Tc(t)}function tO(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 Sf(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}=OP(u,r,f);l=DP(s,w,.5*v,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],xe.setA(t,e,A.worldToUv(t,e,a)),xe.setB(t,e,A.worldToUv(t,e,l)),xe.setC(t,e,A.worldToUv(t,e,c))}function Ef(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=Pe.getEndWorld(t,e)):(o.startBlock!==null?s=A.uvToWorld(t,o.startBlock,o.startBlockUv):s=Pe.getStartWorld(t,e),i=r);const l=A.read(t,e).rotateZ||0,c=TP(t,s,i,o.startBlock,o.endBlock,k0,l),u=A.write(t,e),f=[0,0],h=[1,1];mt.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));Pe.setPoints(t,e,p)}function Na(t,e,n,r){let s=ds.getAll(t).find(l=>l!==e&&R(t,l,me)&&!R(t,l,Ze)&&Cf(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?oO(t,s):Tc(t);let a=[0,0];if(s!==null){const l=_f(t,s,r,b0);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),nO(t,e)}function nO(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=$l(r,null)}}function Cf(t,e){const n=A.read(t,e).tag;return Kn(t,n).connectors.enabled}function rO(t){const e=$0.current(t);return e.length===0?null:Aa.read(t,e[0]).blockEntity}function oO(t,e){if(rO(t)===e)return;Tc(t);const n=A.read(t,e).tag,r=Kn(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);Q(t,l,Aa,{blockEntity:e,terminalIndex:s}),Q(t,l,A,{tag:"arrow-terminal",rank:v0,position:[a[0]-Ao/2,a[1]-Ao/2],size:[Ao,Ao]}),Q(t,l,So,{startPosition:[a[0]-Ao/2,a[1]-Ao/2],startSize:[Ao,Ao]})}}function Tc(t){for(const e of $0.current(t))it(t,e)}function _f(t,e,n,r){const o=A.read(t,e).tag,s=Kn(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 sO(t,e,n,r){const s=ds.getAll(t).find(c=>c!==e&&R(t,c,me)&&!R(t,c,Ze)&&Cf(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=_f(t,s,r,b0);return l===null?null:l.position}function iO(t={}){return{name:pP,components:Object.values(w0).filter(e=>e instanceof Gt),singletons:Object.values(S0).filter(e=>e instanceof kt),blockDefs:[{tag:"arc-arrow",resizeMode:ot.GroupOnly,components:[xe,Ze,In],connectors:{enabled:!1}},{tag:"elbow-arrow",resizeMode:ot.GroupOnly,components:[Pe,Ze,In],connectors:{enabled:!1}},{tag:"arrow-handle",stratum:"overlay",canRotate:!1,canScale:!1,components:[tr],connectors:{enabled:!1}},{tag:"arrow-terminal",stratum:"overlay",canRotate:!1,canScale:!1,components:[Aa],connectors:{enabled:!1}}],systems:[SP,CP,HP,$P],resources:{elbowArrowPadding:t.elbowArrowPadding??k0}}}const xf=[{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 xi(t){return xf.find(e=>e.kind===t)}const V0=Symbol.for("__woven_canvas_dropdown_active__"),F0=Symbol.for("__woven_canvas_dropdown_level__"),j0=Symbol.for("__woven_canvas_floating_menu__"),Tf=Symbol.for("__woven_canvas_toolbar__"),U0=Symbol.for("__woven_canvas_tooltip__"),On=Symbol.for("__woven_canvas__");function Tt(t,e){const n=d.inject(On);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 aO={key:0},lO=["x1","y1","x2","y2","stroke","stroke-width"],cO=["x1","y1","x2","y2","stroke","stroke-width"],uO=["points","fill"],dO=["cx","cy","r","fill"],fO=["points","fill"],hO=15,pO=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/pO)**.33,c=hO*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",aO,[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,lO),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,cO)],64)):t.kind===d.unref(De).Delta&&o.value?(d.openBlock(),d.createElementBlock("polygon",{key:1,points:o.value,fill:t.color},null,8,uO)):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,dO)):t.kind===d.unref(De).Diamond&&i.value?(d.openBlock(),d.createElementBlock("polygon",{key:3,points:i.value,fill:t.color},null,8,fO)):d.createCommentVNode("",!0)])):d.createCommentVNode("",!0)}}),mO={class:"arrow-svg",preserveAspectRatio:"none"},gO=["d","stroke","stroke-width"],yO=["x1","y1","x2","y2","stroke","stroke-width"],wO=["d"],vO=["x1","y1","x2","y2"],kO=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,q,ue,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=((q=xi(S))==null?void 0:q.gap)??0,ee=E>0?j/E:0;_+=ee}let T=i.value.trimEnd;if((ue=e.connector)!=null&&ue.endBlock&&k!=="none"){const j=((se=xi(k))==null?void 0:se.gap)??0,ee=E>0?j/E:0;T+=ee}const I=1-T,B=Re.parametricToPoint(b,_),L=Re.parametricToPoint(b,I),Z=v(Re.directionAt(b,_)),M=Re.directionAt(b,I);return{start:B,end:L,startDir:Z,endDir:M,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:T,arcAngle:I}=m.value,L=I*(E-k)>Math.PI?1:0,Z=T?0:1;return`M ${b[0]} ${b[1]} A ${_} ${_} 0 ${L} ${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",mO,[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,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,stroke:l.value,fill:"none","stroke-width":u.value,"stroke-linecap":"round"},null,8,yO)):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,wO)):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,vO)):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))}}),ws=(t,e)=>{const n=t.__vccOpts||t;for(const[r,o]of e)n[r]=o;return n},W0=ws(kO,[["__scopeId","data-v-bcf5b4f3"]]),bO={},SO={class:"wov-arrow-handle"};function EO(t,e){return d.openBlock(),d.createElementBlock("div",SO,[...e[0]||(e[0]=[d.createElementVNode("div",{class:"wov-arrow-handle-inner"},null,-1)])])}const H0=ws(bO,[["render",EO]]),CO={},_O={class:"wov-arrow-terminal"};function xO(t,e){return d.openBlock(),d.createElementBlock("div",_O,[...e[0]||(e[0]=[d.createElementVNode("div",{class:"wov-arrow-terminal-ring"},[d.createElementVNode("div",{class:"wov-arrow-terminal-fill"})],-1)])])}const Z0=ws(CO,[["render",xO]]),TO={class:"arrow-svg",preserveAspectRatio:"none"},MO=["x1","y1","x2","y2"],AO=["x1","y1","x2","y2","stroke","stroke-width"],IO=["x1","y1","x2","y2"],K0=ws(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,B,L,Z;if(!i.value||h.value.length<2)return null;const g=i.value,y=[...h.value.map(M=>[...M])],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 M=Math.hypot(b[0],b[1]),F=((B=xi(w))==null?void 0:B.gap)??0,q=M>0?F/M:0;k+=q}let E=g.trimEnd;if((L=e.connector)!=null&&L.endBlock&&v!=="none"){const M=Math.hypot(S[0],S[1]),F=((Z=xi(v))==null?void 0:Z.gap)??0,q=M>0?F/M:0;E+=q}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 T=[];for(let M=0;M<y.length-1;M++)T.push({start:y[M],end:y[M+1]});return $.scale(b,-1),{points:y,lines:T,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",TO,[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,MO))),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,AO))),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,IO))),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 NO=Object.defineProperty,Mf=(t,e)=>{for(var n in e)NO(t,n,{get:e[n],enumerable:!0})},Y0=pe("start-eraser-stroke"),q0=pe("add-eraser-stroke-point"),G0=pe("complete-eraser-stroke"),J0=pe("cancel-eraser-stroke"),X0={};Mf(X0,{Erased:()=>vs,EraserStroke:()=>Ba});var vs=Qe({name:"erased"},{eraserStrokeId:C.ref()}),Ti=8,BO="eraser",kr=20,Ba=Qe({name:"eraserStroke"},{points:C.buffer(C.float32()).size(kr*2),pointCount:C.uint32().default(0),firstPointIndex:C.uint32().default(0),radius:C.float32().default(8)}),Q0={};Mf(Q0,{EraserStateSingleton:()=>Af});var ks={Idle:"idle",Erasing:"erasing"},Af=Co("eraserState",{state:C.string().max(16).default(ks.Idle),activeStroke:C.ref(),lastWorldPosition:C.tuple(C.float64(),2).default([0,0])}),ew={};Mf(ew,{captureEraserSystem:()=>OO,updateEraserSystem:()=>zO});var PO=$r({guards:{},actions:{startStroke:({event:t})=>{Y0.spawn(t.ctx,{worldPosition:t.worldPosition})},addPoint:He({lastWorldPosition:({event:t,context:e})=>e.activeStroke?(q0.spawn(t.ctx,{strokeId:e.activeStroke,worldPosition:t.worldPosition}),[t.worldPosition[0],t.worldPosition[1]]):e.lastWorldPosition}),completeStroke:({event:t,context:e})=>{e.activeStroke&&G0.spawn(t.ctx,{strokeId:e.activeStroke})},cancelStroke:({event:t,context:e})=>{e.activeStroke&&J0.spawn(t.ctx,{strokeId:e.activeStroke})},resetContext:He({activeStroke:()=>null,lastWorldPosition:()=>[0,0]})}}).createMachine({id:"eraser",initial:ks.Idle,context:{activeStroke:null,lastWorldPosition:[0,0]},states:{[ks.Idle]:{entry:["resetContext"],on:{pointerDown:{target:ks.Erasing,actions:["startStroke"]}}},[ks.Erasing]:{on:{pointerMove:{actions:["addPoint"]},frame:{actions:["addPoint"]},pointerUp:{target:ks.Idle,actions:["completeStroke"]},cancel:{target:ks.Idle,actions:["cancelStroke"]}}}}}),OO=Se({phase:"capture",priority:100},t=>{const e=ut.getButtons(t,"eraser"),n=jr(t,e,{includeFrameEvent:!0});n.length!==0&&Af.run(t,PO,n)}),DO=ie(t=>t.with(A,me,Ve)),RO=ie(t=>t.with(vs)),zO=Se({phase:"update"},t=>{he(t,Y0,(e,{worldPosition:n})=>{$O(e,n)}),he(t,q0,(e,{strokeId:n,worldPosition:r})=>{LO(e,n,r)}),he(t,G0,(e,{strokeId:n})=>{jO(e,n)}),he(t,J0,(e,{strokeId:n})=>{UO(e,n)})});function $O(t,e){const n=Bt(t);Q(t,n,A,{tag:"eraser",rank:Zn.genNext(t),position:[e[0]-Ti,e[1]-Ti],size:[Ti*2,Ti*2]}),Q(t,n,Ba,{points:e,pointCount:1,firstPointIndex:0,radius:Ti});const r=Af.write(t);r.activeStroke=n,r.lastWorldPosition=e}function LO(t,e,n){const r=Ba.write(t,e),o=r.pointCount,s=(o-1)%kr*2,i=r.points[s],a=r.points[s+1],l=o%kr*2;if(r.points[l]=n[0],r.points[l+1]=n[1],r.pointCount++,r.pointCount>kr&&(r.firstPointIndex=(r.pointCount-kr)%kr),!Ve.containsPoint(t,e,n)){Ve.expandByPoint(t,e,n);const{value:g}=Ve.read(t,e),y=A.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=pt.create(i,a,n[0],n[1],Ti),p=VO(t,DO.current(t)),m=B2(t,h,p);for(const g of m)FO(t,g,e)}function*VO(t,e){for(const n of e)R(t,n,vs)||(yield n)}function FO(t,e,n){Q(t,e,vs,{eraserStrokeId:n}),Q(t,e,ct,{value:80})}function jO(t,e){const n=fr(t,e,vs,"eraserStrokeId");for(const r of n)it(t,r);it(t,e)}function UO(t,e){const n=[];for(const r of RO.current(t))vs.read(t,r).eraserStrokeId===e&&n.push(r);for(const r of n)mn(t,r,vs),mn(t,r,ct);it(t,e)}var WO=t=>Object.values(t).filter(e=>typeof e=="object"&&e!==null&&"_system"in e&&"phase"in e),HO=Un({tailRadius:Xt().positive().optional(),tailLength:Xt().int().min(1).max(kr).optional()});function ZO(t={}){const e=HO.parse(t);return{name:BO,components:Object.values(X0).filter(n=>n instanceof Gt),singletons:Object.values(Q0).filter(n=>n instanceof kt),blockDefs:[{tag:"eraser-stroke",stratum:"overlay",canRotate:!1,canScale:!1,components:[Ba]}],systems:WO(ew),resources:{tailRadius:e.tailRadius??8,tailLength:e.tailLength??kr}}}const{PI:KO}=Math,Pa=KO+1e-4,tw=.5,nw=[1,1];function rw(t,e,n,r=o=>o){return t*r(.5-e*(.5-n))}const{min:If}=Math;function ow(t,e,n){let r=If(1,e/n);return If(1,t+(If(1,1-r)-t)*(r*.275))}function YO(t){return[-t[0],-t[1]]}function br(t,e){return[t[0]+e[0],t[1]+e[1]]}function sw(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[0],t[1]-e[1]]}function Nf(t,e,n){return t[0]=e[0]-n[0],t[1]=e[1]-n[1],t}function No(t,e){return[t[0]*e,t[1]*e]}function Bf(t,e,n){return t[0]=e[0]*n,t[1]=e[1]*n,t}function qO(t,e){return[t[0]/e,t[1]/e]}function iw(t){return[t[1],-t[0]]}function Pf(t,e){let n=e[0];return t[0]=e[1],t[1]=-n,t}function aw(t,e){return t[0]*e[0]+t[1]*e[1]}function GO(t,e){return t[0]===e[0]&&t[1]===e[1]}function JO(t){return Math.hypot(t[0],t[1])}function lw(t,e){let n=t[0]-e[0],r=t[1]-e[1];return n*n+r*r}function cw(t){return qO(t,JO(t))}function XO(t,e){return Math.hypot(t[1]-e[1],t[0]-e[0])}function Of(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 uw(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 dw(t,e,n){return br(t,No(Io(e,t),n))}function QO(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 fw(t,e,n){return br(t,No(e,n))}const $t=[0,0],Bo=[0,0],Po=[0,0];function eD(t,e){let n=fw(t,cw(iw(Io(t,br(t,[1,1])))),-e),r=[],o=1/13;for(let s=o;s<=1;s+=o)r.push(Of(n,t,Pa*2*s));return r}function tD(t,e,n){let r=[],o=1/n;for(let s=o;s<=1;s+=o)r.push(Of(e,t,Pa*s));return r}function nD(t,e,n){let r=Io(e,n),o=No(r,.5),s=No(r,.51);return[Io(t,o),Io(t,s),br(t,s),br(t,o)]}function rD(t,e,n,r){let o=[],s=fw(t,e,n),i=1/r;for(let a=i;a<1;a+=i)o.push(Of(s,t,Pa*3*a));return o}function oD(t,e,n){return[br(t,No(e,n)),br(t,No(e,n*.99)),Io(t,No(e,n*.99)),Io(t,No(e,n))]}function hw(t,e,n){return t===!1||t===void 0?0:t===!0?Math.max(e,n):t}function sD(t,e,n){return t.slice(0,10).reduce((r,o)=>{let s=o.pressure;return e&&(s=ow(r,o.distance,n)),(r+s)/2},t[0].pressure)}function iD(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=hw(a.taper,n,m),y=hw(l.taper,n,m),w=(n*r)**2,v=[],b=[],S=sD(t,s,n),k=rw(n,o,t[t.length-1].pressure,i),E,_=t[0].vector,T=t[0].point,I=T,B=T,L=I,Z=!1;for(let se=0;se<t.length;se++){let{pressure:j}=t[se],{point:ee,vector:fe,distance:Me,runningLength:Ce}=t[se],qe=se===t.length-1;if(!qe&&m-Ce<3)continue;o?(s&&(j=ow(S,Me,n)),k=rw(n,o,j,i)):k=n/2,E===void 0&&(E=k);let lr=Ce<g?f(Ce/g):1,so=m-Ce<y?p((m-Ce)/y):1;k=Math.max(.01,k*Math.min(lr,so));let Ys=(qe?t[se]:t[se+1]).vector,Xo=qe?1:aw(fe,Ys),Lu=aw(fe,_)<0&&!Z,Hi=Xo!==null&&Xo<0;if(Lu||Hi){Pf($t,_),Bf($t,$t,k);for(let Qo=0;Qo<=1;Qo+=.07692307692307693)Nf(Bo,ee,$t),uw(Bo,Bo,ee,Pa*Qo),B=[Bo[0],Bo[1]],v.push(B),sw(Po,ee,$t),uw(Po,Po,ee,Pa*-Qo),L=[Po[0],Po[1]],b.push(L);T=B,I=L,Hi&&(Z=!0);continue}if(Z=!1,qe){Pf($t,fe),Bf($t,$t,k),v.push(Io(ee,$t)),b.push(br(ee,$t));continue}QO($t,Ys,fe,Xo),Pf($t,$t),Bf($t,$t,k),Nf(Bo,ee,$t),B=[Bo[0],Bo[1]],(se<=1||lw(T,B)>w)&&(v.push(B),T=B),sw(Po,ee,$t),L=[Po[0],Po[1]],(se<=1||lw(I,L)>w)&&(b.push(L),I=L),S=j,_=fe}let M=[t[0].point[0],t[0].point[1]],F=t.length>1?[t[t.length-1].point[0],t[t.length-1].point[1]]:br(t[0].point,[1,1]),q=[],ue=[];if(t.length===1){if(!(g||y)||c)return eD(M,E||k)}else{g||y&&t.length===1||(u?q.push(...tD(M,b[0],13)):q.push(...nD(M,v[0],b[0])));let se=iw(YO(t[t.length-1].vector));y||g&&t.length===1?ue.push(F):h?ue.push(...rD(F,se,k,29)):ue.push(...oD(F,se,k))}return v.concat(ue,b.reverse(),q)}const pw=[0,0];function mw(t){return t!=null&&t>=0}function aD(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=tw})=>[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(dw(i[0],p,m/4))}i.length===1&&(i=[...i,[...br(i[0],nw),...i[0].slice(2)]]);let a=[{point:[i[0][0],i[0][1]],pressure:mw(i[0][2])?i[0][2]:.25,vector:[...nw],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]]:dw(u.point,i[p],s);if(GO(u.point,m))continue;let g=XO(m,u.point);if(c+=g,p<f&&!l){if(c<r)continue;l=!0}Nf(pw,u.point,m),u={point:m,pressure:mw(i[p][2])?i[p][2]:tw,vector:cw(pw),distance:g,runningLength:c},a.push(u)}return a[0].vector=((h=a[1])==null?void 0:h.vector)||[0,0],a}function Df(t,e={}){return iD(aD(t,e),e)}const lD={class:"wov-eraser-stroke"},cD={preserveAspectRatio:"none"},uD=["d"],dD="#88888833",gw=d.defineComponent({__name:"Eraser",props:{entityId:{}},setup(t){const e=t,n=Tt(e.entityId,Ba),r=Tt(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,kr);for(let S=0;S<m;S++){const k=(l+S)%kr*2;p.push([c[k]-f,c[k+1]-h])}const g=Df(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",lD,[(d.openBlock(),d.createElementBlock("svg",cD,[d.createElementVNode("path",{d:o.value,fill:dD},null,8,uD)]))]))}}),fD={class:"wov-image-block"},hD={key:0,class:"wov-image-placeholder"},pD={key:1,class:"wov-image-placeholder wov-image-error"},mD=["src","alt"],gD={key:3,class:"wov-image-upload-overlay"},yD={class:"wov-image-upload-status"},yw=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(On);if(!n)throw new Error("ImageBlock must be used within a WovenCanvas component");const r=n,o=Tt(e.entityId,cs),s=Tt(e.entityId,ea),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===gr.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 gr.Pending:return"Loading...";case gr.Uploading:return"Loading...";case gr.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",fD,[a.value&&!i.value?(d.openBlock(),d.createElementBlock("div",hD,[...m[0]||(m[0]=[d.createElementVNode("span",null,"Loading...",-1)])])):l.value?(d.openBlock(),d.createElementBlock("div",pD,[...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,mD)):d.createCommentVNode("",!0),f.value?(d.openBlock(),d.createElementBlock("div",gD,[d.createElementVNode("span",yD,d.toDisplayString(f.value),1)])):d.createCommentVNode("",!0)])}}});function wD(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ww={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})()})(ww);var vD=ww.exports;const vw=wD(vD);var kD=Object.defineProperty,Rf=(t,e)=>{for(var n in e)kD(t,n,{get:e[n],enumerable:!0})},kw=pe("start-pen-stroke"),bw=pe("add-pen-stroke-point"),Sw=pe("complete-pen-stroke"),Ew=pe("remove-pen-stroke"),Cw={};Rf(Cw,{POINTS_CAPACITY:()=>Mc,PenStroke:()=>nr});var Mc=256,bD={points:C.buffer(C.float32()).size(Mc*2),pressures:C.buffer(C.float32()).size(Mc),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)},SD=class extends Gt{constructor(){super({name:"penStroke",sync:"document"},bD)}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}},nr=new SD,ED=8,CD="pen",_w={};Rf(_w,{PenStateSingleton:()=>zf});var bs={Idle:"idle",Drawing:"drawing"},zf=Co("penState",{state:C.string().max(16).default(bs.Idle),activeStroke:C.ref(),lastWorldPosition:C.tuple(C.float64(),2).default([0,0])}),xw={};Rf(xw,{capturePenSystem:()=>xD,updatePenSystem:()=>MD});var _D=$r({guards:{},actions:{startStroke:({event:t})=>{const e=t.pointerType===Vr.Pen?t.pressure:null;kw.spawn(t.ctx,{worldPosition:t.worldPosition,pressure:e,thickness:ED})},addPoint:He({lastWorldPosition:({event:t,context:e})=>{if(!e.activeStroke)return e.lastWorldPosition;const n=t.pointerType===Vr.Pen?t.pressure:null;return bw.spawn(t.ctx,{strokeId:e.activeStroke,worldPosition:t.worldPosition,pressure:n}),t.worldPosition}}),completeStroke:({event:t,context:e})=>{e.activeStroke&&Sw.spawn(t.ctx,{strokeId:e.activeStroke})},removeStroke:({event:t,context:e})=>{e.activeStroke&&Ew.spawn(t.ctx,{strokeId:e.activeStroke})},resetContext:He({activeStroke:()=>null,lastWorldPosition:()=>[0,0]})}}).createMachine({id:"pen",initial:bs.Idle,context:{activeStroke:null,lastWorldPosition:[0,0]},states:{[bs.Idle]:{entry:["resetContext"],on:{pointerDown:{target:bs.Drawing,actions:["startStroke"]}}},[bs.Drawing]:{on:{pointerMove:{actions:["addPoint"]},pointerUp:{target:bs.Idle,actions:["completeStroke"]},cancel:{target:bs.Idle,actions:["removeStroke"]}}}}}),xD=Se({phase:"capture",priority:100},t=>{const e=ut.getButtons(t,"pen"),n=jr(t,e);n.length!==0&&zf.run(t,_D,n)}),TD=ie(t=>t.tracking(nr)),MD=Se({phase:"update"},t=>{he(t,kw,(e,{worldPosition:n,pressure:r,thickness:o})=>{AD(e,n,r,o)}),he(t,bw,(e,{strokeId:n,worldPosition:r,pressure:o})=>{ID(e,n,r,o)}),he(t,Sw,(e,{strokeId:n})=>{ND(e,n)}),he(t,Ew,(e,{strokeId:n})=>{BD(e,n)});for(const e of TD.addedOrChanged(t))nr.read(t,e).isComplete&&Tw(t,e)});function AD(t,e,n,r){const o=r/2,s=Bt(t);Q(t,s,me,{id:crypto.randomUUID()}),Q(t,s,A,{tag:"pen-stroke",rank:Zn.genNext(t),position:[e[0]-o,e[1]-o],size:[o*2,o*2]}),Q(t,s,In,{});const{sessionId:i}=Ge(t);Q(t,s,Rt,{sessionId:i});const a=n!==null;Q(t,s,nr,{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=zf.write(t);c.activeStroke=s,c.lastWorldPosition=e}function ID(t,e,n,r){const o=nr.write(t,e),s=o.pointCount;if(!(s>=Mc)&&(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=A.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 ND(t,e){const n=nr.write(t,e);n.isComplete=!0,mn(t,e,Rt),Tw(t,e)}function BD(t,e){it(t,e)}function Tw(t,e){const n=nr.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=vw(r,o,!1);for(;s.length-1>di;)o*=2,s=vw(r,o,!1);if(s.length===1){const u=s[0];s.push({x:u.x,y:u.y})}R(t,e,Te)?Te.clear(t,e):Q(t,e,Te,{});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];Te.addCapsuleUv(t,e,p,m,n.thickness)}}var PD=t=>Object.values(t).filter(e=>typeof e=="object"&&e!==null&&"_system"in e&&"phase"in e);function OD(){return{name:CD,components:Object.values(Cw).filter(t=>t instanceof Gt),singletons:Object.values(_w).filter(t=>t instanceof kt),blockDefs:[{tag:"pen-stroke",resizeMode:ot.Free,components:[nr,In],connectors:{enabled:!1}}],systems:PD(xw),resources:{}}}const DD=["data-complete"],RD={preserveAspectRatio:"none"},zD=["d","fill"],$D={key:0,class:"highlight",preserveAspectRatio:"none"},LD=["d"],Mw=ws(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,nr),r=Tt(e.entityId,A),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=Df(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=Df(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",RD,[d.createElementVNode("path",{d:s.value,fill:c.value},null,8,zD)])),u.value?(d.openBlock(),d.createElementBlock("svg",$D,[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,LD)])):d.createCommentVNode("",!0)],8,DD)}}}),[["__scopeId","data-v-9b41c649"]]);function dt(){const t=d.inject(On);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 Oa={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 Lt(t){this.content=t}Lt.prototype={constructor:Lt,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 Lt(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 Lt(n)},addToStart:function(t,e){return new Lt([t,e].concat(this.remove(t).content))},addToEnd:function(t,e){var n=this.remove(t).content.slice();return n.push(t,e),new Lt(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 Lt(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=Lt.from(t),t.size?new Lt(t.content.concat(this.subtract(t).content)):this},append:function(t){return t=Lt.from(t),t.size?new Lt(this.subtract(t).content.concat(t.content)):this},subtract:function(t){var e=this;t=Lt.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}},Lt.from=function(t){if(t instanceof Lt)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new Lt(e)};function Aw(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=Aw(o.content,s.content,n+1);if(i!=null)return i}n+=o.nodeSize}}function Iw(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=Iw(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 Aw(this,e,n)}findDiffEnd(e,n=this.size,r=e.size){return Iw(this,e,n,r)}findIndex(e){if(e==0)return Ac(0,e);if(e==this.size)return Ac(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?Ac(n+1,s):Ac(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 $f={index:0,offset:0};function Ac(t,e){return $f.index=t,$f.offset=e,$f}function Ic(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(!Ic(t[r],e[r]))return!1}else{for(let r in t)if(!(r in e)||!Ic(t[r],e[r]))return!1;for(let r in e)if(!(r in t))return!1}return!0}let Fe=class Cp{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&&Ic(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 Cp.none;if(e instanceof Cp)return[e];let n=e.slice();return n.sort((r,o)=>r.type.rank-o.type.rank),n}};Fe.none=[];class Nc 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=Bw(this.content,e+this.openStart,n);return r&&new K(r,this.openStart,this.openEnd)}removeBetween(e,n){return new K(Nw(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 Nw(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(Nw(s.content,e-o-1,n-o-1)))}function Bw(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=Bw(i.content,e-s-1,n,i);return a&&t.replaceChild(o,i.copy(a))}function VD(t,e,n){if(n.openStart>t.depth)throw new Nc("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new Nc("Inconsistent open depths");return Pw(t,e,n,0)}function Pw(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=Pw(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 Es(i,a.cut(0,t.parentOffset).append(n.content).append(a.cut(e.parentOffset)))}else{let{start:i,end:a}=FD(n,t);return Es(s,Dw(t,i,a,e,r))}else return Es(s,Bc(t,e,r))}function Ow(t,e){if(!e.type.compatibleContent(t.type))throw new Nc("Cannot join "+e.type.name+" onto "+t.type.name)}function Lf(t,e,n){let r=t.node(n);return Ow(r,e.node(n)),r}function Ss(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 Da(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&&(Ss(t.nodeAfter,r),s++));for(let a=s;a<i;a++)Ss(o.child(a),r);e&&e.depth==n&&e.textOffset&&Ss(e.nodeBefore,r)}function Es(t,e){return t.type.checkContent(e),t.copy(e)}function Dw(t,e,n,r,o){let s=t.depth>o&&Lf(t,e,o+1),i=r.depth>o&&Lf(n,r,o+1),a=[];return Da(null,t,o,a),s&&i&&e.index(o)==n.index(o)?(Ow(s,i),Ss(Es(s,Dw(t,e,n,r,o+1)),a)):(s&&Ss(Es(s,Bc(t,e,o+1)),a),Da(e,n,o,a),i&&Ss(Es(i,Bc(n,r,o+1)),a)),Da(r,null,o,a),new D(a)}function Bc(t,e,n){let r=[];if(Da(null,t,n,r),t.depth>n){let o=Lf(t,e,n+1);Ss(Es(o,Bc(t,e,n+1)),r)}return Da(e,null,n,r),new D(r)}function FD(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 Ra{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 Pc(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 Ra(n,r,s)}static resolveCached(e,n){let r=Rw.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 Rw.set(e,r=new jD);let o=r.elts[r.i]=Ra.resolve(e,n);return r.i=(r.i+1)%UD,o}}class jD{constructor(){this.elts=[],this.i=0}}const UD=12,Rw=new WeakMap;class Pc{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 WD=Object.create(null);let Yr=class _p{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&&Ic(this.attrs,n||e.defaultAttrs||WD)&&Fe.sameSet(this.marks,r||Fe.none)}copy(e=null){return e==this.content?this:new _p(this.type,this.attrs,e,this.marks)}mark(e){return e==this.marks?this:new _p(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 VD(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 Ra.resolveCached(this,e)}resolveNoCache(e){return Ra.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()+")"),zw(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 Oc 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):zw(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 Oc(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new Oc(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 zw(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class Cs{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new HD(e,n);if(r.next==null)return Cs.empty;let o=$w(r);r.next&&r.err("Unexpected trailing text");let s=XD(JD(o));return QD(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
- `)}}Cs.empty=new Cs(!0);class HD{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 $w(t){let e=[];do e.push(ZD(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function ZD(t){let e=[];do e.push(KD(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function KD(t){let e=GD(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=YD(t,e);else break;return e}function Lw(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function YD(t,e){let n=Lw(t),r=n;return t.eat(",")&&(t.next!="}"?r=Lw(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function qD(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 GD(t){if(t.eat("(")){let e=$w(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=qD(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 JD(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 Vw(t,e){return e-t}function Fw(t,e){let n=[];return r(e),n.sort(Vw);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 XD(t){let e=Object.create(null);return n(Fw(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]);Fw(t,l).forEach(u=>{c||o.push([a,c=[]]),c.indexOf(u)==-1&&c.push(u)})})});let s=e[r.join(",")]=new Cs(r.indexOf(t.length-1)>-1);for(let i=0;i<o.length;i++){let a=o[i][1].sort(Vw);s.next.push({type:o[i][0],next:e[a.join(",")]||n(a)})}return s}}function QD(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 jw(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 Uw(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 Ww(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 Hw(t,e){let n=Object.create(null);if(e)for(let r in e)n[r]=new tR(t,r,e[r]);return n}let Zw=class bS{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=Hw(e,r.attrs),this.defaultAttrs=jw(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==Cs.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:Uw(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){Ww(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 bS(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 eR(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 tR{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?eR(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class Dc{constructor(e,n,r,o){this.name=e,this.rank=n,this.schema=r,this.spec=o,this.attrs=Hw(e,o.attrs),this.excluded=null;let s=jw(this.attrs);this.instance=s?new Fe(this,s):null}create(e=null){return!e&&this.instance?this.instance:new Fe(this,Uw(this.attrs,e))}static compile(e,n){let r=Object.create(null),o=0;return e.forEach((s,i)=>r[s]=new Dc(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){Ww(this.attrs,e,"mark",this.name)}excludes(e){return this.excluded.indexOf(e)>-1}}class Kw{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=Lt.from(e.nodes),n.marks=Lt.from(e.marks||{}),this.nodes=Zw.compile(this.spec.nodes,this),this.marks=Dc.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]=Cs.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?Yw(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==""?[]:Yw(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 Zw){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 Oc(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 Yw(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 nR(t){return t.tag!=null}function rR(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(nR(o))this.tags.push(o);else if(rR(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 Xw(this,n,!1);return r.addAll(e,Fe.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new Xw(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(iR(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=Qw(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=Qw(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 qw={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},oR={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Gw={ol:!0,ul:!0},za=1,Vf=2,$a=4;function Jw(t,e,n){return e!=null?(e?za:0)|(e==="full"?Vf:0):t&&t.whitespace=="pre"?za|Vf:n&~$a}class Rc{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&$a?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&za)){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&&!qw.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class Xw{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=Jw(null,n.preserveWhitespace,0)|(r?$a:0);o?s=new Rc(o.type,o.attrs,Fe.none,!0,n.topMatch||o.type.contentMatch,i):r?s=new Rc(null,null,Fe.none,!0,null,i):s=new Rc(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&Vf?"full":this.localPreserveWS||(o.options&za)>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;Gw.hasOwnProperty(i)&&this.parser.normalizeLists&&sR(e);let l=this.options.ruleFromNode&&this.options.ruleFromNode(e)||(a=this.parser.matchTag(e,this,r));e:if(l?l.ignore:oR.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(qw.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):ev(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=Jw(e,s,i.options);i.options&$a&&i.content.length==0&&(a|=$a);let l=Fe.none;return r=r.filter(c=>(i.type?i.type.allowsMarkType(c.type):ev(c.type,e))?(l=c.addToSet(l),!1):!0),this.nodes.push(new Rc(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|=za)}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 sR(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Gw.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function iR(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function Qw(t){let e={};for(let n in t)e[n]=t[n];return e}function ev(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 _s{constructor(e,n){this.nodes=e,this.marks=n}serializeFragment(e,n={},r){r||(r=Ff(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}=zc(Ff(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&&zc(Ff(r),o(e,n),null,e.attrs)}static renderSpec(e,n,r=null,o){return zc(e,n,r,o)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new _s(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=tv(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return tv(e.marks)}}function tv(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function Ff(t){return t.document||window.document}const nv=new WeakMap;function aR(t){let e=nv.get(t);return e===void 0&&nv.set(t,e=lR(t)),e}function lR(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 zc(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=aR(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}=zc(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 rv=65535,ov=Math.pow(2,16);function cR(t,e){return t+e*ov}function sv(t){return t&rv}function uR(t){return(t-(t&rv))/ov}const iv=1,av=2,$c=4,lv=8;class jf{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&lv)>0}get deletedBefore(){return(this.delInfo&(iv|$c))>0}get deletedAfter(){return(this.delInfo&(av|$c))>0}get deletedAcross(){return(this.delInfo&$c)>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=sv(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+uR(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:cR(a/3,e-l),g=e==l?av:e==f?iv:$c;return(n<0?e!=l:e!=f)&&(g|=lv),new jf(p,g,m)}o+=u-c}return r?e+o:new jf(e+o,0,null)}touches(e,n){let r=0,o=sv(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 La{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 La(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 La;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 jf(e,o,null)}}const Uf=Object.create(null);class Kt{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=Uf[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 Uf)throw new RangeError("Duplicate use of step JSON ID "+e);return Uf[e]=n,n.prototype.jsonID=e,n}}class ft{constructor(e,n){this.doc=e,this.failed=n}static ok(e){return new ft(e,null)}static fail(e){return new ft(null,e)}static fromReplace(e,n,r,o){try{return ft.ok(e.replace(n,r,o))}catch(s){if(s instanceof Nc)return ft.fail(s.message);throw s}}}function Wf(t,e,n){let r=[];for(let o=0;o<t.childCount;o++){let s=t.child(o);s.content.size&&(s=s.copy(Wf(s.content,e,s))),s.isInline&&(s=e(s,n,o)),r.push(s)}return D.fromArray(r)}class Oo extends Kt{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(Wf(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 ft.fromReplace(e,this.from,this.to,s)}invert(){return new rr(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 Oo(n.pos,r.pos,this.mark)}merge(e){return e instanceof Oo&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Oo(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 Oo(n.from,n.to,e.markFromJSON(n.mark))}}Kt.jsonID("addMark",Oo);class rr extends Kt{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(Wf(n.content,o=>o.mark(this.mark.removeFromSet(o.marks)),e),n.openStart,n.openEnd);return ft.fromReplace(e,this.from,this.to,r)}invert(){return new Oo(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 rr(n.pos,r.pos,this.mark)}merge(e){return e instanceof rr&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new rr(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 rr(n.from,n.to,e.markFromJSON(n.mark))}}Kt.jsonID("removeMark",rr);class Do extends Kt{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return ft.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return ft.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 Do(this.pos,n.marks[o]);return new Do(this.pos,this.mark)}}return new xs(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new Do(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 Do(n.pos,e.markFromJSON(n.mark))}}Kt.jsonID("addNodeMark",Do);class xs extends Kt{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return ft.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.removeFromSet(n.marks));return ft.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 Do(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new xs(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 xs(n.pos,e.markFromJSON(n.mark))}}Kt.jsonID("removeNodeMark",xs);class Mt extends Kt{constructor(e,n,r,o=!1){super(),this.from=e,this.to=n,this.slice=r,this.structure=o}apply(e){return this.structure&&Hf(e,this.from,this.to)?ft.fail("Structure replace would overwrite content"):ft.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)}}Kt.jsonID("replace",Mt);class At extends Kt{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&&(Hf(e,this.from,this.gapFrom)||Hf(e,this.gapTo,this.to)))return ft.fail("Structure gap-replace would overwrite content");let n=e.slice(this.gapFrom,this.gapTo);if(n.openStart||n.openEnd)return ft.fail("Gap is not a flat range");let r=this.slice.insertAt(this.insert,n.content);return r?ft.fromReplace(e,this.from,this.to,r):ft.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)}}Kt.jsonID("replaceAround",At);function Hf(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 dR(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 rr(h,p,f[g])));a&&a.to==h?a.to=p:s.push(a=new Oo(h,p,r))}}),o.forEach(l=>t.step(l)),s.forEach(l=>t.step(l))}function fR(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 Dc){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 rr(i.from,i.to,i.style)))}function Zf(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 rr(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 hR(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function Mi(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||!hR(i,a,l))break;a&&(o=1),l<i.childCount&&(s=1)}return null}function pR(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 cv(t,e,n=null,r=t){let o=mR(t,e),s=o&&gR(r,e);return s?o.map(uv).concat({type:e,attrs:n}).concat(s.map(uv)):null}function uv(t){return{type:t,attrs:null}}function mR(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 gR(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 yR(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 wR(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)&&vR(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&&fv(t,i,a,s),Zf(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&&dv(t,i,a,s),!1}})}function dv(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 fv(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 vR(t,e,n){let r=t.resolve(e),o=r.index();return r.parent.canReplaceWith(o,o+1,n)}function kR(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 Gr(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 bR(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 Ts(t,e){let n=t.resolve(e),r=n.index();return hv(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function SR(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 hv(t,e){return!!(t&&e&&!t.isLeaf&&SR(t,e))}function Lc(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&&hv(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 ER(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);fv(t,u.node(),u.before(),a)}i.inlineContent&&Zf(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);dv(t,u.node(),u.before(),t.steps.length)}return t}function CR(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 pv(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 Vc(t,e,n=e,r=K.empty){if(e==n&&!r.size)return null;let o=t.resolve(e),s=t.resolve(n);return mv(o,s,r)?new Mt(e,n,r):new _R(o,s,r).fit()}function mv(t,e,n){return!n.openStart&&!n.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),n.content)}class _R{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=Kf(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=Kf(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=Kf(e,n);if(o.childCount<=1&&n>0){let s=e.size-n<=n+o.size;this.unplaced=new K(Va(e,n-1,1),n-1,s?n-1:r)}else this.unplaced=new K(Va(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(gv(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=Fa(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(Va(i.content,e-1,1),e-1,p<0?i.openEnd:e-1):new K(Va(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||!Yf(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=Yf(e,n,o,r,s);if(i){for(let a=n-1;a>=0;a--){let{match:l,type:c}=this.frontier[a],u=Yf(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=Fa(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=Fa(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=Fa(this.placed,this.frontier.length,n))}}function Va(t,e,n){return e==0?t.cutByIndex(n,t.childCount):t.replaceChild(0,t.firstChild.copy(Va(t.firstChild.content,e-1,n)))}function Fa(t,e,n){return e==0?t.append(n):t.replaceChild(t.childCount-1,t.lastChild.copy(Fa(t.lastChild.content,e-1,n)))}function Kf(t,e){for(let n=0;n<e;n++)t=t.firstChild.content;return t}function gv(t,e,n){if(e<=0)return t;let r=t.content;return e>1&&(r=r.replaceChild(0,gv(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 Yf(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&&!xR(n,s.content,i)?a:null}function xR(t,e,n){for(let r=n;r<e.childCount;r++)if(!t.allowsMarks(e.child(r).marks))return!0;return!1}function TR(t){return t.spec.defining||t.spec.definingForContent}function MR(t,e,n,r){if(!r.size)return t.deleteRange(e,n);let o=t.doc.resolve(e),s=t.doc.resolve(n);if(mv(o,s,r))return t.step(new Mt(e,n,r));let i=wv(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=TR(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(yv(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 yv(t,e,n,r,o){if(e<n){let s=t.firstChild;t=t.replaceChild(0,s.copy(yv(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 AR(t,e,n,r){if(!r.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let o=CR(t.doc,e,r.type);o!=null&&(e=n=o)}t.replaceRange(e,n,new K(D.from(r),0,0))}function IR(t,e,n){let r=t.doc.resolve(e),o=t.doc.resolve(n),s=wv(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 wv(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 Ai extends Kt{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 ft.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 ft.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 Ai(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 Ai(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 Ai(n.pos,n.attr,n.value)}}Kt.jsonID("attr",Ai);class ja extends Kt{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 ft.ok(r)}getMap(){return Cn.empty}invert(e){return new ja(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 ja(n.attr,n.value)}}Kt.jsonID("docAttr",ja);let Ii=class extends Error{};Ii=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n},Ii.prototype=Object.create(Error.prototype),Ii.prototype.constructor=Ii,Ii.prototype.name="TransformError";class vv{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new La}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let n=this.maybeStep(e);if(n.failed)throw new Ii(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=Vc(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 MR(this,e,n,r),this}replaceRangeWith(e,n,r){return AR(this,e,n,r),this}deleteRange(e,n){return IR(this,e,n),this}lift(e,n){return pR(this,e,n),this}join(e,n=1){return ER(this,e,n),this}wrap(e,n){return yR(this,e,n),this}setBlockType(e,n=e,r,o=null){return wR(this,e,n,r,o),this}setNodeMarkup(e,n,r=null,o){return kR(this,e,n,r,o),this}setNodeAttribute(e,n,r){return this.step(new Ai(e,n,r)),this}setDocAttribute(e,n){return this.step(new ja(e,n)),this}addNodeMark(e,n){return this.step(new Do(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 xs(e,n));else{let o=r.marks,s,i=[];for(;s=n.isInSet(o);)i.push(new xs(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 bR(this,e,n,r),this}addMark(e,n,r){return dR(this,e,n,r),this}removeMark(e,n,r){return fR(this,e,n,r),this}clearIncompatible(e,n,r){return Zf(this,e,n,r),this}}const qf=Object.create(null);class be{constructor(e,n,r){this.$anchor=e,this.$head=n,this.ranges=r||[new NR(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&&Sv(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),Sv(e,r,n.isInline?-1:1))}}static findFrom(e,n,r=!1){let o=e.parent.inlineContent?new ye(e):Ni(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?Ni(e.node(0),e.node(s),e.before(s+1),e.index(s),n,r):Ni(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 Ni(e,e,0,0,1)||new _n(e)}static atEnd(e){return Ni(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=qf[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 qf)throw new RangeError("Duplicate use of selection JSON ID "+e);return qf[e]=n,n.prototype.jsonID=e,n}getBookmark(){return ye.between(this.$anchor,this.$head).getBookmark()}}be.prototype.visible=!0;class NR{constructor(e,n){this.$from=e,this.$to=n}}let kv=!1;function bv(t){!kv&&!t.parent.inlineContent&&(kv=!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){bv(e),bv(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 Fc(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 Fc{constructor(e,n){this.anchor=e,this.head=n}map(e){return new Fc(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 Gf(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 Gf{constructor(e){this.anchor=e}map(e){let{deleted:n,pos:r}=e.mapResult(this.anchor);return n?new Fc(r,r):new Gf(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 BR}}be.jsonID("all",_n);const BR={map(){return this},resolve(t){return new _n(t)}};function Ni(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=Ni(t,a,n+o,o<0?a.childCount:0,o,s);if(l)return l}n+=a.nodeSize*o}return null}function Sv(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 Ev=1,jc=2,Cv=4;class PR extends vv{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|Ev)&~jc,this.storedMarks=null,this}get selectionSet(){return(this.updated&Ev)>0}setStoredMarks(e){return this.storedMarks=e,this.updated|=jc,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&jc)>0}addStep(e,n){super.addStep(e,n),this.updated=this.updated&~jc,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|=Cv,this}get scrolledIntoView(){return(this.updated&Cv)>0}}function _v(t,e){return!e||!t?t:t.bind(e)}class Ua{constructor(e,n,r){this.name=e,this.init=_v(n.init,r),this.apply=_v(n.apply,r)}}const OR=[new Ua("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new Ua("selection",{init(t,e){return t.selection||be.atStart(e.doc)},apply(t){return t.selection}}),new Ua("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,n,r){return r.selection.$cursor?t.storedMarks:null}}),new Ua("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})];class Jf{constructor(e,n){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=OR.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 Ua(r.key,r.spec.state,r))})}}class Bi{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 Bi(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 PR(this)}static create(e){let n=new Jf(e.doc?e.doc.type.schema:e.schema,e.plugins),r=new Bi(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 Jf(this.schema,e.plugins),r=n.fields,o=new Bi(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 Jf(e.schema,e.plugins),s=new Bi(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 xv(t,e,n){for(let r in t){let o=t[r];o instanceof Function?o=o.bind(e):r=="handleDOMEvents"&&(o=xv(o,e,{})),n[r]=o}return n}class vt{constructor(e){this.spec=e,this.props={},e.props&&xv(e.props,this,this.props),this.key=e.key?e.key.key:Tv("plugin")}getState(e){return e[this.key]}}const Xf=Object.create(null);function Tv(t){return t in Xf?t+"$"+ ++Xf[t]:(Xf[t]=0,t+"$")}class tn{constructor(e="key"){this.key=Tv(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const Qf=(t,e)=>t.selection.empty?!1:(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function Mv(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0)?null:n}const Av=(t,e,n)=>{let r=Mv(t,n);if(!r)return!1;let o=eh(r);if(!o){let i=r.blockRange(),a=i&&Mi(i);return a==null?!1:(e&&e(t.tr.lift(i,a).scrollIntoView()),!0)}let s=o.nodeBefore;if($v(t,o,e,-1))return!0;if(r.parent.content.size==0&&(Pi(s,"end")||ae.isSelectable(s)))for(let i=r.depth;;i--){let a=Vc(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(Pi(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},DR=(t,e,n)=>{let r=Mv(t,n);if(!r)return!1;let o=eh(r);return o?Iv(t,o,e):!1},RR=(t,e,n)=>{let r=Bv(t,n);if(!r)return!1;let o=th(r);return o?Iv(t,o,e):!1};function Iv(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=Vc(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 Pi(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 Nv=(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=eh(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 eh(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 Bv(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("forward",t):n.parentOffset<n.parent.content.size)?null:n}const Pv=(t,e,n)=>{let r=Bv(t,n);if(!r)return!1;let o=th(r);if(!o)return!1;let s=o.nodeAfter;if($v(t,o,e,1))return!0;if(r.parent.content.size==0&&(Pi(s,"start")||ae.isSelectable(s))){let i=Vc(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(Pi(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},Ov=(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=th(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 th(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 zR=(t,e)=>{let n=t.selection,r=n instanceof ae,o;if(r){if(n.node.isTextblock||!Ts(t.doc,n.from))return!1;o=n.from}else if(o=Lc(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},$R=(t,e)=>{let n=t.selection,r;if(n instanceof ae){if(n.node.isTextblock||!Ts(t.doc,n.to))return!1;r=n.to}else if(r=Lc(t.doc,n.to,1),r==null)return!1;return e&&e(t.tr.join(r).scrollIntoView()),!0},LR=(t,e)=>{let{$from:n,$to:r}=t.selection,o=n.blockRange(r),s=o&&Mi(o);return s==null?!1:(e&&e(t.tr.lift(o,s).scrollIntoView()),!0)},Dv=(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 nh(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 VR=(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=nh(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},Rv=(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=nh(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},zv=(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(Gr(t.doc,s))return e&&e(t.tr.split(s).scrollIntoView()),!0}let r=n.blockRange(),o=r&&Mi(r);return o==null?!1:(e&&e(t.tr.lift(r,o).scrollIntoView()),!0)};function FR(t){return(e,n)=>{let{$from:r,$to:o}=e.selection;if(e.selection instanceof ae&&e.selection.node.isBlock)return!r.parentOffset||!Gr(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=nh(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=Gr(u.doc,f,s.length,s);if(h||(s[0]=a?{type:a}:null,h=Gr(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 jR=FR(),UR=(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 WR(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||Ts(t.doc,e.pos))?!1:(n&&n(t.tr.join(e.pos).scrollIntoView()),!0)}function $v(t,e,n,r){let o=e.nodeBefore,s=e.nodeAfter,i,a,l=o.type.spec.isolating||s.type.spec.isolating;if(!l&&WR(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&&Ts(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&&Mi(f);if(h!=null&&h>=e.depth)return n&&n(t.tr.lift(f,h).scrollIntoView()),!0;if(c&&Pi(s,"start",!0)&&Pi(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 Lv(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 HR=Lv(-1),ZR=Lv(1);function KR(t,e=null){return function(n,r){let{$from:o,$to:s}=n.selection,i=o.blockRange(s),a=i&&cv(i,t,e);return a?(r&&r(n.tr.wrap(i,a).scrollIntoView()),!0):!1}}function Vv(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 rh(...t){return function(e,n,r){for(let o=0;o<t.length;o++)if(t[o](e,n,r))return!0;return!1}}rh(Qf,Av,Nv),rh(Qf,Pv,Ov),rh(Dv,Rv,zv,jR),typeof navigator<"u"?/Mac|iP(hone|[oa]d)/.test(navigator.platform):typeof os<"u"&&os.platform&&os.platform()=="darwin";function YR(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 qR(a,i,t,e)?(r&&r(a.scrollIntoView()),!0):!1}}function qR(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 Pc(l,l,e.depth),e.endIndex<e.parent.childCount&&(e=new Pc(e.$from,i.resolve(e.$to.end(e.depth)),e.depth)),o=!0}let a=cv(s,n,r,e);return a?(t&&GR(t,e,a,o,n),!0):!1}function GR(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&&Gr(t.doc,l,a)&&(t.split(l,a),l+=2*a),l+=c.child(u).nodeSize;return t}function JR(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?XR(e,n,t,s):QR(e,n,s):!0:!1}}function XR(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 Pc(o.doc.resolve(r.$from.pos),o.doc.resolve(i),r.depth));const a=Mi(r);if(a==null)return!1;o.lift(r,a);let l=o.doc.resolve(o.mapping.map(s,-1)-1);return Ts(o.doc,l.pos)&&l.nodeBefore.type==l.nodeAfter.type&&o.join(l.pos),e(o.scrollIntoView()),!0}function QR(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 e3(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 Vt=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},Oi=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e};let oh=null;const Jr=function(t,e,n){let r=oh||(oh=document.createRange());return r.setEnd(t,n??t.nodeValue.length),r.setStart(t,e||0),r},t3=function(){oh=null},Ms=function(t,e,n,r){return n&&(Fv(t,e,n,r,-1)||Fv(t,e,n,r,1))},n3=/^(img|br|input|textarea|hr)$/i;function Fv(t,e,n,r,o){for(var s;;){if(t==n&&e==r)return!0;if(e==(o<0?0:Dn(t))){let i=t.parentNode;if(!i||i.nodeType!=1||Wa(t)||n3.test(t.nodeName)||t.contentEditable=="false")return!1;e=Vt(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?Dn(t):0}else return!1}}function Dn(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function r3(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=Dn(t)}else if(t.parentNode&&!Wa(t))e=Vt(t),t=t.parentNode;else return null}}function o3(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&&!Wa(t))e=Vt(t)+1,t=t.parentNode;else return null}}function s3(t,e,n){for(let r=e==0,o=e==Dn(t);r||o;){if(t==n)return!0;let s=Vt(t);if(t=t.parentNode,!t)return!1;r=r&&s==0,o=o&&s==Dn(t)}}function Wa(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 Uc=function(t){return t.focusNode&&Ms(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset)};function As(t,e){let n=document.createEvent("Event");return n.initEvent("keydown",!0,!0),n.keyCode=t,n.key=n.code=e,n}function i3(t){let e=t.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function a3(t,e,n){if(t.caretPositionFromPoint)try{let r=t.caretPositionFromPoint(e,n);if(r)return{node:r.offsetNode,offset:Math.min(Dn(r.offsetNode),r.offset)}}catch{}if(t.caretRangeFromPoint){let r=t.caretRangeFromPoint(e,n);if(r)return{node:r.startContainer,offset:Math.min(Dn(r.startContainer),r.startOffset)}}}const Sr=typeof navigator<"u"?navigator:null,jv=typeof document<"u"?document:null,Ro=Sr&&Sr.userAgent||"",sh=/Edge\/(\d+)/.exec(Ro),Uv=/MSIE \d/.exec(Ro),ih=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(Ro),fn=!!(Uv||ih||sh),zo=Uv?document.documentMode:ih?+ih[1]:sh?+sh[1]:0,Rn=!fn&&/gecko\/(\d+)/i.test(Ro);Rn&&+(/Firefox\/(\d+)/.exec(Ro)||[0,0])[1];const ah=!fn&&/Chrome\/(\d+)/.exec(Ro),Ft=!!ah,Wv=ah?+ah[1]:0,Yt=!fn&&!!Sr&&/Apple Computer/.test(Sr.vendor),Di=Yt&&(/Mobile\/\w+/.test(Ro)||!!Sr&&Sr.maxTouchPoints>2),zn=Di||(Sr?/Mac/.test(Sr.platform):!1),Hv=Sr?/Win/.test(Sr.platform):!1,Xr=/Android \d/.test(Ro),Ha=!!jv&&"webkitFontSmoothing"in jv.documentElement.style,l3=Ha?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function c3(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 u3(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 Zv(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=Oi(i);continue}let a=i,l=a==s.body,c=l?c3(s):u3(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:Oi(i)}}function d3(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:Kv(t.dom)}}function Kv(t){let e=[],n=t.ownerDocument;for(let r=t;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),t!=n);r=Oi(r));return e}function f3({refDOM:t,refTop:e,stack:n}){let r=t?t.getBoundingClientRect().top:0;Yv(n,r==0?0:r-e)}function Yv(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 Ri=null;function h3(t){if(t.setActive)return t.setActive();if(Ri)return t.focus(Ri);let e=Kv(t);t.focus(Ri==null?{get preventScroll(){return Ri={preventScroll:!0},!0}}:void 0),Ri||(Ri=!1,Yv(e,0))}function qv(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=Jr(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?p3(n,o):!n||r&&n.nodeType==1?{node:t,offset:s}:qv(n,o)}function p3(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=$o(r,1);if(i.top!=i.bottom&&lh(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 lh(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function m3(t,e){let n=t.parentNode;return n&&/^li$/i.test(n.nodeName)&&e.left<t.getBoundingClientRect().left?n:t}function g3(t,e,n){let{node:r,offset:o}=qv(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 y3(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 Gv(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(lh(e,c))return Gv(i,e,c)}}if((s=(s+1)%r)==o)break}return t}function w3(t,e){let n=t.dom.ownerDocument,r,o=0,s=a3(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(!lh(e,c)||(i=Gv(t.dom,e,c),!i))return null}if(Yt)for(let c=i;r&&c;c=Oi(c))c.draggable&&(r=void 0);if(i=m3(i,e),r){if(Rn&&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;Ha&&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=y3(t,r,o,e))}a==null&&(a=g3(t,i,e));let l=t.docView.nearestDesc(i,!0);return{pos:a,inside:l?l.posAtStart-l.border:-1}}function Jv(t){return t.top<t.bottom||t.left<t.right}function $o(t,e){let n=t.getClientRects();if(n.length){let r=n[e<0?0:n.length-1];if(Jv(r))return r}return Array.prototype.find.call(n,Jv)||t.getBoundingClientRect()}const v3=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;function Xv(t,e,n){let{node:r,offset:o,atom:s}=t.docView.domFromPos(e,n<0?-1:1),i=Ha||Rn;if(r.nodeType==3)if(i&&(v3.test(r.nodeValue)||(n<0?!o:o==r.nodeValue.length))){let l=$o(Jr(r,o,o),n);if(Rn&&o&&/\s/.test(r.nodeValue[o-1])&&o<r.nodeValue.length){let c=$o(Jr(r,o-1,o-1),-1);if(c.top==l.top){let u=$o(Jr(r,o,o+1),-1);if(u.top!=l.top)return Za(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++,Za($o(Jr(r,l,c),u),u<0)}if(!t.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&o&&(n<0||o==Dn(r))){let l=r.childNodes[o-1];if(l.nodeType==1)return ch(l.getBoundingClientRect(),!1)}if(s==null&&o<Dn(r)){let l=r.childNodes[o];if(l.nodeType==1)return ch(l.getBoundingClientRect(),!0)}return ch(r.getBoundingClientRect(),n>=0)}if(s==null&&o&&(n<0||o==Dn(r))){let l=r.childNodes[o-1],c=l.nodeType==3?Jr(l,Dn(l)-(i?0:1)):l.nodeType==1&&(l.nodeName!="BR"||!l.nextSibling)?l:null;if(c)return Za($o(c,1),!1)}if(s==null&&o<Dn(r)){let l=r.childNodes[o];for(;l.pmViewDesc&&l.pmViewDesc.ignoreForCoords;)l=l.nextSibling;let c=l?l.nodeType==3?Jr(l,0,i?0:1):l.nodeType==1?l:null:null;if(c)return Za($o(c,-1),!0)}return Za($o(r.nodeType==3?Jr(r):r,-n),n>=0)}function Za(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 ch(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 Qv(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 k3(t,e,n){let r=e.selection,o=n=="up"?r.$from:r.$to;return Qv(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=Xv(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=Jr(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 b3=/[\u0590-\u08ac]/;function S3(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?!b3.test(r.parent.textContent)||!a.modify?n=="left"||n=="backward"?s:i:Qv(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 ek=null,tk=null,nk=!1;function E3(t,e,n){return ek==e&&tk==n?nk:(ek=e,tk=n,nk=n=="up"||n=="down"?k3(t,e,n):S3(t,e,n))}const $n=0,rk=1,Is=2,Er=3;class Ka{constructor(e,n,r,o){this.parent=e,this.children=n,this.dom=r,this.contentDOM=o,this.dirty=$n,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>Vt(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 ik){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 ok&&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?Vt(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?Vt(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=Vt(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=Vt(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((Rn||Yt)&&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:Vt(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(Rn&&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&&Yt)&&Ms(a.node,a.offset,u.anchorNode,u.anchorOffset)&&Ms(l.node,l.offset,u.focusNode,u.focusOffset))return;let h=!1;if((c.extend||e==n)&&!(f&&Rn)){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?Is:rk,e==a&&n==l&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=Er:s.markDirty(e-a,n-a);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?Is:Er}r=i}this.dirty=Is}markParentsDirty(){let e=1;for(let n=this.parent;n;n=n.parent,e++){let r=e==1?Is:rk;n.dirty<r&&(n.dirty=r)}}get domAtom(){return!1}get ignoreForCoords(){return!1}get ignoreForSelection(){return!1}isText(e){return!1}}class ok extends Ka{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==$n&&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 C3 extends Ka{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 Ns extends Ka{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=_s.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new Ns(e,n,i.dom,i.contentDOM||i.dom,i)}parseRule(){return this.dirty&Er||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=Er&&this.mark.eq(e)}markDirty(e,n){if(super.markDirty(e,n),this.dirty!=$n){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty<this.dirty&&(r.dirty=this.dirty),this.dirty=$n}}slice(e,n,r){let o=Ns.create(this.parent,this.mark,!0,r),s=this.children,i=this.size;n<i&&(s=dh(s,n,i,r)),e>0&&(s=dh(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 Ka{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}=_s.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=ck(u,r,n),c?l=new _3(e,n,r,o,u,f||null,h,c,s,i+1):n.isText?new Wc(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==$n&&e.eq(this.node)&&Hc(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 T3(this,i&&i.node,e);I3(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==Is)&&(i&&this.protectLocalComposition(e,i),ak(this.contentDOM,this.children,e),Di&&N3(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=B3(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 C3(this,s,n,o);e.input.compositionNodes.push(i),this.children=dh(this.children,r,r+o.length,e,i)}update(e,n,r,o){return this.dirty==Er||!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=$n}updateOuterDeco(e){if(Hc(e,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=lk(this.dom,this.nodeDOM,uh(this.outerDeco,this.node,n),uh(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 sk(t,e,n,r,o){ck(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 Wc 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==Er||this.dirty!=$n&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=$n||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=$n,!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 Wc(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=Er)}get domAtom(){return!1}isText(e){return this.node.text==e}}class ik extends Ka{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==$n&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class _3 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==Er)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 ak(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=uk(r),o=!0;r=r.nextSibling}else o=!0,t.insertBefore(a,r);if(i instanceof Ns){let l=r?r.previousSibling:t.lastChild;ak(i.contentDOM,i.children,n),r=l?l.nextSibling:t.firstChild}}for(;r;)r=uk(r),o=!0;o&&n.trackWrites==t&&(n.trackWrites=null)}const Ya=function(t){t&&(this.nodeName=t)};Ya.prototype=Object.create(null);const Bs=[new Ya];function uh(t,e,n){if(t.length==0)return Bs;let r=n?Bs[0]:new Ya,o=[r];for(let s=0;s<t.length;s++){let i=t[s].type.attrs;if(i){i.nodeName&&o.push(r=new Ya(i.nodeName));for(let a in i){let l=i[a];l!=null&&(n&&o.length==1&&o.push(r=new Ya(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 lk(t,e,n,r){if(n==Bs&&r==Bs)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=Bs[0]),o=l}x3(o,a||Bs[0],i)}return o}function x3(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 ck(t,e,n){return lk(t,t,Bs,uh(e,n,t.nodeType!=1))}function Hc(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 uk(t){let e=t.nextSibling;return t.parentNode.removeChild(t),e}class T3{constructor(e,n,r){this.lock=n,this.view=r,this.index=0,this.stack=[],this.changed=!1,this.top=e,this.preMatch=M3(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=$n,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=Ns.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==Er&&i.dom==i.contentDOM&&(i.dirty=Is),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!=Er&&Hc(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=Is,f.updateChildren(o,i+1),f.dirty=$n),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)||!Hc(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 ok(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 Ns;)n=e,e=n.children[n.children.length-1];(!e||!(e instanceof Wc)||/\n$/.test(e.node.text)||this.view.requiresGeckoHackNode&&/\s$/.test(e.node.text))&&((Yt||Ft)&&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 ik(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 M3(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 Ns)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 A3(t,e){return t.type.side-e.type.side}function I3(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(A3);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 N3(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 B3(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 dh(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 fh(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(Uc(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&&s3(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=ph(t,u,a,f)}return c}function dk(t){return t.editable?t.hasFocus():wk(t)&&document.activeElement&&document.activeElement.contains(t.dom)}function eo(t,e=!1){let n=t.state.selection;if(mk(t,n),!!dk(t)){if(!e&&t.input.mouseDown&&t.input.mouseDown.allowDefault&&Ft){let r=t.domSelectionRange(),o=t.domObserver.currentSelection;if(r.anchorNode&&o.anchorNode&&Ms(r.anchorNode,r.anchorOffset,o.anchorNode,o.anchorOffset)){t.input.mouseDown.delayedSelectionSync=!0,t.domObserver.setCurSelection();return}}if(t.domObserver.disconnectSelection(),t.cursorWrapper)O3(t);else{let{anchor:r,head:o}=n,s,i;fk&&!(n instanceof ye)&&(n.$from.parent.inlineContent||(s=hk(t,n.from)),!n.empty&&!n.$from.parent.inlineContent&&(i=hk(t,n.to))),t.docView.setSelection(r,o,t,e),fk&&(s&&pk(s),i&&pk(i)),n.visible?t.dom.classList.remove("ProseMirror-hideselection"):(t.dom.classList.add("ProseMirror-hideselection"),"onselectionchange"in document&&P3(t))}t.domObserver.setCurSelection(),t.domObserver.connectSelection()}}const fk=Yt||Ft&&Wv<63;function hk(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(Yt&&o&&o.contentEditable=="false")return hh(o);if((!o||o.contentEditable=="false")&&(!s||s.contentEditable=="false")){if(o)return hh(o);if(s)return hh(s)}}function hh(t){return t.contentEditable="true",Yt&&t.draggable&&(t.draggable=!1,t.wasDraggable=!0),t}function pk(t){t.contentEditable="false",t.wasDraggable&&(t.draggable=!0,t.wasDraggable=null)}function P3(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(()=>{(!dk(t)||t.state.selection.visible)&&t.dom.classList.remove("ProseMirror-hideselection")},20))})}function O3(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,r=n.nodeName=="IMG";r?e.collapse(n.parentNode,Vt(n)+1):e.collapse(n,0),!r&&!t.state.selection.visible&&fn&&zo<=11&&(n.disabled=!0,n.disabled=!1)}function mk(t,e){if(e instanceof ae){let n=t.docView.descAt(e.from);n!=t.lastSelectedViewDesc&&(gk(t),n&&n.selectNode(),t.lastSelectedViewDesc=n)}else gk(t)}function gk(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function ph(t,e,n,r){return t.someProp("createSelectionBetween",o=>o(t,e,n))||ye.between(e,n,r)}function yk(t){return t.editable&&!t.hasFocus()?!1:wk(t)}function wk(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 D3(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return Ms(e.node,e.offset,n.anchorNode,n.anchorOffset)}function mh(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 Vo(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function vk(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 Vo(t,new ye(r.$anchor,i))}else if(r.empty){if(t.endOfTextblock(e>0?"forward":"backward")){let o=mh(t.state,e);return o&&o instanceof ae?Vo(t,o):!1}else if(!(zn&&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)?Vo(t,new ae(e<0?t.state.doc.resolve(o.pos-s.nodeSize):o)):Ha?Vo(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 Vo(t,new ye(e>0?r.$to:r.$from));{let o=mh(t.state,e);return o?Vo(t,o):!1}}}function Zc(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function qa(t,e){let n=t.pmViewDesc;return n&&n.size==0&&(e<0||t.nextSibling||t.nodeName!="BR")}function zi(t,e){return e<0?R3(t):z3(t)}function R3(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let o,s,i=!1;for(Rn&&n.nodeType==1&&r<Zc(n)&&qa(n.childNodes[r],-1)&&(i=!0);;)if(r>0){if(n.nodeType!=1)break;{let a=n.childNodes[r-1];if(qa(a,-1))o=n,s=--r;else if(a.nodeType==3)n=a,r=n.nodeValue.length;else break}}else{if(kk(n))break;{let a=n.previousSibling;for(;a&&qa(a,-1);)o=n.parentNode,s=Vt(a),a=a.previousSibling;if(a)n=a,r=Zc(n);else{if(n=n.parentNode,n==t.dom)break;r=0}}}i?gh(t,n,r):o&&gh(t,o,s)}function z3(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let o=Zc(n),s,i;for(;;)if(r<o){if(n.nodeType!=1)break;let a=n.childNodes[r];if(qa(a,1))s=n,i=++r;else break}else{if(kk(n))break;{let a=n.nextSibling;for(;a&&qa(a,1);)s=a.parentNode,i=Vt(a)+1,a=a.nextSibling;if(a)n=a,r=0,o=Zc(n);else{if(n=n.parentNode,n==t.dom)break;r=o=0}}}s&&gh(t,s,i)}function kk(t){let e=t.pmViewDesc;return e&&e.node&&e.node.isBlock}function $3(t,e){for(;t&&e==t.childNodes.length&&!Wa(t);)e=Vt(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 L3(t,e){for(;t&&!e&&!Wa(t);)e=Vt(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 gh(t,e,n){if(e.nodeType!=3){let s,i;(i=$3(e,n))?(e=i,n=0):(s=L3(e,n))&&(e=s,n=s.nodeValue.length)}let r=t.domSelection();if(!r)return;if(Uc(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 bk(t,e){let n=t.state.doc.resolve(e);if(!(Ft||Hv)&&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 Sk(t,e,n){let r=t.state.selection;if(r instanceof ye&&!r.empty||n.indexOf("s")>-1||zn&&n.indexOf("m")>-1)return!1;let{$from:o,$to:s}=r;if(!o.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let i=mh(t.state,e);if(i&&i instanceof ae)return Vo(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?Vo(t,a):!1}return!1}function Ek(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 Ck(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function V3(t){if(!Yt||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;Ck(t,r,"true"),setTimeout(()=>Ck(t,r,"false"),20)}return!1}function F3(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}function j3(t,e){let n=e.keyCode,r=F3(e);if(n==8||zn&&n==72&&r=="c")return Ek(t,-1)||zi(t,-1);if(n==46&&!e.shiftKey||zn&&n==68&&r=="c")return Ek(t,1)||zi(t,1);if(n==13||n==27)return!0;if(n==37||zn&&n==66&&r=="c"){let o=n==37?bk(t,t.state.selection.from)=="ltr"?-1:1:-1;return vk(t,o,r)||zi(t,o)}else if(n==39||zn&&n==70&&r=="c"){let o=n==39?bk(t,t.state.selection.from)=="ltr"?1:-1:1;return vk(t,o,r)||zi(t,o)}else{if(n==38||zn&&n==80&&r=="c")return Sk(t,-1,r)||zi(t,-1);if(n==40||zn&&n==78&&r=="c")return V3(t)||Sk(t,1,r)||zi(t,1);if(r==(zn?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function yh(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")||_s.fromSchema(t.state.schema),a=Bk(),l=a.createElement("div");l.appendChild(i.serializeFragment(r,{document:a}));let c=l.firstChild,u,f=0;for(;c&&c.nodeType==1&&(u=Ik[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 _k(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=_s.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=Z3(n),Ha&&K3(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&&!U3.test(h.parentNode.nodeName)?{ignore:!0}:null}})),u)a=Y3(Ak(a,+u[1],+u[2]),u[4]);else if(a=K.maxOpen(W3(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=Ak(a,f,h)}return t.someProp("transformPasted",f=>{a=f(a,t,l)}),a}const U3=/^(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 W3(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&&Tk(l,s,a,i[i.length-1],0))i[i.length-1]=c;else{i.length&&(i[i.length-1]=Mk(i[i.length-1],s.length));let u=xk(a,l);i.push(u),o=o.matchType(u.type),s=l}}),i)return D.from(i)}return t}function xk(t,e,n=0){for(let r=e.length-1;r>=n;r--)t=e[r].create(null,D.from(t));return t}function Tk(t,e,n,r,o){if(o<t.length&&o<e.length&&t[o]==e[o]){let s=Tk(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(xk(n,t,o+1))))}}function Mk(t,e){if(e==0)return t;let n=t.content.replaceChild(t.childCount-1,Mk(t.lastChild,e-1)),r=t.contentMatchAt(t.childCount).fillBefore(D.empty,!0);return t.copy(n.append(r))}function wh(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=wh(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 Ak(t,e,n){return e<t.openStart&&(t=new K(wh(t.content,-1,e,t.openStart,0,t.openEnd),e,t.openEnd)),n<t.openEnd&&(t=new K(wh(t.content,1,n,t.openEnd,0,0),t.openStart,n)),t}const Ik={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 Nk=null;function Bk(){return Nk||(Nk=document.implementation.createHTMLDocument("title"))}let vh=null;function H3(t){let e=window.trustedTypes;return e?(vh||(vh=e.defaultPolicy||e.createPolicy("ProseMirrorClipboard",{createHTML:n=>n})),vh.createHTML(t)):t}function Z3(t){let e=/^(\s*<meta [^>]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let n=Bk().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(t),o;if((o=r&&Ik[r[1].toLowerCase()])&&(t=o.map(s=>"<"+s+">").join("")+t+o.map(s=>"</"+s+">").reverse().join("")),n.innerHTML=H3(t),o)for(let s=0;s<o.length;s++)n=n.querySelector(o[s])||n;return n}function K3(t){let e=t.querySelectorAll(Ft?"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 Y3(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={},q3={touchstart:!0,touchmove:!0};class G3{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 J3(t){for(let e in nn){let n=nn[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=r=>{Q3(t,r)&&!bh(t,r)&&(t.editable||!(r.type in rn))&&n(t,r)},q3[e]?{passive:!0}:void 0)}Yt&&t.dom.addEventListener("input",()=>null),kh(t)}function Fo(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function X3(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 kh(t){t.someProp("handleDOMEvents",e=>{for(let n in e)t.input.eventHandlers[n]||t.dom.addEventListener(n,t.input.eventHandlers[n]=r=>bh(t,r))})}function bh(t,e){return t.someProp("handleDOMEvents",n=>{let r=n[e.type];return r?r(t,e)||e.defaultPrevented:!1})}function Q3(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 ez(t,e){!bh(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,!Ok(t,n)&&(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),!(Xr&&Ft&&n.keyCode==13)))if(n.keyCode!=229&&t.domObserver.forceFlush(),Di&&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,As(13,"Enter"))),t.input.lastIOSEnter=0)},200)}else t.someProp("handleKeyDown",r=>r(t,n))||j3(t,n)?n.preventDefault():Fo(t,"key")},rn.keyup=(t,e)=>{e.keyCode==16&&(t.input.shiftKey=!1)},rn.keypress=(t,e)=>{let n=e;if(Ok(t,n)||!n.charCode||n.ctrlKey&&!n.altKey||zn&&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 Kc(t){return{left:t.clientX,top:t.clientY}}function tz(t,e){let n=e.x-t.clientX,r=e.y-t.clientY;return n*n+r*r<100}function Sh(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 $i(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 nz(t,e){if(e==-1)return!1;let n=t.state.doc.resolve(e),r=n.nodeAfter;return r&&r.isAtom&&ae.isSelectable(r)?($i(t,new ae(n)),!0):!1}function rz(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?($i(t,ae.create(t.state.doc,o)),!0):!1}function oz(t,e,n,r,o){return Sh(t,"handleClickOn",e,n,r)||t.someProp("handleClick",s=>s(t,e,r))||(o?rz(t,n):nz(t,n))}function sz(t,e,n,r){return Sh(t,"handleDoubleClickOn",e,n,r)||t.someProp("handleDoubleClick",o=>o(t,e,r))}function iz(t,e,n,r){return Sh(t,"handleTripleClickOn",e,n,r)||t.someProp("handleTripleClick",o=>o(t,e,r))||az(t,n,r)}function az(t,e,n){if(n.button!=0)return!1;let r=t.state.doc;if(e==-1)return r.inlineContent?($i(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)$i(t,ye.create(r,a+1,a+1+i.content.size));else if(ae.isSelectable(i))$i(t,ae.create(r,a));else continue;return!0}}function Eh(t){return Yc(t)}const Pk=zn?"metaKey":"ctrlKey";nn.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let r=Eh(t),o=Date.now(),s="singleClick";o-t.input.lastClick.time<500&&tz(n,t.input.lastClick)&&!n[Pk]&&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(Kc(n));i&&(s=="singleClick"?(t.input.mouseDown&&t.input.mouseDown.done(),t.input.mouseDown=new lz(t,i,n,!!r)):(s=="doubleClick"?sz:iz)(t,i.pos,i.inside,n)?n.preventDefault():Fo(t,"pointer"))};class lz{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[Pk],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&&Rn&&!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)),Fo(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(Kc(e))),this.updateAllowDefault(e),this.allowDefault||!n?Fo(this.view,"pointer"):oz(this.view,n.pos,n.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||Yt&&this.mightDrag&&!this.mightDrag.node.isAtom||Ft&&!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)?($i(this.view,be.near(this.view.state.doc.resolve(n.pos))),e.preventDefault()):Fo(this.view,"pointer")}move(e){this.updateAllowDefault(e),Fo(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(),Eh(t),Fo(t,"pointer")},nn.touchmove=t=>{t.input.lastTouch=Date.now(),Fo(t,"pointer")},nn.contextmenu=t=>Eh(t);function Ok(t,e){return t.composing?!0:Yt&&Math.abs(e.timeStamp-t.input.compositionEndedAt)<500?(t.input.compositionEndedAt=-2e8,!0):!1}const cz=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)||Ft&&Hv&&uz(t)))t.markCursor=t.state.storedMarks||n.marks(),Yc(t,!0),t.markCursor=null;else if(Yc(t,!e.selection.empty),Rn&&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}Dk(t,cz)};function uz(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++,Dk(t,20))};function Dk(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout(()=>Yc(t),e))}function Rk(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=fz());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function dz(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=r3(e.focusNode,e.focusOffset),r=o3(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 fz(){let t=document.createEvent("Event");return t.initEvent("event",!0,!0),t.timeStamp}function Yc(t,e=!1){if(!(Xr&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),Rk(t),e||t.docView&&t.docView.dirty){let n=fh(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 hz(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 Ga=fn&&zo<15||Di&&l3<604;nn.copy=rn.cut=(t,e)=>{let n=e,r=t.state.selection,o=n.type=="cut";if(r.empty)return;let s=Ga?null:n.clipboardData,i=r.content(),{dom:a,text:l}=yh(t,i);s?(n.preventDefault(),s.clearData(),s.setData("text/html",a.innerHTML),s.setData("text/plain",l)):hz(t,a),o&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function pz(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function mz(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?Ja(t,r.value,null,o,e):Ja(t,r.textContent,r.innerHTML,o,e)},50)}function Ja(t,e,n,r,o){let s=_k(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=pz(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 zk(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=Ga?null:n.clipboardData,o=t.input.shiftKey&&t.input.lastKeyCode!=45;r&&Ja(t,zk(r),r.getData("text/html"),o,n)?n.preventDefault():mz(t,n)};class $k{constructor(e,n,r){this.slice=e,this.move=n,this.node=r}}const gz=zn?"altKey":"ctrlKey";function Lk(t,e){let n=t.someProp("dragCopies",r=>!r(e));return n??!e[gz]}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(Kc(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}=yh(t,a);(!n.dataTransfer.files.length||!Ft||Wv>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(Ga?"Text":"text/html",l.innerHTML),n.dataTransfer.effectAllowed="copyMove",Ga||n.dataTransfer.setData("text/plain",c),t.dragging=new $k(u,Lk(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{yz(t,e,t.dragging)}finally{t.dragging=null}};function yz(t,e,n){if(!e.dataTransfer)return;let r=t.posAtCoords(Kc(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=_k(t,zk(e.dataTransfer),Ga?null:e.dataTransfer.getData("text/html"),!1,o);let i=!!(n&&Lk(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?pv(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(ph(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(Ft&&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,As(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 Xa(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 qc{constructor(e,n){this.toDOM=e,this.spec=n||Ps,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 qc&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Xa(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class jo{constructor(e,n){this.attrs=e,this.spec=n||Ps}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 jo&&Xa(this.attrs,e.attrs)&&Xa(this.spec,e.spec)}static is(e){return e.type instanceof jo}destroy(){}}class Ch{constructor(e,n){this.attrs=e,this.spec=n||Ps}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 Ch&&Xa(this.attrs,e.attrs)&&Xa(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 qc(n,r))}static inline(e,n,r,o){return new on(e,n,new jo(r,o))}static node(e,n,r,o){return new on(e,n,new Ch(r,o))}get spec(){return this.type.spec}get inline(){return this.type instanceof jo}get widget(){return this.type instanceof qc}}const Li=[],Ps={};class nt{constructor(e,n){this.local=e.length?e:Li,this.children=n.length?n:Li}static create(e,n){return n.length?Gc(n,e,0,Ps):qt}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==qt||e.maps.length==0?this:this.mapInner(e,n,0,0,r||Ps)}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?wz(this.children,i||[],e,n,r,o,s):i?new nt(i.sort(Os),Li):qt}add(e,n){return n.length?this==qt?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=Fk(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,Gc(u,a,c+1,Ps)),s+=3}});let i=Vk(s?jk(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(Os):this.local,o||this.children)}remove(e){return e.length==0||this==qt?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!=qt?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):qt}forChild(e,n){if(this==qt)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 jo){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(Os),Li);return r?new Uo([a,r]):a}return r||qt}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 _h(this.localsInner(e))}localsInner(e){if(this==qt)return Li;if(e.inlineContent||!this.local.some(jo.is))return this.local;let n=[];for(let r=0;r<this.local.length;r++)this.local[r].type instanceof jo||n.push(this.local[r]);return n}forEachSet(e){e(this)}}nt.empty=new nt([],[]),nt.removeOverlap=_h;const qt=nt.empty;class Uo{constructor(e){this.members=e}map(e,n){const r=this.members.map(o=>o.map(e,n,Ps));return Uo.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!=qt&&(s instanceof Uo?r=r.concat(s.members):r.push(s))}return Uo.from(r)}eq(e){if(!(e instanceof Uo)||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?_h(r?n:n.sort(Os)):Li}static from(e){switch(e.length){case 0:return qt;case 1:return e[0];default:return new Uo(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 wz(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!=qt?(a[c]=f,a[c+1]=p,a[c+2]=w):(a[c+1]=-2,l=!0)}else l=!0}if(l){let c=vz(a,t,e,n,o,s,i),u=Gc(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(Os),a)}function Vk(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 vz(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 Fk(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 jk(t){let e=[];for(let n=0;n<t.length;n++)t[n]!=null&&e.push(t[n]);return e}function Gc(t,e,n,r){let o=[],s=!1;e.forEach((a,l)=>{let c=Fk(t,a,l+n);if(c){s=!0;let u=Gc(c,a,n+l+1,r);u!=qt&&o.push(l,l+a.nodeSize,u)}});let i=Vk(s?jk(t):t,-n).sort(Os);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):qt}function Os(t,e){return t.from-e.from||t.to-e.to}function _h(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),Uk(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),Uk(e,o,r.copy(s.from,r.to)));break}}}return e}function Uk(t,e,n){for(;e<t.length&&Os(n,t[e])>0;)e++;t.splice(e,0,n)}function xh(t){let e=[];return t.someProp("decorations",n=>{let r=n(t.state);r&&r!=qt&&e.push(r)}),t.cursorWrapper&&e.push(nt.create(t.state.doc,[t.cursorWrapper.deco])),Uo.from(e)}const kz={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},bz=fn&&zo<=11;class Sz{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 Ez{constructor(e,n){this.view=e,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Sz,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&&zo<=11&&r.some(o=>o.type=="childList"&&o.removedNodes.length||o.type=="characterData"&&o.oldValue.length>o.target.nodeValue.length)?this.flushSoon():Yt&&e.composing&&r.some(o=>o.type=="childList"&&o.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),bz&&(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,kz)),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(yk(this.view)){if(this.suppressingSelectionUpdates)return eo(this.view);if(fn&&zo<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&Ms(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=Oi(s))n.add(s);for(let s=e.anchorNode;s;s=Oi(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)&&yk(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(Rn&&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||xz(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&&Uc(r)&&(c=fh(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),Cz(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,Tz(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&&zo<=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?Vt(o)+1:0,a=r.localPosFromDOM(e.target,i,-1),l=s&&s.parentNode==e.target?Vt(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 Wk=new WeakMap,Hk=!1;function Cz(t){if(!Wk.has(t)&&(Wk.set(t,null),["normal","nowrap","pre-line"].indexOf(getComputedStyle(t.dom).whiteSpace)!==-1)){if(t.requiresGeckoHackNode=Rn,Hk)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."),Hk=!0}}function Zk(t,e){let n=e.startContainer,r=e.startOffset,o=e.endContainer,s=e.endOffset,i=t.domAtPos(t.state.selection.anchor);return Ms(i.node,i.offset,o,s)&&([n,r,o,s]=[o,s,n,r]),{anchorNode:n,anchorOffset:r,focusNode:o,focusOffset:s}}function _z(t,e){if(e.getComposedRanges){let o=e.getComposedRanges(t.root)[0];if(o)return Zk(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?Zk(t,n):null}function xz(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 Tz(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 Mz(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}],Uc(l)||c.push({node:l.focusNode,offset:l.focusOffset})),Ft&&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:Az,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 Az(t){let e=t.pmViewDesc;if(e)return e.parseRule();if(t.nodeName=="BR"&&t.parentNode){if(Yt&&/^(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||Yt&&/^(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 Iz=/^(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 Nz(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,T=fh(t,_);if(T&&!t.state.selection.eq(T)){if(Ft&&Xr&&t.input.lastKeyCode===13&&Date.now()-100<t.input.lastKeyCodeTime&&t.someProp("handleKeyDown",B=>B(t,As(13,"Enter"))))return;let I=t.state.tr.setSelection(T);_=="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=Mz(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=Oz(f.content,c.doc.content,c.from,h,p);if(m&&t.input.domChangeCount++,(Di&&t.input.lastIOSEnter>Date.now()-225||Xr)&&o.some(_=>_.nodeType==1&&!Iz.test(_.nodeName))&&(!m||m.endA>=m.endB)&&t.someProp("handleKeyDown",_=>_(t,As(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 _=Kk(t,t.state.doc,c.sel);if(_&&!_.eq(t.state.selection)){let T=t.state.tr.setSelection(_);s&&T.setMeta("composition",s),t.dispatch(T)}}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&&zo<=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((Di&&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,As(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>m.start&&Pz(u,m.start,m.endA,g,y)&&t.someProp("handleKeyDown",_=>_(t,As(8,"Backspace")))){Xr&&Ft&&t.domObserver.suppressSelectionUpdates();return}Ft&&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,As(13,"Enter"))})},20));let b=m.start,S=m.endA,k=_=>{let T=_||t.state.tr.replace(b,S,c.doc.slice(m.start-c.from,m.endB-c.from));if(c.sel){let I=Kk(t,T.doc,c.sel);I&&!(Ft&&t.composing&&I.empty&&(m.start!=m.endB||t.input.lastChromeDelete<Date.now()-100)&&(I.head==b||I.head==T.mapping.map(S)-1)||fn&&I.empty&&I.head==b)&&T.setSelection(I)}return s&&T.setMeta("composition",s),T.scrollIntoView()},E;if(v)if(g.pos==y.pos){fn&&zo<=11&&g.parentOffset==0&&(t.domObserver.suppressSelectionUpdates(),setTimeout(()=>eo(t),20));let _=k(t.state.tr.delete(b,S)),T=u.resolve(m.start).marksAcross(u.resolve(m.endA));T&&_.ensureMarks(T),t.dispatch(_)}else if(m.endA==m.endB&&(E=Bz(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),T=()=>k(t.state.tr.insertText(_,b,S));t.someProp("handleTextInput",I=>I(t,b,S,_,T))||t.dispatch(T())}else t.dispatch(k());else t.dispatch(k())}function Kk(t,e,n){return Math.max(n.anchor,n.head)>e.content.size?null:ph(t,e.resolve(n.anchor),e.resolve(n.head))}function Bz(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 Pz(t,e,n,r,o){if(n-e<=o.pos-r.pos||Th(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(Th(s,!0,!0));return!i.parent.isTextblock||i.pos>n||Th(i,!0,!1)<n?!1:r.parent.content.cut(r.parentOffset).eq(i.parent.content)}function Th(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 Oz(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&&Yk(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&&Yk(t.textBetween(s-1,s+1))&&(s+=l?1:-1),i=s+(i-a),a=s}return{start:s,endA:i,endB:a}}function Yk(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 qk{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 G3,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(e1),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=Xk(this),Jk(this),this.nodeViews=Qk(this),this.docView=sk(this.state.doc,Gk(this),xh(this),this.dom,this),this.domObserver=new Ez(this,(r,o,s,i)=>Nz(this,r,o,s,i)),this.domObserver.start(),J3(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&&kh(this);let n=this._props;this._props=e,e.plugins&&(e.plugins.forEach(e1),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&&(Rk(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=Qk(this);Rz(p,this.nodeViews)&&(this.nodeViews=p,s=!0)}(a||n.handleDOMEvents!=this._props.handleDOMEvents)&&kh(this),this.editable=Xk(this),Jk(this);let l=xh(this),c=Gk(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&&d3(this);if(i){this.domObserver.stop();let p=f&&(fn||Ft)&&!this.composing&&!o.selection.empty&&!e.selection.empty&&Dz(o.selection,e.selection);if(f){let m=Ft?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=dz(this)),(s||!this.docView.update(e.doc,c,l,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=sk(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())&&D3(this))?eo(this,p):(mk(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&&f3(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&&Zv(this,n.getBoundingClientRect(),e)}else Zv(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 $k(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&&h3(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 w3(this,e)}coordsAtPos(e,n=1){return Xv(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 E3(this,n||this.state,e)}pasteHTML(e,n){return Ja(this,"",e,!1,n||new ClipboardEvent("paste"))}pasteText(e,n){return Ja(this,e,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(e){return yh(this,e)}destroy(){this.docView&&(X3(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],xh(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,t3())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return ez(this,e)}domSelectionRange(){let e=this.domSelection();return e?Yt&&this.root.nodeType===11&&i3(this.dom.ownerDocument)==this.dom&&_z(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}qk.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};function Gk(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 Jk(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 Xk(t){return!t.someProp("editable",e=>e(t.state)===!1)}function Dz(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 Qk(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 Rz(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 e1(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 Wo={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:"'"},Jc={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},zz=typeof navigator<"u"&&/Mac/.test(navigator.platform),$z=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),jt=0;jt<10;jt++)Wo[48+jt]=Wo[96+jt]=String(jt);for(var jt=1;jt<=24;jt++)Wo[jt+111]="F"+jt;for(var jt=65;jt<=90;jt++)Wo[jt]=String.fromCharCode(jt+32),Jc[jt]=String.fromCharCode(jt);for(var Mh in Wo)Jc.hasOwnProperty(Mh)||(Jc[Mh]=Wo[Mh]);function Lz(t){var e=zz&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||$z&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",n=!e&&t.key||(t.shiftKey?Jc:Wo)[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 Vz=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),Fz=typeof navigator<"u"&&/Win/.test(navigator.platform);function jz(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))Vz?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 Uz(t){let e=Object.create(null);for(let n in t)e[jz(n)]=t[n];return e}function Ah(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 Wz(t){return new vt({props:{handleKeyDown:t1(t)}})}function t1(t){let e=Uz(t);return function(n,r){let o=Lz(r),s,i=e[Ah(o,r)];if(i&&i(n.state,n.dispatch,n))return!0;if(o.length==1&&o!=" "){if(r.shiftKey){let a=e[Ah(o,r,!1)];if(a&&a(n.state,n.dispatch,n))return!0}if((r.altKey||r.metaKey||r.ctrlKey)&&!(Fz&&r.ctrlKey&&r.altKey)&&(s=Wo[r.keyCode])&&s!=o){let a=e[Ah(s,r)];if(a&&a(n.state,n.dispatch,n))return!0}}return!1}}var Hz=Object.defineProperty,Ih=(t,e)=>{for(var n in e)Hz(t,n,{get:e[n],enumerable:!0})};function Xc(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 Qc=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:Xc({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}},n1={};Ih(n1,{blur:()=>Zz,clearContent:()=>Kz,clearNodes:()=>Yz,command:()=>qz,createParagraphNear:()=>Gz,cut:()=>Jz,deleteCurrentNode:()=>Xz,deleteNode:()=>Qz,deleteRange:()=>e$,deleteSelection:()=>t$,enter:()=>n$,exitCode:()=>r$,extendMarkRange:()=>o$,first:()=>s$,focus:()=>a$,forEach:()=>l$,insertContent:()=>c$,insertContentAt:()=>f$,joinBackward:()=>m$,joinDown:()=>p$,joinForward:()=>g$,joinItemBackward:()=>y$,joinItemForward:()=>w$,joinTextblockBackward:()=>v$,joinTextblockForward:()=>k$,joinUp:()=>h$,keyboardShortcut:()=>S$,lift:()=>E$,liftEmptyBlock:()=>C$,liftListItem:()=>_$,newlineInCode:()=>x$,resetAttributes:()=>T$,scrollIntoView:()=>M$,selectAll:()=>A$,selectNodeBackward:()=>I$,selectNodeForward:()=>N$,selectParentNode:()=>B$,selectTextblockEnd:()=>P$,selectTextblockStart:()=>O$,setContent:()=>D$,setMark:()=>e4,setMeta:()=>t4,setNode:()=>n4,setNodeSelection:()=>r4,setTextDirection:()=>o4,setTextSelection:()=>s4,sinkListItem:()=>i4,splitBlock:()=>a4,splitListItem:()=>l4,toggleList:()=>c4,toggleMark:()=>u4,toggleNode:()=>d4,toggleWrap:()=>f4,undoInputRule:()=>h4,unsetAllMarks:()=>p4,unsetMark:()=>m4,unsetTextDirection:()=>g4,updateAttributes:()=>y4,wrapIn:()=>w4,wrapInList:()=>v4});var Zz=()=>({editor:t,view:e})=>(requestAnimationFrame(()=>{var n;t.isDestroyed||(e.dom.blur(),(n=window==null?void 0:window.getSelection())==null||n.removeAllRanges())}),!0),Kz=(t=!0)=>({commands:e})=>e.setContent("",{emitUpdate:t}),Yz=()=>({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=Mi(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},qz=t=>e=>t(e),Gz=()=>({state:t,dispatch:e})=>Rv(t,e),Jz=(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},Xz=()=>({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 Qz=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},e$=t=>({tr:e,dispatch:n})=>{const{from:r,to:o}=t;return n&&e.delete(r,o),!0},t$=()=>({state:t,dispatch:e})=>Qf(t,e),n$=()=>({commands:t})=>t.keyboardShortcut("Enter"),r$=()=>({state:t,dispatch:e})=>VR(t,e);function Nh(t){return Object.prototype.toString.call(t)==="[object RegExp]"}function eu(t,e,n={strict:!0}){const r=Object.keys(e);return r.length?r.every(o=>n.strict?e[o]===t[o]:Nh(e[o])?e[o].test(t[o]):e[o]===t[o]):!0}function r1(t,e,n={}){return t.find(r=>r.type===e&&eu(Object.fromEntries(Object.keys(n).map(o=>[o,r.attrs[o]])),n))}function o1(t,e,n={}){return!!r1(t,e,n)}function Bh(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),!r1([...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&&o1([...t.parent.child(i-1).marks],e,n);)i-=1,a-=t.parent.child(i).nodeSize;for(;l<t.parent.childCount&&o1([...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 o$=(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=Bh(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},s$=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 ye}function Ds(t=0,e=0,n=0){return Math.min(Math.max(t,e),n)}function i1(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,Ds(0,o,s),Ds(t.content.size,o,s)):ye.create(t,Ds(e,o,s),Ds(e,o,s))}function a1(){return navigator.platform==="Android"||/android/i.test(navigator.userAgent)}function tu(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}function i$(){return typeof navigator<"u"?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}var a$=(t=null,e={})=>({editor:n,view:r,tr:o,dispatch:s})=>{e={scrollIntoView:!0,...e};const i=()=>{(tu()||a1())&&r.dom.focus(),i$()&&!tu()&&!a1()&&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&&!s1(n.state.selection))return i(),!0;const a=i1(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},l$=(t,e)=>n=>t.every((r,o)=>e(r,{...n,index:o})),c$=(t,e)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},t,e),l1=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&&l1(r)}return t};function Qa(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 l1(n)}function el(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),el("",e,n)}if(o){if(n.errorOnInvalidContent){let i=!1,a="";const l=new Kw({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(Qa(t),n.parseOptions):qr.fromSchema(l).parse(Qa(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(Qa(t),n.parseOptions).content:s.parse(Qa(t),n.parseOptions)}return el("",e,n)}function u$(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 d$=t=>!("type"in t),f$=(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{el(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(y){l(y)}try{a=el(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((d$(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&&u$(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},h$=()=>({state:t,dispatch:e})=>zR(t,e),p$=()=>({state:t,dispatch:e})=>$R(t,e),m$=()=>({state:t,dispatch:e})=>Av(t,e),g$=()=>({state:t,dispatch:e})=>Pv(t,e),y$=()=>({state:t,dispatch:e,tr:n})=>{try{const r=Lc(t.doc,t.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},w$=()=>({state:t,dispatch:e,tr:n})=>{try{const r=Lc(t.doc,t.selection.$from.pos,1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},v$=()=>({state:t,dispatch:e})=>DR(t,e),k$=()=>({state:t,dispatch:e})=>RR(t,e);function c1(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function b$(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))tu()||c1()?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 S$=t=>({editor:e,view:n,tr:r,dispatch:o})=>{const s=b$(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 tl(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=>eu(f.node.attrs,n,{strict:!1}));return s?!!c.length:c.reduce((f,h)=>f+h.to-h.from,0)>=l}var E$=(t,e={})=>({state:n,dispatch:r})=>{const o=It(t,n.schema);return tl(n,o,e)?LR(n,r):!1},C$=()=>({state:t,dispatch:e})=>zv(t,e),_$=t=>({state:e,dispatch:n})=>{const r=It(t,e.schema);return JR(r)(e,n)},x$=()=>({state:t,dispatch:e})=>Dv(t,e);function nu(t,e){return e.nodes[t]?"node":e.marks[t]?"mark":null}function u1(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$=(t,e)=>({tr:n,state:r,dispatch:o})=>{let s=null,i=null;const a=nu(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,u1(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(u1(h.attrs,e))))})})}),l},M$=()=>({tr:t,dispatch:e})=>(e&&t.scrollIntoView(),!0),A$=()=>({tr:t,dispatch:e})=>{if(e){const n=new _n(t.doc);t.setSelection(n)}return!0},I$=()=>({state:t,dispatch:e})=>Nv(t,e),N$=()=>({state:t,dispatch:e})=>Ov(t,e),B$=()=>({state:t,dispatch:e})=>UR(t,e),P$=()=>({state:t,dispatch:e})=>ZR(t,e),O$=()=>({state:t,dispatch:e})=>HR(t,e);function Ph(t,e,n={},r={}){return el(t,e,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}var D$=(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=Ph(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 d1(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 R$(t,e){const n=new vv(t);return e.forEach(r=>{r.steps.forEach(o=>{n.step(o)})}),n}function z$(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 $$(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 Oh(t){return e=>$$(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 Dh(t){return t.map(e=>{const n={name:e.name,options:e.options,storage:e.storage},r=oe(e,"addExtensions",n);return r?[e,...Dh(r())]:e}).flat(10)}function ru(t,e){const n=_s.fromSchema(e).serializeFragment(t),o=document.implementation.createHTMLDocument().createElement("div");return o.appendChild(n),o.innerHTML}function f1(t){return typeof t=="function"}function je(t,e=void 0,...n){return f1(t)?e?t.bind(e)(...n):t(...n):t}function L$(t={}){return Object.keys(t).length===0&&t.constructor===Object}function Vi(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 h1(t){const e=[],{nodeExtensions:n,markExtensions:r}=Vi(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 Fi(...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 ou(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)=>Fi(n,r),{})}function V$(t){return typeof t!="string"?t:t.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(t):t==="true"?!0:t==="false"?!1:t}function p1(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):V$(n.getAttribute(i.name));return a==null?s:{...s,[i.name]:a}},{});return{...r,...o}}}}function m1(t){return Object.fromEntries(Object.entries(t).filter(([e,n])=>e==="attrs"&&L$(n)?!1:n!=null))}function g1(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 y1(t,e){var n;const r=h1(t),{nodeExtensions:o,markExtensions:s}=Vi(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=m1({...h,content:je(oe(c,"content",f)),marks:je(oe(c,"marks",f)),group:je(oe(c,"group",f)),inline:je(oe(c,"inline",f)),atom:je(oe(c,"atom",f)),selectable:je(oe(c,"selectable",f)),draggable:je(oe(c,"draggable",f)),code:je(oe(c,"code",f)),whitespace:je(oe(c,"whitespace",f)),linebreakReplacement:je(oe(c,"linebreakReplacement",f)),defining:je(oe(c,"defining",f)),isolating:je(oe(c,"isolating",f)),attrs:Object.fromEntries(u.map(g1))}),m=je(oe(c,"parseHTML",f));m&&(p.parseDOM=m.map(w=>p1(w,u)));const g=oe(c,"renderHTML",f);g&&(p.toDOM=w=>g({node:w,HTMLAttributes:ou(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=m1({...h,inclusive:je(oe(c,"inclusive",f)),excludes:je(oe(c,"excludes",f)),group:je(oe(c,"group",f)),spanning:je(oe(c,"spanning",f)),code:je(oe(c,"code",f)),attrs:Object.fromEntries(u.map(g1))}),m=je(oe(c,"parseHTML",f));m&&(p.parseDOM=m.map(y=>p1(y,u)));const g=oe(c,"renderHTML",f);return g&&(p.toDOM=y=>g({mark:y,HTMLAttributes:ou(y,u)})),[c.name,p]}));return new Kw({topNode:i,nodes:a,marks:l})}function F$(t){const e=t.filter((n,r)=>t.indexOf(n)!==r);return Array.from(new Set(e))}function nl(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 Rh(t){const e=nl(Dh(t)),n=F$(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 w1(t,e){const n=Rh(t);return y1(n,e)}function su(t,e){const n=w1(e),r=Yr.fromJSON(n,t);return ru(r.content,n)}function Ho(t,e){const n=w1(e),r=Qa(t);return qr.fromSchema(n).parse(r).toJSON()}function v1(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 j$(t,e){const n={from:0,to:t.content.size};return v1(t,n,e)}function k1(t){return Object.fromEntries(Object.entries(t.nodes).filter(([,e])=>e.spec.toText).map(([e,n])=>[e,n.spec.toText]))}function U$(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 W$(t,e){const n=nu(typeof e=="string"?e:e.name,t.schema);return n==="node"?U$(t,e):n==="mark"?d1(t,e):{}}function H$(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 Z$(t){const e=H$(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 K$(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}})})}),Z$(r)}function b1(t,e,n){const r=[];return t===e?n.resolve(t).marks().forEach(o=>{const s=n.resolve(t),i=Bh(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 rl(t,e){return e.nodes[t]||e.marks[t]||null}function iu(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 Y$=(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 zh(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=>eu(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=>eu(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 q$(t,e,n={}){if(!e)return tl(t,null,n)||zh(t,null,n);const r=nu(e,t.schema);return r==="node"?tl(t,e,n):r==="mark"?zh(t,e,n):!1}function S1(t,e){return Array.isArray(e)?e.some(n=>(typeof n=="string"?n:n.name)===t.name):e}function E1(t,e){const{nodeExtensions:n}=Vi(e),r=n.find(i=>i.name===t);if(!r)return!1;const o={name:r.name,options:r.options,storage:r.storage},s=je(oe(r,"group",o));return typeof s!="string"?!1:s.split(" ").includes("list")}function au(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&&(au(s,{ignoreWhitespace:n,checkChildren:e})||(o=!1))}),o}return!1}function G$(t){return t instanceof ae}var C1=class SS{constructor(e){this.position=e}static fromJSON(e){return new SS(e.position)}toJSON(){return{position:this.position}}};function J$(t,e){const n=e.mapping.mapResult(t.position);return{position:new C1(n.pos),mapResult:n}}function X$(t){return new C1(t)}function Q$(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 e4=(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=d1(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 Q$(r,n,l)},t4=(t,e)=>({tr:n})=>(n.setMeta(t,e),!0),n4=(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})=>Vv(s,{...i,...e})(n)?!0:a.clearNodes()).command(({state:a})=>Vv(s,{...i,...e})(a,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},r4=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,o=Ds(t,0,r.content.size),s=ae.create(r,o);e.setSelection(s)}return!0},o4=(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},s4=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=Ds(o,i,a),c=Ds(s,i,a),u=ye.create(r,l,c);e.setSelection(u)}return!0},i4=t=>({state:e,dispatch:n})=>{const r=It(t,e.schema);return e3(r)(e,n)};function _1(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 a4=({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=iu(c,a.node().type.name,a.node().attrs);if(s instanceof ae&&s.node.isBlock)return!a.parentOffset||!Gr(i,a.pos)?!1:(r&&(t&&_1(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:z$(a.node(-1).contentMatchAt(a.indexAfter(-1)));let p=f&&h?[{type:h,attrs:u}]:void 0,m=Gr(e.doc,e.mapping.map(a.pos),1,p);if(!p&&!m&&Gr(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&&_1(n,o.extensionManager.splittableMarks),e.scrollIntoView()}return m},l4=(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 T=l.depth-v;T>=l.depth-3;T-=1)w=D.from(l.node(T).copy(w));const b=l.indexAfter(-1)<l.node(-2).childCount?1:l.indexAfter(-2)<l.node(-3).childCount?2:3,S={...iu(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,(T,I)=>{if(_>-1)return!1;T.isTextblock&&T.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={...iu(h,f.type.name,f.attrs),...e},g={...iu(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(!Gr(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},$h=(t,e)=>{const n=Oh(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)&&Ts(t.doc,n.pos)&&t.join(n.pos),!0},Lh=(t,e)=>{const n=Oh(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)&&Ts(t.doc,r)&&t.join(r),!0},c4=(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=Oh(E=>E1(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(E1(k.node.type.name,f)&&p.validContent(k.node.content)&&a)return l().command(()=>(s.setNodeMarkup(k.pos,p),!0)).command(()=>$h(s,p)).command(()=>Lh(s,p)).run()}return!n||!S||!a?l().command(()=>u().wrapInList(p,r)?!0:c.clearNodes()).wrapInList(p,r).command(()=>$h(s,p)).command(()=>Lh(s,p)).run():l().command(()=>{const E=u().wrapInList(p,r),_=S.filter(T=>h.includes(T.type.name));return s.ensureMarks(_),E?!0:c.clearNodes()}).wrapInList(p,r).command(()=>$h(s,p)).command(()=>Lh(s,p)).run()},u4=(t,e={},n={})=>({state:r,commands:o})=>{const{extendEmptyMarkRange:s=!1}=n,i=to(t,r.schema);return zh(r,i,e)?o.unsetMark(i,{extendEmptyMarkRange:s}):o.setMark(i,e)},d4=(t,e,n={})=>({state:r,commands:o})=>{const s=It(t,r.schema),i=It(e,r.schema),a=tl(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})},f4=(t,e={})=>({state:n,commands:r})=>{const o=It(t,n.schema);return tl(n,o,e)?r.lift(o):r.wrapIn(o,e)},h4=()=>({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},p4=()=>({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},m4=(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=Bh(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},g4=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},y4=(t,e={})=>({tr:n,state:r,dispatch:o})=>{let s=null,i=null;const a=nu(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},w4=(t,e={})=>({state:n,dispatch:r})=>{const o=It(t,n.schema);return KR(o,e)(n,r)},v4=(t,e={})=>({state:n,dispatch:r})=>{const o=It(t,n.schema);return YR(o,e)(n,r)},k4=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={}}},b4=class{constructor(t){var e;this.find=t.find,this.handler=t.handler,this.undoable=(e=t.undoable)!=null?e:!0}},S4=(t,e)=>{if(Nh(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 lu(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=Y$(c)+s;return i.forEach(h=>{if(u)return;const p=S4(f,h.find);if(!p)return;const m=l.state.tr,g=Xc({state:l.state,transaction:m}),y={from:r-(p[0].length-s.length),to:o},{commands:w,chain:v,can:b}=new Qc({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 E4(t){const{editor:e,rules:n}=t,r=new vt({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=ru(D.from(u),i.schema);const{from:f}=l,h=f+u.length;lu({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 lu({editor:e,from:s,to:i,text:a,rules:n,plugin:r})},handleDOMEvents:{compositionend:o=>(setTimeout(()=>{const{$cursor:s}=o.state.selection;s&&lu({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?lu({editor:e,from:i.pos,to:i.pos,text:`
81
- `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function C4(t){return Object.prototype.toString.call(t).slice(8,-1)}function cu(t){return C4(t)!=="Object"?!1:t.constructor===Object&&Object.getPrototypeOf(t)===Object.prototype}function x1(t,e){const n={...t};return cu(t)&&cu(e)&&Object.keys(e).forEach(r=>{cu(e[r])&&cu(t[r])?n[r]=x1(t[r],e[r]):n[r]=e[r]}),n}var Vh=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{...je(oe(this,"addOptions",{name:this.name}))||{}}}get storage(){return{...je(oe(this,"addStorage",{name:this.name,options:this.options}))||{}}}configure(t={}){const e=this.extend({...this.config,addOptions:()=>x1(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}},ol=class ES extends Vh{constructor(){super(...arguments),this.type="mark"}static create(e={}){const n=typeof e=="function"?e():e;return new ES(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 _4(t){return typeof t=="number"}var x4=class{constructor(t){this.find=t.find,this.handler=t.handler}},T4=(t,e,n)=>{if(Nh(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 M4(t){const{editor:e,state:n,from:r,to:o,rule:s,pasteEvent:i,dropEvent:a}=t,{commands:l,chain:c,can:u}=new Qc({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,"");T4(_,s.find,i).forEach(I=>{if(I.index===void 0)return;const B=k+I.index+1,L=B+I[0].length,Z={from:n.tr.mapping.map(B),to:n.tr.mapping.map(L)},M=s.handler({state:n,range:Z,match:I,commands:l,chain:c,can:u,pasteEvent:i,dropEvent:a});f.push(M)})}),f.every(p=>p!==null)}var uu=null,A4=t=>{var e;const n=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=n.clipboardData)==null||e.setData("text/html",t),n};function I4(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=Xc({state:u,transaction:g});if(!(!M4({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 vt({view(f){const h=m=>{var g;r=(g=f.dom.parentElement)!=null&&g.contains(m.target)?f.dom.parentElement:null,r&&(uu=e)},p=()=>{uu&&(uu=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=uu;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=ru(D.from(k),p.schema);const{from:E}=w,_=E+k.length,T=A4(k);return l({rule:u,state:p,from:E,to:{b:_},pasteEvt:T})}const b=h.doc.content.findDiffStart(p.doc.content),S=h.doc.content.findDiffEnd(p.doc.content);if(!(!_4(b)||!S||b===S.b))return l({rule:u,state:p,from:b,to:S,pasteEvt:i})}}))}var du=class{constructor(t,e){this.splittableMarks=[],this.editor=e,this.baseExtensions=t,this.extensions=Rh(t),this.schema=y1(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:rl(e.name,this.schema)},r=oe(e,"addCommands",n);return r?{...t,...r()}:t},{})}get plugins(){const{editor:t}=this;return nl([...this.extensions].reverse()).flatMap(r=>{const o={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:t,type:rl(r.name,this.schema)},s=[],i=oe(r,"addKeyboardShortcuts",o);let a={};if(r.type==="mark"&&oe(r,"exitable",o)&&(a.ArrowRight=()=>ol.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=Wz(a);s.push(l);const c=oe(r,"addInputRules",o);if(S1(r,t.options.enableInputRules)&&c){const h=c();if(h&&h.length){const p=E4({editor:t,rules:h}),m=Array.isArray(p)?p:[p];s.push(...m)}}const u=oe(r,"addPasteRules",o);if(S1(r,t.options.enablePasteRules)&&u){const h=u();if(h&&h.length){const p=I4({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 h1(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:e}=Vi(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=ou(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 nl([...this.extensions].reverse()).reduceRight((r,o)=>{const s={name:o.name,options:o.options,storage:this.editor.extensionStorage[o.name],editor:e,type:rl(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 nl([...this.extensions]).reduce((r,o)=>{const s={name:o.name,options:o.options,storage:this.editor.extensionStorage[o.name],editor:e,type:rl(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}=Vi(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=ou(a,r);return s()({mark:a,view:l,inline:c,editor:t,extension:n,HTMLAttributes:u,updateAttributes:f=>{W4(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:rl(e.name,this.schema)};e.type==="mark"&&((n=je(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)})}};du.resolve=Rh,du.sort=nl,du.flatten=Dh;var N4={};Ih(N4,{ClipboardTextSerializer:()=>T1,Commands:()=>M1,Delete:()=>A1,Drop:()=>I1,Editable:()=>N1,FocusEvents:()=>P1,Keymap:()=>O1,Paste:()=>D1,Tabindex:()=>R1,TextDirection:()=>z1,focusEventsPluginKey:()=>B1});var Ye=class CS extends Vh{constructor(){super(...arguments),this.type="extension"}static create(e={}){const n=typeof e=="function"?e():e;return new CS(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}},T1=Ye.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new vt({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=k1(n);return v1(r,{from:i,to:a},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:l})}}})]}}),M1=Ye.create({name:"commands",addCommands(){return{...n1}}}),A1=Ye.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=R$(t.before,[t,...e]);K$(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 rr){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()}}),I1=Ye.create({name:"drop",addProseMirrorPlugins(){return[new vt({key:new tn("tiptapDrop"),props:{handleDrop:(t,e,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:n,moved:r})}}})]}}),N1=Ye.create({name:"editable",addProseMirrorPlugins(){return[new vt({key:new tn("editable"),props:{editable:()=>this.editor.options.editable}})]}}),B1=new tn("focusEvents"),P1=Ye.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:t}=this;return[new vt({key:B1,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}}}})]}}),O1=Ye.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 tu()||c1()?s:o},addProseMirrorPlugins(){return[new vt({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)||!au(n.doc))return;const h=n.tr,p=Xc({state:n,transaction:h}),{commands:m}=new Qc({editor:this.editor,state:p});if(m.clearNodes(),!!h.steps.length)return h}})]}}),D1=Ye.create({name:"paste",addProseMirrorPlugins(){return[new vt({key:new tn("tiptapPaste"),props:{handlePaste:(t,e,n)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:n})}}})]}}),R1=Ye.create({name:"tabindex",addProseMirrorPlugins(){return[new vt({key:new tn("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}}),z1=Ye.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:t}=Vi(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 vt({key:new tn("textDirection"),props:{attributes:()=>{const t=this.options.direction;return t?{dir:t}:{}}}})]}}),B4=class hl{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 hl(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 hl(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 hl(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 hl(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)}},P4=`.ProseMirror {
31
+ </svg>`}var Sv={drag:{makeSvg:()=>bv,hotspot:[12,12],rotationOffset:0},ns:{makeSvg:oi,hotspot:[12,12],rotationOffset:0},ew:{makeSvg:oi,hotspot:[12,12],rotationOffset:Math.PI/2},nwse:{makeSvg:oi,hotspot:[12,12],rotationOffset:-Math.PI/4},nesw:{makeSvg:oi,hotspot:[12,12],rotationOffset:Math.PI/4},rotateNW:{makeSvg:si,hotspot:[16,16],rotationOffset:0},rotateNE:{makeSvg:si,hotspot:[16,16],rotationOffset:Math.PI/2},rotateSW:{makeSvg:si,hotspot:[16,16],rotationOffset:-Math.PI/2},rotateSE:{makeSvg:si,hotspot:[16,16],rotationOffset:-Math.PI}},de={Idle:"idle",Pointing:"pointing",Dragging:"dragging",SelectionBoxPointing:"selectionBoxPointing",SelectionBoxDragging:"selectionBoxDragging"},_t={None:"none",Idle:"idle",Editing:"editing"},Et={Scale:"scale",Stretch:"stretch",Rotate:"rotate"},ht={Idle:"idle",Waiting:"waiting",Scrolling:"scrolling"},wf=rn.object({enabled:rn.boolean().default(!0),edgeSizePx:rn.number().default(10),edgeScrollSpeedPxPerFrame:rn.number().default(15),edgeScrollDelayMs:rn.number().default(250)}),Cv=rn.object({edgeScrolling:wf.default(wf.parse({}))}),ve=h.defineCanvasComponent({name:"transformHandle"},{kind:h.field.string().max(16).default(Et.Scale),vectorX:h.field.int8().default(0),vectorY:h.field.int8().default(0),transformBox:h.field.ref(),cursorKind:h.field.string().max(16).default("drag")}),vf="selection";function xv(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]=_v(t,a)}return r}function _v(t,e){return e==null||!h.hasComponent(t,e,h.Synced)?null:h.Synced.read(t,e).id}function Ev(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 Tv(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 Mv=h.defineQuery(t=>t.with(Ie));h.defineQuery(t=>t.with(h.Block));function Qr(t,e){if(h.hasComponent(t,e,Ie)||h.isHeldByRemote(t,e))return;const{sessionId:n}=h.getResources(t);h.addComponent(t,e,Ie,{}),h.hasComponent(t,e,h.Held)||h.addComponent(t,e,h.Held,{sessionId:n})}function Jo(t,e){h.hasComponent(t,e,Ie)&&(h.removeComponent(t,e,Ie),h.removeComponent(t,e,h.Held))}function bf(t){for(const e of Mv.current(t))Jo(t,e)}function Av(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 Nv=class{constructor(t){this.seed=typeof t=="string"?Av(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 Sl(t,e){const n=t+e,r=new Nv(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 Sf={};Yr(Sf,{Clipboard:()=>qo,ScrollEdgesStateSingleton:()=>Cl,SelectionStateSingleton:()=>Tt,TransformBoxStateSingleton:()=>xl});var Bv={count:h.field.uint32().default(0),center:h.field.tuple(h.field.float64(),2).default([0,0])},ii=new WeakMap,Ov=class extends h.CanvasSingletonDef{constructor(){super({name:"clipboard"},Bv)}setEntities(t,e){const{editor:n}=h.getResources(t);ii.set(n,e)}getEntities(t){const{editor:e}=h.getResources(t);return ii.get(e)??[]}clearEntities(t){const{editor:e}=h.getResources(t);ii.delete(e)}hasContent(t){const{editor:e}=h.getResources(t),n=ii.get(e);return n!==void 0&&n.length>0}},qo=new Ov,Cl=h.defineEditorState("scrollEdgesState",{state:h.field.enum(ht).default(ht.Idle),edgeEnterStartTime:h.field.float64().default(0)}),Tt=h.defineEditorState("selectionState",{state:h.field.enum(de).default(de.Idle),dragStart:h.field.tuple(h.field.float64(),2).default([0,0]),pointingStartClient:h.field.tuple(h.field.float64(),2).default([0,0]),pointingStartWorld:h.field.tuple(h.field.float64(),2).default([0,0]),draggedEntityStart:h.field.tuple(h.field.float64(),2).default([0,0]),draggedEntity:h.field.ref(),cloneGeneratorSeed:h.field.string().max(36).default(""),isCloning:h.field.boolean()}),xl=h.defineEditorState("transformBoxState",{state:h.field.string().max(32).default(_t.None),transformBoxId:h.field.ref()}),Cf={};Yr(Cf,{hoverCursorSystem:()=>Pv,scrollEdgesSystem:()=>Dv,transformBoxSystem:()=>Vv});var _l=h.defineQuery(t=>t.with(h.Hovered,ve).tracking(h.Hovered)),Iv=h.defineQuery(t=>t.with(h.Block,Ye).tracking(h.Block)),Pv=h.defineEditorSystem({phase:"capture"},t=>{const e=_l.added(t),n=_l.removed(t),r=_l.current(t),o=Iv.changed(t);if(r.length===0&&n.length>0){h.Cursor.clearContextCursor(t);return}if((e.length>0||o.length>0)&&r.length>0){const i=r[0],a=ve.read(t,i);if(a.transformBox===null)return;const l=h.Block.read(t,a.transformBox),c=h.Cursor.read(t);(a.cursorKind!==c.contextCursorKind||l.rotateZ!==c.contextRotation)&&h.Cursor.setContextCursor(t,a.cursorKind,l.rotateZ)}});function ai(t){return h.getPluginResources(t,vf).edgeScrolling}var Rv=on({guards:{isPointerNearEdge:({event:t})=>{const{edgeSizePx:e}=ai(t.ctx),n=h.Screen.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}=ai(e.ctx);return performance.now()-t.edgeEnterStartTime>=n}},actions:{setEdgeEnterStartTime:we({edgeEnterStartTime:()=>performance.now()}),moveCamera:({event:t})=>{const{edgeSizePx:e,edgeScrollSpeedPxPerFrame:n}=ai(t.ctx),r=h.Screen.read(t.ctx),o=h.Camera.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 p=h.Camera.write(t.ctx);p.left+=c,p.top+=u},resetContext:we({edgeEnterStartTime:0})}}).createMachine({id:"scrollEdges",initial:ht.Idle,context:{edgeEnterStartTime:0},states:{[ht.Idle]:{entry:"resetContext",on:{pointerMove:{guard:"isPointerNearEdge",target:ht.Waiting}}},[ht.Waiting]:{entry:"setEdgeEnterStartTime",on:{pointerMove:{guard:nr("isPointerNearEdge"),target:ht.Idle},frame:{guard:"isEdgeScrollDelayPassed",target:ht.Scrolling}}},[ht.Scrolling]:{on:{frame:[{guard:nr("isPointerNearEdge"),target:ht.Idle},{actions:"moveCamera"}]}}}}),Dv=h.defineEditorSystem({phase:"capture"},t=>{if(!ai(t).enabled)return;const e=Tt.read(t).state;if(e!==de.Dragging&&e!==de.SelectionBoxDragging)return;const n=Cl.read(t).state,r=n===ht.Waiting||n===ht.Scrolling,o=h.Controls.getButtons(t,"select"),s=h.getPointerInput(t,o,{includeFrameEvent:r});s.length!==0&&Cl.run(t,Rv,s)}),li=h.defineQuery(t=>t.with(h.Block).tracking(Ie)),zv=on({guards:{isSelectionEditable:({event:t})=>$v(t.ctx),isOverTransformBox:({event:t})=>!("intersects"in t)||t.intersects.length===0?!1:h.hasComponent(t.ctx,t.intersects[0],Ye),isOverTransformHandle:({event:t})=>!("intersects"in t)||t.intersects.length===0?!1:h.hasComponent(t.ctx,t.intersects[0],ve),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];return h.getBlockResizeMode(t.ctx,e)!==h.ResizeMode.GroupOnly},hasEditAfterPlacing:({event:t})=>t.type!=="selectionChanged"||t.selectedEntityIds.length!==1?!1:h.hasComponent(t.ctx,t.selectedEntityIds[0],Ko)},actions:{addTransformBox:we(({context:t,event:e},n)=>{t.transformBoxId!==null&&bl.spawn(e.ctx,{transformBoxId:t.transformBoxId});const r=h.createEntity(e.ctx);return pf.spawn(e.ctx,{transformBoxId:r,skipHandles:n==null?void 0:n.skipHandles}),{transformBoxId:r}}),updateTransformBox:({context:t,event:e})=>{t.transformBoxId!==null&&vl.spawn(e.ctx,{transformBoxId:t.transformBoxId})},hideTransformBox:({context:t,event:e})=>{t.transformBoxId!==null&&mf.spawn(e.ctx,{transformBoxId:t.transformBoxId})},showTransformBox:({context:t,event:e})=>{t.transformBoxId!==null&&gf.spawn(e.ctx,{transformBoxId:t.transformBoxId})},removeTransformBox:({context:t,event:e})=>{t.transformBoxId!==null&&bl.spawn(e.ctx,{transformBoxId:t.transformBoxId})},clearTransformBoxId:we({transformBoxId:()=>null}),startTransformBoxEdit:({context:t,event:e})=>{t.transformBoxId!==null&&yf.spawn(e.ctx,{transformBoxId:t.transformBoxId})},removeEditAfterPlacing:({event:t})=>{if(t.type==="selectionChanged")for(const e of t.selectedEntityIds)h.hasComponent(t.ctx,e,Ko)&&h.removeComponent(t.ctx,e,Ko)}}}).createMachine({id:"transformBox",initial:_t.None,context:{transformBoxId:null},states:{[_t.None]:{entry:["removeTransformBox","clearTransformBoxId"],on:{selectionChanged:[{guard:Ho(["hasEditAfterPlacing","selectionIsTransformable","isSelectionEditable"]),actions:[{type:"addTransformBox",params:{skipHandles:!0}},"removeEditAfterPlacing"],target:_t.Editing},{guard:"selectionIsTransformable",target:_t.Idle}]}},[_t.Idle]:{entry:["addTransformBox"],on:{selectionChanged:[{guard:nr("selectionIsTransformable"),target:_t.None},{guard:"selectionIsTransformable",actions:"showTransformBox"},{actions:"updateTransformBox"}],pointerDown:{actions:"hideTransformBox"},pointerUp:{actions:"showTransformBox"},click:{guard:Ho(["isOverTransformBox","isSelectionEditable"]),target:_t.Editing}}},[_t.Editing]:{entry:["hideTransformBox","startTransformBoxEdit"],on:{pointerDown:{guard:Ho([nr("isOverTransformBox"),nr("isOverTransformHandle")]),target:_t.None},selectionChanged:{target:_t.None,actions:ei(({event:t})=>t)}}}}});function $v(t){const e=li.current(t);if(e.length!==1)return!1;const n=e[0],r=h.Block.read(t,n);return h.canBlockEdit(t,r.tag)}var Vv=h.defineEditorSystem({phase:"capture"},t=>{const e=[],n=li.added(t),r=li.removed(t);if(n.length>0||r.length>0){const i=[...li.current(t)],a={type:"selectionChanged",ctx:t,selectedEntityIds:i};e.push(a)}const o=h.Controls.getButtons(t,"select"),s=h.getPointerInput(t,o);e.push(...s),e.length!==0&&xl.run(t,zv,e)}),xf={};Yr(xf,{transformBoxSystem:()=>Wv});var ci=h.defineQuery(t=>t.with(h.Block,Ie)),Lv=h.defineQuery(t=>t.with(h.Block,h.Edited)),Fv="a",jv="b",_f="c",Hv="d",Wv=h.defineEditorSystem({phase:"update",priority:-100},t=>{h.on(t,bl,(e,{transformBoxId:n})=>{Zv(e,n)}),h.on(t,pf,(e,{transformBoxId:n,skipHandles:r})=>{Uv(e,n,r)}),h.on(t,vl,(e,{transformBoxId:n})=>{El(e,n)}),h.on(t,mf,(e,{transformBoxId:n})=>{Jv(e,n)}),h.on(t,gf,(e,{transformBoxId:n})=>{qv(e,n)}),h.on(t,yf,(e,{transformBoxId:n})=>{Gv(e,n)}),h.on(t,vv,Tl)});function Zv(t,e){if(!h.hasComponent(t,e,Ye)){Tl(t);return}const n=h.getBackrefs(t,e,ve,"transformBox");for(const r of n)h.removeEntity(t,r);h.removeEntity(t,e),Tl(t)}function Uv(t,e,n){h.addComponent(t,e,h.Block,{tag:"transform-box",position:[0,0],size:[0,0],rotateZ:0,rank:Fv}),h.addComponent(t,e,Ye,{}),h.addComponent(t,e,Ae,{position:[0,0],size:[0,0],rotateZ:0,fontSize:16}),n||El(t,e)}function El(t,e){if(!h.isAlive(t,e))return;const n=ci.current(t);if(n.length===0)return;let r=0;r=h.Block.read(t,n[0]).rotateZ;for(let c=1;c<n.length;c++){const u=h.Block.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=h.Block.getCorners(t,c);s.push(...u)}if(s.length===0)return;const i=h.Block.write(t,e);if(i.rotateZ=r,E.Rect.boundPoints(i.position,i.size,r,s),!(Tt.read(t).state===de.Dragging)){if(h.hasComponent(t,e,Ae)){const c=Ae.write(t,e);c.position=i.position,c.size=i.size,c.rotateZ=r}for(const c of n){const u=h.Block.read(t,c),f=h.hasComponent(t,c,h.Text)?h.Text.read(t,c).fontSizePx:16;if(!h.hasComponent(t,c,Ae))h.addComponent(t,c,Ae,{position:u.position,size:u.size,rotateZ:u.rotateZ,flip:u.flip,fontSize:f});else{const p=Ae.write(t,c);p.position=u.position,p.size=u.size,p.rotateZ=u.rotateZ,p.flip=u.flip,p.fontSize=f}}}Kv(t,e)}function Kv(t,e){const n=h.Block.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,p=2*f,m=1.25*f,g=[],y=["rotateNW","rotateNE","rotateSW","rotateSE"],k=ci.current(t);let w=h.ResizeMode.Scale;k.length===1?w=h.getBlockResizeMode(t,k[0]):k.length>1&&k.every($=>h.getBlockResizeMode(t,$)===h.ResizeMode.Free)&&(w=h.ResizeMode.Free);const v=k.every(M=>{const $=h.Block.read(t,M);return h.getBlockDef(t,$.tag).canRotate}),b=k.every(M=>{const $=h.Block.read(t,M);return h.getBlockDef(t,$.tag).canScale});let S;switch(w){case"scale":case"text":S=Et.Scale;break;case"free":S=Et.Stretch;break;default:S=Et.Scale;break}const C=h.Camera.read(t),x=l*C.zoom,_=c*C.zoom,T=Math.min(x,_),N=15;for(let M=0;M<2;M++)for(let $=0;$<2;$++)M+$!==1&&T<N/2||M+$===1&&_<N||(b&&g.push({tag:"transform-handle",kind:S,vectorX:M*2-1,vectorY:$*2-1,left:i+l*M-f/2,top:a+c*$-f/2,width:f,height:f,rotateZ:s,rank:Hv,cursorKind:M+$===1?"nesw":"nwse",scaleMultiplier:[1,1],anchor:[.5,.5]}),v&&g.push({tag:"transform-rotate",kind:Et.Rotate,vectorX:M*2-1,vectorY:$*2-1,left:i+M*l-(1-M)*p,top:a+$*c-(1-$)*p,width:p,height:p,rotateZ:s,rank:jv,cursorKind:y[M+$*2],scaleMultiplier:[.5,.5],anchor:[1-M,1-$]}));if(b)for(let M=0;M<2;M++)g.push({tag:"transform-edge",kind:S,vectorX:0,vectorY:M*2-1,left:i,top:a+c*M-m/2,width:l,height:m,rotateZ:s,rank:_f,cursorKind:"ns",scaleMultiplier:[0,1],anchor:[.5,.5]});if(b||w===h.ResizeMode.Text)for(let M=0;M<2;M++)g.push({tag:"transform-edge",kind:w===h.ResizeMode.Text?Et.Stretch:S,vectorX:M*2-1,vectorY:0,left:i+l*M-m/2,top:a,width:m,height:c,rotateZ:s,rank:_f,cursorKind:"ew",scaleMultiplier:[1,0],anchor:[.5,.5]});const I=h.getBackrefs(t,e,ve,"transformBox"),V=new Map;for(const M of I){const $=ve.read(t,M),Z=`${$.kind}-${$.vectorX}-${$.vectorY}`;V.set(Z,M)}const K=new Set;for(const M of g){const $=`${M.kind}-${M.vectorX}-${M.vectorY}`;let Z=V.get($);const ae=[M.left+M.width/2,M.top+M.height/2],X=E.Vec2.clone(ae);E.Vec2.rotateAround(X,u,s);const j=X[0]-M.width/2,q=X[1]-M.height/2;Z||(Z=h.createEntity(t),h.addComponent(t,Z,h.Block),h.addComponent(t,Z,ve),h.addComponent(t,Z,Ae),h.addComponent(t,Z,h.ScaleWithZoom));const te=h.Block.write(t,Z);te.tag=M.tag,te.position=[j,q],te.size=[M.width,M.height],te.rotateZ=M.rotateZ,te.rank=M.rank;const fe=ve.write(t,Z);fe.transformBox=e,fe.kind=M.kind,fe.vectorX=M.vectorX,fe.vectorY=M.vectorY,fe.cursorKind=M.cursorKind;const ce=Ae.write(t,Z);ce.position=[j,q],ce.size=[M.width,M.height],ce.rotateZ=M.rotateZ;const Se=h.ScaleWithZoom.write(t,Z);Se.startPosition=[j,q],Se.startSize=[M.width,M.height],E.Vec2.copy(Se.scaleMultiplier,M.scaleMultiplier),E.Vec2.copy(Se.anchor,M.anchor),K.add(Z)}for(const M of I)K.has(M)||h.removeEntity(t,M)}function Jv(t,e){if(!h.hasComponent(t,e,Ye))return;if(!h.hasComponent(t,e,h.Opacity))h.addComponent(t,e,h.Opacity,{value:0});else{const r=h.Opacity.write(t,e);r.value=0}const n=h.getBackrefs(t,e,ve,"transformBox");for(const r of n)if(!h.hasComponent(t,r,h.Opacity))h.addComponent(t,r,h.Opacity,{value:0});else{const o=h.Opacity.write(t,r);o.value=0}}function qv(t,e){if(!h.hasComponent(t,e,Ye))return;const n=ci.current(t);if(n.length===0||n.length===1&&h.getBlockResizeMode(t,n[0])===h.ResizeMode.GroupOnly)return;h.hasComponent(t,e,h.Opacity)&&h.removeComponent(t,e,h.Opacity);const r=h.getBackrefs(t,e,ve,"transformBox");for(const o of r)h.hasComponent(t,o,h.Opacity)&&h.removeComponent(t,o,h.Opacity);El(t,e)}function Gv(t,e){if(h.hasComponent(t,e,Ye)){const n=h.getBackrefs(t,e,ve,"transformBox");for(const r of n)h.removeEntity(t,r)}for(const n of ci.current(t))h.hasComponent(t,n,h.Edited)||h.addComponent(t,n,h.Edited,{})}function Tl(t){for(const e of Lv.current(t))h.hasComponent(t,e,h.Edited)&&h.removeComponent(t,e,h.Edited)}var Ef={};Yr(Ef,{selectSystem:()=>eb});var Yv=4,Tf=h.defineQuery(t=>t.with(h.Block,Ie,h.Synced)),Xv=h.defineQuery(t=>t.with(h.Block,h.Edited)),Qv=on({guards:{isThresholdReached:({context:t,event:e})=>E.Vec2.distance(t.pointingStartClient,e.screenPosition)>=Yv,isOverBlock:({event:t})=>t.intersects.length>0,isOverSyncedBlock:({event:t})=>{const e=t.ctx;for(const n of t.intersects)if(h.hasComponent(e,n,h.Synced))return!0;return!1},isNotHeldByRemote:({event:t})=>{const e=t.ctx,n=t.intersects[0];return n?!h.isHeldByRemote(e,n):!0},hasEditedBlocks:({event:t})=>Xv.current(t.ctx).length>0},actions:{setPointingStart:we({pointingStartClient:({event:t})=>t.screenPosition,pointingStartWorld:({event:t})=>t.worldPosition}),setDragStart:we({dragStart:({event:t})=>t.worldPosition}),addHeldToDragged:({context:t,event:e})=>{t.draggedEntity!==null&&ff.spawn(e.ctx,{entityId:t.draggedEntity})},removeHeldFromDragged:({context:t,event:e})=>{t.draggedEntity!==null&&hf.spawn(e.ctx,{entityId:t.draggedEntity})},setDragCursor:({event:t,context:e})=>{if(e.draggedEntity)if(h.hasComponent(t.ctx,e.draggedEntity,ve)){const n=ve.read(t.ctx,e.draggedEntity),r=n.transformBox!==null?h.Block.read(t.ctx,n.transformBox):void 0;ni.spawn(t.ctx,{contextCursorKind:n.cursorKind,contextRotation:(r==null?void 0:r.rotateZ)??0})}else ni.spawn(t.ctx,{contextCursorKind:"drag",contextRotation:0})},unsetDragCursor:({event:t})=>{ni.spawn(t.ctx,{contextCursorKind:""})},setDraggedEntity:we({draggedEntity:({event:t})=>t.intersects[0]??null,draggedEntityStart:({event:t})=>{if(!t.intersects.length)return[0,0];const e=t.intersects[0],n=h.Block.read(t.ctx,e);return[n.position[0],n.position[1]]}}),resetDragged:({context:t,event:e})=>{t.draggedEntity!==null&&(Uo.spawn(e.ctx,{entityId:t.draggedEntity,position:t.draggedEntityStart}),t.isCloning&&kl.spawn(e.ctx,{entityIds:[t.draggedEntity],seed:t.cloneGeneratorSeed}))},resetContext:we({dragStart:()=>[0,0],pointingStartClient:()=>[0,0],pointingStartWorld:()=>[0,0],draggedEntityStart:()=>[0,0],draggedEntity:()=>null,cloneGeneratorSeed:()=>crypto.randomUUID(),isCloning:()=>!1}),createSelectionBox:({event:t})=>{cf.spawn(t.ctx,void 0)},removeSelectionBox:({event:t})=>{uf.spawn(t.ctx,void 0)},updateDragged:we({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=h.hasComponent(n,t.draggedEntity,h.Synced)||h.hasComponent(n,t.draggedEntity,Ye);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=h.Grid.snapX(n,r),o=h.Grid.snapY(n,o)),Uo.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=h.hasComponent(n,t.draggedEntity,Ye)?Array.from(Tf.current(n)):[t.draggedEntity];nf.spawn(n,{entityIds:u,offset:[a,l],seed:t.cloneGeneratorSeed})}else if(!e.altDown&&t.isCloning){const l=h.hasComponent(n,t.draggedEntity,Ye)?Array.from(Tf.current(n)):[t.draggedEntity];kl.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]);df.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(h.hasComponent(e,r,h.Synced)){n=r;break}n!==void 0&&(t.shiftDown?af.spawn(e,{entityId:n}):wl.spawn(e,{entityId:n,deselectOthers:!0}))},selectDragged:({context:t,event:e})=>{t.draggedEntity!==null&&h.hasComponent(e.ctx,t.draggedEntity,h.Synced)&&wl.spawn(e.ctx,{entityId:t.draggedEntity,deselectOthers:!0})},deselectAllIfShiftNotDown:({event:t})=>{t.shiftDown||Xr.spawn(t.ctx,void 0)},deselectAllIfDraggedNotSelected:({context:t,event:e})=>{t.draggedEntity!==null&&(h.hasComponent(e.ctx,t.draggedEntity,Ie)||h.hasComponent(e.ctx,t.draggedEntity,Ye)||h.hasComponent(e.ctx,t.draggedEntity,ve)||Xr.spawn(e.ctx,void 0))}}}).createMachine({id:"selection",initial:de.Idle,context:{dragStart:[0,0],pointingStartClient:[0,0],pointingStartWorld:[0,0],draggedEntityStart:[0,0],draggedEntity:null,cloneGeneratorSeed:crypto.randomUUID(),isCloning:!1},states:{[de.Idle]:{entry:["resetContext"],on:{pointerDown:[{guard:Ho(["isOverBlock","isNotHeldByRemote"]),target:de.Pointing},{actions:"deselectAllIfShiftNotDown",target:de.SelectionBoxPointing}]}},[de.Pointing]:{entry:["setPointingStart","setDraggedEntity"],on:{pointerMove:{guard:Ho(["isThresholdReached",nr("hasEditedBlocks")]),target:de.Dragging},pointerUp:[{guard:"isOverSyncedBlock",actions:"selectIntersect",target:de.Idle},{actions:"deselectAllIfShiftNotDown",target:de.Idle}],cancel:{target:de.Idle}}},[de.Dragging]:{entry:["setDragStart","addHeldToDragged","setDragCursor","deselectAllIfDraggedNotSelected"],exit:["unsetDragCursor"],on:{pointerMove:{actions:"updateDragged"},pointerUp:{actions:"selectDragged",target:de.Idle},cancel:{actions:["resetDragged","removeHeldFromDragged"],target:de.Idle}}},[de.SelectionBoxPointing]:{entry:["setPointingStart"],on:{pointerMove:{guard:"isThresholdReached",target:de.SelectionBoxDragging},pointerUp:{target:de.Idle},cancel:{target:de.Idle}}},[de.SelectionBoxDragging]:{entry:["setDragStart","createSelectionBox"],exit:"removeSelectionBox",on:{pointerMove:{actions:"resizeSelectionBox"},pointerUp:{target:de.Idle},cancel:{target:de.Idle}}}}}),eb=h.defineEditorSystem({phase:"capture",priority:100},t=>{let e=h.Controls.getButtons(t,"select");Tt.read(t).state===de.Dragging&&e.length===0&&(e=["left"]);const r=h.getPointerInput(t,e);r.length!==0&&Tt.run(t,Qv,r)}),Mf={};Yr(Mf,{blockSystem:()=>tb,dragHandlerSystem:()=>ab,selectSystem:()=>pb});var eo=h.defineQuery(t=>t.with(h.Block,Ie)),Af=h.defineQuery(t=>t.with(h.Block,h.Synced)),tb=h.defineEditorSystem({phase:"update"},t=>{h.on(t,Uo,(e,{entityId:n,position:r})=>{if(!h.hasComponent(e,n,h.Block))return;const o=h.Block.write(e,n);o.position=r}),h.on(t,wl,(e,{entityId:n,deselectOthers:r})=>{r&&Ml(e),Qr(e,n)}),h.on(t,wv,(e,{entityId:n})=>{Jo(e,n)}),h.on(t,af,(e,{entityId:n})=>{h.hasComponent(e,n,Ie)?Jo(e,n):Qr(e,n)}),h.on(t,Xr,Ml),h.on(t,ff,(e,{entityId:n})=>{if(!h.hasComponent(e,n,h.Synced)||h.hasComponent(e,n,h.Held))return;const{sessionId:r}=h.getResources(e);h.addComponent(e,n,h.Held,{sessionId:r})}),h.on(t,hf,(e,{entityId:n})=>{h.hasComponent(e,n,Ie)||h.hasComponent(e,n,h.Held)&&h.removeComponent(e,n,h.Held)}),h.on(t,lf,e=>{for(const n of Af.current(e))Qr(e,n)}),h.on(t,kv,(e,{entityId:n})=>{h.removeEntity(e,n)}),h.on(t,yl,e=>{for(const n of eo.current(e))h.removeEntity(e,n)}),h.on(t,ef,nb),h.on(t,tf,rb),h.on(t,ni,(e,n)=>{n.cursorKind!==void 0&&h.Cursor.setCursor(e,n.cursorKind,n.rotation??0),n.contextCursorKind!==void 0&&h.Cursor.setContextCursor(e,n.contextCursorKind,n.contextRotation??0),n.contextCursorKind===""&&h.Cursor.clearContextCursor(e)}),h.on(t,of,e=>{Nf(e)}),h.on(t,rf,e=>{Nf(e);for(const n of eo.current(e))h.removeEntity(e,n)}),h.on(t,sf,(e,n)=>{ob(e,n==null?void 0:n.position)}),h.on(t,nf,(e,{entityIds:n,offset:r,seed:o})=>{sb(e,n,r,o)}),h.on(t,kl,(e,{entityIds:n,seed:r})=>{ib(e,n,r)})});function Ml(t){for(const e of eo.current(t))Jo(t,e)}function nb(t){const e=[...eo.current(t)];if(e.length!==0){e.sort((n,r)=>{const o=h.Block.read(t,n),s=h.Block.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=h.Block.write(t,n);r.rank=h.RankBounds.genNext(t)}}}function rb(t){const e=[...eo.current(t)];if(e.length!==0){e.sort((n,r)=>{const o=h.Block.read(t,n),s=h.Block.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=h.Block.write(t,n);r.rank=h.RankBounds.genPrev(t)}}}function Nf(t){const e=[...eo.current(t)];if(e.length===0)return;const{componentsById:n}=h.getResources(t),r=new Map([...n].filter(([,c])=>c.sync==="document")),o=[],s=E.Aabb.zero();let i=!1;const a=h.Synced._getComponentId(t);for(const c of e){const u=new Map;h.hasComponent(t,c,h.Synced)&&u.set(a,h.Synced.snapshot(t,c));for(const f of t.entityBuffer.getComponentIds(c)){if(f===a)continue;const p=r.get(f);if(p){const m=p.snapshot(t,c),g=xv(t,p.schema,m);u.set(f,g)}}if(o.push(u),h.hasComponent(t,c,h.Aabb)){const{value:f}=h.Aabb.read(t,c);i?E.Aabb.union(s,f):(E.Aabb.copy(s,f),i=!0)}}qo.setEntities(t,o);const l=qo.write(t);l.count=o.length,l.center=E.Aabb.center(s)}function ob(t,e){const n=qo.getEntities(t);if(n.length===0)return;const{componentsById:r}=h.getResources(t),o=new Map([...r].filter(([,p])=>p.sync==="document")),s=qo.read(t),i=h.Synced._getComponentId(t),a=h.Block._getComponentId(t);let l;if(e)l=E.Vec2.clone(e),E.Vec2.sub(l,s.center);else{const p=h.Camera.getWorldCenter(t);l=E.Vec2.clone(p),E.Vec2.sub(l,s.center),h.Grid.snapPosition(t,l)}const c=[...n].sort((p,m)=>{const g=p.get(a),y=m.get(a),k=(g==null?void 0:g.rank)??"",w=(y==null?void 0:y.rank)??"";return k<w?-1:k>w?1:0});Ml(t);const u=new Map,f=[];for(const p of c){const m=h.createEntity(t),g=p.get(i);g!=null&&g.id&&u.set(g.id,m),h.addComponent(t,m,h.Synced,{id:crypto.randomUUID()});for(const[y,k]of p){if(y===i)continue;const w=o.get(y);if(!w)continue;const v={...k};if(y===a){const S=E.Vec2.clone(v.position);E.Vec2.add(S,l),v.position=S,v.rank=h.RankBounds.genNext(t)}const b=Ev(w.schema);if(b.length>0){for(const S of b)delete v[S];f.push({entityId:m,componentDef:w,componentData:k})}h.addComponent(t,m,w,v)}Qr(t,m)}for(const{entityId:p,componentDef:m,componentData:g}of f)Tv(t,p,m,g,u)}function sb(t,e,n,r){const{componentsById:o}=h.getResources(t),s=new Map([...o].filter(([,c])=>c.sync==="document")),i=h.Synced._getComponentId(t),a=h.Block._getComponentId(t),l=new Map;for(const c of e){if(!h.hasComponent(t,c,h.Synced))continue;const u=h.Synced.read(t,c),f=Sl(u.id,r),p=h.createEntity(t);l.set(c,p),h.addComponent(t,p,h.Synced,{id:f});for(const m of t.entityBuffer.getComponentIds(c)){if(m===i)continue;const g=s.get(m);if(!g)continue;const y={...g.snapshot(t,c)};if(m===a){const k=E.Vec2.clone(y.position);E.Vec2.add(k,n),y.position=k,y.rank=h.RankBounds.genPrev(t)}h.addComponent(t,p,g,y)}}Bf(t,l)}function ib(t,e,n){const r=new Set;for(const i of e){if(!h.hasComponent(t,i,h.Synced))continue;const a=h.Synced.read(t,i);r.add(Sl(a.id,n))}const o=[];for(const i of Af.current(t)){const a=h.Synced.read(t,i);r.has(a.id)&&o.push(i)}const s=new Map;for(const i of o){const a=h.Synced.read(t,i).id;for(const l of e){if(!h.hasComponent(t,l,h.Synced))continue;const c=h.Synced.read(t,l).id;if(Sl(c,n)===a){s.set(i,l);break}}}Bf(t,s);for(const i of o)h.removeEntity(t,i)}function Bf(t,e){for(const[n,r]of e){for(const o of h.getBackrefs(t,n,h.Connector,"startBlock"))h.Connector.write(t,o).startBlock=r;for(const o of h.getBackrefs(t,n,h.Connector,"endBlock"))h.Connector.write(t,o).endBlock=r}}var Al=h.defineQuery(t=>t.with(h.Block,Ie)),Of=h.defineQuery(t=>t.with(h.Block,Ye,Ae)),ab=h.defineEditorSystem({phase:"update"},t=>{h.on(t,Uo,(e,{entityId:n,position:r})=>{if(h.hasComponent(e,n,Ye)){lb(e,n,r);return}if(h.hasComponent(e,n,ve)){cb(e,n,r);return}})});function lb(t,e,n){const r=Ae.read(t,e),o=n[0]-r.position[0],s=n[1]-r.position[1];for(const i of Al.current(t)){if(!h.hasComponent(t,i,Ae))continue;const a=Ae.read(t,i),l=h.Block.write(t,i);l.position=[a.position[0]+o,a.position[1]+s],h.Grid.snapPosition(t,l.position)}}function cb(t,e,n){const r=ve.read(t,e);r.kind===Et.Rotate?db(t,e,n):r.kind===Et.Scale?If(t,e,n,!0):r.kind===Et.Stretch&&If(t,e,n,!1)}function db(t,e,n){const r=Of.current(t);if(r.length===0){console.warn("No transform box found for rotation");return}const o=r[0],s=h.Block.write(t,o),i=h.Block.getCenter(t,o),a=h.Block.read(t,e),l=[n[0]+a.size[0]/2,n[1]+a.size[1]/2],c=E.Vec2.angleTo(i,l),u=Ae.read(t,o),f=ve.read(t,e),p=E.Vec2.angle([s.size[0]*f.vectorX,s.size[1]*f.vectorY])+u.rotateZ;let m=c-p;const g=h.Grid.read(t),y=h.Keyboard.read(t);let k=0;if(y.shiftDown?k=g.shiftSnapAngleRad:g.enabled&&(k=g.snapAngleRad),k>0){const w=u.rotateZ%k;m=Math.round(m/k)*k-w}s.rotateZ=E.Scalar.normalizeAngle(u.rotateZ+m);for(const w of Al.current(t)){if(!h.hasComponent(t,w,Ae))continue;const v=Ae.read(t,w),b=h.Block.write(t,w);b.rotateZ=E.Scalar.normalizeAngle(v.rotateZ+m);const S=[v.position[0]+v.size[0]/2,v.position[1]+v.size[1]/2],C=E.Vec2.distance(i,S),x=E.Vec2.angleTo(i,S)+m,_=E.Vec2.fromPolar(C,x,i);b.position=[_[0]-b.size[0]/2,_[1]-b.size[1]/2],g.strict&&h.Grid.snapPosition(t,b.position)}}function If(t,e,n,r){const o=Of.current(t);if(o.length===0){console.warn("No transform box found for scaling");return}const s=o[0],i=Ae.read(t,s),a=ve.read(t,e),l=h.Block.read(t,e),c=[n[0]+l.size[0]/2,n[1]+l.size[1]/2];h.Grid.snapPosition(t,c);const u=i.rotateZ,f=[i.position[0]+i.size[0]/2,i.position[1]+i.size[1]/2],p=[-a.vectorX*i.size[0]/2,-a.vectorY*i.size[1]/2];E.Vec2.rotate(p,u);const m=[f[0]+p[0],f[1]+p[1]],g=[c[0]-m[0],c[1]-m[1]],y=E.Vec2.clone(g);E.Vec2.rotate(y,-u);let k=a.vectorX,w=a.vectorY,v=!1,b=!1;Math.sign(y[0])!==k&&k!==0&&(k=-k,v=!0),Math.sign(y[1])!==w&&w!==0&&(w=-w,b=!0);let S=Math.max(Math.abs(y[0]),1),C=Math.max(Math.abs(y[1]),1);if(r){const K=i.size[0]/i.size[1];S/C>K?C=S/K:S=C*K}else a.vectorX===0?S=i.size[0]:a.vectorY===0&&(C=i.size[1]);const x=i.size[0]>0?S/i.size[0]:1,_=i.size[1]>0?C/i.size[1]:1,T=h.Grid.read(t),N=E.Vec2.create(k*S,w*C);E.Vec2.rotate(N,u),E.Vec2.scale(N,.5);const I=E.Vec2.clone(m);E.Vec2.add(I,N);const V=[x,_];for(const K of Al.current(t)){if(!h.hasComponent(t,K,Ae))continue;const M=Ae.read(t,K),$=h.Block.write(t,K),Z=E.Vec2.clone(M.position);E.Vec2.add(Z,[M.size[0]/2,M.size[1]/2]);const ae=E.Vec2.clone(Z);E.Vec2.sub(ae,f),E.Vec2.rotate(ae,-u),E.Vec2.multiply(ae,V),v&&(ae[0]=-ae[0]),b&&(ae[1]=-ae[1]),E.Vec2.rotate(ae,u);const X=E.Vec2.clone(I);E.Vec2.add(X,ae);const j=E.Vec2.clone(M.size);E.Vec2.multiply(j,V);const q=h.getBlockResizeMode(t,K)===h.ResizeMode.Text;if(T.strict)if(q&&r){j[1]=Math.max(T.rowHeight,h.Grid.snapY(t,j[1]));const te=M.size[0]/M.size[1];j[0]=j[1]*te}else h.Grid.snapSize(t,j);if(E.Vec2.copy($.position,X),E.Vec2.sub($.position,[j[0]/2,j[1]/2]),T.strict&&h.Grid.snapPosition(t,$.position),!r&&a.vectorY===0?$.size[0]=j[0]:!r&&a.vectorX===0?$.size[1]=j[1]:E.Vec2.copy($.size,j),h.hasComponent(t,K,h.Text)){const te=a.kind===Et.Stretch,fe=h.Text.write(t,K);if(te)fe.constrainWidth=!0;else{const ce=M.size[1]>0?j[1]/M.size[1]:1;fe.fontSizePx=M.fontSize*ce}}$.flip=[v!==M.flip[0],b!==M.flip[1]]}}var ub=h.defineQuery(t=>t.with(h.Block,Ie)),Pf=h.defineQuery(t=>t.with(h.Block,ri)),fb=h.defineQuery(t=>t.with(h.Block,h.Synced,h.Aabb)),hb="z",pb=h.defineEditorSystem({phase:"update"},t=>{h.on(t,cf,e=>{const n=h.createEntity(e);h.addComponent(e,n,h.Block,{tag:"selection-box",position:[0,0],size:[0,0],rotateZ:0,rank:hb}),h.addComponent(e,n,ri,{})}),h.on(t,df,(e,{bounds:n,deselectOthers:r})=>{const o=Pf.current(e);if(o.length===0){console.warn("Can't update selection box: not found");return}const s=o[0],i=h.Block.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=h.intersectAabb(e,n,fb.current(e));if(r)for(const p of ub.current(e))!f.includes(p)&&Jo(e,p);for(const p of f)Qr(e,p)}),h.on(t,uf,e=>{const n=Pf.current(e);if(n.length===0){console.warn("Can't remove selection box: not found");return}const r=n[0];h.removeEntity(e,r)})}),di=t=>Object.values(t).filter(e=>typeof e=="object"&&e!==null&&"_system"in e&&"phase"in e);function mb(t={}){return{name:vf,resources:Cv.parse(t),components:Object.values(kf).filter(e=>e instanceof h.CanvasComponentDef),singletons:Object.values(Sf).filter(e=>e instanceof h.CanvasSingletonDef),blockDefs:[{tag:"selection-box",stratum:"overlay",canRotate:!1,canScale:!1,components:[ri]},{tag:"transform-box",stratum:"overlay",canRotate:!1,canScale:!1,components:[Ye]},{tag:"transform-handle",stratum:"overlay",canRotate:!1,canScale:!1,components:[ve]},{tag:"transform-edge",stratum:"overlay",canRotate:!1,canScale:!1,components:[ve]},{tag:"transform-rotate",stratum:"overlay",canRotate:!1,canScale:!1,components:[ve]}],systems:[...di(Ef),...di(Cf),...di(Mf),...di(xf)],keybinds:[{command:rf.name,key:h.Key.X,mod:!0},{command:of.name,key:h.Key.C,mod:!0},{command:sf.name,key:h.Key.V,mod:!0},{command:yl.name,key:h.Key.Delete},{command:lf.name,key:h.Key.A,mod:!0},{command:ef.name,key:h.Key.BracketRight},{command:tf.name,key:h.Key.BracketLeft}],cursors:Sv}}function gb(t){const e=yb(t.chars),n=kb(e,t.firstPositive,t.mostPositive,t.mostNegative),r=t.jitterRange??Math.floor(Math.pow(e.length,3)/5),o=wb(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 yb(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 kb(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 wb(t,e){const n={};for(let r=0;r<100&&(n[r]=Math.pow(e,r),!(n[r]>t));r++);return n}var Nl=null;function Rf(){return Nl||(Nl=gb({chars:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",firstPositive:"a",mostPositive:"z",mostNegative:"A"}))}function Cn(t,e,n){const r=n.byChar[t],o=n.byChar[e];return Math.abs(r-o)}function Bl(t,e){const n=t[0];if(n>e.mostPositive||n<e.mostNegative)throw new Error("invalid firstChar on key");return n===e.mostPositive?Cn(n,e.firstPositive,e)+1+ui(t.slice(1),"positive",e):n===e.mostNegative?Cn(n,e.firstNegative,e)+1+ui(t.slice(1),"negative",e):n>=e.firstPositive?Cn(n,e.firstPositive,e)+2:Cn(n,e.firstNegative,e)+2}function ui(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"?Cn(r,n.mostNegative,n)+1+ui(t.slice(1),e,n):r===n.mostNegative&&e==="negative"?Cn(r,n.mostPositive,n)+1+ui(t.slice(1),e,n):e==="positive"?Cn(r,n.mostNegative,n)+2:Cn(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 vb(t,e,n){const[r,o]=Ol(t,e,"end",n.first).sort(),s=zf(o,r,n);return Sb(s,n)}function Df(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 p=f%r;i.unshift(n.byCode[p])}return a>0&&i.unshift(n.byCode[a]),i.join("")}function zf(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 p=u-f;a.unshift(n.byCode[p])}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 $f(t,e){return Df(t,e.byCode[1],e)}function Il(t,e){return zf(t,e.byCode[1],e,!1)}function bb(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 Sb(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 Cb(t){return t.firstPositive+t.byCode[0]}function xb(t,e){return Bl(t,e)===t.length}function _b(t,e){fi(t,e)}function fi(t,e){const n=Ff(t,e),r=Bl(n,e);if(r>t.length)throw new Error("invalid order key length: "+t);return t.slice(0,r)}function Vf(t,e){if(!xb(t,e))throw new Error("invalid integer length: "+t)}function Lf(t,e){Vf(t,e);const[n,r]=jf(t,e);if(r.split("").some(i=>i!==e.byCode[e.length-1])){const i=$f(r,e);return n+i}const s=Tb(n,e);return Hf(s,"lower",e)}function Eb(t,e){Vf(t,e);const[n,r]=jf(t,e);if(r.split("").some(i=>i!==e.byCode[0])){const i=Il(r,e);return n+i}const s=Mb(n,e);return Hf(s,"upper",e)}function Ff(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 jf(t,e){const n=Ff(t,e),r=t.slice(n.length);return[n,r]}function Tb(t,e){const n=t>=e.firstPositive,r=$f(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 Mb(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 Il(o,e)}return!n&&r?t+e.mostPositive:Il(t,e)}function Hf(t,e,n){const r=Bl(t,n),o=e==="upper"?n.byCode[n.length-1]:n.byCode[0];return t+o.repeat(r-t.length)}function Wf(t,e){const n=bb(Math.floor(Math.random()*e.jitterRange),e);return Df(t,n,e)}function Ab(t,e,n){const r=t.padEnd(t.length+e,n.first);return Wf(r,n)}function Nb(t,e,n){const r=fi(t,n),o=Lf(r,n);let s=0;const i=vb(t,o,n);return i<n.jitterRange+1&&(s=Math.max(s,Bb(i,n))),s}function Bb(t,e){const n=e.jitterRange-t,r=Object.entries(e.paddingDict).find(([o,s])=>s>n);return r?parseInt(r[0]):0}function Ob(t,e,n=Rf()){if(t!==null&&_b(t,n),t===null&&e===null)return Cb(n);if(t===null){const r=fi(e,n);return Eb(r,n)}{const r=fi(t,n);return Lf(r,n)}}function Ib(t,e,n=Rf()){const r=Ob(t,e,n),o=Nb(r,e,n);return o?Ab(r,o,n):Wf(r,n)}var Pb=Object.defineProperty,Zf=(t,e)=>{for(var n in e)Pb(t,n,{get:e[n],enumerable:!0})},Uf={};Zf(Uf,{ArcArrow:()=>ue,ArrowHandle:()=>At,ArrowTerminal:()=>Go,ElbowArrow:()=>he});var Rb="arrows",Kf="zzzzz",Db=24,Jf=50,Pl=4,zb=4,Rl=24,xn=24,qf=40,Mt={Idle:"idle",Pointing:"pointing",Dragging:"dragging"},to={None:"none",Idle:"idle"},ge={Start:"start",Middle:"middle",End:"end"},pe={None:"none",V:"v",Delta:"delta",Circle:"circle",Diamond:"diamond"},sr={Arc:"arc",Elbow:"elbow"},hi=0,pi=1,mi=2,gi=3,yi=4,ki=5,Dl=6,$b={value:h.field.tuple(h.field.float64(),7).default([0,0,.5,.5,1,1,Pl]),startArrowHead:h.field.enum(pe).default(pe.None),endArrowHead:h.field.enum(pe).default(pe.V),trimStart:h.field.float64().default(0),trimEnd:h.field.float64().default(1)},Vb=class extends h.CanvasComponentDef{constructor(){super({name:"arcArrow",sync:"document"},$b)}getA(t,e){const{value:n}=this.read(t,e);return[n[hi],n[pi]]}getB(t,e){const{value:n}=this.read(t,e);return[n[mi],n[gi]]}getC(t,e){const{value:n}=this.read(t,e);return[n[yi],n[ki]]}getThickness(t,e){const{value:n}=this.read(t,e);return n[Dl]}setA(t,e,n){const{value:r}=this.write(t,e);r[hi]=n[0],r[pi]=n[1]}setB(t,e,n){const{value:r}=this.write(t,e);r[mi]=n[0],r[gi]=n[1]}setC(t,e,n){const{value:r}=this.write(t,e);r[yi]=n[0],r[ki]=n[1]}setThickness(t,e,n){const{value:r}=this.write(t,e);r[Dl]=n}getWorldArc(t,e){const{value:n}=this.read(t,e),r=h.Block.uvToWorld(t,e,[n[hi],n[pi]]),o=h.Block.uvToWorld(t,e,[n[mi],n[gi]]),s=h.Block.uvToWorld(t,e,[n[yi],n[ki]]);return[r[0],r[1],o[0],o[1],s[0],s[1],n[Dl]]}getWorldPoints(t,e){const{value:n}=this.read(t,e);return{a:h.Block.uvToWorld(t,e,[n[hi],n[pi]]),b:h.Block.uvToWorld(t,e,[n[mi],n[gi]]),c:h.Block.uvToWorld(t,e,[n[yi],n[ki]])}}isCurved(t,e){const{value:n}=this.read(t,e);return!E.Arc.isCollinear(n)}directionAt(t,e,n){const r=this.getWorldArc(t,e);return E.Arc.directionAt(r,n)}pointAt(t,e,n){const r=this.getWorldArc(t,e);return E.Arc.parametricToPoint(r,n)}length(t,e){const n=this.getWorldArc(t,e);return E.Arc.length(n)}containsPoint(t,e,n){const r=this.getWorldArc(t,e);return E.Arc.containsPoint(r,n)}},ue=new Vb,At=h.defineCanvasComponent({name:"arrowHandle"},{kind:h.field.enum(ge).default(ge.Start),arrowEntity:h.field.ref()}),Go=h.defineCanvasComponent({name:"arrowTerminal"},{blockEntity:h.field.ref(),terminalIndex:h.field.uint8().default(0)}),Lb={points:h.field.buffer(h.field.float64()).size(Rl*2),pointCount:h.field.uint8().default(0),thickness:h.field.float32().default(Pl),startArrowHead:h.field.enum(pe).default(pe.None),endArrowHead:h.field.enum(pe).default(pe.V),trimStart:h.field.float64().default(0),trimEnd:h.field.float64().default(1)},Fb=class extends h.CanvasComponentDef{constructor(){super({name:"elbowArrow",sync:"document"},Lb)}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>Rl)throw new Error(`ElbowArrow points exceed capacity of ${Rl}`);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 h.Block.uvToWorld(t,e,n)}getEndWorld(t,e){const{pointCount:n}=this.read(t,e),r=this.getPoint(t,e,n-1);return h.Block.uvToWorld(t,e,r)}getWorldPoints(t,e){return this.getPoints(t,e).map(r=>h.Block.uvToWorld(t,e,r))}getThickness(t,e){const{thickness:n}=this.read(t,e);return n}},he=new Fb,Gf={};Zf(Gf,{ArrowDrawState:()=>zl,ArrowTransformState:()=>Yf});var zl=h.defineEditorState("arrowDrawState",{state:h.field.string().max(16).default(Mt.Idle),activeArrow:h.field.ref(),kind:h.field.enum(sr).default(sr.Elbow),pointingStartClient:h.field.tuple(h.field.int32(),2).default([0,0]),pointingStartWorld:h.field.tuple(h.field.float64(),2).default([0,0])}),Yf=h.defineEditorState("arrowTransformState",{state:h.field.string().max(16).default(to.None),activeArrow:h.field.ref()}),Xf=h.defineCommand("arrows-add-arrow");h.defineCommand("arrows-draw-arrow");var Qf=h.defineCommand("arrows-remove-arrow");h.defineCommand("arrows-complete-arrow");var eh=h.defineCommand("arrows-add-or-update-transform-handles"),th=h.defineCommand("arrows-remove-transform-handles"),nh=h.defineCommand("arrows-hide-transform-handles"),rh=h.defineCommand("arrows-show-transform-handles"),jb=on({guards:{isThresholdReached:({context:t,event:e})=>E.Vec2.distance(t.pointingStartClient,e.screenPosition)>=zb},actions:{setPointingStart:we({pointingStartClient:({event:t})=>[t.screenPosition[0],t.screenPosition[1]],pointingStartWorld:({event:t})=>[t.worldPosition[0],t.worldPosition[1]]}),resetContext:we({pointingStartClient:()=>[0,0],pointingStartWorld:()=>[0,0],activeArrow:()=>null}),addArrow:we({activeArrow:({context:t,event:e})=>{const n=t.kind,r=t.pointingStartWorld,o=h.createEntity(e.ctx);return Xf.spawn(e.ctx,{entityId:o,position:r,kind:n}),o}}),removeArrow:we({activeArrow:({context:t,event:e})=>(t.activeArrow&&Qf.spawn(e.ctx,{entityId:t.activeArrow}),null)}),exitArrowControl:({event:t})=>{const e=h.Controls.write(t.ctx);e.leftMouseTool="select";const n=h.Cursor.write(t.ctx);n.cursorKind="select"},deselectAll:({event:t})=>{Xr.spawn(t.ctx)}}}).createMachine({id:"arrowDraw",initial:Mt.Idle,context:{activeArrow:null,kind:sr.Elbow,pointingStartClient:[0,0],pointingStartWorld:[0,0]},states:{[Mt.Idle]:{entry:"resetContext",on:{pointerDown:[{actions:"deselectAll",target:Mt.Pointing}]}},[Mt.Pointing]:{entry:"setPointingStart",on:{pointerMove:{guard:"isThresholdReached",target:Mt.Dragging},pointerUp:{target:Mt.Idle},cancel:{target:Mt.Idle}}},[Mt.Dragging]:{entry:"addArrow",exit:"exitArrowControl",on:{pointerUp:{target:Mt.Idle},cancel:{actions:"removeArrow",target:Mt.Idle}}}}}),Hb=h.defineEditorSystem({phase:"capture",priority:100},t=>{const e=h.Controls.getButtons(t,"arc-arrow","elbow-arrow");if(e.length===0)return;const n=h.getPointerInput(t,e);if(n.length===0)return;const r=h.Controls.read(t).leftMouseTool,o=zl.write(t);o.kind=r==="elbow-arrow"?sr.Elbow:sr.Arc,zl.run(t,jb,n)}),$l=h.defineQuery(t=>t.with(h.Block).tracking(Ie)),Wb=on({guards:{selectingSingleArrow:({event:t})=>{if(!("selectedEntities"in t)||t.selectedEntities.length!==1)return!1;const e=t.selectedEntities[0];return h.hasComponent(t.ctx,e,ue)||h.hasComponent(t.ctx,e,he)}},actions:{setActiveArrow:we({activeArrow:({event:t})=>!("selectedEntities"in t)||t.selectedEntities.length===0?null:t.selectedEntities[0]}),addOrUpdateTransformHandles:({context:t,event:e})=>{t.activeArrow&&eh.spawn(e.ctx,{arrowEntityId:t.activeArrow})},removeTransformHandles:({event:t})=>{th.spawn(t.ctx,{})},hideTransformHandles:({event:t})=>{nh.spawn(t.ctx,{})},showTransformHandles:({event:t})=>{rh.spawn(t.ctx,{})}}}).createMachine({id:"arrowTransform",initial:to.None,context:{activeArrow:null},states:{[to.None]:{entry:"removeTransformHandles",on:{selectionChanged:[{guard:"selectingSingleArrow",actions:"setActiveArrow",target:to.Idle}]}},[to.Idle]:{entry:"addOrUpdateTransformHandles",on:{selectionChanged:[{guard:nr("selectingSingleArrow"),target:to.None},{actions:["setActiveArrow","addOrUpdateTransformHandles"]}],pointerDown:{actions:"hideTransformHandles"},pointerUp:{actions:"showTransformHandles"}}}}}),Zb=h.defineEditorSystem({phase:"capture",priority:99},t=>{const e=Ub(t);e.length!==0&&Yf.run(t,Wb,e)});function Ub(t){const e=[],n=$l.added(t),r=$l.removed(t);if(n.length>0||r.length>0){const i=[...$l.current(t)];e.push({type:"selectionChanged",ctx:t,selectedEntities:i})}const o=h.Controls.getButtons(t,"select"),s=h.getPointerInput(t,o);return e.push(...s),e}var Kb=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 Jb(t,e,n,r,o,s,i){return new qb(t,e,n,s,i).calculate(r,o)}var qb=class{constructor(t,e,n,r,o){this.ctx=t,this.padding=r,this.rotation=o;const s=E.Vec2.midPoint(e,n);this.toLocal=E.Mat2.fromTranslation(-s[0],-s[1]),E.Mat2.rotate(this.toLocal,-o),this.toWorld=E.Mat2.fromRotation(o),E.Mat2.translate(this.toWorld,s[0],s[1]),this.localStart=this.transformToLocal(e),this.localEnd=this.transformToLocal(n)}transformToLocal(t){const e=E.Vec2.clone(t);return E.Mat2.transformPoint(this.toLocal,e),e}transformToWorld(t){const e=E.Vec2.clone(t);return E.Mat2.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=Yo(E.Ray.origin(n),E.Ray.origin(r)):o=this.routeBlockToBlock(t,e,n,r)}else t&&!e?this.isPointInsideBlockMargin(this.localEnd,t)?o=Yo(E.Ray.origin(n),this.localEnd):o=this.routeBlockToPoint(t,n,this.localEnd):!t&&e?this.isPointInsideBlockMargin(this.localStart,e)?o=Yo(this.localStart,E.Ray.origin(r)):o=this.routeBlockToPoint(e,r,this.localStart).reverse():o=Yo(E.Ray.origin(n),this.localEnd);for(let s=0;s<o.length;s++)o[s]=this.transformToWorld(o[s]);return o}getBlockAabb(t){const e=h.Block.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 E.Rect.getAabb(s,e.size,o,i),i}isPointInsideBlockMargin(t,e){const n=this.getBlockAabb(e);return E.Aabb.pad(n,this.padding),E.Aabb.containsPoint(n,t)}routeBlockToBlock(t,e,n,r){const o=this.getBlockAabb(t),s=this.getBlockAabb(e);E.Aabb.pad(o,this.padding),E.Aabb.pad(s,this.padding),Qb(o,s);const i=eS(o,s),a=wi(n,i),l=wi(r,i),c=E.Ray.origin(n),u=E.Ray.origin(r);if(a===null||l===null)return console.warn("[routeBlockToBlock] Failed to add start or end node to graph"),[c,u];const f=ah(i,a,l);if(f===null)return[c,u];const p=[c];for(const m of f){const g=i.find(y=>y.id===m);g&&p.push(g.coords)}return p.push(u),Gb(p),oh(p),Yb(p),p}routeBlockToPoint(t,e,n){const r=E.Ray.origin(e),o=E.Ray.direction(e),s=vi(r,n);if(o[0]===s[0]&&o[1]===s[1])return Yo(r,n);const i=this.getBlockAabb(t);E.Aabb.pad(i,this.padding);const a=E.Ray.fromPoints(n,[-s[0],-s[1]]),l=E.Ray.intersectAabb(a,i);l.length===0&&E.Aabb.expand(i,n);const c=E.Aabb.corners(i),u=sh(c),f=wi(a,u),p=wi(e,u);if(p===null||f===null)return[r,n];const m=ah(u,p,f);if(m===null)return[r,n];const g=[r];for(const y of m){const k=u.find(w=>w.id===y);k&&g.push(k.coords)}return l.length>0&&g.push(n),oh(g),g}calculateRay(t,e,n){let r;return n?r=this.exitClosestSide(t,n).direction:r=vi(t,e),E.Ray.fromPoints(t,r)}exitClosestSide(t,e){const n=h.Block.read(this.ctx,e),r=h.Block.getCenter(this.ctx,e),o=this.transformToWorld(t),s=E.Vec2.clone(o),i=E.Vec2.clone(r);E.Vec2.sub(i,o),E.Vec2.scale(i,.01),E.Vec2.add(s,i);const a=[[0,-1],[1,0],[0,1],[-1,0]],l=a.map(g=>{const y=E.Vec2.clone(g);return E.Vec2.rotate(y,this.rotation),y}),c=[];for(let g=0;g<l.length;g++){const y=l[g],k=E.Ray.fromPoints(s,y),w=E.Ray.intersectRect(k,n.position,n.size,n.rotateZ);w.length!==0&&c.push({direction:a[g],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((g,y)=>g.distance-y.distance);const u=c[0],f=(o[0]-n.position[0])/n.size[0],p=(o[1]-n.position[1])/n.size[1],m=.2;if(Math.abs(f-.5)<m&&Math.abs(p-.5)<m){const g=vi(t,this.localEnd),y=c.find(k=>k.direction[0]===g[0]&&k.direction[1]===g[1]);if(y)return y}return u}};function Yo(t,e){const n=[];n.push(t);const r=e[0]-t[0],o=e[1]-t[1];if(E.Scalar.approxEqual(o,0)||E.Scalar.approxEqual(r,0))return n.push(e),n;const s=vi(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 Gb(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=E.Scalar.approxEqual(r[0],o[0]),i=E.Scalar.approxEqual(r[1],o[1]);(!s||!i)&&e.push(o)}t.length=0,t.push(...e)}function oh(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=E.Scalar.approxEqual(r[0],o[0])&&E.Scalar.approxEqual(o[0],s[0]),a=E.Scalar.approxEqual(r[1],o[1])&&E.Scalar.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 Yb(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=Xb(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 Xb(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0])>0?"left":"right"}function Qb(t,e){if(!E.Aabb.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 sh(t){const e=t.map((n,r)=>({id:r,connections:[],distances:{},coords:n}));return ih(e,0),ih(e,1),e}function ih(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 eS(t,e){if(!E.Aabb.intersects(t,e))return[];const n=[],r=E.Aabb.corners(t),o=E.Aabb.corners(e);for(const c of r)E.Aabb.containsPoint(e,c,!1)||n.push(c);for(const c of o)E.Aabb.containsPoint(t,c,!1)||n.push(c);const s=E.Aabb.clone(t);E.Aabb.intersection(s,e);const i=E.Aabb.corners(s);for(const c of i)E.Aabb.containsPoint(t,c,!1)||E.Aabb.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 sh(a)}function wi(t,e){const n=E.Ray.origin(t),r=e.find(m=>m.coords[0]===n[0]&&m.coords[1]===n[1]);if(r)return r.id;let o=null,s=-1,i=-1;for(const m of e)for(const g of m.connections){if(m.id>=g)continue;const y=e.find(w=>w.id===g);if(!y)continue;const k=E.Ray.intersectSegment(t,m.coords,y.coords);k&&(o===null||k.distance<o.distance)&&(o=k,s=m.id,i=g)}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]),p=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]=p,c.connections.push(a),c.distances[a]=f,u.connections.push(a),u.distances[a]=p,c.connections=c.connections.filter(m=>m!==i),delete c.distances[i],u.connections=u.connections.filter(m=>m!==s),delete u.distances[s],e.push(l),a}function ah(t,e,n){const r={},o={},s=new Kb;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 vi(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 lh(t,e){if(t.length===0)return null;let n=t[0],r=E.Vec2.distanceSq(t[0],e);for(let o=1;o<t.length;o++){const s=E.Vec2.distanceSq(t[o],e);s<r&&(r=s,n=t[o])}return n}function tS(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 nS(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 ch=20,rS=h.defineQuery(t=>t.tracking(ue,h.Connector)),oS=h.defineQuery(t=>t.tracking(he,h.Connector)),sS=h.defineEditorSystem({phase:"update",priority:-10},t=>{for(const e of rS.addedOrChanged(t))iS(t,e);for(const e of oS.addedOrChanged(t))aS(t,e)});function iS(t,e){h.hasComponent(t,e,h.HitGeometry)||h.addComponent(t,e,h.HitGeometry,{});const n=ue.read(t,e),r=E.Arc.clone(n.value);r[6]=Math.max(r[6],ch),h.HitGeometry.clear(t,e),h.HitGeometry.addArc(t,e,r),lS(t,e)}function aS(t,e){h.hasComponent(t,e,h.HitGeometry)||h.addComponent(t,e,h.HitGeometry,{});const n=he.read(t,e),r=Math.max(n.thickness,ch),o=he.getPoints(t,e),s=h.HitGeometry.write(t,e),i=Math.min(o.length-1,h.MAX_HIT_CAPSULES);s.capsuleCount=i,s.arcCount=0;for(let a=0;a<i;a++){const l=o[a],c=o[a+1],u=E.Capsule.create(l[0],l[1],c[0],c[1],r/2);h.HitGeometry.setCapsuleAt(t,e,a,u)}cS(t,e)}function lS(t,e){const n=h.Connector.read(t,e),r=ue.getWorldArc(t,e),{a:o,c:s}=ue.getWorldPoints(t,e);let i=dh(t,n.startBlock,r,o),a=dh(t,n.endBlock,r,s);1-a-i<.1&&(i=0,a=0);const l=ue.read(t,e);if(!E.Scalar.approxEqual(l.trimStart,i)||!E.Scalar.approxEqual(l.trimEnd,a)){const u=ue.write(t,e);u.trimStart=i,u.trimEnd=a}const c=h.HitGeometry.read(t,e);for(let u=0;u<c.arcCount;u++){const f=h.HitGeometry.getArcAt(t,e,u);E.Arc.trim(f,i,1-a),h.HitGeometry.setArcAt(t,e,u,f)}}function dh(t,e,n,r){if(!e)return 0;const o=h.Block.getCorners(t,e),s=E.Arc.intersectRect(n,o);if(s.length===0)return 0;const i=lh(s,r);return i?E.Arc.pointToParametric(n,i)??0:0}function cS(t,e){const n=h.Connector.read(t,e),r=he.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=uh(t,n.startBlock,s,a),u=uh(t,n.endBlock,i,l),f=he.read(t,e);if(!E.Scalar.approxEqual(f.trimStart,c)||!E.Scalar.approxEqual(f.trimEnd,u)){const y=he.write(t,e);y.trimStart=c,y.trimEnd=u}const p=h.HitGeometry.getCapsuleAt(t,e,0);E.Capsule.trim(p,c,1),h.HitGeometry.setCapsuleAt(t,e,0,p);const m=o-1,g=h.HitGeometry.getCapsuleAt(t,e,m);E.Capsule.trim(g,0,1-u),h.HitGeometry.setCapsuleAt(t,e,m,g)}function uh(t,e,n,r){if(!e)return 0;const o=h.Block.getCorners(t,e),s=[];for(let f=0;f<4;f++){const p=o[f],m=o[(f+1)%4],g=dS(n,r,p,m);g&&s.push(g)}if(s.length===0)return 0;const i=lh(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 dS(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,p=(c*s-u*o)/l;return f>=0&&f<=1&&p>=0&&p<=1?[t[0]+f*o,t[1]+f*s]:null}var bi=h.defineQuery(t=>t.with(At,h.Block)),uS=h.defineQuery(t=>t.with(h.Synced,h.Aabb).tracking(h.Block)),fh=h.defineQuery(t=>t.with(Go,h.Block)),fS=h.defineEditorSystem({phase:"update"},t=>{h.on(t,Xf,(e,{entityId:n,position:r,kind:o})=>{pS(e,n,r,o)}),h.on(t,Qf,(e,{entityId:n})=>{mS(e,n)}),h.on(t,eh,(e,{arrowEntityId:n})=>{Vl(e,n)}),h.on(t,th,e=>{vS(e)}),h.on(t,nh,e=>{Ll(e)}),h.on(t,rh,e=>{bS(e)}),h.on(t,Uo,(e,{entityId:n,position:r})=>{gS(e,n,r)}),hS(t)});function hS(t){const e=uS.addedOrChangedOrRemoved(t);if(e.length===0)return;const n=new Set;for(const r of e){const o=h.getBackrefs(t,r,h.Connector,"startBlock",!1);for(const i of o)n.has(i)||(n.add(i),hh(t,i));const s=h.getBackrefs(t,r,h.Connector,"endBlock",!1);for(const i of s)n.has(i)||(n.add(i),hh(t,i))}}function hh(t,e){const n=h.Connector.read(t,e);if(h.hasComponent(t,e,ue)){const{a:r,c:o}=ue.getWorldPoints(t,e);let s=r,i=o;n.startBlock!==null&&(s=h.Block.uvToWorld(t,n.startBlock,n.startBlockUv),Fl(t,e,ge.Start,s)),n.endBlock!==null&&(i=h.Block.uvToWorld(t,n.endBlock,n.endBlockUv),Fl(t,e,ge.End,i))}else if(h.hasComponent(t,e,he)){if(n.startBlock!==null){const r=h.Block.uvToWorld(t,n.startBlock,n.startBlockUv);jl(t,e,ge.Start,r)}if(n.endBlock!==null){const r=h.Block.uvToWorld(t,n.endBlock,n.endBlockUv);jl(t,e,ge.End,r)}}}function pS(t,e,n,r){const o=Pl,s=r===sr.Elbow?"elbow-arrow":"arc-arrow",a=h.Intersect.getAll(t).find(p=>h.hasComponent(t,p,h.Synced)&&Hl(t,p))??null;let l=n,c=[0,0];if(a!==null){const p=Wl(t,a,n);p!==null?(l=p.position,c=p.uv):(l=h.Block.uvToWorld(t,a,[.5,.5]),c=[.5,.5])}h.addComponent(t,e,h.Block,{tag:s,rank:h.RankBounds.genNext(t),position:l,size:[o,o]}),h.addComponent(t,e,h.Synced,{id:crypto.randomUUID()}),r===sr.Arc?h.addComponent(t,e,ue,{value:[0,0,.5,.5,1,1,o],startArrowHead:pe.None,endArrowHead:pe.V}):h.addComponent(t,e,he,{points:[0,0,.5,0,.5,1,1,1],pointCount:4,thickness:o,startArrowHead:pe.None,endArrowHead:pe.V}),h.addComponent(t,e,h.Connector,{startBlock:a,startBlockUv:c}),Qr(t,e);const f=Vl(t,e).find(p=>At.read(t,p).kind===ge.End);if(f){const p=h.Block.read(t,f),m=Tt.write(t);m.state=de.Dragging,m.draggedEntity=f,m.dragStart=l,m.draggedEntityStart=[p.position[0],p.position[1]],Ll(t)}}function mS(t,e){h.removeEntity(t,e)}function gS(t,e,n){h.hasComponent(t,e,ue)?yS(t,e):h.hasComponent(t,e,he)?kS(t,e):h.hasComponent(t,e,At)&&wS(t,e,n)}function yS(t,e){const n=h.Connector.read(t,e);if(n.startBlock!==null){const{a:r}=ue.getWorldPoints(t,e);Xo(t,e,ge.Start,r)}if(n.endBlock!==null){const{c:r}=ue.getWorldPoints(t,e);Xo(t,e,ge.End,r)}}function kS(t,e){const n=h.Connector.read(t,e);if(n.startBlock!==null){const r=he.getStartWorld(t,e);Xo(t,e,ge.Start,r)}if(n.endBlock!==null){const r=he.getEndWorld(t,e);Xo(t,e,ge.End,r)}}function wS(t,e,n){const r=At.read(t,e),o=r.arrowEntity;if(!o)return;const s=h.Block.read(t,e);let i=[n[0]+s.size[0]/2,n[1]+s.size[1]/2];if(r.kind!==ge.Middle){const a=ES(t,o,r.kind,i);a!==null&&(i=a)}h.hasComponent(t,o,ue)?Fl(t,o,r.kind,i):h.hasComponent(t,o,he)&&jl(t,o,r.kind,i),r.kind!==ge.Middle&&Xo(t,o,r.kind,i)}function Vl(t,e){const n=Db,r=[ge.Start,ge.End];h.hasComponent(t,e,ue)&&r.push(ge.Middle);const o=Array.from(bi.current(t)),s=new Map;for(const l of o){const c=At.read(t,l);s.set(c.kind,l)}const i=new Set;for(const l of r){const c=SS(t,e,l),u=c[0]-n/2,f=c[1]-n/2;let p=s.get(l);p||(p=h.createEntity(t),h.addComponent(t,p,At),h.addComponent(t,p,h.Block),h.addComponent(t,p,h.ScaleWithZoom),h.addComponent(t,p,ve,{kind:"arrow"}));const m=At.write(t,p);m.kind=l,m.arrowEntity=e;const g=h.Block.write(t,p);g.tag="arrow-handle",g.rank=Kf,g.position=[u,f],g.size=[n,n];const y=h.ScaleWithZoom.write(t,p);y.startPosition=[u,f],y.startSize=[n,n],i.add(p)}for(const l of o)i.has(l)||h.removeEntity(t,l);const a=Tt.read(t);return a.state===de.Dragging&&a.draggedEntity!==null&&h.hasComponent(t,a.draggedEntity,At)&&Ll(t),Array.from(i)}function vS(t){for(const e of bi.current(t))h.removeEntity(t,e);Si(t)}function Ll(t){for(const e of bi.current(t))if(!h.hasComponent(t,e,h.Opacity))h.addComponent(t,e,h.Opacity,{value:0});else{const n=h.Opacity.write(t,e);n.value=0}}function bS(t){const e=bi.current(t);for(const n of e)h.hasComponent(t,n,h.Opacity)&&h.removeComponent(t,n,h.Opacity);if(e.length>0){const n=At.read(t,e[0]);n.arrowEntity&&Vl(t,n.arrowEntity)}Si(t)}function SS(t,e,n){if(h.hasComponent(t,e,ue)){const{a:r,b:o,c:s}=ue.getWorldPoints(t,e);switch(n){case ge.Start:return r;case ge.Middle:return o;case ge.End:return s}}if(h.hasComponent(t,e,he))switch(n){case ge.Start:return he.getStartWorld(t,e);case ge.End:return he.getEndWorld(t,e)}return console.warn("Arrow entity has no recognized arrow component"),[0,0]}function Fl(t,e,n,r){const{a:o,b:s,c:i}=ue.getWorldPoints(t,e);let a=o,l=s,c=i,u=[0,0],f=[0,0];if(n===ge.Start?(u=o,f=i,a=r):n===ge.Middle?l=r:(u=i,f=o,c=r),n!==ge.Middle){const{angle:w,distance:v}=tS(u,r,f);l=nS(s,w,.5*v,f)}const p=h.Block.write(t,e),m=Math.min(a[0],l[0],c[0]),g=Math.min(a[1],l[1],c[1]),y=Math.max(a[0],l[0],c[0]),k=Math.max(a[1],l[1],c[1]);p.position=[m,g],p.size=[y-m||1,k-g||1],ue.setA(t,e,h.Block.worldToUv(t,e,a)),ue.setB(t,e,h.Block.worldToUv(t,e,l)),ue.setC(t,e,h.Block.worldToUv(t,e,c))}function jl(t,e,n,r){const o=h.Connector.read(t,e);let s,i;n===ge.Start?(s=r,o.endBlock!==null?i=h.Block.uvToWorld(t,o.endBlock,o.endBlockUv):i=he.getEndWorld(t,e)):(o.startBlock!==null?s=h.Block.uvToWorld(t,o.startBlock,o.startBlockUv):s=he.getStartWorld(t,e),i=r);const l=h.Block.read(t,e).rotateZ||0,c=Jb(t,s,i,o.startBlock,o.endBlock,Jf,l),u=h.Block.write(t,e),f=[0,0],p=[1,1];E.Rect.boundPoints(f,p,l,c),u.position=f,u.size=[Math.max(p[0],1),Math.max(p[1],1)];const m=c.map(g=>h.Block.worldToUv(t,e,g));he.setPoints(t,e,m)}function Xo(t,e,n,r){let s=h.Intersect.getAll(t).find(l=>l!==e&&h.hasComponent(t,l,h.Synced)&&!h.hasComponent(t,l,h.Connector)&&Hl(t,l))??null;const i=h.Connector.write(t,e);if(s!==null){const l=n===ge.Start?i.endBlock:i.startBlock;s===l&&(s=null)}s!==null?_S(t,s):Si(t);let a=[0,0];if(s!==null){const l=Wl(t,s,r,qf);l!==null?a=l.uv:a=h.Block.worldToUv(t,s,r)}n===ge.Start?(i.startBlock=s,i.startBlockUv=a):(i.endBlock=s,i.endBlockUv=a),CS(t,e)}function CS(t,e){const n=h.Connector.read(t,e);let r=null;for(const s of[n.startBlock,n.endBlock]){if(s===null)continue;const i=h.Block.read(t,s).rank;(r===null||i>r)&&(r=i)}const o=h.Block.read(t,e).rank;if(r!==null&&o<r){const s=h.Block.write(t,e);s.rank=Ib(r,null)}}function Hl(t,e){const n=h.Block.read(t,e).tag;return h.getBlockDef(t,n).connectors.enabled}function xS(t){const e=fh.current(t);return e.length===0?null:Go.read(t,e[0]).blockEntity}function _S(t,e){if(xS(t)===e)return;Si(t);const n=h.Block.read(t,e).tag,r=h.getBlockDef(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=h.Block.uvToWorld(t,e,i),l=h.createEntity(t);h.addComponent(t,l,Go,{blockEntity:e,terminalIndex:s}),h.addComponent(t,l,h.Block,{tag:"arrow-terminal",rank:Kf,position:[a[0]-xn/2,a[1]-xn/2],size:[xn,xn]}),h.addComponent(t,l,h.ScaleWithZoom,{startPosition:[a[0]-xn/2,a[1]-xn/2],startSize:[xn,xn]})}}function Si(t){for(const e of fh.current(t))h.removeEntity(t,e)}function Wl(t,e,n,r){const o=h.Block.read(t,e).tag,s=h.getBlockDef(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=h.Block.uvToWorld(t,e,c),f=u[0]-n[0],p=u[1]-n[1],m=Math.sqrt(f*f+p*p);m<l&&(l=m,a={position:u,uv:c})}return a}function ES(t,e,n,r){const s=h.Intersect.getAll(t).find(c=>c!==e&&h.hasComponent(t,c,h.Synced)&&!h.hasComponent(t,c,h.Connector)&&Hl(t,c))??null;if(s===null)return null;const i=h.Connector.read(t,e),a=n===ge.Start?i.endBlock:i.startBlock;if(s===a)return null;const l=Wl(t,s,r,qf);return l===null?null:l.position}function TS(t={}){return{name:Rb,components:Object.values(Uf).filter(e=>e instanceof h.CanvasComponentDef),singletons:Object.values(Gf).filter(e=>e instanceof h.CanvasSingletonDef),blockDefs:[{tag:"arc-arrow",resizeMode:h.ResizeMode.GroupOnly,components:[ue,h.Connector,h.Color],connectors:{enabled:!1}},{tag:"elbow-arrow",resizeMode:h.ResizeMode.GroupOnly,components:[he,h.Connector,h.Color],connectors:{enabled:!1}},{tag:"arrow-handle",stratum:"overlay",canRotate:!1,canScale:!1,components:[At],connectors:{enabled:!1}},{tag:"arrow-terminal",stratum:"overlay",canRotate:!1,canScale:!1,components:[Go],connectors:{enabled:!1}}],systems:[Hb,Zb,fS,sS],resources:{elbowArrowPadding:t.elbowArrowPadding??Jf}}}const Zl=[{kind:pe.None,label:"None",gap:0,svg:""},{kind:pe.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:pe.Delta,label:"Triangle",gap:20,svg:'<polygon points="-1,0 -12,-7 -12,7" fill="currentColor" />'},{kind:pe.Circle,label:"Circle",gap:0,svg:'<circle cx="-6" cy="0" r="6" fill="currentColor" />'},{kind:pe.Diamond,label:"Diamond",gap:0,svg:'<polygon points="0,0 -7,-6 -14,0 -7,6" fill="currentColor" />'}];function no(t){return Zl.find(e=>e.kind===t)}const ph=Symbol.for("__woven_canvas_dropdown_active__"),mh=Symbol.for("__woven_canvas_dropdown_level__"),gh=Symbol.for("__woven_canvas_floating_menu__"),Ul=Symbol.for("__woven_canvas_toolbar__"),yh=Symbol.for("__woven_canvas_tooltip__"),pt=Symbol.for("__woven_canvas__");function Pe(t,e){const n=d.inject(pt);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();h.hasComponent(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 MS={key:0},AS=["x1","y1","x2","y2","stroke","stroke-width"],NS=["x1","y1","x2","y2","stroke","stroke-width"],BS=["points","fill"],OS=["cx","cy","r","fill"],IS=["points","fill"],PS=15,RS=2,sn=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/RS)**.33,c=PS*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,p=[e.position[0]-a[0]*u+l[0]*(f/2),e.position[1]-a[1]*u+l[1]*(f/2)],m=[e.position[0]-a[0]*u-l[0]*(f/2),e.position[1]-a[1]*u-l[1]*(f/2)];return{p1:p,p2:m}}),o=d.computed(()=>{if(!n.value)return null;const{unitDir:a,perpDir:l,size:c}=n.value,u=c,f=c,p=[a[0]*(c*.4),a[1]*(c*.4)],m=[e.position[0]-a[0]*u+p[0],e.position[1]-a[1]*u+p[1]],g=[m[0]+l[0]*(f/2),m[1]+l[1]*(f/2)],y=[m[0]-l[0]*(f/2),m[1]-l[1]*(f/2)],k=[e.position[0]+p[0],e.position[1]+p[1]];return`${k[0]},${k[1]} ${g[0]},${g[1]} ${y[0]},${y[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,p=[a[0]*(c*.8),a[1]*(c*.8)],m=[e.position[0]-a[0]*(u/2)+p[0],e.position[1]-a[1]*(u/2)+p[1]],g=[e.position[0]-a[0]*u+p[0],e.position[1]-a[1]*u+p[1]],y=[m[0]+l[0]*(f/2),m[1]+l[1]*(f/2)],k=[m[0]-l[0]*(f/2),m[1]-l[1]*(f/2)],w=[e.position[0]+p[0],e.position[1]+p[1]];return`${w[0]},${w[1]} ${y[0]},${y[1]} ${g[0]},${g[1]} ${k[0]},${k[1]}`});return(a,l)=>n.value?(d.openBlock(),d.createElementBlock("g",MS,[t.kind===d.unref(pe).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,AS),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,NS)],64)):t.kind===d.unref(pe).Delta&&o.value?(d.openBlock(),d.createElementBlock("polygon",{key:1,points:o.value,fill:t.color},null,8,BS)):t.kind===d.unref(pe).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,OS)):t.kind===d.unref(pe).Diamond&&i.value?(d.openBlock(),d.createElementBlock("polygon",{key:3,points:i.value,fill:t.color},null,8,IS)):d.createCommentVNode("",!0)])):d.createCommentVNode("",!0)}}),DS={class:"arrow-svg",preserveAspectRatio:"none"},zS=["d","stroke","stroke-width"],$S=["x1","y1","x2","y2","stroke","stroke-width"],VS=["d"],LS=["x1","y1","x2","y2"],FS=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=Pe(e.entityId,h.Color),i=Pe(e.entityId,ue);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"),C=s.value.blue.toString(16).padStart(2,"0");return`#${b}${S}${C}`}),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),p=d.computed(()=>{if(!i.value)return!1;const b=i.value.value,S=E.Arc.create(b[0],b[1],b[2],b[3],b[4],b[5],b[6]);return!E.Arc.isCollinear(S)}),m=d.computed(()=>{if(!i.value)return null;const b=i.value.value,S=r.value,C=o.value;return E.Arc.create(b[0]*S,b[1]*C,b[2]*S,b[3]*C,b[4]*S,b[5]*C,b[6])}),g=d.computed(()=>!m.value||!p.value?null:E.Arc.compute(m.value)),y=d.computed(()=>{var $,Z,ae,X;if(!i.value||!m.value)return null;const b=m.value,S=i.value.startArrowHead,C=i.value.endArrowHead,x=E.Arc.length(b);let _=i.value.trimStart;if(($=e.connector)!=null&&$.startBlock&&S!=="none"){const j=((Z=no(S))==null?void 0:Z.gap)??0,q=x>0?j/x:0;_+=q}let T=i.value.trimEnd;if((ae=e.connector)!=null&&ae.endBlock&&C!=="none"){const j=((X=no(C))==null?void 0:X.gap)??0,q=x>0?j/x:0;T+=q}const N=1-T,I=E.Arc.parametricToPoint(b,_),V=E.Arc.parametricToPoint(b,N),K=v(E.Arc.directionAt(b,_)),M=E.Arc.directionAt(b,N);return{start:I,end:V,startDir:K,endDir:M,tStart:_,tEnd:N,startHead:S,endHead:C}}),k=d.computed(()=>{if(!y.value||!g.value||!p.value)return"";const{start:b,end:S,tStart:C,tEnd:x}=y.value,{radius:_,clockwise:T,arcAngle:N}=g.value,V=N*(x-C)>Math.PI?1:0,K=T?0:1;return`M ${b[0]} ${b[1]} A ${_} ${_} 0 ${V} ${K} ${S[0]} ${S[1]}`}),w=d.computed(()=>!y.value||p.value?null:{x1:y.value.start[0],y1:y.value.start[1],x2:y.value.end[0],y2:y.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",DS,[p.value&&k.value?(d.openBlock(),d.createElementBlock("path",{key:0,d:k.value,stroke:l.value,fill:"none","stroke-width":u.value,"stroke-linecap":"round"},null,8,zS)):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,$S)):d.createCommentVNode("",!0),y.value?(d.openBlock(),d.createElementBlock(d.Fragment,{key:2},[y.value.startHead!=="none"?(d.openBlock(),d.createBlock(sn,{key:0,position:y.value.start,direction:y.value.startDir,thickness:u.value,"arrow-thickness":c.value,color:l.value,kind:y.value.startHead},null,8,["position","direction","thickness","arrow-thickness","color","kind"])):d.createCommentVNode("",!0),y.value.endHead!=="none"?(d.openBlock(),d.createBlock(sn,{key:1,position:y.value.end,direction:y.value.endDir,thickness:u.value,"arrow-thickness":c.value,color:l.value,kind:y.value.endHead},null,8,["position","direction","thickness","arrow-thickness","color","kind"])):d.createCommentVNode("",!0),f.value?(d.openBlock(),d.createElementBlock(d.Fragment,{key:2},[p.value&&k.value?(d.openBlock(),d.createElementBlock("path",{key:0,d:k.value,class:"highlight-overlay",fill:"none",style:{"stroke-width":"calc(2px / var(--wov-zoom))"},"stroke-linecap":"round"},null,8,VS)):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,LS)):d.createCommentVNode("",!0),y.value.startHead!=="none"?(d.openBlock(),d.createBlock(sn,{key:2,position:y.value.start,direction:y.value.startDir,thickness:"calc(2px / var(--wov-zoom))","arrow-thickness":c.value,color:"var(--wov-highlighted-block-outline-color)",kind:y.value.startHead},null,8,["position","direction","arrow-thickness","kind"])):d.createCommentVNode("",!0),y.value.endHead!=="none"?(d.openBlock(),d.createBlock(sn,{key:3,position:y.value.end,direction:y.value.endDir,thickness:"calc(2px / var(--wov-zoom))","arrow-thickness":c.value,color:"var(--wov-highlighted-block-outline-color)",kind:y.value.endHead},null,8,["position","direction","arrow-thickness","kind"])):d.createCommentVNode("",!0)],64)):d.createCommentVNode("",!0)],64)):d.createCommentVNode("",!0)]))],512))}}),ir=(t,e)=>{const n=t.__vccOpts||t;for(const[r,o]of e)n[r]=o;return n},kh=ir(FS,[["__scopeId","data-v-bcf5b4f3"]]),jS={},HS={class:"wov-arrow-handle"};function WS(t,e){return d.openBlock(),d.createElementBlock("div",HS,[...e[0]||(e[0]=[d.createElementVNode("div",{class:"wov-arrow-handle-inner"},null,-1)])])}const wh=ir(jS,[["render",WS]]),ZS={},US={class:"wov-arrow-terminal"};function KS(t,e){return d.openBlock(),d.createElementBlock("div",US,[...e[0]||(e[0]=[d.createElementVNode("div",{class:"wov-arrow-terminal-ring"},[d.createElementVNode("div",{class:"wov-arrow-terminal-fill"})],-1)])])}const vh=ir(ZS,[["render",KS]]),JS={class:"arrow-svg",preserveAspectRatio:"none"},qS=["x1","y1","x2","y2"],GS=["x1","y1","x2","y2","stroke","stroke-width"],YS=["x1","y1","x2","y2"],bh=ir(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=Pe(e.entityId,h.Color),i=Pe(e.entityId,he),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 y=s.value.red.toString(16).padStart(2,"0"),k=s.value.green.toString(16).padStart(2,"0"),w=s.value.blue.toString(16).padStart(2,"0");return`#${y}${k}${w}`}),u=d.computed(()=>{var y;return((y=i.value)==null?void 0:y.thickness)??2}),f=d.computed(()=>`${u.value}px`),p=d.computed(()=>{if(!i.value)return[];const y=i.value,k=r.value,w=o.value,v=[];for(let b=0;b<y.pointCount;b++){const S=y.points[b*2]*k,C=y.points[b*2+1]*w;v.push([S,C])}return v}),m=d.computed(()=>{const y=p.value;if(y.length<2)return[];const k=[];for(let w=0;w<y.length-1;w++)k.push({start:y[w],end:y[w+1]});return k}),g=d.computed(()=>{var N,I,V,K;if(!i.value||p.value.length<2)return null;const y=i.value,k=[...p.value.map(M=>[...M])],w=y.startArrowHead,v=y.endArrowHead,b=[k[1][0]-k[0][0],k[1][1]-k[0][1]],S=[k[k.length-1][0]-k[k.length-2][0],k[k.length-1][1]-k[k.length-2][1]];let C=y.trimStart;if((N=e.connector)!=null&&N.startBlock&&w!=="none"){const M=Math.hypot(b[0],b[1]),$=((I=no(w))==null?void 0:I.gap)??0,Z=M>0?$/M:0;C+=Z}let x=y.trimEnd;if((V=e.connector)!=null&&V.endBlock&&v!=="none"){const M=Math.hypot(S[0],S[1]),$=((K=no(v))==null?void 0:K.gap)??0,Z=M>0?$/M:0;x+=Z}k[0]=[k[0][0]+(k[1][0]-k[0][0])*C,k[0][1]+(k[1][1]-k[0][1])*C];const _=k.length-1;k[_]=[k[_-1][0]+(k[_][0]-k[_-1][0])*(1-x),k[_-1][1]+(k[_][1]-k[_-1][1])*(1-x)];const T=[];for(let M=0;M<k.length-1;M++)T.push({start:k[M],end:k[M+1]});return E.Vec2.scale(b,-1),{points:k,lines:T,startPos:k[0],endPos:k[k.length-1],startDir:b,endDir:S,startHead:w,endHead:v}});return(y,k)=>(d.openBlock(),d.createElementBlock("div",{ref_key:"containerRef",ref:n,class:"wov-elbow-arrow"},[(d.openBlock(),d.createElementBlock("svg",JS,[a.value&&m.value.length>0?(d.openBlock(!0),d.createElementBlock(d.Fragment,{key:0},d.renderList(m.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,qS))),128)):d.createCommentVNode("",!0),g.value?(d.openBlock(),d.createElementBlock(d.Fragment,{key:1},[(d.openBlock(!0),d.createElementBlock(d.Fragment,null,d.renderList(g.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,GS))),128)),g.value.startHead!=="none"?(d.openBlock(),d.createBlock(sn,{key:0,position:g.value.startPos,direction:g.value.startDir,thickness:f.value,"arrow-thickness":u.value,color:c.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(sn,{key:1,position:g.value.endPos,direction:g.value.endDir,thickness:f.value,"arrow-thickness":u.value,color:c.value,kind:g.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(g.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,YS))),128)),g.value.startHead!=="none"?(d.openBlock(),d.createBlock(sn,{key:0,position:g.value.startPos,direction:g.value.startDir,thickness:"calc(2px / var(--wov-zoom))","arrow-thickness":u.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(sn,{key:1,position:g.value.endPos,direction:g.value.endDir,thickness:"calc(2px / var(--wov-zoom))","arrow-thickness":u.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))}}),[["__scopeId","data-v-b2719db1"]]);function J(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 p=u[f];p in a||(a[p]=c[p].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 ro extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Sh extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const Ch={};function ar(t){return Ch}function xh(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 Kl(t,e){return typeof e=="bigint"?e.toString():e}function Jl(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function ql(t){return t==null}function Gl(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function XS(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 _h=Symbol("evaluating");function me(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==_h)return r===void 0&&(r=_h,r=n()),r},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function lr(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function _n(...t){const e={};for(const n of t){const r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function Eh(t){return JSON.stringify(t)}const Th="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function Ci(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const QS=Jl(()=>{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 Qo(t){if(Ci(t)===!1)return!1;const e=t.constructor;if(e===void 0||typeof e!="function")return!0;const n=e.prototype;return!(Ci(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Mh(t){return Qo(t)?{...t}:Array.isArray(t)?[...t]:t}const eC=new Set(["string","number","symbol"]);function tC(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function En(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 _e(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 nC(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const rC={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 oC(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=_n(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 lr(this,"shape",i),i},checks:[]});return En(t,s)}function sC(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=_n(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 lr(this,"shape",i),i},checks:[]});return En(t,s)}function iC(t,e){if(!Qo(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=_n(t._zod.def,{get shape(){const s={...t._zod.def.shape,...e};return lr(this,"shape",s),s}});return En(t,o)}function aC(t,e){if(!Qo(e))throw new Error("Invalid input to safeExtend: expected a plain object");const n=_n(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e};return lr(this,"shape",r),r}});return En(t,n)}function lC(t,e){const n=_n(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return lr(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:[]});return En(t,n)}function cC(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=_n(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 lr(this,"shape",l),l},checks:[]});return En(e,i)}function dC(t,e,n){const r=_n(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 lr(this,"shape",s),s}});return En(e,r)}function oo(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 Ah(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function xi(t){return typeof t=="string"?t:t==null?void 0:t.message}function cr(t,e,n){var o,s,i,a,l,c;const r={...t,path:t.path??[]};if(!t.message){const u=xi((i=(s=(o=t.inst)==null?void 0:o._zod.def)==null?void 0:s.error)==null?void 0:i.call(s,t))??xi((a=e==null?void 0:e.error)==null?void 0:a.call(e,t))??xi((l=n.customError)==null?void 0:l.call(n,t))??xi((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 Yl(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function es(...t){const[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}const Nh=(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,Kl,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Bh=J("$ZodError",Nh),Oh=J("$ZodError",Nh,{Parent:Error});function uC(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 fC(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 Xl=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 ro;if(i.issues.length){const a=new((o==null?void 0:o.Err)??t)(i.issues.map(l=>cr(l,s,ar())));throw Th(a,o==null?void 0:o.callee),a}return i.value},Ql=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=>cr(l,s,ar())));throw Th(a,o==null?void 0:o.callee),a}return i.value},_i=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 ro;return s.issues.length?{success:!1,error:new(t??Bh)(s.issues.map(i=>cr(i,o,ar())))}:{success:!0,data:s.value}},hC=_i(Oh),Ei=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=>cr(i,o,ar())))}:{success:!0,data:s.value}},pC=Ei(Oh),mC=t=>(e,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Xl(t)(e,n,o)},gC=t=>(e,n,r)=>Xl(t)(e,n,r),yC=t=>async(e,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Ql(t)(e,n,o)},kC=t=>async(e,n,r)=>Ql(t)(e,n,r),wC=t=>(e,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return _i(t)(e,n,o)},vC=t=>(e,n,r)=>_i(t)(e,n,r),bC=t=>async(e,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Ei(t)(e,n,o)},SC=t=>async(e,n,r)=>Ei(t)(e,n,r),CC=/^-?\d+$/,xC=/^-?\d+(?:\.\d+)?$/,Ht=J("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Ih={number:"number",bigint:"bigint",object:"date"},Ph=J("$ZodCheckLessThan",(t,e)=>{Ht.init(t,e);const n=Ih[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})}}),Rh=J("$ZodCheckGreaterThan",(t,e)=>{Ht.init(t,e);const n=Ih[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})}}),_C=J("$ZodCheckMultipleOf",(t,e)=>{Ht.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):XS(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})}}),EC=J("$ZodCheckNumberFormat",(t,e)=>{var i;Ht.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]=rC[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=CC)}),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})}}),TC=J("$ZodCheckMaxLength",(t,e)=>{var n;Ht.init(t,e),(n=t._zod.def).when??(n.when=r=>{const o=r.value;return!ql(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=Yl(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),MC=J("$ZodCheckMinLength",(t,e)=>{var n;Ht.init(t,e),(n=t._zod.def).when??(n.when=r=>{const o=r.value;return!ql(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=Yl(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),AC=J("$ZodCheckLengthEquals",(t,e)=>{var n;Ht.init(t,e),(n=t._zod.def).when??(n.when=r=>{const o=r.value;return!ql(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=Yl(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})}}),NC=J("$ZodCheckOverwrite",(t,e)=>{Ht.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class BC{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(`
32
+ `).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(`
33
+ `))}}const OC={major:4,minor:3,patch:6},Ne=J("$ZodType",(t,e)=>{var o;var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=OC;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=oo(a),f;for(const p of l){if(p._zod.def.when){if(!p._zod.def.when(a))continue}else if(u)continue;const m=a.issues.length,g=p._zod.check(a);if(g instanceof Promise&&(c==null?void 0:c.async)===!1)throw new ro;if(f||g instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await g,a.issues.length!==m&&(u||(u=oo(a,m)))});else{if(a.issues.length===m)continue;u||(u=oo(a,m))}}return f?f.then(()=>a):a},i=(a,l,c)=>{if(oo(a))return a.aborted=!0,a;const u=s(l,r,c);if(u instanceof Promise){if(c.async===!1)throw new ro;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 ro;return c.then(u=>s(u,r,l))}return s(c,r,l)}}me(t,"~standard",()=>({validate:s=>{var i;try{const a=hC(t,s);return a.success?{value:a.data}:{issues:(i=a.error)==null?void 0:i.issues}}catch{return pC(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}))}),Dh=J("$ZodNumber",(t,e)=>{Ne.init(t,e),t._zod.pattern=t._zod.bag.pattern??xC,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}}),IC=J("$ZodNumberFormat",(t,e)=>{EC.init(t,e),Dh.init(t,e)}),PC=J("$ZodUnknown",(t,e)=>{Ne.init(t,e),t._zod.parse=n=>n}),RC=J("$ZodNever",(t,e)=>{Ne.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function zh(t,e,n){t.issues.length&&e.issues.push(...Ah(n,t.issues)),e.value[n]=t.value}const DC=J("$ZodArray",(t,e)=>{Ne.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=>zh(c,n,i))):zh(l,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function Ti(t,e,n,r,o){if(t.issues.length){if(o&&!(n in r))return;e.issues.push(...Ah(n,t.issues))}t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function $h(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=nC(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Vh(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 p=l.run({value:e[f],issues:[]},r);p instanceof Promise?t.push(p.then(m=>Ti(m,n,f,e,u))):Ti(p,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 zC=J("$ZodObject",(t,e)=>{Ne.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=Jl(()=>$h(e));me(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=Ci,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 p of i.keys){const m=f[p],g=m._zod.optout==="optional",y=m._zod.run({value:c[p],issues:[]},l);y instanceof Promise?u.push(y.then(k=>Ti(k,a,p,c,g))):Ti(y,a,p,c,g)}return s?Vh(u,c,a,l,r.value,t):u.length?Promise.all(u).then(()=>a):a}}),$C=J("$ZodObjectJIT",(t,e)=>{zC.init(t,e);const n=t._zod.parse,r=Jl(()=>$h(e)),o=p=>{var b;const m=new BC(["shape","payload","ctx"]),g=r.value,y=S=>{const C=Eh(S);return`shape[${C}]._zod.run({ value: input[${C}], issues: [] }, ctx)`};m.write("const input = payload.value;");const k=Object.create(null);let w=0;for(const S of g.keys)k[S]=`key_${w++}`;m.write("const newResult = {};");for(const S of g.keys){const C=k[S],x=Eh(S),_=p[S],T=((b=_==null?void 0:_._zod)==null?void 0:b.optout)==="optional";m.write(`const ${C} = ${y(S)};`),T?m.write(`
34
+ if (${C}.issues.length) {
35
+ if (${x} in input) {
36
+ payload.issues = payload.issues.concat(${C}.issues.map(iss => ({
37
+ ...iss,
38
+ path: iss.path ? [${x}, ...iss.path] : [${x}]
39
+ })));
40
+ }
41
+ }
42
+
43
+ if (${C}.value === undefined) {
44
+ if (${x} in input) {
45
+ newResult[${x}] = undefined;
46
+ }
47
+ } else {
48
+ newResult[${x}] = ${C}.value;
49
+ }
50
+
51
+ `):m.write(`
52
+ if (${C}.issues.length) {
53
+ payload.issues = payload.issues.concat(${C}.issues.map(iss => ({
54
+ ...iss,
55
+ path: iss.path ? [${x}, ...iss.path] : [${x}]
56
+ })));
57
+ }
58
+
59
+ if (${C}.value === undefined) {
60
+ if (${x} in input) {
61
+ newResult[${x}] = undefined;
62
+ }
63
+ } else {
64
+ newResult[${x}] = ${C}.value;
65
+ }
66
+
67
+ `)}m.write("payload.value = newResult;"),m.write("return payload;");const v=m.compile();return(S,C)=>v(p,S,C)};let s;const i=Ci,a=!Ch.jitless,c=a&&QS.value,u=e.catchall;let f;t._zod.parse=(p,m)=>{f??(f=r.value);const g=p.value;return i(g)?a&&c&&(m==null?void 0:m.async)===!1&&m.jitless!==!0?(s||(s=o(e.shape)),p=s(p,m),u?Vh([],g,p,m,f,t):p):n(p,m):(p.issues.push({expected:"object",code:"invalid_type",input:g,inst:t}),p)}});function Lh(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=>!oo(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=>cr(i,r,ar())))}),e)}const VC=J("$ZodUnion",(t,e)=>{Ne.init(t,e),me(t._zod,"optin",()=>e.options.some(o=>o._zod.optin==="optional")?"optional":void 0),me(t._zod,"optout",()=>e.options.some(o=>o._zod.optout==="optional")?"optional":void 0),me(t._zod,"values",()=>{if(e.options.every(o=>o._zod.values))return new Set(e.options.flatMap(o=>Array.from(o._zod.values)))}),me(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=>Gl(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=>Lh(l,o,t,s)):Lh(a,o,t,s)}}),LC=J("$ZodIntersection",(t,e)=>{Ne.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])=>Fh(n,l,c)):Fh(n,s,i)}});function ec(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(Qo(t)&&Qo(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=ec(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=ec(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 Fh(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}),oo(t))return t;const i=ec(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 FC=J("$ZodEnum",(t,e)=>{Ne.init(t,e);const n=xh(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(o=>eC.has(typeof o)).map(o=>typeof o=="string"?tC(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}}),jC=J("$ZodTransform",(t,e)=>{Ne.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Sh(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 ro;return n.value=o,n}});function jh(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}const Hh=J("$ZodOptional",(t,e)=>{Ne.init(t,e),t._zod.optin="optional",t._zod.optout="optional",me(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),me(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Gl(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=>jh(s,n.value)):jh(o,n.value)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),HC=J("$ZodExactOptional",(t,e)=>{Hh.init(t,e),me(t._zod,"values",()=>e.innerType._zod.values),me(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(n,r)=>e.innerType._zod.run(n,r)}),WC=J("$ZodNullable",(t,e)=>{Ne.init(t,e),me(t._zod,"optin",()=>e.innerType._zod.optin),me(t._zod,"optout",()=>e.innerType._zod.optout),me(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Gl(n.source)}|null)$`):void 0}),me(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)}),ZC=J("$ZodDefault",(t,e)=>{Ne.init(t,e),t._zod.optin="optional",me(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=>Wh(s,e)):Wh(o,e)}});function Wh(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const UC=J("$ZodPrefault",(t,e)=>{Ne.init(t,e),t._zod.optin="optional",me(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))}),KC=J("$ZodNonOptional",(t,e)=>{Ne.init(t,e),me(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=>Zh(s,t)):Zh(o,t)}});function Zh(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 JC=J("$ZodCatch",(t,e)=>{Ne.init(t,e),me(t._zod,"optin",()=>e.innerType._zod.optin),me(t._zod,"optout",()=>e.innerType._zod.optout),me(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=>cr(i,r,ar()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(s=>cr(s,r,ar()))},input:n.value}),n.issues=[]),n)}}),qC=J("$ZodPipe",(t,e)=>{Ne.init(t,e),me(t._zod,"values",()=>e.in._zod.values),me(t._zod,"optin",()=>e.in._zod.optin),me(t._zod,"optout",()=>e.out._zod.optout),me(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=>Mi(i,e.in,r)):Mi(s,e.in,r)}const o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Mi(s,e.out,r)):Mi(o,e.out,r)}});function Mi(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},n)}const GC=J("$ZodReadonly",(t,e)=>{Ne.init(t,e),me(t._zod,"propValues",()=>e.innerType._zod.propValues),me(t._zod,"values",()=>e.innerType._zod.values),me(t._zod,"optin",()=>{var n,r;return(r=(n=e.innerType)==null?void 0:n._zod)==null?void 0:r.optin}),me(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(Uh):Uh(o)}});function Uh(t){return t.value=Object.freeze(t.value),t}const YC=J("$ZodCustom",(t,e)=>{Ht.init(t,e),Ne.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=>Kh(s,n,r,t));Kh(o,n,r,t)}});function Kh(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(es(o))}}var Jh;class XC{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 QC(){return new XC}(Jh=globalThis).__zod_globalRegistry??(Jh.__zod_globalRegistry=QC());const ts=globalThis.__zod_globalRegistry;function ex(t,e){return new t({type:"number",checks:[],..._e(e)})}function tx(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",..._e(e)})}function nx(t){return new t({type:"unknown"})}function rx(t,e){return new t({type:"never",..._e(e)})}function qh(t,e){return new Ph({check:"less_than",..._e(e),value:t,inclusive:!1})}function tc(t,e){return new Ph({check:"less_than",..._e(e),value:t,inclusive:!0})}function Gh(t,e){return new Rh({check:"greater_than",..._e(e),value:t,inclusive:!1})}function nc(t,e){return new Rh({check:"greater_than",..._e(e),value:t,inclusive:!0})}function Yh(t,e){return new _C({check:"multiple_of",..._e(e),value:t})}function ox(t,e){return new TC({check:"max_length",..._e(e),maximum:t})}function Xh(t,e){return new MC({check:"min_length",..._e(e),minimum:t})}function sx(t,e){return new AC({check:"length_equals",..._e(e),length:t})}function ix(t){return new NC({check:"overwrite",tx:t})}function ax(t,e,n){return new t({type:"array",element:e,..._e(n)})}function lx(t,e,n){return new t({type:"custom",check:"custom",fn:e,..._e(n)})}function cx(t){const e=dx(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(es(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(es(o))}},t(n.value,n)));return e}function dx(t,e){const n=new Ht({check:"custom",..._e(e)});return n._zod.check=t,n}function Qh(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)??ts,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 Ve(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 p={...n,schemaPath:[...n.schemaPath,t],path:n.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,i.schema,p);else{const g=i.schema,y=e.processors[o.type];if(!y)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);y(t,e,g,p)}const m=t._zod.parent;m&&(i.ref||(i.ref=m),Ve(m,e,p),e.seen.get(m).isParent=!0)}const l=e.metadataRegistry.get(t);return l&&Object.assign(i.schema,l),e.io==="input"&&Xe(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 ep(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 p=r.get(f);if(p&&p!==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 y;const f=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){const k=(y=t.external.registry.get(u[0]))==null?void 0:y.id,w=t.external.uri??(b=>b);if(k)return{ref:w(k)};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 m=`#/${f}/`,g=u[1].schema.id??`__schema${t.counter++}`;return{defId:g,ref:m+g}},s=u=>{if(u[1].schema.$ref)return;const f=u[1],{ref:p,defId:m}=o(u);f.def={...f.schema},m&&(f.defId=m);const g=f.schema;for(const y in g)delete g[y];g.$ref=p};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>
68
+
69
+ 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 m=(l=t.external.registry.get(u[0]))==null?void 0:l.id;if(e!==u[0]&&m){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 tp(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,p={...f},m=u.ref;if(u.ref=null,m){r(m);const y=t.seen.get(m),k=y.schema;if(k.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(f.allOf=f.allOf??[],f.allOf.push(k)):Object.assign(f,k),Object.assign(f,p),c._zod.parent===m)for(const v in f)v==="$ref"||v==="allOf"||v in p||delete f[v];if(k.$ref&&y.def)for(const v in f)v==="$ref"||v==="allOf"||v in y.def&&JSON.stringify(f[v])===JSON.stringify(y.def[v])&&delete f[v]}const g=c._zod.parent;if(g&&g!==m){r(g);const y=t.seen.get(g);if(y!=null&&y.schema.$ref&&(f.$ref=y.schema.$ref,y.def))for(const k in f)k==="$ref"||k==="allOf"||k in y.def&&JSON.stringify(f[k])===JSON.stringify(y.def[k])&&delete f[k]}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:Ai(e,"input",t.processors),output:Ai(e,"output",t.processors)}},enumerable:!1,writable:!1}),c}catch{throw new Error("Error converting schema to JSON.")}}function Xe(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 Xe(r.element,n);if(r.type==="set")return Xe(r.valueType,n);if(r.type==="lazy")return Xe(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 Xe(r.innerType,n);if(r.type==="intersection")return Xe(r.left,n)||Xe(r.right,n);if(r.type==="record"||r.type==="map")return Xe(r.keyType,n)||Xe(r.valueType,n);if(r.type==="pipe")return Xe(r.in,n)||Xe(r.out,n);if(r.type==="object"){for(const o in r.shape)if(Xe(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(const o of r.options)if(Xe(o,n))return!0;return!1}if(r.type==="tuple"){for(const o of r.items)if(Xe(o,n))return!0;return!!(r.rest&&Xe(r.rest,n))}return!1}const ux=(t,e={})=>n=>{const r=Qh({...n,processors:e});return Ve(t,r),ep(r,t),tp(r,t)},Ai=(t,e,n={})=>r=>{const{libraryOptions:o,target:s}=r??{},i=Qh({...o??{},target:s,io:e,processors:n});return Ve(t,i),ep(i,t),tp(i,t)},fx=(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)},hx=(t,e,n,r)=>{n.not={}},px=(t,e,n,r)=>{},mx=(t,e,n,r)=>{const o=t._zod.def,s=xh(o.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},gx=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},yx=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},kx=(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=Ve(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]=Ve(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=Ve(s.catchall,e,{...r,path:[...r.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},vx=(t,e,n,r)=>{const o=t._zod.def,s=o.inclusive===!1,i=o.options.map((a,l)=>Ve(a,e,{...r,path:[...r.path,s?"oneOf":"anyOf",l]}));s?n.oneOf=i:n.anyOf=i},bx=(t,e,n,r)=>{const o=t._zod.def,s=Ve(o.left,e,{...r,path:[...r.path,"allOf",0]}),i=Ve(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},Sx=(t,e,n,r)=>{const o=t._zod.def,s=Ve(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;Ve(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType},xx=(t,e,n,r)=>{const o=t._zod.def;Ve(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},_x=(t,e,n,r)=>{const o=t._zod.def;Ve(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)))},Ex=(t,e,n,r)=>{const o=t._zod.def;Ve(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},Tx=(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;Ve(s,e,r);const i=e.seen.get(t);i.ref=s},Mx=(t,e,n,r)=>{const o=t._zod.def;Ve(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType,n.readOnly=!0},np=(t,e,n,r)=>{const o=t._zod.def;Ve(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType},mt=J("ZodError",(t,e)=>{Bh.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>fC(t,n)},flatten:{value:n=>uC(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,Kl,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,Kl,2)}},isEmpty:{get(){return t.issues.length===0}}})},{Parent:Error}),Ax=Xl(mt),Nx=Ql(mt),Bx=_i(mt),Ox=Ei(mt),Ix=mC(mt),Px=gC(mt),Rx=yC(mt),Dx=kC(mt),zx=wC(mt),$x=vC(mt),Vx=bC(mt),Lx=SC(mt),Be=J("ZodType",(t,e)=>(Ne.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:Ai(t,"input"),output:Ai(t,"output")}}),t.toJSONSchema=ux(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone(_n(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)=>En(t,n,r),t.brand=()=>t,t.register=(n,r)=>(n.add(t,r),t),t.parse=(n,r)=>Ax(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Bx(t,n,r),t.parseAsync=async(n,r)=>Nx(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Ox(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>Ix(t,n,r),t.decode=(n,r)=>Px(t,n,r),t.encodeAsync=async(n,r)=>Rx(t,n,r),t.decodeAsync=async(n,r)=>Dx(t,n,r),t.safeEncode=(n,r)=>zx(t,n,r),t.safeDecode=(n,r)=>$x(t,n,r),t.safeEncodeAsync=async(n,r)=>Vx(t,n,r),t.safeDecodeAsync=async(n,r)=>Lx(t,n,r),t.refine=(n,r)=>t.check(g_(n,r)),t.superRefine=n=>t.check(y_(n)),t.overwrite=n=>t.check(ix(n)),t.optional=()=>lp(t),t.exactOptional=()=>r_(t),t.nullable=()=>cp(t),t.nullish=()=>lp(cp(t)),t.nonoptional=n=>c_(t,n),t.array=()=>Ux(t),t.or=n=>Gx([t,n]),t.and=n=>Xx(t,n),t.transform=n=>up(t,t_(n)),t.default=n=>i_(t,n),t.prefault=n=>l_(t,n),t.catch=n=>u_(t,n),t.pipe=n=>up(t,n),t.readonly=()=>p_(t),t.describe=n=>{const r=t.clone();return ts.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){var n;return(n=ts.get(t))==null?void 0:n.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return ts.get(t);const r=t.clone();return ts.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t.apply=n=>n(t),t)),rp=J("ZodNumber",(t,e)=>{Dh.init(t,e),Be.init(t,e),t._zod.processJSONSchema=(r,o,s)=>fx(t,r,o),t.gt=(r,o)=>t.check(Gh(r,o)),t.gte=(r,o)=>t.check(nc(r,o)),t.min=(r,o)=>t.check(nc(r,o)),t.lt=(r,o)=>t.check(qh(r,o)),t.lte=(r,o)=>t.check(tc(r,o)),t.max=(r,o)=>t.check(tc(r,o)),t.int=r=>t.check(sp(r)),t.safe=r=>t.check(sp(r)),t.positive=r=>t.check(Gh(0,r)),t.nonnegative=r=>t.check(nc(0,r)),t.negative=r=>t.check(qh(0,r)),t.nonpositive=r=>t.check(tc(0,r)),t.multipleOf=(r,o)=>t.check(Yh(r,o)),t.step=(r,o)=>t.check(Yh(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 op(t){return ex(rp,t)}const Fx=J("ZodNumberFormat",(t,e)=>{IC.init(t,e),rp.init(t,e)});function sp(t){return tx(Fx,t)}const jx=J("ZodUnknown",(t,e)=>{PC.init(t,e),Be.init(t,e),t._zod.processJSONSchema=(n,r,o)=>px()});function ip(){return nx(jx)}const Hx=J("ZodNever",(t,e)=>{RC.init(t,e),Be.init(t,e),t._zod.processJSONSchema=(n,r,o)=>hx(t,n,r)});function Wx(t){return rx(Hx,t)}const Zx=J("ZodArray",(t,e)=>{DC.init(t,e),Be.init(t,e),t._zod.processJSONSchema=(n,r,o)=>kx(t,n,r,o),t.element=e.element,t.min=(n,r)=>t.check(Xh(n,r)),t.nonempty=n=>t.check(Xh(1,n)),t.max=(n,r)=>t.check(ox(n,r)),t.length=(n,r)=>t.check(sx(n,r)),t.unwrap=()=>t.element});function Ux(t,e){return ax(Zx,t,e)}const Kx=J("ZodObject",(t,e)=>{$C.init(t,e),Be.init(t,e),t._zod.processJSONSchema=(n,r,o)=>wx(t,n,r,o),me(t,"shape",()=>e.shape),t.keyof=()=>Qx(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:ip()}),t.loose=()=>t.clone({...t._zod.def,catchall:ip()}),t.strict=()=>t.clone({...t._zod.def,catchall:Wx()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>iC(t,n),t.safeExtend=n=>aC(t,n),t.merge=n=>lC(t,n),t.pick=n=>oC(t,n),t.omit=n=>sC(t,n),t.partial=(...n)=>cC(ap,t,n[0]),t.required=(...n)=>dC(dp,t,n[0])});function Jx(t,e){const n={type:"object",shape:t??{},..._e(e)};return new Kx(n)}const qx=J("ZodUnion",(t,e)=>{VC.init(t,e),Be.init(t,e),t._zod.processJSONSchema=(n,r,o)=>vx(t,n,r,o),t.options=e.options});function Gx(t,e){return new qx({type:"union",options:t,..._e(e)})}const Yx=J("ZodIntersection",(t,e)=>{LC.init(t,e),Be.init(t,e),t._zod.processJSONSchema=(n,r,o)=>bx(t,n,r,o)});function Xx(t,e){return new Yx({type:"intersection",left:t,right:e})}const rc=J("ZodEnum",(t,e)=>{FC.init(t,e),Be.init(t,e),t._zod.processJSONSchema=(r,o,s)=>mx(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 rc({...e,checks:[],..._e(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 rc({...e,checks:[],..._e(o),entries:s})}});function Qx(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new rc({type:"enum",entries:n,..._e(e)})}const e_=J("ZodTransform",(t,e)=>{jC.init(t,e),Be.init(t,e),t._zod.processJSONSchema=(n,r,o)=>yx(t,n),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Sh(t.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(es(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(es(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 e_({type:"transform",transform:t})}const ap=J("ZodOptional",(t,e)=>{Hh.init(t,e),Be.init(t,e),t._zod.processJSONSchema=(n,r,o)=>np(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function lp(t){return new ap({type:"optional",innerType:t})}const n_=J("ZodExactOptional",(t,e)=>{HC.init(t,e),Be.init(t,e),t._zod.processJSONSchema=(n,r,o)=>np(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function r_(t){return new n_({type:"optional",innerType:t})}const o_=J("ZodNullable",(t,e)=>{WC.init(t,e),Be.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Sx(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function cp(t){return new o_({type:"nullable",innerType:t})}const s_=J("ZodDefault",(t,e)=>{ZC.init(t,e),Be.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 i_(t,e){return new s_({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():Mh(e)}})}const a_=J("ZodPrefault",(t,e)=>{UC.init(t,e),Be.init(t,e),t._zod.processJSONSchema=(n,r,o)=>_x(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function l_(t,e){return new a_({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():Mh(e)}})}const dp=J("ZodNonOptional",(t,e)=>{KC.init(t,e),Be.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Cx(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function c_(t,e){return new dp({type:"nonoptional",innerType:t,..._e(e)})}const d_=J("ZodCatch",(t,e)=>{JC.init(t,e),Be.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Ex(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function u_(t,e){return new d_({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const f_=J("ZodPipe",(t,e)=>{qC.init(t,e),Be.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Tx(t,n,r,o),t.in=e.in,t.out=e.out});function up(t,e){return new f_({type:"pipe",in:t,out:e})}const h_=J("ZodReadonly",(t,e)=>{GC.init(t,e),Be.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Mx(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function p_(t){return new h_({type:"readonly",innerType:t})}const m_=J("ZodCustom",(t,e)=>{YC.init(t,e),Be.init(t,e),t._zod.processJSONSchema=(n,r,o)=>gx(t,n)});function g_(t,e={}){return lx(m_,t,e)}function y_(t){return cx(t)}var k_=Object.defineProperty,oc=(t,e)=>{for(var n in e)k_(t,n,{get:e[n],enumerable:!0})},fp=h.defineCommand("start-eraser-stroke"),hp=h.defineCommand("add-eraser-stroke-point"),pp=h.defineCommand("complete-eraser-stroke"),mp=h.defineCommand("cancel-eraser-stroke");h.defineCommand("mark-as-erased");var gp={};oc(gp,{Erased:()=>dr,EraserStroke:()=>ns});var dr=h.defineCanvasComponent({name:"erased"},{eraserStrokeId:h.field.ref()}),so=8,w_="eraser",Wt=20,ns=h.defineCanvasComponent({name:"eraserStroke"},{points:h.field.buffer(h.field.float32()).size(Wt*2),pointCount:h.field.uint32().default(0),firstPointIndex:h.field.uint32().default(0),radius:h.field.float32().default(8)}),yp={};oc(yp,{EraserStateSingleton:()=>sc});var ur={Idle:"idle",Erasing:"erasing"},sc=h.defineEditorState("eraserState",{state:h.field.string().max(16).default(ur.Idle),activeStroke:h.field.ref(),lastWorldPosition:h.field.tuple(h.field.float64(),2).default([0,0])}),kp={};oc(kp,{captureEraserSystem:()=>b_,updateEraserSystem:()=>x_});var v_=on({guards:{},actions:{startStroke:({event:t})=>{fp.spawn(t.ctx,{worldPosition:t.worldPosition})},addPoint:we({lastWorldPosition:({event:t,context:e})=>e.activeStroke?(hp.spawn(t.ctx,{strokeId:e.activeStroke,worldPosition:t.worldPosition}),[t.worldPosition[0],t.worldPosition[1]]):e.lastWorldPosition}),completeStroke:({event:t,context:e})=>{e.activeStroke&&pp.spawn(t.ctx,{strokeId:e.activeStroke})},cancelStroke:({event:t,context:e})=>{e.activeStroke&&mp.spawn(t.ctx,{strokeId:e.activeStroke})},resetContext:we({activeStroke:()=>null,lastWorldPosition:()=>[0,0]})}}).createMachine({id:"eraser",initial:ur.Idle,context:{activeStroke:null,lastWorldPosition:[0,0]},states:{[ur.Idle]:{entry:["resetContext"],on:{pointerDown:{target:ur.Erasing,actions:["startStroke"]}}},[ur.Erasing]:{on:{pointerMove:{actions:["addPoint"]},frame:{actions:["addPoint"]},pointerUp:{target:ur.Idle,actions:["completeStroke"]},cancel:{target:ur.Idle,actions:["cancelStroke"]}}}}}),b_=h.defineEditorSystem({phase:"capture",priority:100},t=>{const e=h.Controls.getButtons(t,"eraser"),n=h.getPointerInput(t,e,{includeFrameEvent:!0});n.length!==0&&sc.run(t,v_,n)}),S_=h.defineQuery(t=>t.with(h.Block,h.Synced,h.Aabb)),C_=h.defineQuery(t=>t.with(dr)),x_=h.defineEditorSystem({phase:"update"},t=>{h.on(t,fp,(e,{worldPosition:n})=>{__(e,n)}),h.on(t,hp,(e,{strokeId:n,worldPosition:r})=>{E_(e,n,r)}),h.on(t,pp,(e,{strokeId:n})=>{A_(e,n)}),h.on(t,mp,(e,{strokeId:n})=>{N_(e,n)})});function __(t,e){const n=h.createEntity(t);h.addComponent(t,n,h.Block,{tag:"eraser",rank:h.RankBounds.genNext(t),position:[e[0]-so,e[1]-so],size:[so*2,so*2]}),h.addComponent(t,n,ns,{points:e,pointCount:1,firstPointIndex:0,radius:so});const r=sc.write(t);r.activeStroke=n,r.lastWorldPosition=e}function E_(t,e,n){const r=ns.write(t,e),o=r.pointCount,s=(o-1)%Wt*2,i=r.points[s],a=r.points[s+1],l=o%Wt*2;if(r.points[l]=n[0],r.points[l+1]=n[1],r.pointCount++,r.pointCount>Wt&&(r.firstPointIndex=(r.pointCount-Wt)%Wt),!h.Aabb.containsPoint(t,e,n)){h.Aabb.expandByPoint(t,e,n);const{value:y}=h.Aabb.read(t,e),k=h.Block.write(t,e);E.Vec2.set(k.position,E.Aabb.left(y),E.Aabb.top(y)),E.Vec2.set(k.size,E.Aabb.width(y),E.Aabb.height(y))}const c=n[0]-i,u=n[1]-a;if(c*c+u*u<1)return;const p=E.Capsule.create(i,a,n[0],n[1],so),m=T_(t,S_.current(t)),g=h.intersectCapsule(t,p,m);for(const y of g)M_(t,y,e)}function*T_(t,e){for(const n of e)h.hasComponent(t,n,dr)||(yield n)}function M_(t,e,n){h.addComponent(t,e,dr,{eraserStrokeId:n}),h.addComponent(t,e,h.Opacity,{value:80})}function A_(t,e){const n=h.getBackrefs(t,e,dr,"eraserStrokeId");for(const r of n)h.removeEntity(t,r);h.removeEntity(t,e)}function N_(t,e){const n=[];for(const r of C_.current(t))dr.read(t,r).eraserStrokeId===e&&n.push(r);for(const r of n)h.removeComponent(t,r,dr),h.removeComponent(t,r,h.Opacity);h.removeEntity(t,e)}var B_=t=>Object.values(t).filter(e=>typeof e=="object"&&e!==null&&"_system"in e&&"phase"in e),O_=Jx({tailRadius:op().positive().optional(),tailLength:op().int().min(1).max(Wt).optional()});function I_(t={}){const e=O_.parse(t);return{name:w_,components:Object.values(gp).filter(n=>n instanceof h.CanvasComponentDef),singletons:Object.values(yp).filter(n=>n instanceof h.CanvasSingletonDef),blockDefs:[{tag:"eraser-stroke",stratum:"overlay",canRotate:!1,canScale:!1,components:[ns]}],systems:B_(kp),resources:{tailRadius:e.tailRadius??8,tailLength:e.tailLength??Wt}}}const{PI:P_}=Math,rs=P_+1e-4,wp=.5,vp=[1,1];function bp(t,e,n,r=o=>o){return t*r(.5-e*(.5-n))}const{min:ic}=Math;function Sp(t,e,n){let r=ic(1,e/n);return ic(1,t+(ic(1,1-r)-t)*(r*.275))}function R_(t){return[-t[0],-t[1]]}function Zt(t,e){return[t[0]+e[0],t[1]+e[1]]}function Cp(t,e,n){return t[0]=e[0]+n[0],t[1]=e[1]+n[1],t}function Tn(t,e){return[t[0]-e[0],t[1]-e[1]]}function ac(t,e,n){return t[0]=e[0]-n[0],t[1]=e[1]-n[1],t}function Mn(t,e){return[t[0]*e,t[1]*e]}function lc(t,e,n){return t[0]=e[0]*n,t[1]=e[1]*n,t}function D_(t,e){return[t[0]/e,t[1]/e]}function xp(t){return[t[1],-t[0]]}function cc(t,e){let n=e[0];return t[0]=e[1],t[1]=-n,t}function _p(t,e){return t[0]*e[0]+t[1]*e[1]}function z_(t,e){return t[0]===e[0]&&t[1]===e[1]}function $_(t){return Math.hypot(t[0],t[1])}function Ep(t,e){let n=t[0]-e[0],r=t[1]-e[1];return n*n+r*r}function Tp(t){return D_(t,$_(t))}function V_(t,e){return Math.hypot(t[1]-e[1],t[0]-e[0])}function dc(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 Mp(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 Ap(t,e,n){return Zt(t,Mn(Tn(e,t),n))}function L_(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 Np(t,e,n){return Zt(t,Mn(e,n))}const Le=[0,0],An=[0,0],Nn=[0,0];function F_(t,e){let n=Np(t,Tp(xp(Tn(t,Zt(t,[1,1])))),-e),r=[],o=1/13;for(let s=o;s<=1;s+=o)r.push(dc(n,t,rs*2*s));return r}function j_(t,e,n){let r=[],o=1/n;for(let s=o;s<=1;s+=o)r.push(dc(e,t,rs*s));return r}function H_(t,e,n){let r=Tn(e,n),o=Mn(r,.5),s=Mn(r,.51);return[Tn(t,o),Tn(t,s),Zt(t,s),Zt(t,o)]}function W_(t,e,n,r){let o=[],s=Np(t,e,n),i=1/r;for(let a=i;a<1;a+=i)o.push(dc(s,t,rs*3*a));return o}function Z_(t,e,n){return[Zt(t,Mn(e,n)),Zt(t,Mn(e,n*.99)),Tn(t,Mn(e,n*.99)),Tn(t,Mn(e,n))]}function Bp(t,e,n){return t===!1||t===void 0?0:t===!0?Math.max(e,n):t}function U_(t,e,n){return t.slice(0,10).reduce((r,o)=>{let s=o.pressure;return e&&(s=Sp(r,o.distance,n)),(r+s)/2},t[0].pressure)}function K_(t,e={}){let{size:n=16,smoothing:r=.5,thinning:o=.5,simulatePressure:s=!0,easing:i=X=>X,start:a={},end:l={},last:c=!1}=e,{cap:u=!0,easing:f=X=>X*(2-X)}=a,{cap:p=!0,easing:m=X=>--X*X*X+1}=l;if(t.length===0||n<=0)return[];let g=t[t.length-1].runningLength,y=Bp(a.taper,n,g),k=Bp(l.taper,n,g),w=(n*r)**2,v=[],b=[],S=U_(t,s,n),C=bp(n,o,t[t.length-1].pressure,i),x,_=t[0].vector,T=t[0].point,N=T,I=T,V=N,K=!1;for(let X=0;X<t.length;X++){let{pressure:j}=t[X],{point:q,vector:te,distance:fe,runningLength:ce}=t[X],Se=X===t.length-1;if(!Se&&g-ce<3)continue;o?(s&&(j=Sp(S,fe,n)),C=bp(n,o,j,i)):C=n/2,x===void 0&&(x=C);let Dt=ce<y?f(ce/y):1,gn=g-ce<k?m((g-ce)/k):1;C=Math.max(.01,C*Math.min(Dt,gn));let Dr=(Se?t[X]:t[X+1]).vector,qn=Se?1:_p(te,Dr),ja=_p(te,_)<0&&!K,xo=qn!==null&&qn<0;if(ja||xo){cc(Le,_),lc(Le,Le,C);for(let Gn=0;Gn<=1;Gn+=.07692307692307693)ac(An,q,Le),Mp(An,An,q,rs*Gn),I=[An[0],An[1]],v.push(I),Cp(Nn,q,Le),Mp(Nn,Nn,q,rs*-Gn),V=[Nn[0],Nn[1]],b.push(V);T=I,N=V,xo&&(K=!0);continue}if(K=!1,Se){cc(Le,te),lc(Le,Le,C),v.push(Tn(q,Le)),b.push(Zt(q,Le));continue}L_(Le,Dr,te,qn),cc(Le,Le),lc(Le,Le,C),ac(An,q,Le),I=[An[0],An[1]],(X<=1||Ep(T,I)>w)&&(v.push(I),T=I),Cp(Nn,q,Le),V=[Nn[0],Nn[1]],(X<=1||Ep(N,V)>w)&&(b.push(V),N=V),S=j,_=te}let M=[t[0].point[0],t[0].point[1]],$=t.length>1?[t[t.length-1].point[0],t[t.length-1].point[1]]:Zt(t[0].point,[1,1]),Z=[],ae=[];if(t.length===1){if(!(y||k)||c)return F_(M,x||C)}else{y||k&&t.length===1||(u?Z.push(...j_(M,b[0],13)):Z.push(...H_(M,v[0],b[0])));let X=xp(R_(t[t.length-1].vector));k||y&&t.length===1?ae.push($):p?ae.push(...W_($,X,C,29)):ae.push(...Z_($,X,C))}return v.concat(ae,b.reverse(),Z)}const Op=[0,0];function Ip(t){return t!=null&&t>=0}function J_(t,e={}){var p;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:m,y:g,pressure:y=wp})=>[m,g,y]);if(i.length===2){let m=i[1];i=i.slice(0,-1);for(let g=1;g<5;g++)i.push(Ap(i[0],m,g/4))}i.length===1&&(i=[...i,[...Zt(i[0],vp),...i[0].slice(2)]]);let a=[{point:[i[0][0],i[0][1]],pressure:Ip(i[0][2])?i[0][2]:.25,vector:[...vp],distance:0,runningLength:0}],l=!1,c=0,u=a[0],f=i.length-1;for(let m=1;m<i.length;m++){let g=o&&m===f?[i[m][0],i[m][1]]:Ap(u.point,i[m],s);if(z_(u.point,g))continue;let y=V_(g,u.point);if(c+=y,m<f&&!l){if(c<r)continue;l=!0}ac(Op,u.point,g),u={point:g,pressure:Ip(i[m][2])?i[m][2]:wp,vector:Tp(Op),distance:y,runningLength:c},a.push(u)}return a[0].vector=((p=a[1])==null?void 0:p.vector)||[0,0],a}function uc(t,e={}){return K_(J_(t,e),e)}const q_={class:"wov-eraser-stroke"},G_={preserveAspectRatio:"none"},Y_=["d"],X_="#88888833",Pp=d.defineComponent({__name:"Eraser",props:{entityId:{}},setup(t){const e=t,n=Pe(e.entityId,ns),r=Pe(e.entityId,h.Block),o=d.shallowRef("");function s(a,l){return(a+l)/2}function i(a,l,c,u,f,p){if(a<=4)return"";const m=[],g=Math.min(a,Wt);for(let S=0;S<g;S++){const C=(l+S)%Wt*2;m.push([c[C]-f,c[C+1]-p])}const y=uc(m,{size:u,start:{taper:66,cap:!0}});if(y.length<3)return"";let k=y[0],w=y[1];const v=y[2];let b=`M${k[0].toFixed(2)},${k[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<y.length-1;S++)k=y[S],w=y[S+1],b+=`${s(k[0],w[0]).toFixed(2)},${s(k[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",q_,[(d.openBlock(),d.createElementBlock("svg",G_,[d.createElementVNode("path",{d:o.value,fill:X_},null,8,Y_)]))]))}}),Q_={class:"wov-image-block"},eE={key:0,class:"wov-image-placeholder"},tE={key:1,class:"wov-image-placeholder wov-image-error"},nE=["src","alt"],rE={key:3,class:"wov-image-upload-overlay"},oE={class:"wov-image-upload-status"},Rp=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(pt);if(!n)throw new Error("ImageBlock must be used within a WovenCanvas component");const r=n,o=Pe(e.entityId,h.Asset),s=Pe(e.entityId,h.Image),i=d.ref(null),a=d.ref(!0),l=d.ref(!1);let c=!0;d.onUnmounted(()=>{c=!1});async function u(){const m=r.getAssetManager();if(!m){a.value=!1,l.value=!0;return}const g=o.value;if(!g){a.value=!1;return}try{a.value=!0,l.value=!1;const y=await m.getDisplayUrl(g.identifier);if(!c)return;y?(i.value=y,a.value=!1):g.uploadState===h.UploadState.Failed&&(l.value=!0,a.value=!1)}catch(y){if(!c)return;console.error("Failed to get display URL:",y),l.value=!0,a.value=!1}}d.watch(()=>o.value,()=>{u()},{immediate:!0}),d.onMounted(()=>{u()});const f=d.computed(()=>{const m=o.value;if(!m)return null;switch(m.uploadState){case h.UploadState.Pending:return"Loading...";case h.UploadState.Uploading:return"Loading...";case h.UploadState.Failed:return"Failed";default:return null}}),p=d.computed(()=>({width:"100%",height:"100%",objectFit:"fill"}));return(m,g)=>{var y;return d.openBlock(),d.createElementBlock("div",Q_,[a.value&&!i.value?(d.openBlock(),d.createElementBlock("div",eE,[...g[0]||(g[0]=[d.createElementVNode("span",null,"Loading...",-1)])])):l.value?(d.openBlock(),d.createElementBlock("div",tE,[...g[1]||(g[1]=[d.createElementVNode("span",null,"Failed to load image",-1)])])):i.value?(d.openBlock(),d.createElementBlock("img",{key:2,src:i.value,alt:((y=d.unref(s))==null?void 0:y.alt)||"",style:d.normalizeStyle(p.value),draggable:"false"},null,12,nE)):d.createCommentVNode("",!0),f.value?(d.openBlock(),d.createElementBlock("div",rE,[d.createElementVNode("span",oE,d.toDisplayString(f.value),1)])):d.createCommentVNode("",!0)])}}});function sE(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Dp={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,p=c.x-u,m=c.y-f;if(p!==0||m!==0){var g=((a.x-u)*p+(a.y-f)*m)/(p*p+m*m);g>1?(u=c.x,f=c.y):g>0&&(u+=p*g,f+=m*g)}return p=a.x-u,m=a.y-f,p*p+m*m}function r(a,l){for(var c=a[0],u=[c],f,p=1,m=a.length;p<m;p++)f=a[p],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 p=u,m,g=l+1;g<c;g++){var y=n(a[g],a[l],a[c]);y>p&&(m=g,p=y)}p>u&&(m-l>1&&o(a,l,m,u,f),f.push(a[m]),c-m>1&&o(a,m,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})()})(Dp);var iE=Dp.exports;const zp=sE(iE);var aE=Object.defineProperty,fc=(t,e)=>{for(var n in e)aE(t,n,{get:e[n],enumerable:!0})},$p=h.defineCommand("start-pen-stroke"),Vp=h.defineCommand("add-pen-stroke-point"),Lp=h.defineCommand("complete-pen-stroke"),Fp=h.defineCommand("remove-pen-stroke"),jp={};fc(jp,{POINTS_CAPACITY:()=>Ni,PenStroke:()=>Nt});var Ni=256,lE={points:h.field.buffer(h.field.float32()).size(Ni*2),pressures:h.field.buffer(h.field.float32()).size(Ni),pointCount:h.field.uint32().default(0),thickness:h.field.float32().default(8),originalLeft:h.field.float32().default(0),originalTop:h.field.float32().default(0),originalWidth:h.field.float32().default(0),originalHeight:h.field.float32().default(0),isComplete:h.field.boolean().default(!1),hasPressure:h.field.boolean().default(!1)},cE=class extends h.CanvasComponentDef{constructor(){super({name:"penStroke",sync:"document"},lE)}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}},Nt=new cE,dE=8,uE="pen",Hp={};fc(Hp,{PenStateSingleton:()=>hc});var fr={Idle:"idle",Drawing:"drawing"},hc=h.defineEditorState("penState",{state:h.field.string().max(16).default(fr.Idle),activeStroke:h.field.ref(),lastWorldPosition:h.field.tuple(h.field.float64(),2).default([0,0])}),Wp={};fc(Wp,{capturePenSystem:()=>hE,updatePenSystem:()=>mE});var fE=on({guards:{},actions:{startStroke:({event:t})=>{const e=t.pointerType===h.PointerType.Pen?t.pressure:null;$p.spawn(t.ctx,{worldPosition:t.worldPosition,pressure:e,thickness:dE})},addPoint:we({lastWorldPosition:({event:t,context:e})=>{if(!e.activeStroke)return e.lastWorldPosition;const n=t.pointerType===h.PointerType.Pen?t.pressure:null;return Vp.spawn(t.ctx,{strokeId:e.activeStroke,worldPosition:t.worldPosition,pressure:n}),t.worldPosition}}),completeStroke:({event:t,context:e})=>{e.activeStroke&&Lp.spawn(t.ctx,{strokeId:e.activeStroke})},removeStroke:({event:t,context:e})=>{e.activeStroke&&Fp.spawn(t.ctx,{strokeId:e.activeStroke})},resetContext:we({activeStroke:()=>null,lastWorldPosition:()=>[0,0]})}}).createMachine({id:"pen",initial:fr.Idle,context:{activeStroke:null,lastWorldPosition:[0,0]},states:{[fr.Idle]:{entry:["resetContext"],on:{pointerDown:{target:fr.Drawing,actions:["startStroke"]}}},[fr.Drawing]:{on:{pointerMove:{actions:["addPoint"]},pointerUp:{target:fr.Idle,actions:["completeStroke"]},cancel:{target:fr.Idle,actions:["removeStroke"]}}}}}),hE=h.defineEditorSystem({phase:"capture",priority:100},t=>{const e=h.Controls.getButtons(t,"pen"),n=h.getPointerInput(t,e);n.length!==0&&hc.run(t,fE,n)}),pE=h.defineQuery(t=>t.tracking(Nt)),mE=h.defineEditorSystem({phase:"update"},t=>{h.on(t,$p,(e,{worldPosition:n,pressure:r,thickness:o})=>{gE(e,n,r,o)}),h.on(t,Vp,(e,{strokeId:n,worldPosition:r,pressure:o})=>{yE(e,n,r,o)}),h.on(t,Lp,(e,{strokeId:n})=>{kE(e,n)}),h.on(t,Fp,(e,{strokeId:n})=>{wE(e,n)});for(const e of pE.addedOrChanged(t))Nt.read(t,e).isComplete&&Zp(t,e)});function gE(t,e,n,r){const o=r/2,s=h.createEntity(t);h.addComponent(t,s,h.Synced,{id:crypto.randomUUID()}),h.addComponent(t,s,h.Block,{tag:"pen-stroke",rank:h.RankBounds.genNext(t),position:[e[0]-o,e[1]-o],size:[o*2,o*2]}),h.addComponent(t,s,h.Color,{});const{sessionId:i}=h.getResources(t);h.addComponent(t,s,h.Held,{sessionId:i});const a=n!==null,l=a?n:.5;h.addComponent(t,s,Nt,{points:e,pressures:[l],pointCount:1,thickness:r,originalLeft:e[0]-o,originalTop:e[1]-o,originalWidth:o*2,originalHeight:o*2,isComplete:!1,hasPressure:a});const c=hc.write(t);c.activeStroke=s,c.lastWorldPosition=e}function yE(t,e,n,r){const o=Nt.write(t,e),s=o.pointCount;if(!(s>=Ni)&&(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++,!h.Aabb.containsPoint(t,e,n))){h.Aabb.expandByPoint(t,e,n);const{value:i}=h.Aabb.read(t,e),a=h.Block.write(t,e);E.Vec2.set(a.position,E.Aabb.left(i),E.Aabb.top(i)),E.Vec2.set(a.size,E.Aabb.width(i),E.Aabb.height(i)),o.originalLeft=a.position[0],o.originalTop=a.position[1],o.originalWidth=a.size[0],o.originalHeight=a.size[1]}}function kE(t,e){const n=Nt.write(t,e);n.isComplete=!0,h.removeComponent(t,e,h.Held),Zp(t,e)}function wE(t,e){h.removeEntity(t,e)}function Zp(t,e){const n=Nt.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=zp(r,o,!1);for(;s.length-1>h.MAX_HIT_CAPSULES;)o*=2,s=zp(r,o,!1);if(s.length===1){const u=s[0];s.push({x:u.x,y:u.y})}h.hasComponent(t,e,h.HitGeometry)?h.HitGeometry.clear(t,e):h.addComponent(t,e,h.HitGeometry,{});const{originalLeft:i,originalTop:a,originalWidth:l,originalHeight:c}=n;for(let u=0;u<s.length-1;u++){const f=s[u],p=s[u+1],m=[(f.x-i)/l,(f.y-a)/c],g=[(p.x-i)/l,(p.y-a)/c];h.HitGeometry.addCapsuleUv(t,e,m,g,n.thickness)}}var vE=t=>Object.values(t).filter(e=>typeof e=="object"&&e!==null&&"_system"in e&&"phase"in e);function bE(){return{name:uE,components:Object.values(jp).filter(t=>t instanceof h.CanvasComponentDef),singletons:Object.values(Hp).filter(t=>t instanceof h.CanvasSingletonDef),blockDefs:[{tag:"pen-stroke",resizeMode:h.ResizeMode.Free,components:[Nt,h.Color],connectors:{enabled:!1}}],systems:vE(Wp),resources:{}}}const SE=["data-complete"],CE={preserveAspectRatio:"none"},xE=["d","fill"],_E={key:0,class:"highlight",preserveAspectRatio:"none"},EE=["d"],Up=ir(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=Pe(e.entityId,Nt),r=Pe(e.entityId,h.Block),o=Pe(e.entityId,h.Color),s=d.shallowRef(""),i=d.shallowRef("");function a(f,p){return(f+p)/2}function l(f,p,m){if(p<=4||f.length<3){const v=m/2;return`M ${v},0 a ${v},${v} 0 1 0 0.0001 0`}let g=f[0],y=f[1];const k=f[2];let w=`M${g[0].toFixed(2)},${g[1].toFixed(2)} Q${y[0].toFixed(2)},${y[1].toFixed(2)} ${a(y[0],k[0]).toFixed(2)},${a(y[1],k[1]).toFixed(2)} T`;for(let v=2;v<f.length-1;v++)g=f[v],y=f[v+1],w+=`${a(g[0],y[0]).toFixed(2)},${a(g[1],y[1]).toFixed(2)} `;return w+=`${y[0].toFixed(2)},${y[1].toFixed(2)} `,w+="Z",w}d.watch([n,r],([f,p])=>{if(!f||!p){s.value="",i.value="";return}if(!f.originalWidth||!f.originalHeight){s.value="",i.value="";return}const m=p.size[0]/f.originalWidth,g=p.size[1]/f.originalHeight,y=[];for(let w=0;w<f.pointCount;w++){const v=f.points[w*2],b=f.points[w*2+1],S=(v-f.originalLeft)*m,C=(b-f.originalTop)*g;f.hasPressure?y.push([S,C,f.pressures[w]]):y.push([S,C])}const k=uc(y,{last:f.isComplete,size:f.thickness,simulatePressure:!f.hasPressure});if(s.value=l(k,f.pointCount,f.thickness),f.isComplete){const w=y.length===1?f.thickness:1,v=uc(y,{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,p)=>{var m;return d.openBlock(),d.createElementBlock("div",{class:"wov-pen-stroke","data-complete":((m=d.unref(n))==null?void 0:m.isComplete)||void 0},[(d.openBlock(),d.createElementBlock("svg",CE,[d.createElementVNode("path",{d:s.value,fill:c.value},null,8,xE)])),u.value?(d.openBlock(),d.createElementBlock("svg",_E,[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,EE)])):d.createCommentVNode("",!0)],8,SE)}}}),[["__scopeId","data-v-9b41c649"]]);function Ee(){const t=d.inject(pt);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 ss={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 Fe(t){this.content=t}Fe.prototype={constructor:Fe,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 Fe(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 Fe(n)},addToStart:function(t,e){return new Fe([t,e].concat(this.remove(t).content))},addToEnd:function(t,e){var n=this.remove(t).content.slice();return n.push(t,e),new Fe(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 Fe(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=Fe.from(t),t.size?new Fe(t.content.concat(this.subtract(t).content)):this},append:function(t){return t=Fe.from(t),t.size?new Fe(this.subtract(t).content.concat(t.content)):this},subtract:function(t){var e=this;t=Fe.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}},Fe.from=function(t){if(t instanceof Fe)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new Fe(e)};function Kp(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=Kp(o.content,s.content,n+1);if(i!=null)return i}n+=o.nodeSize}}function Jp(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=Jp(i.content,a.content,n-1,r-1);if(c)return c}n-=l,r-=l}}class B{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 B(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 B(r,o)}cutByIndex(e,n){return e==n?B.empty:e==0&&n==this.content.length?this:new B(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 B(o,s)}addToStart(e){return new B([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new B(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 Kp(this,e,n)}findDiffEnd(e,n=this.size,r=e.size){return Jp(this,e,n,r)}findIndex(e){if(e==0)return Bi(0,e);if(e==this.size)return Bi(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?Bi(n+1,s):Bi(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 B.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new B(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return B.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 B(n||e,r)}static from(e){if(!e)return B.empty;if(e instanceof B)return e;if(Array.isArray(e))return this.fromArray(e);if(e.attrs)return new B([e],e.nodeSize);throw new RangeError("Can not convert "+e+" to a Fragment"+(e.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}}B.empty=new B([],0);const pc={index:0,offset:0};function Bi(t,e){return pc.index=t,pc.offset=e,pc}function Oi(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(!Oi(t[r],e[r]))return!1}else{for(let r in t)if(!(r in e)||!Oi(t[r],e[r]))return!1;for(let r in e)if(!(r in t))return!1}return!0}let ye=class cu{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&&Oi(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 cu.none;if(e instanceof cu)return[e];let n=e.slice();return n.sort((r,o)=>r.type.rank-o.type.rank),n}};ye.none=[];class Ii extends Error{}class L{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=Gp(this.content,e+this.openStart,n);return r&&new L(r,this.openStart,this.openEnd)}removeBetween(e,n){return new L(qp(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 L.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 L(B.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 L(e,r,o)}}L.empty=new L(B.empty,0,0);function qp(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(qp(s.content,e-o-1,n-o-1)))}function Gp(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=Gp(i.content,e-s-1,n,i);return a&&t.replaceChild(o,i.copy(a))}function TE(t,e,n){if(n.openStart>t.depth)throw new Ii("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new Ii("Inconsistent open depths");return Yp(t,e,n,0)}function Yp(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=Yp(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 pr(i,a.cut(0,t.parentOffset).append(n.content).append(a.cut(e.parentOffset)))}else{let{start:i,end:a}=ME(n,t);return pr(s,Qp(t,i,a,e,r))}else return pr(s,Pi(t,e,r))}function Xp(t,e){if(!e.type.compatibleContent(t.type))throw new Ii("Cannot join "+e.type.name+" onto "+t.type.name)}function mc(t,e,n){let r=t.node(n);return Xp(r,e.node(n)),r}function hr(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 is(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&&(hr(t.nodeAfter,r),s++));for(let a=s;a<i;a++)hr(o.child(a),r);e&&e.depth==n&&e.textOffset&&hr(e.nodeBefore,r)}function pr(t,e){return t.type.checkContent(e),t.copy(e)}function Qp(t,e,n,r,o){let s=t.depth>o&&mc(t,e,o+1),i=r.depth>o&&mc(n,r,o+1),a=[];return is(null,t,o,a),s&&i&&e.index(o)==n.index(o)?(Xp(s,i),hr(pr(s,Qp(t,e,n,r,o+1)),a)):(s&&hr(pr(s,Pi(t,e,o+1)),a),is(e,n,o,a),i&&hr(pr(i,Pi(n,r,o+1)),a)),is(r,null,o,a),new B(a)}function Pi(t,e,n){let r=[];if(is(null,t,n,r),t.depth>n){let o=mc(t,e,n+1);hr(pr(o,Pi(t,e,n+1)),r)}return is(e,null,n,r),new B(r)}function ME(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(B.from(o));return{start:o.resolveNoCache(t.openStart+n),end:o.resolveNoCache(o.content.size-t.openEnd-n)}}class as{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 ye.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 Ri(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 as(n,r,s)}static resolveCached(e,n){let r=em.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 em.set(e,r=new AE);let o=r.elts[r.i]=as.resolve(e,n);return r.i=(r.i+1)%NE,o}}class AE{constructor(){this.elts=[],this.i=0}}const NE=12,em=new WeakMap;class Ri{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 BE=Object.create(null);let an=class du{constructor(e,n,r,o=ye.none){this.type=e,this.attrs=n,this.marks=o,this.content=r||B.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&&Oi(this.attrs,n||e.defaultAttrs||BE)&&ye.sameSet(this.marks,r||ye.none)}copy(e=null){return e==this.content?this:new du(this.type,this.attrs,e,this.marks)}mark(e){return e==this.marks?this:new du(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 L.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 L(c,o.depth-i,s.depth-i)}replace(e,n,r){return TE(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 as.resolveCached(this,e)}resolveNoCache(e){return as.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()+")"),tm(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=B.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=ye.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(!ye.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=B.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,o,r);return s.type.checkAttrs(s.attrs),s}};an.prototype.text=void 0;class Di extends an{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):tm(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 Di(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new Di(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 tm(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class mr{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new OE(e,n);if(r.next==null)return mr.empty;let o=nm(r);r.next&&r.err("Unexpected trailing text");let s=VE($E(o));return LE(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 B.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 p=s(f,a.concat(u));if(p)return p}}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
+ `)}}mr.empty=new mr(!0);class OE{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 nm(t){let e=[];do e.push(IE(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function IE(t){let e=[];do e.push(PE(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function PE(t){let e=zE(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=RE(t,e);else break;return e}function rm(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function RE(t,e){let n=rm(t),r=n;return t.eat(",")&&(t.next!="}"?r=rm(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function DE(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 zE(t){if(t.eat("(")){let e=nm(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=DE(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 $E(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 om(t,e){return e-t}function sm(t,e){let n=[];return r(e),n.sort(om);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 VE(t){let e=Object.create(null);return n(sm(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]);sm(t,l).forEach(u=>{c||o.push([a,c=[]]),c.indexOf(u)==-1&&c.push(u)})})});let s=e[r.join(",")]=new mr(r.indexOf(t.length-1)>-1);for(let i=0;i<o.length;i++){let a=o[i][1].sort(om);s.next.push({type:o[i][0],next:e[a.join(",")]||n(a)})}return s}}function LE(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 im(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 am(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 lm(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 cm(t,e){let n=Object.create(null);if(e)for(let r in e)n[r]=new jE(t,r,e[r]);return n}let dm=class Zk{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=cm(e,r.attrs),this.defaultAttrs=im(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==mr.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:am(this.attrs,e)}create(e=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new an(this,this.computeAttrs(e),B.from(n),ye.setFrom(r))}createChecked(e=null,n,r){return n=B.from(n),this.checkContent(n),new an(this,this.computeAttrs(e),n,ye.setFrom(r))}createAndFill(e=null,n,r){if(e=this.computeAttrs(e),n=B.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(B.empty,!0);return s?new an(this,e,n.append(s),ye.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){lm(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:ye.none:e}static compile(e,n){let r=Object.create(null);e.forEach((s,i)=>r[s]=new Zk(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 FE(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 jE{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?FE(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class zi{constructor(e,n,r,o){this.name=e,this.rank=n,this.schema=r,this.spec=o,this.attrs=cm(e,o.attrs),this.excluded=null;let s=im(this.attrs);this.instance=s?new ye(this,s):null}create(e=null){return!e&&this.instance?this.instance:new ye(this,am(this.attrs,e))}static compile(e,n){let r=Object.create(null),o=0;return e.forEach((s,i)=>r[s]=new zi(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){lm(this.attrs,e,"mark",this.name)}excludes(e){return this.excluded.indexOf(e)>-1}}class um{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=Fe.from(e.nodes),n.marks=Fe.from(e.marks||{}),this.nodes=dm.compile(this.spec.nodes,this),this.marks=zi.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]=mr.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?fm(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==""?[]:fm(this,i.split(" "))}this.nodeFromJSON=o=>an.fromJSON(this,o),this.markFromJSON=o=>ye.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 dm){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 Di(r,r.defaultAttrs,e,ye.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 fm(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 HE(t){return t.tag!=null}function WE(t){return t.style!=null}class ln{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(o=>{if(HE(o))this.tags.push(o);else if(WE(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 gm(this,n,!1);return r.addAll(e,ye.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new gm(this,n,!0);return r.addAll(e,ye.none,n.from,n.to),L.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(KE(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=ym(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=ym(i)),i.node||i.ignore||i.mark||(i.node=o)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new ln(e,ln.schemaRules(e)))}}const hm={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},ZE={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},pm={ol:!0,ul:!0},ls=1,gc=2,cs=4;function mm(t,e,n){return e!=null?(e?ls:0)|(e==="full"?gc:0):t&&t.whitespace=="pre"?ls|gc:n&~cs}class $i{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=ye.none,this.match=s||(i&cs?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(B.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&ls)){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=B.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(B.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&&!hm.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class gm{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=mm(null,n.preserveWhitespace,0)|(r?cs:0);o?s=new $i(o.type,o.attrs,ye.none,!0,n.topMatch||o.type.contentMatch,i):r?s=new $i(null,null,ye.none,!0,null,i):s=new $i(e.schema.topNodeType,null,ye.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&gc?"full":this.localPreserveWS||(o.options&ls)>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;pm.hasOwnProperty(i)&&this.parser.normalizeLists&&UE(e);let l=this.options.ruleFromNode&&this.options.ruleFromNode(e)||(a=this.parser.matchTag(e,this,r));e:if(l?l.ignore:ZE.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(hm.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=ye.none;for(let a of o.concat(e.marks))(s.type?s.type.allowsMarkType(a.type):km(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=mm(e,s,i.options);i.options&cs&&i.content.length==0&&(a|=cs);let l=ye.none;return r=r.filter(c=>(i.type?i.type.allowsMarkType(c.type):km(c.type,e))?(l=c.addToSet(l),!1):!0),this.nodes.push(new $i(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|=ls)}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 UE(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&pm.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function KE(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function ym(t){let e={};for(let n in t)e[n]=t[n];return e}function km(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 gr{constructor(e,n){this.nodes=e,this.marks=n}serializeFragment(e,n={},r){r||(r=yc(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}=Vi(yc(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&&Vi(yc(r),o(e,n),null,e.attrs)}static renderSpec(e,n,r=null,o){return Vi(e,n,r,o)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new gr(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=wm(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return wm(e.marks)}}function wm(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function yc(t){return t.document||window.document}const vm=new WeakMap;function JE(t){let e=vm.get(t);return e===void 0&&vm.set(t,e=qE(t)),e}function qE(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 Vi(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=JE(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 p=f.indexOf(" ");p>0?l.setAttributeNS(f.slice(0,p),f.slice(p+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 p=e[f];if(p===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:m,contentDOM:g}=Vi(t,p,n,r);if(l.appendChild(m),g){if(a)throw new RangeError("Multiple content holes");a=g}}}return{dom:l,contentDOM:a}}const bm=65535,Sm=Math.pow(2,16);function GE(t,e){return t+e*Sm}function Cm(t){return t&bm}function YE(t){return(t-(t&bm))/Sm}const xm=1,_m=2,Li=4,Em=8;class kc{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&Em)>0}get deletedBefore(){return(this.delInfo&(xm|Li))>0}get deletedAfter(){return(this.delInfo&(_m|Li))>0}get deletedAcross(){return(this.delInfo&Li)>0}}class ct{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&ct.empty)return ct.empty}recover(e){let n=0,r=Cm(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+YE(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 p=c?e==l?-1:e==f?1:n:n,m=l+o+(p<0?0:u);if(r)return m;let g=e==(n<0?l:f)?null:GE(a/3,e-l),y=e==l?_m:e==f?xm:Li;return(n<0?e!=l:e!=f)&&(y|=Em),new kc(m,y,g)}o+=u-c}return r?e+o:new kc(e+o,0,null)}touches(e,n){let r=0,o=Cm(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 ct(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(e){return e==0?ct.empty:new ct(e<0?[0,-e,0]:[0,0,e])}}ct.empty=new ct([]);class ds{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 ds(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 ds;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 kc(e,o,null)}}const wc=Object.create(null);class Ke{getMap(){return ct.empty}merge(e){return null}static fromJSON(e,n){if(!n||!n.stepType)throw new RangeError("Invalid input for Step.fromJSON");let r=wc[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 wc)throw new RangeError("Duplicate use of step JSON ID "+e);return wc[e]=n,n.prototype.jsonID=e,n}}class Te{constructor(e,n){this.doc=e,this.failed=n}static ok(e){return new Te(e,null)}static fail(e){return new Te(null,e)}static fromReplace(e,n,r,o){try{return Te.ok(e.replace(n,r,o))}catch(s){if(s instanceof Ii)return Te.fail(s.message);throw s}}}function vc(t,e,n){let r=[];for(let o=0;o<t.childCount;o++){let s=t.child(o);s.content.size&&(s=s.copy(vc(s.content,e,s))),s.isInline&&(s=e(s,n,o)),r.push(s)}return B.fromArray(r)}class Bn extends Ke{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 L(vc(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 Te.fromReplace(e,this.from,this.to,s)}invert(){return new Bt(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 Bn(n.pos,r.pos,this.mark)}merge(e){return e instanceof Bn&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Bn(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 Bn(n.from,n.to,e.markFromJSON(n.mark))}}Ke.jsonID("addMark",Bn);class Bt extends Ke{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 L(vc(n.content,o=>o.mark(this.mark.removeFromSet(o.marks)),e),n.openStart,n.openEnd);return Te.fromReplace(e,this.from,this.to,r)}invert(){return new Bn(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 Bt(n.pos,r.pos,this.mark)}merge(e){return e instanceof Bt&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Bt(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 Bt(n.from,n.to,e.markFromJSON(n.mark))}}Ke.jsonID("removeMark",Bt);class On extends Ke{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return Te.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return Te.fromReplace(e,this.pos,this.pos+1,new L(B.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 On(this.pos,n.marks[o]);return new On(this.pos,this.mark)}}return new yr(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new On(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 On(n.pos,e.markFromJSON(n.mark))}}Ke.jsonID("addNodeMark",On);class yr extends Ke{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return Te.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.removeFromSet(n.marks));return Te.fromReplace(e,this.pos,this.pos+1,new L(B.from(r),0,n.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);return!n||!this.mark.isInSet(n.marks)?this:new On(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new yr(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 yr(n.pos,e.markFromJSON(n.mark))}}Ke.jsonID("removeNodeMark",yr);class Re extends Ke{constructor(e,n,r,o=!1){super(),this.from=e,this.to=n,this.slice=r,this.structure=o}apply(e){return this.structure&&bc(e,this.from,this.to)?Te.fail("Structure replace would overwrite content"):Te.fromReplace(e,this.from,this.to,this.slice)}getMap(){return new ct([this.from,this.to-this.from,this.slice.size])}invert(e){return new Re(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 Re(n.pos,Math.max(n.pos,r.pos),this.slice,this.structure)}merge(e){if(!(e instanceof Re)||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?L.empty:new L(this.slice.content.append(e.slice.content),this.slice.openStart,e.slice.openEnd);return new Re(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?L.empty:new L(e.slice.content.append(this.slice.content),e.slice.openStart,this.slice.openEnd);return new Re(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 Re(n.from,n.to,L.fromJSON(e,n.slice),!!n.structure)}}Ke.jsonID("replace",Re);class De extends Ke{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&&(bc(e,this.from,this.gapFrom)||bc(e,this.gapTo,this.to)))return Te.fail("Structure gap-replace would overwrite content");let n=e.slice(this.gapFrom,this.gapTo);if(n.openStart||n.openEnd)return Te.fail("Gap is not a flat range");let r=this.slice.insertAt(this.insert,n.content);return r?Te.fromReplace(e,this.from,this.to,r):Te.fail("Content does not fit in gap")}getMap(){return new ct([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 De(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 De(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 De(n.from,n.to,n.gapFrom,n.gapTo,L.fromJSON(e,n.slice),n.insert,!!n.structure)}}Ke.jsonID("replaceAround",De);function bc(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 XE(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 p=Math.max(c,e),m=Math.min(c+l.nodeSize,n),g=r.addToSet(f);for(let y=0;y<f.length;y++)f[y].isInSet(g)||(i&&i.to==p&&i.mark.eq(f[y])?i.to=m:o.push(i=new Bt(p,m,f[y])));a&&a.to==p?a.to=m:s.push(a=new Bn(p,m,r))}}),o.forEach(l=>t.step(l)),s.forEach(l=>t.step(l))}function QE(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 zi){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],p;for(let m=0;m<o.length;m++){let g=o[m];g.step==s-1&&f.eq(o[m].style)&&(p=g)}p?(p.to=c,p.step=s):o.push({style:f,from:Math.max(a,e),to:c,step:s})}}}),o.forEach(i=>t.step(new Bt(i.from,i.to,i.style)))}function Sc(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 Re(a,u,L.empty));else{r=f;for(let p=0;p<c.marks.length;p++)n.allowsMarkType(c.marks[p].type)||t.step(new Bt(a,u,c.marks[p]));if(o&&c.isText&&n.whitespace!="pre"){let p,m=/\r?\n|\r/g,g;for(;p=m.exec(c.text);)g||(g=new L(B.from(n.schema.text(" ",n.allowedMarks(c.marks))),0,0)),i.push(new Re(a+p.index,a+p.index+p[0].length,g))}}a=u}if(!r.validEnd){let l=r.fillBefore(B.empty,!0);t.replace(a,a,new L(l,0,0))}for(let l=i.length-1;l>=0;l--)t.step(i[l])}function eT(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function io(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||!eT(i,a,l))break;a&&(o=1),l<i.childCount&&(s=1)}return null}function tT(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=B.empty,f=0;for(let g=s,y=!1;g>n;g--)y||r.index(g)>0?(y=!0,u=B.from(r.node(g).copy(u)),f++):l--;let p=B.empty,m=0;for(let g=s,y=!1;g>n;g--)y||o.after(g+1)<o.end(g)?(y=!0,p=B.from(o.node(g).copy(p)),m++):c++;t.step(new De(l,c,i,a,new L(u.append(p),f,m),u.size-f,!0))}function Tm(t,e,n=null,r=t){let o=nT(t,e),s=o&&rT(r,e);return s?o.map(Mm).concat({type:e,attrs:n}).concat(s.map(Mm)):null}function Mm(t){return{type:t,attrs:null}}function nT(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 rT(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 oT(t,e,n){let r=B.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=B.from(n[i].type.create(n[i].attrs,r))}let o=e.start,s=e.end;t.step(new De(o,s,o,s,new L(r,0,0),n.length,!0))}function sT(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)&&iT(t.doc,t.mapping.slice(s).map(a),r)){let c=null;if(r.schema.linebreakReplacement){let m=r.whitespace=="pre",g=!!r.contentMatch.matchType(r.schema.linebreakReplacement);m&&!g?c=!1:!m&&g&&(c=!0)}c===!1&&Nm(t,i,a,s),Sc(t,t.mapping.slice(s).map(a,1),r,void 0,c===null);let u=t.mapping.slice(s),f=u.map(a,1),p=u.map(a+i.nodeSize,1);return t.step(new De(f,p,f+1,p-1,new L(B.from(r.create(l,null,i.marks)),0,0),1,!0)),c===!0&&Am(t,i,a,s),!1}})}function Am(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 Nm(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 iT(t,e,n){let r=t.resolve(e),o=r.index();return r.parent.canReplaceWith(o,o+1,n)}function aT(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 De(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new L(B.from(i),0,0),1,!0))}function cn(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),p=o.index(c);if(f.type.spec.isolating)return!1;let m=f.content.cutByIndex(p,f.childCount),g=r&&r[u+1];g&&(m=m.replaceChild(0,g.type.create(g.attrs)));let y=r&&r[u]||f;if(!f.canReplace(p+1,f.childCount)||!y.type.validContent(m))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 lT(t,e,n=1,r){let o=t.doc.resolve(e),s=B.empty,i=B.empty;for(let a=o.depth,l=o.depth-n,c=n-1;a>l;a--,c--){s=B.from(o.node(a).copy(s));let u=r&&r[c];i=B.from(u?u.type.create(u.attrs,i):o.node(a).copy(i))}t.step(new Re(e,e,new L(s.append(i),n,n),!0))}function kr(t,e){let n=t.resolve(e),r=n.index();return Bm(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function cT(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 Bm(t,e){return!!(t&&e&&!t.isLeaf&&cT(t,e))}function Fi(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&&Bm(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 dT(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);Nm(t,u.node(),u.before(),a)}i.inlineContent&&Sc(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 Re(c,l.map(e+n,-1),L.empty,!0)),r===!0){let u=t.doc.resolve(c);Am(t,u.node(),u.before(),t.steps.length)}return t}function uT(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 Om(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 ji(t,e,n=e,r=L.empty){if(e==n&&!r.size)return null;let o=t.resolve(e),s=t.resolve(n);return Im(o,s,r)?new Re(e,n,r):new fT(o,s,r).fit()}function Im(t,e,n){return!n.openStart&&!n.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),n.content)}class fT{constructor(e,n,r){this.$from=e,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=B.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=B.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 L(s,i,a);return e>-1?new De(r.pos,e,this.$to.pos,this.$to.end(),l,n):l.size||r.pos!=this.$to.pos?new Re(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=Cc(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(B.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=Cc(e,n);return!o.childCount||o.firstChild.isLeaf?!1:(this.unplaced=new L(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=Cc(e,n);if(o.childCount<=1&&n>0){let s=e.size-n<=n+o.size;this.unplaced=new L(us(e,n-1,1),n-1,s?n-1:r)}else this.unplaced=new L(us(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 y=0;y<s.length;y++)this.openFrontierNode(s[y]);let i=this.unplaced,a=r?r.content:i.content,l=i.openStart-e,c=0,u=[],{match:f,type:p}=this.frontier[n];if(o){for(let y=0;y<o.childCount;y++)u.push(o.child(y));f=f.matchFragment(o)}let m=a.size+e-(i.content.size-i.openEnd);for(;c<a.childCount;){let y=a.child(c),k=f.matchType(y.type);if(!k)break;c++,(c>1||l==0||y.content.size)&&(f=k,u.push(Pm(y.mark(p.allowedMarks(y.marks)),c==1?l:0,c==a.childCount?m:-1)))}let g=c==a.childCount;g||(m=-1),this.placed=fs(this.placed,n,B.from(u)),this.frontier[n].match=f,g&&m<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let y=0,k=a;y<m;y++){let w=k.lastChild;this.frontier.push({type:w.type,match:w.contentMatchAt(w.childCount)}),k=w.content}this.unplaced=g?e==0?L.empty:new L(us(i.content,e-1,1),e-1,m<0?i.openEnd:e-1):new L(us(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||!xc(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=xc(e,n,o,r,s);if(i){for(let a=n-1;a>=0;a--){let{match:l,type:c}=this.frontier[a],u=xc(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=fs(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=fs(this.placed,this.depth,B.from(e.create(n,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(B.empty,!0);n.childCount&&(this.placed=fs(this.placed,this.frontier.length,n))}}function us(t,e,n){return e==0?t.cutByIndex(n,t.childCount):t.replaceChild(0,t.firstChild.copy(us(t.firstChild.content,e-1,n)))}function fs(t,e,n){return e==0?t.append(n):t.replaceChild(t.childCount-1,t.lastChild.copy(fs(t.lastChild.content,e-1,n)))}function Cc(t,e){for(let n=0;n<e;n++)t=t.firstChild.content;return t}function Pm(t,e,n){if(e<=0)return t;let r=t.content;return e>1&&(r=r.replaceChild(0,Pm(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(B.empty,!0)))),t.copy(r)}function xc(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&&!hT(n,s.content,i)?a:null}function hT(t,e,n){for(let r=n;r<e.childCount;r++)if(!t.allowsMarks(e.child(r).marks))return!0;return!1}function pT(t){return t.spec.defining||t.spec.definingForContent}function mT(t,e,n,r){if(!r.size)return t.deleteRange(e,n);let o=t.doc.resolve(e),s=t.doc.resolve(n);if(Im(o,s,r))return t.step(new Re(e,n,r));let i=Dm(o,s);i[i.length-1]==0&&i.pop();let a=-(o.depth+1);i.unshift(a);for(let p=o.depth,m=o.pos-1;p>0;p--,m--){let g=o.node(p).type.spec;if(g.defining||g.definingAsContext||g.isolating)break;i.indexOf(p)>-1?a=p:o.before(p)==m&&i.splice(1,0,-p)}let l=i.indexOf(a),c=[],u=r.openStart;for(let p=r.content,m=0;;m++){let g=p.firstChild;if(c.push(g),m==r.openStart)break;p=g.content}for(let p=u-1;p>=0;p--){let m=c[p],g=pT(m.type);if(g&&!m.sameMarkup(o.node(Math.abs(a)-1)))u=p;else if(g||!m.type.isTextblock)break}for(let p=r.openStart;p>=0;p--){let m=(p+u+1)%(r.openStart+1),g=c[m];if(g)for(let y=0;y<i.length;y++){let k=i[(y+l)%i.length],w=!0;k<0&&(w=!1,k=-k);let v=o.node(k-1),b=o.index(k-1);if(v.canReplaceWith(b,b,g.type,g.marks))return t.replace(o.before(k),w?s.after(k):n,new L(Rm(r.content,0,r.openStart,m),m,r.openEnd))}}let f=t.steps.length;for(let p=i.length-1;p>=0&&(t.replace(e,n,r),!(t.steps.length>f));p--){let m=i[p];m<0||(e=o.before(m),n=s.after(m))}}function Rm(t,e,n,r,o){if(e<n){let s=t.firstChild;t=t.replaceChild(0,s.copy(Rm(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(B.empty,!0))}return t}function gT(t,e,n,r){if(!r.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let o=uT(t.doc,e,r.type);o!=null&&(e=n=o)}t.replaceRange(e,n,new L(B.from(r),0,0))}function yT(t,e,n){let r=t.doc.resolve(e),o=t.doc.resolve(n),s=Dm(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 Dm(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 ao extends Ke{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 Te.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 Te.fromReplace(e,this.pos,this.pos+1,new L(B.from(o),0,n.isLeaf?0:1))}getMap(){return ct.empty}invert(e){return new ao(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 ao(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 ao(n.pos,n.attr,n.value)}}Ke.jsonID("attr",ao);class hs extends Ke{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 Te.ok(r)}getMap(){return ct.empty}invert(e){return new hs(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 hs(n.attr,n.value)}}Ke.jsonID("docAttr",hs);let lo=class extends Error{};lo=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n},lo.prototype=Object.create(Error.prototype),lo.prototype.constructor=lo,lo.prototype.name="TransformError";class zm{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new ds}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let n=this.maybeStep(e);if(n.failed)throw new lo(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=L.empty){let o=ji(this.doc,e,n,r);return o&&this.step(o),this}replaceWith(e,n,r){return this.replace(e,n,new L(B.from(r),0,0))}delete(e,n){return this.replace(e,n,L.empty)}insert(e,n){return this.replaceWith(e,e,n)}replaceRange(e,n,r){return mT(this,e,n,r),this}replaceRangeWith(e,n,r){return gT(this,e,n,r),this}deleteRange(e,n){return yT(this,e,n),this}lift(e,n){return tT(this,e,n),this}join(e,n=1){return dT(this,e,n),this}wrap(e,n){return oT(this,e,n),this}setBlockType(e,n=e,r,o=null){return sT(this,e,n,r,o),this}setNodeMarkup(e,n,r=null,o){return aT(this,e,n,r,o),this}setNodeAttribute(e,n,r){return this.step(new ao(e,n,r)),this}setDocAttribute(e,n){return this.step(new hs(e,n)),this}addNodeMark(e,n){return this.step(new On(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 ye)n.isInSet(r.marks)&&this.step(new yr(e,n));else{let o=r.marks,s,i=[];for(;s=n.isInSet(o);)i.push(new yr(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 lT(this,e,n,r),this}addMark(e,n,r){return XE(this,e,n,r),this}removeMark(e,n,r){return QE(this,e,n,r),this}clearIncompatible(e,n,r){return Sc(this,e,n,r),this}}const _c=Object.create(null);class ie{constructor(e,n,r){this.$anchor=e,this.$head=n,this.ranges=r||[new kT(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=L.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?L.empty:n),a==0&&Lm(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),Lm(e,r,n.isInline?-1:1))}}static findFrom(e,n,r=!1){let o=e.parent.inlineContent?new re(e):co(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?co(e.node(0),e.node(s),e.before(s+1),e.index(s),n,r):co(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 dt(e.node(0))}static atStart(e){return co(e,e,0,0,1)||new dt(e)}static atEnd(e){return co(e,e,e.content.size,e.childCount,-1)||new dt(e)}static fromJSON(e,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=_c[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 _c)throw new RangeError("Duplicate use of selection JSON ID "+e);return _c[e]=n,n.prototype.jsonID=e,n}getBookmark(){return re.between(this.$anchor,this.$head).getBookmark()}}ie.prototype.visible=!0;class kT{constructor(e,n){this.$from=e,this.$to=n}}let $m=!1;function Vm(t){!$m&&!t.parent.inlineContent&&($m=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}class re extends ie{constructor(e,n=e){Vm(e),Vm(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 ie.near(r);let o=e.resolve(n.map(this.anchor));return new re(o.parent.inlineContent?o:r,r)}replace(e,n=L.empty){if(super.replace(e,n),n==L.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof re&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Hi(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 re(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=ie.findFrom(n,r,!0)||ie.findFrom(n,-r,!0);if(s)n=s.$head;else return ie.near(n,r)}return e.parent.inlineContent||(o==0?e=n:(e=(ie.findFrom(e,-r,!0)||ie.findFrom(e,r,!0)).$anchor,e.pos<n.pos!=o<0&&(e=n))),new re(e,n)}}ie.jsonID("text",re);class Hi{constructor(e,n){this.anchor=e,this.head=n}map(e){return new Hi(e.map(this.anchor),e.map(this.head))}resolve(e){return re.between(e.resolve(this.anchor),e.resolve(this.head))}}class G extends ie{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?ie.near(s):new G(s)}content(){return new L(B.from(this.node),0,0)}eq(e){return e instanceof G&&e.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new Ec(this.anchor)}static fromJSON(e,n){if(typeof n.anchor!="number")throw new RangeError("Invalid input for NodeSelection.fromJSON");return new G(e.resolve(n.anchor))}static create(e,n){return new G(e.resolve(n))}static isSelectable(e){return!e.isText&&e.type.spec.selectable!==!1}}G.prototype.visible=!1,ie.jsonID("node",G);class Ec{constructor(e){this.anchor=e}map(e){let{deleted:n,pos:r}=e.mapResult(this.anchor);return n?new Hi(r,r):new Ec(r)}resolve(e){let n=e.resolve(this.anchor),r=n.nodeAfter;return r&&G.isSelectable(r)?new G(n):ie.near(n)}}class dt extends ie{constructor(e){super(e.resolve(0),e.resolve(e.content.size))}replace(e,n=L.empty){if(n==L.empty){e.delete(0,e.doc.content.size);let r=ie.atStart(e.doc);r.eq(e.selection)||e.setSelection(r)}else super.replace(e,n)}toJSON(){return{type:"all"}}static fromJSON(e){return new dt(e)}map(e){return new dt(e)}eq(e){return e instanceof dt}getBookmark(){return wT}}ie.jsonID("all",dt);const wT={map(){return this},resolve(t){return new dt(t)}};function co(t,e,n,r,o,s=!1){if(e.inlineContent)return re.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&&G.isSelectable(a))return G.create(t,n-(o<0?a.nodeSize:0))}else{let l=co(t,a,n+o,o<0?a.childCount:0,o,s);if(l)return l}n+=a.nodeSize*o}return null}function Lm(t,e,n){let r=t.steps.length-1;if(r<e)return;let o=t.steps[r];if(!(o instanceof Re||o instanceof De))return;let s=t.mapping.maps[r],i;s.forEach((a,l,c,u)=>{i==null&&(i=u)}),t.setSelection(ie.near(t.doc.resolve(i),n))}const Fm=1,Wi=2,jm=4;class vT extends zm{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|Fm)&~Wi,this.storedMarks=null,this}get selectionSet(){return(this.updated&Fm)>0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Wi,this}ensureMarks(e){return ye.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&Wi)>0}addStep(e,n){super.addStep(e,n),this.updated=this.updated&~Wi,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)||ye.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(ie.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|=jm,this}get scrolledIntoView(){return(this.updated&jm)>0}}function Hm(t,e){return!e||!t?t:t.bind(e)}class ps{constructor(e,n,r){this.name=e,this.init=Hm(n.init,r),this.apply=Hm(n.apply,r)}}const bT=[new ps("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new ps("selection",{init(t,e){return t.selection||ie.atStart(e.doc)},apply(t){return t.selection}}),new ps("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,n,r){return r.selection.$cursor?t.storedMarks:null}}),new ps("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})];class Tc{constructor(e,n){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=bT.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 ps(r.key,r.spec.state,r))})}}class uo{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 uo(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 vT(this)}static create(e){let n=new Tc(e.doc?e.doc.type.schema:e.schema,e.plugins),r=new uo(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 Tc(this.schema,e.plugins),r=n.fields,o=new uo(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 Tc(e.schema,e.plugins),s=new uo(o);return o.fields.forEach(i=>{if(i.name=="doc")s.doc=an.fromJSON(e.schema,n.doc);else if(i.name=="selection")s.selection=ie.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 Wm(t,e,n){for(let r in t){let o=t[r];o instanceof Function?o=o.bind(e):r=="handleDOMEvents"&&(o=Wm(o,e,{})),n[r]=o}return n}class Oe{constructor(e){this.spec=e,this.props={},e.props&&Wm(e.props,this,this.props),this.key=e.key?e.key.key:Zm("plugin")}getState(e){return e[this.key]}}const Mc=Object.create(null);function Zm(t){return t in Mc?t+"$"+ ++Mc[t]:(Mc[t]=0,t+"$")}class Qe{constructor(e="key"){this.key=Zm(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const Ac=(t,e)=>t.selection.empty?!1:(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function Um(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0)?null:n}const Km=(t,e,n)=>{let r=Um(t,n);if(!r)return!1;let o=Nc(r);if(!o){let i=r.blockRange(),a=i&&io(i);return a==null?!1:(e&&e(t.tr.lift(i,a).scrollIntoView()),!0)}let s=o.nodeBefore;if(ng(t,o,e,-1))return!0;if(r.parent.content.size==0&&(fo(s,"end")||G.isSelectable(s)))for(let i=r.depth;;i--){let a=ji(t.doc,r.before(i),r.after(i),L.empty);if(a&&a.slice.size<a.to-a.from){if(e){let l=t.tr.step(a);l.setSelection(fo(s,"end")?ie.findFrom(l.doc.resolve(l.mapping.map(o.pos,-1)),-1):G.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},ST=(t,e,n)=>{let r=Um(t,n);if(!r)return!1;let o=Nc(r);return o?Jm(t,o,e):!1},CT=(t,e,n)=>{let r=Gm(t,n);if(!r)return!1;let o=Bc(r);return o?Jm(t,o,e):!1};function Jm(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=ji(t.doc,s,l,L.empty);if(!c||c.from!=s||c instanceof Re&&c.slice.size>=l-s)return!1;if(n){let u=t.tr.step(c);u.setSelection(re.create(u.doc,s)),n(u.scrollIntoView())}return!0}function fo(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 qm=(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=Nc(r)}let i=s&&s.nodeBefore;return!i||!G.isSelectable(i)?!1:(e&&e(t.tr.setSelection(G.create(t.doc,s.pos-i.nodeSize)).scrollIntoView()),!0)};function Nc(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 Gm(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("forward",t):n.parentOffset<n.parent.content.size)?null:n}const Ym=(t,e,n)=>{let r=Gm(t,n);if(!r)return!1;let o=Bc(r);if(!o)return!1;let s=o.nodeAfter;if(ng(t,o,e,1))return!0;if(r.parent.content.size==0&&(fo(s,"start")||G.isSelectable(s))){let i=ji(t.doc,r.before(),r.after(),L.empty);if(i&&i.slice.size<i.to-i.from){if(e){let a=t.tr.step(i);a.setSelection(fo(s,"start")?ie.findFrom(a.doc.resolve(a.mapping.map(o.pos)),1):G.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},Xm=(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=Bc(r)}let i=s&&s.nodeAfter;return!i||!G.isSelectable(i)?!1:(e&&e(t.tr.setSelection(G.create(t.doc,s.pos)).scrollIntoView()),!0)};function Bc(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 xT=(t,e)=>{let n=t.selection,r=n instanceof G,o;if(r){if(n.node.isTextblock||!kr(t.doc,n.from))return!1;o=n.from}else if(o=Fi(t.doc,n.from,-1),o==null)return!1;if(e){let s=t.tr.join(o);r&&s.setSelection(G.create(s.doc,o-t.doc.resolve(o).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},_T=(t,e)=>{let n=t.selection,r;if(n instanceof G){if(n.node.isTextblock||!kr(t.doc,n.to))return!1;r=n.to}else if(r=Fi(t.doc,n.to,1),r==null)return!1;return e&&e(t.tr.join(r).scrollIntoView()),!0},ET=(t,e)=>{let{$from:n,$to:r}=t.selection,o=n.blockRange(r),s=o&&io(o);return s==null?!1:(e&&e(t.tr.lift(o,s).scrollIntoView()),!0)},Qm=(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 Oc(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 TT=(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=Oc(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(ie.near(l.doc.resolve(a),1)),e(l.scrollIntoView())}return!0},eg=(t,e)=>{let n=t.selection,{$from:r,$to:o}=n;if(n instanceof dt||r.parent.inlineContent||o.parent.inlineContent)return!1;let s=Oc(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(re.create(a.doc,i+1)),e(a.scrollIntoView())}return!0},tg=(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(cn(t.doc,s))return e&&e(t.tr.split(s).scrollIntoView()),!0}let r=n.blockRange(),o=r&&io(r);return o==null?!1:(e&&e(t.tr.lift(r,o).scrollIntoView()),!0)};function MT(t){return(e,n)=>{let{$from:r,$to:o}=e.selection;if(e.selection instanceof G&&e.selection.node.isBlock)return!r.parentOffset||!cn(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 m=r.depth;;m--)if(r.node(m).isBlock){l=r.end(m)==r.pos+(r.depth-m),c=r.start(m)==r.pos-(r.depth-m),a=Oc(r.node(m-1).contentMatchAt(r.indexAfter(m-1))),s.unshift(l&&a?{type:a}:null),i=m;break}else{if(m==1)return!1;s.unshift(null)}let u=e.tr;(e.selection instanceof re||e.selection instanceof dt)&&u.deleteSelection();let f=u.mapping.map(r.pos),p=cn(u.doc,f,s.length,s);if(p||(s[0]=a?{type:a}:null,p=cn(u.doc,f,s.length,s)),!p)return!1;if(u.split(f,s.length,s),!l&&c&&r.node(i).type!=a){let m=u.mapping.map(r.before(i)),g=u.doc.resolve(m);a&&r.node(i-1).canReplaceWith(g.index(),g.index()+1,a)&&u.setNodeMarkup(u.mapping.map(r.before(i)),a)}return n&&n(u.scrollIntoView()),!0}}const AT=MT(),NT=(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(G.create(t.doc,o))),!0)};function BT(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||kr(t.doc,e.pos))?!1:(n&&n(t.tr.join(e.pos).scrollIntoView()),!0)}function ng(t,e,n,r){let o=e.nodeBefore,s=e.nodeAfter,i,a,l=o.type.spec.isolating||s.type.spec.isolating;if(!l&&BT(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 m=e.pos+s.nodeSize,g=B.empty;for(let w=i.length-1;w>=0;w--)g=B.from(i[w].create(null,g));g=B.from(o.copy(g));let y=t.tr.step(new De(e.pos-1,m,e.pos,m,new L(g,1,0),i.length,!0)),k=y.doc.resolve(m+2*i.length);k.nodeAfter&&k.nodeAfter.type==o.type&&kr(y.doc,k.pos)&&y.join(k.pos),n(y.scrollIntoView())}return!0}let u=s.type.spec.isolating||r>0&&l?null:ie.findFrom(e,1),f=u&&u.$from.blockRange(u.$to),p=f&&io(f);if(p!=null&&p>=e.depth)return n&&n(t.tr.lift(f,p).scrollIntoView()),!0;if(c&&fo(s,"start",!0)&&fo(o,"end")){let m=o,g=[];for(;g.push(m),!m.isTextblock;)m=m.lastChild;let y=s,k=1;for(;!y.isTextblock;y=y.firstChild)k++;if(m.canReplace(m.childCount,m.childCount,y.content)){if(n){let w=B.empty;for(let b=g.length-1;b>=0;b--)w=B.from(g[b].copy(w));let v=t.tr.step(new De(e.pos-g.length,e.pos+s.nodeSize,e.pos+k,e.pos+s.nodeSize-k,new L(w,g.length,0),0,!0));n(v.scrollIntoView())}return!0}}return!1}function rg(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(re.create(e.doc,t<0?o.start(s):o.end(s)))),!0):!1}}const OT=rg(-1),IT=rg(1);function PT(t,e=null){return function(n,r){let{$from:o,$to:s}=n.selection,i=o.blockRange(s),a=i&&Tm(i,t,e);return a?(r&&r(n.tr.wrap(i,a).scrollIntoView()),!0):!1}}function og(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 Ic(...t){return function(e,n,r){for(let o=0;o<t.length;o++)if(t[o](e,n,r))return!0;return!1}}Ic(Ac,Km,qm),Ic(Ac,Ym,Xm),Ic(Qm,eg,tg,AT),typeof navigator<"u"?/Mac|iP(hone|[oa]d)/.test(navigator.platform):typeof os<"u"&&os.platform&&os.platform()=="darwin";function RT(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 DT(a,i,t,e)?(r&&r(a.scrollIntoView()),!0):!1}}function DT(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 Ri(l,l,e.depth),e.endIndex<e.parent.childCount&&(e=new Ri(e.$from,i.resolve(e.$to.end(e.depth)),e.depth)),o=!0}let a=Tm(s,n,r,e);return a?(t&&zT(t,e,a,o,n),!0):!1}function zT(t,e,n,r,o){let s=B.empty;for(let u=n.length-1;u>=0;u--)s=B.from(n[u].type.create(n[u].attrs,s));t.step(new De(e.start-(r?2:0),e.end,e.start,e.end,new L(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,p=!0;u<f;u++,p=!1)!p&&cn(t.doc,l,a)&&(t.split(l,a),l+=2*a),l+=c.child(u).nodeSize;return t}function $T(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?VT(e,n,t,s):LT(e,n,s):!0:!1}}function VT(t,e,n,r){let o=t.tr,s=r.end,i=r.$to.end(r.depth);s<i&&(o.step(new De(s-1,i,s,i,new L(B.from(n.create(null,r.parent.copy())),1,0),1,!0)),r=new Ri(o.doc.resolve(r.$from.pos),o.doc.resolve(i),r.depth));const a=io(r);if(a==null)return!1;o.lift(r,a);let l=o.doc.resolve(o.mapping.map(s,-1)-1);return kr(o.doc,l.pos)&&l.nodeBefore.type==l.nodeAfter.type&&o.join(l.pos),e(o.scrollIntoView()),!0}function LT(t,e,n){let r=t.tr,o=n.parent;for(let m=n.end,g=n.endIndex-1,y=n.startIndex;g>y;g--)m-=o.child(g).nodeSize,r.delete(m-1,m+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?B.empty:B.from(o))))return!1;let f=s.pos,p=f+i.nodeSize;return r.step(new De(f-(a?1:0),p+(l?1:0),f+1,p-1,new L((a?B.empty:B.from(o.copy(B.empty))).append(l?B.empty:B.from(o.copy(B.empty))),a?0:1,l?0:1),a?0:1)),e(r.scrollIntoView()),!0}function FT(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=B.from(c?t.create():null),f=new L(B.from(t.create(null,B.from(a.type.create(null,u)))),c?3:1,0),p=s.start,m=s.end;n(e.tr.step(new De(p-(c?3:1),m,p,m,f,1,!0)).scrollIntoView())}return!0}}const je=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},ho=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e};let Pc=null;const dn=function(t,e,n){let r=Pc||(Pc=document.createRange());return r.setEnd(t,n??t.nodeValue.length),r.setStart(t,e||0),r},jT=function(){Pc=null},wr=function(t,e,n,r){return n&&(sg(t,e,n,r,-1)||sg(t,e,n,r,1))},HT=/^(img|br|input|textarea|hr)$/i;function sg(t,e,n,r,o){for(var s;;){if(t==n&&e==r)return!0;if(e==(o<0?0:gt(t))){let i=t.parentNode;if(!i||i.nodeType!=1||ms(t)||HT.test(t.nodeName)||t.contentEditable=="false")return!1;e=je(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?gt(t):0}else return!1}}function gt(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function WT(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=gt(t)}else if(t.parentNode&&!ms(t))e=je(t),t=t.parentNode;else return null}}function ZT(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&&!ms(t))e=je(t)+1,t=t.parentNode;else return null}}function UT(t,e,n){for(let r=e==0,o=e==gt(t);r||o;){if(t==n)return!0;let s=je(t);if(t=t.parentNode,!t)return!1;r=r&&s==0,o=o&&s==gt(t)}}function ms(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 Zi=function(t){return t.focusNode&&wr(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset)};function vr(t,e){let n=document.createEvent("Event");return n.initEvent("keydown",!0,!0),n.keyCode=t,n.key=n.code=e,n}function KT(t){let e=t.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function JT(t,e,n){if(t.caretPositionFromPoint)try{let r=t.caretPositionFromPoint(e,n);if(r)return{node:r.offsetNode,offset:Math.min(gt(r.offsetNode),r.offset)}}catch{}if(t.caretRangeFromPoint){let r=t.caretRangeFromPoint(e,n);if(r)return{node:r.startContainer,offset:Math.min(gt(r.startContainer),r.startOffset)}}}const Ut=typeof navigator<"u"?navigator:null,ig=typeof document<"u"?document:null,In=Ut&&Ut.userAgent||"",Rc=/Edge\/(\d+)/.exec(In),ag=/MSIE \d/.exec(In),Dc=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(In),ot=!!(ag||Dc||Rc),Pn=ag?document.documentMode:Dc?+Dc[1]:Rc?+Rc[1]:0,yt=!ot&&/gecko\/(\d+)/i.test(In);yt&&+(/Firefox\/(\d+)/.exec(In)||[0,0])[1];const zc=!ot&&/Chrome\/(\d+)/.exec(In),He=!!zc,lg=zc?+zc[1]:0,Je=!ot&&!!Ut&&/Apple Computer/.test(Ut.vendor),po=Je&&(/Mobile\/\w+/.test(In)||!!Ut&&Ut.maxTouchPoints>2),kt=po||(Ut?/Mac/.test(Ut.platform):!1),cg=Ut?/Win/.test(Ut.platform):!1,un=/Android \d/.test(In),gs=!!ig&&"webkitFontSmoothing"in ig.documentElement.style,qT=gs?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function GT(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 fn(t,e){return typeof t=="number"?t:t[e]}function YT(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 dg(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=ho(i);continue}let a=i,l=a==s.body,c=l?GT(s):YT(a),u=0,f=0;if(e.top<c.top+fn(r,"top")?f=-(c.top-e.top+fn(o,"top")):e.bottom>c.bottom-fn(r,"bottom")&&(f=e.bottom-e.top>c.bottom-c.top?e.top+fn(o,"top")-c.top:e.bottom-c.bottom+fn(o,"bottom")),e.left<c.left+fn(r,"left")?u=-(c.left-e.left+fn(o,"left")):e.right>c.right-fn(r,"right")&&(u=e.right-c.right+fn(o,"right")),u||f)if(l)s.defaultView.scrollBy(u,f);else{let m=a.scrollLeft,g=a.scrollTop;f&&(a.scrollTop+=f),u&&(a.scrollLeft+=u);let y=a.scrollLeft-m,k=a.scrollTop-g;e={left:e.left-y,top:e.top-k,right:e.right-y,bottom:e.bottom-k}}let p=l?"fixed":getComputedStyle(i).position;if(/^(fixed|sticky)$/.test(p))break;i=p=="absolute"?i.offsetParent:ho(i)}}function XT(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:ug(t.dom)}}function ug(t){let e=[],n=t.ownerDocument;for(let r=t;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),t!=n);r=ho(r));return e}function QT({refDOM:t,refTop:e,stack:n}){let r=t?t.getBoundingClientRect().top:0;fg(n,r==0?0:r-e)}function fg(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 mo=null;function e2(t){if(t.setActive)return t.setActive();if(mo)return t.focus(mo);let e=ug(t);t.focus(mo==null?{get preventScroll(){return mo={preventScroll:!0},!0}}:void 0),mo||(mo=!1,fg(e,0))}function hg(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 p;if(u.nodeType==1)p=u.getClientRects();else if(u.nodeType==3)p=dn(u).getClientRects();else continue;for(let m=0;m<p.length;m++){let g=p[m];if(g.top<=i&&g.bottom>=a){i=Math.max(g.bottom,i),a=Math.min(g.top,a);let y=g.left>e.left?g.left-e.left:g.right<e.left?e.left-g.right:0;if(y<r){n=u,r=y,o=y&&n.nodeType==3?{left:g.right<e.left?g.right:g.left,top:e.top}:e,u.nodeType==1&&y&&(s=f+(e.left>=(g.left+g.right)/2?1:0));continue}}else g.top>e.top&&!l&&g.left<=e.left&&g.right>=e.left&&(l=u,c={left:Math.max(g.left,Math.min(g.right,e.left)),top:g.top});!n&&(e.left>=g.right&&e.top>=g.top||e.left>=g.left&&e.top>=g.bottom)&&(s=f+1)}}return!n&&l&&(n=l,o=c,r=0),n&&n.nodeType==3?t2(n,o):!n||r&&n.nodeType==1?{node:t,offset:s}:hg(n,o)}function t2(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=Rn(r,1);if(i.top!=i.bottom&&$c(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 $c(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function n2(t,e){let n=t.parentNode;return n&&/^li$/i.test(n.nodeName)&&e.left<t.getBoundingClientRect().left?n:t}function r2(t,e,n){let{node:r,offset:o}=hg(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 o2(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 pg(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($c(e,c))return pg(i,e,c)}}if((s=(s+1)%r)==o)break}return t}function s2(t,e){let n=t.dom.ownerDocument,r,o=0,s=JT(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(!$c(e,c)||(i=pg(t.dom,e,c),!i))return null}if(Je)for(let c=i;r&&c;c=ho(c))c.draggable&&(r=void 0);if(i=n2(i,e),r){if(yt&&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;gs&&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=o2(t,r,o,e))}a==null&&(a=r2(t,i,e));let l=t.docView.nearestDesc(i,!0);return{pos:a,inside:l?l.posAtStart-l.border:-1}}function mg(t){return t.top<t.bottom||t.left<t.right}function Rn(t,e){let n=t.getClientRects();if(n.length){let r=n[e<0?0:n.length-1];if(mg(r))return r}return Array.prototype.find.call(n,mg)||t.getBoundingClientRect()}const i2=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;function gg(t,e,n){let{node:r,offset:o,atom:s}=t.docView.domFromPos(e,n<0?-1:1),i=gs||yt;if(r.nodeType==3)if(i&&(i2.test(r.nodeValue)||(n<0?!o:o==r.nodeValue.length))){let l=Rn(dn(r,o,o),n);if(yt&&o&&/\s/.test(r.nodeValue[o-1])&&o<r.nodeValue.length){let c=Rn(dn(r,o-1,o-1),-1);if(c.top==l.top){let u=Rn(dn(r,o,o+1),-1);if(u.top!=l.top)return ys(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++,ys(Rn(dn(r,l,c),u),u<0)}if(!t.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&o&&(n<0||o==gt(r))){let l=r.childNodes[o-1];if(l.nodeType==1)return Vc(l.getBoundingClientRect(),!1)}if(s==null&&o<gt(r)){let l=r.childNodes[o];if(l.nodeType==1)return Vc(l.getBoundingClientRect(),!0)}return Vc(r.getBoundingClientRect(),n>=0)}if(s==null&&o&&(n<0||o==gt(r))){let l=r.childNodes[o-1],c=l.nodeType==3?dn(l,gt(l)-(i?0:1)):l.nodeType==1&&(l.nodeName!="BR"||!l.nextSibling)?l:null;if(c)return ys(Rn(c,1),!1)}if(s==null&&o<gt(r)){let l=r.childNodes[o];for(;l.pmViewDesc&&l.pmViewDesc.ignoreForCoords;)l=l.nextSibling;let c=l?l.nodeType==3?dn(l,0,i?0:1):l.nodeType==1?l:null:null;if(c)return ys(Rn(c,-1),!0)}return ys(Rn(r.nodeType==3?dn(r):r,-n),n>=0)}function ys(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 Vc(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 yg(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 a2(t,e,n){let r=e.selection,o=n=="up"?r.$from:r.$to;return yg(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=gg(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=dn(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 l2=/[\u0590-\u08ac]/;function c2(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?!l2.test(r.parent.textContent)||!a.modify?n=="left"||n=="backward"?s:i:yg(t,e,()=>{let{focusNode:l,focusOffset:c,anchorNode:u,anchorOffset:f}=t.domSelectionRange(),p=a.caretBidiLevel;a.modify("move",n,"character");let m=r.depth?t.docView.domAfterPos(r.before()):t.dom,{focusNode:g,focusOffset:y}=t.domSelectionRange(),k=g&&!m.contains(g.nodeType==1?g:g.parentNode)||l==g&&c==y;try{a.collapse(u,f),l&&(l!=u||c!=f)&&a.extend&&a.extend(l,c)}catch{}return p!=null&&(a.caretBidiLevel=p),k}):r.pos==r.start()||r.pos==r.end()}let kg=null,wg=null,vg=!1;function d2(t,e,n){return kg==e&&wg==n?vg:(kg=e,wg=n,vg=n=="up"||n=="down"?a2(t,e,n):c2(t,e,n))}const wt=0,bg=1,br=2,Kt=3;class ks{constructor(e,n,r,o){this.parent=e,this.children=n,this.dom=r,this.contentDOM=o,this.dirty=wt,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>je(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 xg){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 Sg&&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?je(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?je(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 p=this.children[f-1];if(p.size&&p.dom.parentNode==this.contentDOM&&!p.emptyChildAt(1)){o=je(p.dom)+1;break}e-=p.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=je(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 m=0,g=0;m<this.children.length;m++){let y=this.children[m],k=g+y.size;if(s>g&&i<k)return y.setSelection(e-g-y.border,n-g-y.border,r,o);g=k}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((yt||Je)&&e==n){let{node:m,offset:g}=a;if(m.nodeType==3){if(f=!!(g&&m.nodeValue[g-1]==`
75
+ `),f&&g==m.nodeValue.length)for(let y=m,k;y;y=y.parentNode){if(k=y.nextSibling){k.nodeName=="BR"&&(a=l={node:k.parentNode,offset:je(k)+1});break}let w=y.pmViewDesc;if(w&&w.node&&w.node.isBlock)break}}else{let y=m.childNodes[g-1];f=y&&(y.nodeName=="BR"||y.contentEditable=="false")}}if(yt&&u.focusNode&&u.focusNode!=l.node&&u.focusNode.nodeType==1){let m=u.focusNode.childNodes[u.focusOffset];m&&m.contentEditable=="false"&&(o=!0)}if(!(o||f&&Je)&&wr(a.node,a.offset,u.anchorNode,u.anchorOffset)&&wr(l.node,l.offset,u.focusNode,u.focusOffset))return;let p=!1;if((c.extend||e==n)&&!(f&&yt)){c.collapse(a.node,a.offset);try{e!=n&&c.extend(l.node,l.offset),p=!0}catch{}}if(!p){if(e>n){let g=a;a=l,l=g}let m=document.createRange();m.setEnd(l.node,l.offset),m.setStart(a.node,a.offset),c.removeAllRanges(),c.addRange(m)}}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?br:bg,e==a&&n==l&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=Kt:s.markDirty(e-a,n-a);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?br:Kt}r=i}this.dirty=br}markParentsDirty(){let e=1;for(let n=this.parent;n;n=n.parent,e++){let r=e==1?br:bg;n.dirty<r&&(n.dirty=r)}}get domAtom(){return!1}get ignoreForCoords(){return!1}get ignoreForSelection(){return!1}isText(e){return!1}}class Sg extends ks{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==wt&&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 u2 extends ks{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 Sr extends ks{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=gr.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new Sr(e,n,i.dom,i.contentDOM||i.dom,i)}parseRule(){return this.dirty&Kt||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=Kt&&this.mark.eq(e)}markDirty(e,n){if(super.markDirty(e,n),this.dirty!=wt){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty<this.dirty&&(r.dirty=this.dirty),this.dirty=wt}}slice(e,n,r){let o=Sr.create(this.parent,this.mark,!0,r),s=this.children,i=this.size;n<i&&(s=Fc(s,n,i,r)),e>0&&(s=Fc(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 Dn extends ks{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}=gr.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 p=u;return u=Tg(u,r,n),c?l=new f2(e,n,r,o,u,f||null,p,c,s,i+1):n.isText?new Ui(e,n,r,o,u,p,s):new Dn(e,n,r,o,u,f||null,p,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=()=>B.empty)}return e}matchesNode(e,n,r){return this.dirty==wt&&e.eq(this.node)&&Ki(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 p2(this,i&&i.node,e);y2(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?ye.none:this.node.child(u).marks,r,e,u),l.placeWidget(c,e,o)},(c,u,f,p)=>{l.syncToMarks(c.marks,r,e,p);let m;l.findNodeMatch(c,u,f,p)||a&&e.state.selection.from>o&&e.state.selection.to<o+c.nodeSize&&(m=l.findIndexWithChild(s.node))>-1&&l.updateNodeAt(c,u,f,m,e)||l.updateNextNode(c,u,f,e,p,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==br)&&(i&&this.protectLocalComposition(e,i),_g(this.contentDOM,this.children,e),po&&k2(this.dom))}localCompositionInfo(e,n){let{from:r,to:o}=e.state.selection;if(!(e.state.selection instanceof re)||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=w2(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 u2(this,s,n,o);e.input.compositionNodes.push(i),this.children=Fc(this.children,r,r+o.length,e,i)}update(e,n,r,o){return this.dirty==Kt||!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=wt}updateOuterDeco(e){if(Ki(e,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=Eg(this.dom,this.nodeDOM,Lc(this.outerDeco,this.node,n),Lc(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 Cg(t,e,n,r,o){Tg(r,e,t);let s=new Dn(void 0,t,e,n,r,r,r,o,0);return s.contentDOM&&s.updateChildren(o,0),s}class Ui extends Dn{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==Kt||this.dirty!=wt&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=wt||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=wt,!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 Ui(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=Kt)}get domAtom(){return!1}isText(e){return this.node.text==e}}class xg extends ks{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==wt&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class f2 extends Dn{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==Kt)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 _g(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=Mg(r),o=!0;r=r.nextSibling}else o=!0,t.insertBefore(a,r);if(i instanceof Sr){let l=r?r.previousSibling:t.lastChild;_g(i.contentDOM,i.children,n),r=l?l.nextSibling:t.firstChild}}for(;r;)r=Mg(r),o=!0;o&&n.trackWrites==t&&(n.trackWrites=null)}const ws=function(t){t&&(this.nodeName=t)};ws.prototype=Object.create(null);const Cr=[new ws];function Lc(t,e,n){if(t.length==0)return Cr;let r=n?Cr[0]:new ws,o=[r];for(let s=0;s<t.length;s++){let i=t[s].type.attrs;if(i){i.nodeName&&o.push(r=new ws(i.nodeName));for(let a in i){let l=i[a];l!=null&&(n&&o.length==1&&o.push(r=new ws(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 Eg(t,e,n,r){if(n==Cr&&r==Cr)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=Cr[0]),o=l}h2(o,a||Cr[0],i)}return o}function h2(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 Tg(t,e,n){return Eg(t,t,Cr,Lc(e,n,t.nodeType!=1))}function Ki(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 Mg(t){let e=t.nextSibling;return t.parentNode.removeChild(t),e}class p2{constructor(e,n,r){this.lock=n,this.view=r,this.index=0,this.stack=[],this.changed=!1,this.top=e,this.preMatch=m2(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=wt,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=Sr.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==Kt&&i.dom==i.contentDOM&&(i.dirty=br),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 Dn){let c=this.preMatch.matched.get(l);if(c!=null&&c!=s)return!1;let u=l.dom,f,p=this.isLocked(u)&&!(e.isText&&l.node&&l.node.isText&&l.nodeDOM.nodeValue==e.text&&l.dirty!=Kt&&Ki(n,l.outerDeco));if(!p&&l.update(e,n,r,o))return this.destroyBetween(this.index,a),l.dom!=u&&(this.changed=!0),this.index++,!0;if(!p&&(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=br,f.updateChildren(o,i+1),f.dirty=wt),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)||!Ki(r,e.outerDeco)||!o.eq(e.innerDeco))return null;let a=Dn.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=Dn.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 Sg(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 Sr;)n=e,e=n.children[n.children.length-1];(!e||!(e instanceof Ui)||/\n$/.test(e.node.text)||this.view.requiresGeckoHackNode&&/\s$/.test(e.node.text))&&((Je||He)&&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 xg(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 m2(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 Sr)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 g2(t,e){return t.type.side-e.type.side}function y2(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 k=o[i++];k.widget&&(u?(f||(f=[u])).push(k):u=k)}if(u)if(f){f.sort(g2);for(let k=0;k<f.length;k++)n(f[k],c,!!l)}else n(u,c,!!l);let p,m;if(l)m=-1,p=l,l=null;else if(c<t.childCount)m=c,p=t.child(c++);else break;for(let k=0;k<a.length;k++)a[k].to<=s&&a.splice(k--,1);for(;i<o.length&&o[i].from<=s&&o[i].to>s;)a.push(o[i++]);let g=s+p.nodeSize;if(p.isText){let k=g;i<o.length&&o[i].from<k&&(k=o[i].from);for(let w=0;w<a.length;w++)a[w].to<k&&(k=a[w].to);k<g&&(l=p.cut(k-s),p=p.cut(0,k-s),g=k,m=-1)}else for(;i<o.length&&o[i].to<g;)i++;let y=p.isInline&&!p.isLeaf?a.filter(k=>!k.inline):a.slice();r(p,y,e.forChild(s,p),m),s=g}}function k2(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 w2(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 Fc(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 jc(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(Zi(n)){for(l=i;o&&!o.node;)o=o.parent;let f=o.node;if(o&&f.isAtom&&G.isSelectable(f)&&o.parent&&!(f.isInline&&UT(n.focusNode,n.focusOffset,o.dom))){let p=o.posBefore;c=new G(i==p?a:r.resolve(p))}}else{if(n instanceof t.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let f=i,p=i;for(let m=0;m<n.rangeCount;m++){let g=n.getRangeAt(m);f=Math.min(f,t.docView.posFromDOM(g.startContainer,g.startOffset,1)),p=Math.max(p,t.docView.posFromDOM(g.endContainer,g.endOffset,-1))}if(f<0)return null;[l,i]=p==t.state.selection.anchor?[p,f]:[f,p],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=Wc(t,u,a,f)}return c}function Ag(t){return t.editable?t.hasFocus():Dg(t)&&document.activeElement&&document.activeElement.contains(t.dom)}function hn(t,e=!1){let n=t.state.selection;if(Ig(t,n),!!Ag(t)){if(!e&&t.input.mouseDown&&t.input.mouseDown.allowDefault&&He){let r=t.domSelectionRange(),o=t.domObserver.currentSelection;if(r.anchorNode&&o.anchorNode&&wr(r.anchorNode,r.anchorOffset,o.anchorNode,o.anchorOffset)){t.input.mouseDown.delayedSelectionSync=!0,t.domObserver.setCurSelection();return}}if(t.domObserver.disconnectSelection(),t.cursorWrapper)b2(t);else{let{anchor:r,head:o}=n,s,i;Ng&&!(n instanceof re)&&(n.$from.parent.inlineContent||(s=Bg(t,n.from)),!n.empty&&!n.$from.parent.inlineContent&&(i=Bg(t,n.to))),t.docView.setSelection(r,o,t,e),Ng&&(s&&Og(s),i&&Og(i)),n.visible?t.dom.classList.remove("ProseMirror-hideselection"):(t.dom.classList.add("ProseMirror-hideselection"),"onselectionchange"in document&&v2(t))}t.domObserver.setCurSelection(),t.domObserver.connectSelection()}}const Ng=Je||He&&lg<63;function Bg(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(Je&&o&&o.contentEditable=="false")return Hc(o);if((!o||o.contentEditable=="false")&&(!s||s.contentEditable=="false")){if(o)return Hc(o);if(s)return Hc(s)}}function Hc(t){return t.contentEditable="true",Je&&t.draggable&&(t.draggable=!1,t.wasDraggable=!0),t}function Og(t){t.contentEditable="false",t.wasDraggable&&(t.draggable=!0,t.wasDraggable=null)}function v2(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(()=>{(!Ag(t)||t.state.selection.visible)&&t.dom.classList.remove("ProseMirror-hideselection")},20))})}function b2(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,r=n.nodeName=="IMG";r?e.collapse(n.parentNode,je(n)+1):e.collapse(n,0),!r&&!t.state.selection.visible&&ot&&Pn<=11&&(n.disabled=!0,n.disabled=!1)}function Ig(t,e){if(e instanceof G){let n=t.docView.descAt(e.from);n!=t.lastSelectedViewDesc&&(Pg(t),n&&n.selectNode(),t.lastSelectedViewDesc=n)}else Pg(t)}function Pg(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function Wc(t,e,n,r){return t.someProp("createSelectionBetween",o=>o(t,e,n))||re.between(e,n,r)}function Rg(t){return t.editable&&!t.hasFocus()?!1:Dg(t)}function Dg(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 S2(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return wr(e.node,e.offset,n.anchorNode,n.anchorOffset)}function Zc(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&&ie.findFrom(s,e)}function zn(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function zg(t,e,n){let r=t.state.selection;if(r instanceof re)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 zn(t,new re(r.$anchor,i))}else if(r.empty){if(t.endOfTextblock(e>0?"forward":"backward")){let o=Zc(t.state,e);return o&&o instanceof G?zn(t,o):!1}else if(!(kt&&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?G.isSelectable(s)?zn(t,new G(e<0?t.state.doc.resolve(o.pos-s.nodeSize):o)):gs?zn(t,new re(t.state.doc.resolve(e<0?a:a+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof G&&r.node.isInline)return zn(t,new re(e>0?r.$to:r.$from));{let o=Zc(t.state,e);return o?zn(t,o):!1}}}function Ji(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function vs(t,e){let n=t.pmViewDesc;return n&&n.size==0&&(e<0||t.nextSibling||t.nodeName!="BR")}function go(t,e){return e<0?C2(t):x2(t)}function C2(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let o,s,i=!1;for(yt&&n.nodeType==1&&r<Ji(n)&&vs(n.childNodes[r],-1)&&(i=!0);;)if(r>0){if(n.nodeType!=1)break;{let a=n.childNodes[r-1];if(vs(a,-1))o=n,s=--r;else if(a.nodeType==3)n=a,r=n.nodeValue.length;else break}}else{if($g(n))break;{let a=n.previousSibling;for(;a&&vs(a,-1);)o=n.parentNode,s=je(a),a=a.previousSibling;if(a)n=a,r=Ji(n);else{if(n=n.parentNode,n==t.dom)break;r=0}}}i?Uc(t,n,r):o&&Uc(t,o,s)}function x2(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let o=Ji(n),s,i;for(;;)if(r<o){if(n.nodeType!=1)break;let a=n.childNodes[r];if(vs(a,1))s=n,i=++r;else break}else{if($g(n))break;{let a=n.nextSibling;for(;a&&vs(a,1);)s=a.parentNode,i=je(a)+1,a=a.nextSibling;if(a)n=a,r=0,o=Ji(n);else{if(n=n.parentNode,n==t.dom)break;r=o=0}}}s&&Uc(t,s,i)}function $g(t){let e=t.pmViewDesc;return e&&e.node&&e.node.isBlock}function _2(t,e){for(;t&&e==t.childNodes.length&&!ms(t);)e=je(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 E2(t,e){for(;t&&!e&&!ms(t);)e=je(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 Uc(t,e,n){if(e.nodeType!=3){let s,i;(i=_2(e,n))?(e=i,n=0):(s=E2(e,n))&&(e=s,n=s.nodeValue.length)}let r=t.domSelection();if(!r)return;if(Zi(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&&hn(t)},50)}function Vg(t,e){let n=t.state.doc.resolve(e);if(!(He||cg)&&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 Lg(t,e,n){let r=t.state.selection;if(r instanceof re&&!r.empty||n.indexOf("s")>-1||kt&&n.indexOf("m")>-1)return!1;let{$from:o,$to:s}=r;if(!o.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let i=Zc(t.state,e);if(i&&i instanceof G)return zn(t,i)}if(!o.parent.inlineContent){let i=e<0?o:s,a=r instanceof dt?ie.near(i,e):ie.findFrom(i,e);return a?zn(t,a):!1}return!1}function Fg(t,e){if(!(t.state.selection instanceof re))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 jg(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function T2(t){if(!Je||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;jg(t,r,"true"),setTimeout(()=>jg(t,r,"false"),20)}return!1}function M2(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}function A2(t,e){let n=e.keyCode,r=M2(e);if(n==8||kt&&n==72&&r=="c")return Fg(t,-1)||go(t,-1);if(n==46&&!e.shiftKey||kt&&n==68&&r=="c")return Fg(t,1)||go(t,1);if(n==13||n==27)return!0;if(n==37||kt&&n==66&&r=="c"){let o=n==37?Vg(t,t.state.selection.from)=="ltr"?-1:1:-1;return zg(t,o,r)||go(t,o)}else if(n==39||kt&&n==70&&r=="c"){let o=n==39?Vg(t,t.state.selection.from)=="ltr"?1:-1:1;return zg(t,o,r)||go(t,o)}else{if(n==38||kt&&n==80&&r=="c")return Lg(t,-1,r)||go(t,-1);if(n==40||kt&&n==78&&r=="c")return T2(t)||Lg(t,1,r)||go(t,1);if(r==(kt?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function Kc(t,e){t.someProp("transformCopied",m=>{e=m(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 m=r.firstChild;n.push(m.type.name,m.attrs!=m.type.defaultAttrs?m.attrs:null),r=m.content}let i=t.someProp("clipboardSerializer")||gr.fromSchema(t.state.schema),a=Gg(),l=a.createElement("div");l.appendChild(i.serializeFragment(r,{document:a}));let c=l.firstChild,u,f=0;for(;c&&c.nodeType==1&&(u=Jg[c.nodeName.toLowerCase()]);){for(let m=u.length-1;m>=0;m--){let g=a.createElement(u[m]);for(;l.firstChild;)g.appendChild(l.firstChild);l.appendChild(g),f++}c=l.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${o} ${s}${f?` -${f}`:""} ${JSON.stringify(n)}`);let p=t.someProp("clipboardTextSerializer",m=>m(e,t))||e.content.textBetween(0,e.content.size,`
76
+
77
+ `);return{dom:l,text:p,slice:e}}function Hg(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",p=>{e=p(e,s||r,t)}),s)return a=new L(B.from(t.state.schema.text(e.replace(/\r\n?/g,`
78
+ `))),0,0),t.someProp("transformPasted",p=>{a=p(a,t,!0)}),a;let f=t.someProp("clipboardTextParser",p=>p(e,o,r,t));if(f)a=f;else{let p=o.marks(),{schema:m}=t.state,g=gr.fromSchema(m);i=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(y=>{let k=i.appendChild(document.createElement("p"));y&&k.appendChild(g.serializeNode(m.text(y,p)))})}}else t.someProp("transformPastedHTML",f=>{n=f(n,t)}),i=I2(n),gs&&P2(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 p=i.firstChild;for(;p&&p.nodeType!=1;)p=p.nextSibling;if(!p)break;i=p}if(a||(a=(t.someProp("clipboardParser")||t.someProp("domParser")||ln.fromSchema(t.state.schema)).parseSlice(i,{preserveWhitespace:!!(l||u),context:o,ruleFromNode(p){return p.nodeName=="BR"&&!p.nextSibling&&p.parentNode&&!N2.test(p.parentNode.nodeName)?{ignore:!0}:null}})),u)a=R2(Kg(a,+u[1],+u[2]),u[4]);else if(a=L.maxOpen(B2(a.content,o),!0),a.openStart||a.openEnd){let f=0,p=0;for(let m=a.content.firstChild;f<a.openStart&&!m.type.spec.isolating;f++,m=m.firstChild);for(let m=a.content.lastChild;p<a.openEnd&&!m.type.spec.isolating;p++,m=m.lastChild);a=Kg(a,f,p)}return t.someProp("transformPasted",f=>{a=f(a,t,l)}),a}const N2=/^(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 B2(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&&Zg(l,s,a,i[i.length-1],0))i[i.length-1]=c;else{i.length&&(i[i.length-1]=Ug(i[i.length-1],s.length));let u=Wg(a,l);i.push(u),o=o.matchType(u.type),s=l}}),i)return B.from(i)}return t}function Wg(t,e,n=0){for(let r=e.length-1;r>=n;r--)t=e[r].create(null,B.from(t));return t}function Zg(t,e,n,r,o){if(o<t.length&&o<e.length&&t[o]==e[o]){let s=Zg(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(B.from(Wg(n,t,o+1))))}}function Ug(t,e){if(e==0)return t;let n=t.content.replaceChild(t.childCount-1,Ug(t.lastChild,e-1)),r=t.contentMatchAt(t.childCount).fillBefore(B.empty,!0);return t.copy(n.append(r))}function Jc(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=Jc(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(B.empty,!0))),t.replaceChild(e<0?0:t.childCount-1,i.copy(a))}function Kg(t,e,n){return e<t.openStart&&(t=new L(Jc(t.content,-1,e,t.openStart,0,t.openEnd),e,t.openEnd)),n<t.openEnd&&(t=new L(Jc(t.content,1,n,t.openEnd,0,0),t.openStart,n)),t}const Jg={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 qg=null;function Gg(){return qg||(qg=document.implementation.createHTMLDocument("title"))}let qc=null;function O2(t){let e=window.trustedTypes;return e?(qc||(qc=e.defaultPolicy||e.createPolicy("ProseMirrorClipboard",{createHTML:n=>n})),qc.createHTML(t)):t}function I2(t){let e=/^(\s*<meta [^>]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let n=Gg().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(t),o;if((o=r&&Jg[r[1].toLowerCase()])&&(t=o.map(s=>"<"+s+">").join("")+t+o.map(s=>"</"+s+">").reverse().join("")),n.innerHTML=O2(t),o)for(let s=0;s<o.length;s++)n=n.querySelector(o[s])||n;return n}function P2(t){let e=t.querySelectorAll(He?"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 R2(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=B.from(l.create(r[a+1],o)),s++,i++}return new L(o,s,i)}const et={},tt={},D2={touchstart:!0,touchmove:!0};class z2{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 $2(t){for(let e in et){let n=et[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=r=>{L2(t,r)&&!Yc(t,r)&&(t.editable||!(r.type in tt))&&n(t,r)},D2[e]?{passive:!0}:void 0)}Je&&t.dom.addEventListener("input",()=>null),Gc(t)}function $n(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function V2(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 Gc(t){t.someProp("handleDOMEvents",e=>{for(let n in e)t.input.eventHandlers[n]||t.dom.addEventListener(n,t.input.eventHandlers[n]=r=>Yc(t,r))})}function Yc(t,e){return t.someProp("handleDOMEvents",n=>{let r=n[e.type];return r?r(t,e)||e.defaultPrevented:!1})}function L2(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 F2(t,e){!Yc(t,e)&&et[e.type]&&(t.editable||!(e.type in tt))&&et[e.type](t,e)}tt.keydown=(t,e)=>{let n=e;if(t.input.shiftKey=n.keyCode==16||n.shiftKey,!Xg(t,n)&&(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),!(un&&He&&n.keyCode==13)))if(n.keyCode!=229&&t.domObserver.forceFlush(),po&&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,vr(13,"Enter"))),t.input.lastIOSEnter=0)},200)}else t.someProp("handleKeyDown",r=>r(t,n))||A2(t,n)?n.preventDefault():$n(t,"key")},tt.keyup=(t,e)=>{e.keyCode==16&&(t.input.shiftKey=!1)},tt.keypress=(t,e)=>{let n=e;if(Xg(t,n)||!n.charCode||n.ctrlKey&&!n.altKey||kt&&n.metaKey)return;if(t.someProp("handleKeyPress",o=>o(t,n))){n.preventDefault();return}let r=t.state.selection;if(!(r instanceof re)||!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 qi(t){return{left:t.clientX,top:t.clientY}}function j2(t,e){let n=e.x-t.clientX,r=e.y-t.clientY;return n*n+r*r<100}function Xc(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 yo(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 H2(t,e){if(e==-1)return!1;let n=t.state.doc.resolve(e),r=n.nodeAfter;return r&&r.isAtom&&G.isSelectable(r)?(yo(t,new G(n)),!0):!1}function W2(t,e){if(e==-1)return!1;let n=t.state.selection,r,o;n instanceof G&&(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(G.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?(yo(t,G.create(t.state.doc,o)),!0):!1}function Z2(t,e,n,r,o){return Xc(t,"handleClickOn",e,n,r)||t.someProp("handleClick",s=>s(t,e,r))||(o?W2(t,n):H2(t,n))}function U2(t,e,n,r){return Xc(t,"handleDoubleClickOn",e,n,r)||t.someProp("handleDoubleClick",o=>o(t,e,r))}function K2(t,e,n,r){return Xc(t,"handleTripleClickOn",e,n,r)||t.someProp("handleTripleClick",o=>o(t,e,r))||J2(t,n,r)}function J2(t,e,n){if(n.button!=0)return!1;let r=t.state.doc;if(e==-1)return r.inlineContent?(yo(t,re.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)yo(t,re.create(r,a+1,a+1+i.content.size));else if(G.isSelectable(i))yo(t,G.create(r,a));else continue;return!0}}function Qc(t){return Gi(t)}const Yg=kt?"metaKey":"ctrlKey";et.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let r=Qc(t),o=Date.now(),s="singleClick";o-t.input.lastClick.time<500&&j2(n,t.input.lastClick)&&!n[Yg]&&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(qi(n));i&&(s=="singleClick"?(t.input.mouseDown&&t.input.mouseDown.done(),t.input.mouseDown=new q2(t,i,n,!!r)):(s=="doubleClick"?U2:K2)(t,i.pos,i.inside,n)?n.preventDefault():$n(t,"pointer"))};class q2{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[Yg],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 G&&c.from<=i&&c.to>i)&&(this.mightDrag={node:s,pos:i,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&yt&&!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)),$n(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(()=>hn(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(qi(e))),this.updateAllowDefault(e),this.allowDefault||!n?$n(this.view,"pointer"):Z2(this.view,n.pos,n.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||Je&&this.mightDrag&&!this.mightDrag.node.isAtom||He&&!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)?(yo(this.view,ie.near(this.view.state.doc.resolve(n.pos))),e.preventDefault()):$n(this.view,"pointer")}move(e){this.updateAllowDefault(e),$n(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)}}et.touchstart=t=>{t.input.lastTouch=Date.now(),Qc(t),$n(t,"pointer")},et.touchmove=t=>{t.input.lastTouch=Date.now(),$n(t,"pointer")},et.contextmenu=t=>Qc(t);function Xg(t,e){return t.composing?!0:Je&&Math.abs(e.timeStamp-t.input.compositionEndedAt)<500?(t.input.compositionEndedAt=-2e8,!0):!1}const G2=un?5e3:-1;tt.compositionstart=tt.compositionupdate=t=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,n=e.selection.$to;if(e.selection instanceof re&&(e.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||He&&cg&&Y2(t)))t.markCursor=t.state.storedMarks||n.marks(),Gi(t,!0),t.markCursor=null;else if(Gi(t,!e.selection.empty),yt&&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}Qg(t,G2)};function Y2(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"}tt.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++,Qg(t,20))};function Qg(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout(()=>Gi(t),e))}function ey(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=Q2());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function X2(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=WT(e.focusNode,e.focusOffset),r=ZT(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 Q2(){let t=document.createEvent("Event");return t.initEvent("event",!0,!0),t.timeStamp}function Gi(t,e=!1){if(!(un&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),ey(t),e||t.docView&&t.docView.dirty){let n=jc(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 eM(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 bs=ot&&Pn<15||po&&qT<604;et.copy=tt.cut=(t,e)=>{let n=e,r=t.state.selection,o=n.type=="cut";if(r.empty)return;let s=bs?null:n.clipboardData,i=r.content(),{dom:a,text:l}=Kc(t,i);s?(n.preventDefault(),s.clearData(),s.setData("text/html",a.innerHTML),s.setData("text/plain",l)):eM(t,a),o&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function tM(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function nM(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?Ss(t,r.value,null,o,e):Ss(t,r.textContent,r.innerHTML,o,e)},50)}function Ss(t,e,n,r,o){let s=Hg(t,e,n,r,t.state.selection.$from);if(t.someProp("handlePaste",l=>l(t,o,s||L.empty)))return!0;if(!s)return!1;let i=tM(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 ty(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," "):""}tt.paste=(t,e)=>{let n=e;if(t.composing&&!un)return;let r=bs?null:n.clipboardData,o=t.input.shiftKey&&t.input.lastKeyCode!=45;r&&Ss(t,ty(r),r.getData("text/html"),o,n)?n.preventDefault():nM(t,n)};class ny{constructor(e,n,r){this.slice=e,this.move=n,this.node=r}}const rM=kt?"altKey":"ctrlKey";function ry(t,e){let n=t.someProp("dragCopies",r=>!r(e));return n??!e[rM]}et.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(qi(n)),i;if(!(s&&s.pos>=o.from&&s.pos<=(o instanceof G?o.to-1:o.to))){if(r&&r.mightDrag)i=G.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=G.create(t.state.doc,f.posBefore))}}let a=(i||t.state.selection).content(),{dom:l,text:c,slice:u}=Kc(t,a);(!n.dataTransfer.files.length||!He||lg>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(bs?"Text":"text/html",l.innerHTML),n.dataTransfer.effectAllowed="copyMove",bs||n.dataTransfer.setData("text/plain",c),t.dragging=new ny(u,ry(t,n),i)},et.dragend=t=>{let e=t.dragging;window.setTimeout(()=>{t.dragging==e&&(t.dragging=null)},50)},tt.dragover=tt.dragenter=(t,e)=>e.preventDefault(),tt.drop=(t,e)=>{try{oM(t,e,t.dragging)}finally{t.dragging=null}};function oM(t,e,n){if(!e.dataTransfer)return;let r=t.posAtCoords(qi(e));if(!r)return;let o=t.state.doc.resolve(r.pos),s=n&&n.slice;s?t.someProp("transformPasted",m=>{s=m(s,t,!1)}):s=Hg(t,ty(e.dataTransfer),bs?null:e.dataTransfer.getData("text/html"),!1,o);let i=!!(n&&ry(t,e));if(t.someProp("handleDrop",m=>m(t,e,s||L.empty,i))){e.preventDefault();return}if(!s)return;e.preventDefault();let a=s?Om(t.state.doc,o.pos,s):o.pos;a==null&&(a=o.pos);let l=t.state.tr;if(i){let{node:m}=n;m?m.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 p=l.doc.resolve(c);if(u&&G.isSelectable(s.content.firstChild)&&p.nodeAfter&&p.nodeAfter.sameMarkup(s.content.firstChild))l.setSelection(new G(p));else{let m=l.mapping.map(a);l.mapping.maps[l.mapping.maps.length-1].forEach((g,y,k,w)=>m=w),l.setSelection(Wc(t,p,l.doc.resolve(m)))}t.focus(),t.dispatch(l.setMeta("uiEvent","drop"))}et.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())&&hn(t)},20))},et.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)},et.beforeinput=(t,e)=>{if(He&&un&&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,vr(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 tt)et[t]=tt[t];function Cs(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 Yi{constructor(e,n){this.toDOM=e,this.spec=n||xr,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 nt(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof Yi&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Cs(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class Vn{constructor(e,n){this.attrs=e,this.spec=n||xr}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 nt(s,i,this)}valid(e,n){return n.from<n.to}eq(e){return this==e||e instanceof Vn&&Cs(this.attrs,e.attrs)&&Cs(this.spec,e.spec)}static is(e){return e.type instanceof Vn}destroy(){}}class ed{constructor(e,n){this.attrs=e,this.spec=n||xr}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 nt(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 ed&&Cs(this.attrs,e.attrs)&&Cs(this.spec,e.spec)}destroy(){}}class nt{constructor(e,n,r){this.from=e,this.to=n,this.type=r}copy(e,n){return new nt(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 nt(e,e,new Yi(n,r))}static inline(e,n,r,o){return new nt(e,n,new Vn(r,o))}static node(e,n,r,o){return new nt(e,n,new ed(r,o))}get spec(){return this.type.spec}get inline(){return this.type instanceof Vn}get widget(){return this.type instanceof Yi}}const ko=[],xr={};class Ce{constructor(e,n){this.local=e.length?e:ko,this.children=n.length?n:ko}static create(e,n){return n.length?Xi(n,e,0,xr):qe}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==qe||e.maps.length==0?this:this.mapInner(e,n,0,0,r||xr)}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?sM(this.children,i||[],e,n,r,o,s):i?new Ce(i.sort(_r),ko):qe}add(e,n){return n.length?this==qe?Ce.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=sy(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,Xi(u,a,c+1,xr)),s+=3}});let i=oy(s?iy(n):n,-r);for(let a=0;a<i.length;a++)i[a].type.valid(e,i[a])||i.splice(a--,1);return new Ce(i.length?this.local.concat(i).sort(_r):this.local,o||this.children)}remove(e){return e.length==0||this==qe?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!=qe?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 Ce(o,r):qe}forChild(e,n){if(this==qe)return this;if(n.isLeaf)return Ce.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 Vn){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 Ce(o.sort(_r),ko);return r?new Ln([a,r]):a}return r||qe}eq(e){if(this==e)return!0;if(!(e instanceof Ce)||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 td(this.localsInner(e))}localsInner(e){if(this==qe)return ko;if(e.inlineContent||!this.local.some(Vn.is))return this.local;let n=[];for(let r=0;r<this.local.length;r++)this.local[r].type instanceof Vn||n.push(this.local[r]);return n}forEachSet(e){e(this)}}Ce.empty=new Ce([],[]),Ce.removeOverlap=td;const qe=Ce.empty;class Ln{constructor(e){this.members=e}map(e,n){const r=this.members.map(o=>o.map(e,n,xr));return Ln.from(r)}forChild(e,n){if(n.isLeaf)return Ce.empty;let r=[];for(let o=0;o<this.members.length;o++){let s=this.members[o].forChild(e,n);s!=qe&&(s instanceof Ln?r=r.concat(s.members):r.push(s))}return Ln.from(r)}eq(e){if(!(e instanceof Ln)||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?td(r?n:n.sort(_r)):ko}static from(e){switch(e.length){case 0:return qe;case 1:return e[0];default:return new Ln(e.every(n=>n instanceof Ce)?e:e.reduce((n,r)=>n.concat(r instanceof Ce?r:r.members),[]))}}forEachSet(e){for(let n=0;n<this.members.length;n++)this.members[n].forEachSet(e)}}function sM(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((p,m,g,y)=>{let k=y-g-(m-p);for(let w=0;w<a.length;w+=3){let v=a[w+1];if(v<0||p>v+u-f)continue;let b=a[w]+u-f;m>=b?a[w+1]=p<=b?-2:-1:p>=u&&k&&(a[w]+=k,a[w+1]+=k)}f+=k}),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 p=n.map(t[c+1]+s,-1),m=p-o,{index:g,offset:y}=r.content.findIndex(f),k=r.maybeChild(g);if(k&&y==f&&y+k.nodeSize==m){let w=a[c+2].mapInner(n,k,u+1,t[c]+s+1,i);w!=qe?(a[c]=f,a[c+1]=m,a[c+2]=w):(a[c+1]=-2,l=!0)}else l=!0}if(l){let c=iM(a,t,e,n,o,s,i),u=Xi(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,p=0;f<u.children.length;f+=3){let m=u.children[f];for(;p<a.length&&a[p]<m;)p+=3;a.splice(p,0,u.children[f],u.children[f+1],u.children[f+2])}}return new Ce(e.sort(_r),a)}function oy(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 nt(o.from+e,o.to+e,o.type))}return n}function iM(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 sy(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 iy(t){let e=[];for(let n=0;n<t.length;n++)t[n]!=null&&e.push(t[n]);return e}function Xi(t,e,n,r){let o=[],s=!1;e.forEach((a,l)=>{let c=sy(t,a,l+n);if(c){s=!0;let u=Xi(c,a,n+l+1,r);u!=qe&&o.push(l,l+a.nodeSize,u)}});let i=oy(s?iy(t):t,-n).sort(_r);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 Ce(i,o):qe}function _r(t,e){return t.from-e.from||t.to-e.to}function td(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),ay(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),ay(e,o,r.copy(s.from,r.to)));break}}}return e}function ay(t,e,n){for(;e<t.length&&_r(n,t[e])>0;)e++;t.splice(e,0,n)}function nd(t){let e=[];return t.someProp("decorations",n=>{let r=n(t.state);r&&r!=qe&&e.push(r)}),t.cursorWrapper&&e.push(Ce.create(t.state.doc,[t.cursorWrapper.deco])),Ln.from(e)}const aM={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},lM=ot&&Pn<=11;class cM{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 dM{constructor(e,n){this.view=e,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new cM,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]);ot&&Pn<=11&&r.some(o=>o.type=="childList"&&o.removedNodes.length||o.type=="characterData"&&o.oldValue.length>o.target.nodeValue.length)?this.flushSoon():Je&&e.composing&&r.some(o=>o.type=="childList"&&o.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),lM&&(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,aM)),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(Rg(this.view)){if(this.suppressingSelectionUpdates)return hn(this.view);if(ot&&Pn<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&wr(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=ho(s))n.add(s);for(let s=e.anchorNode;s;s=ho(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)&&Rg(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(yt&&l.length){let u=l.filter(f=>f.nodeName=="BR");if(u.length==2){let[f,p]=u;f.parentNode&&f.parentNode.parentNode==p.parentNode?p.remove():f.remove()}else{let{focusNode:f}=this.currentSelection;for(let p of u){let m=p.parentNode;m&&m.nodeName=="LI"&&(!f||hM(e,f)!=m)&&p.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&&Zi(r)&&(c=jc(e))&&c.eq(ie.near(e.state.doc.resolve(0),1))?(e.input.lastFocus=0,hn(e),this.currentSelection.set(r),e.scrollToSelection()):(s>-1||o)&&(s>-1&&(e.docView.markDirty(s,i),uM(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,pM(e,l)),this.handleDOMChange(s,i,a,l),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||hn(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(ot&&Pn<=11&&e.addedNodes.length)for(let u=0;u<e.addedNodes.length;u++){let{previousSibling:f,nextSibling:p}=e.addedNodes[u];(!f||Array.prototype.indexOf.call(e.addedNodes,f)<0)&&(o=f),(!p||Array.prototype.indexOf.call(e.addedNodes,p)<0)&&(s=p)}let i=o&&o.parentNode==e.target?je(o)+1:0,a=r.localPosFromDOM(e.target,i,-1),l=s&&s.parentNode==e.target?je(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 ly=new WeakMap,cy=!1;function uM(t){if(!ly.has(t)&&(ly.set(t,null),["normal","nowrap","pre-line"].indexOf(getComputedStyle(t.dom).whiteSpace)!==-1)){if(t.requiresGeckoHackNode=yt,cy)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."),cy=!0}}function dy(t,e){let n=e.startContainer,r=e.startOffset,o=e.endContainer,s=e.endOffset,i=t.domAtPos(t.state.selection.anchor);return wr(i.node,i.offset,o,s)&&([n,r,o,s]=[o,s,n,r]),{anchorNode:n,anchorOffset:r,focusNode:o,focusOffset:s}}function fM(t,e){if(e.getComposedRanges){let o=e.getComposedRanges(t.root)[0];if(o)return dy(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?dy(t,n):null}function hM(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 pM(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 mM(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}],Zi(l)||c.push({node:l.focusNode,offset:l.focusOffset})),He&&t.input.lastKeyCode===8)for(let k=s;k>o;k--){let w=r.childNodes[k-1],v=w.pmViewDesc;if(w.nodeName=="BR"&&!v){s=k;break}if(!v||v.size)break}let f=t.state.doc,p=t.someProp("domParser")||ln.fromSchema(t.state.schema),m=f.resolve(i),g=null,y=p.parse(r,{topNode:m.parent,topMatch:m.parent.contentMatchAt(m.index()),topOpen:!0,from:o,to:s,preserveWhitespace:m.parent.type.whitespace=="pre"?"full":!0,findPositions:c,ruleFromNode:gM,context:m});if(c&&c[0].pos!=null){let k=c[0].pos,w=c[1]&&c[1].pos;w==null&&(w=k),g={anchor:k+i,head:w+i}}return{doc:y,sel:g,from:i,to:a}}function gM(t){let e=t.pmViewDesc;if(e)return e.parseRule();if(t.nodeName=="BR"&&t.parentNode){if(Je&&/^(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||Je&&/^(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 yM=/^(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 kM(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,T=jc(t,_);if(T&&!t.state.selection.eq(T)){if(He&&un&&t.input.lastKeyCode===13&&Date.now()-100<t.input.lastKeyCodeTime&&t.someProp("handleKeyDown",I=>I(t,vr(13,"Enter"))))return;let N=t.state.tr.setSelection(T);_=="pointer"?N.setMeta("pointer",!0):_=="key"&&N.scrollIntoView(),s&&N.setMeta("composition",s),t.dispatch(N)}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=mM(t,e,n),u=t.state.doc,f=u.slice(c.from,c.to),p,m;t.input.lastKeyCode===8&&Date.now()-100<t.input.lastKeyCodeTime?(p=t.state.selection.to,m="end"):(p=t.state.selection.from,m="start"),t.input.lastKeyCode=null;let g=bM(f.content,c.doc.content,c.from,p,m);if(g&&t.input.domChangeCount++,(po&&t.input.lastIOSEnter>Date.now()-225||un)&&o.some(_=>_.nodeType==1&&!yM.test(_.nodeName))&&(!g||g.endA>=g.endB)&&t.someProp("handleKeyDown",_=>_(t,vr(13,"Enter")))){t.input.lastIOSEnter=0;return}if(!g)if(r&&l instanceof re&&!l.empty&&l.$head.sameParent(l.$anchor)&&!t.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))g={start:l.from,endA:l.to,endB:l.to};else{if(c.sel){let _=uy(t,t.state.doc,c.sel);if(_&&!_.eq(t.state.selection)){let T=t.state.tr.setSelection(_);s&&T.setMeta("composition",s),t.dispatch(T)}}return}t.state.selection.from<t.state.selection.to&&g.start==g.endB&&t.state.selection instanceof re&&(g.start>t.state.selection.from&&g.start<=t.state.selection.from+2&&t.state.selection.from>=c.from?g.start=t.state.selection.from:g.endA<t.state.selection.to&&g.endA>=t.state.selection.to-2&&t.state.selection.to<=c.to&&(g.endB+=t.state.selection.to-g.endA,g.endA=t.state.selection.to)),ot&&Pn<=11&&g.endB==g.start+1&&g.endA==g.start&&g.start>c.from&&c.doc.textBetween(g.start-c.from-1,g.start-c.from+1)=="  "&&(g.start--,g.endA--,g.endB--);let y=c.doc.resolveNoCache(g.start-c.from),k=c.doc.resolveNoCache(g.endB-c.from),w=u.resolve(g.start),v=y.sameParent(k)&&y.parent.inlineContent&&w.end()>=g.endA;if((po&&t.input.lastIOSEnter>Date.now()-225&&(!v||o.some(_=>_.nodeName=="DIV"||_.nodeName=="P"))||!v&&y.pos<c.doc.content.size&&(!y.sameParent(k)||!y.parent.inlineContent)&&y.pos<k.pos&&!/\S/.test(c.doc.textBetween(y.pos,k.pos,"","")))&&t.someProp("handleKeyDown",_=>_(t,vr(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>g.start&&vM(u,g.start,g.endA,y,k)&&t.someProp("handleKeyDown",_=>_(t,vr(8,"Backspace")))){un&&He&&t.domObserver.suppressSelectionUpdates();return}He&&g.endB==g.start&&(t.input.lastChromeDelete=Date.now()),un&&!v&&y.start()!=k.start()&&k.parentOffset==0&&y.depth==k.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==g.endA&&(g.endB-=2,k=c.doc.resolveNoCache(g.endB-c.from),setTimeout(()=>{t.someProp("handleKeyDown",function(_){return _(t,vr(13,"Enter"))})},20));let b=g.start,S=g.endA,C=_=>{let T=_||t.state.tr.replace(b,S,c.doc.slice(g.start-c.from,g.endB-c.from));if(c.sel){let N=uy(t,T.doc,c.sel);N&&!(He&&t.composing&&N.empty&&(g.start!=g.endB||t.input.lastChromeDelete<Date.now()-100)&&(N.head==b||N.head==T.mapping.map(S)-1)||ot&&N.empty&&N.head==b)&&T.setSelection(N)}return s&&T.setMeta("composition",s),T.scrollIntoView()},x;if(v)if(y.pos==k.pos){ot&&Pn<=11&&y.parentOffset==0&&(t.domObserver.suppressSelectionUpdates(),setTimeout(()=>hn(t),20));let _=C(t.state.tr.delete(b,S)),T=u.resolve(g.start).marksAcross(u.resolve(g.endA));T&&_.ensureMarks(T),t.dispatch(_)}else if(g.endA==g.endB&&(x=wM(y.parent.content.cut(y.parentOffset,k.parentOffset),w.parent.content.cut(w.parentOffset,g.endA-w.start())))){let _=C(t.state.tr);x.type=="add"?_.addMark(b,S,x.mark):_.removeMark(b,S,x.mark),t.dispatch(_)}else if(y.parent.child(y.index()).isText&&y.index()==k.index()-(k.textOffset?0:1)){let _=y.parent.textBetween(y.parentOffset,k.parentOffset),T=()=>C(t.state.tr.insertText(_,b,S));t.someProp("handleTextInput",N=>N(t,b,S,_,T))||t.dispatch(T())}else t.dispatch(C());else t.dispatch(C())}function uy(t,e,n){return Math.max(n.anchor,n.head)>e.content.size?null:Wc(t,e.resolve(n.anchor),e.resolve(n.head))}function wM(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(B.from(c).eq(t))return{mark:a,type:i}}function vM(t,e,n,r,o){if(n-e<=o.pos-r.pos||rd(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(rd(s,!0,!0));return!i.parent.isTextblock||i.pos>n||rd(i,!0,!1)<n?!1:r.parent.content.cut(r.parentOffset).eq(i.parent.content)}function rd(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 bM(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&&fy(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&&fy(t.textBetween(s-1,s+1))&&(s+=l?1:-1),i=s+(i-a),a=s}return{start:s,endA:i,endB:a}}function fy(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 hy{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 z2,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(ky),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=gy(this),my(this),this.nodeViews=yy(this),this.docView=Cg(this.state.doc,py(this),nd(this),this.dom,this),this.domObserver=new dM(this,(r,o,s,i)=>kM(this,r,o,s,i)),this.domObserver.start(),$2(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&&Gc(this);let n=this._props;this._props=e,e.plugins&&(e.plugins.forEach(ky),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&&(ey(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 m=yy(this);CM(m,this.nodeViews)&&(this.nodeViews=m,s=!0)}(a||n.handleDOMEvents!=this._props.handleDOMEvents)&&Gc(this),this.editable=gy(this),my(this);let l=nd(this),c=py(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 p=u=="preserve"&&i&&this.dom.style.overflowAnchor==null&&XT(this);if(i){this.domObserver.stop();let m=f&&(ot||He)&&!this.composing&&!o.selection.empty&&!e.selection.empty&&SM(o.selection,e.selection);if(f){let g=He?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=X2(this)),(s||!this.docView.update(e.doc,c,l,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=Cg(e.doc,c,l,this.dom,this)),g&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(m=!0)}m||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&S2(this))?hn(this,m):(Ig(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():p&&QT(p)}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 G){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&dg(this,n.getBoundingClientRect(),e)}else dg(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 ny(e.slice,e.move,o<0?void 0:G.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(ot){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&&e2(this.dom),hn(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 s2(this,e)}coordsAtPos(e,n=1){return gg(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 d2(this,n||this.state,e)}pasteHTML(e,n){return Ss(this,"",e,!1,n||new ClipboardEvent("paste"))}pasteText(e,n){return Ss(this,e,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(e){return Kc(this,e)}destroy(){this.docView&&(V2(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],nd(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,jT())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return F2(this,e)}domSelectionRange(){let e=this.domSelection();return e?Je&&this.root.nodeType===11&&KT(this.dom.ownerDocument)==this.dom&&fM(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}hy.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};function py(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"),[nt.node(0,t.state.doc.content.size,e)]}function my(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:nt.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function gy(t){return!t.someProp("editable",e=>e(t.state)===!1)}function SM(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 yy(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 CM(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 ky(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 Fn={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:"'"},Qi={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},xM=typeof navigator<"u"&&/Mac/.test(navigator.platform),_M=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),We=0;We<10;We++)Fn[48+We]=Fn[96+We]=String(We);for(var We=1;We<=24;We++)Fn[We+111]="F"+We;for(var We=65;We<=90;We++)Fn[We]=String.fromCharCode(We+32),Qi[We]=String.fromCharCode(We);for(var od in Fn)Qi.hasOwnProperty(od)||(Qi[od]=Fn[od]);function EM(t){var e=xM&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||_M&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",n=!e&&t.key||(t.shiftKey?Qi:Fn)[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 TM=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),MM=typeof navigator<"u"&&/Win/.test(navigator.platform);function AM(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))TM?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 NM(t){let e=Object.create(null);for(let n in t)e[AM(n)]=t[n];return e}function sd(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 BM(t){return new Oe({props:{handleKeyDown:wy(t)}})}function wy(t){let e=NM(t);return function(n,r){let o=EM(r),s,i=e[sd(o,r)];if(i&&i(n.state,n.dispatch,n))return!0;if(o.length==1&&o!=" "){if(r.shiftKey){let a=e[sd(o,r,!1)];if(a&&a(n.state,n.dispatch,n))return!0}if((r.altKey||r.metaKey||r.ctrlKey)&&!(MM&&r.ctrlKey&&r.altKey)&&(s=Fn[r.keyCode])&&s!=o){let a=e[sd(s,r)];if(a&&a(n.state,n.dispatch,n))return!0}}return!1}}var OM=Object.defineProperty,id=(t,e)=>{for(var n in e)OM(t,n,{get:e[n],enumerable:!0})};function ea(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 ta=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,p])=>[f,(...g)=>{const y=this.buildProps(l,e),k=p(...g)(y);return i.push(k),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:ea({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}},vy={};id(vy,{blur:()=>IM,clearContent:()=>PM,clearNodes:()=>RM,command:()=>DM,createParagraphNear:()=>zM,cut:()=>$M,deleteCurrentNode:()=>VM,deleteNode:()=>LM,deleteRange:()=>FM,deleteSelection:()=>jM,enter:()=>HM,exitCode:()=>WM,extendMarkRange:()=>ZM,first:()=>UM,focus:()=>JM,forEach:()=>qM,insertContent:()=>GM,insertContentAt:()=>QM,joinBackward:()=>nA,joinDown:()=>tA,joinForward:()=>rA,joinItemBackward:()=>oA,joinItemForward:()=>sA,joinTextblockBackward:()=>iA,joinTextblockForward:()=>aA,joinUp:()=>eA,keyboardShortcut:()=>cA,lift:()=>dA,liftEmptyBlock:()=>uA,liftListItem:()=>fA,newlineInCode:()=>hA,resetAttributes:()=>pA,scrollIntoView:()=>mA,selectAll:()=>gA,selectNodeBackward:()=>yA,selectNodeForward:()=>kA,selectParentNode:()=>wA,selectTextblockEnd:()=>vA,selectTextblockStart:()=>bA,setContent:()=>SA,setMark:()=>FA,setMeta:()=>jA,setNode:()=>HA,setNodeSelection:()=>WA,setTextDirection:()=>ZA,setTextSelection:()=>UA,sinkListItem:()=>KA,splitBlock:()=>JA,splitListItem:()=>qA,toggleList:()=>GA,toggleMark:()=>YA,toggleNode:()=>XA,toggleWrap:()=>QA,undoInputRule:()=>eN,unsetAllMarks:()=>tN,unsetMark:()=>nN,unsetTextDirection:()=>rN,updateAttributes:()=>oN,wrapIn:()=>sN,wrapInList:()=>iN});var IM=()=>({editor:t,view:e})=>(requestAnimationFrame(()=>{var n;t.isDestroyed||(e.dom.blur(),(n=window==null?void 0:window.getSelection())==null||n.removeAllRanges())}),!0),PM=(t=!0)=>({commands:e})=>e.setContent("",{emitUpdate:t}),RM=()=>({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)),p=c.resolve(u.map(l+a.nodeSize)),m=f.blockRange(p);if(!m)return;const g=io(m);if(a.type.isTextblock){const{defaultType:y}=f.parent.contentMatchAt(f.index());e.setNodeMarkup(m.start,y)}(g||g===0)&&e.lift(m,g)})}),!0},DM=t=>e=>t(e),zM=()=>({state:t,dispatch:e})=>eg(t,e),$M=(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 re(r.doc.resolve(Math.max(i-1,0)))),!0},VM=()=>({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 ze(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 LM=t=>({tr:e,state:n,dispatch:r})=>{const o=ze(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},FM=t=>({tr:e,dispatch:n})=>{const{from:r,to:o}=t;return n&&e.delete(r,o),!0},jM=()=>({state:t,dispatch:e})=>Ac(t,e),HM=()=>({commands:t})=>t.keyboardShortcut("Enter"),WM=()=>({state:t,dispatch:e})=>TT(t,e);function ad(t){return Object.prototype.toString.call(t)==="[object RegExp]"}function na(t,e,n={strict:!0}){const r=Object.keys(e);return r.length?r.every(o=>n.strict?e[o]===t[o]:ad(e[o])?e[o].test(t[o]):e[o]===t[o]):!0}function by(t,e,n={}){return t.find(r=>r.type===e&&na(Object.fromEntries(Object.keys(n).map(o=>[o,r.attrs[o]])),n))}function Sy(t,e,n={}){return!!by(t,e,n)}function ld(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),!by([...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&&Sy([...t.parent.child(i-1).marks],e,n);)i-=1,a-=t.parent.child(i).nodeSize;for(;l<t.parent.childCount&&Sy([...t.parent.child(l).marks],e,n);)c+=t.parent.child(l).nodeSize,l+=1;return{from:a,to:c}}function pn(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 ZM=(t,e={})=>({tr:n,state:r,dispatch:o})=>{const s=pn(t,r.schema),{doc:i,selection:a}=n,{$from:l,from:c,to:u}=a;if(o){const f=ld(l,s,e);if(f&&f.from<=c&&f.to>=u){const p=re.create(i,f.from,f.to);n.setSelection(p)}}return!0},UM=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 Cy(t){return t instanceof re}function Er(t=0,e=0,n=0){return Math.min(Math.max(t,e),n)}function xy(t,e=null){if(!e)return null;const n=ie.atStart(t),r=ie.atEnd(t);if(e==="start"||e===!0)return n;if(e==="end")return r;const o=n.from,s=r.to;return e==="all"?re.create(t,Er(0,o,s),Er(t.content.size,o,s)):re.create(t,Er(e,o,s),Er(e,o,s))}function _y(){return navigator.platform==="Android"||/android/i.test(navigator.userAgent)}function ra(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}function KM(){return typeof navigator<"u"?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}var JM=(t=null,e={})=>({editor:n,view:r,tr:o,dispatch:s})=>{e={scrollIntoView:!0,...e};const i=()=>{(ra()||_y())&&r.dom.focus(),KM()&&!ra()&&!_y()&&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&&!Cy(n.state.selection))return i(),!0;const a=xy(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},qM=(t,e)=>n=>t.every((r,o)=>e(r,{...n,index:o})),GM=(t,e)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},t,e),Ey=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&&Ey(r)}return t};function xs(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 Ey(n)}function _s(t,e,n){if(t instanceof an||t instanceof B)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 B.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),_s("",e,n)}if(o){if(n.errorOnInvalidContent){let i=!1,a="";const l=new um({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?ln.fromSchema(l).parseSlice(xs(t),n.parseOptions):ln.fromSchema(l).parse(xs(t),n.parseOptions),n.errorOnInvalidContent&&i)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${a}`)})}const s=ln.fromSchema(e);return n.slice?s.parseSlice(xs(t),n.parseOptions).content:s.parse(xs(t),n.parseOptions)}return _s("",e,n)}function YM(t,e,n){const r=t.steps.length-1;if(r<e)return;const o=t.steps[r];if(!(o instanceof Re||o instanceof De))return;const s=t.mapping.maps[r];let i=0;s.forEach((a,l,c,u)=>{i===0&&(i=u)}),t.setSelection(ie.near(t.doc.resolve(i),n))}var XM=t=>!("type"in t),QM=(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=k=>{s.emit("contentError",{editor:s,error:k,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{_s(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(k){l(k)}try{a=_s(e,s.schema,{parseOptions:c,errorOnInvalidContent:(i=n.errorOnInvalidContent)!=null?i:s.options.enableContentCheck})}catch(k){return l(k),!1}let{from:u,to:f}=typeof t=="number"?{from:t,to:t}:{from:t.from,to:t.to},p=!0,m=!0;if((XM(a)?a:[a]).forEach(k=>{k.check(),p=p?k.isText&&k.marks.length===0:!1,m=m?k.isBlock:!1}),u===f&&m){const{parent:k}=r.doc.resolve(u);k.isTextblock&&!k.type.spec.code&&!k.childCount&&(u-=1,f+=1)}let y;if(p){if(Array.isArray(e))y=e.map(k=>k.text||"").join("");else if(e instanceof B){let k="";e.forEach(w=>{w.text&&(k+=w.text)}),y=k}else typeof e=="object"&&e&&e.text?y=e.text:y=e;r.insertText(y,u,f)}else{y=a;const k=r.doc.resolve(u),w=k.node(),v=k.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,y)}n.updateSelection&&YM(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:u,text:y}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:u,text:y})}return!0},eA=()=>({state:t,dispatch:e})=>xT(t,e),tA=()=>({state:t,dispatch:e})=>_T(t,e),nA=()=>({state:t,dispatch:e})=>Km(t,e),rA=()=>({state:t,dispatch:e})=>Ym(t,e),oA=()=>({state:t,dispatch:e,tr:n})=>{try{const r=Fi(t.doc,t.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},sA=()=>({state:t,dispatch:e,tr:n})=>{try{const r=Fi(t.doc,t.selection.$from.pos,1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},iA=()=>({state:t,dispatch:e})=>ST(t,e),aA=()=>({state:t,dispatch:e})=>CT(t,e);function Ty(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function lA(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))ra()||Ty()?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 cA=t=>({editor:e,view:n,tr:r,dispatch:o})=>{const s=lA(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 Es(t,e,n={}){const{from:r,to:o,empty:s}=t.selection,i=e?ze(e,t.schema):null,a=[];t.doc.nodesBetween(r,o,(f,p)=>{if(f.isText)return;const m=Math.max(r,p),g=Math.min(o,p+f.nodeSize);a.push({node:f,from:m,to:g})});const l=o-r,c=a.filter(f=>i?i.name===f.node.type.name:!0).filter(f=>na(f.node.attrs,n,{strict:!1}));return s?!!c.length:c.reduce((f,p)=>f+p.to-p.from,0)>=l}var dA=(t,e={})=>({state:n,dispatch:r})=>{const o=ze(t,n.schema);return Es(n,o,e)?ET(n,r):!1},uA=()=>({state:t,dispatch:e})=>tg(t,e),fA=t=>({state:e,dispatch:n})=>{const r=ze(t,e.schema);return $T(r)(e,n)},hA=()=>({state:t,dispatch:e})=>Qm(t,e);function oa(t,e){return e.nodes[t]?"node":e.marks[t]?"mark":null}function My(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 pA=(t,e)=>({tr:n,state:r,dispatch:o})=>{let s=null,i=null;const a=oa(typeof t=="string"?t:t.name,r.schema);if(!a)return!1;a==="node"&&(s=ze(t,r.schema)),a==="mark"&&(i=pn(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,My(u.attrs,e))),i&&u.marks.length&&u.marks.forEach(p=>{i===p.type&&(l=!0,o&&n.addMark(f,f+u.nodeSize,i.create(My(p.attrs,e))))})})}),l},mA=()=>({tr:t,dispatch:e})=>(e&&t.scrollIntoView(),!0),gA=()=>({tr:t,dispatch:e})=>{if(e){const n=new dt(t.doc);t.setSelection(n)}return!0},yA=()=>({state:t,dispatch:e})=>qm(t,e),kA=()=>({state:t,dispatch:e})=>Xm(t,e),wA=()=>({state:t,dispatch:e})=>NT(t,e),vA=()=>({state:t,dispatch:e})=>IT(t,e),bA=()=>({state:t,dispatch:e})=>OT(t,e);function cd(t,e,n={},r={}){return _s(t,e,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}var SA=(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=cd(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 Ay(t,e){const n=pn(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 CA(t,e){const n=new zm(t);return e.forEach(r=>{r.steps.forEach(o=>{n.step(o)})}),n}function xA(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 _A(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 dd(t){return e=>_A(e.$from,t)}function U(t,e,n){return t.config[e]===void 0&&t.parent?U(t.parent,e,n):typeof t.config[e]=="function"?t.config[e].bind({...n,parent:t.parent?U(t.parent,e,n):null}):t.config[e]}function ud(t){return t.map(e=>{const n={name:e.name,options:e.options,storage:e.storage},r=U(e,"addExtensions",n);return r?[e,...ud(r())]:e}).flat(10)}function sa(t,e){const n=gr.fromSchema(e).serializeFragment(t),o=document.implementation.createHTMLDocument().createElement("div");return o.appendChild(n),o.innerHTML}function Ny(t){return typeof t=="function"}function ke(t,e=void 0,...n){return Ny(t)?e?t.bind(e)(...n):t(...n):t}function EA(t={}){return Object.keys(t).length===0&&t.constructor===Object}function wo(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 By(t){const e=[],{nodeExtensions:n,markExtensions:r}=wo(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=U(c,"addGlobalAttributes",u);if(!f)return;f().forEach(m=>{let g;Array.isArray(m.types)?g=m.types:m.types==="*"?g=l:m.types==="nodes"?g=i:m.types==="marks"?g=a:g=[],g.forEach(y=>{Object.entries(m.attributes).forEach(([k,w])=>{e.push({type:y,name:k,attribute:{...s,...w}})})})})}),o.forEach(c=>{const u={name:c.name,options:c.options,storage:c.storage},f=U(c,"addAttributes",u);if(!f)return;const p=f();Object.entries(p).forEach(([m,g])=>{const y={...s,...g};typeof(y==null?void 0:y.default)=="function"&&(y.default=y.default()),y!=null&&y.isRequired&&(y==null?void 0:y.default)===void 0&&delete y.default,e.push({type:c.name,name:m,attribute:y})})}),e}function vo(...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,p]=u.split(":").map(m=>m.trim());c.set(f,p)}),a.forEach(u=>{const[f,p]=u.split(":").map(m=>m.trim());c.set(f,p)}),r[o]=Array.from(c.entries()).map(([u,f])=>`${u}: ${f}`).join("; ")}else r[o]=s}),r},{})}function ia(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)=>vo(n,r),{})}function TA(t){return typeof t!="string"?t:t.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(t):t==="true"?!0:t==="false"?!1:t}function Oy(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):TA(n.getAttribute(i.name));return a==null?s:{...s,[i.name]:a}},{});return{...r,...o}}}}function Iy(t){return Object.fromEntries(Object.entries(t).filter(([e,n])=>e==="attrs"&&EA(n)?!1:n!=null))}function Py(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 Ry(t,e){var n;const r=By(t),{nodeExtensions:o,markExtensions:s}=wo(t),i=(n=o.find(c=>U(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},p=t.reduce((w,v)=>{const b=U(v,"extendNodeSchema",f);return{...w,...b?b(c):{}}},{}),m=Iy({...p,content:ke(U(c,"content",f)),marks:ke(U(c,"marks",f)),group:ke(U(c,"group",f)),inline:ke(U(c,"inline",f)),atom:ke(U(c,"atom",f)),selectable:ke(U(c,"selectable",f)),draggable:ke(U(c,"draggable",f)),code:ke(U(c,"code",f)),whitespace:ke(U(c,"whitespace",f)),linebreakReplacement:ke(U(c,"linebreakReplacement",f)),defining:ke(U(c,"defining",f)),isolating:ke(U(c,"isolating",f)),attrs:Object.fromEntries(u.map(Py))}),g=ke(U(c,"parseHTML",f));g&&(m.parseDOM=g.map(w=>Oy(w,u)));const y=U(c,"renderHTML",f);y&&(m.toDOM=w=>y({node:w,HTMLAttributes:ia(w,u)}));const k=U(c,"renderText",f);return k&&(m.toText=k),[c.name,m]})),l=Object.fromEntries(s.map(c=>{const u=r.filter(k=>k.type===c.name),f={name:c.name,options:c.options,storage:c.storage,editor:e},p=t.reduce((k,w)=>{const v=U(w,"extendMarkSchema",f);return{...k,...v?v(c):{}}},{}),m=Iy({...p,inclusive:ke(U(c,"inclusive",f)),excludes:ke(U(c,"excludes",f)),group:ke(U(c,"group",f)),spanning:ke(U(c,"spanning",f)),code:ke(U(c,"code",f)),attrs:Object.fromEntries(u.map(Py))}),g=ke(U(c,"parseHTML",f));g&&(m.parseDOM=g.map(k=>Oy(k,u)));const y=U(c,"renderHTML",f);return y&&(m.toDOM=k=>y({mark:k,HTMLAttributes:ia(k,u)})),[c.name,m]}));return new um({topNode:i,nodes:a,marks:l})}function MA(t){const e=t.filter((n,r)=>t.indexOf(n)!==r);return Array.from(new Set(e))}function Ts(t){return t.sort((n,r)=>{const o=U(n,"priority")||100,s=U(r,"priority")||100;return o>s?-1:o<s?1:0})}function fd(t){const e=Ts(ud(t)),n=MA(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 Dy(t,e){const n=fd(t);return Ry(n,e)}function aa(t,e){const n=Dy(e),r=an.fromJSON(n,t);return sa(r.content,n)}function jn(t,e){const n=Dy(e),r=xs(t);return ln.fromSchema(n).parse(r).toJSON()}function zy(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 p;l.isBlock&&c>r&&(a+=s);const m=i==null?void 0:i[l.type.name];if(m)return u&&(a+=m({node:l,pos:c,parent:u,index:f,range:e})),!1;l.isText&&(a+=(p=l==null?void 0:l.text)==null?void 0:p.slice(Math.max(r,c)-c,o-c))}),a}function AA(t,e){const n={from:0,to:t.content.size};return zy(t,n,e)}function $y(t){return Object.fromEntries(Object.entries(t.nodes).filter(([,e])=>e.spec.toText).map(([e,n])=>[e,n.spec.toText]))}function NA(t,e){const n=ze(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 BA(t,e){const n=oa(typeof e=="string"?e:e.name,t.schema);return n==="node"?NA(t,e):n==="mark"?Ay(t,e):{}}function OA(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 IA(t){const e=OA(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 PA(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),p=e.invert().map(u);r.push({oldRange:{from:f,to:p},newRange:{from:c,to:u}})})}),IA(r)}function Vy(t,e,n){const r=[];return t===e?n.resolve(t).marks().forEach(o=>{const s=n.resolve(t),i=ld(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 Ms(t,e){return e.nodes[t]||e.marks[t]||null}function la(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 RA=(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 hd(t,e,n={}){const{empty:r,ranges:o}=t.selection,s=e?pn(e,t.schema):null;if(r)return!!(t.storedMarks||t.selection.$from.marks()).filter(f=>s?s.name===f.type.name:!0).find(f=>na(f.attrs,n,{strict:!1}));let i=0;const a=[];if(o.forEach(({$from:f,$to:p})=>{const m=f.pos,g=p.pos;t.doc.nodesBetween(m,g,(y,k)=>{if(s&&y.inlineContent&&!y.type.allowsMarkType(s))return!1;if(!y.isText&&!y.marks.length)return;const w=Math.max(m,k),v=Math.min(g,k+y.nodeSize),b=v-w;i+=b,a.push(...y.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=>na(f.mark.attrs,n,{strict:!1})).reduce((f,p)=>f+p.to-p.from,0),c=a.filter(f=>s?f.mark.type!==s&&f.mark.type.excludes(s):!0).reduce((f,p)=>f+p.to-p.from,0);return(l>0?l+c:l)>=i}function DA(t,e,n={}){if(!e)return Es(t,null,n)||hd(t,null,n);const r=oa(e,t.schema);return r==="node"?Es(t,e,n):r==="mark"?hd(t,e,n):!1}function Ly(t,e){return Array.isArray(e)?e.some(n=>(typeof n=="string"?n:n.name)===t.name):e}function Fy(t,e){const{nodeExtensions:n}=wo(e),r=n.find(i=>i.name===t);if(!r)return!1;const o={name:r.name,options:r.options,storage:r.storage},s=ke(U(r,"group",o));return typeof s!="string"?!1:s.split(" ").includes("list")}function ca(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&&(ca(s,{ignoreWhitespace:n,checkChildren:e})||(o=!1))}),o}return!1}function zA(t){return t instanceof G}var jy=class Uk{constructor(e){this.position=e}static fromJSON(e){return new Uk(e.position)}toJSON(){return{position:this.position}}};function $A(t,e){const n=e.mapping.mapResult(t.position);return{position:new jy(n.pos),mapResult:n}}function VA(t){return new jy(t)}function LA(t,e,n){var r;const{selection:o}=e;let s=null;if(Cy(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,p)=>{if(c)return!1;if(u.isInline){const m=!p||p.type.allowsMarkType(n),g=!!n.isInSet(u.marks)||!u.marks.some(y=>y.type.excludes(n));c=m&&g}return!c}),c})}var FA=(t,e={})=>({tr:n,state:r,dispatch:o})=>{const{selection:s}=n,{empty:i,ranges:a}=s,l=pn(t,r.schema);if(o)if(i){const c=Ay(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,(p,m)=>{const g=Math.max(m,u),y=Math.min(m+p.nodeSize,f);p.marks.find(w=>w.type===l)?p.marks.forEach(w=>{l===w.type&&n.addMark(g,y,l.create({...w.attrs,...e}))}):n.addMark(g,y,l.create(e))})});return LA(r,n,l)},jA=(t,e)=>({tr:n})=>(n.setMeta(t,e),!0),HA=(t,e={})=>({state:n,dispatch:r,chain:o})=>{const s=ze(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})=>og(s,{...i,...e})(n)?!0:a.clearNodes()).command(({state:a})=>og(s,{...i,...e})(a,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},WA=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,o=Er(t,0,r.content.size),s=G.create(r,o);e.setSelection(s)}return!0},ZA=(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},UA=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,{from:o,to:s}=typeof t=="number"?{from:t,to:t}:t,i=re.atStart(r).from,a=re.atEnd(r).to,l=Er(o,i,a),c=Er(s,i,a),u=re.create(r,l,c);e.setSelection(u)}return!0},KA=t=>({state:e,dispatch:n})=>{const r=ze(t,e.schema);return FT(r)(e,n)};function Hy(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 JA=({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=la(c,a.node().type.name,a.node().attrs);if(s instanceof G&&s.node.isBlock)return!a.parentOffset||!cn(i,a.pos)?!1:(r&&(t&&Hy(n,o.extensionManager.splittableMarks),e.split(a.pos).scrollIntoView()),!0);if(!a.parent.isBlock)return!1;const f=l.parentOffset===l.parent.content.size,p=a.depth===0?void 0:xA(a.node(-1).contentMatchAt(a.indexAfter(-1)));let m=f&&p?[{type:p,attrs:u}]:void 0,g=cn(e.doc,e.mapping.map(a.pos),1,m);if(!m&&!g&&cn(e.doc,e.mapping.map(a.pos),1,p?[{type:p}]:void 0)&&(g=!0,m=p?[{type:p,attrs:u}]:void 0),r){if(g&&(s instanceof re&&e.deleteSelection(),e.split(e.mapping.map(a.pos),1,m),p&&!f&&!a.parentOffset&&a.parent.type!==p)){const y=e.mapping.map(a.before()),k=e.doc.resolve(y);a.node(-1).canReplaceWith(k.index(),k.index()+1,p)&&e.setNodeMarkup(e.mapping.map(a.before()),p)}t&&Hy(n,o.extensionManager.splittableMarks),e.scrollIntoView()}return g},qA=(t,e={})=>({tr:n,state:r,dispatch:o,editor:s})=>{var i;const a=ze(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 p=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=B.empty;const v=l.index(-1)?1:l.index(-2)?2:3;for(let T=l.depth-v;T>=l.depth-3;T-=1)w=B.from(l.node(T).copy(w));const b=l.indexAfter(-1)<l.node(-2).childCount?1:l.indexAfter(-2)<l.node(-3).childCount?2:3,S={...la(p,l.node().type.name,l.node().attrs),...e},C=((i=a.contentMatch.defaultType)==null?void 0:i.createAndFill(S))||void 0;w=w.append(B.from(a.createAndFill(null,C)||void 0));const x=l.before(l.depth-(v-1));n.replace(x,l.after(-b),new L(w,4-v,0));let _=-1;n.doc.nodesBetween(x,n.doc.content.size,(T,N)=>{if(_>-1)return!1;T.isTextblock&&T.content.size===0&&(_=N+1)}),_>-1&&n.setSelection(re.near(n.doc.resolve(_))),n.scrollIntoView()}return!0}const m=c.pos===l.end()?f.contentMatchAt(0).defaultType:null,g={...la(p,f.type.name,f.attrs),...e},y={...la(p,l.node().type.name,l.node().attrs),...e};n.delete(l.pos,c.pos);const k=m?[{type:a,attrs:g},{type:m,attrs:y}]:[{type:a,attrs:g}];if(!cn(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,k).scrollIntoView(),!S||!o)return!0;const C=S.filter(x=>b.includes(x.type.name));n.ensureMarks(C)}return!0},pd=(t,e)=>{const n=dd(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)&&kr(t.doc,n.pos)&&t.join(n.pos),!0},md=(t,e)=>{const n=dd(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)&&kr(t.doc,r)&&t.join(r),!0},GA=(t,e,n,r={})=>({editor:o,tr:s,state:i,dispatch:a,chain:l,commands:c,can:u})=>{const{extensions:f,splittableMarks:p}=o.extensionManager,m=ze(t,i.schema),g=ze(e,i.schema),{selection:y,storedMarks:k}=i,{$from:w,$to:v}=y,b=w.blockRange(v),S=k||y.$to.parentOffset&&y.$from.marks();if(!b)return!1;const C=dd(x=>Fy(x.type.name,f))(y);if(b.depth>=1&&C&&b.depth-C.depth<=1){if(C.node.type===m)return c.liftListItem(g);if(Fy(C.node.type.name,f)&&m.validContent(C.node.content)&&a)return l().command(()=>(s.setNodeMarkup(C.pos,m),!0)).command(()=>pd(s,m)).command(()=>md(s,m)).run()}return!n||!S||!a?l().command(()=>u().wrapInList(m,r)?!0:c.clearNodes()).wrapInList(m,r).command(()=>pd(s,m)).command(()=>md(s,m)).run():l().command(()=>{const x=u().wrapInList(m,r),_=S.filter(T=>p.includes(T.type.name));return s.ensureMarks(_),x?!0:c.clearNodes()}).wrapInList(m,r).command(()=>pd(s,m)).command(()=>md(s,m)).run()},YA=(t,e={},n={})=>({state:r,commands:o})=>{const{extendEmptyMarkRange:s=!1}=n,i=pn(t,r.schema);return hd(r,i,e)?o.unsetMark(i,{extendEmptyMarkRange:s}):o.setMark(i,e)},XA=(t,e,n={})=>({state:r,commands:o})=>{const s=ze(t,r.schema),i=ze(e,r.schema),a=Es(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})},QA=(t,e={})=>({state:n,commands:r})=>{const o=ze(t,n.schema);return Es(n,o,e)?r.lift(o):r.wrapIn(o,e)},eN=()=>({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},tN=()=>({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},nN=(t,e={})=>({tr:n,state:r,dispatch:o})=>{var s;const{extendEmptyMarkRange:i=!1}=e,{selection:a}=n,l=pn(t,r.schema),{$from:c,empty:u,ranges:f}=a;if(!o)return!0;if(u&&i){let{from:p,to:m}=a;const g=(s=c.marks().find(k=>k.type===l))==null?void 0:s.attrs,y=ld(c,l,g);y&&(p=y.from,m=y.to),n.removeMark(p,m,l)}else f.forEach(p=>{n.removeMark(p.$from.pos,p.$to.pos,l)});return n.removeStoredMark(l),!0},rN=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},oN=(t,e={})=>({tr:n,state:r,dispatch:o})=>{let s=null,i=null;const a=oa(typeof t=="string"?t:t.name,r.schema);if(!a)return!1;a==="node"&&(s=ze(t,r.schema)),a==="mark"&&(i=pn(t,r.schema));let l=!1;return n.selection.ranges.forEach(c=>{const u=c.$from.pos,f=c.$to.pos;let p,m,g,y;n.selection.empty?r.doc.nodesBetween(u,f,(k,w)=>{s&&s===k.type&&(l=!0,g=Math.max(w,u),y=Math.min(w+k.nodeSize,f),p=w,m=k)}):r.doc.nodesBetween(u,f,(k,w)=>{w<u&&s&&s===k.type&&(l=!0,g=Math.max(w,u),y=Math.min(w+k.nodeSize,f),p=w,m=k),w>=u&&w<=f&&(s&&s===k.type&&(l=!0,o&&n.setNodeMarkup(w,void 0,{...k.attrs,...e})),i&&k.marks.length&&k.marks.forEach(v=>{if(i===v.type&&(l=!0,o)){const b=Math.max(w,u),S=Math.min(w+k.nodeSize,f);n.addMark(b,S,i.create({...v.attrs,...e}))}}))}),m&&(p!==void 0&&o&&n.setNodeMarkup(p,void 0,{...m.attrs,...e}),i&&m.marks.length&&m.marks.forEach(k=>{i===k.type&&o&&n.addMark(g,y,i.create({...k.attrs,...e}))}))}),l},sN=(t,e={})=>({state:n,dispatch:r})=>{const o=ze(t,n.schema);return PT(o,e)(n,r)},iN=(t,e={})=>({state:n,dispatch:r})=>{const o=ze(t,n.schema);return RT(o,e)(n,r)},aN=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={}}},lN=class{constructor(t){var e;this.find=t.find,this.handler=t.handler,this.undoable=(e=t.undoable)!=null?e:!0}},cN=(t,e)=>{if(ad(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 da(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(p=>p.type.spec.code))return!1;let u=!1;const f=RA(c)+s;return i.forEach(p=>{if(u)return;const m=cN(f,p.find);if(!m)return;const g=l.state.tr,y=ea({state:l.state,transaction:g}),k={from:r-(m[0].length-s.length),to:o},{commands:w,chain:v,can:b}=new ta({editor:n,state:y});p.handler({state:y,range:k,match:m,commands:w,chain:v,can:b})===null||!g.steps.length||(p.undoable&&g.setMeta(a,{transform:g,from:r,to:o,text:s}),l.dispatch(g),u=!0)}),u}function dN(t){const{editor:e,rules:n}=t,r=new Oe({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=sa(B.from(u),i.schema);const{from:f}=l,p=f+u.length;da({editor:e,from:f,to:p,text:u,rules:n,plugin:r})}),o.selectionSet||o.docChanged?null:s}},props:{handleTextInput(o,s,i,a){return da({editor:e,from:s,to:i,text:a,rules:n,plugin:r})},handleDOMEvents:{compositionend:o=>(setTimeout(()=>{const{$cursor:s}=o.state.selection;s&&da({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?da({editor:e,from:i.pos,to:i.pos,text:`
81
+ `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function uN(t){return Object.prototype.toString.call(t).slice(8,-1)}function ua(t){return uN(t)!=="Object"?!1:t.constructor===Object&&Object.getPrototypeOf(t)===Object.prototype}function Wy(t,e){const n={...t};return ua(t)&&ua(e)&&Object.keys(e).forEach(r=>{ua(e[r])&&ua(t[r])?n[r]=Wy(t[r],e[r]):n[r]=e[r]}),n}var gd=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{...ke(U(this,"addOptions",{name:this.name}))||{}}}get storage(){return{...ke(U(this,"addStorage",{name:this.name,options:this.options}))||{}}}configure(t={}){const e=this.extend({...this.config,addOptions:()=>Wy(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}},As=class Kk extends gd{constructor(){super(...arguments),this.type="mark"}static create(e={}){const n=typeof e=="function"?e():e;return new Kk(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 fN(t){return typeof t=="number"}var hN=class{constructor(t){this.find=t.find,this.handler=t.handler}},pN=(t,e,n)=>{if(ad(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 mN(t){const{editor:e,state:n,from:r,to:o,rule:s,pasteEvent:i,dropEvent:a}=t,{commands:l,chain:c,can:u}=new ta({editor:e,state:n}),f=[];return n.doc.nodesBetween(r,o,(m,g)=>{var y,k,w,v,b;if((k=(y=m.type)==null?void 0:y.spec)!=null&&k.code||!(m.isText||m.isTextblock||m.isInline))return;const S=(b=(v=(w=m.content)==null?void 0:w.size)!=null?v:m.nodeSize)!=null?b:0,C=Math.max(r,g),x=Math.min(o,g+S);if(C>=x)return;const _=m.isText?m.text||"":m.textBetween(C-g,x-g,void 0,"");pN(_,s.find,i).forEach(N=>{if(N.index===void 0)return;const I=C+N.index+1,V=I+N[0].length,K={from:n.tr.mapping.map(I),to:n.tr.mapping.map(V)},M=s.handler({state:n,range:K,match:N,commands:l,chain:c,can:u,pasteEvent:i,dropEvent:a});f.push(M)})}),f.every(m=>m!==null)}var fa=null,gN=t=>{var e;const n=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=n.clipboardData)==null||e.setData("text/html",t),n};function yN(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:p,rule:m,pasteEvt:g})=>{const y=u.tr,k=ea({state:u,transaction:y});if(!(!mN({editor:e,state:k,from:Math.max(f-1,0),to:p.b-1,rule:m,pasteEvent:g,dropEvent:a})||!y.steps.length)){try{a=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{a=null}return i=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,y}};return n.map(u=>new Oe({view(f){const p=g=>{var y;r=(y=f.dom.parentElement)!=null&&y.contains(g.target)?f.dom.parentElement:null,r&&(fa=e)},m=()=>{fa&&(fa=null)};return window.addEventListener("dragstart",p),window.addEventListener("dragend",m),{destroy(){window.removeEventListener("dragstart",p),window.removeEventListener("dragend",m)}}},props:{handleDOMEvents:{drop:(f,p)=>{if(s=r===f.dom.parentElement,a=p,!s){const m=fa;m!=null&&m.isEditable&&setTimeout(()=>{const g=m.state.selection;g&&m.commands.deleteRange({from:g.from,to:g.to})},10)}return!1},paste:(f,p)=>{var m;const g=(m=p.clipboardData)==null?void 0:m.getData("text/html");return i=p,o=!!(g!=null&&g.includes("data-pm-slice")),!1}}},appendTransaction:(f,p,m)=>{const g=f[0],y=g.getMeta("uiEvent")==="paste"&&!o,k=g.getMeta("uiEvent")==="drop"&&!s,w=g.getMeta("applyPasteRules"),v=!!w;if(!y&&!k&&!v)return;if(v){let{text:C}=w;typeof C=="string"?C=C:C=sa(B.from(C),m.schema);const{from:x}=w,_=x+C.length,T=gN(C);return l({rule:u,state:m,from:x,to:{b:_},pasteEvt:T})}const b=p.doc.content.findDiffStart(m.doc.content),S=p.doc.content.findDiffEnd(m.doc.content);if(!(!fN(b)||!S||b===S.b))return l({rule:u,state:m,from:b,to:S,pasteEvt:i})}}))}var ha=class{constructor(t,e){this.splittableMarks=[],this.editor=e,this.baseExtensions=t,this.extensions=fd(t),this.schema=Ry(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:Ms(e.name,this.schema)},r=U(e,"addCommands",n);return r?{...t,...r()}:t},{})}get plugins(){const{editor:t}=this;return Ts([...this.extensions].reverse()).flatMap(r=>{const o={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:t,type:Ms(r.name,this.schema)},s=[],i=U(r,"addKeyboardShortcuts",o);let a={};if(r.type==="mark"&&U(r,"exitable",o)&&(a.ArrowRight=()=>As.handleExit({editor:t,mark:r})),i){const p=Object.fromEntries(Object.entries(i()).map(([m,g])=>[m,()=>g({editor:t})]));a={...a,...p}}const l=BM(a);s.push(l);const c=U(r,"addInputRules",o);if(Ly(r,t.options.enableInputRules)&&c){const p=c();if(p&&p.length){const m=dN({editor:t,rules:p}),g=Array.isArray(m)?m:[m];s.push(...g)}}const u=U(r,"addPasteRules",o);if(Ly(r,t.options.enablePasteRules)&&u){const p=u();if(p&&p.length){const m=yN({editor:t,rules:p});s.push(...m)}}const f=U(r,"addProseMirrorPlugins",o);if(f){const p=f();s.push(...p)}return s})}get attributes(){return By(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:e}=wo(this.extensions);return Object.fromEntries(e.filter(n=>!!U(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:ze(n.name,this.schema)},s=U(n,"addNodeView",o);if(!s)return[];const i=s();if(!i)return[];const a=(l,c,u,f,p)=>{const m=ia(l,r);return i({node:l,view:c,getPos:u,decorations:f,innerDecorations:p,editor:t,extension:n,HTMLAttributes:m})};return[n.name,a]}))}dispatchTransaction(t){const{editor:e}=this;return Ts([...this.extensions].reverse()).reduceRight((r,o)=>{const s={name:o.name,options:o.options,storage:this.editor.extensionStorage[o.name],editor:e,type:Ms(o.name,this.schema)},i=U(o,"dispatchTransaction",s);return i?a=>{i.call(s,{transaction:a,next:r})}:r},t)}transformPastedHTML(t){const{editor:e}=this;return Ts([...this.extensions]).reduce((r,o)=>{const s={name:o.name,options:o.options,storage:this.editor.extensionStorage[o.name],editor:e,type:Ms(o.name,this.schema)},i=U(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}=wo(this.extensions);return Object.fromEntries(e.filter(n=>!!U(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:pn(n.name,this.schema)},s=U(n,"addMarkView",o);if(!s)return[];const i=(a,l,c)=>{const u=ia(a,r);return s()({mark:a,view:l,inline:c,editor:t,extension:n,HTMLAttributes:u,updateAttributes:f=>{BN(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:Ms(e.name,this.schema)};e.type==="mark"&&((n=ke(U(e,"keepOnSplit",r)))==null||n)&&this.splittableMarks.push(e.name);const o=U(e,"onBeforeCreate",r),s=U(e,"onCreate",r),i=U(e,"onUpdate",r),a=U(e,"onSelectionUpdate",r),l=U(e,"onTransaction",r),c=U(e,"onFocus",r),u=U(e,"onBlur",r),f=U(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)})}};ha.resolve=fd,ha.sort=Ts,ha.flatten=ud;var kN={};id(kN,{ClipboardTextSerializer:()=>Zy,Commands:()=>Uy,Delete:()=>Ky,Drop:()=>Jy,Editable:()=>qy,FocusEvents:()=>Yy,Keymap:()=>Xy,Paste:()=>Qy,Tabindex:()=>e0,TextDirection:()=>t0,focusEventsPluginKey:()=>Gy});var be=class Jk extends gd{constructor(){super(...arguments),this.type="extension"}static create(e={}){const n=typeof e=="function"?e():e;return new Jk(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}},Zy=be.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new Oe({key:new Qe("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=$y(n);return zy(r,{from:i,to:a},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:l})}}})]}}),Uy=be.create({name:"commands",addCommands(){return{...vy}}}),Ky=be.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=CA(t.before,[t,...e]);PA(u).forEach(m=>{u.mapping.mapResult(m.oldRange.from).deletedAfter&&u.mapping.mapResult(m.oldRange.to).deletedBefore&&u.before.nodesBetween(m.oldRange.from,m.oldRange.to,(g,y)=>{const k=y+g.nodeSize-2,w=m.oldRange.from<=y&&k<=m.oldRange.to;this.editor.emit("delete",{type:"node",node:g,from:y,to:k,newFrom:u.mapping.map(y),newTo:u.mapping.map(k),deletedRange:m.oldRange,newRange:m.newRange,partial:!w,editor:this.editor,transaction:t,combinedTransform:u})})});const p=u.mapping;u.steps.forEach((m,g)=>{var y,k;if(m instanceof Bt){const w=p.slice(g).map(m.from,-1),v=p.slice(g).map(m.to),b=p.invert().map(w,-1),S=p.invert().map(v),C=(y=u.doc.nodeAt(w-1))==null?void 0:y.marks.some(_=>_.eq(m.mark)),x=(k=u.doc.nodeAt(v))==null?void 0:k.marks.some(_=>_.eq(m.mark));this.editor.emit("delete",{type:"mark",mark:m.mark,from:m.from,to:m.to,deletedRange:{from:b,to:S},newRange:{from:w,to:v},partial:!!(x||C),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()}}),Jy=be.create({name:"drop",addProseMirrorPlugins(){return[new Oe({key:new Qe("tiptapDrop"),props:{handleDrop:(t,e,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:n,moved:r})}}})]}}),qy=be.create({name:"editable",addProseMirrorPlugins(){return[new Oe({key:new Qe("editable"),props:{editable:()=>this.editor.options.editable}})]}}),Gy=new Qe("focusEvents"),Yy=be.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:t}=this;return[new Oe({key:Gy,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}}}})]}}),Xy=be.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:p,parent:m}=f,g=f.parent.isTextblock&&p>0?a.doc.resolve(p-1):f,y=g.parent.type.spec.isolating,k=f.pos-f.parentOffset,w=y&&g.parent.childCount===1?k===f.pos:ie.atStart(c).from===p;return!u||!m.type.isTextblock||m.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 ra()||Ty()?s:o},addProseMirrorPlugins(){return[new Oe({key:new Qe("clearDocument"),appendTransaction:(t,e,n)=>{if(t.some(y=>y.getMeta("composition")))return;const r=t.some(y=>y.docChanged)&&!e.doc.eq(n.doc),o=t.some(y=>y.getMeta("preventClearDocument"));if(!r||o)return;const{empty:s,from:i,to:a}=e.selection,l=ie.atStart(e.doc).from,c=ie.atEnd(e.doc).to;if(s||!(i===l&&a===c)||!ca(n.doc))return;const p=n.tr,m=ea({state:n,transaction:p}),{commands:g}=new ta({editor:this.editor,state:m});if(g.clearNodes(),!!p.steps.length)return p}})]}}),Qy=be.create({name:"paste",addProseMirrorPlugins(){return[new Oe({key:new Qe("tiptapPaste"),props:{handlePaste:(t,e,n)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:n})}}})]}}),e0=be.create({name:"tabindex",addProseMirrorPlugins(){return[new Oe({key:new Qe("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}}),t0=be.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:t}=wo(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 Oe({key:new Qe("textDirection"),props:{attributes:()=>{const t=this.options.direction;return t?{dir:t}:{}}}})]}}),wN=class $s{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 $s(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 $s(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 $s(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 $s(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)}},vN=`.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 O4(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 D4=class extends k4{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:J$,createMappablePosition:X$},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=i1(n,this.options.autofocus);this.editorState=Bi.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=O4(P4,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=f1(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?[N1,T1.configure({blockSeparator:(n=(e=this.options.coreExtensionOptions)==null?void 0:e.clipboardTextSerializer)==null?void 0:n.blockSeparator}),M1,P1,O1,R1,I1,D1,A1,z1.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 du(o,this)}createCommandManager(){this.commandManager=new Qc({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let e;try{e=Ph(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=Ph(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 qk(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 W$(this.state,e)}isActive(e,n){const r=typeof e=="string"?e:null,o=typeof e=="string"?n:e;return q$(this.state,r,o)}getJSON(){return this.state.doc.toJSON()}getHTML(){return ru(this.state.doc.content,this.schema)}getText(e){const{blockSeparator:n=`
151
+ }`;function bN(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 SN=class extends aN{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:$A,createMappablePosition:VA},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=xy(n,this.options.autofocus);this.editorState=uo.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=bN(vN,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=Ny(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?[qy,Zy.configure({blockSeparator:(n=(e=this.options.coreExtensionOptions)==null?void 0:e.clipboardTextSerializer)==null?void 0:n.blockSeparator}),Uy,Yy,Xy,e0,Jy,Qy,Ky,t0.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 ha(o,this)}createCommandManager(){this.commandManager=new ta({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let e;try{e=cd(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=cd(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 hy(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 BA(this.state,e)}isActive(e,n){const r=typeof e=="string"?e:null,o=typeof e=="string"?n:e;return DA(this.state,r,o)}getJSON(){return this.state.doc.toJSON()}getHTML(){return sa(this.state.doc.content,this.schema)}getText(e){const{blockSeparator:n=`
152
152
 
153
- `,textSerializers:r={}}=e||{};return j$(this.state.doc,{blockSeparator:n,textSerializers:{...k1(this.schema),...r}})}get isEmpty(){return au(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 B4(n,this)}get $doc(){return this.$pos(0)}};function fu(t){return new b4({find:t.find,handler:({state:e,range:n,match:r})=>{const o=je(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(b1(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 R4={};Ih(R4,{createAtomBlockMarkdownSpec:()=>z4,createBlockMarkdownSpec:()=>$4,createInlineMarkdownSpec:()=>F4,parseAttributes:()=>Fh,parseIndentedBlocks:()=>j4,renderNestedMarkdownContent:()=>U4,serializeAttributes:()=>jh});function Fh(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 jh(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 z4(t){const{nodeName:e,name:n,parseAttributes:r=Fh,serializeAttributes:o=jh,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 $4(t){const{nodeName:e,name:n,getContent:r,parseAttributes:o=Fh,serializeAttributes:s=jh,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,T=f.slice(k);for(_.lastIndex=0;;){const I=_.exec(T);if(I===null)break;const B=I.index,L=I[1];if(!((m=I[2])!=null&&m.endsWith(":::"))){if(L)S+=1;else if(S-=1,S===0){const Z=T.slice(0,B);E=Z.trim();const M=f.slice(0,k+B+I[0].length);let F=[];if(E)if(a==="block")for(F=p.blockTokens(Z),F.forEach(q=>{q.text&&(!q.tokens||q.tokens.length===0)&&(q.tokens=p.inlineTokens(q.text))});F.length>0;){const q=F[F.length-1];if(q.type==="paragraph"&&(!q.text||q.text.trim()===""))F.pop();else break}else F=p.inlineTokens(E);return{type:e,raw:M,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||[],`
153
+ `,textSerializers:r={}}=e||{};return AA(this.state.doc,{blockSeparator:n,textSerializers:{...$y(this.schema),...r}})}get isEmpty(){return ca(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 wN(n,this)}get $doc(){return this.$pos(0)}};function pa(t){return new lN({find:t.find,handler:({state:e,range:n,match:r})=>{const o=ke(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(Vy(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>c).length)return null;u<n.to&&s.delete(u,n.to),c>n.from&&s.delete(n.from+l,c);const p=n.from+l+i.length;s.addMark(n.from+l,p,t.type.create(o||{})),s.removeStoredMark(t.type)}},undoable:t.undoable})}var CN={};id(CN,{createAtomBlockMarkdownSpec:()=>xN,createBlockMarkdownSpec:()=>_N,createInlineMarkdownSpec:()=>MN,parseAttributes:()=>yd,parseIndentedBlocks:()=>AN,renderNestedMarkdownContent:()=>NN,serializeAttributes:()=>kd});function yd(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 p=parseInt(((f=u.match(/__QUOTED_(\d+)__/))==null?void 0:f[1])||"0",10),m=n[p];m&&(e[c]=m.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 kd(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 xN(t){const{nodeName:e,name:n,parseAttributes:r=yd,serializeAttributes:o=kd,defaultAttributes:s={},requiredAttributes:i=[],allowedAttributes:a}=t,l=n||e,c=u=>{if(!a)return u;const f={};return a.forEach(p=>{p in u&&(f[p]=u[p])}),f};return{parseMarkdown:(u,f)=>{const p={...s,...u.attributes};return f.createNode(e,p,[])},markdownTokenizer:{name:e,level:"block",start(u){var f;const p=new RegExp(`^:::${l}(?:\\s|$)`,"m"),m=(f=u.match(p))==null?void 0:f.index;return m!==void 0?m:-1},tokenize(u,f,p){const m=new RegExp(`^:::${l}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`),g=u.match(m);if(!g)return;const y=g[1]||"",k=r(y);if(!i.find(v=>!(v in k)))return{type:e,raw:g[0],attributes:k}}},renderMarkdown:u=>{const f=c(u.attrs||{}),p=o(f),m=p?` {${p}}`:"";return`:::${l}${m} :::`}}}function _N(t){const{nodeName:e,name:n,getContent:r,parseAttributes:o=yd,serializeAttributes:s=kd,defaultAttributes:i={},content:a="block",allowedAttributes:l}=t,c=n||e,u=f=>{if(!l)return f;const p={};return l.forEach(m=>{m in f&&(p[m]=f[m])}),p};return{parseMarkdown:(f,p)=>{let m;if(r){const y=r(f);m=typeof y=="string"?[{type:"text",text:y}]:y}else a==="block"?m=p.parseChildren(f.tokens||[]):m=p.parseInline(f.tokens||[]);const g={...i,...f.attributes};return p.createNode(e,g,m)},markdownTokenizer:{name:e,level:"block",start(f){var p;const m=new RegExp(`^:::${c}`,"m"),g=(p=f.match(m))==null?void 0:p.index;return g!==void 0?g:-1},tokenize(f,p,m){var g;const y=new RegExp(`^:::${c}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),k=f.match(y);if(!k)return;const[w,v=""]=k,b=o(v);let S=1;const C=w.length;let x="";const _=/^:::([\w-]*)(\s.*)?/gm,T=f.slice(C);for(_.lastIndex=0;;){const N=_.exec(T);if(N===null)break;const I=N.index,V=N[1];if(!((g=N[2])!=null&&g.endsWith(":::"))){if(V)S+=1;else if(S-=1,S===0){const K=T.slice(0,I);x=K.trim();const M=f.slice(0,C+I+N[0].length);let $=[];if(x)if(a==="block")for($=m.blockTokens(K),$.forEach(Z=>{Z.text&&(!Z.tokens||Z.tokens.length===0)&&(Z.tokens=m.inlineTokens(Z.text))});$.length>0;){const Z=$[$.length-1];if(Z.type==="paragraph"&&(!Z.text||Z.text.trim()===""))$.pop();else break}else $=m.inlineTokens(x);return{type:e,raw:M,attributes:b,content:x,tokens:$}}}}}},renderMarkdown:(f,p)=>{const m=u(f.attrs||{}),g=s(m),y=g?` {${g}}`:"",k=p.renderChildren(f.content||[],`
154
154
 
155
- `);return`:::${c}${g}
155
+ `);return`:::${c}${y}
156
156
 
157
- ${y}
157
+ ${k}
158
158
 
159
- :::`}}}function L4(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 V4(t){return Object.entries(t).filter(([,e])=>e!=null).map(([e,n])=>`${e}="${n}"`).join(" ")}function F4(t){const{nodeName:e,name:n,getContent:r,parseAttributes:o=L4,serializeAttributes:s=V4,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 j4(t,e,n){var r,o,s,i;const a=t.split(`
160
- `),l=[];let c="",u=0;const f=e.baseIndentSize||2;for(;u<a.length;){const h=a[u],p=h.match(e.itemPattern);if(!p){if(l.length>0)break;if(h.trim()===""){u+=1,c=`${c}${h}
161
- `;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 k=a[u];if(k.trim()===""){const _=a.slice(u+1).findIndex(B=>B.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 U4(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
- `).map(h=>h?e.indent(h):"").join(`
159
+ :::`}}}function EN(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 TN(t){return Object.entries(t).filter(([,e])=>e!=null).map(([e,n])=>`${e}="${n}"`).join(" ")}function MN(t){const{nodeName:e,name:n,getContent:r,parseAttributes:o=EN,serializeAttributes:s=TN,defaultAttributes:i={},selfClosing:a=!1,allowedAttributes:l}=t,c=n||e,u=p=>{if(!l)return p;const m={};return l.forEach(g=>{const y=typeof g=="string"?g:g.name,k=typeof g=="string"?void 0:g.skipIfDefault;if(y in p){const w=p[y];if(k!==void 0&&w===k)return;m[y]=w}}),m},f=c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{parseMarkdown:(p,m)=>{const g={...i,...p.attributes};if(a)return m.createNode(e,g);const y=r?r(p):p.content||"";return y?m.createNode(e,g,[m.createTextNode(y)]):m.createNode(e,g,[])},markdownTokenizer:{name:e,level:"inline",start(p){const m=a?new RegExp(`\\[${f}\\s*[^\\]]*\\]`):new RegExp(`\\[${f}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${f}\\]`),g=p.match(m),y=g==null?void 0:g.index;return y!==void 0?y:-1},tokenize(p,m,g){const y=a?new RegExp(`^\\[${f}\\s*([^\\]]*)\\]`):new RegExp(`^\\[${f}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${f}\\]`),k=p.match(y);if(!k)return;let w="",v="";if(a){const[,S]=k;v=S}else{const[,S,C]=k;v=S,w=C||""}const b=o(v.trim());return{type:e,raw:k[0],content:w.trim(),attributes:b}}},renderMarkdown:p=>{let m="";r?m=r(p):p.content&&p.content.length>0&&(m=p.content.filter(w=>w.type==="text").map(w=>w.text).join(""));const g=u(p.attrs||{}),y=s(g),k=y?` ${y}`:"";return a?`[${c}${k}]`:`[${c}${k}]${m}[/${c}]`}}}function AN(t,e,n){var r,o,s,i;const a=t.split(`
160
+ `),l=[];let c="",u=0;const f=e.baseIndentSize||2;for(;u<a.length;){const p=a[u],m=p.match(e.itemPattern);if(!m){if(l.length>0)break;if(p.trim()===""){u+=1,c=`${c}${p}
161
+ `;continue}else return}const g=e.extractItemData(m),{indentLevel:y,mainContent:k}=g;c=`${c}${p}
162
+ `;const w=[k];for(u+=1;u<a.length;){const C=a[u];if(C.trim()===""){const _=a.slice(u+1).findIndex(I=>I.trim()!=="");if(_===-1)break;if((((o=(r=a[u+1+_].match(/^(\s*)/))==null?void 0:r[1])==null?void 0:o.length)||0)>y){w.push(C),c=`${c}${C}
163
+ `,u+=1;continue}else break}if((((i=(s=C.match(/^(\s*)/))==null?void 0:s[1])==null?void 0:i.length)||0)>y)w.push(C),c=`${c}${C}
164
+ `,u+=1;else break}let v;const b=w.slice(1);if(b.length>0){const C=b.map(x=>x.slice(y+f)).join(`
165
+ `);C.trim()&&(e.customNestedParser?v=e.customNestedParser(C):v=n.blockTokens(C))}const S=e.createToken(g,v);l.push(S)}if(l.length!==0)return{items:l,raw:c}}function NN(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
+ `).map(p=>p?e.indent(p):"").join(`
167
167
  `);l.push(f)}}),l.join(`
168
- `)}function W4(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 Uh=class _S extends Vh{constructor(){super(...arguments),this.type="node"}static create(e={}){const n=typeof e=="function"?e():e;return new _S(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}};function hu(t){return new x4({find:t.find,handler:({state:e,range:n,match:r,pasteEvent:o})=>{const s=je(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(b1(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 $1(t){return d.customRef((e,n)=>({get(){return e(),t},set(r){t=r,requestAnimationFrame(()=>{requestAnimationFrame(()=>{n()})})}}))}var H4=class extends D4{constructor(t={}){return super(t),this.contentComponent=null,this.appContext=null,this.reactiveState=$1(this.view.state),this.reactiveExtensionStorage=$1(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}},Z4=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 K4=Uh.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,`
168
+ `)}function BN(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(m=>{if(m!==i)return!1;f=m}),!f)return;let p=!1;if(Object.keys(n).forEach(m=>{n[m]!==f.attrs[m]&&(p=!0)}),p){const m=t.type.create({...t.attrs,...n});s.removeMark(c,u,t.type),s.addMark(c,u,m)}}),s.docChanged&&e.view.dispatch(s)}var wd=class qk extends gd{constructor(){super(...arguments),this.type="node"}static create(e={}){const n=typeof e=="function"?e():e;return new qk(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}};function ma(t){return new hN({find:t.find,handler:({state:e,range:n,match:r,pasteEvent:o})=>{const s=ke(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),p=f+a.length;if(Vy(n.from,n.to,e.doc).filter(g=>g.mark.type.excluded.find(k=>k===t.type&&k!==g.mark.type)).filter(g=>g.to>f).length)return null;p<n.to&&i.delete(p,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 n0(t){return d.customRef((e,n)=>({get(){return e(),t},set(r){t=r,requestAnimationFrame(()=>{requestAnimationFrame(()=>{n()})})}}))}var ON=class extends SN{constructor(t={}){return super(t),this.contentComponent=null,this.appContext=null,this.reactiveState=n0(this.view.state),this.reactiveExtensionStorage=n0(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}},IN=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 PN=wd.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,`
169
169
 
170
- `):""}),L1=K4,V1="&nbsp;",Y4=" ",q4=Uh.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:t}){return["p",Fi(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===V1||r[0].text===Y4)?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?V1:e.renderChildren(n)},addCommands(){return{setParagraph:()=>({commands:t})=>t.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),F1=q4,G4=Uh.create({name:"text",group:"inline",parseMarkdown:t=>({type:"text",text:t.text||""}),renderMarkdown:t=>t.text||""}),j1=G4,U1=(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]},J4=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,X4=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,Q4=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,eL=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,tL=ol.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 U1("strong",{...Fi(this.options.HTMLAttributes,t),children:U1("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[fu({find:J4,type:this.type}),fu({find:Q4,type:this.type})]},addPasteRules(){return[hu({find:X4,type:this.type}),hu({find:eL,type:this.type})]}}),W1=tL,nL=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,rL=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,oL=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,sL=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,iL=ol.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",Fi(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[fu({find:nL,type:this.type}),fu({find:oL,type:this.type})]},addPasteRules(){return[hu({find:rL,type:this.type}),hu({find:sL,type:this.type})]}}),H1=iL,aL=ol.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",Fi(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()}}}),Z1=aL,lL=Ye.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")}}}),K1=lL,cL=20,Y1=(t,e=0)=>{const n=[];return!t.children.length||e>cL||Array.from(t.children).forEach(r=>{r.tagName==="SPAN"?n.push(r):r.children.length&&n.push(...Y1(r,e+1))}),n},uL=t=>{if(!t.children.length)return;const e=Y1(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}`)})},Wh=ol.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!0}},parseHTML(){return[{tag:"span",consuming:!1,getAttrs:t=>t.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&uL(t),{}):!1}]},renderHTML({HTMLAttributes:t}){return["span",Fi(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}}}}),dL=Ye.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()}}}),q1=Ye.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()}}}),fL=Ye.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()}}}),hL=Ye.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()}}}),pL=Ye.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()}}});Ye.create({name:"textStyleKit",addExtensions(){const t=[];return this.options.backgroundColor!==!1&&t.push(dL.configure(this.options.backgroundColor)),this.options.color!==!1&&t.push(q1.configure(this.options.color)),this.options.fontFamily!==!1&&t.push(fL.configure(this.options.fontFamily)),this.options.fontSize!==!1&&t.push(hL.configure(this.options.fontSize)),this.options.lineHeight!==!1&&t.push(pL.configure(this.options.lineHeight)),this.options.textStyle!==!1&&t.push(Wh.configure(this.options.textStyle)),t}});var G1=q1;function mL(t={}){return new vt({view(e){return new gL(e,t)}})}class gL{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=pv(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 st extends be{constructor(e){super(e,e)}map(e,n){let r=e.resolve(n.map(this.head));return st.valid(r)?new st(r):be.near(r)}content(){return K.empty}eq(e){return e instanceof st&&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 st(e.resolve(n.pos))}getBookmark(){return new Hh(this.anchor)}static valid(e){let n=e.parent;if(n.isTextblock||!yL(e)||!wL(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&&st.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(st.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(st.valid(a))return a}return null}}}st.prototype.visible=!1,st.findFrom=st.findGapCursorFrom,be.jsonID("gapcursor",st);class Hh{constructor(e){this.pos=e}map(e){return new Hh(e.map(this.pos))}resolve(e){let n=e.resolve(this.pos);return st.valid(n)?new st(n):be.near(n)}}function J1(t){return t.isAtom||t.spec.isolating||t.spec.createGapCursor}function yL(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||J1(o.type))return!0;if(o.inlineContent)return!1}}return!0}function wL(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||J1(o.type))return!0;if(o.inlineContent)return!1}}return!0}function vL(){return new vt({props:{decorations:EL,createSelectionBetween(t,e,n){return e.pos==n.pos&&st.valid(n)?new st(n):null},handleClick:bL,handleKeyDown:kL,handleDOMEvents:{beforeinput:SL}}})}const kL=t1({ArrowLeft:pu("horiz",-1),ArrowRight:pu("horiz",1),ArrowUp:pu("vert",-1),ArrowDown:pu("vert",1)});function pu(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=st.findGapCursorFrom(a,e,l);return c?(o&&o(r.tr.setSelection(new st(c))),!0):!1}}function bL(t,e,n){if(!t||!t.editable)return!1;let r=t.state.doc.resolve(e);if(!st.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 st(r))),!0)}function SL(t,e){if(e.inputType!="insertCompositionText"||!(t.state.selection instanceof st))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 EL(t){if(!(t.selection instanceof st))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 mu=200,Nt=function(){};Nt.prototype.append=function(e){return e.length?(e=Nt.from(e),!this.length&&e||e.length<mu&&this.leafAppend(e)||this.length<mu&&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 CL(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 X1(e):Nt.empty};var X1=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<=mu)return new e(this.values.concat(o.flatten()))},e.prototype.leafPrepend=function(o){if(this.length+o.length<=mu)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 X1([]);var CL=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 _L=500;class or{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 Cr(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 Cr(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 or(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 Cr(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>TL&&(a=xL(a,c),i-=c),new or(a.append(s),i)}remapping(e,n){let r=new La;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 or(this.items.append(e.map(n=>new Cr(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 Cr(m,g,y))}else r.push(new Cr(m))},o);let c=[];for(let h=n;h<i;h++)c.push(new Cr(s.maps[h]));let u=this.items.slice(0,o).append(c).append(r),f=new or(u,a);return f.emptyItemCount()>_L&&(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 Cr(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 or(Nt.from(o.reverse()),s)}}or.empty=new or(Nt.empty,0);function xL(t,e){let n;return t.forEach((r,o)=>{if(r.selection&&e--==0)return n=o,!1}),t.slice(n)}class Cr{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 Cr(n.getMap().invert(),n,this.selection)}}}class Zo{constructor(e,n,r,o,s){this.done=e,this.undone=n,this.prevRanges=r,this.prevTime=o,this.prevComposition=s}}const TL=20;function ML(t,e,n,r){let o=n.getMeta(Rs),s;if(o)return o.historyState;n.getMeta(NL)&&(t=new Zo(t.done,t.undone,null,0,-1));let i=n.getMeta("appendedTransaction");if(n.steps.length==0)return t;if(i&&i.getMeta(Rs))return i.getMeta(Rs).redo?new Zo(t.done.addTransform(n,void 0,r,gu(e)),t.undone,Q1(n.mapping.maps),t.prevTime,t.prevComposition):new Zo(t.done,t.undone.addTransform(n,void 0,r,gu(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||!AL(n,t.prevRanges)),c=i?Zh(t.prevRanges,n.mapping):Q1(n.mapping.maps);return new Zo(t.done.addTransform(n,l?e.selection.getBookmark():void 0,r,gu(e)),or.empty,c,n.time,a??t.prevComposition)}else return(s=n.getMeta("rebased"))?new Zo(t.done.rebased(n,s),t.undone.rebased(n,s),Zh(t.prevRanges,n.mapping),t.prevTime,t.prevComposition):new Zo(t.done.addMaps(n.mapping.maps),t.undone.addMaps(n.mapping.maps),Zh(t.prevRanges,n.mapping),t.prevTime,t.prevComposition)}function AL(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 Q1(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 Zh(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 IL(t,e,n){let r=gu(e),o=Rs.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 Zo(n?a:s.remaining,n?s.remaining:a,null,0,-1);return s.transform.setSelection(i).setMeta(Rs,{redo:n,historyState:l})}let Kh=!1,eb=null;function gu(t){let e=t.plugins;if(eb!=e){Kh=!1,eb=e;for(let n=0;n<e.length;n++)if(e[n].spec.historyPreserveItems){Kh=!0;break}}return Kh}const Rs=new tn("history"),NL=new tn("closeHistory");function BL(t={}){return t={depth:t.depth||100,newGroupDelay:t.newGroupDelay||500},new vt({key:Rs,state:{init(){return new Zo(or.empty,or.empty,null,0,-1)},apply(e,n,r){return ML(n,r,e,t)}},config:t,props:{handleDOMEvents:{beforeinput(e,n){let r=n.inputType,o=r=="historyUndo"?nb:r=="historyRedo"?rb:null;return!o||!e.editable?!1:(n.preventDefault(),o(e.state,e.dispatch))}}}})}function tb(t,e){return(n,r)=>{let o=Rs.getState(n);if(!o||(t?o.undone:o.done).eventCount==0)return!1;if(r){let s=IL(o,n,t);s&&r(e?s.scrollIntoView():s)}return!0}}const nb=tb(!1,!0),rb=tb(!0,!0);Ye.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 vt({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)}})]}}),Ye.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[mL(this.options)]}}),Ye.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new vt({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)}}})]}}),Ye.create({name:"gapCursor",addProseMirrorPlugins(){return[vL()]},extendNodeSchema(t){var e;const n={name:t.name,options:t.options,storage:t.storage};return{allowGapCursor:(e=je(oe(t,"allowGapCursor",n)))!=null?e:null}}});var ob="placeholder";function PL(t){return t.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}Ye.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:ob,placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){const t=this.options.dataAttribute?`data-${PL(this.options.dataAttribute)}`:`data-${ob}`;return[new vt({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&&au(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)}}})]}}),Ye.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){const{editor:t,options:e}=this;return[new vt({key:new tn("selection"),props:{decorations(n){return n.selection.empty||t.isFocused||!t.isEditable||G$(n.selection)||t.view.dragging?null:nt.create(n.doc,[on.inline(n.selection.from,n.selection.to,{class:e.className})])}}})]}});function sb({types:t,node:e}){return e&&Array.isArray(t)&&t.includes(e.type)||(e==null?void 0:e.type)===t}Ye.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 vt({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!sb({node:i,types:r})},apply:(o,s)=>{if(!o.docChanged||o.getMeta("__uniqueIDTransaction"))return s;const i=o.doc.lastChild;return!sb({node:i,types:r})}}})]}});var OL=Ye.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:t,dispatch:e})=>nb(t,e),redo:()=>({state:t,dispatch:e})=>rb(t,e)}},addProseMirrorPlugins(){return[BL(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 Ko(t,e){const n=d.inject(On);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 ib(){const t=d.inject(On);if(!t)throw new Error("useImageCreation must be used within a WovenCanvas component");const{nextEditorTick:e}=dt();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=Ht.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);Q(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,Ht.snapPosition(f,w.position);const v=crypto.randomUUID();Q(f,y,cs);const b=cs.write(f,y);b.identifier=v,b.uploadState=gr.Pending,Q(f,y,ea);const S=ea.write(f,y);return S.width=u.width,S.height=u.height,S.alt=s.name,Q(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=cs.write(c,s);u.uploadState=gr.Complete}catch{const c=await e(),u=cs.write(c,s);u.uploadState=gr.Failed}}return{getImageDimensions:n,createImageBlock:r}}function ab(t){const e=d.inject(On);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 Ut(t){const e=d.inject(On);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 DL(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 Yh(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=n.value.left,c=n.value.top,u=new DOMPoint(a.left+a.width/2-l,a.top+a.height/2-c),f=e.value.left,h=e.value.top,p=e.value.zoom,m=new DOMMatrix;m.translateSelf(-f*p,-h*p),m.scaleSelf(p,p),m.invertSelf();const g=m.transformPoint(u),y=m.transformPoint(new DOMPoint(a.left-l,a.top-c)),w=m.transformPoint(new DOMPoint(a.right-l,a.bottom-c)),v=w.x-y.x,b=w.y-y.y,{width:S,height:k}=DL(v,b,-i);return{width:S,height:k,left:g.x-S/2,top:g.y-k/2}}function lb(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 sl(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 qh(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 cb(t){const e=qh(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 ub(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 db(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),Gh=d.shallowRef(null),Jh=d.shallowRef(null),Yo=d.ref(0);function il(){const t={hasEditor:d.computed(()=>hn.value!==null),isBold:d.computed(()=>{var o;return Yo.value,((o=hn.value)==null?void 0:o.isActive("bold"))??!1}),isItalic:d.computed(()=>{var o;return Yo.value,((o=hn.value)==null?void 0:o.isActive("italic"))??!1}),isUnderline:d.computed(()=>{var o;return Yo.value,((o=hn.value)==null?void 0:o.isActive("underline"))??!1}),alignment:d.computed(()=>{Yo.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(()=>{Yo.value;const o=hn.value;if(!o)return null;const i=o.getAttributes("textStyle").color??null;return i?lb(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,Jh.value=s,Gh.value=i,o.on("selectionUpdate",()=>{Yo.value++}),o.on("transaction",()=>{Yo.value++})}function r(){hn.value=null,Jh.value=null,Gh.value=null}return{editor:hn,blockElement:Gh,textElement:Jh,state:t,commands:e,updateCounter:Yo,register:n,unregister:r}}const Ln=[L1,F1,j1,Wh,G1,W1,H1,Z1,K1.configure({types:["paragraph"],alignments:["left","center","right","justify"],defaultAlignment:"left"})];function RL(t){return t.type==="text"&&typeof t.text=="string"}function zs(t,e){if(RL(t)){e(t);return}if(t.content)for(const n of t.content)zs(n,e)}function Xh(t,e){if(t.type==="paragraph"){e(t);return}if(t.content)for(const n of t.content)Xh(n,e)}function zL(t,e){var n;return((n=t.marks)==null?void 0:n.some(r=>r.type===e))??!1}function $L(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?lb(n):null}function LL(t,e){if(!t.trim())return!1;const n=Ho(t,Ln);let r=!1,o=!0,s=0;return zs(n,i=>{s++,zL(i,e)?r=!0:o=!1}),s===0?!1:o?!0:r?null:!1}function VL(t){if(!t.trim())return"left";const e=Ho(t,Ln);let n="left";return Xh(e,r=>{var s;const o=(s=r.attrs)==null?void 0:s.textAlign;o&&(n=o)}),n}function FL(t){if(!t.trim())return null;const e=Ho(t,Ln);let n=null;return zs(e,r=>{n===null&&(n=$L(r))}),n}function Qh(t,e){if(!t.trim())return t;const n=Ho(t,Ln);return zs(n,r=>{const o=r.marks??[];o.findIndex(i=>i.type===e)===-1&&(r.marks=[...o,{type:e}])}),su(n,Ln)}function ep(t,e){if(!t.trim())return t;const n=Ho(t,Ln);return zs(n,r=>{const o=r.marks??[];r.marks=o.filter(s=>s.type!==e)}),su(n,Ln)}function jL(t,e){if(!t.trim())return t;const n=Ho(t,Ln);return Xh(n,r=>{r.attrs={...r.attrs,textAlign:e}}),su(n,Ln)}function UL(t,e){if(!t.trim())return t;const n=Ho(t,Ln);return zs(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}}]}),su(n,Ln)}function fb(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 hb(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=Yh(o,e,n);return o.remove(),a}function pb(t){const{nextEditorTick:e}=dt(),n=Ko(t,yt),r=Ut(we),o=Ut(_t),s=il(),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?Ho(h.content,Ln):null;if(p){let m=!1;if(zs(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=VL(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=FL(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=LL(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?ep(h,"bold"):Qh(h,"bold"))},toggleItalic(){u(h=>i.isItalic.value?ep(h,"italic"):Qh(h,"italic"))},toggleUnderline(){u(h=>i.isUnderline.value?ep(h,"underline"):Qh(h,"underline"))},setAlignment(h){f(p=>jL(p,h))},setColor(h){f(p=>UL(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=fb(y);if(v){const b=hb(v,r,o,h(w));g.push({entityId:y,...b})}}e(y=>{for(const w of m)p(yt.write(y,w));for(const{entityId:w,width:v,height:b,left:S,top:k}of g){const E=A.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=fb(g);if(v){const b=hb(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=yt.write(g,y);if(E.content=w,v>0&&b>0){const _=A.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=yt.write(m,g);y.content=h(y.content)}})}return{state:i,commands:l}}function _r(t){const e=il(),n=pb(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 tp(t){const e=Ut(we),n=Ut(_t),r=Ut(cf),o=Ut(Qn),{nextEditorTick:s}=dt();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),v=Math.abs(w.size[0]-g)>.5,b=Math.abs(w.size[1]-y)>.5;if(!v&&!b)return;const S=A.write(u,h);S.size=[g,y],S.position=[f.left,f.top],r.value.transformBoxId!==null&&of.spawn(u,{transformBoxId:r.value.transformBoxId})}d.watch(()=>o.value,()=>{const u=t.containerRef.value;u&&i&&(a=Yh(u,e,n)),s(f=>{const h=WL(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(yt.read(p,m).content!==f){const y=yt.write(p,m);y.content=f}l(p,h)})}return{handleEditEnd:c}}function WL(t){const e=Qn.read(t);return e.state===_e.Dragging&&e.draggedEntity!==null&&R(t,e.draggedEntity,Ke)&&Ke.read(t,e.draggedEntity).kind===Xn.Stretch}function np(){const t=d.inject(Tf);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 HL=500,ZL=1500;function mb(){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},HL)}function a(){s(),e.value=!1,t.value=null,n.value&&(o=setTimeout(()=>{n.value=!1,o=null},ZL))}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 qo(){const t=d.inject(U0);if(!t)throw new Error("useTooltipSingleton must be used within a WovenCanvas component");return t}const KL={key:1},YL=["innerHTML"],qL=50,GL=300,yu=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,yt),i=Ut(we),a=Ut(_t),l=il(),{nextEditorTick:c}=dt(),u=Ut(Bn),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 B;const T=s.value;return!T||T.constrainWidth||(((B=_.clipboardData)==null?void 0:B.getData("text/plain"))??"").length>qL&&c(L=>{const Z=yt.write(L,r.entityId);Z.constrainWidth=!0;const M=A.read(L,r.entityId),F=Math.max(M.size[0],GL),q=A.write(L,r.entityId);q.size=[F,M.size[1]],ay.spawn(L),Si.spawn(L)}),!1}function g(){var E,_;return new H4({extensions:[L1,F1,j1,Wh,G1,W1,H1,Z1,K1.configure({types:["paragraph"],alignments:["left","center","right","justify"],defaultAlignment:((E=s.value)==null?void 0:E.defaultAlignment)??"left"}),OL],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 B;const _=(B=u.value)==null?void 0:B.position,T=a.value;await d.nextTick(),await new Promise(L=>requestAnimationFrame(L));const I=f.value;if(_&&T&&I){const L=_[0]+T.left,Z=_[1]+T.top,M=E.view.posAtCoords({left:L,top:Z});if(M){E.chain().focus().setTextSelection(M.pos).run();return}}E.commands.focus("start")}function w(E){let _=E.getHTML();const I=_.replace(/<[^>]*>/g,"").trim().length>0;I||(_=""),h.value=_,c(B=>{var q,ue;const L=Kn(B,r.block.tag);if(!I&&((q=L.editOptions)!=null&&q.removeWhenTextEmpty)){it(B,r.entityId);return}const Z=(ue=f.value)==null?void 0:ue.closest(".wov-block"),M=(Z==null?void 0:Z.firstElementChild)??f.value;if(!M){console.warn("EditableText: no element to measure");return}const F=Yh(M,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;if(!E)return{};const[_,T]=r.block.flip,I=_?-1:1,B=T?-1:1,L=_||T;return{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",transform:L?`scale(${I}, ${B})`:void 0}});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(Z4),{key:0,editor:p.value},null,8,["editor"])):(d.openBlock(),d.createElementBlock("div",KL,[d.createElementVNode("div",{class:"tiptap ProseMirror",innerHTML:h.value},null,8,YL)]))],36))}}),JL={class:"wov-shape-svg",viewBox:"0 0 100 100",preserveAspectRatio:"none"},XL=["d","fill","stroke","stroke-width","stroke-dasharray"],gb=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,Hn),r=Tt(e.entityId,us),o=d.ref(null),s={[gt.Top]:"flex-start",[gt.Center]:"center",[gt.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===zt.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)??zt.Solid}),u=d.computed(()=>{var g;return Oa[((g=n.value)==null?void 0:g.kind)??"rectangle"]??Oa.rectangle}),f=d.computed(()=>{const g=l.value;switch(c.value){case zt.Dashed:return`${g*3} ${g*3}`;case zt.None:return"";case zt.Solid:default:return""}}),h=d.computed(()=>{var g;return{overflow:e.edited?"visible":"hidden",alignItems:s[((g=r.value)==null?void 0:g.value)??gt.Top]}}),{nextEditorTick:p}=dt();function m(g){p(y=>{if(yt.read(y,e.entityId).content===g.content)return;const v=yt.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",JL,[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,XL)])),d.createElementVNode("div",{class:"wov-shape-content",style:d.normalizeStyle(h.value)},[d.createVNode(yu,d.mergeProps(e,{"block-element":o.value,onEditEnd:m}),null,16,["block-element"])],4)],512))}}),QL=["data-text-empty"],yb=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,yt),o=d.computed(()=>{var l;return(((l=r.value)==null?void 0:l.content)??"").replace(/<[^>]*>/g,"").trim().length===0}),{handleEditEnd:s}=tp({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(yu,d.mergeProps(e,{"block-element":n.value,onEditEnd:d.unref(s)}),null,16,["block-element","onEditEnd"])],8,QL))}}),wu=Math.min,$s=Math.max,vu=Math.round,ku=Math.floor,xr=t=>({x:t,y:t}),eV={left:"right",right:"left",bottom:"top",top:"bottom"},tV={start:"end",end:"start"};function wb(t,e,n){return $s(t,wu(e,n))}function bu(t,e){return typeof t=="function"?t(e):t}function Ls(t){return t.split("-")[0]}function Su(t){return t.split("-")[1]}function vb(t){return t==="x"?"y":"x"}function kb(t){return t==="y"?"height":"width"}const nV=new Set(["top","bottom"]);function Go(t){return nV.has(Ls(t))?"y":"x"}function bb(t){return vb(Go(t))}function rV(t,e,n){n===void 0&&(n=!1);const r=Su(t),o=bb(t),s=kb(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return e.reference[s]>e.floating[s]&&(i=Eu(i)),[i,Eu(i)]}function oV(t){const e=Eu(t);return[rp(t),e,rp(e)]}function rp(t){return t.replace(/start|end/g,e=>tV[e])}const Sb=["left","right"],Eb=["right","left"],sV=["top","bottom"],iV=["bottom","top"];function aV(t,e,n){switch(t){case"top":case"bottom":return n?e?Eb:Sb:e?Sb:Eb;case"left":case"right":return e?sV:iV;default:return[]}}function lV(t,e,n,r){const o=Su(t);let s=aV(Ls(t),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),e&&(s=s.concat(s.map(rp)))),s}function Eu(t){return t.replace(/left|right|bottom|top/g,e=>eV[e])}function cV(t){return{top:0,right:0,bottom:0,left:0,...t}}function uV(t){return typeof t!="number"?cV(t):{top:t,right:t,bottom:t,left:t}}function Cu(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 Cb(t,e,n){let{reference:r,floating:o}=t;const s=Go(e),i=bb(e),a=kb(i),l=Ls(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(Su(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 dV(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}=bu(e,t),m=uV(p),y=a[h?f==="floating"?"reference":"floating":f],w=Cu(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=Cu(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 fV=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}=Cb(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:dV},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}=Cb(c,h,l)),y=-1)}return{x:u,y:f,placement:h,strategy:o,middlewareData:p}},hV=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}=bu(t,e);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const w=Ls(o),v=Go(a),b=Ls(a)===a,S=await(l.isRTL==null?void 0:l.isRTL(c.floating)),k=h||(b||!g?[Eu(a)]:oV(a)),E=m!=="none";!h&&E&&k.push(...lV(a,g,m,S));const _=[a,...k],T=await l.detectOverflow(e,y),I=[];let B=((r=s.flip)==null?void 0:r.overflows)||[];if(u&&I.push(T[w]),f){const F=rV(o,i,S);I.push(T[F[0]],T[F[1]])}if(B=[...B,{placement:o,overflows:I}],!I.every(F=>F<=0)){var L,Z;const F=(((L=s.flip)==null?void 0:L.index)||0)+1,q=_[F];if(q&&(!(f==="alignment"?v!==Go(q):!1)||B.every(j=>Go(j.placement)===v?j.overflows[0]>0:!0)))return{data:{index:F,overflows:B},reset:{placement:q}};let ue=(Z=B.filter(se=>se.overflows[0]<=0).sort((se,j)=>se.overflows[1]-j.overflows[1])[0])==null?void 0:Z.placement;if(!ue)switch(p){case"bestFit":{var M;const se=(M=B.filter(j=>{if(E){const ee=Go(j.placement);return ee===v||ee==="y"}return!0}).map(j=>[j.placement,j.overflows.filter(ee=>ee>0).reduce((ee,fe)=>ee+fe,0)]).sort((j,ee)=>j[1]-ee[1])[0])==null?void 0:M[0];se&&(ue=se);break}case"initialPlacement":ue=a;break}if(o!==ue)return{reset:{placement:ue}}}return{}}}},pV=new Set(["left","top"]);async function mV(t,e){const{placement:n,platform:r,elements:o}=t,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=Ls(n),a=Su(n),l=Go(n)==="y",c=pV.has(i)?-1:1,u=s&&l?-1:1,f=bu(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 gV=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 mV(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}}}}},yV=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}=bu(t,e),u={x:n,y:r},f=await s.detectOverflow(e,c),h=Go(Ls(o)),p=vb(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=wb(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=wb(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 _u(){return typeof window<"u"}function Vs(t){return op(t)?(t.nodeName||"").toLowerCase():"#document"}function xn(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function Tr(t){var e;return(e=(op(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function op(t){return _u()?t instanceof Node||t instanceof xn(t).Node:!1}function sr(t){return _u()?t instanceof Element||t instanceof xn(t).Element:!1}function Mr(t){return _u()?t instanceof HTMLElement||t instanceof xn(t).HTMLElement:!1}function _b(t){return!_u()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof xn(t).ShadowRoot}const wV=new Set(["inline","contents"]);function al(t){const{overflow:e,overflowX:n,overflowY:r,display:o}=ir(t);return/auto|scroll|overlay|hidden|clip/.test(e+r+n)&&!wV.has(o)}const vV=new Set(["table","td","th"]);function kV(t){return vV.has(Vs(t))}const bV=[":popover-open",":modal"];function xu(t){return bV.some(e=>{try{return t.matches(e)}catch{return!1}})}const SV=["transform","translate","scale","rotate","perspective"],EV=["transform","translate","scale","rotate","perspective","filter"],CV=["paint","layout","strict","content"];function sp(t){const e=ip(),n=sr(t)?ir(t):t;return SV.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)||EV.some(r=>(n.willChange||"").includes(r))||CV.some(r=>(n.contain||"").includes(r))}function _V(t){let e=Jo(t);for(;Mr(e)&&!ji(e);){if(sp(e))return e;if(xu(e))return null;e=Jo(e)}return null}function ip(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const xV=new Set(["html","body","#document"]);function ji(t){return xV.has(Vs(t))}function ir(t){return xn(t).getComputedStyle(t)}function Tu(t){return sr(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function Jo(t){if(Vs(t)==="html")return t;const e=t.assignedSlot||t.parentNode||_b(t)&&t.host||Tr(t);return _b(e)?e.host:e}function xb(t){const e=Jo(t);return ji(e)?t.ownerDocument?t.ownerDocument.body:t.body:Mr(e)&&al(e)?e:xb(e)}function ll(t,e,n){var r;e===void 0&&(e=[]),n===void 0&&(n=!0);const o=xb(t),s=o===((r=t.ownerDocument)==null?void 0:r.body),i=xn(o);if(s){const a=ap(i);return e.concat(i,i.visualViewport||[],al(o)?o:[],a&&n?ll(a):[])}return e.concat(o,ll(o,[],n))}function ap(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function Tb(t){const e=ir(t);let n=parseFloat(e.width)||0,r=parseFloat(e.height)||0;const o=Mr(t),s=o?t.offsetWidth:n,i=o?t.offsetHeight:r,a=vu(n)!==s||vu(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function lp(t){return sr(t)?t:t.contextElement}function Ui(t){const e=lp(t);if(!Mr(e))return xr(1);const n=e.getBoundingClientRect(),{width:r,height:o,$:s}=Tb(e);let i=(s?vu(n.width):n.width)/r,a=(s?vu(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const TV=xr(0);function Mb(t){const e=xn(t);return!ip()||!e.visualViewport?TV:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function MV(t,e,n){return e===void 0&&(e=!1),!n||e&&n!==xn(t)?!1:e}function Fs(t,e,n,r){e===void 0&&(e=!1),n===void 0&&(n=!1);const o=t.getBoundingClientRect(),s=lp(t);let i=xr(1);e&&(r?sr(r)&&(i=Ui(r)):i=Ui(t));const a=MV(s,n,r)?Mb(s):xr(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&&sr(r)?xn(r):r;let m=h,g=ap(m);for(;g&&r&&p!==m;){const y=Ui(g),w=g.getBoundingClientRect(),v=ir(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=ap(m)}}return Cu({width:u,height:f,x:l,y:c})}function Mu(t,e){const n=Tu(t).scrollLeft;return e?e.left+n:Fs(Tr(t)).left+n}function Ab(t,e){const n=t.getBoundingClientRect(),r=n.left+e.scrollLeft-Mu(t,n),o=n.top+e.scrollTop;return{x:r,y:o}}function AV(t){let{elements:e,rect:n,offsetParent:r,strategy:o}=t;const s=o==="fixed",i=Tr(r),a=e?xu(e.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=xr(1);const u=xr(0),f=Mr(r);if((f||!f&&!s)&&((Vs(r)!=="body"||al(i))&&(l=Tu(r)),Mr(r))){const p=Fs(r);c=Ui(r),u.x=p.x+r.clientLeft,u.y=p.y+r.clientTop}const h=i&&!f&&!s?Ab(i,l):xr(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 IV(t){return Array.from(t.getClientRects())}function NV(t){const e=Tr(t),n=Tu(t),r=t.ownerDocument.body,o=$s(e.scrollWidth,e.clientWidth,r.scrollWidth,r.clientWidth),s=$s(e.scrollHeight,e.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+Mu(t);const a=-n.scrollTop;return ir(r).direction==="rtl"&&(i+=$s(e.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const Ib=25;function BV(t,e){const n=xn(t),r=Tr(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=ip();(!u||u&&e==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=Mu(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<=Ib&&(s-=m)}else c<=Ib&&(s+=c);return{width:s,height:i,x:a,y:l}}const PV=new Set(["absolute","fixed"]);function OV(t,e){const n=Fs(t,!0,e==="fixed"),r=n.top+t.clientTop,o=n.left+t.clientLeft,s=Mr(t)?Ui(t):xr(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 Nb(t,e,n){let r;if(e==="viewport")r=BV(t,n);else if(e==="document")r=NV(Tr(t));else if(sr(e))r=OV(e,n);else{const o=Mb(t);r={x:e.x-o.x,y:e.y-o.y,width:e.width,height:e.height}}return Cu(r)}function Bb(t,e){const n=Jo(t);return n===e||!sr(n)||ji(n)?!1:ir(n).position==="fixed"||Bb(n,e)}function DV(t,e){const n=e.get(t);if(n)return n;let r=ll(t,[],!1).filter(a=>sr(a)&&Vs(a)!=="body"),o=null;const s=ir(t).position==="fixed";let i=s?Jo(t):t;for(;sr(i)&&!ji(i);){const a=ir(i),l=sp(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&PV.has(o.position)||al(i)&&!l&&Bb(t,i))?r=r.filter(u=>u!==i):o=a,i=Jo(i)}return e.set(t,r),r}function RV(t){let{element:e,boundary:n,rootBoundary:r,strategy:o}=t;const i=[...n==="clippingAncestors"?xu(e)?[]:DV(e,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,u)=>{const f=Nb(e,u,o);return c.top=$s(f.top,c.top),c.right=wu(f.right,c.right),c.bottom=wu(f.bottom,c.bottom),c.left=$s(f.left,c.left),c},Nb(e,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function zV(t){const{width:e,height:n}=Tb(t);return{width:e,height:n}}function $V(t,e,n){const r=Mr(e),o=Tr(e),s=n==="fixed",i=Fs(t,!0,s,e);let a={scrollLeft:0,scrollTop:0};const l=xr(0);function c(){l.x=Mu(o)}if(r||!r&&!s)if((Vs(e)!=="body"||al(o))&&(a=Tu(e)),r){const p=Fs(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?Ab(o,a):xr(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 cp(t){return ir(t).position==="static"}function Pb(t,e){if(!Mr(t)||ir(t).position==="fixed")return null;if(e)return e(t);let n=t.offsetParent;return Tr(t)===n&&(n=n.ownerDocument.body),n}function Ob(t,e){const n=xn(t);if(xu(t))return n;if(!Mr(t)){let o=Jo(t);for(;o&&!ji(o);){if(sr(o)&&!cp(o))return o;o=Jo(o)}return n}let r=Pb(t,e);for(;r&&kV(r)&&cp(r);)r=Pb(r,e);return r&&ji(r)&&cp(r)&&!sp(r)?n:r||_V(t)||n}const LV=async function(t){const e=this.getOffsetParent||Ob,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 VV(t){return ir(t).direction==="rtl"}const FV={convertOffsetParentRelativeRectToViewportRelativeRect:AV,getDocumentElement:Tr,getClippingRect:RV,getOffsetParent:Ob,getElementRects:LV,getClientRects:IV,getDimensions:zV,getScale:Ui,isElement:sr,isRTL:VV};function Db(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function jV(t,e){let n=null,r;const o=Tr(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=ku(f),g=ku(o.clientWidth-(u+h)),y=ku(o.clientHeight-(f+p)),w=ku(u),b={rootMargin:-m+"px "+-g+"px "+-y+"px "+-w+"px",threshold:$s(0,wu(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&&!Db(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 Rb(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=lp(t),u=o||s?[...c?ll(c):[],...ll(e)]:[];u.forEach(w=>{o&&w.addEventListener("scroll",n,{passive:!0}),s&&w.addEventListener("resize",n)});const f=c&&a?jV(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?Fs(t):null;l&&y();function y(){const w=Fs(t);g&&!Db(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 Au=gV,Iu=yV,Nu=hV,UV=(t,e,n)=>{const r=new Map,o={platform:FV,...n},s={...o.platform,_c:r};return fV(t,e,{...o,platform:s})};function WV(t){return t!=null&&typeof t=="object"&&"$el"in t}function zb(t){if(WV(t)){const e=t.$el;return op(e)&&Vs(e)==="#comment"?null:e}return t}function cl(t){return typeof t=="function"?t():d.unref(t)}function $b(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function Lb(t,e){const n=$b(t);return Math.round(e*n)/n}function Bu(t,e,n){n===void 0&&(n={});const r=n.whileElementsMounted,o=d.computed(()=>{var _;return(_=cl(n.open))!=null?_:!0}),s=d.computed(()=>cl(n.middleware)),i=d.computed(()=>{var _;return(_=cl(n.placement))!=null?_:"bottom"}),a=d.computed(()=>{var _;return(_=cl(n.strategy))!=null?_:"absolute"}),l=d.computed(()=>{var _;return(_=cl(n.transform))!=null?_:!0}),c=d.computed(()=>zb(t.value)),u=d.computed(()=>zb(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 T=Lb(u.value,f.value),I=Lb(u.value,h.value);return l.value?{..._,transform:"translate("+T+"px, "+I+"px)",...$b(u.value)>=1.5&&{willChange:"transform"}}:{position:p.value,left:T+"px",top:I+"px"}});let v;function b(){if(c.value==null||u.value==null)return;const _=o.value;UV(c.value,u.value,{middleware:s.value,placement:i.value,strategy:a.value}).then(T=>{f.value=T.x,h.value=T.y,p.value=T.strategy,m.value=T.placement,g.value=T.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 HV=["menu-open"],Vn=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(V0,null),i=d.inject(F0,0),a=Math.random().toString(36).slice(2);d.provide(F0,i+1);const{show:l,hide:c}=qo(),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}=Bu(f,h,{placement:n.placement,middleware:[Au(n.offsetPx),Nu(),Iu({padding:8})],whileElementsMounted:Rb});function m(){n.disabled||(u.value=!u.value)}function g(){u.value=!1}function y(b){var T,I,B;const S=b.target,k=(T=f.value)==null?void 0:T.contains(S),E=(I=h.value)==null?void 0:I.contains(S),_=(B=S.closest)==null?void 0:B.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,HV),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))}}),ZV={},KV={viewBox:"0 0 512 320",fill:"currentColor",style:{width:"7px",color:"var(--wov-gray-300)"}};function YV(t,e){return d.openBlock(),d.createElementBlock("svg",KV,[...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 Fn=ws(ZV,[["render",YV]]),qV={class:"wov-menu-button"},GV=["innerHTML"],JV=["onClick"],XV=["innerHTML"],up=d.defineComponent({__name:"ArrowHeadButton",props:{entityIds:{},side:{}},setup(t){const e=t,{nextEditorTick:n}=dt(),r=d.shallowRef(null),o=d.computed(()=>{const a=r.value??(e.side==="start"?De.None:De.V);return xi(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(Vn,{title:t.side==="start"?"Start Arrow Head":"End Arrow Head"},{button:d.withCtx(()=>[d.createElementVNode("div",qV,[(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,GV)),d.createVNode(Fn,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[(d.openBlock(!0),d.createElementBlock(d.Fragment,null,d.renderList(d.unref(xf),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,XV))],10,JV))),128))]),_:1},8,["title"]))}}),QV={class:"wov-menu-button"},eF=["onClick"],Vb=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}=dt(),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(Vn,{title:"Thickness"},{button:d.withCtx(()=>[d.createElementVNode("div",QV,[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(Fn,{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,eF)),64))]),_:1}))}}),tF=["value"],nF=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,tF))}}),Fb=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))}}),rF={class:"wov-color-picker"},oF={class:"wov-color-picker-area"},sF={class:"wov-color-picker-selector-gradient"},iF="linear-gradient(to bottom, red 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, red 100%)",jb=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(()=>ub({h:h.value.h,s:100,v:100})),m=d.computed(()=>ub({h:h.value.h,s:h.value.s,v:h.value.v})),g=d.computed(()=>n.withOpacity?db(h.value):m.value),y=d.computed(()=>`linear-gradient(to top, transparent 0%, ${m.value} 100%)`);function w(E){if(E){const _=cb(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?db(cb(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(),T=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:T,y:I}}function k(){u.value=!1,window.removeEventListener("pointermove",S),window.removeEventListener("pointerup",k)}return(E,_)=>(d.openBlock(),d.createElementBlock("div",rF,[d.createVNode(nF,{modelValue:g.value,"onUpdate:modelValue":v},null,8,["modelValue"]),d.createElementVNode("div",oF,[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",sF,[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(Fb,{ref_key:"hueSliderRef",ref:o,modelValue:l.value,"onUpdate:modelValue":_[0]||(_[0]=T=>l.value=T),thumbColor:p.value,background:iF},null,8,["modelValue","thumbColor"]),t.withOpacity?(d.openBlock(),d.createBlock(Fb,{key:0,ref_key:"opacitySliderRef",ref:s,modelValue:c.value,"onUpdate:modelValue":_[1]||(_[1]=T=>c.value=T),thumbColor:m.value,background:y.value,class:"wov-color-picker-opacity"},null,8,["modelValue","thumbColor","background"])):d.createCommentVNode("",!0)])]))}}),aF={class:"wov-color-bubbles-container"},lF={key:1,class:"wov-color-bubbles"},cF=["onClick"],Pu=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=qh(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=qh(m);g&&r("change",g)}return(m,g)=>(d.openBlock(),d.createElementBlock("div",aF,[i.value?(d.openBlock(),d.createBlock(jb,{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",lF,[(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,cF))),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)]))]))}}),uF={class:"wov-color-button"},Ub=d.defineComponent({__name:"ColorButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=dt(),r=Ko(()=>e.entityIds,In),o=d.computed(()=>{const c=new Set;for(const u of r.value.values())if(u){const f=sl(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=sl(c);n(f=>{for(const h of e.entityIds)In.fromHex(f,h,u)})}return(c,u)=>(d.openBlock(),d.createBlock(Vn,{title:"Color"},{button:d.withCtx(()=>[d.createElementVNode("div",uF,[d.createElementVNode("div",{class:"wov-color-swatch",style:d.normalizeStyle(a.value)},null,4),d.createVNode(Fn,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createVNode(Pu,{currentColor:i.value??void 0,hideHighlight:s.value,withPicker:!0,onChange:l},null,8,["currentColor","hideHighlight"])]),_:1}))}}),Wi=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}=qo();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))}}),dp=d.defineComponent({__name:"MenuTooltip",setup(t){const{activeTooltip:e,isVisible:n}=qo(),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}=Bu(s,o,{placement:"top",middleware:[Au(8),Nu({fallbackPlacements:["bottom"]}),Iu({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)}}),dF={class:"wov-menu-button"},fF=["onClick"],Wb=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}=dt(),o=Ko(()=>n.entityIds,nr),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=nr.write(l,c);u.thickness=a}})}return(a,l)=>(d.openBlock(),d.createBlock(Vn,{title:"Thickness"},{button:d.withCtx(()=>[d.createElementVNode("div",dF,[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(Fn,{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,fF)),64))]),_:1}))}}),hF={class:"wov-fill-color-button"},pF={class:"wov-fill-dropdown"},mF={key:0,class:"wov-fill-mode-section"},gF=["title","onClick"],yF={viewBox:"0 0 24 24",fill:"none"},wF=["fill","fill-opacity","stroke","stroke-width","stroke-dasharray"],Hb=d.defineComponent({__name:"ShapeFillColorButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=dt(),r=Ko(()=>e.entityIds,Hn),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=Hn.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=sl({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=Hn.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(Vn,{title:"Fill Color"},{button:d.withCtx(()=>[d.createElementVNode("div",hF,[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(Fn,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createElementVNode("div",pF,[h.value?d.createCommentVNode("",!0):(d.openBlock(),d.createElementBlock("div",mF,[(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",yF,[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,wF)])),d.createElementVNode("span",null,d.toDisplayString(g.label),1)],10,gF)),64))])),d.createVNode(Pu,{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}))}}),vF={class:"wov-shape-kind-button"},kF={class:"wov-shape-kind-dropdown"},bF=["onClick"],SF={viewBox:"0 0 20 20",class:"wov-shape-option-icon",fill:"none",stroke:"currentColor","stroke-width":"4"},EF=["d"],Zb=d.defineComponent({__name:"ShapeKindButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=dt(),r=Ko(()=>e.entityIds,Hn),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(Oa).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=Hn.write(c,u);f.kind=l}})}return(l,c)=>(d.openBlock(),d.createBlock(Vn,{title:"Shape Type"},{button:d.withCtx(()=>[d.createElementVNode("div",vF,[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(Fn,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createElementVNode("div",kF,[(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",SF,[d.createElementVNode("path",{d:d.unref(Oa)[u.kind],transform:"translate(2, 2) scale(0.16)"},null,8,EF)])),d.createElementVNode("span",null,d.toDisplayString(u.label),1)],10,bF))),128))])]),_:1}))}}),CF={class:"wov-stroke-style-section"},_F=["title","onClick"],xF={viewBox:"0 0 24 8",fill:"none",stroke:"currentColor","stroke-width":"2"},TF=["stroke-dasharray","stroke-opacity"],MF=d.defineComponent({__name:"StrokeStyleOptions",props:{currentStyle:{},hasMultipleStyles:{type:Boolean}},emits:["change"],setup(t,{emit:e}){const n=e,r=[{kind:zt.Solid,label:"Solid"},{kind:zt.Dashed,label:"Dashed"},{kind:zt.None,label:"None"}];function o(i){switch(i){case zt.Dashed:return"6 6";case zt.None:return"";case zt.Solid:default:return""}}function s(i){n("change",i)}return(i,a)=>(d.openBlock(),d.createElementBlock("div",CF,[(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",xF,[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(zt).None?.3:1},null,8,TF)])),d.createElementVNode("span",null,d.toDisplayString(l.label),1)],10,_F)),64))]))}}),AF={class:"wov-stroke-color-button"},IF={class:"wov-stroke-dropdown"},NF={key:1,class:"wov-stroke-divider"},Kb=d.defineComponent({__name:"ShapeStrokeColorButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=dt(),r=Ko(()=>e.entityIds,Hn),o=d.ref(!1),s=d.computed(()=>{const h=new Set;for(const p of r.value.values())if(p){const m=sl({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)??zt.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=Hn.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=Hn.write(p,m);g.strokeKind=h}})}return(h,p)=>(d.openBlock(),d.createBlock(Vn,{title:"Stroke Color"},{button:d.withCtx(()=>[d.createElementVNode("div",AF,[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(Fn,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createElementVNode("div",IF,[o.value?d.createCommentVNode("",!0):(d.openBlock(),d.createBlock(MF,{key:0,currentStyle:l.value,hasMultipleStyles:c.value,onChange:f},null,8,["currentStyle","hasMultipleStyles"])),o.value?d.createCommentVNode("",!0):(d.openBlock(),d.createElementBlock("div",NF)),d.createVNode(Pu,{currentColor:a.value,hideHighlight:i.value,withPicker:!0,onChange:u,onPickerOpen:p[0]||(p[0]=m=>o.value=m)},null,8,["currentColor","hideHighlight"])])]),_:1}))}}),BF={key:0,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},PF={key:1,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},OF={key:2,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},DF={key:3,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},fp=d.defineComponent({__name:"TextAlignmentButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=_r(()=>e.entityIds),o=[Wn.Left,Wn.Center,Wn.Right,Wn.Justify];function s(){const i=o.indexOf(n.alignment),a=o[(i+1)%o.length];r.setAlignment(a)}return(i,a)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(Wi,{key:0,title:"Text Align",onClick:s},{default:d.withCtx(()=>[d.unref(n).alignment===d.unref(Wn).Left?(d.openBlock(),d.createElementBlock("svg",BF,[...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(Wn).Center?(d.openBlock(),d.createElementBlock("svg",PF,[...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(Wn).Right?(d.openBlock(),d.createElementBlock("svg",OF,[...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",DF,[...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)}}),hp=d.defineComponent({__name:"TextBoldButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=_r(()=>e.entityIds);return(o,s)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(Wi,{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 RF(t,e){return d.getCurrentScope()?(d.onScopeDispose(t,e),!0):!1}const zF=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const $F=Object.prototype.toString,LF=t=>$F.call(t)==="[object Object]",Ou=()=>{};function Du(t){return Array.isArray(t)?t:[t]}function VF(t){return d.getCurrentInstance()}function FF(t,e=!0,n){VF()?d.onMounted(t,n):e?t():d.nextTick(t)}function jF(t,e,n){return d.watch(t,e,{...n,immediate:!0})}const Ru=zF?window:void 0;function ar(t){var e;const n=d.toValue(t);return(e=n==null?void 0:n.$el)!==null&&e!==void 0?e:n}function pp(...t){const e=(r,o,s,i)=>(r.addEventListener(o,s,i),()=>r.removeEventListener(o,s,i)),n=d.computed(()=>{const r=Du(d.toValue(t[0])).filter(o=>o!=null);return r.every(o=>typeof o!="string")?r:void 0});return jF(()=>{var r,o;return[(r=(o=n.value)===null||o===void 0?void 0:o.map(s=>ar(s)))!==null&&r!==void 0?r:[Ru].filter(s=>s!=null),Du(d.toValue(n.value?t[1]:t[0])),Du(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=LF(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 UF(t,e,n={}){const{window:r=Ru,ignore:o=[],capture:s=!0,detectIframe:i=!1,controls:a=!1}=n;if(!r)return a?{stop:Ou,cancel:Ou,trigger:Ou}:Ou;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=ar(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=ar(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=[pp(r,"click",y=>{p||(p=!0,setTimeout(()=>{p=!1},0),h(y))},{passive:!0,capture:s}),pp(r,"pointerdown",y=>{const w=ar(t);l=!c(y)&&!!(w&&!y.composedPath().includes(w))},{passive:!0}),i&&pp(r,"blur",y=>{setTimeout(()=>{var w;const v=ar(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 WF(){const t=d.shallowRef(!1),e=d.getCurrentInstance();return e&&d.onMounted(()=>{t.value=!0},e),t}function HF(t){const e=WF();return d.computed(()=>(e.value,!!t()))}function ZF(t,e,n={}){const{window:r=Ru,...o}=n;let s;const i=HF(()=>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=>ar(f)):[ar(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 RF(c),{isSupported:i,stop:c}}function Yb(t,e={width:0,height:0},n={}){const{window:r=Ru,box:o="content-box"}=n,s=d.computed(()=>{var f;return(f=ar(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}=ZF(t,([f])=>{const h=o==="border-box"?f.borderBoxSize:o==="content-box"?f.contentBoxSize:f.devicePixelContentBoxSize;if(r&&s.value){const p=ar(t);if(p){const m=p.getBoundingClientRect();i.value=m.width,a.value=m.height}}else if(h){const p=Du(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);FF(()=>{const f=ar(t);f&&(i.value="offsetWidth"in f?f.offsetWidth:e.width,a.value="offsetHeight"in f?f.offsetHeight:e.height)});const c=d.watch(()=>ar(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 qb(){const t=d.inject(On);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 KF={class:"wov-font-family-button"},YF={class:"wov-font-family-label"},qF={class:"wov-font-list"},GF=["onClick"],JF=["src","alt"],mp=d.defineComponent({__name:"TextFontFamilyButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=_r(()=>e.entityIds),o=qb(),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(Vn,{key:0,title:"Font Family"},{button:d.withCtx(()=>[d.createElementVNode("div",KF,[d.createElementVNode("span",YF,d.toDisplayString(a.value),1),d.createVNode(Fn,{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",qF,[(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,JF)):(d.openBlock(),d.createElementBlock("span",{key:1,class:"wov-font-name",style:d.normalizeStyle({fontFamily:h.name})},d.toDisplayString(h.displayName),5))],10,GF))),128))])],32)]),_:1})):d.createCommentVNode("",!0)}}),XF={class:"wov-font-size-button"},QF={class:"wov-font-size-label"},e6=["onClick"],t6={key:0,class:"wov-check-icon",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},n6={class:"wov-input-container"},r6=["value"],gp=d.defineComponent({__name:"TextFontSizeButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=_r(()=>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(Vn,{key:0,title:"Font Size"},{button:d.withCtx(()=>[d.createElementVNode("div",XF,[d.createElementVNode("span",QF,d.toDisplayString(i.value),1),d.createVNode(Fn,{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",t6,[...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,e6)),64)),p[3]||(p[3]=d.createElementVNode("div",{class:"wov-separator"},null,-1)),d.createElementVNode("div",n6,[d.createElementVNode("input",{class:"wov-custom-input",value:a.value,onInput:c,onKeydown:u,placeholder:"Custom size"},null,40,r6),p[2]||(p[2]=d.createElementVNode("span",{class:"wov-px-suffix"},"px",-1))])],32)]),_:1})):d.createCommentVNode("",!0)}}),yp=d.defineComponent({__name:"TextItalicButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=_r(()=>e.entityIds);return(o,s)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(Wi,{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)}}),wp=d.defineComponent({__name:"TextUnderlineButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=_r(()=>e.entityIds);return(o,s)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(Wi,{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)}}),o6={class:"wov-text-color-button"},s6={class:"wov-text-icon-container"},vp=d.defineComponent({__name:"TextColorButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=_r(()=>e.entityIds),o=d.computed(()=>n.color??"#000000"),s=d.computed(()=>({backgroundColor:o.value}));function i(a){r.setColor(sl(a))}return(a,l)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(Vn,{key:0,title:"Text Color"},{button:d.withCtx(()=>[d.createElementVNode("div",o6,[d.createElementVNode("div",s6,[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(Fn,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createVNode(Pu,{currentColor:o.value,withPicker:!0,onChange:i},null,8,["currentColor"])]),_:1})):d.createCommentVNode("",!0)}}),i6={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"},a6={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"},l6={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"},Gb=d.defineComponent({__name:"VerticalAlignButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=dt(),{state:r}=_r(()=>e.entityIds),o=[gt.Top,gt.Center,gt.Bottom],s=Ko(()=>e.entityIds,us),i=d.computed(()=>{let l=null;for(const c of s.value.values()){const u=(c==null?void 0:c.value)??gt.Top;if(l===null)l=u;else if(l!==u)return null}return l});function a(){const l=i.value??gt.Top,c=o.indexOf(l),u=o[(c+1)%o.length];n(f=>{for(const h of e.entityIds){const p=us.write(f,h);p.value=u}})}return(l,c)=>d.unref(r).showTextMenuButtons?(d.openBlock(),d.createBlock(Wi,{key:0,title:"Vertical Align",onClick:a},{default:d.withCtx(()=>[i.value===d.unref(gt).Top||i.value===null?(d.openBlock(),d.createElementBlock("svg",i6,[...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(gt).Center?(d.openBlock(),d.createElementBlock("svg",a6,[...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",l6,[...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)}}),c6={class:"wov-text-group-button"},u6={class:"wov-text-group-dropdown"},d6={class:"wov-text-group-row wov-text-group-row-full"},f6={class:"wov-text-group-row"},h6=d.defineComponent({__name:"TextButtonGroup",props:{entityIds:{},showVerticalAlign:{type:Boolean}},setup(t){const e=t,{state:n}=_r(()=>e.entityIds),r=d.inject("containerRef"),{width:o}=Yb(r),s=d.computed(()=>o.value>0&&o.value<600),i=d.ref(new Map);return d.provide(V0,i),(a,l)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createElementBlock(d.Fragment,{key:0},[s.value?(d.openBlock(),d.createBlock(Vn,{key:0,title:"Text Formatting",placement:"top"},{button:d.withCtx(()=>[d.createElementVNode("div",c6,[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(Fn,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createElementVNode("div",u6,[d.createElementVNode("div",d6,[d.createVNode(mp,{entityIds:t.entityIds},null,8,["entityIds"]),l[1]||(l[1]=d.createElementVNode("div",{class:"wov-text-group-spacer"},null,-1)),d.createVNode(gp,{entityIds:t.entityIds},null,8,["entityIds"])]),d.createElementVNode("div",f6,[d.createVNode(hp,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(yp,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(wp,{entityIds:t.entityIds},null,8,["entityIds"]),l[2]||(l[2]=d.createElementVNode("div",{class:"wov-text-group-spacer"},null,-1)),d.createVNode(vp,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(fp,{entityIds:t.entityIds},null,8,["entityIds"]),t.showVerticalAlign?(d.openBlock(),d.createBlock(Gb,{key:0,entityIds:t.entityIds},null,8,["entityIds"])):d.createCommentVNode("",!0)])])]),_:1})):(d.openBlock(),d.createElementBlock(d.Fragment,{key:1},[d.createVNode(mp,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(gp,{entityIds:t.entityIds},null,8,["entityIds"]),l[3]||(l[3]=d.createElementVNode("div",{divider:"",class:"wov-divider"},null,-1)),d.createVNode(hp,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(yp,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(wp,{entityIds:t.entityIds},null,8,["entityIds"]),l[4]||(l[4]=d.createElementVNode("div",{divider:"",class:"wov-divider"},null,-1)),d.createVNode(vp,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(fp,{entityIds:t.entityIds},null,8,["entityIds"]),t.showVerticalAlign?(d.openBlock(),d.createBlock(Gb,{key:0,entityIds:t.entityIds},null,8,["entityIds"])):d.createCommentVNode("",!0)],64))],64)):d.createCommentVNode("",!0)}}),Jb=d.defineComponent({__name:"CanvasBackground",props:{background:{}},setup(t){const e=t,n=Ut(we),r=Ut(Ht),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 T=0;T<v.subdivisionStep;T++){const I=(_+.5)*(S/v.subdivisionStep),B=(T+.5)*(k/v.subdivisionStep),Z=_===0&&T===0?2*b:b;c(E,I,B,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,T=k/v.subdivisionStep;for(let I=0;I<=v.subdivisionStep;I++){const B=I*_,L=I%v.subdivisionStep===0;f(E,B,0,B,k,L?3*b:b)}for(let I=0;I<=v.subdivisionStep;I++){const B=I*T,L=I%v.subdivisionStep===0;f(E,0,B,S,B,L?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,T=E+S/n.value.zoom,I=_+k/n.value.zoom;let B=w*b,L=v*b,Z=0,M=0,F=Number.POSITIVE_INFINITY,q=Number.POSITIVE_INFINITY;for(;;){B=b*w,L=b*v,Z=Math.floor(E/B)*B,M=Math.floor(_/L)*L;const qe=Math.ceil(T/B)*B,lr=Math.ceil(I/L)*L;if(q=Math.round((qe-Z)/w),F=Math.round((lr-M)/v),Math.max(q,F)>200)w*=2,v*=2;else break}const ue=w*n.value.zoom,se=v*n.value.zoom,j=Math.round(ue),ee=Math.round(se),fe=u(j,ee,e.background);if(!fe)return;fe.setTransform(new DOMMatrix().scale(ue/j,se/ee));const Me=(Z-E-w/2)*n.value.zoom,Ce=(M-_-v/2)*n.value.zoom;y.save(),y.translate(Me,Ce),y.fillStyle=fe,y.fillRect(0,0,S+B*n.value.zoom,k+L*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,T=E+S/n.value.zoom,I=_+k/n.value.zoom;let B=w*b,L=v*b,Z=0,M=0,F=Number.POSITIVE_INFINITY,q=Number.POSITIVE_INFINITY;for(;;){B=b*w,L=b*v,Z=Math.floor(E/B)*B,M=Math.floor(_/L)*L;const qe=Math.ceil(T/B)*B,lr=Math.ceil(I/L)*L;if(q=Math.round((qe-Z)/w),F=Math.round((lr-M)/v),Math.max(q,F)>200)w*=2,v*=2;else break}const ue=w*n.value.zoom,se=v*n.value.zoom,j=Math.round(ue),ee=Math.round(se),fe=h(j,ee,e.background);if(!fe)return;fe.setTransform(new DOMMatrix().scale(ue/j,se/ee));const Me=(Z-E)*n.value.zoom,Ce=(M-_)*n.value.zoom;y.save(),y.translate(Me,Ce),y.fillStyle=fe,y.fillRect(0,0,S+B*n.value.zoom,k+L*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 Xb(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 Qb=d.defineComponent({__name:"FloatingMenuBar",setup(t){const e=d.useSlots(),{reset:n}=qo(),r=d.inject(j0),{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(Ub,{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(Zb,{entityIds:d.unref(o)},null,8,["entityIds"]),d.createVNode(Hb,{entityIds:d.unref(o)},null,8,["entityIds"]),d.createVNode(Kb,{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(Wb,{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(Vb,{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(up,{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(up,{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(h6,{key:0,entityIds:d.unref(o),showVerticalAlign:d.unref(s).has("verticalAlign")},null,8,["entityIds","showVerticalAlign"])):d.createCommentVNode("",!0)]),d.createVNode(dp)],32))}}),p6={class:"wov-floating-menu-inner"},eS=d.defineComponent({__name:"FloatingMenu",setup(t){const e=d.inject(On),n=ab([A,xt]),r=Ut(we),o=Ut(_t),s=Ut(Qn),i=il(),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 Xb(S,k)});d.provide(j0,{selectedIds:a,commonComponents:l});const c=[0,0,0,0];function u(...S){let k=1/0,E=1/0,_=-1/0,T=-1/0,I=!1;for(const B of S){if(!B)continue;const L=B.getBoundingClientRect();L.width<=0||(I=!0,k=Math.min(k,L.left),E=Math.min(E,L.top),_=Math.max(_,L.right),T=Math.max(T,L.bottom))}return I?{x:k,y:E,left:k,top:E,right:_,bottom:T,width:_-k,height:T-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;mt.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 T=f.value;if(!T)return null;const I=S.getBoundingClientRect();return{getBoundingClientRect(){return{x:I.left+T[0],y:I.top+T[1],width:T[2]-T[0],height:T[3]-T[1],top:I.top+T[1],left:I.left+T[0],right:I.left+T[2],bottom:I.top+T[3]}}}}),m=d.ref(null),g={name:"clampToViewport",fn({y:S,rects:k}){const T=window.innerHeight-k.floating.height-8;return{y:Math.max(8,Math.min(S,T))}}},{floatingStyles:y}=Bu(p,m,{placement:"top",middleware:[Au(12),Nu({fallbackPlacements:["bottom"]}),Iu({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",p6,[d.renderSlot(S.$slots,"default",{},()=>[d.createVNode(Qb)])])],4)):d.createCommentVNode("",!0)]),_:3}))}}),m6={key:0,class:"wov-loading-overlay"},g6={class:"wov-loading-spinner"},tS=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",m6,[d.createElementVNode("div",g6,d.toDisplayString(e.value),1)])):d.createCommentVNode("",!0)]),_:1}))}}),y6={class:"wov-action-bar"},w6=d.defineComponent({__name:"ActionBar",setup(t){const{getEditor:e}=dt(),n=d.inject(On),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(Kd)}function i(){const l=e();l==null||l.command(Jl)}function a(){const l=e();l==null||l.command(tf)}return(l,c)=>(d.openBlock(),d.createElementBlock("div",y6,[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)])])]))}}),Ar=d.defineComponent({__name:"ToolbarButton",props:{name:{},tooltip:{},dragOutSnapshot:{},placementSnapshot:{},cursor:{default:"crosshair"}},setup(t){const e=t,n=d.inject(Tf);if(!n)throw new Error("ToolbarButton must be used within a Toolbar component");const r=n,o=d.ref(null),{show:s,hide:i}=qo(),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))}}),v6='<?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>',k6='<?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>',b6='<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>',js={Select:"select",Hand:"hand",Crosshair:"crosshair"},nS={[js.Select]:{makeSvg:()=>v6,hotspot:[1,0],rotationOffset:0},[js.Hand]:{makeSvg:()=>k6,hotspot:[12,12],rotationOffset:0},[js.Crosshair]:{makeSvg:()=>b6,hotspot:[12,12],rotationOffset:0}},S6={viewBox:"0 0 20 20",style:{"fill-rule":"evenodd","clip-rule":"evenodd","stroke-miterlimit":"10"}},rS=d.defineComponent({__name:"SelectTool",setup(t){const{nextEditorTick:e}=dt(),{activeTool:n}=np();return d.watch(n,(r,o)=>{o==="select"&&e(s=>{Si.spawn(s)})}),(r,o)=>(d.openBlock(),d.createBlock(Ar,{name:"select",tooltip:"Select",cursor:d.unref(js).Select},{default:d.withCtx(()=>[(d.openBlock(),d.createElementBlock("svg",S6,[...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"]))}}),oS=d.defineComponent({__name:"HandTool",setup(t){return(e,n)=>(d.openBlock(),d.createBlock(Ar,{name:"hand",tooltip:"Hand",cursor:d.unref(js).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"]))}}),sS=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:Wn.Center},verticalAlign:{value:gt.Center}});return(n,r)=>(d.openBlock(),d.createBlock(Ar,{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"]))}}),iS=d.defineComponent({__name:"ShapeTool",setup(t){const e=JSON.stringify({block:{tag:"shape",size:[200,200]},shape:{kind:"rectangle",strokeKind:zt.Solid,strokeWidth:2,strokeRed:0,strokeGreen:0,strokeBlue:0,strokeAlpha:255,fillRed:255,fillGreen:255,fillBlue:255,fillAlpha:0},text:{defaultAlignment:Wn.Center},verticalAlign:{value:gt.Center}});return(n,r)=>(d.openBlock(),d.createBlock(Ar,{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"]))}}),aS=d.defineComponent({__name:"EraserTool",setup(t){return(e,n)=>(d.openBlock(),d.createBlock(Ar,{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}))}}),lS=d.defineComponent({__name:"PenTool",setup(t){return(e,n)=>(d.openBlock(),d.createBlock(Ar,{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}))}}),cS=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(Ar,{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"]))}}),uS=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(Ar,{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"]))}}),dS=d.defineComponent({__name:"ImageTool",setup(t){const{nextEditorTick:e}=dt(),{show:n,hide:r}=qo(),{setTool:o}=np(),{createImageBlock:s}=ib(),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,js.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))}}),E6={class:"wov-toolbar-container"},fS=d.defineComponent({__name:"Toolbar",setup(t){const e=d.useSlots(),{reset:n}=qo(),{nextEditorTick:r}=dt(),o=d.ref(null),s=d.ref(null),i=Ut(ut),a=d.computed(()=>i.value.leftMouseTool),l=[rS,oS,cS,dS,iS,uS,sS,lS,aS],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}=Yb(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 Me;const j=S();if(j.length===0)return;g.value=j.length;const ee=getComputedStyle(h.value);w.value=parseFloat(ee.gap)||8;const fe=((Me=p.value)==null?void 0:Me.offsetWidth)||40;v.value=fe+w.value,y.value=j.map(Ce=>Ce.offsetWidth)}function E(){if(y.value.length===0)return;const fe=b.value-40-20,Me=w.value,Ce=v.value;let qe=0,lr=0;for(let so=0;so<y.value.length;so++){const Ys=y.value[so],Xo=qe>0?Ys+Me:Ys,Qo=y.value.length-so-1>0?Ce:0;if(qe+Xo+Qo<=fe)qe+=Xo,lr++;else break}m.value=Math.max(1,lr)}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((ee,fe)=>{ee.style.display=fe<m.value?"":"none"})}),d.watchEffect(()=>{if(!u.value)return;Array.from(u.value.children).forEach((ee,fe)=>{ee.style.display=fe>=m.value?"":"none"})});const{floatingStyles:T}=Bu(p,u,{placement:"top",middleware:[Au(16),Nu(),Iu({padding:8})],whileElementsMounted:Rb});function I(){f.value=!f.value}function B(){f.value=!1}function L(j){const ee=j.target;p.value&&!p.value.contains(ee)&&u.value&&!u.value.contains(ee)&&B()}d.watch(f,j=>{j?document.addEventListener("click",L,!0):document.removeEventListener("click",L,!0)}),d.watch(_,j=>{j||B()});function Z(j,ee,fe){s.value=ee??null,r(Me=>{const Ce=ut.write(Me);Ce.leftMouseTool=j,Ce.heldSnapshot=ee??"",fe&&Nn.setCursor(Me,fe)})}function M(j){r(ee=>{const fe=ut.write(ee);fe.leftMouseTool="drag-out",fe.heldSnapshot=j})}function F(j,ee){o.value=j,s.value=ee??null}function q(){o.value=null,s.value=null}function ue(){n(),o.value&&s.value&&M(s.value),o.value=null,s.value=null}const se={activeTool:a,heldTool:o,setTool:Z,dragOutTool:M,onToolPointerDown:F,onToolPointerUp:q};return d.provide(Tf,se),(j,ee)=>(d.openBlock(),d.createElementBlock("div",E6,[d.createVNode(w6),d.createElementVNode("div",{ref_key:"toolsContainerRef",ref:h,class:"wov-toolbar",onMouseleave:ue},[d.unref(e).default?d.renderSlot(j.$slots,"default",{key:0}):(d.openBlock(),d.createElementBlock(d.Fragment,{key:1},d.renderList(l,(fe,Me)=>d.createVNode(d.resolveDynamicComponent(fe),{key:Me})),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},[...ee[0]||(ee[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(dp)],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(T))},[d.unref(e).default?d.renderSlot(j.$slots,"default",{key:0}):(d.openBlock(),d.createElementBlock(d.Fragment,{key:1},d.renderList(l,(fe,Me)=>d.createVNode(d.resolveDynamicComponent(fe),{key:Me})),64))],4)):d.createCommentVNode("",!0)],8,["to"])):d.createCommentVNode("",!0)]))}}),C6=d.defineComponent({__name:"ArcArrowTool",setup(t){return(e,n)=>(d.openBlock(),d.createBlock(Ar,{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}))}}),_6={class:"wov-user-presence-avatars"},x6=["src","alt"],T6={class:"wov-user-presence-list"},M6=["src","alt"],A6={class:"wov-user-presence-name"},I6=4,hS=d.defineComponent({__name:"UserPresence",props:{users:{}},setup(t){const e=t,n=d.ref(!1),r=d.ref(null);UF(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,I6));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",_6,[(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,x6)):(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",T6,[(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,M6)):(d.openBlock(),d.createElementBlock(d.Fragment,{key:1},[d.createTextVNode(d.toDisplayString(c.initials),1)],64))],4),d.createElementVNode("span",A6,d.toDisplayString(c.name),1)]))),128))])],32)):d.createCommentVNode("",!0)],512)):d.createCommentVNode("",!0)}});async function kp(t,e){const n=await Ap(t,1,{upgrade(r){r.objectStoreNames.contains(e)||r.createObjectStore(e)}});return new N6(n,e)}var N6=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()}},B6=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([kp(`${t}-jobs`,"jobs"),kp(`${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))}}},P6="wovencanvas-assets",O6="blobs",D6=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=kp(P6,O6).then(t=>(this.store=t,t))),this.initPromise)}},pS=Zr.object({minZoom:Zr.number().default(.05),maxZoom:Zr.number().default(2.7)});pS.parse({});var ul=Co("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)}),Us=Ki({name:"pinchState"},{active:C.boolean().default(!1),prevDistance:C.float64().default(0),prevCenter:C.tuple(C.float64(),2).default([0,0])}),no=[0,0],zu=[0,0],dl=[0,0],bp=[0,0],Sp=[0,0];function R6(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(zu,t),$.sub(zu,no),$.set(dl,(n[0]+i*no[0])*s,(n[1]+i*no[1])*s);const h=[(n[0]-i*dl[0])*l,(n[1]-i*dl[1])*l],p=[zu[0]+(no[0]+dl[0])*l,zu[1]+(no[1]+dl[1])*l];return $.copy(bp,e),$.sub(bp,t),$.copy(Sp,p),$.sub(Sp,e),$.dot(bp,Sp)>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 Ep=.1,mS=.1,z6=$r({guards:{hasVelocity:({event:t})=>{if(t.type!=="pointerUp")return!1;const e=t.velocity;return Math.hypot(e[0],e[1])>mS},isGlideComplete:({context:t})=>Math.hypot(t.velocityX,t.velocityY)<mS,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:He({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:He(({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*Ep,targetY:r.top+i*Ep,expectedLeft:r.left,expectedTop:r.top}}),animateGlide:He(({context:t,event:e})=>{const n=e,{ctx:r,delta:o}=n,s=we.read(r),{position:i,velocity:a}=R6([s.left,s.top],[t.targetX,t.targetY],[t.velocityX,t.velocityY],Ep,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:He({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"}}}}}),$6=Se({phase:"input",priority:-100},t=>{const e=ul.read(t).state;if(Us.read(t).active){e!=="idle"&&ul.copy(t,ul.default());return}const r=ut.getButtons(t,"hand"),s=[...jr(t,r)];e==="gliding"&&s.push(iN(t)),s.push(...aN(t,[dn.Escape])),s.length!==0&&ul.run(t,z6,s)}),L6=ie(t=>t.with(Ct)),V6=Se({phase:"input",priority:-100},t=>{const e=ls(t,"controls"),n=L6.current(t),r=[];for(let m=0;m<n.length;m++){const g=n[m],y=Ct.read(t,g);y.pointerType===Vr.Touch&&r.push(y.position)}if(r.length!==2){if(Us.read(t).active){const g=Us.write(t);g.active=!1}return}const[o,s]=r,i=$.distance(o,s),a=$.midPoint(o,s),l=Us.read(t);if(!l.active){const m=Us.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,T=we.write(t);T.left-=E*S,T.top-=_*k,T.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=Us.write(t);p.prevDistance=i,p.prevCenter=a}),F6=Se({phase:"input",priority:-100},t=>{const e=Sn.read(t);if(!ut.wheelActive(t,"scroll",e.modDown))return;const r=Sy(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}),j6=Se({phase:"input",priority:-100},t=>{const e=ls(t,"controls"),n=Sn.read(t);if(!ut.wheelActive(t,"zoom",n.modDown))return;const o=Sy(t).find(S=>S.type==="wheel");if(!o)return;const s=we.read(t),i=_t.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,v=s.top-y*m,b=we.write(t);b.left=w,b.top=v,b.zoom=l});function U6(t={}){return{name:"controls",resources:pS.parse(t),singletons:[ul,Us],systems:[j6,F6,$6,V6]}}var W6=(t={})=>U6(t);const H6={class:"wov-selection-box"},Z6=d.defineComponent({__name:"SelectionBox",setup(t){return(e,n)=>(d.openBlock(),d.createElementBlock("div",H6))}}),K6={class:"wov-transform-box"},Y6=d.defineComponent({__name:"TransformBox",setup(t){return(e,n)=>(d.openBlock(),d.createElementBlock("div",K6))}}),q6={},G6={class:"wov-transform-handle"};function J6(t,e){return d.openBlock(),d.createElementBlock("div",G6)}const X6=ws(q6,[["render",J6]]),Q6=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,us),o=d.ref(null),s={[gt.Top]:"flex-start",[gt.Center]:"center",[gt.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)??gt.Top]}}),{handleEditEnd:a}=tp({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(yu,d.mergeProps(e,{"block-element":o.value,onEditEnd:d.unref(a)}),null,16,["block-element","onEditEnd"])],4))}}),$u=Ki({name:"blockPlacementState"},{editedCheckpoint:C.string().default("").max(36)}),gS=ie(t=>t.with(Lr));function e5(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 t5(t,e,n){const r=Kn(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||Q(t,l,me,{id:crypto.randomUUID()});const c=Object.assign({},e.block,{position:[s,i],size:o,rank:a});Q(t,l,A,c);for(const f of r.components)if(!(f.name in e))Q(t,l,f);else{const h=e[f.name];Q(t,l,f,h)}const{sessionId:u}=Ge(t);return Q(t,l,Rt,{sessionId:u}),l}function yS(t,e,n,r,o){const s=t5(t,e,n),i=A.read(t,s);if(cy(t,e.block.tag)&&(Q(t,s,xa,{}),o==="placement")){const{store:u}=ls(t,"editing"),f=u.createCheckpoint();if(f){const h=$u.write(t);h.editedCheckpoint=f}}const a=Qn.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=ut.write(t);l.leftMouseTool="select",l.heldSnapshot="";const c=Nn.write(t);c.cursorKind="select",c.rotation=0}function n5(t){const e=$u.read(t);if(e.editedCheckpoint){const n=e.editedCheckpoint;$u.write(t).editedCheckpoint="";const{store:r}=ls(t,"editing");r.onSettled(()=>r.squashToCheckpoint(n),{frames:5})}}const r5=Se({phase:"capture"},t=>{gS.removed(t).length>0&&gS.current(t).length===0&&n5(t);const e=ut.read(t);if(!e.heldSnapshot)return;const n=jr(t,[bn.Left]);if(n.length===0)return;const r=e5(e.heldSnapshot);if(!r)return;if(e.leftMouseTool==="drag-out"){const s=n.find(i=>i.type==="pointerMove"&&!i.obscured);if(!s)return;yS(t,r,s.worldPosition,s.screenPosition,"dragOut")}else{const s=n.find(i=>i.type==="pointerDown"&&!i.obscured);if(!s)return;yS(t,r,s.worldPosition,s.screenPosition,"placement")}}),o5=Se({phase:"update"},t=>{const{store:e}=ls(t,"editing");he(t,Kd,()=>{e.canUndo()&&(r0(t),e.undo())}),he(t,Jl,()=>{e.canRedo()&&(r0(t),e.redo())})}),s5=[{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 wS(t){return{name:"editing",resources:{store:t.store},singletons:[$u],systems:[r5,o5],cursors:nS,fonts:s5,keybinds:[{command:Kd.name,key:dn.Z,mod:!0},{command:Jl.name,key:dn.Y,mod:!0},{command:Jl.name,key:dn.Z,mod:!0,shift:!0}]}}const i5=d.defineComponent({__name:"FileDropZone",props:{maxSize:{default:400}},setup(t){const e=t,{nextEditorTick:n}=dt(),{createImageBlock:r}=ib(),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(T=>!T.startsWith("#")).find(T=>g(T));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),T=E.left+(b-_.left)/E.zoom,I=E.top+(S-_.top)/E.zoom;await r(v,T,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 T=new URL(v).pathname.split("/").pop()||"image",I=new File([E],T,{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))}}),a5={class:"wov-user-cursors"},l5={class:"wov-cursor-svg",viewBox:"0 0 4.35 4.75",width:"20",height:"20"},c5=["fill"],u5="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",d5=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",a5,[(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",l5,[d.createElementVNode("path",{fill:s.color,stroke:"#fff","stroke-miterlimit":"10","stroke-width":".25",d:u5},null,8,c5)])),d.createElementVNode("span",{class:"wov-cursor-label",style:d.normalizeStyle({backgroundColor:s.color})},d.toDisplayString(s.name),5)],4))),128))]))}}),f5={key:0,class:"wov-offline-indicator"},h5=d.defineComponent({__name:"OfflineIndicator",props:{isOnline:{type:Boolean}},setup(t){return(e,n)=>t.isOnline?d.createCommentVNode("",!0):(d.openBlock(),d.createElementBlock("div",f5,"Working Offline"))}}),p5={key:0,class:"wov-version-mismatch-overlay"},m5=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",p5,[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)}}),g5=d.defineComponent({__name:"BackToContentButton",setup(t){const{nextEditorTick:e}=dt(),n=Ut(we),r=ie(l=>l.with(me,A,Ve)),o=d.ref(0),s=d.inject(On);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)}}),y5=["data-entity-id","data-selected","data-held-by-other","data-hovered"],w5=d.defineComponent({__name:"WovenCanvas",props:{store:{},editor:{},background:{},assetProvider:{},pluginOptions:{},controls:{}},emits:["ready"],setup(t,{emit:e}){var vS;const n=ie(P=>P.tracking(A)),r=ie(P=>P.with(A).tracking(Ze)),o=ie(P=>P.with(A).tracking(xt)),s=ie(P=>P.with(A).tracking(Rt)),i=ie(P=>P.with(A).tracking(bo)),a=ie(P=>P.with(A).tracking(Lr)),l=ie(P=>P.with(A).tracking(ct)),c=ie(P=>P.tracking(Eo)),u=t,f=e,h=d.ref(null),p=d.shallowRef(null),m=Xg.parse(((vS=u.editor)==null?void 0:vS.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),T=d.ref(!1),I=d.ref(!0),B=d.shallowRef(we.default());function L(P,ke,W){let le=v.get(P);le||(le=new Map,v.set(P,le));let X=le.get(ke);return X||(X=new Set,le.set(ke,X)),X.add(W),()=>{X.delete(W),X.size===0&&(le.delete(ke),le.size===0&&v.delete(P))}}function Z(P,ke,W,le=!1){const X=v.get(ke);if(!X)return;const U=X.get(W.name);if(!U||U.size===0)return;let ht=null;le||(ht=W.snapshot(P,ke));for(const cr of U)cr(ht)}function M(P,ke){let W=b.get(P);return W||(W=new Set,b.set(P,W)),W.add(ke),()=>{W.delete(ke),W.size===0&&b.delete(P)}}function F(P,ke){const W=b.get(ke.name);if(!W||W.size===0)return;const le=ke.snapshot(P);for(const X of W)X(le)}function q(P){return S.add(P),()=>{S.delete(P)}}function ue(){return m.sessionId}function se(P){return y.get(P)??null}const j={hasEntity:P=>g.has(P),getEditor:()=>p.value,getAssetManager:()=>qe,getSessionId:ue,getUserBySessionId:se,subscribeComponent:L,subscribeSingleton:M,registerTickCallback:q};d.provide(On,j),d.provide("containerRef",h);const ee=mb();d.provide(U0,ee);let fe=0,Me=null,Ce=null,qe=null;async function lr(){!p.value||!Ce||(p.value.nextTick(P=>{Ys(P),Xo(P);for(const ke of S)ke(P);Ce&&Ce.sync(P)}),await p.value.tick(),Me=requestAnimationFrame(lr))}let so=null;d.onMounted(async()=>{var cr,pn;if(!h.value)return;so=()=>{var qs;(qs=h.value)==null||qs.scrollTo(0,0)},h.value.addEventListener("scroll",so);const P=u.store??{},ke={history:!0,...P};P.websocket&&(ke.websocket={...P.websocket,onVersionMismatch:qs=>{var io,fl;T.value=!0,(fl=(io=P.websocket)==null?void 0:io.onVersionMismatch)==null||fl.call(io,qs)},onConnectivityChange:qs=>{var io,fl;_.value=qs,(fl=(io=P.websocket)==null?void 0:io.onConnectivityChange)==null||fl.call(io,qs)}}),Ce=new om(ke);const W=[],le=u.pluginOptions;(le==null?void 0:le.controls)!==!1&&W.push(W6((le==null?void 0:le.controls)??{})),(le==null?void 0:le.selection)!==!1&&W.push(fP((le==null?void 0:le.selection)||void 0)),(le==null?void 0:le.eraser)!==!1&&W.push(ZO((le==null?void 0:le.eraser)||void 0)),(le==null?void 0:le.pen)!==!1&&W.push(OD()),(le==null?void 0:le.arrows)!==!1&&W.push(iO((le==null?void 0:le.arrows)||void 0)),W.push(wS({store:Ce})),(cr=u.editor)!=null&&cr.plugins&&W.push(...u.editor.plugins);const X={...u.editor,user:m,plugins:W,controls:u.controls},U=new rN(h.value,X);await U.initialize(),await Ce.initialize({components:U.components,singletons:U.singletons});const ht=((pn=P.persistence)==null?void 0:pn.documentId)??"default";qe=new B6({provider:u.assetProvider??new D6,documentId:ht}),await qe.init(),await qe.resumePendingUploads(),p.value=U,Me=requestAnimationFrame(lr),I.value=!1,f("ready",U,Ce)}),d.onUnmounted(()=>{var P;Me!==null&&cancelAnimationFrame(Me),qe==null||qe.close(),Ce==null||Ce.close(),(P=p.value)==null||P.dispose()});function Ys(P){const{events:ke,newIndex:W}=P.eventBuffer.readEvents(fe);if(fe=W,ke.length===0)return;const{componentsById:le,singletonsById:X}=Ge(P);for(const{entityId:U,eventType:ht,componentId:cr}of ke){if(U===Js){if(ht===Le.CHANGED){const pn=X.get(cr);pn&&F(P,pn)}continue}if(ht===Le.ADDED)g.add(U);else if(ht===Le.REMOVED)g.delete(U),v.delete(U);else if(ht===Le.COMPONENT_ADDED){g.add(U);const pn=le.get(cr);pn&&Z(P,U,pn)}else if(ht===Le.COMPONENT_REMOVED){const pn=le.get(cr);pn&&Z(P,U,pn,!0)}else if(ht===Le.CHANGED){const pn=le.get(cr);pn&&Z(P,U,pn)}}}function Xo(P){var le;let ke=!1;for(const X of n.added(P)){const U=A.snapshot(P,X),ht=(le=p.value)==null?void 0:le.blockDefs[U.tag],cr=(ht==null?void 0:ht.stratum)??"content";k.set(X,d.ref({entityId:X,block:U,stratum:cr,selected:!1,held:null,hovered:!1,edited:!1,opacity:null,connector:null})),ke=!0}for(const X of n.removed(P))k.delete(X),ke=!0;for(const X of n.changed(P)){const U=k.get(X);if(U){const ht=A.snapshot(P,X);U.value.block.rank!==ht.rank&&(ke=!0),U.value.block=ht}}let W=!1;for(const X of c.addedOrChanged(P)){const U=Eo.snapshot(P,X);y.set(U.sessionId,U),W=!0}for(const X of c.removed(P)){const U=Eo.read(P,X);y.delete(U.sessionId),W=!0}W&&(w.value=Array.from(y.values()));for(const X of o.added(P)){const U=k.get(X);U&&!U.value.selected&&(U.value.selected=!0)}for(const X of o.removed(P)){const U=k.get(X);U&&U.value.selected&&(U.value.selected=!1)}for(const X of s.addedOrChanged(P)){const U=k.get(X);U&&(U.value.held=Rt.snapshot(P,X))}for(const X of s.removed(P)){const U=k.get(X);U&&U.value.held!==null&&(U.value.held=null)}for(const X of i.added(P)){const U=k.get(X);U&&!U.value.hovered&&(U.value.hovered=!0)}for(const X of i.removed(P)){const U=k.get(X);U&&U.value.hovered&&(U.value.hovered=!1)}for(const X of a.added(P)){const U=k.get(X);U&&!U.value.edited&&(U.value.edited=!0)}for(const X of a.removed(P)){const U=k.get(X);U&&U.value.edited&&(U.value.edited=!1)}for(const X of l.addedOrChanged(P)){const U=k.get(X);U&&(U.value.opacity=ct.snapshot(P,X))}for(const X of l.removed(P)){const U=k.get(X);U&&U.value.opacity!==null&&(U.value.opacity=null)}for(const X of r.addedOrChanged(P)){const U=k.get(X);U&&(U.value.connector=Ze.snapshot(P,X))}for(const X of r.removed(P)){const U=k.get(X);U&&U.value.connector!==null&&(U.value.connector=null)}if(ke){const X=Array.from(k.values());X.sort((U,ht)=>U.value.block.rank>ht.value.block.rank?1:-1),E.value=X}}M(we.name,P=>{P&&(B.value=P)});function Lu(P){const ke=P.rotateZ!==0,W=P.flip[0],le=P.flip[1];if(!ke&&!W&&!le)return;const X=[];return ke&&X.push(`rotate(${P.rotateZ}rad)`),W&&X.push("scaleX(-1)"),le&&X.push("scaleY(-1)"),X.join(" ")}function Hi(P){const{held:ke}=P;if(!ke||!ke.sessionId||ke.sessionId===m.sessionId)return null;const W=se(ke.sessionId);return(W==null?void 0:W.color)??null}function Qo(P){const{block:ke,stratum:W,opacity:le}=P,X=Hi(P),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:Fd[W]*1e3,transform:Lu(ke),opacity:U,pointerEvents:"none",userSelect:"none","--wov-held-by-color":X??void 0,transition:U===1?"opacity 0ms 32ms":void 0}}return(P,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(P.$slots,"background",{key:0,background:t.background},()=>[d.createVNode(Jb,{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(${B.value.zoom}) translate(${-B.value.left}px, ${-B.value.top}px)`,"--wov-zoom":B.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(Qo(W.value)),"data-selected":W.value.selected||void 0,"data-held-by-other":Hi(W.value)!==null||void 0,"data-hovered":W.value.hovered||void 0,class:"wov-block"},[d.renderSlot(P.$slots,`block:${W.value.block.tag}`,d.mergeProps({ref_for:!0},W.value),()=>[W.value.block.tag==="selection-box"?(d.openBlock(),d.createBlock(Z6,d.mergeProps({key:0,ref_for:!0},W.value),null,16)):W.value.block.tag==="transform-box"?(d.openBlock(),d.createBlock(Y6,d.mergeProps({key:1,ref_for:!0},W.value),null,16)):W.value.block.tag==="transform-handle"?(d.openBlock(),d.createBlock(X6,d.mergeProps({key:2,ref_for:!0},W.value),null,16)):W.value.block.tag==="arrow-handle"?(d.openBlock(),d.createBlock(H0,d.mergeProps({key:3,ref_for:!0},W.value),null,16)):W.value.block.tag==="arrow-terminal"?(d.openBlock(),d.createBlock(Z0,d.mergeProps({key:4,ref_for:!0},W.value),null,16)):W.value.block.tag==="sticky-note"?(d.openBlock(),d.createBlock(Q6,d.mergeProps({key:5,ref_for:!0},W.value),null,16)):W.value.block.tag==="eraser"?(d.openBlock(),d.createBlock(gw,d.mergeProps({key:6,ref_for:!0},W.value),null,16)):W.value.block.tag==="pen-stroke"?(d.openBlock(),d.createBlock(Mw,d.mergeProps({key:7,ref_for:!0},W.value),null,16)):W.value.block.tag==="arc-arrow"?(d.openBlock(),d.createBlock(W0,d.mergeProps({key:8,ref_for:!0},W.value),null,16)):W.value.block.tag==="elbow-arrow"?(d.openBlock(),d.createBlock(K0,d.mergeProps({key:9,ref_for:!0},W.value),null,16)):W.value.block.tag==="text"?(d.openBlock(),d.createBlock(yb,d.mergeProps({key:10,ref_for:!0},W.value),null,16)):W.value.block.tag==="image"?(d.openBlock(),d.createBlock(yw,d.mergeProps({key:11,ref_for:!0},W.value),null,16)):W.value.block.tag==="shape"?(d.openBlock(),d.createBlock(gb,d.mergeProps({key:12,ref_for:!0},W.value),null,16)):d.createCommentVNode("",!0)])],12,y5))),128))],4),p.value?d.renderSlot(P.$slots,"user-cursors",{key:1,users:w.value,currentSessionId:d.unref(m).sessionId,camera:B.value},()=>[d.createVNode(d5,{users:w.value,"current-session-id":d.unref(m).sessionId,camera:B.value},null,8,["users","current-session-id","camera"])]):d.createCommentVNode("",!0),p.value?(d.openBlock(),d.createBlock(eS,{key:2},{default:d.withCtx(W=>[d.renderSlot(P.$slots,"floating-menu",d.normalizeProps(d.guardReactiveProps(W)))]),_:3})):d.createCommentVNode("",!0),p.value?d.renderSlot(P.$slots,"user-presence",{key:3,users:w.value},()=>[d.createVNode(hS,{users:w.value},null,8,["users"])]):d.createCommentVNode("",!0),p.value?d.renderSlot(P.$slots,"toolbar",{key:4},()=>[d.createVNode(fS)]):d.createCommentVNode("",!0),p.value?d.renderSlot(P.$slots,"default",{key:5}):d.createCommentVNode("",!0),d.renderSlot(P.$slots,"offline-indicator",{isOnline:_.value},()=>[d.createVNode(h5,{"is-online":_.value},null,8,["is-online"])]),d.renderSlot(P.$slots,"version-mismatch",{versionMismatch:T.value},()=>[d.createVNode(m5,{"version-mismatch":T.value},null,8,["version-mismatch"])]),d.renderSlot(P.$slots,"back-to-content",{},()=>[d.createVNode(g5)]),d.renderSlot(P.$slots,"loading",{isLoading:I.value},()=>[d.createVNode(tS,{"is-loading":I.value},null,8,["is-loading"])]),p.value?d.renderSlot(P.$slots,"file-drop-zone",{key:6},()=>[d.createVNode(i5)]):d.createCommentVNode("",!0)],512))}});V.ARROW_HEADS=xf,V.ArcArrow=W0,V.ArcArrowTool=C6,V.ArrowHandle=H0,V.ArrowHead=Kr,V.ArrowHeadButton=up,V.ArrowTerminal=Z0,V.ArrowThicknessButton=Vb,V.CURSORS=nS,V.CanvasBackground=Jb,V.CanvasComponentDef=Gt,V.CanvasSingletonDef=kt,V.CanvasStore=om,V.ColorButton=Ub,V.ColorPicker=jb,V.CursorKind=js,V.EditableText=yu,V.EditingPlugin=wS,V.ElbowArrow=K0,V.ElbowArrowTool=uS,V.Eraser=gw,V.EraserTool=aS,V.FloatingMenu=eS,V.FloatingMenuBar=Qb,V.HandTool=oS,V.IconChevronDown=Fn,V.ImageBlock=yw,V.ImageTool=dS,V.LoadingOverlay=tS,V.MenuButton=Wi,V.MenuDropdown=Vn,V.MenuTooltip=dp,V.PenStroke=Mw,V.PenStrokeThicknessButton=Wb,V.PenTool=lS,V.SHAPES=Oa,V.SelectTool=rS,V.ShapeBlock=gb,V.ShapeFillColorButton=Hb,V.ShapeKindButton=Zb,V.ShapeStrokeColorButton=Kb,V.ShapeTool=iS,V.StickyNoteTool=sS,V.Synced=me,V.TextAlignmentButton=fp,V.TextBlock=yb,V.TextBoldButton=hp,V.TextColorButton=vp,V.TextFontFamilyButton=mp,V.TextFontSizeButton=gp,V.TextItalicButton=yp,V.TextTool=cS,V.TextUnderlineButton=wp,V.Toolbar=fS,V.ToolbarButton=Ar,V.UserPresence=hS,V.WovenCanvas=w5,V.computeCommonComponents=Xb,V.createTooltipContext=mb,V.defineCanvasComponent=Qe,V.defineCanvasSingleton=Ki,V.getArrowHead=xi,V.useComponent=Tt,V.useComponents=Ko,V.useEditorContext=dt,V.useFonts=qb,V.useQuery=ab,V.useSingleton=Ut,V.useTextBatchController=pb,V.useTextEditorController=il,V.useTextFormatting=_r,V.useTextStretchBehavior=tp,V.useToolbar=np,V.useTooltipSingleton=qo,Object.defineProperty(V,Symbol.toStringTag,{value:"Module"})});
170
+ `):""}),r0=PN,o0="&nbsp;",RN=" ",DN=wd.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:t}){return["p",vo(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===o0||r[0].text===RN)?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?o0:e.renderChildren(n)},addCommands(){return{setParagraph:()=>({commands:t})=>t.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),s0=DN,zN=wd.create({name:"text",group:"inline",parseMarkdown:t=>({type:"text",text:t.text||""}),renderMarkdown:t=>t.text||""}),i0=zN,a0=(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]},$N=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,VN=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,LN=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,FN=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,jN=As.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 a0("strong",{...vo(this.options.HTMLAttributes,t),children:a0("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[pa({find:$N,type:this.type}),pa({find:LN,type:this.type})]},addPasteRules(){return[ma({find:VN,type:this.type}),ma({find:FN,type:this.type})]}}),l0=jN,HN=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,WN=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,ZN=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,UN=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,KN=As.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",vo(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[pa({find:HN,type:this.type}),pa({find:ZN,type:this.type})]},addPasteRules(){return[ma({find:WN,type:this.type}),ma({find:UN,type:this.type})]}}),c0=KN,JN=As.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",vo(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()}}}),d0=JN,qN=be.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")}}}),u0=qN,GN=20,f0=(t,e=0)=>{const n=[];return!t.children.length||e>GN||Array.from(t.children).forEach(r=>{r.tagName==="SPAN"?n.push(r):r.children.length&&n.push(...f0(r,e+1))}),n},YN=t=>{if(!t.children.length)return;const e=f0(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}`)})},vd=As.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!0}},parseHTML(){return[{tag:"span",consuming:!1,getAttrs:t=>t.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&YN(t),{}):!1}]},renderHTML({HTMLAttributes:t}){return["span",vo(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}}}}),XN=be.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()}}}),h0=be.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()}}}),QN=be.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()}}}),eB=be.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()}}}),tB=be.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()}}});be.create({name:"textStyleKit",addExtensions(){const t=[];return this.options.backgroundColor!==!1&&t.push(XN.configure(this.options.backgroundColor)),this.options.color!==!1&&t.push(h0.configure(this.options.color)),this.options.fontFamily!==!1&&t.push(QN.configure(this.options.fontFamily)),this.options.fontSize!==!1&&t.push(eB.configure(this.options.fontSize)),this.options.lineHeight!==!1&&t.push(tB.configure(this.options.lineHeight)),this.options.textStyle!==!1&&t.push(vd.configure(this.options.textStyle)),t}});var p0=h0;function nB(t={}){return new Oe({view(e){return new rB(e,t)}})}class rB{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,p=e.nodeAfter;if(f||p){let m=this.editorView.nodeDOM(this.cursorPos-(f?f.nodeSize:0));if(m){let g=m.getBoundingClientRect(),y=f?g.bottom:g.top;f&&p&&(y=(y+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let k=this.width/2*a;r={left:g.left,right:g.right,top:y-k,bottom:y+k}}}}if(!r){let f=this.editorView.coordsAtPos(this.cursorPos),p=this.width/2*i;r={left:f.left-p,right:f.left+p,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(),p=f.width/l.offsetWidth,m=f.height/l.offsetHeight;c=f.left-l.scrollLeft*p,u=f.top-l.scrollTop*m}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=Om(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 xe extends ie{constructor(e){super(e,e)}map(e,n){let r=e.resolve(n.map(this.head));return xe.valid(r)?new xe(r):ie.near(r)}content(){return L.empty}eq(e){return e instanceof xe&&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 xe(e.resolve(n.pos))}getBookmark(){return new bd(this.anchor)}static valid(e){let n=e.parent;if(n.isTextblock||!oB(e)||!sB(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&&xe.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(xe.valid(l))return l}for(;;){let i=n>0?s.firstChild:s.lastChild;if(!i){if(s.isAtom&&!s.isText&&!G.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(xe.valid(a))return a}return null}}}xe.prototype.visible=!1,xe.findFrom=xe.findGapCursorFrom,ie.jsonID("gapcursor",xe);class bd{constructor(e){this.pos=e}map(e){return new bd(e.map(this.pos))}resolve(e){let n=e.resolve(this.pos);return xe.valid(n)?new xe(n):ie.near(n)}}function m0(t){return t.isAtom||t.spec.isolating||t.spec.createGapCursor}function oB(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||m0(o.type))return!0;if(o.inlineContent)return!1}}return!0}function sB(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||m0(o.type))return!0;if(o.inlineContent)return!1}}return!0}function iB(){return new Oe({props:{decorations:dB,createSelectionBetween(t,e,n){return e.pos==n.pos&&xe.valid(n)?new xe(n):null},handleClick:lB,handleKeyDown:aB,handleDOMEvents:{beforeinput:cB}}})}const aB=wy({ArrowLeft:ga("horiz",-1),ArrowRight:ga("horiz",1),ArrowUp:ga("vert",-1),ArrowDown:ga("vert",1)});function ga(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 re){if(!s.endOfTextblock(n)||a.depth==0)return!1;l=!1,a=r.doc.resolve(e>0?a.after():a.before())}let c=xe.findGapCursorFrom(a,e,l);return c?(o&&o(r.tr.setSelection(new xe(c))),!0):!1}}function lB(t,e,n){if(!t||!t.editable)return!1;let r=t.state.doc.resolve(e);if(!xe.valid(r))return!1;let o=t.posAtCoords({left:n.clientX,top:n.clientY});return o&&o.inside>-1&&G.isSelectable(t.state.doc.nodeAt(o.inside))?!1:(t.dispatch(t.state.tr.setSelection(new xe(r))),!0)}function cB(t,e){if(e.inputType!="insertCompositionText"||!(t.state.selection instanceof xe))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=B.empty;for(let i=r.length-1;i>=0;i--)o=B.from(r[i].createAndFill(null,o));let s=t.state.tr.replace(n.pos,n.pos,new L(o,0,0));return s.setSelection(re.near(s.doc.resolve(n.pos+1))),t.dispatch(s),!1}function dB(t){if(!(t.selection instanceof xe))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",Ce.create(t.doc,[nt.widget(t.selection.head,e,{key:"gapcursor"})])}var ya=200,$e=function(){};$e.prototype.append=function(e){return e.length?(e=$e.from(e),!this.length&&e||e.length<ya&&this.leafAppend(e)||this.length<ya&&e.leafPrepend(this)||this.appendInner(e)):this},$e.prototype.prepend=function(e){return e.length?$e.from(e).append(this):this},$e.prototype.appendInner=function(e){return new uB(this,e)},$e.prototype.slice=function(e,n){return e===void 0&&(e=0),n===void 0&&(n=this.length),e>=n?$e.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,n))},$e.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)},$e.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)},$e.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},$e.from=function(e){return e instanceof $e?e:e&&e.length?new g0(e):$e.empty};var g0=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<=ya)return new e(this.values.concat(o.flatten()))},e.prototype.leafPrepend=function(o){if(this.length+o.length<=ya)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}($e);$e.empty=new g0([]);var uB=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}($e);const fB=500;class Ot{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,p)=>{if(!f.step){o||(o=this.remapping(r,p+1),s=o.maps.length),s--,u.push(f);return}if(o){u.push(new Jt(f.map));let m=f.step.map(o.slice(s)),g;m&&i.maybeStep(m).doc&&(g=i.mapping.maps[i.mapping.maps.length-1],c.push(new Jt(g,void 0,void 0,c.length+u.length))),s--,g&&o.appendMap(g,s)}else i.maybeStep(f.step);if(f.selection)return a=o?f.selection.map(o.slice(s)):f.selection,l=new Ot(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]),p=new Jt(e.mapping.maps[u],f,n),m;(m=l&&l.merge(p))&&(p=m,u?s.pop():a=a.slice(0,a.length-1)),s.push(p),n&&(i++,n=void 0),o||(l=p)}let c=i-r.depth;return c>pB&&(a=hB(a,c),i-=c),new Ot(a.append(s),i)}remapping(e,n){let r=new ds;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 Ot(this.items.append(e.map(n=>new Jt(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(p=>{p.selection&&a--},o);let l=n;this.items.forEach(p=>{let m=s.getMirror(--l);if(m==null)return;i=Math.min(i,m);let g=s.maps[m];if(p.step){let y=e.steps[m].invert(e.docs[m]),k=p.selection&&p.selection.map(s.slice(l+1,m));k&&a++,r.push(new Jt(g,y,k))}else r.push(new Jt(g))},o);let c=[];for(let p=n;p<i;p++)c.push(new Jt(s.maps[p]));let u=this.items.slice(0,o).append(c).append(r),f=new Ot(u,a);return f.emptyItemCount()>fB&&(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 Jt(c.invert(),l,u),p,m=o.length-1;(p=o.length&&o[m].merge(f))?o[m]=p:o.push(f)}}else i.map&&r--},this.items.length,0),new Ot($e.from(o.reverse()),s)}}Ot.empty=new Ot($e.empty,0);function hB(t,e){let n;return t.forEach((r,o)=>{if(r.selection&&e--==0)return n=o,!1}),t.slice(n)}class Jt{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 Jt(n.getMap().invert(),n,this.selection)}}}class Hn{constructor(e,n,r,o,s){this.done=e,this.undone=n,this.prevRanges=r,this.prevTime=o,this.prevComposition=s}}const pB=20;function mB(t,e,n,r){let o=n.getMeta(Tr),s;if(o)return o.historyState;n.getMeta(kB)&&(t=new Hn(t.done,t.undone,null,0,-1));let i=n.getMeta("appendedTransaction");if(n.steps.length==0)return t;if(i&&i.getMeta(Tr))return i.getMeta(Tr).redo?new Hn(t.done.addTransform(n,void 0,r,ka(e)),t.undone,y0(n.mapping.maps),t.prevTime,t.prevComposition):new Hn(t.done,t.undone.addTransform(n,void 0,r,ka(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||!gB(n,t.prevRanges)),c=i?Sd(t.prevRanges,n.mapping):y0(n.mapping.maps);return new Hn(t.done.addTransform(n,l?e.selection.getBookmark():void 0,r,ka(e)),Ot.empty,c,n.time,a??t.prevComposition)}else return(s=n.getMeta("rebased"))?new Hn(t.done.rebased(n,s),t.undone.rebased(n,s),Sd(t.prevRanges,n.mapping),t.prevTime,t.prevComposition):new Hn(t.done.addMaps(n.mapping.maps),t.undone.addMaps(n.mapping.maps),Sd(t.prevRanges,n.mapping),t.prevTime,t.prevComposition)}function gB(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 y0(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 Sd(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 yB(t,e,n){let r=ka(e),o=Tr.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 Hn(n?a:s.remaining,n?s.remaining:a,null,0,-1);return s.transform.setSelection(i).setMeta(Tr,{redo:n,historyState:l})}let Cd=!1,k0=null;function ka(t){let e=t.plugins;if(k0!=e){Cd=!1,k0=e;for(let n=0;n<e.length;n++)if(e[n].spec.historyPreserveItems){Cd=!0;break}}return Cd}const Tr=new Qe("history"),kB=new Qe("closeHistory");function wB(t={}){return t={depth:t.depth||100,newGroupDelay:t.newGroupDelay||500},new Oe({key:Tr,state:{init(){return new Hn(Ot.empty,Ot.empty,null,0,-1)},apply(e,n,r){return mB(n,r,e,t)}},config:t,props:{handleDOMEvents:{beforeinput(e,n){let r=n.inputType,o=r=="historyUndo"?v0:r=="historyRedo"?b0:null;return!o||!e.editable?!1:(n.preventDefault(),o(e.state,e.dispatch))}}}})}function w0(t,e){return(n,r)=>{let o=Tr.getState(n);if(!o||(t?o.undone:o.done).eventCount==0)return!1;if(r){let s=yB(o,n,t);s&&r(e?s.scrollIntoView():s)}return!0}}const v0=w0(!1,!0),b0=w0(!0,!0);be.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 Oe({key:new Qe("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)}})]}}),be.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[nB(this.options)]}}),be.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new Oe({key:new Qe("focus"),props:{decorations:({doc:t,selection:e})=>{const{isEditable:n,isFocused:r}=this.editor,{anchor:o}=e,s=[];if(!n||!r)return Ce.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(nt.node(c,c+l.nodeSize,{class:this.options.className}))}),Ce.create(t,s)}}})]}}),be.create({name:"gapCursor",addProseMirrorPlugins(){return[iB()]},extendNodeSchema(t){var e;const n={name:t.name,options:t.options,storage:t.storage};return{allowGapCursor:(e=ke(U(t,"allowGapCursor",n)))!=null?e:null}}});var S0="placeholder";function vB(t){return t.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}be.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:S0,placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){const t=this.options.dataAttribute?`data-${vB(this.options.dataAttribute)}`:`data-${S0}`;return[new Oe({key:new Qe("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&&ca(a);if((c||!this.options.showOnlyCurrent)&&u){const f=[this.options.emptyNodeClass];i&&f.push(this.options.emptyEditorClass);const p=nt.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(p)}return this.options.includeChildren}),Ce.create(e,s)}}})]}}),be.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){const{editor:t,options:e}=this;return[new Oe({key:new Qe("selection"),props:{decorations(n){return n.selection.empty||t.isFocused||!t.isEditable||zA(n.selection)||t.view.dragging?null:Ce.create(n.doc,[nt.inline(n.selection.from,n.selection.to,{class:e.className})])}}})]}});function C0({types:t,node:e}){return e&&Array.isArray(t)&&t.includes(e.type)||(e==null?void 0:e.type)===t}be.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var t;const e=new Qe(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 Oe({key:e,appendTransaction:(o,s,i)=>{const{doc:a,tr:l,schema:c}=i,u=e.getState(i),f=a.content.size,p=c.nodes[n];if(u)return l.insert(f,p.create())},state:{init:(o,s)=>{const i=s.tr.doc.lastChild;return!C0({node:i,types:r})},apply:(o,s)=>{if(!o.docChanged||o.getMeta("__uniqueIDTransaction"))return s;const i=o.doc.lastChild;return!C0({node:i,types:r})}}})]}});var bB=be.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:t,dispatch:e})=>v0(t,e),redo:()=>({state:t,dispatch:e})=>b0(t,e)}},addProseMirrorPlugins(){return[wB(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 Wn(t,e){const n=d.inject(pt);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(h.hasComponent(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 x0(){const t=d.inject(pt);if(!t)throw new Error("useImageCreation must be used within a WovenCanvas component");const{nextEditorTick:e}=Ee();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(),p=Math.min(1,c/Math.max(u.width,u.height));let m=Math.round(u.width*p),g=Math.round(u.height*p);const y=h.Grid.read(f);y.enabled&&(m=Math.max(y.colWidth,Math.round(m/y.colWidth)*y.colWidth),g=Math.max(y.rowHeight,Math.round(g/y.rowHeight)*y.rowHeight));const k=h.createEntity(f);h.addComponent(f,k,h.Block);const w=h.Block.write(f,k);w.tag="image",w.position[0]=i-m/2,w.position[1]=a-g/2,w.size[0]=m,w.size[1]=g,h.Grid.snapPosition(f,w.position);const v=crypto.randomUUID();h.addComponent(f,k,h.Asset);const b=h.Asset.write(f,k);b.identifier=v,b.uploadState=h.UploadState.Pending,h.addComponent(f,k,h.Image);const S=h.Image.write(f,k);return S.width=u.width,S.height=u.height,S.alt=s.name,h.addComponent(f,k,at.Synced,{id:crypto.randomUUID()}),(t==null?void 0:t.getAssetManager())&&o(k,v,s),k}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=h.Asset.write(c,s);u.uploadState=h.UploadState.Complete}catch{const c=await e(),u=h.Asset.write(c,s);u.uploadState=h.UploadState.Failed}}return{getImageDimensions:n,createImageBlock:r}}function _0(t){const e=d.inject(pt);if(!e)throw new Error("useQuery must be used within a WovenCanvas component");const n=d.shallowRef([]),r=h.defineQuery(f=>f.with(...t)),o=new Map;let s=!1;function i(f){const p=e.getEditor();if(!p)return{refs:{},unsubscribes:[]};const m=p._getContext(),g={},y=[];for(const k of t){const w=d.shallowRef(k.snapshot(m,f));g[k.name]=w;const v=e.subscribeComponent(f,k.name,b=>{w.value=b});y.push(v)}return{refs:g,unsubscribes:y}}function a(f){const p=o.get(f);if(p){for(const m of p.unsubscribes)m();o.delete(f)}}function l(){const f=[];for(const[p,m]of o)f.push({entityId:p,...m.refs});return f}function c(f){if(!s){const y=r.current(f);for(const k of y)o.set(k,i(k));n.value=l(),s=!0;return}const p=r.added(f),m=r.removed(f);let g=!1;for(const y of m)a(y),g=!0;for(const y of p)o.has(y)||(o.set(y,i(y)),g=!0);g&&(n.value=l())}const u=e.registerTickCallback(c);return d.onUnmounted(()=>{u();for(const f of o.keys())a(f)}),n}function Ze(t){const e=d.inject(pt);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 SB(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 xd(t,e,n){const r=t.closest(".wov-block");if(!r){const x=t.getBoundingClientRect();return{width:x.width,height:x.height,left:0,top:0}}const o=window.getComputedStyle(r).transform,s=new DOMMatrix(o),i=Math.atan2(s.b,s.a),a=t.getBoundingClientRect(),l=n.value.left,c=n.value.top,u=new DOMPoint(a.left+a.width/2-l,a.top+a.height/2-c),f=e.value.left,p=e.value.top,m=e.value.zoom,g=new DOMMatrix;g.translateSelf(-f*m,-p*m),g.scaleSelf(m,m),g.invertSelf();const y=g.transformPoint(u),k=g.transformPoint(new DOMPoint(a.left-l,a.top-c)),w=g.transformPoint(new DOMPoint(a.right-l,a.bottom-c)),v=w.x-k.x,b=w.y-k.y,{width:S,height:C}=SB(v,b,-i);return{width:S,height:C,left:y.x-S/2,top:y.y-C/2}}function E0(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 Ns(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 _d(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 T0(t){const e=_d(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 M0(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 p=m=>Math.round(m*255).toString(16).padStart(2,"0");return`#${p(o)}${p(s)}${p(i)}`}function A0(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 p=g=>Math.round(g*255).toString(16).padStart(2,"0"),m=Math.round(t.a).toString(16).padStart(2,"0");return t.a<255?`#${p(o)}${p(s)}${p(i)}${m}`:`#${p(o)}${p(s)}${p(i)}`}const st=d.shallowRef(null),Ed=d.shallowRef(null),Td=d.shallowRef(null),Zn=d.ref(0);function Bs(){const t={hasEditor:d.computed(()=>st.value!==null),isBold:d.computed(()=>{var o;return Zn.value,((o=st.value)==null?void 0:o.isActive("bold"))??!1}),isItalic:d.computed(()=>{var o;return Zn.value,((o=st.value)==null?void 0:o.isActive("italic"))??!1}),isUnderline:d.computed(()=>{var o;return Zn.value,((o=st.value)==null?void 0:o.isActive("underline"))??!1}),alignment:d.computed(()=>{Zn.value;const o=st.value;return o?o.isActive({textAlign:"center"})?"center":o.isActive({textAlign:"right"})?"right":o.isActive({textAlign:"justify"})?"justify":"left":"left"}),color:d.computed(()=>{Zn.value;const o=st.value;if(!o)return null;const i=o.getAttributes("textStyle").color??null;return i?E0(i):null})},e={toggleBold(){const o=st.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=st.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=st.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=st.value;s&&s.chain().selectAll().setTextAlign(o).run()},setColor(o){const s=st.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){st.value=o,Td.value=s,Ed.value=i,o.on("selectionUpdate",()=>{Zn.value++}),o.on("transaction",()=>{Zn.value++})}function r(){st.value=null,Td.value=null,Ed.value=null}return{editor:st,blockElement:Ed,textElement:Td,state:t,commands:e,updateCounter:Zn,register:n,unregister:r}}const vt=[r0,s0,i0,vd,p0,l0,c0,d0,u0.configure({types:["paragraph"],alignments:["left","center","right","justify"],defaultAlignment:"left"})];function CB(t){return t.type==="text"&&typeof t.text=="string"}function Mr(t,e){if(CB(t)){e(t);return}if(t.content)for(const n of t.content)Mr(n,e)}function Md(t,e){if(t.type==="paragraph"){e(t);return}if(t.content)for(const n of t.content)Md(n,e)}function xB(t,e){var n;return((n=t.marks)==null?void 0:n.some(r=>r.type===e))??!1}function _B(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?E0(n):null}function EB(t,e){if(!t.trim())return!1;const n=jn(t,vt);let r=!1,o=!0,s=0;return Mr(n,i=>{s++,xB(i,e)?r=!0:o=!1}),s===0?!1:o?!0:r?null:!1}function TB(t){if(!t.trim())return"left";const e=jn(t,vt);let n="left";return Md(e,r=>{var s;const o=(s=r.attrs)==null?void 0:s.textAlign;o&&(n=o)}),n}function MB(t){if(!t.trim())return null;const e=jn(t,vt);let n=null;return Mr(e,r=>{n===null&&(n=_B(r))}),n}function Ad(t,e){if(!t.trim())return t;const n=jn(t,vt);return Mr(n,r=>{const o=r.marks??[];o.findIndex(i=>i.type===e)===-1&&(r.marks=[...o,{type:e}])}),aa(n,vt)}function Nd(t,e){if(!t.trim())return t;const n=jn(t,vt);return Mr(n,r=>{const o=r.marks??[];r.marks=o.filter(s=>s.type!==e)}),aa(n,vt)}function AB(t,e){if(!t.trim())return t;const n=jn(t,vt);return Md(n,r=>{r.attrs={...r.attrs,textAlign:e}}),aa(n,vt)}function NB(t,e){if(!t.trim())return t;const n=jn(t,vt);return Mr(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}}]}),aa(n,vt)}function N0(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 B0(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=xd(o,e,n);return o.remove(),a}function O0(t){const{nextEditorTick:e}=Ee(),n=Wn(t,h.Text),r=Ze(h.Camera),o=Ze(h.Screen),s=Bs(),i={hasTextEntities:d.computed(()=>{for(const p of n.value.values())if(p)return!0;return!1}),hasTextContent:d.computed(()=>{for(const p of n.value.values()){if(!p)continue;const m=p.content?jn(p.content,vt):null;if(m){let g=!1;if(Mr(m,y=>{var k;(k=y.text)!=null&&k.trim()&&(g=!0)}),g)return!0}}return!1}),isBold:d.computed(()=>a("bold")),isItalic:d.computed(()=>a("italic")),isUnderline:d.computed(()=>a("underline")),alignment:d.computed(()=>{let p=null;for(const m of n.value.values()){if(!m)continue;const g=TB(m.content);if(p===null)p=g;else if(p!==g)return null}return p??"left"}),color:d.computed(()=>{let p=null,m=!1;for(const g of n.value.values()){if(!g)continue;const y=MB(g.content);if(!m)p=y,m=!0;else if(p!==y)return null}return p}),fontSize:d.computed(()=>{let p=null,m=!1;for(const g of n.value.values())if(g){if(!m)p=g.fontSizePx,m=!0;else if(p!==g.fontSizePx)return null}return p}),fontFamily:d.computed(()=>{let p=null,m=!1;for(const g of n.value.values())if(g){if(!m)p=g.fontFamily,m=!0;else if(p!==g.fontFamily)return null}return p})};function a(p){let m=null,g=!1;for(const y of n.value.values()){if(!y)continue;const k=EB(y.content,p);if(!g)m=k,g=!0;else if(m!==k)return null}return m}const l={toggleBold(){u(p=>i.isBold.value?Nd(p,"bold"):Ad(p,"bold"))},toggleItalic(){u(p=>i.isItalic.value?Nd(p,"italic"):Ad(p,"italic"))},toggleUnderline(){u(p=>i.isUnderline.value?Nd(p,"underline"):Ad(p,"underline"))},setAlignment(p){f(m=>AB(m,p))},setColor(p){f(m=>NB(m,p))},setFontSize(p){c(m=>({...m,fontSizePx:p}),m=>{m.fontSizePx=p})},setFontFamily(p){c(m=>({...m,fontFamily:p}),m=>{m.fontFamily=p})}};function c(p,m){const g=d.toValue(t),y=[];for(const k of g){const w=n.value.get(k);if(!w)continue;const v=N0(k);if(v){const b=B0(v,r,o,p(w));y.push({entityId:k,...b})}}e(k=>{for(const w of g)m(h.Text.write(k,w));for(const{entityId:w,width:v,height:b,left:S,top:C}of y){const x=h.Block.write(k,w);x.size=[v,b],x.position=[S,C]}d.nextTick(()=>{s.updateCounter.value++})})}function u(p){const m=d.toValue(t),g=[];for(const y of m){const k=n.value.get(y);if(!k)continue;const w=p(k.content),v=N0(y);if(v){const b=B0(v,r,o,{...k,content:w});g.push({entityId:y,content:w,...b})}else g.push({entityId:y,content:w,width:0,height:0,left:0,top:0})}e(y=>{for(const{entityId:k,content:w,width:v,height:b,left:S,top:C}of g){const x=h.Text.write(y,k);if(x.content=w,v>0&&b>0){const _=h.Block.write(y,k);_.size=[v,b],_.position=[S,C]}}})}function f(p){const m=d.toValue(t);e(g=>{for(const y of m){const k=h.Text.write(g,y);k.content=p(k.content)}})}return{state:i,commands:l}}function qt(t){const e=Bs(),n=O0(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 Bd(t){const e=Ze(h.Camera),n=Ze(h.Screen),r=Ze(xl),o=Ze(Tt),{nextEditorTick:s}=Ee();let i=!1,a=null;function l(u,f){const{entityId:p}=d.toValue(t.blockData),m=d.toValue(t.minWidth)??0,g=d.toValue(t.minHeight)??0,y=Math.max(f.width,m),k=Math.max(f.height,g),w=h.Block.read(u,p),v=Math.abs(w.size[0]-y)>.5,b=Math.abs(w.size[1]-k)>.5;if(!v&&!b)return;const S=h.Block.write(u,p);S.size=[y,k],S.position=[f.left,f.top],r.value.transformBoxId!==null&&vl.spawn(u,{transformBoxId:r.value.transformBoxId})}d.watch(()=>o.value,()=>{const u=t.containerRef.value;u&&i&&(a=xd(u,e,n)),s(f=>{const p=BB(f);i&&!p&&a&&(l(f,a),a=null),i=p})},{flush:"sync"});function c(u){const{content:f,...p}=u;s(m=>{const{entityId:g}=d.toValue(t.blockData);if(h.Text.read(m,g).content!==f){const k=h.Text.write(m,g);k.content=f}l(m,p)})}return{handleEditEnd:c}}function BB(t){const e=Tt.read(t);return e.state===de.Dragging&&e.draggedEntity!==null&&h.hasComponent(t,e.draggedEntity,ve)&&ve.read(t,e.draggedEntity).kind===Et.Stretch}function Od(){const t=d.inject(Ul);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 OB=500,IB=1500;function I0(){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},OB)}function a(){s(),e.value=!1,t.value=null,n.value&&(o=setTimeout(()=>{n.value=!1,o=null},IB))}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 Un(){const t=d.inject(yh);if(!t)throw new Error("useTooltipSingleton must be used within a WovenCanvas component");return t}const PB={key:1},RB=["innerHTML"],DB=50,zB=300,wa=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 C;const r=t,o=n,s=Pe(r.entityId,h.Text),i=Ze(h.Camera),a=Ze(h.Screen),l=Bs(),{nextEditorTick:c}=Ee(),u=Ze(h.Mouse),f=d.ref(null);e({editableTextRef:f});const p=d.ref(((C=s.value)==null?void 0:C.content)??""),m=d.shallowRef(null);function g(x,_){var I;const T=s.value;return!T||T.constrainWidth||(((I=_.clipboardData)==null?void 0:I.getData("text/plain"))??"").length>DB&&c(V=>{const K=h.Text.write(V,r.entityId);K.constrainWidth=!0;const M=h.Block.read(V,r.entityId),$=Math.max(M.size[0],zB),Z=h.Block.write(V,r.entityId);Z.size=[$,M.size[1]],h.ResetKeyboard.spawn(V),Xr.spawn(V)}),!1}function y(){var x,_;return new ON({extensions:[r0,s0,i0,vd,p0,l0,c0,d0,u0.configure({types:["paragraph"],alignments:["left","center","right","justify"],defaultAlignment:((x=s.value)==null?void 0:x.defaultAlignment)??"left"}),bB],content:((_=s.value)==null?void 0:_.content)??"",editable:!0,parseOptions:{preserveWhitespace:!0},editorProps:{handlePaste:g}})}d.watch(()=>r.edited,async x=>{if(x&&f.value){if(m.value=y(),await k(m.value),!r.blockElement)return;l.register(m.value,f.value,r.blockElement)}else m.value&&(l.unregister(),w(m.value),m.value.destroy(),m.value=null)},{immediate:!0});async function k(x){var I;const _=(I=u.value)==null?void 0:I.position,T=a.value;await d.nextTick(),await new Promise(V=>requestAnimationFrame(V));const N=f.value;if(_&&T&&N){const V=_[0]+T.left,K=_[1]+T.top,M=x.view.posAtCoords({left:V,top:K});if(M){x.chain().focus().setTextSelection(M.pos).run();return}}x.commands.focus("start")}function w(x){let _=x.getHTML();const N=_.replace(/<[^>]*>/g,"").trim().length>0;N||(_=""),p.value=_,c(I=>{var Z,ae;const V=h.getBlockDef(I,r.block.tag);if(!N&&((Z=V.editOptions)!=null&&Z.removeWhenTextEmpty)){h.removeEntity(I,r.entityId);return}const K=(ae=f.value)==null?void 0:ae.closest(".wov-block"),M=(K==null?void 0:K.firstElementChild)??f.value;if(!M){console.warn("EditableText: no element to measure");return}const $=xd(M,i,a);o("editEnd",{content:_,...$})})}d.watch(()=>{var x;return(x=s.value)==null?void 0:x.content},x=>{x!==void 0&&(m.value?m.value.getHTML()!==x&&m.value.commands.setContent(x,{emitUpdate:!1}):p.value=x)});const v=d.computed(()=>{const x=s.value;if(!x)return{};const[_,T]=r.block.flip,N=_?-1:1,I=T?-1:1,V=_||T;return{fontFamily:x.fontFamily,fontSize:`${x.fontSizePx}px`,lineHeight:x.lineHeight,letterSpacing:`${x.letterSpacingEm}em`,width:x.constrainWidth?"100%":"fit-content",whiteSpace:x.constrainWidth?"pre-wrap":"pre",minWidth:"2px",wordBreak:"break-word",pointerEvents:r.edited?"auto":"none",userSelect:r.edited?"auto":"none",transform:V?`scale(${N}, ${I})`:void 0}});function b(x){x.key==="Control"||x.key==="Meta"||x.stopPropagation()}function S(x){r.edited&&x.stopPropagation()}return d.onUnmounted(()=>{m.value&&(l.unregister(),m.value.destroy(),m.value=null)}),(x,_)=>(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},[m.value?(d.openBlock(),d.createBlock(d.unref(IN),{key:0,editor:m.value},null,8,["editor"])):(d.openBlock(),d.createElementBlock("div",PB,[d.createElementVNode("div",{class:"tiptap ProseMirror",innerHTML:p.value},null,8,RB)]))],36))}}),$B={class:"wov-shape-svg",viewBox:"0 0 100 100",preserveAspectRatio:"none"},VB=["d","fill","stroke","stroke-width","stroke-dasharray"],P0=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=Pe(e.entityId,h.Shape),r=Pe(e.entityId,h.VerticalAlign),o=d.ref(null),s={[h.VerticalAlignment.Top]:"flex-start",[h.VerticalAlignment.Center]:"center",[h.VerticalAlignment.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===h.StrokeKind.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 y;return((y=n.value)==null?void 0:y.strokeWidth)??2}),c=d.computed(()=>{var y;return((y=n.value)==null?void 0:y.strokeKind)??h.StrokeKind.Solid}),u=d.computed(()=>{var y;return ss[((y=n.value)==null?void 0:y.kind)??"rectangle"]??ss.rectangle}),f=d.computed(()=>{const y=l.value;switch(c.value){case h.StrokeKind.Dashed:return`${y*3} ${y*3}`;case h.StrokeKind.None:return"";case h.StrokeKind.Solid:default:return""}}),p=d.computed(()=>{var y;return{overflow:e.edited?"visible":"hidden",alignItems:s[((y=r.value)==null?void 0:y.value)??h.VerticalAlignment.Top]}}),{nextEditorTick:m}=Ee();function g(y){m(k=>{if(h.Text.read(k,e.entityId).content===y.content)return;const v=h.Text.write(k,e.entityId);v.content=y.content})}return(y,k)=>(d.openBlock(),d.createElementBlock("div",{ref_key:"containerRef",ref:o,class:"wov-shape-block"},[(d.openBlock(),d.createElementBlock("svg",$B,[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,VB)])),d.createElementVNode("div",{class:"wov-shape-content",style:d.normalizeStyle(p.value)},[d.createVNode(wa,d.mergeProps(e,{"block-element":o.value,onEditEnd:g}),null,16,["block-element"])],4)],512))}}),LB=["data-text-empty"],R0=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=Pe(e.entityId,h.Text),o=d.computed(()=>{var l;return(((l=r.value)==null?void 0:l.content)??"").replace(/<[^>]*>/g,"").trim().length===0}),{handleEditEnd:s}=Bd({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(wa,d.mergeProps(e,{"block-element":n.value,onEditEnd:d.unref(s)}),null,16,["block-element","onEditEnd"])],8,LB))}}),va=Math.min,Ar=Math.max,ba=Math.round,Sa=Math.floor,Gt=t=>({x:t,y:t}),FB={left:"right",right:"left",bottom:"top",top:"bottom"},jB={start:"end",end:"start"};function D0(t,e,n){return Ar(t,va(e,n))}function Ca(t,e){return typeof t=="function"?t(e):t}function Nr(t){return t.split("-")[0]}function xa(t){return t.split("-")[1]}function z0(t){return t==="x"?"y":"x"}function $0(t){return t==="y"?"height":"width"}const HB=new Set(["top","bottom"]);function Kn(t){return HB.has(Nr(t))?"y":"x"}function V0(t){return z0(Kn(t))}function WB(t,e,n){n===void 0&&(n=!1);const r=xa(t),o=V0(t),s=$0(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return e.reference[s]>e.floating[s]&&(i=_a(i)),[i,_a(i)]}function ZB(t){const e=_a(t);return[Id(t),e,Id(e)]}function Id(t){return t.replace(/start|end/g,e=>jB[e])}const L0=["left","right"],F0=["right","left"],UB=["top","bottom"],KB=["bottom","top"];function JB(t,e,n){switch(t){case"top":case"bottom":return n?e?F0:L0:e?L0:F0;case"left":case"right":return e?UB:KB;default:return[]}}function qB(t,e,n,r){const o=xa(t);let s=JB(Nr(t),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),e&&(s=s.concat(s.map(Id)))),s}function _a(t){return t.replace(/left|right|bottom|top/g,e=>FB[e])}function GB(t){return{top:0,right:0,bottom:0,left:0,...t}}function YB(t){return typeof t!="number"?GB(t):{top:t,right:t,bottom:t,left:t}}function Ea(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 j0(t,e,n){let{reference:r,floating:o}=t;const s=Kn(e),i=V0(e),a=$0(i),l=Nr(e),c=s==="y",u=r.x+r.width/2-o.width/2,f=r.y+r.height/2-o.height/2,p=r[a]/2-o[a]/2;let m;switch(l){case"top":m={x:u,y:r.y-o.height};break;case"bottom":m={x:u,y:r.y+r.height};break;case"right":m={x:r.x+r.width,y:f};break;case"left":m={x:r.x-o.width,y:f};break;default:m={x:r.x,y:r.y}}switch(xa(e)){case"start":m[i]-=p*(n&&c?-1:1);break;case"end":m[i]+=p*(n&&c?-1:1);break}return m}async function XB(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:p=!1,padding:m=0}=Ca(e,t),g=YB(m),k=a[p?f==="floating"?"reference":"floating":f],w=Ea(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(k)))==null||n?k:k.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},C=Ea(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:v,offsetParent:b,strategy:l}):v);return{top:(w.top-C.top+g.top)/S.y,bottom:(C.bottom-w.bottom+g.bottom)/S.y,left:(w.left-C.left+g.left)/S.x,right:(C.right-w.right+g.right)/S.x}}const QB=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}=j0(c,r,l),p=r,m={},g=0;for(let k=0;k<a.length;k++){var y;const{name:w,fn:v}=a[k],{x:b,y:S,data:C,reset:x}=await v({x:u,y:f,initialPlacement:r,placement:p,strategy:o,middlewareData:m,rects:c,platform:{...i,detectOverflow:(y=i.detectOverflow)!=null?y:XB},elements:{reference:t,floating:e}});u=b??u,f=S??f,m={...m,[w]:{...m[w],...C}},x&&g<=50&&(g++,typeof x=="object"&&(x.placement&&(p=x.placement),x.rects&&(c=x.rects===!0?await i.getElementRects({reference:t,floating:e,strategy:o}):x.rects),{x:u,y:f}=j0(c,p,l)),k=-1)}return{x:u,y:f,placement:p,strategy:o,middlewareData:m}},eO=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:p,fallbackStrategy:m="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:y=!0,...k}=Ca(t,e);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const w=Nr(o),v=Kn(a),b=Nr(a)===a,S=await(l.isRTL==null?void 0:l.isRTL(c.floating)),C=p||(b||!y?[_a(a)]:ZB(a)),x=g!=="none";!p&&x&&C.push(...qB(a,y,g,S));const _=[a,...C],T=await l.detectOverflow(e,k),N=[];let I=((r=s.flip)==null?void 0:r.overflows)||[];if(u&&N.push(T[w]),f){const $=WB(o,i,S);N.push(T[$[0]],T[$[1]])}if(I=[...I,{placement:o,overflows:N}],!N.every($=>$<=0)){var V,K;const $=(((V=s.flip)==null?void 0:V.index)||0)+1,Z=_[$];if(Z&&(!(f==="alignment"?v!==Kn(Z):!1)||I.every(j=>Kn(j.placement)===v?j.overflows[0]>0:!0)))return{data:{index:$,overflows:I},reset:{placement:Z}};let ae=(K=I.filter(X=>X.overflows[0]<=0).sort((X,j)=>X.overflows[1]-j.overflows[1])[0])==null?void 0:K.placement;if(!ae)switch(m){case"bestFit":{var M;const X=(M=I.filter(j=>{if(x){const q=Kn(j.placement);return q===v||q==="y"}return!0}).map(j=>[j.placement,j.overflows.filter(q=>q>0).reduce((q,te)=>q+te,0)]).sort((j,q)=>j[1]-q[1])[0])==null?void 0:M[0];X&&(ae=X);break}case"initialPlacement":ae=a;break}if(o!==ae)return{reset:{placement:ae}}}return{}}}},tO=new Set(["left","top"]);async function nO(t,e){const{placement:n,platform:r,elements:o}=t,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=Nr(n),a=xa(n),l=Kn(n)==="y",c=tO.has(i)?-1:1,u=s&&l?-1:1,f=Ca(e,t);let{mainAxis:p,crossAxis:m,alignmentAxis:g}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof g=="number"&&(m=a==="end"?g*-1:g),l?{x:m*u,y:p*c}:{x:p*c,y:m*u}}const rO=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 nO(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}}}}},oO=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}=Ca(t,e),u={x:n,y:r},f=await s.detectOverflow(e,c),p=Kn(Nr(o)),m=z0(p);let g=u[m],y=u[p];if(i){const w=m==="y"?"top":"left",v=m==="y"?"bottom":"right",b=g+f[w],S=g-f[v];g=D0(b,g,S)}if(a){const w=p==="y"?"top":"left",v=p==="y"?"bottom":"right",b=y+f[w],S=y-f[v];y=D0(b,y,S)}const k=l.fn({...e,[m]:g,[p]:y});return{...k,data:{x:k.x-n,y:k.y-r,enabled:{[m]:i,[p]:a}}}}}};function Ta(){return typeof window<"u"}function Br(t){return Pd(t)?(t.nodeName||"").toLowerCase():"#document"}function ut(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function Yt(t){var e;return(e=(Pd(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function Pd(t){return Ta()?t instanceof Node||t instanceof ut(t).Node:!1}function It(t){return Ta()?t instanceof Element||t instanceof ut(t).Element:!1}function Xt(t){return Ta()?t instanceof HTMLElement||t instanceof ut(t).HTMLElement:!1}function H0(t){return!Ta()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof ut(t).ShadowRoot}const sO=new Set(["inline","contents"]);function Os(t){const{overflow:e,overflowX:n,overflowY:r,display:o}=Pt(t);return/auto|scroll|overlay|hidden|clip/.test(e+r+n)&&!sO.has(o)}const iO=new Set(["table","td","th"]);function aO(t){return iO.has(Br(t))}const lO=[":popover-open",":modal"];function Ma(t){return lO.some(e=>{try{return t.matches(e)}catch{return!1}})}const cO=["transform","translate","scale","rotate","perspective"],dO=["transform","translate","scale","rotate","perspective","filter"],uO=["paint","layout","strict","content"];function Rd(t){const e=Dd(),n=It(t)?Pt(t):t;return cO.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)||dO.some(r=>(n.willChange||"").includes(r))||uO.some(r=>(n.contain||"").includes(r))}function fO(t){let e=Jn(t);for(;Xt(e)&&!bo(e);){if(Rd(e))return e;if(Ma(e))return null;e=Jn(e)}return null}function Dd(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const hO=new Set(["html","body","#document"]);function bo(t){return hO.has(Br(t))}function Pt(t){return ut(t).getComputedStyle(t)}function Aa(t){return It(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function Jn(t){if(Br(t)==="html")return t;const e=t.assignedSlot||t.parentNode||H0(t)&&t.host||Yt(t);return H0(e)?e.host:e}function W0(t){const e=Jn(t);return bo(e)?t.ownerDocument?t.ownerDocument.body:t.body:Xt(e)&&Os(e)?e:W0(e)}function Is(t,e,n){var r;e===void 0&&(e=[]),n===void 0&&(n=!0);const o=W0(t),s=o===((r=t.ownerDocument)==null?void 0:r.body),i=ut(o);if(s){const a=zd(i);return e.concat(i,i.visualViewport||[],Os(o)?o:[],a&&n?Is(a):[])}return e.concat(o,Is(o,[],n))}function zd(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function Z0(t){const e=Pt(t);let n=parseFloat(e.width)||0,r=parseFloat(e.height)||0;const o=Xt(t),s=o?t.offsetWidth:n,i=o?t.offsetHeight:r,a=ba(n)!==s||ba(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function $d(t){return It(t)?t:t.contextElement}function So(t){const e=$d(t);if(!Xt(e))return Gt(1);const n=e.getBoundingClientRect(),{width:r,height:o,$:s}=Z0(e);let i=(s?ba(n.width):n.width)/r,a=(s?ba(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const pO=Gt(0);function U0(t){const e=ut(t);return!Dd()||!e.visualViewport?pO:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function mO(t,e,n){return e===void 0&&(e=!1),!n||e&&n!==ut(t)?!1:e}function Or(t,e,n,r){e===void 0&&(e=!1),n===void 0&&(n=!1);const o=t.getBoundingClientRect(),s=$d(t);let i=Gt(1);e&&(r?It(r)&&(i=So(r)):i=So(t));const a=mO(s,n,r)?U0(s):Gt(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 p=ut(s),m=r&&It(r)?ut(r):r;let g=p,y=zd(g);for(;y&&r&&m!==g;){const k=So(y),w=y.getBoundingClientRect(),v=Pt(y),b=w.left+(y.clientLeft+parseFloat(v.paddingLeft))*k.x,S=w.top+(y.clientTop+parseFloat(v.paddingTop))*k.y;l*=k.x,c*=k.y,u*=k.x,f*=k.y,l+=b,c+=S,g=ut(y),y=zd(g)}}return Ea({width:u,height:f,x:l,y:c})}function Na(t,e){const n=Aa(t).scrollLeft;return e?e.left+n:Or(Yt(t)).left+n}function K0(t,e){const n=t.getBoundingClientRect(),r=n.left+e.scrollLeft-Na(t,n),o=n.top+e.scrollTop;return{x:r,y:o}}function gO(t){let{elements:e,rect:n,offsetParent:r,strategy:o}=t;const s=o==="fixed",i=Yt(r),a=e?Ma(e.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=Gt(1);const u=Gt(0),f=Xt(r);if((f||!f&&!s)&&((Br(r)!=="body"||Os(i))&&(l=Aa(r)),Xt(r))){const m=Or(r);c=So(r),u.x=m.x+r.clientLeft,u.y=m.y+r.clientTop}const p=i&&!f&&!s?K0(i,l):Gt(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+p.x,y:n.y*c.y-l.scrollTop*c.y+u.y+p.y}}function yO(t){return Array.from(t.getClientRects())}function kO(t){const e=Yt(t),n=Aa(t),r=t.ownerDocument.body,o=Ar(e.scrollWidth,e.clientWidth,r.scrollWidth,r.clientWidth),s=Ar(e.scrollHeight,e.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+Na(t);const a=-n.scrollTop;return Pt(r).direction==="rtl"&&(i+=Ar(e.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const J0=25;function wO(t,e){const n=ut(t),r=Yt(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=Dd();(!u||u&&e==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=Na(r);if(c<=0){const u=r.ownerDocument,f=u.body,p=getComputedStyle(f),m=u.compatMode==="CSS1Compat"&&parseFloat(p.marginLeft)+parseFloat(p.marginRight)||0,g=Math.abs(r.clientWidth-f.clientWidth-m);g<=J0&&(s-=g)}else c<=J0&&(s+=c);return{width:s,height:i,x:a,y:l}}const vO=new Set(["absolute","fixed"]);function bO(t,e){const n=Or(t,!0,e==="fixed"),r=n.top+t.clientTop,o=n.left+t.clientLeft,s=Xt(t)?So(t):Gt(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 q0(t,e,n){let r;if(e==="viewport")r=wO(t,n);else if(e==="document")r=kO(Yt(t));else if(It(e))r=bO(e,n);else{const o=U0(t);r={x:e.x-o.x,y:e.y-o.y,width:e.width,height:e.height}}return Ea(r)}function G0(t,e){const n=Jn(t);return n===e||!It(n)||bo(n)?!1:Pt(n).position==="fixed"||G0(n,e)}function SO(t,e){const n=e.get(t);if(n)return n;let r=Is(t,[],!1).filter(a=>It(a)&&Br(a)!=="body"),o=null;const s=Pt(t).position==="fixed";let i=s?Jn(t):t;for(;It(i)&&!bo(i);){const a=Pt(i),l=Rd(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&vO.has(o.position)||Os(i)&&!l&&G0(t,i))?r=r.filter(u=>u!==i):o=a,i=Jn(i)}return e.set(t,r),r}function CO(t){let{element:e,boundary:n,rootBoundary:r,strategy:o}=t;const i=[...n==="clippingAncestors"?Ma(e)?[]:SO(e,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,u)=>{const f=q0(e,u,o);return c.top=Ar(f.top,c.top),c.right=va(f.right,c.right),c.bottom=va(f.bottom,c.bottom),c.left=Ar(f.left,c.left),c},q0(e,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function xO(t){const{width:e,height:n}=Z0(t);return{width:e,height:n}}function _O(t,e,n){const r=Xt(e),o=Yt(e),s=n==="fixed",i=Or(t,!0,s,e);let a={scrollLeft:0,scrollTop:0};const l=Gt(0);function c(){l.x=Na(o)}if(r||!r&&!s)if((Br(e)!=="body"||Os(o))&&(a=Aa(e)),r){const m=Or(e,!0,s,e);l.x=m.x+e.clientLeft,l.y=m.y+e.clientTop}else o&&c();s&&!r&&o&&c();const u=o&&!r&&!s?K0(o,a):Gt(0),f=i.left+a.scrollLeft-l.x-u.x,p=i.top+a.scrollTop-l.y-u.y;return{x:f,y:p,width:i.width,height:i.height}}function Vd(t){return Pt(t).position==="static"}function Y0(t,e){if(!Xt(t)||Pt(t).position==="fixed")return null;if(e)return e(t);let n=t.offsetParent;return Yt(t)===n&&(n=n.ownerDocument.body),n}function X0(t,e){const n=ut(t);if(Ma(t))return n;if(!Xt(t)){let o=Jn(t);for(;o&&!bo(o);){if(It(o)&&!Vd(o))return o;o=Jn(o)}return n}let r=Y0(t,e);for(;r&&aO(r)&&Vd(r);)r=Y0(r,e);return r&&bo(r)&&Vd(r)&&!Rd(r)?n:r||fO(t)||n}const EO=async function(t){const e=this.getOffsetParent||X0,n=this.getDimensions,r=await n(t.floating);return{reference:_O(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function TO(t){return Pt(t).direction==="rtl"}const MO={convertOffsetParentRelativeRectToViewportRelativeRect:gO,getDocumentElement:Yt,getClippingRect:CO,getOffsetParent:X0,getElementRects:EO,getClientRects:yO,getDimensions:xO,getScale:So,isElement:It,isRTL:TO};function Q0(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function AO(t,e){let n=null,r;const o=Yt(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:p,height:m}=c;if(a||e(),!p||!m)return;const g=Sa(f),y=Sa(o.clientWidth-(u+p)),k=Sa(o.clientHeight-(f+m)),w=Sa(u),b={rootMargin:-g+"px "+-y+"px "+-k+"px "+-w+"px",threshold:Ar(0,va(1,l))||1};let S=!0;function C(x){const _=x[0].intersectionRatio;if(_!==l){if(!S)return i();_?i(!1,_):r=setTimeout(()=>{i(!1,1e-7)},1e3)}_===1&&!Q0(c,t.getBoundingClientRect())&&i(),S=!1}try{n=new IntersectionObserver(C,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(C,b)}n.observe(t)}return i(!0),s}function ek(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=$d(t),u=o||s?[...c?Is(c):[],...Is(e)]:[];u.forEach(w=>{o&&w.addEventListener("scroll",n,{passive:!0}),s&&w.addEventListener("resize",n)});const f=c&&a?AO(c,n):null;let p=-1,m=null;i&&(m=new ResizeObserver(w=>{let[v]=w;v&&v.target===c&&m&&(m.unobserve(e),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var b;(b=m)==null||b.observe(e)})),n()}),c&&!l&&m.observe(c),m.observe(e));let g,y=l?Or(t):null;l&&k();function k(){const w=Or(t);y&&!Q0(y,w)&&n(),y=w,g=requestAnimationFrame(k)}return n(),()=>{var w;u.forEach(v=>{o&&v.removeEventListener("scroll",n),s&&v.removeEventListener("resize",n)}),f==null||f(),(w=m)==null||w.disconnect(),m=null,l&&cancelAnimationFrame(g)}}const Ba=rO,Oa=oO,Ia=eO,NO=(t,e,n)=>{const r=new Map,o={platform:MO,...n},s={...o.platform,_c:r};return QB(t,e,{...o,platform:s})};function BO(t){return t!=null&&typeof t=="object"&&"$el"in t}function tk(t){if(BO(t)){const e=t.$el;return Pd(e)&&Br(e)==="#comment"?null:e}return t}function Ps(t){return typeof t=="function"?t():d.unref(t)}function nk(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function rk(t,e){const n=nk(t);return Math.round(e*n)/n}function Pa(t,e,n){n===void 0&&(n={});const r=n.whileElementsMounted,o=d.computed(()=>{var _;return(_=Ps(n.open))!=null?_:!0}),s=d.computed(()=>Ps(n.middleware)),i=d.computed(()=>{var _;return(_=Ps(n.placement))!=null?_:"bottom"}),a=d.computed(()=>{var _;return(_=Ps(n.strategy))!=null?_:"absolute"}),l=d.computed(()=>{var _;return(_=Ps(n.transform))!=null?_:!0}),c=d.computed(()=>tk(t.value)),u=d.computed(()=>tk(e.value)),f=d.ref(0),p=d.ref(0),m=d.ref(a.value),g=d.ref(i.value),y=d.shallowRef({}),k=d.ref(!1),w=d.computed(()=>{const _={position:m.value,left:"0",top:"0"};if(!u.value)return _;const T=rk(u.value,f.value),N=rk(u.value,p.value);return l.value?{..._,transform:"translate("+T+"px, "+N+"px)",...nk(u.value)>=1.5&&{willChange:"transform"}}:{position:m.value,left:T+"px",top:N+"px"}});let v;function b(){if(c.value==null||u.value==null)return;const _=o.value;NO(c.value,u.value,{middleware:s.value,placement:i.value,strategy:a.value}).then(T=>{f.value=T.x,p.value=T.y,m.value=T.strategy,g.value=T.placement,y.value=T.middlewareData,k.value=_!==!1})}function S(){typeof v=="function"&&(v(),v=void 0)}function C(){if(S(),r===void 0){b();return}if(c.value!=null&&u.value!=null){v=r(c.value,u.value,b);return}}function x(){o.value||(k.value=!1)}return d.watch([s,i,a,o],b,{flush:"sync"}),d.watch([c,u],C,{flush:"sync"}),d.watch(o,x,{flush:"sync"}),d.getCurrentScope()&&d.onScopeDispose(S),{x:d.shallowReadonly(f),y:d.shallowReadonly(p),strategy:d.shallowReadonly(m),placement:d.shallowReadonly(g),middlewareData:d.shallowReadonly(y),isPositioned:d.shallowReadonly(k),floatingStyles:w,update:b}}const OO=["menu-open"],bt=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(ph,null),i=d.inject(mh,0),a=Math.random().toString(36).slice(2);d.provide(mh,i+1);const{show:l,hide:c}=Un(),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),p=d.ref(null),{floatingStyles:m}=Pa(f,p,{placement:n.placement,middleware:[Ba(n.offsetPx),Ia(),Oa({padding:8})],whileElementsMounted:ek});function g(){n.disabled||(u.value=!u.value)}function y(){u.value=!1}function k(b){var T,N,I;const S=b.target,C=(T=f.value)==null?void 0:T.contains(S),x=(N=p.value)==null?void 0:N.contains(S),_=(I=S.closest)==null?void 0:I.call(S,".wov-menu-dropdown");!C&&!x&&!_&&y()}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",k,!0),s&&(s.value.set(i,a),s.value=new Map(s.value)),r("open")):(document.removeEventListener("click",k,!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",k,!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:g,onMouseenter:w,onMouseleave:v},[d.renderSlot(b.$slots,"button",{isOpen:u.value})],42,OO),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:p,class:"wov-menu-dropdown",style:d.normalizeStyle(d.unref(m))},[d.renderSlot(b.$slots,"dropdown",{close:y})],4)):d.createCommentVNode("",!0)],8,["to"])):d.createCommentVNode("",!0)],64))}}),IO={},PO={viewBox:"0 0 512 320",fill:"currentColor",style:{width:"7px",color:"var(--wov-gray-300)"}};function RO(t,e){return d.openBlock(),d.createElementBlock("svg",PO,[...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 St=ir(IO,[["render",RO]]),DO={class:"wov-menu-button"},zO=["innerHTML"],$O=["onClick"],VO=["innerHTML"],Ld=d.defineComponent({__name:"ArrowHeadButton",props:{entityIds:{},side:{}},setup(t){const e=t,{nextEditorTick:n}=Ee(),r=d.shallowRef(null),o=d.computed(()=>{const a=r.value??(e.side==="start"?pe.None:pe.V);return no(a)});n(a=>{let l=null;for(const c of e.entityIds){if(h.hasComponent(a,c,he)){const u=he.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"?pe.None:pe.V;return}}if(h.hasComponent(a,c,ue)){const u=ue.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"?pe.None:pe.V;return}}}r.value=l});function s(a){r.value=a,n(l=>{for(const c of e.entityIds){if(h.hasComponent(l,c,he)){const u=he.write(l,c);e.side==="start"?u.startArrowHead=a:u.endArrowHead=a}if(h.hasComponent(l,c,ue)){const u=ue.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(bt,{title:t.side==="start"?"Start Arrow Head":"End Arrow Head"},{button:d.withCtx(()=>[d.createElementVNode("div",DO,[(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,zO)),d.createVNode(St,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[(d.openBlock(!0),d.createElementBlock(d.Fragment,null,d.renderList(d.unref(Zl),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,VO))],10,$O))),128))]),_:1},8,["title"]))}}),LO={class:"wov-menu-button"},FO=["onClick"],ok=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}=Ee(),o=d.shallowRef(null);r(i=>{let a=null;for(const l of n.entityIds){if(h.hasComponent(i,l,he)){const c=he.read(i,l);if(a===null)a=c.thickness;else if(c.thickness!==a){o.value=null;return}}if(h.hasComponent(i,l,ue)){const c=ue.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(h.hasComponent(a,l,he)){const c=he.write(a,l);c.thickness=i}h.hasComponent(a,l,ue)&&ue.setThickness(a,l,i)}})}return(i,a)=>(d.openBlock(),d.createBlock(bt,{title:"Thickness"},{button:d.withCtx(()=>[d.createElementVNode("div",LO,[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(St,{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,FO)),64))]),_:1}))}}),jO=["value"],HO=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 p=u.target.value;if((p.length===6||p.length===7)&&s(p)){const m=i(p);o.value=m,r("update:modelValue",m)}}function l(u){const p=u.target.value;if(p&&s(p)){const m=i(p);o.value=m,r("update:modelValue",m)}else n.modelValue&&(o.value=n.modelValue)}function c(u){if(u.stopPropagation(),u.key==="Enter"){const f=u.target,p=f.value;if(p&&s(p)){const m=i(p);o.value=m,r("update:modelValue",m),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,jO))}}),sk=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))}}),WO={class:"wov-color-picker"},ZO={class:"wov-color-picker-area"},UO={class:"wov-color-picker-selector-gradient"},KO="linear-gradient(to bottom, red 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, red 100%)",ik=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 x,_;return u.value||((x=o.value)==null?void 0:x.isDragging)||((_=s.value)==null?void 0:_.isDragging)}),p=d.computed(()=>({h:l.value/100*360,s:a.value.x,v:100-a.value.y,a:(100-c.value)/100*255})),m=d.computed(()=>M0({h:p.value.h,s:100,v:100})),g=d.computed(()=>M0({h:p.value.h,s:p.value.s,v:p.value.v})),y=d.computed(()=>n.withOpacity?A0(p.value):g.value),k=d.computed(()=>`linear-gradient(to top, transparent 0%, ${g.value} 100%)`);function w(x){if(x){const _=T0(x);a.value={x:_.s,y:100-_.v},l.value=_.h/360*100,c.value=100-_.a/255*100}}function v(x){w(x),r("update:modelValue",n.withOpacity?A0(T0(x)):x)}w(n.modelValue),d.watch(()=>n.modelValue,x=>{f.value||w(x)}),d.watch([a,l,c],()=>{f.value&&r("update:modelValue",y.value)});function b(x){u.value=!0,S(x),window.addEventListener("pointermove",S),window.addEventListener("pointerup",C)}function S(x){if(!i.value)return;const _=i.value.getBoundingClientRect(),T=Math.max(0,Math.min(100,(x.clientX-_.left)/_.width*100)),N=Math.max(0,Math.min(100,(x.clientY-_.top)/_.height*100));a.value={x:T,y:N}}function C(){u.value=!1,window.removeEventListener("pointermove",S),window.removeEventListener("pointerup",C)}return(x,_)=>(d.openBlock(),d.createElementBlock("div",WO,[d.createVNode(HO,{modelValue:y.value,"onUpdate:modelValue":v},null,8,["modelValue"]),d.createElementVNode("div",ZO,[d.createElementVNode("div",{ref_key:"selectorRef",ref:i,class:"wov-color-picker-selector",style:d.normalizeStyle({backgroundColor:m.value}),onPointerdown:d.withModifiers(b,["prevent"])},[d.createElementVNode("div",UO,[d.createElementVNode("div",{class:"wov-color-picker-selector-thumb",style:d.normalizeStyle({left:`${a.value.x}%`,top:`${a.value.y}%`,backgroundColor:g.value})},null,4)])],36),d.createVNode(sk,{ref_key:"hueSliderRef",ref:o,modelValue:l.value,"onUpdate:modelValue":_[0]||(_[0]=T=>l.value=T),thumbColor:m.value,background:KO},null,8,["modelValue","thumbColor"]),t.withOpacity?(d.openBlock(),d.createBlock(sk,{key:0,ref_key:"opacitySliderRef",ref:s,modelValue:c.value,"onUpdate:modelValue":_[1]||(_[1]=T=>c.value=T),thumbColor:g.value,background:k.value,class:"wov-color-picker-opacity"},null,8,["modelValue","thumbColor","background"])):d.createCommentVNode("",!0)])]))}}),JO={class:"wov-color-bubbles-container"},qO={key:1,class:"wov-color-bubbles"},GO=["onClick"],Ra=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 g=n.palette??o,y=n.withPicker,k=g.length%2===1;return y&&!k||!y&&k?g.slice(0,-1):g}),i=d.ref(!1),a=d.ref(n.currentColor??"#ff0000");function l(g,y){const k=w=>{const v=w.replace(/^#/,"").toLowerCase();return v.length===6?v+"ff":v};return k(g)===k(y)}function c(g){return n.hideHighlight||!n.currentColor?!1:l(n.currentColor,g)}function u(){return n.hideHighlight||!n.currentColor?!1:!s.value.some(g=>l(n.currentColor,g))}function f(g){const y=_d(g);y&&r("change",y)}function p(){!i.value&&n.currentColor&&(a.value=n.currentColor),i.value=!i.value,r("picker-open",i.value)}function m(g){a.value=g;const y=_d(g);y&&r("change",y)}return(g,y)=>(d.openBlock(),d.createElementBlock("div",JO,[i.value?(d.openBlock(),d.createBlock(ik,{key:0,modelValue:a.value,"onUpdate:modelValue":[y[0]||(y[0]=k=>a.value=k),m],withOpacity:t.withOpacity},null,8,["modelValue","withOpacity"])):(d.openBlock(),d.createElementBlock("div",qO,[(d.openBlock(!0),d.createElementBlock(d.Fragment,null,d.renderList(s.value,k=>(d.openBlock(),d.createElementBlock("div",{key:k,class:d.normalizeClass(["wov-color-bubble",{selected:c(k)}]),style:d.normalizeStyle({backgroundColor:k}),onMousedown:y[1]||(y[1]=d.withModifiers(()=>{},["prevent"])),onClick:w=>f(k)},null,46,GO))),128)),t.withPicker?(d.openBlock(),d.createElementBlock("div",{key:0,class:d.normalizeClass(["wov-color-bubble wov-rainbow-bubble",{selected:u()}]),onMousedown:y[2]||(y[2]=d.withModifiers(()=>{},["prevent"])),onClick:p},null,34)):d.createCommentVNode("",!0)]))]))}}),YO={class:"wov-color-button"},ak=d.defineComponent({__name:"ColorButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=Ee(),r=Wn(()=>e.entityIds,h.Color),o=d.computed(()=>{const c=new Set;for(const u of r.value.values())if(u){const f=Ns(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=Ns(c);n(f=>{for(const p of e.entityIds)h.Color.fromHex(f,p,u)})}return(c,u)=>(d.openBlock(),d.createBlock(bt,{title:"Color"},{button:d.withCtx(()=>[d.createElementVNode("div",YO,[d.createElementVNode("div",{class:"wov-color-swatch",style:d.normalizeStyle(a.value)},null,4),d.createVNode(St,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createVNode(Ra,{currentColor:i.value??void 0,hideHighlight:s.value,withPicker:!0,onChange:l},null,8,["currentColor","hideHighlight"])]),_:1}))}}),Co=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}=Un();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))}}),Fd=d.defineComponent({__name:"MenuTooltip",setup(t){const{activeTooltip:e,isVisible:n}=Un(),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}=Pa(s,o,{placement:"top",middleware:[Ba(8),Ia({fallbackPlacements:["bottom"]}),Oa({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)}}),XO={class:"wov-menu-button"},QO=["onClick"],lk=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}=Ee(),o=Wn(()=>n.entityIds,Nt),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=Nt.write(l,c);u.thickness=a}})}return(a,l)=>(d.openBlock(),d.createBlock(bt,{title:"Thickness"},{button:d.withCtx(()=>[d.createElementVNode("div",XO,[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(St,{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,QO)),64))]),_:1}))}}),eI={class:"wov-fill-color-button"},tI={class:"wov-fill-dropdown"},nI={key:0,class:"wov-fill-mode-section"},rI=["title","onClick"],oI={viewBox:"0 0 24 24",fill:"none"},sI=["fill","fill-opacity","stroke","stroke-width","stroke-dasharray"],ck=d.defineComponent({__name:"ShapeFillColorButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=Ee(),r=Wn(()=>e.entityIds,h.Shape),o=[{mode:"solid",label:"Solid",alpha:255},{mode:"faded",label:"Faded",alpha:128},{mode:"none",label:"None",alpha:0}],s=d.computed(()=>{const m=r.value.values().next().value,g=(m==null?void 0:m.fillAlpha)??255;return g===0?"none":g<200?"faded":"solid"}),i=d.computed(()=>{const m=new Set;for(const g of r.value.values())if(g){const y=g.fillAlpha??255;y===0?m.add("none"):y<200?m.add("faded"):m.add("solid")}return m.size>1});function a(m){n(g=>{for(const y of e.entityIds){const k=h.Shape.write(g,y);k.fillAlpha=m}})}const l=d.computed(()=>{const m=new Set;for(const g of r.value.values())if(g){const y=Ns({red:g.fillRed,green:g.fillGreen,blue:g.fillBlue,alpha:g.fillAlpha??255});m.add(y)}return Array.from(m)}),c=d.computed(()=>l.value.length>1),u=d.computed(()=>l.value[0]??"#4a90d9");function f(m){n(g=>{for(const y of e.entityIds){const k=h.Shape.write(g,y);k.fillRed=m.red,k.fillGreen=m.green,k.fillBlue=m.blue,k.fillAlpha=m.alpha}})}const p=d.ref(!1);return(m,g)=>(d.openBlock(),d.createBlock(bt,{title:"Fill Color"},{button:d.withCtx(()=>[d.createElementVNode("div",eI,[g[1]||(g[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(St,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createElementVNode("div",tI,[p.value?d.createCommentVNode("",!0):(d.openBlock(),d.createElementBlock("div",nI,[(d.openBlock(),d.createElementBlock(d.Fragment,null,d.renderList(o,y=>d.createElementVNode("button",{key:y.mode,class:d.normalizeClass(["wov-fill-mode-option",{"is-active":!i.value&&y.mode===s.value}]),title:y.label,onClick:k=>a(y.alpha)},[(d.openBlock(),d.createElementBlock("svg",oI,[d.createElementVNode("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",fill:y.mode==="none"?"none":"currentColor","fill-opacity":y.mode==="faded"?.4:1,stroke:y.mode==="none"?"currentColor":"none","stroke-width":y.mode==="none"?1.5:0,"stroke-dasharray":y.mode==="none"?"3 3":""},null,8,sI)])),d.createElementVNode("span",null,d.toDisplayString(y.label),1)],10,rI)),64))])),d.createVNode(Ra,{currentColor:u.value,hideHighlight:c.value,withPicker:!0,withOpacity:!0,onChange:f,onPickerOpen:g[0]||(g[0]=y=>p.value=y)},null,8,["currentColor","hideHighlight"])])]),_:1}))}}),iI={class:"wov-shape-kind-button"},aI={class:"wov-shape-kind-dropdown"},lI=["onClick"],cI={viewBox:"0 0 20 20",class:"wov-shape-option-icon",fill:"none",stroke:"currentColor","stroke-width":"4"},dI=["d"],dk=d.defineComponent({__name:"ShapeKindButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=Ee(),r=Wn(()=>e.entityIds,h.Shape),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(ss).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=h.Shape.write(c,u);f.kind=l}})}return(l,c)=>(d.openBlock(),d.createBlock(bt,{title:"Shape Type"},{button:d.withCtx(()=>[d.createElementVNode("div",iI,[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(St,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createElementVNode("div",aI,[(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",cI,[d.createElementVNode("path",{d:d.unref(ss)[u.kind],transform:"translate(2, 2) scale(0.16)"},null,8,dI)])),d.createElementVNode("span",null,d.toDisplayString(u.label),1)],10,lI))),128))])]),_:1}))}}),uI={class:"wov-stroke-style-section"},fI=["title","onClick"],hI={viewBox:"0 0 24 8",fill:"none",stroke:"currentColor","stroke-width":"2"},pI=["stroke-dasharray","stroke-opacity"],mI=d.defineComponent({__name:"StrokeStyleOptions",props:{currentStyle:{},hasMultipleStyles:{type:Boolean}},emits:["change"],setup(t,{emit:e}){const n=e,r=[{kind:h.StrokeKind.Solid,label:"Solid"},{kind:h.StrokeKind.Dashed,label:"Dashed"},{kind:h.StrokeKind.None,label:"None"}];function o(i){switch(i){case h.StrokeKind.Dashed:return"6 6";case h.StrokeKind.None:return"";case h.StrokeKind.Solid:default:return""}}function s(i){n("change",i)}return(i,a)=>(d.openBlock(),d.createElementBlock("div",uI,[(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",hI,[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(h.StrokeKind).None?.3:1},null,8,pI)])),d.createElementVNode("span",null,d.toDisplayString(l.label),1)],10,fI)),64))]))}}),gI={class:"wov-stroke-color-button"},yI={class:"wov-stroke-dropdown"},kI={key:1,class:"wov-stroke-divider"},uk=d.defineComponent({__name:"ShapeStrokeColorButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=Ee(),r=Wn(()=>e.entityIds,h.Shape),o=d.ref(!1),s=d.computed(()=>{const p=new Set;for(const m of r.value.values())if(m){const g=Ns({red:m.strokeRed,green:m.strokeGreen,blue:m.strokeBlue,alpha:255});p.add(g)}return Array.from(p)}),i=d.computed(()=>s.value.length>1),a=d.computed(()=>s.value[0]??"#000000"),l=d.computed(()=>{const p=r.value.values().next().value;return(p==null?void 0:p.strokeKind)??h.StrokeKind.Solid}),c=d.computed(()=>{const p=new Set;for(const m of r.value.values())m&&p.add(m.strokeKind);return p.size>1});function u(p){n(m=>{for(const g of e.entityIds){const y=h.Shape.write(m,g);y.strokeRed=p.red,y.strokeGreen=p.green,y.strokeBlue=p.blue}})}function f(p){n(m=>{for(const g of e.entityIds){const y=h.Shape.write(m,g);y.strokeKind=p}})}return(p,m)=>(d.openBlock(),d.createBlock(bt,{title:"Stroke Color"},{button:d.withCtx(()=>[d.createElementVNode("div",gI,[m[1]||(m[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(St,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createElementVNode("div",yI,[o.value?d.createCommentVNode("",!0):(d.openBlock(),d.createBlock(mI,{key:0,currentStyle:l.value,hasMultipleStyles:c.value,onChange:f},null,8,["currentStyle","hasMultipleStyles"])),o.value?d.createCommentVNode("",!0):(d.openBlock(),d.createElementBlock("div",kI)),d.createVNode(Ra,{currentColor:a.value,hideHighlight:i.value,withPicker:!0,onChange:u,onPickerOpen:m[0]||(m[0]=g=>o.value=g)},null,8,["currentColor","hideHighlight"])])]),_:1}))}}),wI={key:0,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},vI={key:1,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},bI={key:2,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},SI={key:3,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},jd=d.defineComponent({__name:"TextAlignmentButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=qt(()=>e.entityIds),o=[h.TextAlignment.Left,h.TextAlignment.Center,h.TextAlignment.Right,h.TextAlignment.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(Co,{key:0,title:"Text Align",onClick:s},{default:d.withCtx(()=>[d.unref(n).alignment===d.unref(h.TextAlignment).Left?(d.openBlock(),d.createElementBlock("svg",wI,[...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(h.TextAlignment).Center?(d.openBlock(),d.createElementBlock("svg",vI,[...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(h.TextAlignment).Right?(d.openBlock(),d.createElementBlock("svg",bI,[...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",SI,[...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)}}),Hd=d.defineComponent({__name:"TextBoldButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=qt(()=>e.entityIds);return(o,s)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(Co,{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 CI(t,e){return d.getCurrentScope()?(d.onScopeDispose(t,e),!0):!1}const xI=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const _I=Object.prototype.toString,EI=t=>_I.call(t)==="[object Object]",Da=()=>{};function za(t){return Array.isArray(t)?t:[t]}function TI(t){return d.getCurrentInstance()}function MI(t,e=!0,n){TI()?d.onMounted(t,n):e?t():d.nextTick(t)}function AI(t,e,n){return d.watch(t,e,{...n,immediate:!0})}const $a=xI?window:void 0;function Rt(t){var e;const n=d.toValue(t);return(e=n==null?void 0:n.$el)!==null&&e!==void 0?e:n}function Wd(...t){const e=(r,o,s,i)=>(r.addEventListener(o,s,i),()=>r.removeEventListener(o,s,i)),n=d.computed(()=>{const r=za(d.toValue(t[0])).filter(o=>o!=null);return r.every(o=>typeof o!="string")?r:void 0});return AI(()=>{var r,o;return[(r=(o=n.value)===null||o===void 0?void 0:o.map(s=>Rt(s)))!==null&&r!==void 0?r:[$a].filter(s=>s!=null),za(d.toValue(n.value?t[1]:t[0])),za(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=EI(i)?{...i}:i,u=r.flatMap(f=>o.flatMap(p=>s.map(m=>e(f,p,m,c))));l(()=>{u.forEach(f=>f())})},{flush:"post"})}function NI(t,e,n={}){const{window:r=$a,ignore:o=[],capture:s=!0,detectIframe:i=!1,controls:a=!1}=n;if(!r)return a?{stop:Da,cancel:Da,trigger:Da}:Da;let l=!0;const c=k=>d.toValue(o).some(w=>{if(typeof w=="string")return Array.from(r.document.querySelectorAll(w)).some(v=>v===k.target||k.composedPath().includes(v));{const v=Rt(w);return v&&(k.target===v||k.composedPath().includes(v))}});function u(k){const w=d.toValue(k);return w&&w.$.subTree.shapeFlag===16}function f(k,w){const v=d.toValue(k),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 p=k=>{const w=Rt(t);if(k.target!=null&&!(!(w instanceof Element)&&u(t)&&f(t,k))&&!(!w||w===k.target||k.composedPath().includes(w))){if("detail"in k&&k.detail===0&&(l=!c(k)),!l){l=!0;return}e(k)}};let m=!1;const g=[Wd(r,"click",k=>{m||(m=!0,setTimeout(()=>{m=!1},0),p(k))},{passive:!0,capture:s}),Wd(r,"pointerdown",k=>{const w=Rt(t);l=!c(k)&&!!(w&&!k.composedPath().includes(w))},{passive:!0}),i&&Wd(r,"blur",k=>{setTimeout(()=>{var w;const v=Rt(t);((w=r.document.activeElement)===null||w===void 0?void 0:w.tagName)==="IFRAME"&&!(v!=null&&v.contains(r.document.activeElement))&&e(k)},0)},{passive:!0})].filter(Boolean),y=()=>g.forEach(k=>k());return a?{stop:y,cancel:()=>{l=!1},trigger:k=>{l=!0,p(k),l=!1}}:y}function BI(){const t=d.shallowRef(!1),e=d.getCurrentInstance();return e&&d.onMounted(()=>{t.value=!0},e),t}function OI(t){const e=BI();return d.computed(()=>(e.value,!!t()))}function II(t,e,n={}){const{window:r=$a,...o}=n;let s;const i=OI(()=>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=>Rt(f)):[Rt(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 CI(c),{isSupported:i,stop:c}}function fk(t,e={width:0,height:0},n={}){const{window:r=$a,box:o="content-box"}=n,s=d.computed(()=>{var f;return(f=Rt(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}=II(t,([f])=>{const p=o==="border-box"?f.borderBoxSize:o==="content-box"?f.contentBoxSize:f.devicePixelContentBoxSize;if(r&&s.value){const m=Rt(t);if(m){const g=m.getBoundingClientRect();i.value=g.width,a.value=g.height}}else if(p){const m=za(p);i.value=m.reduce((g,{inlineSize:y})=>g+y,0),a.value=m.reduce((g,{blockSize:y})=>g+y,0)}else i.value=f.contentRect.width,a.value=f.contentRect.height},n);MI(()=>{const f=Rt(t);f&&(i.value="offsetWidth"in f?f.offsetWidth:e.width,a.value="offsetHeight"in f?f.offsetHeight:e.height)});const c=d.watch(()=>Rt(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 hk(){const t=d.inject(pt);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 PI={class:"wov-font-family-button"},RI={class:"wov-font-family-label"},DI={class:"wov-font-list"},zI=["onClick"],$I=["src","alt"],Zd=d.defineComponent({__name:"TextFontFamilyButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=qt(()=>e.entityIds),o=hk(),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(p=>p.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(bt,{key:0,title:"Font Family"},{button:d.withCtx(()=>[d.createElementVNode("div",PI,[d.createElementVNode("span",RI,d.toDisplayString(a.value),1),d.createVNode(St,{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",DI,[(d.openBlock(!0),d.createElementBlock(d.Fragment,null,d.renderList(s.value,p=>(d.openBlock(),d.createElementBlock("div",{key:p.name,class:d.normalizeClass(["wov-font-item",{active:i.value===p.name}]),onClick:m=>l(p.name)},[p.previewImage?(d.openBlock(),d.createElementBlock("img",{key:0,class:"wov-font-preview",src:p.previewImage,alt:p.name},null,8,$I)):(d.openBlock(),d.createElementBlock("span",{key:1,class:"wov-font-name",style:d.normalizeStyle({fontFamily:p.name})},d.toDisplayString(p.displayName),5))],10,zI))),128))])],32)]),_:1})):d.createCommentVNode("",!0)}}),VI={class:"wov-font-size-button"},LI={class:"wov-font-size-label"},FI=["onClick"],jI={key:0,class:"wov-check-icon",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},HI={class:"wov-input-container"},WI=["value"],Ud=d.defineComponent({__name:"TextFontSizeButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=qt(()=>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 p=s.value;if(p===null)return"Mixed";const m=o.find(g=>g.value===p);return m?m.label:`${+p.toFixed(1)} px`}),a=d.computed(()=>{const p=s.value;return p===null?"":String(+p.toFixed(1))});function l(p){r.setFontSize(p)}function c(p){const m=p.target,g=Number.parseFloat(m.value);!Number.isNaN(g)&&g>0&&l(g)}function u(p){p.key==="Enter"&&p.target.blur()}function f(p){p.stopPropagation()}return(p,m)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(bt,{key:0,title:"Font Size"},{button:d.withCtx(()=>[d.createElementVNode("div",VI,[d.createElementVNode("span",LI,d.toDisplayString(i.value),1),d.createVNode(St,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createElementVNode("div",{class:"wov-font-size-menu",onWheel:f,onClick:m[0]||(m[0]=d.withModifiers(()=>{},["stop"]))},[(d.openBlock(),d.createElementBlock(d.Fragment,null,d.renderList(o,g=>d.createElementVNode("div",{key:g.value,class:d.normalizeClass(["wov-font-size-option",{active:s.value===g.value}]),onClick:y=>l(g.value)},[s.value===g.value?(d.openBlock(),d.createElementBlock("svg",jI,[...m[1]||(m[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:`${g.displayValue}px`})},d.toDisplayString(g.label),5)],10,FI)),64)),m[3]||(m[3]=d.createElementVNode("div",{class:"wov-separator"},null,-1)),d.createElementVNode("div",HI,[d.createElementVNode("input",{class:"wov-custom-input",value:a.value,onInput:c,onKeydown:u,placeholder:"Custom size"},null,40,WI),m[2]||(m[2]=d.createElementVNode("span",{class:"wov-px-suffix"},"px",-1))])],32)]),_:1})):d.createCommentVNode("",!0)}}),Kd=d.defineComponent({__name:"TextItalicButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=qt(()=>e.entityIds);return(o,s)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(Co,{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)}}),Jd=d.defineComponent({__name:"TextUnderlineButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=qt(()=>e.entityIds);return(o,s)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(Co,{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)}}),ZI={class:"wov-text-color-button"},UI={class:"wov-text-icon-container"},qd=d.defineComponent({__name:"TextColorButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=qt(()=>e.entityIds),o=d.computed(()=>n.color??"#000000"),s=d.computed(()=>({backgroundColor:o.value}));function i(a){r.setColor(Ns(a))}return(a,l)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(bt,{key:0,title:"Text Color"},{button:d.withCtx(()=>[d.createElementVNode("div",ZI,[d.createElementVNode("div",UI,[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(St,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createVNode(Ra,{currentColor:o.value,withPicker:!0,onChange:i},null,8,["currentColor"])]),_:1})):d.createCommentVNode("",!0)}}),KI={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"},JI={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"},qI={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"},pk=d.defineComponent({__name:"VerticalAlignButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=Ee(),{state:r}=qt(()=>e.entityIds),o=[h.VerticalAlignment.Top,h.VerticalAlignment.Center,h.VerticalAlignment.Bottom],s=Wn(()=>e.entityIds,h.VerticalAlign),i=d.computed(()=>{let l=null;for(const c of s.value.values()){const u=(c==null?void 0:c.value)??h.VerticalAlignment.Top;if(l===null)l=u;else if(l!==u)return null}return l});function a(){const l=i.value??h.VerticalAlignment.Top,c=o.indexOf(l),u=o[(c+1)%o.length];n(f=>{for(const p of e.entityIds){const m=h.VerticalAlign.write(f,p);m.value=u}})}return(l,c)=>d.unref(r).showTextMenuButtons?(d.openBlock(),d.createBlock(Co,{key:0,title:"Vertical Align",onClick:a},{default:d.withCtx(()=>[i.value===d.unref(h.VerticalAlignment).Top||i.value===null?(d.openBlock(),d.createElementBlock("svg",KI,[...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(h.VerticalAlignment).Center?(d.openBlock(),d.createElementBlock("svg",JI,[...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",qI,[...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)}}),GI={class:"wov-text-group-button"},YI={class:"wov-text-group-dropdown"},XI={class:"wov-text-group-row wov-text-group-row-full"},QI={class:"wov-text-group-row"},eP=d.defineComponent({__name:"TextButtonGroup",props:{entityIds:{},showVerticalAlign:{type:Boolean}},setup(t){const e=t,{state:n}=qt(()=>e.entityIds),r=d.inject("containerRef"),{width:o}=fk(r),s=d.computed(()=>o.value>0&&o.value<600),i=d.ref(new Map);return d.provide(ph,i),(a,l)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createElementBlock(d.Fragment,{key:0},[s.value?(d.openBlock(),d.createBlock(bt,{key:0,title:"Text Formatting",placement:"top"},{button:d.withCtx(()=>[d.createElementVNode("div",GI,[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(St,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createElementVNode("div",YI,[d.createElementVNode("div",XI,[d.createVNode(Zd,{entityIds:t.entityIds},null,8,["entityIds"]),l[1]||(l[1]=d.createElementVNode("div",{class:"wov-text-group-spacer"},null,-1)),d.createVNode(Ud,{entityIds:t.entityIds},null,8,["entityIds"])]),d.createElementVNode("div",QI,[d.createVNode(Hd,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(Kd,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(Jd,{entityIds:t.entityIds},null,8,["entityIds"]),l[2]||(l[2]=d.createElementVNode("div",{class:"wov-text-group-spacer"},null,-1)),d.createVNode(qd,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(jd,{entityIds:t.entityIds},null,8,["entityIds"]),t.showVerticalAlign?(d.openBlock(),d.createBlock(pk,{key:0,entityIds:t.entityIds},null,8,["entityIds"])):d.createCommentVNode("",!0)])])]),_:1})):(d.openBlock(),d.createElementBlock(d.Fragment,{key:1},[d.createVNode(Zd,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(Ud,{entityIds:t.entityIds},null,8,["entityIds"]),l[3]||(l[3]=d.createElementVNode("div",{divider:"",class:"wov-divider"},null,-1)),d.createVNode(Hd,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(Kd,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(Jd,{entityIds:t.entityIds},null,8,["entityIds"]),l[4]||(l[4]=d.createElementVNode("div",{divider:"",class:"wov-divider"},null,-1)),d.createVNode(qd,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(jd,{entityIds:t.entityIds},null,8,["entityIds"]),t.showVerticalAlign?(d.openBlock(),d.createBlock(pk,{key:0,entityIds:t.entityIds},null,8,["entityIds"])):d.createCommentVNode("",!0)],64))],64)):d.createCommentVNode("",!0)}}),mk=d.defineComponent({__name:"CanvasBackground",props:{background:{}},setup(t){const e=t,n=Ze(h.Camera),r=Ze(h.Grid),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(k,w,v,b){const S=b/2;k.beginPath(),k.arc(w,v,S,0,Math.PI*2),k.fill()}function u(k,w,v){if(!l)return null;const b=v.dotSize??2,S=k*v.subdivisionStep,C=w*v.subdivisionStep;l.width=S,l.height=C;const x=l.getContext("2d");if(!x)return null;if(x.clearRect(0,0,S,C),x.fillStyle=v.strokeColor,v.subdivisionStep===1)c(x,S/2,C/2,b);else for(let _=0;_<v.subdivisionStep;_++)for(let T=0;T<v.subdivisionStep;T++){const N=(_+.5)*(S/v.subdivisionStep),I=(T+.5)*(C/v.subdivisionStep),K=_===0&&T===0?2*b:b;c(x,N,I,K)}return x.createPattern(l,"repeat")}function f(k,w,v,b,S,C){k.lineWidth=C,k.beginPath(),k.moveTo(w,v),k.lineTo(b,S),k.stroke()}function p(k,w,v){if(!l)return null;const b=v.gridSize??1,S=k*v.subdivisionStep,C=w*v.subdivisionStep;l.width=S,l.height=C;const x=l.getContext("2d");if(!x)return null;if(x.clearRect(0,0,S,C),x.strokeStyle=v.strokeColor,v.subdivisionStep===1)f(x,0,0,S,0,b),f(x,0,0,0,C,b);else{const _=S/v.subdivisionStep,T=C/v.subdivisionStep;for(let N=0;N<=v.subdivisionStep;N++){const I=N*_,V=N%v.subdivisionStep===0;f(x,I,0,I,C,V?3*b:b)}for(let N=0;N<=v.subdivisionStep;N++){const I=N*T,V=N%v.subdivisionStep===0;f(x,0,I,S,I,V?3*b:b)}}return x.createPattern(l,"repeat")}function m(k){let w=r.value.colWidth,v=r.value.rowHeight;const b=e.background.subdivisionStep,S=s.value.width,C=s.value.height,x=n.value.left,_=n.value.top,T=x+S/n.value.zoom,N=_+C/n.value.zoom;let I=w*b,V=v*b,K=0,M=0,$=Number.POSITIVE_INFINITY,Z=Number.POSITIVE_INFINITY;for(;;){I=b*w,V=b*v,K=Math.floor(x/I)*I,M=Math.floor(_/V)*V;const Se=Math.ceil(T/I)*I,Dt=Math.ceil(N/V)*V;if(Z=Math.round((Se-K)/w),$=Math.round((Dt-M)/v),Math.max(Z,$)>200)w*=2,v*=2;else break}const ae=w*n.value.zoom,X=v*n.value.zoom,j=Math.round(ae),q=Math.round(X),te=u(j,q,e.background);if(!te)return;te.setTransform(new DOMMatrix().scale(ae/j,X/q));const fe=(K-x-w/2)*n.value.zoom,ce=(M-_-v/2)*n.value.zoom;k.save(),k.translate(fe,ce),k.fillStyle=te,k.fillRect(0,0,S+I*n.value.zoom,C+V*n.value.zoom),k.restore()}function g(k){let w=r.value.colWidth,v=r.value.rowHeight;const b=e.background.subdivisionStep,S=s.value.width,C=s.value.height,x=n.value.left,_=n.value.top,T=x+S/n.value.zoom,N=_+C/n.value.zoom;let I=w*b,V=v*b,K=0,M=0,$=Number.POSITIVE_INFINITY,Z=Number.POSITIVE_INFINITY;for(;;){I=b*w,V=b*v,K=Math.floor(x/I)*I,M=Math.floor(_/V)*V;const Se=Math.ceil(T/I)*I,Dt=Math.ceil(N/V)*V;if(Z=Math.round((Se-K)/w),$=Math.round((Dt-M)/v),Math.max(Z,$)>200)w*=2,v*=2;else break}const ae=w*n.value.zoom,X=v*n.value.zoom,j=Math.round(ae),q=Math.round(X),te=p(j,q,e.background);if(!te)return;te.setTransform(new DOMMatrix().scale(ae/j,X/q));const fe=(K-x)*n.value.zoom,ce=(M-_)*n.value.zoom;k.save(),k.translate(fe,ce),k.fillStyle=te,k.fillRect(0,0,S+I*n.value.zoom,C+V*n.value.zoom),k.restore()}function y(){const k=a.value;if(!k)return;const w=k.getContext("2d");if(!w)return;const{width:v,height:b}=s.value;v===0||b===0||(k.width=v,k.height=b,w.clearRect(0,0,v,b),w.fillStyle=e.background.color,w.fillRect(0,0,v,b),e.background.kind==="dots"?m(w):e.background.kind==="grid"&&g(w))}return d.watch(()=>[e.background,n.value,r.value,s.value],()=>{y()},{deep:!0}),d.onMounted(()=>{const k=o==null?void 0:o.value;if(k){const w=()=>{s.value={width:k.clientWidth,height:k.clientHeight}};w(),i=new ResizeObserver(w),i.observe(k)}y()}),d.onUnmounted(()=>{i==null||i.disconnect()}),(k,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 gk(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 yk=d.defineComponent({__name:"FloatingMenuBar",setup(t){const e=d.useSlots(),{reset:n}=Un(),r=d.inject(gh),{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(ak,{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(dk,{entityIds:d.unref(o)},null,8,["entityIds"]),d.createVNode(ck,{entityIds:d.unref(o)},null,8,["entityIds"]),d.createVNode(uk,{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(lk,{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(ok,{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(Ld,{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(Ld,{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(eP,{key:0,entityIds:d.unref(o),showVerticalAlign:d.unref(s).has("verticalAlign")},null,8,["entityIds","showVerticalAlign"])):d.createCommentVNode("",!0)]),d.createVNode(Fd)],32))}}),tP={class:"wov-floating-menu-inner"},kk=d.defineComponent({__name:"FloatingMenu",setup(t){const e=d.inject(pt),n=_0([h.Block,Ie]),r=Ze(h.Camera),o=Ze(h.Screen),s=Ze(Tt),i=Bs(),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 C=n.value.map(x=>({tag:x.block.value.tag}));return gk(S,C)});d.provide(gh,{selectedIds:a,commonComponents:l});const c=[0,0,0,0];function u(...S){let C=1/0,x=1/0,_=-1/0,T=-1/0,N=!1;for(const I of S){if(!I)continue;const V=I.getBoundingClientRect();V.width<=0||(N=!0,C=Math.min(C,V.left),x=Math.min(x,V.top),_=Math.max(_,V.right),T=Math.max(T,V.bottom))}return N?{x:C,y:x,left:C,top:x,right:_,bottom:T,width:_-C,height:T-x,toJSON:()=>({})}:null}const f=d.computed(()=>{if(n.value.length===0)return null;const S=r.value;if(!S)return null;let C=null;for(const x of n.value){const _=x.block.value;E.Rect.getAabb(_.position,_.size,_.rotateZ,c),E.Aabb.translate(c,[-S.left,-S.top]),E.Aabb.scale(c,S.zoom),C===null?C=E.Aabb.clone(c):E.Aabb.union(C,c)}return C}),p=d.inject("containerRef"),m=d.computed(()=>{const S=p==null?void 0:p.value;if(!S)return null;r.value,i.updateCounter.value;const C=i.blockElement.value,x=i.textElement.value,_=u(C,x);if(_)return{getBoundingClientRect:()=>_};const T=f.value;if(!T)return null;const N=S.getBoundingClientRect();return{getBoundingClientRect(){return{x:N.left+T[0],y:N.top+T[1],width:T[2]-T[0],height:T[3]-T[1],top:N.top+T[1],left:N.left+T[0],right:N.left+T[2],bottom:N.top+T[3]}}}}),g=d.ref(null),y={name:"clampToViewport",fn({y:S,rects:C}){const T=window.innerHeight-C.floating.height-8;return{y:Math.max(8,Math.min(S,T))}}},{floatingStyles:k}=Pa(m,g,{placement:"top",middleware:[Ba(12),Ia({fallbackPlacements:["bottom"]}),Oa({padding:8}),y]}),w=d.computed(()=>{const S=f.value,C=o.value;return!S||!C?!0:S[2]<0||S[0]>C.width||S[3]<0||S[1]>C.height}),v=[de.Dragging,de.SelectionBoxDragging],b=d.computed(()=>n.value.length>0&&!w.value&&!v.includes(s.value.state));return(S,C)=>(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:g,class:"wov-floating-menu",style:d.normalizeStyle(d.unref(k))},[d.createElementVNode("div",tP,[d.renderSlot(S.$slots,"default",{},()=>[d.createVNode(yk)])])],4)):d.createCommentVNode("",!0)]),_:3}))}}),nP={key:0,class:"wov-loading-overlay"},rP={class:"wov-loading-spinner"},wk=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",nP,[d.createElementVNode("div",rP,d.toDisplayString(e.value),1)])):d.createCommentVNode("",!0)]),_:1}))}}),oP={class:"wov-action-bar"},sP=d.defineComponent({__name:"ActionBar",setup(t){const{getEditor:e}=Ee(),n=d.inject(pt),r=d.ref(!1),o=d.ref(!1);if(n){const l=n.registerTickCallback(c=>{const{store:u}=h.getPluginResources(c,"editing");r.value=u.canUndo(),o.value=u.canRedo()});d.onUnmounted(l)}function s(){const l=e();l==null||l.command(h.Undo)}function i(){const l=e();l==null||l.command(h.Redo)}function a(){const l=e();l==null||l.command(yl)}return(l,c)=>(d.openBlock(),d.createElementBlock("div",oP,[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)])])]))}}),Qt=d.defineComponent({__name:"ToolbarButton",props:{name:{},tooltip:{},dragOutSnapshot:{},placementSnapshot:{},cursor:{default:"crosshair"}},setup(t){const e=t,n=d.inject(Ul);if(!n)throw new Error("ToolbarButton must be used within a Toolbar component");const r=n,o=d.ref(null),{show:s,hide:i}=Un(),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 p(){i()}return(m,g)=>(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:p},[d.renderSlot(m.$slots,"default")],34))}}),iP='<?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>',aP='<?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>',lP='<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>',Ir={Select:"select",Hand:"hand",Crosshair:"crosshair"},vk={[Ir.Select]:{makeSvg:()=>iP,hotspot:[1,0],rotationOffset:0},[Ir.Hand]:{makeSvg:()=>aP,hotspot:[12,12],rotationOffset:0},[Ir.Crosshair]:{makeSvg:()=>lP,hotspot:[12,12],rotationOffset:0}},cP={viewBox:"0 0 20 20",style:{"fill-rule":"evenodd","clip-rule":"evenodd","stroke-miterlimit":"10"}},bk=d.defineComponent({__name:"SelectTool",setup(t){const{nextEditorTick:e}=Ee(),{activeTool:n}=Od();return d.watch(n,(r,o)=>{o==="select"&&e(s=>{Xr.spawn(s)})}),(r,o)=>(d.openBlock(),d.createBlock(Qt,{name:"select",tooltip:"Select",cursor:d.unref(Ir).Select},{default:d.withCtx(()=>[(d.openBlock(),d.createElementBlock("svg",cP,[...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"]))}}),Sk=d.defineComponent({__name:"HandTool",setup(t){return(e,n)=>(d.openBlock(),d.createBlock(Qt,{name:"hand",tooltip:"Hand",cursor:d.unref(Ir).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"]))}}),Ck=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:h.TextAlignment.Center},verticalAlign:{value:h.VerticalAlignment.Center}});return(n,r)=>(d.openBlock(),d.createBlock(Qt,{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"]))}}),xk=d.defineComponent({__name:"ShapeTool",setup(t){const e=JSON.stringify({block:{tag:"shape",size:[200,200]},shape:{kind:"rectangle",strokeKind:h.StrokeKind.Solid,strokeWidth:2,strokeRed:0,strokeGreen:0,strokeBlue:0,strokeAlpha:255,fillRed:255,fillGreen:255,fillBlue:255,fillAlpha:0},text:{defaultAlignment:h.TextAlignment.Center},verticalAlign:{value:h.VerticalAlignment.Center}});return(n,r)=>(d.openBlock(),d.createBlock(Qt,{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"]))}}),_k=d.defineComponent({__name:"EraserTool",setup(t){return(e,n)=>(d.openBlock(),d.createBlock(Qt,{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}))}}),Ek=d.defineComponent({__name:"PenTool",setup(t){return(e,n)=>(d.openBlock(),d.createBlock(Qt,{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}))}}),Tk=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(Qt,{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"]))}}),Mk=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:pe.None,endArrowHead:pe.V},connector:{}});return(n,r)=>(d.openBlock(),d.createBlock(Qt,{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"]))}}),Ak=d.defineComponent({__name:"ImageTool",setup(t){const{nextEditorTick:e}=Ee(),{show:n,hide:r}=Un(),{setTool:o}=Od(),{createImageBlock:s}=x0(),i=d.ref(null),a=d.ref(null);function l(){var p;(p=a.value)==null||p.click()}async function c(p){var S;const m=p.target,g=(S=m.files)==null?void 0:S[0];if(!g)return;if(m.value="",!g.type.startsWith("image/")){console.warn("Selected file is not an image");return}const y=await e(),k=h.Camera.read(y),w=h.Screen.read(y),v=k.left+w.width/k.zoom/2,b=k.top+w.height/k.zoom/2;await s(g,v,b),o("select",void 0,Ir.Select)}function u(){i.value&&n("Image",i.value)}function f(){r()}return(p,m)=>(d.openBlock(),d.createElementBlock("button",{ref_key:"buttonRef",ref:i,class:"wov-toolbar-button",onClick:l,onMouseenter:u,onMouseleave:f},[m[0]||(m[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))}}),dP={class:"wov-toolbar-container"},Nk=d.defineComponent({__name:"Toolbar",setup(t){const e=d.useSlots(),{reset:n}=Un(),{nextEditorTick:r}=Ee(),o=d.ref(null),s=d.ref(null),i=Ze(h.Controls),a=d.computed(()=>i.value.leftMouseTool),l=[bk,Sk,Tk,Ak,xk,Mk,Ck,Ek,_k],c=d.inject("containerRef"),u=d.ref(null),f=d.ref(!1),p=d.ref(null),m=d.ref(null),g=d.ref(1/0),y=d.ref(0),k=d.ref([]),w=d.ref(8),v=d.ref(48),{width:b}=fk(c);function S(){return p.value?Array.from(p.value.children).filter(j=>!j.classList.contains("wov-overflow-button")&&!j.classList.contains("wov-menu-tooltip")):[]}function C(){var fe;const j=S();if(j.length===0)return;y.value=j.length;const q=getComputedStyle(p.value);w.value=parseFloat(q.gap)||8;const te=((fe=m.value)==null?void 0:fe.offsetWidth)||40;v.value=te+w.value,k.value=j.map(ce=>ce.offsetWidth)}function x(){if(k.value.length===0)return;const te=b.value-40-20,fe=w.value,ce=v.value;let Se=0,Dt=0;for(let gn=0;gn<k.value.length;gn++){const Dr=k.value[gn],qn=Se>0?Dr+fe:Dr,Gn=k.value.length-gn-1>0?ce:0;if(Se+qn+Gn<=te)Se+=qn,Dt++;else break}g.value=Math.max(1,Dt)}d.watch(b,()=>{k.value.length>0&&x()}),d.onMounted(()=>{d.nextTick(()=>{C(),x()})});const _=d.computed(()=>g.value<y.value);d.watchEffect(()=>{S().forEach((q,te)=>{q.style.display=te<g.value?"":"none"})}),d.watchEffect(()=>{if(!u.value)return;Array.from(u.value.children).forEach((q,te)=>{q.style.display=te>=g.value?"":"none"})});const{floatingStyles:T}=Pa(m,u,{placement:"top",middleware:[Ba(16),Ia(),Oa({padding:8})],whileElementsMounted:ek});function N(){f.value=!f.value}function I(){f.value=!1}function V(j){const q=j.target;m.value&&!m.value.contains(q)&&u.value&&!u.value.contains(q)&&I()}d.watch(f,j=>{j?document.addEventListener("click",V,!0):document.removeEventListener("click",V,!0)}),d.watch(_,j=>{j||I()});function K(j,q,te){s.value=q??null,r(fe=>{const ce=h.Controls.write(fe);ce.leftMouseTool=j,ce.heldSnapshot=q??"",te&&h.Cursor.setCursor(fe,te)})}function M(j){r(q=>{const te=h.Controls.write(q);te.leftMouseTool="drag-out",te.heldSnapshot=j})}function $(j,q){o.value=j,s.value=q??null}function Z(){o.value=null,s.value=null}function ae(){n(),o.value&&s.value&&M(s.value),o.value=null,s.value=null}const X={activeTool:a,heldTool:o,setTool:K,dragOutTool:M,onToolPointerDown:$,onToolPointerUp:Z};return d.provide(Ul,X),(j,q)=>(d.openBlock(),d.createElementBlock("div",dP,[d.createVNode(sP),d.createElementVNode("div",{ref_key:"toolsContainerRef",ref:p,class:"wov-toolbar",onMouseleave:ae},[d.unref(e).default?d.renderSlot(j.$slots,"default",{key:0}):(d.openBlock(),d.createElementBlock(d.Fragment,{key:1},d.renderList(l,(te,fe)=>d.createVNode(d.resolveDynamicComponent(te),{key:fe})),64)),_.value?(d.openBlock(),d.createElementBlock("button",{key:2,ref_key:"overflowBtnRef",ref:m,class:d.normalizeClass(["wov-toolbar-button wov-overflow-button",{"menu-open":f.value}]),onClick:N},[...q[0]||(q[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(Fd)],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(T))},[d.unref(e).default?d.renderSlot(j.$slots,"default",{key:0}):(d.openBlock(),d.createElementBlock(d.Fragment,{key:1},d.renderList(l,(te,fe)=>d.createVNode(d.resolveDynamicComponent(te),{key:fe})),64))],4)):d.createCommentVNode("",!0)],8,["to"])):d.createCommentVNode("",!0)]))}}),uP=d.defineComponent({__name:"ArcArrowTool",setup(t){return(e,n)=>(d.openBlock(),d.createBlock(Qt,{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}))}}),fP={class:"wov-user-presence-avatars"},hP=["src","alt"],pP={class:"wov-user-presence-list"},mP=["src","alt"],gP={class:"wov-user-presence-name"},yP=4,Bk=d.defineComponent({__name:"UserPresence",props:{users:{}},setup(t){const e=t,n=d.ref(!1),r=d.ref(null);NI(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,yP));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",fP,[(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,hP)):(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",pP,[(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,mP)):(d.openBlock(),d.createElementBlock(d.Fragment,{key:1},[d.createTextVNode(d.toDisplayString(c.initials),1)],64))],4),d.createElementVNode("span",gP,d.toDisplayString(c.name),1)]))),128))])],32)):d.createCommentVNode("",!0)],512)):d.createCommentVNode("",!0)}}),Gd=(t,e)=>e.some(n=>t instanceof n);let Ok,Ik;function kP(){return Ok||(Ok=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function wP(){return Ik||(Ik=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const Yd=new WeakMap,Xd=new WeakMap,Va=new WeakMap;function vP(t){const e=new Promise((n,r)=>{const o=()=>{t.removeEventListener("success",s),t.removeEventListener("error",i)},s=()=>{n(Pr(t.result)),o()},i=()=>{r(t.error),o()};t.addEventListener("success",s),t.addEventListener("error",i)});return Va.set(e,t),e}function bP(t){if(Yd.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)});Yd.set(t,e)}let Qd={get(t,e,n){if(t instanceof IDBTransaction){if(e==="done")return Yd.get(t);if(e==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Pr(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 Pk(t){Qd=t(Qd)}function SP(t){return wP().includes(t)?function(...e){return t.apply(eu(this),e),Pr(this.request)}:function(...e){return Pr(t.apply(eu(this),e))}}function CP(t){return typeof t=="function"?SP(t):(t instanceof IDBTransaction&&bP(t),Gd(t,kP())?new Proxy(t,Qd):t)}function Pr(t){if(t instanceof IDBRequest)return vP(t);if(Xd.has(t))return Xd.get(t);const e=CP(t);return e!==t&&(Xd.set(t,e),Va.set(e,t)),e}const eu=t=>Va.get(t);function xP(t,e,{blocked:n,upgrade:r,blocking:o,terminated:s}={}){const i=indexedDB.open(t,e),a=Pr(i);return r&&i.addEventListener("upgradeneeded",l=>{r(Pr(i.result),l.oldVersion,l.newVersion,Pr(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 _P=["get","getKey","getAll","getAllKeys","count"],EP=["put","add","delete","clear"],tu=new Map;function Rk(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(tu.get(e))return tu.get(e);const n=e.replace(/FromIndex$/,""),r=e!==n,o=EP.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(o||_P.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 tu.set(e,s),s}Pk(t=>({...t,get:(e,n,r)=>Rk(e,n)||t.get(e,n,r),has:(e,n)=>!!Rk(e,n)||t.has(e,n)}));const TP=["continue","continuePrimaryKey","advance"],Dk={},nu=new WeakMap,zk=new WeakMap,MP={get(t,e){if(!TP.includes(e))return t[e];let n=Dk[e];return n||(n=Dk[e]=function(...r){nu.set(this,zk.get(this)[e](...r))}),n}};async function*AP(...t){let e=this;if(e instanceof IDBCursor||(e=await e.openCursor(...t)),!e)return;e=e;const n=new Proxy(e,MP);for(zk.set(n,e),Va.set(n,eu(e));e;)yield n,e=await(nu.get(n)||e.continue()),nu.delete(n)}function $k(t,e){return e===Symbol.asyncIterator&&Gd(t,[IDBIndex,IDBObjectStore,IDBCursor])||e==="iterate"&&Gd(t,[IDBIndex,IDBObjectStore])}Pk(t=>({...t,get(e,n,r){return $k(e,n)?AP:t.get(e,n,r)},has(e,n){return $k(e,n)||t.has(e,n)}}));async function ru(t,e){const n=await xP(t,1,{upgrade(r){r.objectStoreNames.contains(e)||r.createObjectStore(e)}});return new NP(n,e)}var NP=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()}},BP=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([ru(`${t}-jobs`,"jobs"),ru(`${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))}}},OP="wovencanvas-assets",IP="blobs",PP=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=ru(OP,IP).then(t=>(this.store=t,t))),this.initPromise)}},Vk=rn.object({minZoom:rn.number().default(.05),maxZoom:rn.number().default(2.7)});Vk.parse({});var Rs=h.defineEditorState("panState",{state:h.field.string().max(16).default("idle"),panStartX:h.field.float64().default(0),panStartY:h.field.float64().default(0),velocityX:h.field.float64().default(0),velocityY:h.field.float64().default(0),targetX:h.field.float64().default(0),targetY:h.field.float64().default(0),expectedLeft:h.field.float64().default(0),expectedTop:h.field.float64().default(0)}),Rr=h.defineCanvasSingleton({name:"pinchState"},{active:h.field.boolean().default(!1),prevDistance:h.field.float64().default(0),prevCenter:h.field.tuple(h.field.float64(),2).default([0,0])}),mn=[0,0],La=[0,0],Ds=[0,0],ou=[0,0],su=[0,0];function RP(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);E.Vec2.copy(mn,t),E.Vec2.sub(mn,e);const c=o*r,u=c*c,f=E.Vec2.lengthSq(mn);f>u&&E.Vec2.scale(mn,c/Math.sqrt(f)),E.Vec2.copy(La,t),E.Vec2.sub(La,mn),E.Vec2.set(Ds,(n[0]+i*mn[0])*s,(n[1]+i*mn[1])*s);const p=[(n[0]-i*Ds[0])*l,(n[1]-i*Ds[1])*l],m=[La[0]+(mn[0]+Ds[0])*l,La[1]+(mn[1]+Ds[1])*l];return E.Vec2.copy(ou,e),E.Vec2.sub(ou,t),E.Vec2.copy(su,m),E.Vec2.sub(su,e),E.Vec2.dot(ou,su)>0&&(m[0]=e[0],m[1]=e[1],p[0]=(m[0]-e[0])/s,p[1]=(m[1]-e[1])/s),{position:m,velocity:p}}var iu=.1,Lk=.1,DP=on({guards:{hasVelocity:({event:t})=>{if(t.type!=="pointerUp")return!1;const e=t.velocity;return Math.hypot(e[0],e[1])>Lk},isGlideComplete:({context:t})=>Math.hypot(t.velocityX,t.velocityY)<Lk,cameraWasMoved:({context:t,event:e})=>{const n=h.Camera.read(e.ctx);return n.left!==t.expectedLeft||n.top!==t.expectedTop},isEscapeKey:({event:t})=>t.key===h.Key.Escape},actions:{setDragStart:we({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=h.Camera.write(r);i.left-=o,i.top-=s},startGlide:we(({event:t})=>{const e=t,{ctx:n}=e,r=h.Camera.read(n),o=e.cameraZoom,s=-e.velocity[0]/o,i=-e.velocity[1]/o;return{velocityX:s,velocityY:i,targetX:r.left+s*iu,targetY:r.top+i*iu,expectedLeft:r.left,expectedTop:r.top}}),animateGlide:we(({context:t,event:e})=>{const n=e,{ctx:r,delta:o}=n,s=h.Camera.read(r),{position:i,velocity:a}=RP([s.left,s.top],[t.targetX,t.targetY],[t.velocityX,t.velocityY],iu,Number.POSITIVE_INFINITY,o),l=h.Camera.write(r);return l.left=i[0],l.top=i[1],{velocityX:a[0],velocityY:a[1],expectedLeft:i[0],expectedTop:i[1]}}),resetContext:we({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"}}}}}),zP=h.defineEditorSystem({phase:"input",priority:-100},t=>{const e=Rs.read(t).state;if(Rr.read(t).active){e!=="idle"&&Rs.copy(t,Rs.default());return}const r=h.Controls.getButtons(t,"hand"),s=[...h.getPointerInput(t,r)];e==="gliding"&&s.push(h.getFrameInput(t)),s.push(...h.getKeyboardInput(t,[h.Key.Escape])),s.length!==0&&Rs.run(t,DP,s)}),$P=h.defineQuery(t=>t.with(h.Pointer)),VP=h.defineEditorSystem({phase:"input",priority:-100},t=>{const e=h.getPluginResources(t,"controls"),n=$P.current(t),r=[];for(let g=0;g<n.length;g++){const y=n[g],k=h.Pointer.read(t,y);k.pointerType===h.PointerType.Touch&&r.push(k.position)}if(r.length!==2){if(Rr.read(t).active){const y=Rr.write(t);y.active=!1}return}const[o,s]=r,i=E.Vec2.distance(o,s),a=E.Vec2.midPoint(o,s),l=Rr.read(t);if(!l.active){const g=Rr.write(t);g.prevDistance=i,g.prevCenter=a,g.active=!0;return}const c=h.Camera.read(t),u=h.Screen.read(t);if(l.prevDistance>0&&i>0){const g=i/l.prevDistance;let y=c.zoom*g;y=Math.min(e.maxZoom,Math.max(e.minZoom,y));const k=u.width/c.zoom,w=u.height/c.zoom,v=u.width/y,b=u.height/y,S=v-k,C=b-w,x=a[0]/u.width,_=a[1]/u.height,T=h.Camera.write(t);T.left-=x*S,T.top-=_*C,T.zoom=y}const f=a[0]-l.prevCenter[0],p=a[1]-l.prevCenter[1];if(f!==0||p!==0){const g=h.Camera.write(t);g.left-=f/g.zoom,g.top-=p/g.zoom}const m=Rr.write(t);m.prevDistance=i,m.prevCenter=a}),LP=h.defineEditorSystem({phase:"input",priority:-100},t=>{const e=h.Keyboard.read(t);if(!h.Controls.wheelActive(t,"scroll",e.modDown))return;const r=h.getMouseInput(t).find(l=>l.type==="wheel");if(!r)return;const o=h.Camera.read(t),s=o.left+r.wheelDeltaX/o.zoom,i=o.top+r.wheelDeltaY/o.zoom,a=h.Camera.write(t);a.left=s,a.top=i}),FP=h.defineEditorSystem({phase:"input",priority:-100},t=>{const e=h.getPluginResources(t,"controls"),n=h.Keyboard.read(t);if(!h.Controls.wheelActive(t,"zoom",n.modDown))return;const o=h.getMouseInput(t).find(S=>S.type==="wheel");if(!o)return;const s=h.Camera.read(t),i=h.Screen.read(t),a=h.Mouse.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,p=i.height/l,m=f-c,g=p-u,y=a.position[0]/i.width,k=a.position[1]/i.height,w=s.left-y*m,v=s.top-k*g,b=h.Camera.write(t);b.left=w,b.top=v,b.zoom=l});function jP(t={}){return{name:"controls",resources:Vk.parse(t),singletons:[Rs,Rr],systems:[FP,LP,zP,VP]}}var HP=(t={})=>jP(t);const WP={class:"wov-selection-box"},ZP=d.defineComponent({__name:"SelectionBox",setup(t){return(e,n)=>(d.openBlock(),d.createElementBlock("div",WP))}}),UP={class:"wov-transform-box"},KP=d.defineComponent({__name:"TransformBox",setup(t){return(e,n)=>(d.openBlock(),d.createElementBlock("div",UP))}}),JP={},qP={class:"wov-transform-handle"};function GP(t,e){return d.openBlock(),d.createElementBlock("div",qP)}const YP=ir(JP,[["render",GP]]),XP=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=Pe(e.entityId,h.Color),r=Pe(e.entityId,h.VerticalAlign),o=d.ref(null),s={[h.VerticalAlignment.Top]:"flex-start",[h.VerticalAlignment.Center]:"center",[h.VerticalAlignment.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)??h.VerticalAlignment.Top]}}),{handleEditEnd:a}=Bd({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(wa,d.mergeProps(e,{"block-element":o.value,onEditEnd:d.unref(a)}),null,16,["block-element","onEditEnd"])],4))}}),Fa=at.defineCanvasSingleton({name:"blockPlacementState"},{editedCheckpoint:h.field.string().default("").max(36)}),Fk=h.defineQuery(t=>t.with(h.Edited));function QP(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 eR(t,e,n){const r=h.getBlockDef(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??h.RankBounds.genNext(t),l=h.createEntity(t);"synced"in e||h.addComponent(t,l,h.Synced,{id:crypto.randomUUID()});const c=Object.assign({},e.block,{position:[s,i],size:o,rank:a});h.addComponent(t,l,h.Block,c);for(const f of r.components)if(!(f.name in e))h.addComponent(t,l,f);else{const p=e[f.name];h.addComponent(t,l,f,p)}const{sessionId:u}=h.getResources(t);return h.addComponent(t,l,h.Held,{sessionId:u}),l}function jk(t,e,n,r,o){const s=eR(t,e,n),i=h.Block.read(t,s);if(h.canBlockEdit(t,e.block.tag)&&(h.addComponent(t,s,Ko,{}),o==="placement")){const{store:u}=h.getPluginResources(t,"editing"),f=u.createCheckpoint();if(f){const p=Fa.write(t);p.editedCheckpoint=f}}const a=Tt.write(t);a.state=o==="dragOut"?de.Dragging:de.Pointing,a.dragStart=n,a.draggedEntity=s,a.draggedEntityStart=i.position,a.pointingStartClient=r,a.pointingStartWorld=n,a.isCloning=!1;const l=h.Controls.write(t);l.leftMouseTool="select",l.heldSnapshot="";const c=h.Cursor.write(t);c.cursorKind="select",c.rotation=0}function tR(t){const e=Fa.read(t);if(e.editedCheckpoint){const n=e.editedCheckpoint;Fa.write(t).editedCheckpoint="";const{store:r}=h.getPluginResources(t,"editing");r.onSettled(()=>r.squashToCheckpoint(n),{frames:5})}}const nR=h.defineEditorSystem({phase:"capture"},t=>{Fk.removed(t).length>0&&Fk.current(t).length===0&&tR(t);const e=h.Controls.read(t);if(!e.heldSnapshot)return;const n=h.getPointerInput(t,[h.PointerButton.Left]);if(n.length===0)return;const r=QP(e.heldSnapshot);if(!r)return;if(e.leftMouseTool==="drag-out"){const s=n.find(i=>i.type==="pointerMove"&&!i.obscured);if(!s)return;jk(t,r,s.worldPosition,s.screenPosition,"dragOut")}else{const s=n.find(i=>i.type==="pointerDown"&&!i.obscured);if(!s)return;jk(t,r,s.worldPosition,s.screenPosition,"placement")}}),rR=h.defineEditorSystem({phase:"update"},t=>{const{store:e}=h.getPluginResources(t,"editing");h.on(t,h.Undo,()=>{e.canUndo()&&(bf(t),e.undo())}),h.on(t,h.Redo,()=>{e.canRedo()&&(bf(t),e.redo())})}),oR=[{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 Hk(t){return{name:"editing",resources:{store:t.store},singletons:[Fa],systems:[nR,rR],cursors:vk,fonts:oR,keybinds:[{command:h.Undo.name,key:h.Key.Z,mod:!0},{command:h.Redo.name,key:h.Key.Y,mod:!0},{command:h.Redo.name,key:h.Key.Z,mod:!0,shift:!0}]}}const sR=d.defineComponent({__name:"FileDropZone",props:{maxSize:{default:400}},setup(t){const e=t,{nextEditorTick:n}=Ee(),{createImageBlock:r}=x0(),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 p(v){v.preventDefault()}async function m(v){if(v.preventDefault(),!v.dataTransfer)return;const b=v.clientX,S=v.clientY,C=Array.from(v.dataTransfer.files).filter(_=>_.type.startsWith("image/"));if(C.length>0){for(const _ of C)await k(_,b,S);return}const x=g(v.dataTransfer);x&&await w(x,b,S)}function g(v){const b=v.getData("text/uri-list");if(b){const _=b.split(`
171
+ `).filter(T=>!T.startsWith("#")).find(T=>y(T));if(_)return _}const S=v.getData("text/html");if(S){const x=S.match(/<img[^>]+src=["']([^"']+)["']/i);if(x!=null&&x[1])return x[1]}const C=v.getData("text/plain");return C&&y(C)?C:null}function y(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 k(v,b,S){const C=await n(),x=h.Camera.read(C),_=h.Screen.read(C),T=x.left+(b-_.left)/x.zoom,N=x.top+(S-_.top)/x.zoom;await r(v,T,N,{maxSize:e.maxSize})}async function w(v,b,S){try{const C=await fetch(v);if(!C.ok){console.warn("Failed to fetch image from URL:",v);return}const x=await C.blob();if(!x.type.startsWith("image/")){console.warn("URL did not return an image:",v);return}const T=new URL(v).pathname.split("/").pop()||"image",N=new File([x],T,{type:x.type});await k(N,b,S)}catch(C){console.warn("Failed to load image from URL:",v,C)}}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:p,onDrop:m},null,34))}}),iR={class:"wov-user-cursors"},aR={class:"wov-cursor-svg",viewBox:"0 0 4.35 4.75",width:"20",height:"20"},lR=["fill"],cR="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",dR=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",iR,[(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",aR,[d.createElementVNode("path",{fill:s.color,stroke:"#fff","stroke-miterlimit":"10","stroke-width":".25",d:cR},null,8,lR)])),d.createElementVNode("span",{class:"wov-cursor-label",style:d.normalizeStyle({backgroundColor:s.color})},d.toDisplayString(s.name),5)],4))),128))]))}}),uR={key:0,class:"wov-offline-indicator"},fR=d.defineComponent({__name:"OfflineIndicator",props:{isOnline:{type:Boolean}},setup(t){return(e,n)=>t.isOnline?d.createCommentVNode("",!0):(d.openBlock(),d.createElementBlock("div",uR,"Working Offline"))}}),hR={key:0,class:"wov-version-mismatch-overlay"},pR=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",hR,[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)}}),mR=d.defineComponent({__name:"BackToContentButton",setup(t){const{nextEditorTick:e}=Ee(),n=Ze(h.Camera),r=h.defineQuery(l=>l.with(h.Synced,h.Block,h.Aabb)),o=d.ref(0),s=d.inject(pt);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,p=Number.NEGATIVE_INFINITY,m=Number.NEGATIVE_INFINITY;for(const x of c){const _=h.Aabb.read(l,x);u=Math.min(u,_.value[0]),f=Math.min(f,_.value[1]),p=Math.max(p,_.value[2]),m=Math.max(m,_.value[3])}const g=h.Screen.read(l),y=h.Camera.read(l);let k=Math.min(g.width/(p-u),g.height/(m-f));k/=1.1,k=Math.min(k,y.zoom);const w=(u+p)/2,v=(f+m)/2,b=w-g.width/k/2,S=v-g.height/k/2,C=h.Camera.write(l);C.left=b,C.top=S,C.zoom=k})}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)}}),gR=["data-entity-id","data-selected","data-held-by-other","data-hovered"],yR=d.defineComponent({__name:"WovenCanvas",props:{store:{},editor:{},background:{},assetProvider:{},pluginOptions:{},controls:{}},emits:["ready"],setup(t,{emit:e}){var Wk;const n=h.defineQuery(A=>A.tracking(h.Block)),r=h.defineQuery(A=>A.with(h.Block).tracking(h.Connector)),o=h.defineQuery(A=>A.with(h.Block).tracking(Ie)),s=h.defineQuery(A=>A.with(h.Block).tracking(h.Held)),i=h.defineQuery(A=>A.with(h.Block).tracking(h.Hovered)),a=h.defineQuery(A=>A.with(h.Block).tracking(h.Edited)),l=h.defineQuery(A=>A.with(h.Block).tracking(h.Opacity)),c=h.defineQuery(A=>A.tracking(h.User)),u=t,f=e,p=d.ref(null),m=d.shallowRef(null),g=h.UserData.parse(((Wk=u.editor)==null?void 0:Wk.user)??{}),y=new Set,k=new Map,w=d.shallowRef([]),v=new Map,b=new Map,S=new Set,C=new Map,x=d.shallowRef([]),_=d.ref(!0),T=d.ref(!1),N=d.ref(!0),I=d.shallowRef(h.Camera.default());function V(A,se,D){let Y=v.get(A);Y||(Y=new Map,v.set(A,Y));let H=Y.get(se);return H||(H=new Set,Y.set(se,H)),H.add(D),()=>{H.delete(D),H.size===0&&(Y.delete(se),Y.size===0&&v.delete(A))}}function K(A,se,D,Y=!1){const H=v.get(se);if(!H)return;const R=H.get(D.name);if(!R||R.size===0)return;let Me=null;Y||(Me=D.snapshot(A,se));for(const zt of R)zt(Me)}function M(A,se){let D=b.get(A);return D||(D=new Set,b.set(A,D)),D.add(se),()=>{D.delete(se),D.size===0&&b.delete(A)}}function $(A,se){const D=b.get(se.name);if(!D||D.size===0)return;const Y=se.snapshot(A);for(const H of D)H(Y)}function Z(A){return S.add(A),()=>{S.delete(A)}}function ae(){return g.sessionId}function X(A){return k.get(A)??null}const j={hasEntity:A=>y.has(A),getEditor:()=>m.value,getAssetManager:()=>Se,getSessionId:ae,getUserBySessionId:X,subscribeComponent:V,subscribeSingleton:M,registerTickCallback:Z};d.provide(pt,j),d.provide("containerRef",p);const q=I0();d.provide(yh,q);let te=0,fe=null,ce=null,Se=null;async function Dt(){!m.value||!ce||(m.value.nextTick(A=>{Dr(A),qn(A);for(const se of S)se(A);ce&&ce.sync(A)}),await m.value.tick(),fe=requestAnimationFrame(Dt))}let gn=null;d.onMounted(async()=>{var zt,it;if(!p.value)return;gn=()=>{var zr;(zr=p.value)==null||zr.scrollTo(0,0)},p.value.addEventListener("scroll",gn);const A=u.store??{},se={history:!0,...A};A.websocket&&(se.websocket={...A.websocket,onVersionMismatch:zr=>{var yn,zs;T.value=!0,(zs=(yn=A.websocket)==null?void 0:yn.onVersionMismatch)==null||zs.call(yn,zr)},onConnectivityChange:zr=>{var yn,zs;_.value=zr,(zs=(yn=A.websocket)==null?void 0:yn.onConnectivityChange)==null||zs.call(yn,zr)}}),ce=new at.CanvasStore(se);const D=[],Y=u.pluginOptions;(Y==null?void 0:Y.controls)!==!1&&D.push(HP((Y==null?void 0:Y.controls)??{})),(Y==null?void 0:Y.selection)!==!1&&D.push(mb((Y==null?void 0:Y.selection)||void 0)),(Y==null?void 0:Y.eraser)!==!1&&D.push(I_((Y==null?void 0:Y.eraser)||void 0)),(Y==null?void 0:Y.pen)!==!1&&D.push(bE()),(Y==null?void 0:Y.arrows)!==!1&&D.push(TS((Y==null?void 0:Y.arrows)||void 0)),D.push(Hk({store:ce})),(zt=u.editor)!=null&&zt.plugins&&D.push(...u.editor.plugins);const H={...u.editor,user:g,plugins:D,controls:u.controls},R=new h.Editor(p.value,H);await R.initialize(),await ce.initialize({components:R.components,singletons:R.singletons});const Me=((it=A.persistence)==null?void 0:it.documentId)??"default";Se=new BP({provider:u.assetProvider??new PP,documentId:Me}),await Se.init(),await Se.resumePendingUploads(),m.value=R,fe=requestAnimationFrame(Dt),N.value=!1,f("ready",R,ce)}),d.onUnmounted(()=>{var A;fe!==null&&cancelAnimationFrame(fe),Se==null||Se.close(),ce==null||ce.close(),(A=m.value)==null||A.dispose()});function Dr(A){const{events:se,newIndex:D}=A.eventBuffer.readEvents(te);if(te=D,se.length===0)return;const{componentsById:Y,singletonsById:H}=h.getResources(A);for(const{entityId:R,eventType:Me,componentId:zt}of se){if(R===h.SINGLETON_ENTITY_ID){if(Me===h.EventType.CHANGED){const it=H.get(zt);it&&$(A,it)}continue}if(Me===h.EventType.ADDED)y.add(R);else if(Me===h.EventType.REMOVED)y.delete(R),v.delete(R);else if(Me===h.EventType.COMPONENT_ADDED){y.add(R);const it=Y.get(zt);it&&K(A,R,it)}else if(Me===h.EventType.COMPONENT_REMOVED){const it=Y.get(zt);it&&K(A,R,it,!0)}else if(Me===h.EventType.CHANGED){const it=Y.get(zt);it&&K(A,R,it)}}}function qn(A){var Y;let se=!1;for(const H of n.added(A)){const R=h.Block.snapshot(A,H),Me=(Y=m.value)==null?void 0:Y.blockDefs[R.tag],zt=(Me==null?void 0:Me.stratum)??"content";C.set(H,d.ref({entityId:H,block:R,stratum:zt,selected:!1,held:null,hovered:!1,edited:!1,opacity:null,connector:null})),se=!0}for(const H of n.removed(A))C.delete(H),se=!0;for(const H of n.changed(A)){const R=C.get(H);if(R){const Me=h.Block.snapshot(A,H);R.value.block.rank!==Me.rank&&(se=!0),R.value.block=Me}}let D=!1;for(const H of c.addedOrChanged(A)){const R=h.User.snapshot(A,H);k.set(R.sessionId,R),D=!0}for(const H of c.removed(A)){const R=h.User.read(A,H);k.delete(R.sessionId),D=!0}D&&(w.value=Array.from(k.values()));for(const H of o.added(A)){const R=C.get(H);R&&!R.value.selected&&(R.value.selected=!0)}for(const H of o.removed(A)){const R=C.get(H);R&&R.value.selected&&(R.value.selected=!1)}for(const H of s.addedOrChanged(A)){const R=C.get(H);R&&(R.value.held=h.Held.snapshot(A,H))}for(const H of s.removed(A)){const R=C.get(H);R&&R.value.held!==null&&(R.value.held=null)}for(const H of i.added(A)){const R=C.get(H);R&&!R.value.hovered&&(R.value.hovered=!0)}for(const H of i.removed(A)){const R=C.get(H);R&&R.value.hovered&&(R.value.hovered=!1)}for(const H of a.added(A)){const R=C.get(H);R&&!R.value.edited&&(R.value.edited=!0)}for(const H of a.removed(A)){const R=C.get(H);R&&R.value.edited&&(R.value.edited=!1)}for(const H of l.addedOrChanged(A)){const R=C.get(H);R&&(R.value.opacity=h.Opacity.snapshot(A,H))}for(const H of l.removed(A)){const R=C.get(H);R&&R.value.opacity!==null&&(R.value.opacity=null)}for(const H of r.addedOrChanged(A)){const R=C.get(H);R&&(R.value.connector=h.Connector.snapshot(A,H))}for(const H of r.removed(A)){const R=C.get(H);R&&R.value.connector!==null&&(R.value.connector=null)}if(se){const H=Array.from(C.values());H.sort((R,Me)=>R.value.block.rank>Me.value.block.rank?1:-1),x.value=H}}M(h.Camera.name,A=>{A&&(I.value=A)});function ja(A){const se=A.rotateZ!==0,D=A.flip[0],Y=A.flip[1];if(!se&&!D&&!Y)return;const H=[];return se&&H.push(`rotate(${A.rotateZ}rad)`),D&&H.push("scaleX(-1)"),Y&&H.push("scaleY(-1)"),H.join(" ")}function xo(A){const{held:se}=A;if(!se||!se.sessionId||se.sessionId===g.sessionId)return null;const D=X(se.sessionId);return(D==null?void 0:D.color)??null}function Gn(A){const{block:se,stratum:D,opacity:Y}=A,H=xo(A),R=Y!==null?Y.value/255:1;return{position:"absolute",left:`${se.position[0]}px`,top:`${se.position[1]}px`,width:`${se.size[0]}px`,height:`${se.size[1]}px`,zIndex:h.STRATUM_ORDER[D]*1e3,transform:ja(se),opacity:R,pointerEvents:"none",userSelect:"none","--wov-held-by-color":H??void 0,transition:R===1?"opacity 0ms 32ms":void 0}}return(A,se)=>(d.openBlock(),d.createElementBlock("div",{ref_key:"containerRef",ref:p,class:"wov-root",style:{position:"relative",width:"100%",height:"100%",overflow:"hidden"}},[t.background?d.renderSlot(A.$slots,"background",{key:0,background:t.background},()=>[d.createVNode(mk,{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(${I.value.zoom}) translate(${-I.value.left}px, ${-I.value.top}px)`,"--wov-zoom":I.value.zoom})},[(d.openBlock(!0),d.createElementBlock(d.Fragment,null,d.renderList(x.value,D=>(d.openBlock(),d.createElementBlock("div",{key:D.value.entityId,"data-entity-id":D.value.entityId,style:d.normalizeStyle(Gn(D.value)),"data-selected":D.value.selected||void 0,"data-held-by-other":xo(D.value)!==null||void 0,"data-hovered":D.value.hovered||void 0,class:"wov-block"},[d.renderSlot(A.$slots,`block:${D.value.block.tag}`,d.mergeProps({ref_for:!0},D.value),()=>[D.value.block.tag==="selection-box"?(d.openBlock(),d.createBlock(ZP,d.mergeProps({key:0,ref_for:!0},D.value),null,16)):D.value.block.tag==="transform-box"?(d.openBlock(),d.createBlock(KP,d.mergeProps({key:1,ref_for:!0},D.value),null,16)):D.value.block.tag==="transform-handle"?(d.openBlock(),d.createBlock(YP,d.mergeProps({key:2,ref_for:!0},D.value),null,16)):D.value.block.tag==="arrow-handle"?(d.openBlock(),d.createBlock(wh,d.mergeProps({key:3,ref_for:!0},D.value),null,16)):D.value.block.tag==="arrow-terminal"?(d.openBlock(),d.createBlock(vh,d.mergeProps({key:4,ref_for:!0},D.value),null,16)):D.value.block.tag==="sticky-note"?(d.openBlock(),d.createBlock(XP,d.mergeProps({key:5,ref_for:!0},D.value),null,16)):D.value.block.tag==="eraser"?(d.openBlock(),d.createBlock(Pp,d.mergeProps({key:6,ref_for:!0},D.value),null,16)):D.value.block.tag==="pen-stroke"?(d.openBlock(),d.createBlock(Up,d.mergeProps({key:7,ref_for:!0},D.value),null,16)):D.value.block.tag==="arc-arrow"?(d.openBlock(),d.createBlock(kh,d.mergeProps({key:8,ref_for:!0},D.value),null,16)):D.value.block.tag==="elbow-arrow"?(d.openBlock(),d.createBlock(bh,d.mergeProps({key:9,ref_for:!0},D.value),null,16)):D.value.block.tag==="text"?(d.openBlock(),d.createBlock(R0,d.mergeProps({key:10,ref_for:!0},D.value),null,16)):D.value.block.tag==="image"?(d.openBlock(),d.createBlock(Rp,d.mergeProps({key:11,ref_for:!0},D.value),null,16)):D.value.block.tag==="shape"?(d.openBlock(),d.createBlock(P0,d.mergeProps({key:12,ref_for:!0},D.value),null,16)):d.createCommentVNode("",!0)])],12,gR))),128))],4),m.value?d.renderSlot(A.$slots,"user-cursors",{key:1,users:w.value,currentSessionId:d.unref(g).sessionId,camera:I.value},()=>[d.createVNode(dR,{users:w.value,"current-session-id":d.unref(g).sessionId,camera:I.value},null,8,["users","current-session-id","camera"])]):d.createCommentVNode("",!0),m.value?(d.openBlock(),d.createBlock(kk,{key:2},{default:d.withCtx(D=>[d.renderSlot(A.$slots,"floating-menu",d.normalizeProps(d.guardReactiveProps(D)))]),_:3})):d.createCommentVNode("",!0),m.value?d.renderSlot(A.$slots,"user-presence",{key:3,users:w.value},()=>[d.createVNode(Bk,{users:w.value},null,8,["users"])]):d.createCommentVNode("",!0),m.value?d.renderSlot(A.$slots,"toolbar",{key:4},()=>[d.createVNode(Nk)]):d.createCommentVNode("",!0),m.value?d.renderSlot(A.$slots,"default",{key:5}):d.createCommentVNode("",!0),d.renderSlot(A.$slots,"offline-indicator",{isOnline:_.value},()=>[d.createVNode(fR,{"is-online":_.value},null,8,["is-online"])]),d.renderSlot(A.$slots,"version-mismatch",{versionMismatch:T.value},()=>[d.createVNode(pR,{"version-mismatch":T.value},null,8,["version-mismatch"])]),d.renderSlot(A.$slots,"back-to-content",{},()=>[d.createVNode(mR)]),d.renderSlot(A.$slots,"loading",{isLoading:N.value},()=>[d.createVNode(wk,{"is-loading":N.value},null,8,["is-loading"])]),m.value?d.renderSlot(A.$slots,"file-drop-zone",{key:6},()=>[d.createVNode(sR)]):d.createCommentVNode("",!0)],512))}});Object.defineProperty(P,"CanvasComponentDef",{enumerable:!0,get:()=>at.CanvasComponentDef}),Object.defineProperty(P,"CanvasSingletonDef",{enumerable:!0,get:()=>at.CanvasSingletonDef}),Object.defineProperty(P,"CanvasStore",{enumerable:!0,get:()=>at.CanvasStore}),Object.defineProperty(P,"Synced",{enumerable:!0,get:()=>at.Synced}),Object.defineProperty(P,"defineCanvasComponent",{enumerable:!0,get:()=>at.defineCanvasComponent}),Object.defineProperty(P,"defineCanvasSingleton",{enumerable:!0,get:()=>at.defineCanvasSingleton}),P.ARROW_HEADS=Zl,P.ArcArrow=kh,P.ArcArrowTool=uP,P.ArrowHandle=wh,P.ArrowHead=sn,P.ArrowHeadButton=Ld,P.ArrowTerminal=vh,P.ArrowThicknessButton=ok,P.CURSORS=vk,P.CanvasBackground=mk,P.ColorButton=ak,P.ColorPicker=ik,P.CursorKind=Ir,P.EditableText=wa,P.EditingPlugin=Hk,P.ElbowArrow=bh,P.ElbowArrowTool=Mk,P.Eraser=Pp,P.EraserTool=_k,P.FloatingMenu=kk,P.FloatingMenuBar=yk,P.HandTool=Sk,P.IconChevronDown=St,P.ImageBlock=Rp,P.ImageTool=Ak,P.LoadingOverlay=wk,P.MenuButton=Co,P.MenuDropdown=bt,P.MenuTooltip=Fd,P.PenStroke=Up,P.PenStrokeThicknessButton=lk,P.PenTool=Ek,P.SHAPES=ss,P.SelectTool=bk,P.ShapeBlock=P0,P.ShapeFillColorButton=ck,P.ShapeKindButton=dk,P.ShapeStrokeColorButton=uk,P.ShapeTool=xk,P.StickyNoteTool=Ck,P.TextAlignmentButton=jd,P.TextBlock=R0,P.TextBoldButton=Hd,P.TextColorButton=qd,P.TextFontFamilyButton=Zd,P.TextFontSizeButton=Ud,P.TextItalicButton=Kd,P.TextTool=Tk,P.TextUnderlineButton=Jd,P.Toolbar=Nk,P.ToolbarButton=Qt,P.UserPresence=Bk,P.WovenCanvas=yR,P.computeCommonComponents=gk,P.createTooltipContext=I0,P.getArrowHead=no,P.useComponent=Pe,P.useComponents=Wn,P.useEditorContext=Ee,P.useFonts=hk,P.useQuery=_0,P.useSingleton=Ze,P.useTextBatchController=O0,P.useTextEditorController=Bs,P.useTextFormatting=qt,P.useTextStretchBehavior=Bd,P.useToolbar=Od,P.useTooltipSingleton=Un,Object.defineProperty(P,Symbol.toStringTag,{value:"Module"})});