tutuca 0.9.113 → 0.9.114

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.
@@ -1,3 +1,3 @@
1
- function invariant(condition,error){if(!condition)throw Error(error)}function assertNotInfinite(size){invariant(size!==1/0,"Cannot perform this action with an infinite size.")}function reduce(collection,reducer,reduction,context,useFirst,reverse){return assertNotInfinite(collection.size),collection.__iterate((v,k,c)=>{if(useFirst)useFirst=!1,reduction=v;else reduction=reducer.call(context,reduction,v,k,c)},reverse),reduction}var keyMapper=(v,k)=>k,entryMapper=(v,k)=>[k,v],not=(predicate)=>function(...args){return!predicate.apply(this,args)},neg=(predicate)=>function(...args){return-predicate.apply(this,args)};function defaultComparator(a,b){if(a===void 0&&b===void 0)return 0;if(a===void 0)return 1;if(b===void 0)return-1;return a>b?1:a<b?-1:0}var defaultNegComparator=(a,b)=>a<b?1:a>b?-1:0,DONE={done:!0,value:void 0};class Iter{constructor(next){this.next=next}[Symbol.iterator](){return this}}function makeIterator(next){return new Iter(next)}function makeEntryIterator(next){let entry=[void 0,void 0],result={done:!1,value:void 0};return makeIterator(()=>{if(next(entry))return result.value=[entry[0],entry[1]],result;return DONE})}var EMPTY_ITERATOR=makeIterator(()=>DONE),emptyIterator=()=>EMPTY_ITERATOR;function makeIndexKeys(size){let i=0,result={done:!1,value:void 0};return makeIterator(()=>{if(i===size)return DONE;return result.value=i++,result})}function mapEntries(source,transform){return makeEntryIterator((entry)=>{let step=source.next();if(step.done)return!1;return transform(step.value[0],step.value[1],entry),!0})}function hasIterator(maybeIterable){if(Array.isArray(maybeIterable))return!0;return!!getIteratorFn(maybeIterable)}var isIterator=(maybeIterator)=>typeof maybeIterator?.next==="function";function getIterator(iterable){return getIteratorFn(iterable)?.call(iterable)}function getIteratorFn(iterable){let iteratorFn=iterable?.[Symbol.iterator];if(typeof iteratorFn==="function")return iteratorFn}function isEntriesIterable(maybeIterable){let iteratorFn=getIteratorFn(maybeIterable);return iteratorFn&&iteratorFn===maybeIterable.entries}function isKeysIterable(maybeIterable){let iteratorFn=getIteratorFn(maybeIterable);return iteratorFn&&iteratorFn===maybeIterable.keys}var DELETE="delete",SHIFT=5,SIZE=1<<SHIFT,MASK=SIZE-1,NOT_SET={},MakeRef=()=>({value:!1});function SetRef(ref){if(ref)ref.value=!0}class OwnerID{}function ensureSize(iter){if(iter.size===void 0)iter.size=iter.__iterate(returnTrue);return iter.size}function wrapIndex(iter,index){if(typeof index!=="number"){let uint32Index=index>>>0;if(String(uint32Index)!==index||uint32Index===4294967295)return NaN;index=uint32Index}return index<0?ensureSize(iter)+index:index}var returnTrue=()=>!0,isNeg=(value)=>value<0||Object.is(value,-0),wholeSlice=(begin,end,size)=>(begin===0&&!isNeg(begin)||size!==void 0&&(begin??0)<=-size)&&(end===void 0||size!==void 0&&end>=size),resolveIndex=(index,size,defaultIndex)=>index===void 0?defaultIndex:isNeg(index)?size===1/0?size:Math.max(0,size+index)|0:size===void 0||size===index?index:Math.min(size,index)|0,resolveBegin=(begin,size)=>resolveIndex(begin,size,0),resolveEnd=(end,size)=>resolveIndex(end,size,size),IS_COLLECTION_SYMBOL="@@__IMMUTABLE_ITERABLE__@@",IS_KEYED_SYMBOL="@@__IMMUTABLE_KEYED__@@",IS_INDEXED_SYMBOL="@@__IMMUTABLE_INDEXED__@@",IS_ORDERED_SYMBOL="@@__IMMUTABLE_ORDERED__@@",IS_SEQ_SYMBOL="@@__IMMUTABLE_SEQ__@@",IS_LIST_SYMBOL="@@__IMMUTABLE_LIST__@@",IS_MAP_SYMBOL="@@__IMMUTABLE_MAP__@@",IS_SET_SYMBOL="@@__IMMUTABLE_SET__@@",IS_STACK_SYMBOL="@@__IMMUTABLE_STACK__@@",IS_RECORD_SYMBOL="@@__IMMUTABLE_RECORD__@@";function hasSymbol(v,symbol){return typeof v==="object"&&v!==null&&symbol in v}var isCollection=(v)=>hasSymbol(v,IS_COLLECTION_SYMBOL),isKeyed=(v)=>hasSymbol(v,IS_KEYED_SYMBOL),isIndexed=(v)=>hasSymbol(v,IS_INDEXED_SYMBOL),isAssociative=(v)=>isKeyed(v)||isIndexed(v),isOrdered=(v)=>hasSymbol(v,IS_ORDERED_SYMBOL),isSeq=(v)=>hasSymbol(v,IS_SEQ_SYMBOL),isList=(v)=>hasSymbol(v,IS_LIST_SYMBOL),isMap=(v)=>hasSymbol(v,IS_MAP_SYMBOL),isSet=(v)=>hasSymbol(v,IS_SET_SYMBOL),isStack=(v)=>hasSymbol(v,IS_STACK_SYMBOL),isRecord=(v)=>hasSymbol(v,IS_RECORD_SYMBOL),isImmutable=(v)=>isCollection(v)||isRecord(v),isOrderedMap=(v)=>isMap(v)&&isOrdered(v),isOrderedSet=(v)=>isSet(v)&&isOrdered(v),isValueObject=(v)=>typeof v==="object"&&v!==null&&typeof v.equals==="function"&&typeof v.hashCode==="function";function flipFactory(collection){let flipSequence=makeSequence(collection);return flipSequence._iter=collection,flipSequence.size=collection.size,flipSequence.flip=()=>collection,flipSequence.reverse=function(){let reversedSequence=collection.reverse.call(this);return reversedSequence.flip=()=>collection.reverse(),reversedSequence},flipSequence.has=(key)=>collection.includes(key),flipSequence.includes=(key)=>collection.has(key),flipSequence.cacheResult=cacheResultThrough,flipSequence.__iterate=function(fn,reverse){return collection.__iterate((v,k)=>fn(k,v,this),reverse)},flipSequence.__iteratorUncached=(reverse)=>mapEntries(collection.__iterator(reverse),(k,v,entry)=>{entry[0]=v,entry[1]=k}),flipSequence}function mapFactory(collection,mapper,context){let mappedSequence=makeSequence(collection);return mappedSequence.size=collection.size,mappedSequence.has=(key)=>collection.has(key),mappedSequence.get=(key,notSetValue)=>{let v=collection.get(key,NOT_SET);return v===NOT_SET?notSetValue:mapper.call(context,v,key,collection)},mappedSequence.__iterate=function(fn,reverse){return collection.__iterate((v,k)=>fn(mapper.call(context,v,k,collection),k,this),reverse)},mappedSequence.__iteratorUncached=(reverse)=>mapEntries(collection.__iterator(reverse),(k,v,entry)=>{entry[0]=k,entry[1]=mapper.call(context,v,k,collection)}),mappedSequence}function reverseFactory(collection,useKeys){let reversedSequence=makeSequence(collection);if(reversedSequence._iter=collection,reversedSequence.size=collection.size,reversedSequence.reverse=()=>collection,collection.flip)reversedSequence.flip=function(){let flipSequence=flipFactory(collection);return flipSequence.reverse=()=>collection.flip(),flipSequence};return reversedSequence.get=(key,notSetValue)=>collection.get(useKeys?key:-1-key,notSetValue),reversedSequence.has=(key)=>collection.has(useKeys?key:-1-key),reversedSequence.includes=(value)=>collection.includes(value),reversedSequence.cacheResult=cacheResultThrough,reversedSequence.__iterate=function(fn,reverse){let i=0;if(reverse)ensureSize(collection);return collection.__iterate((v,k)=>fn(v,useKeys?k:reverse?this.size-++i:i++,this),!reverse)},reversedSequence.__iteratorUncached=function(reverse){let i=0;if(reverse)ensureSize(collection);let size=this.size;return mapEntries(collection.__iterator(!reverse),(k,v,entry)=>{entry[0]=useKeys?k:reverse?size-++i:i++,entry[1]=v})},reversedSequence}function sliceFactory(collection,begin,end,useKeys){let originalSize=collection.size;if(wholeSlice(begin,end,originalSize))return collection;if(originalSize===void 0&&(begin<0||end<0))return sliceFactory(collection.toSeq().cacheResult(),begin,end,useKeys);let resolvedBegin=resolveBegin(begin,originalSize),resolvedSize=resolveEnd(end,originalSize)-resolvedBegin,sliceSize;if(!Number.isNaN(resolvedSize))sliceSize=Math.max(0,resolvedSize);let sliceSeq=makeSequence(collection);if(sliceSeq.size=sliceSize===0?sliceSize:collection.size&&sliceSize||void 0,!useKeys&&isSeq(collection)&&sliceSize>=0)sliceSeq.get=function(index,notSetValue){return index=wrapIndex(this,index),index>=0&&index<sliceSize?collection.get(index+resolvedBegin,notSetValue):notSetValue};return sliceSeq.__iterateUncached=function(fn,reverse){if(sliceSize!==0&&reverse)return this.cacheResult().__iterate(fn,reverse);if(sliceSize===0)return 0;let skipped=0,iterations=0;return collection.__iterate((v,k)=>{if(skipped<resolvedBegin){skipped++;return}if(sliceSize!==void 0&&iterations>=sliceSize)return!1;if(iterations++,fn(v,useKeys?k:iterations-1,this)===!1)return!1},reverse),iterations},sliceSeq.__iteratorUncached=function(reverse){if(sliceSize!==0&&reverse)return this.cacheResult().__iterator(reverse);if(sliceSize===0)return emptyIterator();let iterator=collection.__iterator(reverse),skipped=0,iterations=0;if(useKeys)return makeIterator(()=>{while(skipped<resolvedBegin)skipped++,iterator.next();if(sliceSize!==void 0&&iterations>=sliceSize)return DONE;let step=iterator.next();if(step.done)return step;return iterations++,step});return makeEntryIterator((entry)=>{while(skipped<resolvedBegin)skipped++,iterator.next();if(sliceSize!==void 0&&iterations>=sliceSize)return!1;let step=iterator.next();if(step.done)return!1;return iterations++,entry[0]=iterations-1,entry[1]=step.value[1],!0})},sliceSeq}function sortFactory(collection,comparator,mapper){if(!comparator)comparator=defaultComparator;let isKeyedCollection=isKeyed(collection),index=0,entries=collection.toSeq().map((v,k)=>[k,v,index++,mapper?mapper(v,k,collection):v]).valueSeq().toArray();return entries.sort((a,b)=>comparator(a[3],b[3])||a[2]-b[2]).forEach(isKeyedCollection?(v,i)=>{entries[i].length=2}:(v,i)=>{entries[i]=v[1]}),isKeyedCollection?KeyedSeq(entries):isIndexed(collection)?IndexedSeq(entries):SetSeq(entries)}function maxFactory(collection,comparator,mapper){if(!comparator)comparator=defaultComparator;if(mapper)return collection.toSeq().map((v,k)=>[v,mapper(v,k,collection)]).reduce((a,b)=>maxCompare(comparator,a[1],b[1])?b:a)?.[0];return collection.reduce((a,b)=>maxCompare(comparator,a,b)?b:a)}function maxCompare(comparator,a,b){let comp=comparator(b,a);return comp===0&&b!==a&&(b===void 0||b===null||Number.isNaN(b))||comp>0}function zipWithFactory(keyIter,zipper,iters,zipAll){let zipSequence=makeSequence(keyIter),sizes=new ArraySeq(iters).map((i)=>i.size);return zipSequence.size=zipAll?sizes.max():sizes.min(),zipSequence.__iterate=function(fn,reverse){let iterator=this.__iterator(reverse),iterations=0,step;while(!(step=iterator.next()).done)if(fn(step.value[1],iterations++,this)===!1)break;return iterations},zipSequence.__iteratorUncached=function(reverse){let iterators=iters.map((i)=>{let col=Collection(i);return getIterator(reverse?col.reverse():col)}),iterations=0,steps=Array(iterators.length),values=Array(iterators.length);return makeEntryIterator((entry)=>{let done=zipAll;for(let i=0;i<iterators.length;i++)steps[i]=iterators[i].next(),done=zipAll?done&&steps[i].done:done||steps[i].done;if(done)return!1;for(let i=0;i<steps.length;i++)values[i]=steps[i].value;return entry[0]=iterations++,entry[1]=zipper(...values),!0})},zipSequence}function isArrayLike(value){if(Array.isArray(value)||typeof value==="string")return!0;return value&&typeof value==="object"&&Number.isInteger(value.length)&&value.length>=0&&(value.length===0?Object.keys(value).length===1:Object.hasOwn(value,value.length-1))}function isPlainObject(value){if(!value||typeof value!=="object"||Object.prototype.toString.call(value)!=="[object Object]")return!1;let proto=Object.getPrototypeOf(value);if(proto===null)return!0;let parentProto=proto,nextProto=Object.getPrototypeOf(proto);while(nextProto!==null)parentProto=nextProto,nextProto=Object.getPrototypeOf(parentProto);return parentProto===proto}var isDataStructure=(value)=>typeof value==="object"&&(isImmutable(value)||Array.isArray(value)||isPlainObject(value));function coerceKeyPath(keyPath){if(isArrayLike(keyPath)&&typeof keyPath!=="string")return keyPath;if(isOrdered(keyPath))return keyPath.toArray();throw TypeError(`Invalid keyPath: expected Ordered Collection or Array: ${keyPath}`)}var has=(collection,key)=>isImmutable(collection)?collection.has(key):isDataStructure(collection)&&Object.hasOwn(collection,key);function get(collection,key,notSetValue){return isImmutable(collection)?collection.get(key,notSetValue):!has(collection,key)?notSetValue:typeof collection.get==="function"?collection.get(key):collection[key]}function getIn$1(collection,searchKeyPath,notSetValue){let keyPath=coerceKeyPath(searchKeyPath),i=0;while(i!==keyPath.length)if(collection=get(collection,keyPath[i++],NOT_SET),collection===NOT_SET)return notSetValue;return collection}var hasIn$1=(collection,keyPath)=>getIn$1(collection,keyPath,NOT_SET)!==NOT_SET;function is(valueA,valueB){if(valueA===valueB||Number.isNaN(valueA)&&Number.isNaN(valueB))return!0;if(!valueA||!valueB)return!1;if(typeof valueA.valueOf==="function"&&typeof valueB.valueOf==="function"){if(valueA=valueA.valueOf(),valueB=valueB.valueOf(),valueA===valueB||Number.isNaN(valueA)&&Number.isNaN(valueB))return!0;if(!valueA||!valueB)return!1}return!!(isValueObject(valueA)&&isValueObject(valueB)&&valueA.equals(valueB))}function toJS(value){if(!value||typeof value!=="object")return value;if(!isCollection(value)){if(!isDataStructure(value))return value;value=Seq(value)}if(isKeyed(value)){let result2={};return value.__iterate((v,k)=>{result2[String(k)]=toJS(v)}),result2}let result=[];return value.__iterate((v)=>{result.push(toJS(v))}),result}function deepEqual(a,b){if(a===b)return!0;if(!isCollection(b)||a.size!==void 0&&b.size!==void 0&&a.size!==b.size||a.__hash!==void 0&&b.__hash!==void 0&&a.__hash!==b.__hash||isKeyed(a)!==isKeyed(b)||isIndexed(a)!==isIndexed(b)||isOrdered(a)!==isOrdered(b))return!1;if(a.size===0&&b.size===0)return!0;let notAssociative=!isAssociative(a);if(isOrdered(a)){let entries=a.entries();return!!(b.every((v,k)=>{let entry=entries.next().value;return entry&&is(entry[1],v)&&(notAssociative||is(entry[0],k))})&&entries.next().done)}let flipped=!1;if(a.size===void 0)if(b.size===void 0){if(typeof a.cacheResult==="function")a.cacheResult()}else{flipped=!0;let _=a;a=b,b=_}let allEqual=!0,bSize=b.__iterate((v,k)=>{if(notAssociative?!a.has(v):flipped?!is(v,a.get(k,NOT_SET)):!is(a.get(k,NOT_SET),v))return allEqual=!1,!1;return!0});return allEqual&&a.size===bSize}var smi=(i32)=>i32>>>1&1073741824|i32&3221225471;function hash(o){if(o===null||o===void 0)return hashNullish(o);if(typeof o.hashCode==="function")return smi(o.hashCode(o));let v=valueOf(o);if(v===null||v===void 0)return hashNullish(v);switch(typeof v){case"boolean":return v?1108378657:1108378656;case"number":return hashNumber(v);case"string":return v.length>STRING_HASH_CACHE_MIN_STRLEN?cachedHashString(v):hashString(v);case"object":case"function":return hashJSObj(v);case"symbol":return hashSymbol(v);default:if(typeof v.toString==="function")return hashString(v.toString());throw Error(`Value type ${typeof v} cannot be hashed.`)}}var hashNullish=(nullish)=>nullish===null?1108378658:1108378659;function hashNumber(n){if(Number.isNaN(n)||n===1/0)return 0;let hash2=n|0;if(hash2!==n)hash2^=n*4294967295;while(n>4294967295)n/=4294967295,hash2^=n;return smi(hash2)}function cachedHashString(string){let hashed=stringHashCache[string];if(hashed===void 0){if(hashed=hashString(string),STRING_HASH_CACHE_SIZE===STRING_HASH_CACHE_MAX_SIZE)STRING_HASH_CACHE_SIZE=0,stringHashCache={};STRING_HASH_CACHE_SIZE++,stringHashCache[string]=hashed}return hashed}function hashString(string){let hashed=0;for(let ii=0;ii<string.length;ii++)hashed=31*hashed+string.charCodeAt(ii)|0;return smi(hashed)}function hashSymbol(sym){let hashed=symbolMap[sym];if(hashed!==void 0)return hashed;return hashed=nextHash(),symbolMap[sym]=hashed,hashed}function hashJSObj(obj){let hashed=weakMap.get(obj);if(hashed!==void 0)return hashed;return hashed=nextHash(),weakMap.set(obj,hashed),hashed}var valueOf=(obj)=>obj.valueOf!==Object.prototype.valueOf?obj.valueOf():obj;function nextHash(){let nextHash2=++_objHashUID;if(_objHashUID&1073741824)_objHashUID=0;return nextHash2}var weakMap=new WeakMap,symbolMap=Object.create(null),_objHashUID=0,STRING_HASH_CACHE_MIN_STRLEN=16,STRING_HASH_CACHE_MAX_SIZE=255,STRING_HASH_CACHE_SIZE=0,stringHashCache={};function hashCollection(collection){if(collection.size===1/0)return 0;let ordered=isOrdered(collection),keyed=isKeyed(collection),h=ordered?1:0;return collection.__iterate(keyed?ordered?(v,k)=>{h=31*h+hashMerge(hash(v),hash(k))|0}:(v,k)=>{h=h+hashMerge(hash(v),hash(k))|0}:ordered?(v)=>{h=31*h+hash(v)|0}:(v)=>{h=h+hash(v)|0}),murmurHashOfSize(collection.size,h)}var hashMerge=(a,b)=>a^b+2654435769+(a<<6)+(a>>2)|0;function murmurHashOfSize(size,h){return h=Math.imul(h,3432918353),h=Math.imul(h<<15|h>>>-15,461845907),h=Math.imul(h<<13|h>>>-13,5),h=(h+3864292196|0)^size,h=Math.imul(h^h>>>16,2246822507),h=Math.imul(h^h>>>13,3266489909),h=smi(h^h>>>16),h}function quoteString(value){try{return typeof value==="string"?JSON.stringify(value):String(value)}catch{return JSON.stringify(value)}}var reify=(iter,seq)=>iter===seq?iter:isSeq(iter)?seq:iter.create?iter.create(seq):iter.constructor(seq),reifyValues=(collection,arr)=>reify(collection,(isKeyed(collection)?KeyedCollection:isIndexed(collection)?IndexedCollection:SetCollection)(arr)),defaultZipper=(...values)=>values,Collection=(value)=>isCollection(value)?value:Seq(value);class CollectionImpl{size=0;static{this.prototype[IS_COLLECTION_SYMBOL]=!0,this.prototype.__toStringMapper=quoteString,this.prototype[Symbol.iterator]=this.prototype.values,this.prototype.toJSON=this.prototype.toArray,this.prototype.contains=this.prototype.includes}equals(other){return deepEqual(this,other)}hashCode(){return this.__hash??(this.__hash=hashCollection(this))}toArray(){assertNotInfinite(this.size);let array=Array(this.size||0),useTuples=isKeyed(this),i=0;return this.__iterate((v,k)=>{array[i++]=useTuples?[k,v]:v}),array}toIndexedSeq(){return new ToIndexedSequence(this)}toJS(){return toJS(this)}toKeyedSeq(){return new ToKeyedSequence(this,!0)}toMap(){throw Error("toMap: not patched — import CollectionConversions")}toObject(){assertNotInfinite(this.size);let object={};return this.__iterate((v,k)=>{object[k]=v}),object}toOrderedMap(){throw Error("toOrderedMap: not patched — import CollectionConversions")}toOrderedSet(){throw Error("toOrderedSet: not patched — import CollectionConversions")}toSet(){throw Error("toSet: not patched — import CollectionConversions")}toSetSeq(){return new ToSetSequence(this)}toSeq(){return isIndexed(this)?this.toIndexedSeq():isKeyed(this)?this.toKeyedSeq():this.toSetSeq()}toStack(){throw Error("toStack: not patched — import CollectionConversions")}toList(){throw Error("toList: not patched — import CollectionConversions")}toString(){return"[Collection]"}__toString(head,tail){if(this.size===0)return`${head}${tail}`;return`${head} ${this.toSeq().map(this.__toStringMapper).join(", ")} ${tail}`}concat(...values){let isKeyedCollection=isKeyed(this),iters=[this,...values].map((v)=>{if(!isCollection(v))v=isKeyedCollection?keyedSeqFromValue(v):indexedSeqFromValue(Array.isArray(v)?v:[v]);else if(isKeyedCollection)v=KeyedCollection(v);return v}).filter((v)=>v.size!==0);if(iters.length===0)return this;if(iters.length===1){let singleton=iters[0];if(singleton===this||isKeyedCollection&&isKeyed(singleton)||isIndexed(this)&&isIndexed(singleton))return singleton}return reify(this,new ConcatSeq(iters))}includes(searchValue){return this.some((value)=>is(value,searchValue))}every(predicate,context){assertNotInfinite(this.size);let returnValue=!0;return this.__iterate((v,k,c)=>{if(!predicate.call(context,v,k,c))return returnValue=!1,!1}),returnValue}entries(){return this.__iterator()}filter(predicate,context){let collection=this,useKeys=isKeyed(this),filterSequence=makeSequence(collection);if(useKeys)filterSequence.has=(key)=>{let v=collection.get(key,NOT_SET);return v!==NOT_SET&&!!predicate.call(context,v,key,collection)},filterSequence.get=(key,notSetValue)=>{let v=collection.get(key,NOT_SET);return v!==NOT_SET&&predicate.call(context,v,key,collection)?v:notSetValue};return filterSequence.__iterateUncached=function(fn,reverse){let iterations=0;return collection.__iterate((v,k)=>{if(predicate.call(context,v,k,collection))return iterations++,fn(v,useKeys?k:iterations-1,this)},reverse),iterations},filterSequence.__iteratorUncached=function(reverse){let iterator=collection.__iterator(reverse),iterations=0;return makeEntryIterator((entry)=>{while(!0){let step=iterator.next();if(step.done)return!1;let k=step.value[0],v=step.value[1];if(predicate.call(context,v,k,collection))return entry[0]=useKeys?k:iterations++,entry[1]=v,!0}})},reify(this,filterSequence)}partition(predicate,context){let isKeyedIter=isKeyed(this),groups=[[],[]];return this.__iterate((v,k)=>{groups[predicate.call(context,v,k,this)?1:0].push(isKeyedIter?[k,v]:v)}),groups.map((arr)=>reifyValues(this,arr))}find(predicate,context,notSetValue){let entry=this.findEntry(predicate,context);return entry?entry[1]:notSetValue}forEach(sideEffect,context){return assertNotInfinite(this.size),this.__iterate(context?sideEffect.bind(context):sideEffect)}join(separator){assertNotInfinite(this.size),separator=separator!==void 0?String(separator):",";let joined="",isFirst=!0;return this.__iterate((v)=>{if(isFirst)isFirst=!1;else joined+=separator;joined+=v!==null&&v!==void 0?String(v):""}),joined}keys(){let iterator=this.__iterator(),result={done:!1,value:void 0};return makeIterator(()=>{let step=iterator.next();if(step.done)return DONE;return result.value=step.value[0],result})}map(mapper,context){return reify(this,mapFactory(this,mapper,context))}reduce(reducer,initialReduction=NOT_SET,context){return reduce(this,reducer,initialReduction,context,initialReduction===NOT_SET,!1)}reduceRight(reducer,initialReduction=NOT_SET,context){return reduce(this,reducer,initialReduction,context,initialReduction===NOT_SET,!0)}reverse(){return reify(this,reverseFactory(this,isKeyed(this)))}slice(begin,end){return reify(this,sliceFactory(this,begin,end,isKeyed(this)))}some(predicate,context){assertNotInfinite(this.size);let returnValue=!1;return this.__iterate((v,k,c)=>{if(predicate.call(context,v,k,c))return returnValue=!0,!1}),returnValue}sort(comparator){return reify(this,sortFactory(this,comparator))}values(){let iterator=this.__iterator(),result={done:!1,value:void 0};return makeIterator(()=>{let step=iterator.next();if(step.done)return DONE;return result.value=step.value[1],result})}butLast(){return this.slice(0,-1)}isEmpty(){return this.size!==void 0?this.size===0:!this.some(()=>!0)}count(predicate,context){return ensureSize(predicate?this.toSeq().filter(predicate,context):this)}countBy(_grouper,_context){throw Error("countBy: not patched — import CollectionConversions")}entrySeq(){let collection=this;if(collection._cache)return new ArraySeq(collection._cache);let entriesSequence=collection.toSeq().map(entryMapper).toIndexedSeq();return entriesSequence.fromEntrySeq=()=>collection.toSeq(),entriesSequence}filterNot(predicate,context){return this.filter(not(predicate),context)}findEntry(predicate,context,notSetValue){let found=notSetValue;return this.__iterate((v,k,c)=>{if(predicate.call(context,v,k,c))return found=[k,v],!1}),found}findKey(predicate,context){return this.findEntry(predicate,context)?.[0]}findLast(predicate,context,notSetValue){return this.toKeyedSeq().reverse().find(predicate,context,notSetValue)}findLastEntry(predicate,context,notSetValue){return this.toKeyedSeq().reverse().findEntry(predicate,context,notSetValue)}findLastKey(predicate,context){return this.toKeyedSeq().reverse().findKey(predicate,context)}first(notSetValue){return this.find(returnTrue,null,notSetValue)}flatMap(mapper,context){return reify(this,this.toSeq().map((v,k)=>(isKeyed(this)?KeyedCollection:isIndexed(this)?IndexedCollection:SetCollection)(mapper.call(context,v,k,this))).flatten(!0))}flatten(depth){let collection=this,useKeys=isKeyed(this),flatSequence=makeSequence(collection);return flatSequence.__iterateUncached=function(fn,reverse){if(reverse)return this.cacheResult().__iterate(fn,reverse);let iterations=0,stopped=!1;function flatDeep(iter,currentDepth){iter.__iterate((v,k)=>{if((!depth||currentDepth<depth)&&isCollection(v))flatDeep(v,currentDepth+1);else if(iterations++,fn(v,useKeys?k:iterations-1,flatSequence)===!1)stopped=!0;if(stopped)return!1},reverse)}return flatDeep(collection,0),iterations},flatSequence.__iteratorUncached=function(reverse){if(reverse)return this.cacheResult().__iterator(reverse);let iterations=0,stack=[{iterator:collection.__iterator(reverse),depth:0}];return makeEntryIterator((entry)=>{while(stack.length>0){let frame=stack[stack.length-1],step=frame.iterator.next();if(step.done){stack.pop();continue}let v=step.value[1];if((!depth||frame.depth<depth)&&isCollection(v)){stack.push({iterator:v.__iterator(reverse),depth:frame.depth+1});continue}return entry[0]=useKeys?step.value[0]:iterations++,entry[1]=v,!0}return!1})},reify(this,flatSequence)}fromEntrySeq(){return new FromEntriesSequence(this)}get(searchKey,notSetValue){return this.find((_,key)=>is(key,searchKey),void 0,notSetValue)}getIn(searchKeyPath,notSetValue){return getIn$1(this,searchKeyPath,notSetValue)}groupBy(_grouper,_context){throw Error("groupBy: not patched — import CollectionConversions")}has(searchKey){return this.get(searchKey,NOT_SET)!==NOT_SET}hasIn(searchKeyPath){return hasIn$1(this,searchKeyPath)}isSubset(iter){let other=typeof iter.includes==="function"?iter:Collection(iter);return this.every((value)=>other.includes(value))}isSuperset(iter){return(typeof iter.isSubset==="function"?iter:Collection(iter)).isSubset(this)}keyOf(searchValue){return this.findKey((value)=>is(value,searchValue))}keySeq(){return this.toSeq().map(keyMapper).toIndexedSeq()}last(notSetValue){return this.toSeq().reverse().first(notSetValue)}lastKeyOf(searchValue){return this.toKeyedSeq().reverse().keyOf(searchValue)}max(comparator){return maxFactory(this,comparator)}maxBy(mapper,comparator){return maxFactory(this,comparator,mapper)}min(comparator){return maxFactory(this,comparator?neg(comparator):defaultNegComparator)}minBy(mapper,comparator){return maxFactory(this,comparator?neg(comparator):defaultNegComparator,mapper)}rest(){return this.slice(1)}skip(amount){return amount===0?this:this.slice(Math.max(0,amount))}skipLast(amount){return amount===0?this:this.slice(0,-Math.max(0,amount))}skipWhile(predicate,context){let collection=this,useKeys=isKeyed(this),skipSequence=makeSequence(collection);return skipSequence.__iterateUncached=function(fn,reverse){if(reverse)return this.cacheResult().__iterate(fn,reverse);let skipping=!0,iterations=0;return collection.__iterate((v,k)=>{if(skipping&&predicate.call(context,v,k,this))return;return skipping=!1,iterations++,fn(v,useKeys?k:iterations-1,this)},reverse),iterations},skipSequence.__iteratorUncached=function(reverse){if(reverse)return this.cacheResult().__iterator(reverse);let iterator=collection.__iterator(reverse),iterations=0,seq=this,skipping=!0;return makeEntryIterator((entry)=>{while(!0){let step=iterator.next();if(step.done)return!1;let k=step.value[0],v=step.value[1];if(skipping&&predicate.call(context,v,k,seq))continue;return skipping=!1,entry[0]=useKeys?k:iterations++,entry[1]=v,!0}})},reify(this,skipSequence)}skipUntil(predicate,context){return this.skipWhile(not(predicate),context)}sortBy(mapper,comparator){return reify(this,sortFactory(this,comparator,mapper))}take(amount){return this.slice(0,Math.max(0,amount))}takeLast(amount){return this.slice(-Math.max(0,amount))}takeWhile(predicate,context){let collection=this,takeSequence=makeSequence(collection);return takeSequence.__iterateUncached=function(fn,reverse){if(reverse)return this.cacheResult().__iterate(fn,reverse);let iterations=0;return collection.__iterate((v,k)=>{if(!predicate.call(context,v,k,this))return!1;return iterations++,fn(v,k,this)},reverse),iterations},takeSequence.__iteratorUncached=function(reverse){if(reverse)return this.cacheResult().__iterator(reverse);let iterator=collection.__iterator(reverse),seq=this,finished=!1;return makeIterator(()=>{if(finished)return DONE;let step=iterator.next();if(step.done)return step;if(!predicate.call(context,step.value[1],step.value[0],seq))return finished=!0,DONE;return step})},reify(this,takeSequence)}takeUntil(predicate,context){return this.takeWhile(not(predicate),context)}update(fn){return fn(this)}valueSeq(){return this.toIndexedSeq()}__iterate(fn,reverse=!1){let iterator=this.__iterator(reverse),iterations=0,step;while(!(step=iterator.next()).done)if(iterations++,fn(step.value[1],step.value[0],this)===!1)break;return iterations}__iterator(_reverse=!1){throw Error("CollectionImpl does not implement __iterator. Use a subclass instead.")}}var KeyedCollection=(value)=>isKeyed(value)?value:KeyedSeq(value);class KeyedCollectionImpl extends CollectionImpl{static{this.prototype[IS_KEYED_SYMBOL]=!0,this.prototype.__toStringMapper=(v,k)=>`${quoteString(k)}: ${quoteString(v)}`,this.prototype[Symbol.iterator]=CollectionImpl.prototype.entries,this.prototype.toJSON=function(){assertNotInfinite(this.size);let object={};return this.__iterate((v,k)=>{object[k]=v}),object}}flip(){return reify(this,flipFactory(this))}mapEntries(mapper,context){let iterations=0;return reify(this,this.toSeq().map((v,k)=>mapper.call(context,[k,v],iterations++,this)).fromEntrySeq())}mapKeys(mapper,context){return reify(this,this.toSeq().flip().map((k,v)=>mapper.call(context,k,v,this)).flip())}}var IndexedCollection=(value)=>isIndexed(value)?value:IndexedSeq(value);class IndexedCollectionImpl extends CollectionImpl{static{this.prototype[IS_INDEXED_SYMBOL]=!0,this.prototype[IS_ORDERED_SYMBOL]=!0}toKeyedSeq(){return new ToKeyedSequence(this,!1)}findIndex(predicate,context){let entry=this.findEntry(predicate,context);return entry?entry[0]:-1}indexOf(searchValue){let key=this.keyOf(searchValue);return key===void 0?-1:key}lastIndexOf(searchValue){let key=this.lastKeyOf(searchValue);return key===void 0?-1:key}splice(index,removeNum=NOT_SET,...values){if(index===void 0)return this;let hasRemoveNum=removeNum!==NOT_SET;if(removeNum=hasRemoveNum?Math.max(removeNum||0,0):0,hasRemoveNum&&!removeNum&&values.length===0)return this;index=resolveBegin(index,index<0?this.count():this.size);let spliced=this.slice(0,index);return reify(this,!hasRemoveNum?spliced:spliced.concat(values,this.slice(index+removeNum)))}findLastIndex(predicate,context){let entry=this.findLastEntry(predicate,context);return entry?entry[0]:-1}first(notSetValue){return this.get(0,notSetValue)}get(index,notSetValue){return index=wrapIndex(this,index),index<0||this.size===1/0||this.size!==void 0&&index>this.size?notSetValue:this.find((_,key)=>key===index,void 0,notSetValue)}has(index){return index=wrapIndex(this,index),index>=0&&(this.size!==void 0?this.size===1/0||index<this.size:this.indexOf(index)!==-1)}interpose(separator){let collection=this,interposedSequence=makeSequence(collection);return interposedSequence.size=collection.size&&collection.size*2-1,interposedSequence.__iterateUncached=function(fn,reverse){let iterations=0,isFirst=!0;return collection.__iterate((v)=>{if(!isFirst){if(fn(separator,iterations++,this)===!1)return!1}return isFirst=!1,fn(v,iterations++,this)},reverse),iterations},interposedSequence.__iteratorUncached=function(reverse){let iterator=collection.__iterator(reverse),iterations=0,isFirst=!0,pendingValue,hasPending=!1;return makeEntryIterator((entry)=>{if(hasPending)return hasPending=!1,entry[0]=iterations++,entry[1]=pendingValue,!0;let step=iterator.next();if(step.done)return!1;let value=step.value[1];if(!isFirst)return pendingValue=value,hasPending=!0,entry[0]=iterations++,entry[1]=separator,!0;return isFirst=!1,entry[0]=iterations++,entry[1]=value,!0})},reify(this,interposedSequence)}interleave(...collections){let thisAndCollections=[this,...collections],zipped=zipWithFactory(this.toSeq(),IndexedSeq.of,thisAndCollections),interleaved=zipped.flatten(!0);if(zipped.size)interleaved.size=zipped.size*thisAndCollections.length;return reify(this,interleaved)}keySeq(){throw Error("keySeq: not patched — import CollectionConversions")}last(notSetValue){return this.get(-1,notSetValue)}zip(...collections){return this.zipWith(defaultZipper,...collections)}zipAll(...collections){let thisAndCollections=[this,...collections];return reify(this,zipWithFactory(this,defaultZipper,thisAndCollections,!0))}zipWith(zipper,...collections){let thisAndCollections=[this,...collections];return reify(this,zipWithFactory(this,zipper,thisAndCollections))}}var SetCollection=(value)=>isCollection(value)&&!isAssociative(value)?value:SetSeq(value);class SetCollectionImpl extends CollectionImpl{static{this.prototype.has=CollectionImpl.prototype.includes,this.prototype.contains=CollectionImpl.prototype.includes,this.prototype.keys=SetCollectionImpl.prototype.values}get(value,notSetValue){return this.has(value)?value:notSetValue}includes(value){return this.has(value)}keySeq(){return this.valueSeq()}}Collection.Keyed=KeyedCollection;Collection.Indexed=IndexedCollection;Collection.Set=SetCollection;var IndexedCollectionPrototype=IndexedCollectionImpl.prototype,Seq=(value)=>value===void 0||value===null?emptySequence():isImmutable(value)?value.toSeq():seqFromValue(value),makeSequence=(collection)=>Object.create((isKeyed(collection)?KeyedSeqImpl:isIndexed(collection)?IndexedSeqImpl:SetSeqImpl).prototype);class SeqImpl extends CollectionImpl{static{this.prototype[IS_SEQ_SYMBOL]=!0}toSeq(){return this}toString(){return this.__toString("Seq {","}")}cacheResult(){if(!this._cache&&this.__iterateUncached)this._cache=this.entrySeq().toArray(),this.size=this._cache.length;return this}__iterateUncached(fn,reverse){let iterator=this.__iteratorUncached(reverse),iterations=0,step;while(!(step=iterator.next()).done)if(iterations++,fn(step.value[1],step.value[0],this)===!1)break;return iterations}__iterate(fn,reverse){let cache=this._cache;if(cache){let size=cache.length,i=0;while(i!==size){let entry=cache[reverse?size-++i:i++];if(fn(entry[1],entry[0],this)===!1)break}return i}return this.__iterateUncached(fn,reverse)}__iterator(reverse){let cache=this._cache;if(cache){let size=cache.length,i=0,result={done:!1,value:void 0};return makeIterator(()=>{if(i===size)return DONE;return result.value=cache[reverse?size-++i:i++],result})}return this.__iteratorUncached(reverse)}}var seqMixin={cacheResult:SeqImpl.prototype.cacheResult,__iterateUncached:SeqImpl.prototype.__iterateUncached,__iterate:SeqImpl.prototype.__iterate,__iterator:SeqImpl.prototype.__iterator},KeyedSeq=(value)=>value===void 0||value===null?emptySequence().toKeyedSeq():isCollection(value)?isKeyed(value)?value.toSeq():value.fromEntrySeq():isRecord(value)?value.toSeq():keyedSeqFromValue(value);class KeyedSeqImpl extends KeyedCollectionImpl{static{this.prototype[IS_SEQ_SYMBOL]=!0,Object.assign(this.prototype,seqMixin)}toSeq(){return this}toKeyedSeq(){return this}}var IndexedSeq=(value)=>value===void 0||value===null?emptySequence():isCollection(value)?isKeyed(value)?value.entrySeq():value.toIndexedSeq():isRecord(value)?value.toSeq().entrySeq():indexedSeqFromValue(value);IndexedSeq.of=(...values)=>IndexedSeq(values);class IndexedSeqImpl extends IndexedCollectionImpl{static{this.prototype[IS_SEQ_SYMBOL]=!0,Object.assign(this.prototype,seqMixin)}toSeq(){return this}toIndexedSeq(){return this}toString(){return this.__toString("Seq [","]")}}var SetSeq=(value)=>(isCollection(value)&&!isAssociative(value)?value:IndexedSeq(value)).toSetSeq();SetSeq.of=(...values)=>SetSeq(values);class SetSeqImpl extends SetCollectionImpl{static{this.prototype[IS_SEQ_SYMBOL]=!0,Object.assign(this.prototype,seqMixin)}toSeq(){return this}toSetSeq(){return this}}Seq.isSeq=isSeq;Seq.Keyed=KeyedSeq;Seq.Set=SetSeq;Seq.Indexed=IndexedSeq;class ArraySeq extends IndexedSeqImpl{constructor(array){super();this._array=array,this.size=array.length}get(index,notSetValue){return this.has(index)?this._array[wrapIndex(this,index)]:notSetValue}__iterateUncached(fn,reverse){let array=this._array,size=array.length,i=0;while(i!==size){let ii=reverse?size-++i:i++;if(fn(array[ii],ii,this)===!1)break}return i}__iteratorUncached(reverse){let array=this._array,size=array.length,i=0;return makeEntryIterator((entry)=>{if(i===size)return!1;let ii=reverse?size-++i:i++;return entry[0]=ii,entry[1]=array[ii],!0})}}class ObjectSeq extends KeyedSeqImpl{static{this.prototype[IS_ORDERED_SYMBOL]=!0}constructor(object){super();let keys=[...Object.keys(object),...Object.getOwnPropertySymbols(object)];this._object=object,this._keys=keys,this.size=keys.length}get(key,notSetValue){if(notSetValue!==void 0&&!this.has(key))return notSetValue;return this._object[key]}has(key){return Object.hasOwn(this._object,key)}__iterateUncached(fn,reverse){let object=this._object,keys=this._keys,size=keys.length,i=0;while(i!==size){let key=keys[reverse?size-++i:i++];if(fn(object[key],key,this)===!1)break}return i}__iteratorUncached(reverse){let object=this._object,keys=this._keys,size=keys.length,i=0;return makeEntryIterator((entry)=>{if(i===size)return!1;let key=keys[reverse?size-++i:i++];return entry[0]=key,entry[1]=object[key],!0})}}class CollectionSeq extends IndexedSeqImpl{constructor(collection){super();this._collection=collection,this.size=collection.length||collection.size}__iterateUncached(fn,reverse){if(reverse)return this.cacheResult().__iterate(fn,reverse);let iterations=0;for(let value of this._collection){if(fn(value,iterations,this)===!1)break;iterations++}return iterations}__iteratorUncached(reverse){if(reverse)return this.cacheResult().__iterator(reverse);let collection=this._collection,iterator=getIterator(collection);if(!isIterator(iterator))return emptyIterator();let iterations=0;return makeEntryIterator((entry)=>{let step=iterator.next();if(step.done)return!1;return entry[0]=iterations++,entry[1]=step.value,!0})}}var emptySequence=()=>new ArraySeq([]),maybeIndexedSeqFromValue=(value)=>isArrayLike(value)?new ArraySeq(value):hasIterator(value)?new CollectionSeq(value):void 0;function keyedSeqFromValue(value){let seq=maybeIndexedSeqFromValue(value);if(seq)return seq.fromEntrySeq();if(typeof value==="object")return new ObjectSeq(value);throw TypeError(`Expected Array or collection object of [k, v] entries, or keyed object: ${value}`)}function indexedSeqFromValue(value){let seq=maybeIndexedSeqFromValue(value);if(seq)return seq;throw TypeError(`Expected Array or collection object of values: ${value}`)}function seqFromValue(value){let seq=maybeIndexedSeqFromValue(value);if(seq)return isEntriesIterable(value)?seq.fromEntrySeq():isKeysIterable(value)?seq.toSetSeq():seq;if(typeof value==="object")return new ObjectSeq(value);throw TypeError(`Expected Array or collection object of values, or keyed object: ${value}`)}class ConcatSeq extends SeqImpl{constructor(iterables){super();let wrappedIterables=[],size=0,sizeKnown=!0;for(let iterable of iterables)if(iterable._wrappedIterables){for(let wrapped of iterable._wrappedIterables)if(wrappedIterables.push(wrapped),sizeKnown){let s=wrapped.size;if(s!==void 0)size+=s;else sizeKnown=!1}}else if(wrappedIterables.push(iterable),sizeKnown){let s=iterable.size;if(s!==void 0)size+=s;else sizeKnown=!1}this._wrappedIterables=wrappedIterables,this.size=sizeKnown?size:void 0;let first=this._wrappedIterables[0];if(first[IS_KEYED_SYMBOL])this[IS_KEYED_SYMBOL]=!0;if(first[IS_INDEXED_SYMBOL])this[IS_INDEXED_SYMBOL]=!0;if(first[IS_ORDERED_SYMBOL])this[IS_ORDERED_SYMBOL]=!0}__iterateUncached(fn,reverse){if(this._wrappedIterables.length===0)return 0;if(reverse)return this.cacheResult().__iterate(fn,reverse);let wrappedIterables=this._wrappedIterables,reIndex=!isKeyed(this),index=0,stopped=!1;for(let iterable of wrappedIterables)if(iterable.__iterate((v,k)=>{if(fn(v,reIndex?index++:k,this)===!1)return stopped=!0,!1},reverse),stopped)break;return index}__iteratorUncached(reverse){if(this._wrappedIterables.length===0)return emptyIterator();if(reverse)return this.cacheResult().__iterator(reverse);let wrappedIterables=this._wrappedIterables,reIndex=!isKeyed(this),iterableIdx=0,currentIterator=wrappedIterables[0].__iterator(reverse);function nextStep(){while(iterableIdx<wrappedIterables.length){let step=currentIterator.next();if(!step.done)return step;if(iterableIdx++,iterableIdx<wrappedIterables.length)currentIterator=wrappedIterables[iterableIdx].__iterator(reverse)}return}if(reIndex){let index=0;return makeEntryIterator((entry)=>{let step=nextStep();if(!step)return!1;return entry[0]=index++,entry[1]=step.value[1],!0})}return makeIterator(()=>nextStep()||DONE)}}class ToKeyedSequence extends KeyedSeqImpl{static{this.prototype[IS_ORDERED_SYMBOL]=!0}constructor(indexed,useKeys){super();this._iter=indexed,this._useKeys=useKeys,this.size=indexed.size}cacheResult(){return cacheResultThrough.call(this)}get(key,notSetValue){return this._iter.get(key,notSetValue)}has(key){return this._iter.has(key)}valueSeq(){return this._iter.valueSeq()}reverse(){let reversedSequence=reverseFactory(this,!0);if(!this._useKeys)reversedSequence.valueSeq=()=>this._iter.toSeq().reverse();return reversedSequence}map(mapper,context){let mappedSequence=mapFactory(this,mapper,context);if(!this._useKeys)mappedSequence.valueSeq=()=>this._iter.toSeq().map(mapper,context);return mappedSequence}__iterateUncached(fn,reverse){return this._iter.__iterate(fn,reverse)}__iteratorUncached(reverse){return this._iter.__iterator(reverse)}}class ToIndexedSequence extends IndexedSeqImpl{constructor(iter){super();this._iter=iter,this.size=iter.size}cacheResult(){return cacheResultThrough.call(this)}includes(value){return this._iter.includes(value)}__iterateUncached(fn,reverse){let i=0;if(reverse)ensureSize(this);let size=this.size;return this._iter.__iterate((v)=>{let ii=reverse?size-++i:i++;return fn(v,ii,this)},reverse),i}__iteratorUncached(reverse){let i=0;if(reverse)ensureSize(this);let size=this.size;return mapEntries(this._iter.__iterator(reverse),(k,v,entry)=>{entry[0]=reverse?size-++i:i++,entry[1]=v})}}class ToSetSequence extends SetSeqImpl{constructor(iter){super();this._iter=iter,this.size=iter.size}cacheResult(){return cacheResultThrough.call(this)}has(key){return this._iter.includes(key)}__iterateUncached(fn,reverse){return this._iter.__iterate((v)=>fn(v,v,this),reverse)}__iteratorUncached(reverse){return mapEntries(this._iter.__iterator(reverse),(k,v,entry)=>{entry[0]=v,entry[1]=v})}}class FromEntriesSequence extends KeyedSeqImpl{constructor(entries){super();this._iter=entries,this.size=entries.size}cacheResult(){return cacheResultThrough.call(this)}entrySeq(){return this._iter.toSeq()}__iterateUncached(fn,reverse){let iterations=0;return this._iter.__iterate((entry)=>{if(entry){validateEntry(entry),iterations++;let indexedCollection=isCollection(entry);return fn(indexedCollection?entry.get(1):entry[1],indexedCollection?entry.get(0):entry[0],this)}},reverse),iterations}__iteratorUncached(reverse){let iterator=this._iter.__iterator(reverse);return makeEntryIterator((out)=>{while(!0){let step=iterator.next();if(step.done)return!1;let entry=step.value[1];if(entry){validateEntry(entry);let indexedCollection=isCollection(entry);return out[0]=indexedCollection?entry.get(0):entry[0],out[1]=indexedCollection?entry.get(1):entry[1],!0}}})}}function cacheResultThrough(){if(this._iter.cacheResult)return this._iter.cacheResult(),this.size=this._iter.size,this;return SeqImpl.prototype.cacheResult.call(this)}function validateEntry(entry){if(entry!==Object(entry))throw TypeError(`Expected [K, V] tuple: ${entry}`)}var Map2=(value)=>value===void 0||value===null?emptyMap():isMap(value)&&!isOrdered(value)?value:emptyMap().withMutations((map)=>{let iter=KeyedCollection(value);assertNotInfinite(iter.size),iter.forEach((v,k)=>map.set(k,v))});class MapImpl extends KeyedCollectionImpl{static{mixin(this,{...mutatorMethods(),...deepPathMethods(),...keyedMergeMethods(),wasAltered,concat:merge,[IS_MAP_SYMBOL]:!0,[DELETE]:this.prototype.remove,removeAll:this.prototype.deleteAll,[Symbol.iterator]:this.prototype.entries,[Symbol.toStringTag]:"Immutable.Map"})}constructor(size,root,ownerID,hash2){super();this.size=size,this._root=root,this.__ownerID=ownerID,this.__hash=hash2,this.__altered=!1}create(value){return Map2(value)}toString(){return this.__toString("Map {","}")}get(k,notSetValue){return this._root?this._root.get(0,hash(k),k,notSetValue):notSetValue}set(k,v){return updateMap(this,k,v)}remove(k){return updateMap(this,k,NOT_SET)}deleteAll(keys){let collection=Collection(keys);if(collection.size===0)return this;return this.withMutations((map)=>{collection.forEach((key)=>map.remove(key))})}clear(){if(this.size===0)return this;if(this.__ownerID)return this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this;return emptyMap()}map(mapper,context){return this.withMutations((map)=>{map.forEach((value,key)=>{map.set(key,mapper.call(context,value,key,this))})})}keys(){if(!this._root)return emptyIterator();return mapIteratorGenerator(this._root,!1,0)}values(){if(!this._root)return emptyIterator();return mapIteratorGenerator(this._root,!1,1)}entries(){if(!this._root)return emptyIterator();return mapIteratorGenerator(this._root,!1)}__iterator(reverse){if(!this._root)return emptyIterator();return mapIteratorGenerator(this._root,reverse)}__iterate(fn,reverse){let iterations=0;if(this._root)this._root.iterate(([key,value])=>{return iterations++,fn(value,key,this)},reverse);return iterations}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;if(!ownerID){if(this.size===0)return emptyMap();return this.__ownerID=ownerID,this.__altered=!1,this}return makeMap(this.size,this._root,ownerID,this.__hash)}}Map2.isMap=isMap;class ArrayMapNode{constructor(ownerID,entries){this.ownerID=ownerID,this.entries=entries}get(shift,keyHash,key,notSetValue){return linearGet(this.entries,key,notSetValue)}iterate(fn,reverse){return iterateLinearEntries(this.entries,fn,reverse)}update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){let removed=value===NOT_SET,entries=this.entries,idx=0,len=entries.length;for(;idx<len;idx++)if(is(key,entries[idx][0]))break;let exists=idx<len;if(exists?entries[idx][1]===value:removed)return this;if(SetRef(didAlter),removed||!exists)SetRef(didChangeSize);if(removed&&len===1)return;if(!exists&&!removed&&len>=MAX_ARRAY_MAP_SIZE)return createNodes(ownerID,entries,key,value);let isEditable=ownerID&&ownerID===this.ownerID,newEntries=isEditable?entries:entries.slice();if(exists)if(removed)if(idx===len-1)newEntries.pop();else newEntries[idx]=newEntries.pop();else newEntries[idx]=[key,value];else newEntries.push([key,value]);if(isEditable)return this.entries=newEntries,this;return new ArrayMapNode(ownerID,newEntries)}}class BitmapIndexedNode{constructor(ownerID,bitmap,nodes){this.ownerID=ownerID,this.bitmap=bitmap,this.nodes=nodes}iterate(fn,reverse){return iterateNodeArray(this.nodes,fn,reverse)}get(shift,keyHash,key,notSetValue){let bit=1<<((shift===0?keyHash:keyHash>>>shift)&MASK),bitmap=this.bitmap;return(bitmap&bit)===0?notSetValue:this.nodes[popCount(bitmap&bit-1)].get(shift+SHIFT,keyHash,key,notSetValue)}update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){let keyHashFrag=(shift===0?keyHash:keyHash>>>shift)&MASK,bit=1<<keyHashFrag,bitmap=this.bitmap,exists=(bitmap&bit)!==0;if(!exists&&value===NOT_SET)return this;let idx=popCount(bitmap&bit-1),nodes=this.nodes,node=exists?nodes[idx]:void 0,newNode=updateNode(node,ownerID,shift+SHIFT,keyHash,key,value,didChangeSize,didAlter);if(newNode===node)return this;if(!exists&&newNode&&nodes.length>=MAX_BITMAP_INDEXED_SIZE)return expandNodes(ownerID,nodes,bitmap,keyHashFrag,newNode);if(exists&&!newNode&&nodes.length===2&&isLeafNode(nodes[idx^1]))return nodes[idx^1];if(exists&&newNode&&nodes.length===1&&isLeafNode(newNode))return newNode;let isEditable=ownerID&&ownerID===this.ownerID,newBitmap=exists?newNode?bitmap:bitmap^bit:bitmap|bit,newNodes=exists?newNode?setAt(nodes,idx,newNode,isEditable):spliceOut(nodes,idx,isEditable):spliceIn(nodes,idx,newNode,isEditable);if(isEditable)return this.bitmap=newBitmap,this.nodes=newNodes,this;return new BitmapIndexedNode(ownerID,newBitmap,newNodes)}}class HashArrayMapNode{constructor(ownerID,count,nodes){this.ownerID=ownerID,this.count=count,this.nodes=nodes}iterate(fn,reverse){return iterateNodeArray(this.nodes,fn,reverse)}get(shift,keyHash,key,notSetValue){let idx=(shift===0?keyHash:keyHash>>>shift)&MASK,node=this.nodes[idx];return node?node.get(shift+SHIFT,keyHash,key,notSetValue):notSetValue}update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){let idx=(shift===0?keyHash:keyHash>>>shift)&MASK,removed=value===NOT_SET,nodes=this.nodes,node=nodes[idx];if(removed&&!node)return this;let newNode=updateNode(node,ownerID,shift+SHIFT,keyHash,key,value,didChangeSize,didAlter);if(newNode===node)return this;let newCount=this.count;if(!node)newCount++;else if(!newNode){if(newCount--,newCount<MIN_HASH_ARRAY_MAP_SIZE)return packNodes(ownerID,nodes,newCount,idx)}let isEditable=ownerID&&ownerID===this.ownerID,newNodes=setAt(nodes,idx,newNode,isEditable);if(isEditable)return this.count=newCount,this.nodes=newNodes,this;return new HashArrayMapNode(ownerID,newCount,newNodes)}}class HashCollisionNode{constructor(ownerID,keyHash,entries){this.ownerID=ownerID,this.keyHash=keyHash,this.entries=entries}get(shift,keyHash,key,notSetValue){return linearGet(this.entries,key,notSetValue)}iterate(fn,reverse){return iterateLinearEntries(this.entries,fn,reverse)}update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){if(keyHash!==this.keyHash){if(value===NOT_SET)return this;return SetRef(didAlter),SetRef(didChangeSize),mergeIntoNode(this,ownerID,shift,keyHash,[key,value])}let removed=value===NOT_SET,entries=this.entries,idx=0,len=entries.length;for(;idx<len;idx++)if(is(key,entries[idx][0]))break;let exists=idx<len;if(exists?entries[idx][1]===value:removed)return this;if(SetRef(didAlter),removed||!exists)SetRef(didChangeSize);if(removed&&len===2)return new ValueNode(ownerID,this.keyHash,entries[idx^1]);let isEditable=ownerID&&ownerID===this.ownerID,newEntries=isEditable?entries:entries.slice();if(exists)if(removed)if(idx===len-1)newEntries.pop();else newEntries[idx]=newEntries.pop();else newEntries[idx]=[key,value];else newEntries.push([key,value]);if(isEditable)return this.entries=newEntries,this;return new HashCollisionNode(ownerID,this.keyHash,newEntries)}}class ValueNode{constructor(ownerID,keyHash,entry){this.ownerID=ownerID,this.keyHash=keyHash,this.entry=entry}iterate(fn,_reverse){return fn(this.entry)}get(shift,keyHash,key,notSetValue){return is(key,this.entry[0])?this.entry[1]:notSetValue}update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){let removed=value===NOT_SET,keyMatch=is(key,this.entry[0]);if(keyMatch?value===this.entry[1]:removed)return this;if(SetRef(didAlter),removed){SetRef(didChangeSize);return}if(keyMatch){if(ownerID&&ownerID===this.ownerID)return this.entry[1]=value,this;return new ValueNode(ownerID,this.keyHash,[key,value])}return SetRef(didChangeSize),mergeIntoNode(this,ownerID,shift,hash(key),[key,value])}}function linearGet(entries,key,notSetValue){for(let ii=0,len=entries.length;ii<len;ii++)if(is(key,entries[ii][0]))return entries[ii][1];return notSetValue}function iterateLinearEntries(entries,fn,reverse){for(let ii=0,maxIndex=entries.length-1;ii<=maxIndex;ii++)if(fn(entries[reverse?maxIndex-ii:ii])===!1)return!1}function iterateNodeArray(nodes,fn,reverse){for(let ii=0,maxIndex=nodes.length-1;ii<=maxIndex;ii++)if(nodes[reverse?maxIndex-ii:ii]?.iterate(fn,reverse)===!1)return!1}function mapIteratorGenerator(node,reverse,entryIndex){let stack={node,index:0,__prev:null},extractValue=entryIndex!==void 0?(entry)=>entry[entryIndex]:(entry)=>entry,result={done:!1,value:void 0};return makeIterator(()=>{while(stack){let node2=stack.node,index=stack.index++,maxIndex;if(node2.entry){if(index===0)return result.value=extractValue(node2.entry),result}else if(node2.entries){if(maxIndex=node2.entries.length-1,index<=maxIndex)return result.value=extractValue(node2.entries[reverse?maxIndex-index:index]),result}else if(maxIndex=node2.nodes.length-1,index<=maxIndex){let subNode=node2.nodes[reverse?maxIndex-index:index];if(subNode){if(subNode.entry)return result.value=extractValue(subNode.entry),result;stack={node:subNode,index:0,__prev:stack}}continue}stack=stack.__prev}return DONE})}var makeMap=(size,root,ownerID,hash2)=>new MapImpl(size,root,ownerID,hash2),EMPTY_MAP,emptyMap=()=>EMPTY_MAP||(EMPTY_MAP=makeMap(0));function updateMap(map,k,v){let newRoot,newSize;if(!map._root){if(v===NOT_SET)return map;newSize=1,newRoot=new ArrayMapNode(map.__ownerID,[[k,v]])}else{let didChangeSize=MakeRef(),didAlter=MakeRef();if(newRoot=updateNode(map._root,map.__ownerID,0,hash(k),k,v,didChangeSize,didAlter),!didAlter.value)return map;newSize=map.size+(didChangeSize.value?v===NOT_SET?-1:1:0)}if(map.__ownerID)return map.size=newSize,map._root=newRoot,map.__hash=void 0,map.__altered=!0,map;return newRoot?makeMap(newSize,newRoot):emptyMap()}function updateNode(node,ownerID,shift,keyHash,key,value,didChangeSize,didAlter){if(!node){if(value===NOT_SET)return node;return SetRef(didAlter),SetRef(didChangeSize),new ValueNode(ownerID,keyHash,[key,value])}return node.update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter)}var isLeafNode=(node)=>node.constructor===ValueNode||node.constructor===HashCollisionNode;function mergeIntoNode(node,ownerID,shift,keyHash,entry){if(node.keyHash===keyHash)return new HashCollisionNode(ownerID,keyHash,[node.entry,entry]);let idx1=(shift===0?node.keyHash:node.keyHash>>>shift)&MASK,idx2=(shift===0?keyHash:keyHash>>>shift)&MASK,newNode=new ValueNode(ownerID,keyHash,entry),nodes=idx1===idx2?[mergeIntoNode(node,ownerID,shift+SHIFT,keyHash,entry)]:idx1<idx2?[node,newNode]:[newNode,node];return new BitmapIndexedNode(ownerID,1<<idx1|1<<idx2,nodes)}function createNodes(ownerID,entries,key,value){if(!ownerID)ownerID=new OwnerID;let node=new ValueNode(ownerID,hash(key),[key,value]);for(let[k,v]of entries)node=node.update(ownerID,0,hash(k),k,v);return node}function packNodes(ownerID,nodes,count,excluding){let bitmap=0,packedII=0,packedNodes=Array(count);for(let ii=0,bit=1,len=nodes.length;ii<len;ii++,bit<<=1){let node=nodes[ii];if(node!==void 0&&ii!==excluding)bitmap|=bit,packedNodes[packedII++]=node}return new BitmapIndexedNode(ownerID,bitmap,packedNodes)}function expandNodes(ownerID,nodes,bitmap,including,node){let count=0,expandedNodes=Array(SIZE);for(let ii=0;bitmap!==0;ii++,bitmap>>>=1)expandedNodes[ii]=bitmap&1?nodes[count++]:void 0;return expandedNodes[including]=node,new HashArrayMapNode(ownerID,count+1,expandedNodes)}function popCount(x){return x-=x>>1&1431655765,x=(x&858993459)+(x>>2&858993459),x=x+(x>>4)&252645135,x+=x>>8,x+=x>>16,x&127}function setAt(array,idx,val,canEdit){let newArray=canEdit?array:array.slice();return newArray[idx]=val,newArray}function spliceIn(array,idx,val,canEdit){let newLen=array.length+1;if(canEdit&&idx+1===newLen)return array[idx]=val,array;let newArray=Array(newLen),after=0;for(let ii=0;ii<newLen;ii++)if(ii===idx)newArray[ii]=val,after=-1;else newArray[ii]=array[ii+after];return newArray}function spliceOut(array,idx,canEdit){let newLen=array.length-1;if(canEdit&&idx===newLen)return array.pop(),array;let newArray=Array(newLen),after=0;for(let ii=0;ii<newLen;ii++){if(ii===idx)after=1;newArray[ii]=array[ii+after]}return newArray}var MAX_ARRAY_MAP_SIZE=SIZE/4,MAX_BITMAP_INDEXED_SIZE=SIZE/2,MIN_HASH_ARRAY_MAP_SIZE=SIZE/4;function shallowCopy(from){if(Array.isArray(from))return from.slice();return{...from}}var merge$1=(collection,...sources)=>mergeWithSources(collection,sources),mergeWith$1=(merger,collection,...sources)=>mergeWithSources(collection,sources,merger),mergeDeepWithSources=(collection,sources,merger)=>mergeWithSources(collection,sources,deepMergerWith(merger)),mergeDeep$1=(collection,...sources)=>mergeDeepWithSources(collection,sources),mergeDeepWith$1=(merger,collection,...sources)=>mergeDeepWithSources(collection,sources,merger);function mergeWithSources(collection,sources,merger){if(!isDataStructure(collection))throw TypeError(`Cannot merge into non-data-structure value: ${collection}`);if(isImmutable(collection))return typeof merger==="function"&&collection.mergeWith?collection.mergeWith(merger,...sources):collection.merge?collection.merge(...sources):collection.concat(...sources);let isArray=Array.isArray(collection),merged=collection,Collection2=isArray?IndexedCollection:KeyedCollection,mergeItem=isArray?(value)=>{if(merged===collection)merged=shallowCopy(merged);merged.push(value)}:(value,key)=>{let hasVal=Object.hasOwn(merged,key),nextVal=hasVal&&merger?merger(merged[key],value,key):value;if(!hasVal||nextVal!==merged[key]){if(merged===collection)merged=shallowCopy(merged);merged[key]=nextVal}};for(let source of sources)Collection2(source).forEach(mergeItem);return merged}function deepMergerWith(merger){function deepMerger(oldValue,newValue,key){return isDataStructure(oldValue)&&isDataStructure(newValue)&&areMergeable(oldValue,newValue)?mergeWithSources(oldValue,[newValue],deepMerger):merger?merger(oldValue,newValue,key):newValue}return deepMerger}function areMergeable(oldDataStructure,newDataStructure){let oldSeq=Seq(oldDataStructure),newSeq=Seq(newDataStructure);return isIndexed(oldSeq)===isIndexed(newSeq)&&isKeyed(oldSeq)===isKeyed(newSeq)}function remove(collection,key){if(!isDataStructure(collection))throw TypeError(`Cannot update non-data-structure value: ${collection}`);if(isImmutable(collection)){if(!collection.remove)throw TypeError(`Cannot update immutable value without .remove() method: ${collection}`);return collection.remove(key)}if(!Object.hasOwn(collection,key))return collection;let collectionCopy=shallowCopy(collection);if(Array.isArray(collectionCopy))collectionCopy.splice(key,1);else delete collectionCopy[key];return collectionCopy}function set(collection,key,value){if(!isDataStructure(collection))throw TypeError(`Cannot update non-data-structure value: ${collection}`);if(isImmutable(collection)){if(!collection.set)throw TypeError(`Cannot update immutable value without .set() method: ${collection}`);return collection.set(key,value)}if(Object.hasOwn(collection,key)&&value===collection[key])return collection;let collectionCopy=shallowCopy(collection);return collectionCopy[key]=value,collectionCopy}function updateIn$1(collection,keyPath,notSetValue,updater){if(!updater)updater=notSetValue,notSetValue=void 0;let updatedValue=updateInDeeply(isImmutable(collection),collection,coerceKeyPath(keyPath),0,notSetValue,updater);return updatedValue===NOT_SET?notSetValue:updatedValue}function updateInDeeply(inImmutable,existing,keyPath,i,notSetValue,updater){let wasNotSet=existing===NOT_SET;if(i===keyPath.length){let existingValue=wasNotSet?notSetValue:existing,newValue=updater(existingValue);return newValue===existingValue?existing:newValue}if(!wasNotSet&&!isDataStructure(existing))throw TypeError(`Cannot update within non-data-structure value in path [${Array.from(keyPath).slice(0,i).map(quoteString)}]: ${existing}`);let key=keyPath[i],nextExisting=wasNotSet?NOT_SET:get(existing,key,NOT_SET),nextUpdated=updateInDeeply(nextExisting===NOT_SET?inImmutable:isImmutable(nextExisting),nextExisting,keyPath,i+1,notSetValue,updater);if(nextUpdated===nextExisting)return existing;if(nextUpdated===NOT_SET)return remove(existing,key);let collection=wasNotSet?inImmutable?emptyMap():{}:existing;return set(collection,key,nextUpdated)}var removeIn=(collection,keyPath)=>updateIn$1(collection,keyPath,()=>NOT_SET),setIn$1=(collection,keyPath,value)=>updateIn$1(collection,keyPath,NOT_SET,()=>value);function update$1(collection,key,notSetValue,updater){return updateIn$1(collection,[key],notSetValue,updater)}function asImmutable(){return this.__ensureOwner()}function asMutable(){return this.__ownerID?this:this.__ensureOwner(new OwnerID)}function wasAltered(){return this.__altered}function withMutations(fn){let mutable=this.asMutable();return fn(mutable),mutable.wasAltered()?mutable.__ensureOwner(this.__ownerID):this}function getIn(searchKeyPath,notSetValue){return getIn$1(this,searchKeyPath,notSetValue)}function hasIn(searchKeyPath){return hasIn$1(this,searchKeyPath)}function deleteIn(keyPath){return removeIn(this,keyPath)}function setIn(keyPath,v){return setIn$1(this,keyPath,v)}function update(key,notSetValue,updater){return typeof key==="function"?key(this):update$1(this,key,notSetValue,updater)}function updateIn(keyPath,notSetValue,updater){return updateIn$1(this,keyPath,notSetValue,updater)}function toObject(){assertNotInfinite(this.size);let object={};return this.__iterate((v,k)=>{object[k]=v}),object}function merge(...iters){return mergeIntoKeyedWith(this,iters)}function mergeWith(merger,...iters){if(typeof merger!=="function")throw TypeError(`Invalid merger function: ${merger}`);return mergeIntoKeyedWith(this,iters,merger)}function mergeIntoKeyedWith(collection,collections,merger){let iters=[];for(let item of collections){let collection2=KeyedCollection(item);if(collection2.size!==0)iters.push(collection2)}if(iters.length===0)return collection;if(collection.toSeq().size===0&&!collection.__ownerID&&iters.length===1)return isRecord(collection)?collection:collection.create(iters[0]);return collection.withMutations((collection2)=>{let mergeIntoCollection=merger?(value,key)=>{update$1(collection2,key,NOT_SET,(oldVal)=>oldVal===NOT_SET?value:merger(oldVal,value,key))}:(value,key)=>{collection2.set(key,value)};for(let iter of iters)iter.forEach(mergeIntoCollection)})}function mergeDeep(...iters){return mergeDeepWithSources(this,iters)}function mergeDeepWith(merger,...iters){return mergeDeepWithSources(this,iters,merger)}function mergeIn(keyPath,...iters){return updateIn$1(this,keyPath,emptyMap(),(m)=>mergeWithSources(m,iters))}function mergeDeepIn(keyPath,...iters){return updateIn$1(this,keyPath,emptyMap(),(m)=>mergeDeepWithSources(m,iters))}function mixin(Class,methods){Object.assign(Class.prototype,methods)}function mutatorMethods(){return{asImmutable,asMutable,withMutations}}function deepPathMethods(){return{deleteIn,removeIn:deleteIn,mergeDeepIn,mergeIn,setIn,update,updateIn}}function keyedMergeMethods(){return{merge,mergeWith,mergeDeep,mergeDeepWith}}var List=(value)=>{let empty=emptyList();if(value===void 0||value===null)return empty;if(isList(value))return value;let iter=IndexedCollection(value),size=iter.size;if(size===0)return empty;if(assertNotInfinite(size),size>0&&size<SIZE)return makeList(0,size,SHIFT,null,new VNode(iter.toArray()));return empty.withMutations((list)=>{list.setSize(size),iter.forEach((v,i)=>list.set(i,v))})};List.of=(...values)=>List(values);class ListImpl extends IndexedCollectionImpl{static{mixin(this,{...mutatorMethods(),...deepPathMethods(),wasAltered,[IS_LIST_SYMBOL]:!0,[DELETE]:this.prototype.remove,merge:this.prototype.concat,[Symbol.toStringTag]:"Immutable.List",[Symbol.iterator]:this.prototype.values})}constructor(origin,capacity,level,root,tail,ownerID,hash2){super();this.size=capacity-origin,this._origin=origin,this._capacity=capacity,this._level=level,this._root=root,this._tail=tail,this.__ownerID=ownerID,this.__hash=hash2,this.__altered=!1}create(value){return List(value)}toString(){return this.__toString("List [","]")}get(index,notSetValue){if(index=wrapIndex(this,index),index>=0&&index<this.size)return index+=this._origin,listNodeFor(this,index)?.array[index&MASK];return notSetValue}set(index,value){return updateList(this,index,value)}remove(index){return!this.has(index)?this:index===0?this.shift():index===this.size-1?this.pop():this.splice(index,1)}insert(index,value){return this.splice(index,0,value)}clear(){if(this.size===0)return this;if(this.__ownerID)return this.size=this._origin=this._capacity=0,this._level=SHIFT,this._root=this._tail=this.__hash=void 0,this.__altered=!0,this;return emptyList()}push(...values){let oldSize=this.size;return this.withMutations((list)=>{setListBounds(list,0,oldSize+values.length);for(let ii=0;ii<values.length;ii++)list.set(oldSize+ii,values[ii])})}pop(){return setListBounds(this,0,-1)}unshift(...values){return this.withMutations((list)=>{setListBounds(list,-values.length);for(let ii=0;ii<values.length;ii++)list.set(ii,values[ii])})}shift(){return setListBounds(this,1)}shuffle(random=Math.random){return this.withMutations((mutable)=>{let current=mutable.size,destination,tmp;while(current)destination=Math.floor(random()*current--),tmp=mutable.get(destination),mutable.set(destination,mutable.get(current)),mutable.set(current,tmp)})}concat(...collections){let seqs=[];for(let collection of collections){let seq=IndexedCollection(typeof collection!=="string"&&hasIterator(collection)?collection:[collection]);if(seq.size!==0)seqs.push(seq)}if(seqs.length===0)return this;if(this.size===0&&!this.__ownerID&&seqs.length===1)return List(seqs[0]);return this.withMutations((list)=>{seqs.forEach((seq)=>seq.forEach((value)=>list.push(value)))})}setSize(size){return setListBounds(this,0,size)}map(mapper,context){return this.withMutations((list)=>{for(let i=0;i<this.size;i++)list.set(i,mapper.call(context,list.get(i),i,this))})}slice(begin,end){let size=this.size;if(wholeSlice(begin,end,size))return this;return setListBounds(this,resolveBegin(begin,size),resolveEnd(end,size))}__iterate(fn,reverse){let index=reverse?this.size:0;return iterateListCallback(this,(value)=>fn(value,reverse?--index:index++,this),reverse),reverse?this.size-index:index}__iterator(reverse){let index=reverse?this.size:0,iter=iterateList(this,reverse);return makeEntryIterator((entry)=>{let step=iter.next();if(step.done)return!1;return entry[0]=reverse?--index:index++,entry[1]=step.value,!0})}values(){return iterateList(this,!1)}keys(){return makeIndexKeys(this.size)}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;if(!ownerID){if(this.size===0)return emptyList();return this.__ownerID=ownerID,this.__altered=!1,this}return makeList(this._origin,this._capacity,this._level,this._root,this._tail,ownerID,this.__hash)}}List.isList=isList;class VNode{constructor(array,ownerID){this.array=array,this.ownerID=ownerID}removeBefore(ownerID,level,index){if((index&(1<<level+SHIFT)-1)===0||this.array.length===0)return this;let originIndex=index>>>level&MASK;if(originIndex>=this.array.length)return new VNode([],ownerID);let removingFirst=originIndex===0,newChild;if(level>0){let oldChild=this.array[originIndex];if(newChild=oldChild?.removeBefore(ownerID,level-SHIFT,index),newChild===oldChild&&removingFirst)return this}if(removingFirst&&!newChild)return this;let editable=editableVNode(this,ownerID);if(!removingFirst)for(let ii=0;ii<originIndex;ii++)editable.array[ii]=void 0;if(newChild)editable.array[originIndex]=newChild;return editable}removeAfter(ownerID,level,index){if(index===(level?1<<level+SHIFT:SIZE)||this.array.length===0)return this;let sizeIndex=index-1>>>level&MASK;if(sizeIndex>=this.array.length)return this;let newChild;if(level>0){let oldChild=this.array[sizeIndex];if(newChild=oldChild?.removeAfter(ownerID,level-SHIFT,index),newChild===oldChild&&sizeIndex===this.array.length-1)return this}let editable=editableVNode(this,ownerID);if(editable.array.splice(sizeIndex+1),newChild)editable.array[sizeIndex]=newChild;return editable}}function iterateList(list,reverse){let{_origin:left,_capacity:right}=list,tailPos=getTailOffset(right),tail=list._tail,stack=[];pushFrame(list._root,list._level,0);let result={done:!1,value:void 0};return makeIterator(()=>{while(stack.length>0){let frame=stack[stack.length-1];if(frame.from===frame.to){stack.pop();continue}let idx=reverse?--frame.to:frame.from++;if(frame.isLeaf)return result.value=frame.array?.[idx],result;let childNode=frame.array?.[idx],childLevel=frame.level-SHIFT,childOffset=frame.offset+(idx<<frame.level);pushFrame(childNode,childLevel,childOffset)}return DONE});function pushFrame(node,level,offset){if(level===0){let array=offset===tailPos?tail?.array:node?.array,from=offset>left?0:left-offset,to=right-offset;if(to>SIZE)to=SIZE;if(from!==to)stack.push({array,from,to,isLeaf:!0})}else{let array=node?.array,from=offset>left?0:left-offset>>level,to=(right-offset>>level)+1;if(to>SIZE)to=SIZE;if(from!==to)stack.push({array,from,to,level,offset,isLeaf:!1})}}}function iterateListCallback(list,fn,reverse){let{_origin:left,_capacity:right}=list,tailPos=getTailOffset(right),tail=list._tail,level=list._level,root=list._root;return level===0?iterateLeaf(root,0,left,right,tailPos,tail,fn,reverse):iterateNode(root,level,0,left,right,tailPos,tail,fn,reverse)}function iterateLeaf(node,offset,left,right,tailPos,tail,fn,reverse){let array=offset===tailPos?tail?.array:node?.array,from=offset>left?0:left-offset,to=right-offset;if(to>SIZE)to=SIZE;while(from!==to){let idx=reverse?--to:from++;if(fn(array?.[idx])===!1)return!1}}function iterateNode(node,level,offset,left,right,tailPos,tail,fn,reverse){let array=node?.array,from=offset>left?0:left-offset>>level,to=(right-offset>>level)+1;if(to>SIZE)to=SIZE;let nextLevel=level-SHIFT;while(from!==to){let idx=reverse?--to:from++,nextOffset=offset+(idx<<level);if((nextLevel===0?iterateLeaf(array?.[idx],nextOffset,left,right,tailPos,tail,fn,reverse):iterateNode(array?.[idx],nextLevel,nextOffset,left,right,tailPos,tail,fn,reverse))===!1)return!1}}var makeList=(origin,capacity,level,root,tail,ownerID,hash2)=>new ListImpl(origin,capacity,level,root,tail,ownerID,hash2),emptyList=()=>makeList(0,0,SHIFT);function updateList(list,index,value){if(index=wrapIndex(list,index),Number.isNaN(index))return list;if(index>=list.size||index<0)return list.withMutations((list2)=>{if(index<0)setListBounds(list2,index).set(0,value);else setListBounds(list2,0,index+1).set(index,value)});index+=list._origin;let{_tail:newTail,_root:newRoot}=list,didAlter=MakeRef();if(index>=getTailOffset(list._capacity))newTail=updateVNode(newTail,list.__ownerID,0,index,value,didAlter);else newRoot=updateVNode(newRoot,list.__ownerID,list._level,index,value,didAlter);if(!didAlter.value)return list;if(list.__ownerID)return list._root=newRoot,list._tail=newTail,list.__hash=void 0,list.__altered=!0,list;return makeList(list._origin,list._capacity,list._level,newRoot,newTail)}function updateVNode(node,ownerID,level,index,value,didAlter){let idx=index>>>level&MASK,nodeHas=node&&idx<node.array.length;if(!nodeHas&&value===void 0)return node;let newNode;if(level>0){let lowerNode=node?.array[idx],newLowerNode=updateVNode(lowerNode,ownerID,level-SHIFT,index,value,didAlter);if(newLowerNode===lowerNode)return node;return newNode=editableVNode(node,ownerID),newNode.array[idx]=newLowerNode,newNode}if(nodeHas&&node.array[idx]===value)return node;if(didAlter)SetRef(didAlter);if(newNode=editableVNode(node,ownerID),value===void 0&&idx===newNode.array.length-1)newNode.array.pop();else newNode.array[idx]=value;return newNode}function editableVNode(node,ownerID){if(ownerID&&ownerID===node?.ownerID)return node;return new VNode(node?.array.slice()??[],ownerID)}function listNodeFor(list,rawIndex){if(rawIndex>=getTailOffset(list._capacity))return list._tail;if(rawIndex<1<<list._level+SHIFT){let{_root:node,_level:level}=list;while(node&&level>0)node=node.array[rawIndex>>>level&MASK],level-=SHIFT;return node}}function setListBounds(list,begin,end){if(begin!==void 0)begin|=0;if(end!==void 0)end|=0;let owner=list.__ownerID||new OwnerID,oldOrigin=list._origin,oldCapacity=list._capacity,newOrigin=oldOrigin+begin,newCapacity=end===void 0?oldCapacity:end<0?oldCapacity+end:oldOrigin+end;if(newOrigin===oldOrigin&&newCapacity===oldCapacity)return list;if(newOrigin>=newCapacity)return list.clear();let{_level:newLevel,_root:newRoot}=list,offsetShift=0;while(newOrigin+offsetShift<0)newRoot=new VNode(newRoot?.array.length?[void 0,newRoot]:[],owner),newLevel+=SHIFT,offsetShift+=1<<newLevel;if(offsetShift)newOrigin+=offsetShift,oldOrigin+=offsetShift,newCapacity+=offsetShift,oldCapacity+=offsetShift;let oldTailOffset=getTailOffset(oldCapacity),newTailOffset=getTailOffset(newCapacity);while(newTailOffset>=1<<newLevel+SHIFT)newRoot=new VNode(newRoot?.array.length?[newRoot]:[],owner),newLevel+=SHIFT;let oldTail=list._tail,newTail=newTailOffset<oldTailOffset?listNodeFor(list,newCapacity-1):newTailOffset>oldTailOffset?new VNode([],owner):oldTail;if(oldTail&&newTailOffset>oldTailOffset&&newOrigin<oldCapacity&&oldTail.array.length){newRoot=editableVNode(newRoot,owner);let node=newRoot;for(let level=newLevel;level>SHIFT;level-=SHIFT){let idx=oldTailOffset>>>level&MASK;node=node.array[idx]=editableVNode(node.array[idx],owner)}node.array[oldTailOffset>>>SHIFT&MASK]=oldTail}if(newCapacity<oldCapacity)newTail=newTail?.removeAfter(owner,0,newCapacity);if(newOrigin>=newTailOffset)newOrigin-=newTailOffset,newCapacity-=newTailOffset,newLevel=SHIFT,newRoot=null,newTail=newTail?.removeBefore(owner,0,newOrigin);else if(newOrigin>oldOrigin||newTailOffset<oldTailOffset){offsetShift=0;while(newRoot){let beginIndex=newOrigin>>>newLevel&MASK;if(beginIndex!==newTailOffset>>>newLevel&MASK)break;if(beginIndex)offsetShift+=(1<<newLevel)*beginIndex;newLevel-=SHIFT,newRoot=newRoot.array[beginIndex]}if(newRoot&&newOrigin>oldOrigin)newRoot=newRoot.removeBefore(owner,newLevel,newOrigin-offsetShift);if(newRoot&&newTailOffset<oldTailOffset)newRoot=newRoot.removeAfter(owner,newLevel,newTailOffset-offsetShift);if(offsetShift)newOrigin-=offsetShift,newCapacity-=offsetShift}if(list.__ownerID)return list.size=newCapacity-newOrigin,list._origin=newOrigin,list._capacity=newCapacity,list._level=newLevel,list._root=newRoot,list._tail=newTail,list.__hash=void 0,list.__altered=!0,list;return makeList(newOrigin,newCapacity,newLevel,newRoot,newTail)}var getTailOffset=(size)=>size<SIZE?0:size-1>>>SHIFT<<SHIFT,OrderedMap=(value)=>value===void 0||value===null?emptyOrderedMap():isOrderedMap(value)?value:emptyOrderedMap().withMutations((map)=>{let iter=KeyedCollection(value);assertNotInfinite(iter.size),iter.forEach((v,k)=>map.set(k,v))});OrderedMap.of=(...values)=>OrderedMap(values);class OrderedMapImpl extends MapImpl{static{mixin(this,{[IS_ORDERED_SYMBOL]:!0,[DELETE]:this.prototype.remove,[Symbol.iterator]:this.prototype.entries,[Symbol.toStringTag]:"Immutable.OrderedMap",keys:CollectionImpl.prototype.keys,values:CollectionImpl.prototype.values,__iterate:CollectionImpl.prototype.__iterate})}_map;_list;constructor(map,list,ownerID,hash2){super(map?map.size:0,void 0,ownerID,hash2);this._map=map,this._list=list}create(value){return OrderedMap(value)}toString(){return this.__toString("OrderedMap {","}")}get(k,notSetValue){let index=this._map.get(k);return index!==void 0?this._list.get(index)[1]:notSetValue}clear(){if(this.size===0)return this;if(this.__ownerID)return this.size=0,this._map.clear(),this._list.clear(),this.__altered=!0,this;return emptyOrderedMap()}set(k,v){return updateOrderedMap(this,k,v)}remove(k){return updateOrderedMap(this,k,NOT_SET)}entries(){return this.__iterator(!1)}__iterator(reverse){let listIter=this._list.__iterator(reverse);return makeEntryIterator((entry)=>{while(!0){let step=listIter.next();if(step.done)return!1;let e=step.value[1];if(e)return entry[0]=e[0],entry[1]=e[1],!0}})}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;let newMap=this._map.__ensureOwner(ownerID),newList=this._list.__ensureOwner(ownerID);if(!ownerID){if(this.size===0)return emptyOrderedMap();return this.__ownerID=ownerID,this.__altered=!1,this._map=newMap,this._list=newList,this}return makeOrderedMap(newMap,newList,ownerID,this.__hash)}}OrderedMap.isOrderedMap=isOrderedMap;var makeOrderedMap=(map,list,ownerID,hash2)=>new OrderedMapImpl(map,list,ownerID,hash2),emptyOrderedMap=()=>makeOrderedMap(emptyMap(),emptyList());function updateOrderedMap(omap,k,v){let{_map:map,_list:list}=omap,i=map.get(k),has2=i!==void 0,newMap,newList;if(v===NOT_SET){if(!has2)return omap;if(list.size>=SIZE&&list.size>=map.size*2){let entries=[];if(list.forEach((entry,idx)=>{if(entry!==void 0&&i!==idx)entries.push(entry)}),newList=emptyList().withMutations((l)=>{for(let j=0;j<entries.length;j++)l.set(j,entries[j])}),newMap=emptyMap().withMutations((m)=>{for(let j=0;j<entries.length;j++)m.set(entries[j][0],j)}),omap.__ownerID)newMap.__ownerID=newList.__ownerID=omap.__ownerID}else newMap=map.remove(k),newList=i===list.size-1?list.pop():list.set(i,void 0)}else if(has2){if(v===list.get(i)[1])return omap;newMap=map,newList=list.set(i,[k,v])}else{let newIdx=list.size;newMap=map.set(k,newIdx),newList=list.set(newIdx,[k,v])}if(omap.__ownerID)return omap.size=newMap.size,omap._map=newMap,omap._list=newList,omap.__hash=void 0,omap.__altered=!0,omap;return makeOrderedMap(newMap,newList)}var Stack=(value)=>value===void 0||value===null?emptyStack():isStack(value)?value:emptyStack().pushAll(value);Stack.of=(...values)=>Stack(values);class StackImpl extends IndexedCollectionImpl{static{mixin(this,{...mutatorMethods(),wasAltered,[IS_STACK_SYMBOL]:!0,shift:this.prototype.pop,unshift:this.prototype.push,unshiftAll:this.prototype.pushAll,[Symbol.toStringTag]:"Immutable.Stack",[Symbol.iterator]:this.prototype.values})}_head;__ownerID;__altered;constructor(size,head,ownerID,hash2){super();this.size=size,this._head=head,this.__ownerID=ownerID,this.__hash=hash2,this.__altered=!1}create(value){return Stack(value)}toString(){return this.__toString("Stack [","]")}get(index,notSetValue){let head=this._head;index=wrapIndex(this,index);while(head&&index--)head=head.next;return head?head.value:notSetValue}peek(){return this._head?.value}push(...values){if(values.length===0)return this;let newSize=this.size+values.length,head=this._head;for(let ii=values.length-1;ii>=0;ii--)head={value:values[ii],next:head};return returnStack(this,newSize,head)}pushAll(iter){let collection=IndexedCollection(iter);if(collection.size===0)return this;if(this.size===0&&isStack(collection))return collection;assertNotInfinite(collection.size);let newSize=this.size,head=this._head;return collection.__iterate((value)=>{newSize++,head={value,next:head}},!0),returnStack(this,newSize,head)}pop(){return this.slice(1)}clear(){if(this.size===0)return this;if(this.__ownerID)return this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this;return emptyStack()}slice(begin,end){if(wholeSlice(begin,end,this.size))return this;let resolvedBegin=resolveBegin(begin,this.size);if(resolveEnd(end,this.size)!==this.size)return IndexedCollectionImpl.prototype.slice.call(this,begin,end);let newSize=this.size-resolvedBegin,head=this._head;while(resolvedBegin--)head=head?.next;return returnStack(this,newSize,head)}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;if(!ownerID){if(this.size===0)return emptyStack();return this.__ownerID=ownerID,this.__altered=!1,this}return makeStack(this.size,this._head,ownerID,this.__hash)}__iterate(fn,reverse=!1){if(reverse){let arr=this.toArray(),size=arr.length,i=0;while(i!==size)if(fn(arr[size-++i],size-i,this)===!1)break;return i}let iterations=0,node=this._head;while(node){if(fn(node.value,iterations++,this)===!1)break;node=node.next}return iterations}__iterator(reverse=!1){if(reverse){let arr=this.toArray(),size=arr.length,i=0;return makeEntryIterator((entry)=>{if(i===size)return!1;let ii=size-++i;return entry[0]=ii,entry[1]=arr[ii],!0})}let iterations=0,node=this._head;return makeEntryIterator((entry)=>{if(!node)return!1;return entry[0]=iterations++,entry[1]=node.value,node=node.next,!0})}values(){let node=this._head,result={done:!1,value:void 0};return makeIterator(()=>{if(!node)return DONE;return result.value=node.value,node=node.next,result})}keys(){return makeIndexKeys(this.size)}}Stack.isStack=isStack;function returnStack(stack,newSize,head){if(stack.__ownerID)return stack.size=newSize,stack._head=head,stack.__hash=void 0,stack.__altered=!0,stack;return makeStack(newSize,head)}var makeStack=(size,head,ownerID,hash2)=>new StackImpl(size,head,ownerID,hash2),EMPTY_STACK,emptyStack=()=>EMPTY_STACK||(EMPTY_STACK=makeStack(0)),Set2=(value)=>value===void 0||value===null?emptySet():isSet(value)&&!isOrdered(value)?value:emptySet().withMutations((set2)=>{let iter=SetCollection(value);assertNotInfinite(iter.size),iter.forEach((v)=>set2.add(v))});Set2.of=(...values)=>Set2(values);Set2.fromKeys=(value)=>Set2(KeyedCollection(value).keySeq());Set2.intersect=(sets)=>{let setArray=Collection(sets).toArray();return setArray.length?Set2(setArray.pop()).intersect(...setArray):emptySet()};Set2.union=(sets)=>{let setArray=Collection(sets).toArray();return setArray.length?Set2(setArray.pop()).union(...setArray):emptySet()};class SetImpl extends SetCollectionImpl{static{mixin(this,{...mutatorMethods(),[IS_SET_SYMBOL]:!0,[DELETE]:this.prototype.remove,merge:this.prototype.union,concat:this.prototype.union,[Symbol.toStringTag]:"Immutable.Set"})}_map;__ownerID;constructor(map,ownerID){super();this.size=map?map.size:0,this._map=map,this.__ownerID=ownerID}create(value){return Set2(value)}toString(){return this.__toString("Set {","}")}has(value){return this._map.has(value)}add(value){return updateSet(this,this._map.set(value,value))}remove(value){return updateSet(this,this._map.remove(value))}clear(){return updateSet(this,this._map.clear())}map(mapper,context){let didChanges=!1,newMap=updateSet(this,this._map.mapEntries(([,v])=>{let mapped=mapper.call(context,v,v,this);if(mapped!==v)didChanges=!0;return[mapped,mapped]},context));return didChanges?newMap:this}union(...iters){if(iters=iters.filter((x)=>x.size!==0),iters.length===0)return this;if(this.size===0&&!this.__ownerID&&iters.length===1&&!isOrdered(this))return Set2(iters[0]);return this.withMutations((set2)=>{for(let iter of iters)if(typeof iter==="string")set2.add(iter);else SetCollection(iter).forEach((value)=>set2.add(value))})}intersect(...iters){return filterByIters(this,iters,(value,sets)=>!sets.every((iter)=>iter.includes(value)))}subtract(...iters){return filterByIters(this,iters,(value,sets)=>sets.some((iter)=>iter.includes(value)))}wasAltered(){return this._map.wasAltered()}__iterator(reverse){return this._map.__iterator(reverse)}__empty(){return emptySet()}__make(map,ownerID){return makeSet(map,ownerID)}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;let newMap=this._map.__ensureOwner(ownerID);if(!ownerID){if(this.size===0)return this.__empty();return this.__ownerID=ownerID,this._map=newMap,this}return this.__make(newMap,ownerID)}}Set2.isSet=isSet;var makeSet=(map,ownerID)=>new SetImpl(map,ownerID),EMPTY_SET,emptySet=()=>EMPTY_SET||(EMPTY_SET=makeSet(emptyMap()));function filterByIters(set2,iters,shouldRemove){if(iters.length===0)return set2;let sets=iters.map((iter)=>SetCollection(iter));return set2.withMutations((s)=>{set2.forEach((value)=>{if(shouldRemove(value,sets))s.remove(value)})})}function updateSet(set2,newMap){if(set2.__ownerID)return set2.size=newMap.size,set2._map=newMap,set2;return newMap===set2._map?set2:newMap.size===0?set2.__empty():set2.__make(newMap)}var OrderedSet=(value)=>value===void 0||value===null?emptyOrderedSet():isOrderedSet(value)?value:emptyOrderedSet().withMutations((set2)=>{let iter=SetCollection(value);assertNotInfinite(iter.size),iter.forEach((v)=>set2.add(v))});OrderedSet.of=(...values)=>OrderedSet(values);OrderedSet.fromKeys=(value)=>OrderedSet(KeyedCollection(value).keySeq());class OrderedSetImpl extends SetImpl{static{mixin(this,{[IS_ORDERED_SYMBOL]:!0,[Symbol.toStringTag]:"Immutable.OrderedSet",zip:IndexedCollectionPrototype.zip,zipWith:IndexedCollectionPrototype.zipWith,zipAll:IndexedCollectionPrototype.zipAll})}create(value){return OrderedSet(value)}toString(){return this.__toString("OrderedSet {","}")}__empty(){return emptyOrderedSet()}__make(map,ownerID){return makeOrderedSet(map,ownerID)}}OrderedSet.isOrderedSet=isOrderedSet;var makeOrderedSet=(map,ownerID)=>new OrderedSetImpl(map,ownerID),emptyOrderedSet=()=>makeOrderedSet(emptyOrderedMap()),PairSorting={LeftThenRight:-1,RightThenLeft:1};function throwOnInvalidDefaultValues(defaultValues){if(isRecord(defaultValues))throw Error("Can not call `Record` with an immutable Record as default values. Use a plain javascript object instead.");if(isImmutable(defaultValues))throw Error("Can not call `Record` with an immutable Collection as default values. Use a plain javascript object instead.");if(defaultValues===null||typeof defaultValues!=="object")throw Error("Can not call `Record` with a non-object as default values. Use a plain javascript object instead.")}var Record=(defaultValues,name)=>{let hasInitialized;throwOnInvalidDefaultValues(defaultValues);let RecordType=function(values){if(values instanceof RecordType)return values;if(!(this instanceof RecordType))return new RecordType(values);if(!hasInitialized){hasInitialized=!0;let keys=Object.keys(defaultValues),indices=RecordTypePrototype._indices={};RecordTypePrototype._name=name,RecordTypePrototype._keys=keys,RecordTypePrototype._defaultValues=defaultValues;for(let i=0;i<keys.length;i++){let propName=keys[i];if(indices[propName]=i,RecordTypePrototype[propName])console.warn(`Cannot define ${recordName(this)} with property "${propName}" since that property name is part of the Record API.`);else setProp(RecordTypePrototype,propName)}}return this.__ownerID=void 0,this._values=List().withMutations((l)=>{l.setSize(this._keys.length),KeyedCollection(values).forEach((v,k)=>{l.set(this._indices[k],v===this._defaultValues[k]?void 0:v)})}),this},RecordTypePrototype=RecordType.prototype=Object.create(RecordPrototype);if(RecordTypePrototype.constructor=RecordType,RecordTypePrototype.create=RecordType,name)RecordType.displayName=name;return RecordType};class RecordImpl{static{mixin(this,{...mutatorMethods(),...deepPathMethods(),...keyedMergeMethods(),getIn,hasIn,toObject,toJSON:toObject,[IS_RECORD_SYMBOL]:!0,[DELETE]:this.prototype.remove,[Symbol.iterator]:this.prototype.entries,[Symbol.toStringTag]:"Immutable.Record"})}toString(){let body=this._keys.map((k)=>`${k}: ${quoteString(this.get(k))}`).join(", ");return`${recordName(this)} { ${body} }`}equals(other){return this===other||isRecord(other)&&recordSeq(this).equals(recordSeq(other))}hashCode(){return recordSeq(this).hashCode()}has(k){return Object.hasOwn(this._indices,k)}get(k,notSetValue){if(!this.has(k))return notSetValue;let index=this._indices[k],value=this._values.get(index);return value===void 0?this._defaultValues[k]:value}set(k,v){if(this.has(k)){let newValues=this._values.set(this._indices[k],v===this._defaultValues[k]?void 0:v);if(newValues!==this._values&&!this.__ownerID)return makeRecord(this,newValues)}return this}remove(k){return this.set(k)}clear(){let newValues=this._values.clear().setSize(this._keys.length);return this.__ownerID?this:makeRecord(this,newValues)}wasAltered(){return this._values.wasAltered()}toSeq(){return recordSeq(this)}toJS(){return toJS(this)}entries(){return this.__iterator()}__iterate(fn,reverse){return recordSeq(this).__iterate(fn,reverse)}__iterator(reverse){return recordSeq(this).__iterator(reverse)}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;let newValues=this._values.__ensureOwner(ownerID);if(!ownerID)return this.__ownerID=ownerID,this._values=newValues,this;return makeRecord(this,newValues,ownerID)}}Record.isRecord=isRecord;var recordName=(record)=>record.constructor.displayName||record.constructor.name||"Record";class RecordSeq extends KeyedSeqImpl{constructor(record){super();this._record=record,this.size=record._keys.length}get(key,notSetValue){return this._record.get(key,notSetValue)}has(key){return this._record.has(key)}__iterateUncached(fn,reverse){let record=this._record,keys=record._keys,size=keys.length,i=0;while(i!==size){let ii=reverse?size-++i:i++,k=keys[ii];if(fn(record.get(k),k,this)===!1)break}return i}__iteratorUncached(reverse){let record=this._record,keys=record._keys,size=keys.length,i=0;return makeEntryIterator((entry)=>{if(i===size)return!1;let ii=reverse?size-++i:i++,k=keys[ii];return entry[0]=k,entry[1]=record.get(k),!0})}}var recordSeq=(record)=>new RecordSeq(record);Record.getDescriptiveName=recordName;var RecordPrototype=RecordImpl.prototype;function makeRecord(likeRecord,values,ownerID){let record=Object.create(Object.getPrototypeOf(likeRecord));return record._values=values,record.__ownerID=ownerID,record}function setProp(prototype,name){Object.defineProperty(prototype,name,{get(){return this.get(name)},set(value){invariant(this.__ownerID,"Cannot set on an immutable record."),this.set(name,value)}})}var Range=(start,end,step=1)=>{if(invariant(step!==0,"Cannot step a Range by 0"),invariant(start!==void 0,"You must define a start value when using Range"),invariant(end!==void 0,"You must define an end value when using Range"),step=Math.abs(step),end<start)step=-step;let size=Math.max(0,Math.ceil((end-start)/step-1)+1);return new RangeImpl(start,end,step,size)};class RangeImpl extends IndexedSeqImpl{_start;_end;_step;constructor(start,end,step,size){super();this._start=start,this._end=end,this._step=step,this.size=size}toString(){return this.size===0?"Range []":`Range [ ${this._start}...${this._end}${this._step!==1?` by ${this._step}`:""} ]`}get(index,notSetValue){return this.has(index)?this._start+wrapIndex(this,index)*this._step:notSetValue}includes(searchValue){let possibleIndex=(searchValue-this._start)/this._step;return possibleIndex>=0&&possibleIndex<this.size&&possibleIndex===Math.floor(possibleIndex)}slice(begin,end){if(wholeSlice(begin,end,this.size))return this;if(begin=resolveBegin(begin,this.size),end=resolveEnd(end,this.size),end<=begin)return Range(0,0);return Range(this.get(begin,this._end),this.get(end,this._end),this._step)}indexOf(searchValue){let offsetValue=searchValue-this._start;if(offsetValue%this._step===0){let index=offsetValue/this._step;if(index>=0&&index<this.size)return index}return-1}lastIndexOf(searchValue){return this.indexOf(searchValue)}__iterateUncached(fn,reverse=!1){let size=this.size,step=this._step,value=reverse?this._start+(size-1)*step:this._start,i=0;while(i!==size){let v=value;value+=reverse?-step:step;let ii=reverse?size-++i:i++;if(fn(v,ii,this)===!1)break}return i}__iteratorUncached(reverse=!1){let size=this.size,step=this._step,value=reverse?this._start+(size-1)*step:this._start,i=0;return makeEntryIterator((entry)=>{if(i===size)return!1;let v=value;return value+=reverse?-step:step,entry[0]=reverse?size-++i:i++,entry[1]=v,!0})}values(){let size=this.size,step=this._step,value=this._start,i=0,result={done:!1,value:void 0};return makeIterator(()=>{if(i===size)return DONE;return result.value=value,value+=step,i++,result})}keys(){return makeIndexKeys(this.size)}equals(other){return other instanceof RangeImpl?this._start===other._start&&this._end===other._end&&this._step===other._step:deepEqual(this,other)}static{this.prototype[Symbol.iterator]=this.prototype.values}}var Repeat=(value,times)=>{let size=times===void 0?1/0:Math.max(0,times);return new RepeatImpl(value,size)};class RepeatImpl extends IndexedSeqImpl{_value;constructor(value,size){super();this._value=value,this.size=size}toString(){if(this.size===0)return"Repeat []";return`Repeat [ ${this._value} ${this.size} times ]`}get(index,notSetValue){return this.has(index)?this._value:notSetValue}includes(searchValue){return is(this._value,searchValue)}slice(begin,end){let size=this.size;return wholeSlice(begin,end,size)?this:new RepeatImpl(this._value,resolveEnd(end,size)-resolveBegin(begin,size))}reverse(){return this}indexOf(searchValue){if(is(this._value,searchValue))return 0;return-1}lastIndexOf(searchValue){if(is(this._value,searchValue))return this.size;return-1}__iterateUncached(fn,reverse=!1){let size=this.size,i=0;while(i!==size)if(fn(this._value,reverse?size-++i:i++,this)===!1)break;return i}__iteratorUncached(reverse=!1){let size=this.size,val=this._value,i=0;return makeEntryIterator((entry)=>{if(i===size)return!1;return entry[0]=reverse?size-++i:i++,entry[1]=val,!0})}values(){let size=this.size,val=this._value,i=0,result={done:!1,value:void 0};return makeIterator(()=>{if(i===size)return DONE;return i++,result.value=val,result})}keys(){return makeIndexKeys(this.size)}equals(other){return other instanceof RepeatImpl?this.size===other.size&&is(this._value,other._value):deepEqual(this,other)}static{this.prototype[Symbol.iterator]=this.prototype.values}}var fromJS=(value,converter)=>fromJSWith([],converter??defaultConverter,value,"",converter&&converter.length>2?[]:void 0,{"":value});function fromJSWith(stack,converter,value,key,keyPath,parentValue){if(typeof value!=="string"&&!isImmutable(value)&&(isArrayLike(value)||hasIterator(value)||isPlainObject(value))){if(stack.includes(value))throw TypeError("Cannot convert circular structure to Immutable");if(stack.push(value),keyPath&&key!=="")keyPath.push(key);let converted=converter.call(parentValue,key,Seq(value).map((v,k)=>fromJSWith(stack,converter,v,k,keyPath,value)),keyPath?.slice());if(stack.pop(),keyPath)keyPath.pop();return converted}return value}var defaultConverter=(k,v)=>isIndexed(v)?v.toList():isKeyed(v)?v.toMap():v.toSet(),asValues=(collection)=>isKeyed(collection)?collection.valueSeq():collection;function initCollectionConversions(){CollectionImpl.prototype.toMap=function(){return Map2(this.toKeyedSeq())},CollectionImpl.prototype.toOrderedMap=function(){return OrderedMap(this.toKeyedSeq())},CollectionImpl.prototype.toOrderedSet=function(){return OrderedSet(asValues(this))},CollectionImpl.prototype.toSet=function(){return Set2(asValues(this))},CollectionImpl.prototype.toStack=function(){return Stack(asValues(this))},CollectionImpl.prototype.toList=function(){return List(asValues(this))},CollectionImpl.prototype.countBy=function(grouper,context){let groups=Map2().asMutable();return this.__iterate((v,k)=>{groups.update(grouper.call(context,v,k,this),0,(a)=>a+1)}),groups.asImmutable()},CollectionImpl.prototype.groupBy=function(grouper,context){let isKeyedIter=isKeyed(this),groups=(isOrdered(this)?OrderedMap():Map2()).asMutable();return this.__iterate((v,k)=>{groups.update(grouper.call(context,v,k,this),(a)=>{return a??=[],a.push(isKeyedIter?[k,v]:v),a})}),groups.map((arr)=>reifyValues(this,arr)).asImmutable()},IndexedCollectionImpl.prototype.keySeq=function(){return Range(0,this.size)};let patchSort=(Impl,OrderedCtor)=>{Impl.prototype.sort=function(comparator){return OrderedCtor(sortFactory(this,comparator))},Impl.prototype.sortBy=function(mapper,comparator){return OrderedCtor(sortFactory(this,comparator,mapper))}};patchSort(MapImpl,OrderedMap),patchSort(SetImpl,OrderedSet)}var version$1="7.0.0",pkg={version:version$1};initCollectionConversions();var{version}=pkg;var NONE=Symbol("NONE");class Step{lookup(_v,dval=null){return dval}setValue(root,_v){return root}enterFrame(stack,_prev,next){return stack.enter(next,{},!0)}toAbstractPathStep(){return this}pinKey(_v){return this}toKey(){return null}}class BindStep extends Step{constructor(binds){super();this.binds=binds}lookup(v,_dval){return v}setValue(_root,v){return v}enterFrame(stack,_prev,next){return stack.enter(next,{...this.binds},!1)}withIndex(i){return new BindStep({...this.binds,key:i})}withKey(key){return new BindStep({...this.binds,key})}toAbstractPathStep(){return null}}class ScopeBindStep extends BindStep{constructor(val,binds={}){super(binds);this.val=val}enterFrame(stack,_prev,next){let dyn=this.val.evalAsHandler(stack)?.call(stack.it)??{};return stack.enter(next,{...this.binds,...dyn},!1)}withIndex(i){return new ScopeBindStep(this.val,{...this.binds,key:i})}withKey(key){return new ScopeBindStep(this.val,{...this.binds,key})}}class FieldStep extends Step{constructor(field){super();this.field=field}lookup(v,dval=null){return v?.get?v.get(this.field,dval):dval}setValue(root,v){return root.set(this.field,v)}withIndex(i){return new SeqStep(this.field,i)}withKey(k){return new SeqStep(this.field,k)}toKey(){return{field:this.field}}}class SeqStep extends Step{constructor(field,key){super();this.field=field,this.key=key}lookup(v,dval=null){let o=v?.get(this.field,null);return o?.get?o.get(this.key,dval):dval}setValue(root,v){let seq=root?.get(this.field,null);return seq?root.set(this.field,seq.set(this.key,v)):root}enterFrame(stack,_prev,next){return stack.enter(next,{key:this.key},!0)}toKey(){return{field:this.field,key:this.key}}}class SeqAccessStep extends Step{constructor(seqField,keyField){super();this.seqField=seqField,this.keyField=keyField}lookup(v,dval=null){let seq=v?.get(this.seqField,NONE),key=v?.get(this.keyField,NONE);return key!==NONE&&seq?.get?seq.get(key,dval):dval}setValue(root,v){let seq=root?.get(this.seqField,NONE),key=root?.get(this.keyField,NONE);return seq===NONE||key===NONE?root:root.set(this.seqField,seq.set(key,v))}pinKey(v){let key=v?.get(this.keyField,NONE);return key===NONE?this:new SeqStep(this.seqField,key)}toKey(){return{field:this.seqField}}}class EachBindStep extends Step{constructor(iterInfo,key){super();this.iterInfo=iterInfo,this.key=key}lookup(v,_dval){return v}setValue(_root,v){return v}enterFrame(stack,_prev,next){return stack.enter(next,this.iterInfo.enrichBinds(stack,this.key),!1)}toAbstractPathStep(){return null}}class EachRenderItStep extends SeqStep{enterFrame(stack,_prev,next){return stack.enter(next,{key:this.key,value:next},!1).enter(next,{},!0)}toAbstractPathStep(){return new SeqStep(this.field,this.key)}}function warnRawDynStep(op,step){console.warn(`Path.${op} reached a DynStep: call toTransactionPath() first`,step)}class DynStep extends Step{constructor(producerCompId,producerSteps){super();this.producerCompId=producerCompId,this.producerSteps=producerSteps,this.interiorCids=new Set}teleportSteps(){return this.producerSteps}lookup(_v,dval=null){return warnRawDynStep("lookup",this),dval}setValue(root,_v){return warnRawDynStep("setValue",this),root}enterFrame(stack,_prev,_next){return warnRawDynStep("enterFrame",this),stack}}class DynEachStep extends DynStep{constructor(producerCompId,producerSteps,key){super(producerCompId,producerSteps);this.key=key}teleportSteps(){let{producerSteps,key}=this;if(producerSteps.length===0)return producerSteps;let last=producerSteps[producerSteps.length-1];if(!(last instanceof FieldStep))return console.warn("DynEachStep: seq-access dynamic cannot be iterated",this),producerSteps;return producerSteps.slice(0,-1).concat(new SeqStep(last.field,key))}}class Path{constructor(steps=[]){this.steps=steps}concat(steps){return new Path(this.steps.concat(steps))}popStep(){return new Path(this.steps.slice(0,-1))}compact(){let out=[];for(let step of this.steps){let s=step.toAbstractPathStep();if(s!==null){if(s!==step)s._originCid=step._originCid;out.push(s)}}return new Path(out)}toTransactionPath(){let hasDyn=!1;for(let step of this.steps)if(step instanceof DynStep){hasDyn=!0;break}if(!hasDyn)return this;let out=[];for(let step of this.steps)if(step instanceof DynStep){while(out.length>0&&step.interiorCids.has(out[out.length-1]._originCid))out.pop();for(let ts of step.teleportSteps())ts._originCid=step.producerCompId,out.push(ts)}else out.push(step);return new Path(out)}pinKeys(root){let curVal=root,out=null;for(let i=0;i<this.steps.length;i++){let step=this.steps[i],pinned=step.pinKey(curVal);if(pinned!==step)(out??=this.steps.slice())[i]=pinned;if(curVal=step.lookup(curVal,NONE),curVal===NONE)break}return out?new Path(out):this}lookup(v,dval=null){let curVal=v;for(let step of this.steps)if(curVal=step.lookup(curVal,NONE),curVal===NONE)return dval;return curVal}resolveChain(root){let out=[root],curVal=root;for(let step of this.steps){if(curVal=step.lookup(curVal,NONE),curVal===NONE)break;out.push(curVal)}return out}toKeys(){let out=[];for(let step of this.steps){let k=step.toKey();if(k!==null)out.push(k)}return out}setValue(root,v){let intermediates=Array(this.steps.length),curVal=root;for(let i=0;i<this.steps.length;i++)if(intermediates[i]=curVal,curVal=this.steps[i].lookup(curVal,NONE),curVal===NONE)return root;let newVal=v;for(let i=this.steps.length-1;i>=0;i--)newVal=this.steps[i].setValue(intermediates[i],newVal),intermediates[i]=newVal;return newVal}buildStack(stack){let prev=stack.it;for(let step of this.steps){let next=step.lookup(prev,NONE);if(next===NONE)return console.warn("bad PathItem",{root:stack.it,step,path:this}),null;stack=step.enterFrame(stack,prev,next),prev=next}return stack}static fromNodeAndEventName(node,eventName,rootNode,maxDepth,comps,stopOnNoEvent=!0){let pathSteps=[],pendingDyns=[],bubbles=BUBBLING_EVENTS.has(eventName),depth=0,eventIds=[],handlers=null,nodeIds=[],isLeafComponent=!0,crossComponent=(cidNum,vid)=>{let comp=comps.getComponentForId(cidNum),pushStep=!0;if(handlers===null&&(isLeafComponent||bubbles)){if(handlers=findHandlers(comp,eventIds,vid,eventName),handlers===null){if(isLeafComponent&&stopOnNoEvent&&!bubbles)return!1}else if(!isLeafComponent)pathSteps.length=0,pendingDyns.length=0,pushStep=!1}isLeafComponent=!1;for(let dyn of pendingDyns)dyn.interiorCids.add(cidNum);if(pushStep){let step=resolvePathStep(comp,nodeIds,vid);if(step){if(step._originCid=cidNum,pathSteps.push(step),step instanceof DynStep)step.interiorCids.add(cidNum),pendingDyns.push(step)}}for(let i=pendingDyns.length-1;i>=0;i--)if(pendingDyns[i].producerCompId===cidNum)pendingDyns.splice(i,1);return eventIds=[],nodeIds=[],!0};while(node&&node!==rootNode&&depth<maxDepth){if(node?.dataset){let{eid,cid,vid}=node.dataset;if(eid!==void 0)eventIds.push(eid);let metas=metaChain(node.previousSibling),sawComp=!1;for(let m of metas)if(m.$==="Comp"){if(sawComp=!0,!crossComponent(m.cid,m.vid))return NO_EVENT_INFO;nodeIds.push({nid:m.nid})}else nodeIds.push({nid:m.nid,si:m.si,sk:m.sk});if(!sawComp&&cid!==void 0&&!crossComponent(+cid,vid))return NO_EVENT_INFO}depth+=1,node=node.parentNode}if(pendingDyns.length>0)console.warn("event reconstruction: dynamic-var producer not found",pendingDyns);return[new Path(pathSteps.reverse()),handlers]}static fromEvent(e,rNode,maxDepth,comps,stopOnNoEvent=!0){let{type,target}=e;return Path.fromNodeAndEventName(target,type,rNode,maxDepth,comps,stopOnNoEvent)}}function metaChain(n){let out=[];while(n?.nodeType===8&&n.textContent[0]==="§"){try{out.push(JSON.parse(n.textContent.slice(1,-1)))}catch(err){console.warn(err,n)}n=n.previousSibling}return out}function findHandlers(comp,eventIds,vid,eventName){for(let eid of eventIds){let handlers=comp.getEventForId(+eid,vid).getHandlersFor(eventName);if(handlers!==null)return handlers}return null}class StepCtx{constructor(comp,nodeIds,idx,vid){this.comp=comp,this.nodeIds=nodeIds,this.idx=idx,this.vid=vid}get meta(){return this.nodeIds[this.idx]}get key(){let m=this.meta;return m.si!==void 0?+m.si:m.sk}get hasKey(){let m=this.meta;return m.si!==void 0||m.sk!==void 0}next(){let{idx,nodeIds}=this;return idx+1<nodeIds.length?new StepCtx(this.comp,nodeIds,idx+1,this.vid):null}resolveNode(){return this.comp.getNodeForId(+this.meta.nid,this.vid)}applyKey(pi){if(pi===null)return null;let m=this.meta;if(m.si!==void 0)return pi.withIndex(+m.si);if(m.sk!==void 0)return pi.withKey(m.sk);return pi}}function resolvePathStep(comp,nodeIds,vid){for(let i=0;i<nodeIds.length;i++){let ctx=new StepCtx(comp,nodeIds,i,vid),step=ctx.resolveNode().toPathStep(ctx);if(step!==null)return step}return null}var NO_EVENT_INFO=[null,null],BUBBLING_EVENTS=new Set(["drop"]);class PathBuilder{constructor(){this.pathChanges=[]}add(pathChange){return this.pathChanges.push(pathChange),this}field(name){return this.add(new FieldStep(name))}index(name,index){return this.add(new SeqStep(name,index))}key(name,key){return this.add(new SeqStep(name,key))}}var VALID_VAL_ID_RE=/^[a-zA-Z][a-zA-Z0-9_]*\??$/,isValidValId=(name)=>VALID_VAL_ID_RE.test(name),VALID_FLOAT_RE=/^-?[0-9]+(\.[0-9]+)?$/,STR_TPL_SPLIT_RE=/(\{[^}]+\})/g,mkVal=(name,Cls)=>isValidValId(name)?new Cls(name):null,VAL_TOKEN_RE=/\$'(?:[^'\\]|\\.)*'|'(?:[^'\\]|\\.)*'|\S+/g,tokenizeValue=(s)=>s.match(VAL_TOKEN_RE)??[],unescapeStr=(s)=>s.replace(/\\(['\\])/g,"$1"),K_CONST=1,K_STRTPL=2,K_FIELD=4,K_BIND=8,K_DYN=16,K_NAME=32,K_TYPE=64,K_SEQ=256,K_METHOD=1024,G_BOOL=K_FIELD|K_METHOD|K_BIND|K_DYN|K_CONST,G_TEXT=G_BOOL|K_STRTPL,G_COMPONENT=K_FIELD|K_SEQ|K_DYN,G_SEQUENCE=K_FIELD|K_DYN,G_PROVIDE=K_FIELD|K_SEQ,G_FIELD=K_FIELD|K_METHOD|K_CONST|K_SEQ,G_VALUE=K_FIELD|K_METHOD|K_BIND|K_DYN|K_NAME|K_TYPE|K_CONST,G_ALL=G_VALUE|K_STRTPL|K_SEQ;function sizeOf(v){if(v==null)return null;let s=v.size;if(typeof s==="number")return s;let l=v.length;return typeof l==="number"?l:null}var predTruthy=(v)=>{let n=sizeOf(v);return n===null?!!v:n>0},PREDICATES={"empty?":{name:"empty?",arity:1,fn:(v)=>v==null||sizeOf(v)===0},"truthy?":{name:"truthy?",arity:1,fn:predTruthy},"falsy?":{name:"falsy?",arity:1,fn:(v)=>!predTruthy(v)},"null?":{name:"null?",arity:1,fn:(v)=>v==null},"equals?":{name:"equals?",arity:2,fn:(a,b)=>is(a,b)}};class ValParser{constructor(){this.nullConstVal=new ConstVal(null)}const(v){return new ConstVal(v)}parseToken(s,px){let c0=s.charCodeAt(0);if(c0===39)return s.length>=2&&s.charCodeAt(s.length-1)===39?new ConstVal(unescapeStr(s.slice(1,-1))):null;if(c0===36&&s.charCodeAt(1)===39)return s.length>=3&&s.charCodeAt(s.length-1)===39?StrTplVal.parse(s.slice(2,-1),px):null;if(s.indexOf("[")!==-1||s.indexOf("]")!==-1)return this._parseSeqAccess(s,px);if(s.indexOf("{")!==-1||s.indexOf("}")!==-1)return null;switch(c0){case 94:{let name=s.slice(1),newS=px.frame.macroVars?.[name];if(newS!==void 0){let tokens=tokenizeValue(newS.trim());if(tokens.length!==1)return null;let val=this.parseToken(tokens[0],px);if(val instanceof ConstVal)val.fromMacroVar=!0;return val}return px.onParseIssue("bad-value",{role:"macro-var",name,value:s}),null}case 36:return mkVal(s.slice(1),MethodVal);case 64:{let dot=s.indexOf(".",1);if(dot===-1)return mkVal(s.slice(1),BindVal);let name=s.slice(1,dot),member=s.slice(dot+1);return isValidValId(name)&&isValidValId(member)?new BindMemberVal(name,member):null}case 42:return mkVal(s.slice(1),DynVal);case 46:return mkVal(s.slice(1),FieldVal)}let num=VALID_FLOAT_RE.test(s)?parseFloat(s):null;if(Number.isFinite(num))return new ConstVal(num);if(s==="true"||s==="false")return new ConstVal(s==="true");if(c0>=97&&c0<=122)return mkVal(s,NameVal);if(c0>=65&&c0<=90)return mkVal(s,TypeVal);return null}_parseSeqAccess(s,px){let open=s.indexOf("["),close=s.indexOf("]");if(open<1||close!==s.length-1||close<open||s.indexOf("[",open+1)!==-1)return null;let left=this.parseToken(s.slice(0,open),px),right=this.parseToken(s.slice(open+1,close),px);return left instanceof FieldVal&&right instanceof FieldVal?new SeqAccessVal(left,right):null}_parseSingle(s,px,group){let tokens=tokenizeValue(s.trim());if(tokens.length!==1)return null;let val=this.parseToken(tokens[0],px);return val!==null&&kindOf(val)&group?val:null}parseBool(s,px){let t=s.trim(),tokens=tokenizeValue(t);if(tokens.length!==1)return tokens.length===0?null:this._parsePredicate(t,tokens,px);let val=this.parseToken(tokens[0],px);return val!==null&&kindOf(val)&G_BOOL?val:null}parseText(s,px){return this._parseSingle(s,px,G_TEXT)}parseComponent(s,px){return this._parseSingle(s,px,G_COMPONENT)}parseSequence(s,px){return this._parseSingle(s,px,G_SEQUENCE)}parseField(s,px){return this._parseSingle(s,px,G_FIELD)}parseProvide(s,px){return this._parseSingle(s,px,G_PROVIDE)}parseHandlerArg(s,px){return this._parseSingle(s,px,G_VALUE)}parseMacroAttr(s,px){return this._parseSingle(s,px,G_ALL)}parseInputHandler(s,px){return this._parseHandler(s,px,"input",!0,!0)}parseAlterHandler(s,px){let r=this._parseHandler(s,px,"alter",!1,!1);return r===null?null:r.handlerVal}_parseHandler(s,px,namespace,allowArgs,report){let tokens=tokenizeValue(s.trim()),headTok=tokens[0]??"",head=headTok===""?null:this.parseToken(headTok,px),hk=kindOf(head),handlerVal;if(hk&K_METHOD)handlerVal=head;else if(hk&K_NAME)handlerVal=new HandlerNameVal(head.name,namespace);else{if(report)px.onParseIssue("bad-value",{role:"handler-name",value:headTok});return null}if(!allowArgs)return tokens.length===1?{handlerVal,args:[]}:null;let args=Array(tokens.length-1);for(let i=1;i<tokens.length;i++){let val=this.parseToken(tokens[i],px);if(val!==null&&kindOf(val)&G_VALUE)args[i-1]=val;else{if(report)px.onParseIssue("bad-value",{role:"handler-arg",value:tokens[i]});args[i-1]=this.nullConstVal}}return{handlerVal,args}}_parsePredicate(s,tokens,px){let predName=tokens[0],pred=PREDICATES[predName];if(pred===void 0)return px.onParseIssue("bad-value",{role:"predicate",value:predName}),null;let arity=tokens.length-1;if(arity!==pred.arity)return px.onParseIssue("bad-value",{role:"predicate-arity",value:s,predicate:predName}),null;let args=Array(arity);for(let i=0;i<arity;i++){let tok=tokens[i+1],val=this.parseToken(tok,px);if(val===null||!(kindOf(val)&G_BOOL))return px.onParseIssue("bad-value",{role:"predicate-arg",value:tok}),null;args[i]=val}return new PredicateVal(pred,args)}}function kindOf(val){if(val===null)return 0;if(val instanceof ConstVal)return val.kind;if(val instanceof StrTplVal)return val.kind;if(val instanceof SeqAccessVal)return K_SEQ;if(val instanceof FieldVal)return K_FIELD;if(val instanceof MethodVal)return K_METHOD;if(val instanceof BindVal)return K_BIND;if(val instanceof DynVal)return K_DYN;if(val instanceof TypeVal)return K_TYPE;if(val instanceof NameVal)return K_NAME;return 0}class BaseVal{render(_stack,_rx){}eval(_stack){}toPathItem(){return null}evalAsHandler(stack){return this.eval(stack)}}class ConstVal extends BaseVal{constructor(val,kind=K_CONST){super();this.val=val,this.kind=kind}render(_stack,_rx){return this.val}eval(_stack){return this.val}toString(){let v=this.val;return typeof v==="string"?`'${v.replace(/(['\\])/g,"\\$1")}'`:`${v}`}}class PredicateVal extends BaseVal{constructor(pred,args){super();this.pred=pred,this.args=args}eval(stack){let n=this.args.length,vals=Array(n);for(let i=0;i<n;i++)vals[i]=this.args[i].eval(stack);return this.pred.fn(...vals)}toString(){return`${this.pred.name} ${this.args.map(String).join(" ")}`}}class VarVal extends BaseVal{}class StrTplVal extends VarVal{constructor(vals){super();this.vals=vals,this.kind=this.isLiteral()?K_CONST:K_STRTPL}isLiteral(){for(let v of this.vals)if(!(v instanceof ConstVal)||v.fromMacroVar)return!1;return!0}render(stack,_rx){return this.eval(stack)}eval(stack){let strs=Array(this.vals.length);for(let i=0;i<this.vals.length;i++)strs[i]=this.vals[i]?.eval(stack,"");return strs.join("")}toLiteralSource(){if(!this.isLiteral())return null;let out="";for(let v of this.vals)out+=v.val;return new ConstVal(out).toString()}static parse(s,px){let parts=unescapeStr(s).split(STR_TPL_SPLIT_RE),vals=Array(parts.length);for(let i=0;i<parts.length;i++){let part=parts[i],isExpr=part[0]==="{"&&part.at(-1)==="}";vals[i]=isExpr?vp.parseText(part.slice(1,-1),px):new ConstVal(part)}let lo=0,hi=vals.length,isTrimmable=(v)=>v instanceof ConstVal&&v.val===""&&!v.fromMacroVar;while(lo<hi&&isTrimmable(vals[lo]))lo++;while(hi>lo&&isTrimmable(vals[hi-1]))hi--;return new StrTplVal(lo===0&&hi===vals.length?vals:vals.slice(lo,hi))}}class NameVal extends VarVal{constructor(name){super();this.name=name}eval(stack){return stack.lookupName(this.name)}toString(){return this.name}}class HandlerNameVal extends NameVal{constructor(name,namespace){super(name);this.namespace=namespace}eval(stack){return stack.getHandlerFor(this.name,this.namespace)??mk404Handler(this.namespace,this.name)}}var mk404Handler=(type,name)=>function(...args){return console.warn("handler not found",{type,name,args},this),this};class TypeVal extends NameVal{eval(stack){return stack.lookupType(this.name)}}class RenderVal extends BaseVal{render(stack,_rx){return this.eval(stack)}}class RenderNameVal extends RenderVal{constructor(name){super();this.name=name}}class BindVal extends RenderNameVal{eval(stack){return stack.lookupBind(this.name)}toString(){return`@${this.name}`}}class BindMemberVal extends BindVal{constructor(name,member){super(name);this.member=member}eval(stack){let v=stack.lookupBind(this.name);return typeof v?.get==="function"?v.get(this.member,null):v?.[this.member]??null}toString(){return`@${this.name}.${this.member}`}}class DynVal extends RenderNameVal{eval(stack){return stack.lookupDynamic(this.name)}toString(){return`*${this.name}`}}class FieldVal extends RenderNameVal{eval(stack){return stack.lookupFieldRaw(this.name)}toPathItem(){return new FieldStep(this.name)}toString(){return`.${this.name}`}}class MethodVal extends RenderNameVal{eval(stack){return stack.lookupMethod(this.name)}evalAsHandler(stack){return stack.lookupFieldRaw(this.name)}toString(){return`$${this.name}`}}class SeqAccessVal extends RenderVal{constructor(seqVal,keyVal){super();this.seqVal=seqVal,this.keyVal=keyVal}toPathItem(){return new SeqAccessStep(this.seqVal.name,this.keyVal.name)}eval(stack){let key=this.keyVal.eval(stack);return this.seqVal.eval(stack)?.get(key,null)}toString(){return`${this.seqVal}[${this.keyVal}]`}}var vp=new ValParser;class Attributes{constructor(items){this.items=items}eval(_stack){return{}}static parse(attributes,px,parseAll=!1){return getAttrParser(px).parse(attributes,parseAll)}isConstant(){return!1}}var booleanAttrsRaw="itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly,async,autofocus,autoplay,controls,default,defer,disabled,hidden,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected",booleanAttrs=new Set(booleanAttrsRaw.split(","));class AttrParser{constructor(px){this.clear(px)}clear(px){this.px=px,this.attrs=null,this.hasDynamic=!1,this.wrapperAttrs=null,this.textChild=null,this.eachAttr=null,this.ifAttr=null,this.events=null}parseAttr(name,value,parseAll=!1){let val=parseAll?vp.parseMacroAttr(value,this.px):vp.parseText(value,this.px);if(val!==null)this.attrs??=[],this.attrs.push(new Attr(name,val)),this.hasDynamic||=!(val instanceof ConstVal);else this.px.onParseIssue("bad-value",{role:"attr",attr:name,value})}pushWrapper(name,raw,val){let node={name,val,raw};return this.wrapperAttrs??=[],this.wrapperAttrs.push(node),node}parseIf(directiveName,value){let dynVal=vp.parseBool(value,this.px);if(dynVal)this.ifAttr=new IfAttr(directiveName.slice(3),dynVal),this.attrs??=[],this.attrs.push(this.ifAttr),this.hasDynamic=!0;else{let info={role:"if",attr:directiveName.slice(3),value};this.px.onParseIssue("bad-value",info)}}parseThen(s){if(this.ifAttr)this.ifAttr.thenVal=vp.parseText(s,this.px)??NOT_SET_VAL}parseElse(value){if(this.ifAttr)this.ifAttr.elseVal=vp.parseText(value,this.px)??NOT_SET_VAL}parseEvent(directiveName,value){let[eventName,...modifiers]=directiveName.slice(3).split("+"),handler=EventHandler.parse(value,this.px);if(handler){if(this.events===null)this.events=this.px.registerEvents(),this.attrs??=[],this.attrs.push(new ConstAttr("data-eid",vp.const(this.events.id)));this.events.add(eventName,handler,modifiers)}}_parseDirectiveValue(directiveName,s,parserFn){let val=parserFn.call(vp,s,this.px);if(val===null){let info={role:"directive",directive:directiveName,value:s};this.px.onParseIssue("bad-value",info)}return val}parseDirective(s,directiveName){switch(directiveName){case"dangerouslysetinnerhtml":this.attrs??=[],this.attrs.push(new RawHtmlAttr(this._parseDirectiveValue(directiveName,s,vp.parseText))),this.hasDynamic=!0;return;case"push-view":this.pushWrapper("push-view",s,this._parseDirectiveValue(directiveName,s,vp.parseText));return;case"text":this.textChild=this._parseDirectiveValue(directiveName,s,vp.parseText);return;case"show":this.pushWrapper("show",s,this._parseDirectiveValue(directiveName,s,vp.parseBool));return;case"hide":this.pushWrapper("hide",s,this._parseDirectiveValue(directiveName,s,vp.parseBool));return;case"each":{let val=this._parseDirectiveValue(directiveName,s,vp.parseSequence);this.eachAttr=this.pushWrapper("each",s,val);return}case"enrich-with":if(this.eachAttr!==null)this.eachAttr.enrichWithVal=this._parseDirectiveValue(directiveName,s,vp.parseAlterHandler);else this.pushWrapper("scope",s,this._parseDirectiveValue(directiveName,s,vp.parseAlterHandler));return;case"when":this._parseWhen(s);return;case"loop-with":this._parseLoopWith(s);return;case"then":this.parseThen(s);return;case"else":this.parseElse(s);return}if(directiveName.startsWith("on."))this.parseEvent(directiveName,s);else if(directiveName.startsWith("if."))this.parseIf(directiveName,s);else if(directiveName.startsWith("then."))this.parseThen(s);else if(directiveName.startsWith("else."))this.parseElse(s);else{let info={name:directiveName,value:s};this.px.onParseIssue("unknown-directive",info)}}_parseWhen(s){if(this.eachAttr!==null)this.eachAttr.whenVal=this._parseDirectiveValue("when",s,vp.parseAlterHandler)}_parseLoopWith(s){if(this.eachAttr!==null)this.eachAttr.loopWithVal=this._parseDirectiveValue("loop-with",s,vp.parseAlterHandler)}parse(attributes,parseAll=!1){for(let{name,value}of attributes){let charCode=name.charCodeAt(0);if(charCode===58)this.parseAttr(name===":viewbox"?"viewBox":name.slice(1),value,parseAll);else if(charCode===64)this.parseDirective(value,name.slice(1));else{this.attrs??=[];let constVal=value===""&&booleanAttrs.has(name)?!0:value;this.attrs.push(new ConstAttr(name,vp.const(constVal)))}}let{attrs,hasDynamic}=this;return[hasDynamic?new DynAttrs(attrs):ConstAttrs.fromAttrs(attrs??[]),this.wrapperAttrs,this.textChild]}}class ConstAttrs extends Attributes{eval(_stack){return this.items}static fromAttrs(attrs){let attrsObj={};for(let attr of attrs)attrsObj[attr.name]=attr.val.eval(null);return new ConstAttrs(attrsObj)}setDataAttr(key,val){this.items[key]=val}toMacroVars(){let r={};for(let name in this.items)r[name]=new ConstVal(`${this.items[name]}`).toString();return r}isConstant(){return!0}}class DynAttrs extends Attributes{eval(stack){let attrs={};for(let i=0;i<this.items.length;i++){let attr=this.items[i];attrs[attr.name]=attr.eval(stack)}return attrs}setDataAttr(key,val){this.items.push(new ConstAttr(key,new ConstVal(val)))}toMacroVars(){let r={};for(let attr of this.items)r[attr.name]=attr.val.toString();return r}}class BaseAttr{constructor(name){this.name=name}}class Attr extends BaseAttr{constructor(name,val){super(name);this.val=val}eval(stack){return this.val.eval(stack)}}class ConstAttr extends Attr{}class RawHtmlAttr extends Attr{constructor(val){super("dangerouslySetInnerHTML",val??vp.nullConstVal)}eval(stack){return{__html:`${this.val.eval(stack)}`}}}var NOT_SET_VAL=vp.nullConstVal;class IfAttr extends BaseAttr{constructor(name,condVal){super(name);this.condVal=condVal,this.thenVal=this.elseVal=NOT_SET_VAL}get anyBranchIsSet(){return this.thenVal!==NOT_SET_VAL||this.elseVal!==NOT_SET_VAL}eval(stack){return this.condVal.eval(stack)?this.thenVal.eval(stack):this.elseVal.eval(stack)}}var _attrParser=null;function getAttrParser(px){return _attrParser??=new AttrParser(px),_attrParser.clear(px),_attrParser}class EventHandler{constructor(handlerVal,args=[]){this.handlerVal=handlerVal,this.args=args}getHandlerAndArgs(stack,_event){let argValues=Array(this.args.length);for(let i=0;i<argValues.length;i++)argValues[i]=this.args[i].eval(stack);return[this.handlerVal.evalAsHandler(stack),argValues]}static parse(s,px){let r=vp.parseInputHandler(s,px);return r===null?null:new EventHandler(r.handlerVal,r.args)}}class RequestHandler{constructor(name,fn){this.name=name,this.fn=fn}}var isWeakKey=(k)=>k!==null&&(typeof k==="object"||typeof k==="function");class NullDomCache{get(_keys,_cacheKey){}set(_keys,_cacheKey,_v){}evict(){return{hit:0,miss:0,badKey:0}}}class WeakMapDomCache{constructor(){this.hit=this.miss=this.badKey=0,this.keysByLen=new Map}_returnValue(r){if(r===void 0)this.miss+=1;else this.hit+=1;return r}get(keys,cacheKey){let len=keys.length,cur=this.keysByLen.get(len);if(!cur)return this._returnValue(void 0);for(let i=0;i<len-1;i++)if(cur=cur.get(keys[i]),!cur)return this._returnValue(void 0);return this._returnValue(cur.get(keys[len-1])?.[cacheKey])}set(keys,cacheKey,v){let len=keys.length,cur=this.keysByLen.get(len);if(!cur)cur=new WeakMap,this.keysByLen.set(len,cur);for(let i=0;i<len-1;i++){let key=keys[i],next=cur.get(key);if(!next){if(!isWeakKey(key)){this.badKey+=1;return}next=new WeakMap,cur.set(key,next)}cur=next}let lastKey=keys[len-1],leaf=cur.get(lastKey);if(leaf)leaf[cacheKey]=v;else if(isWeakKey(lastKey))cur.set(lastKey,{[cacheKey]:v});else this.badKey+=1}evict(){let{hit,miss,badKey}=this;return this.hit=this.miss=this.badKey=0,this.keysByLen=new Map,{hit,miss,badKey}}}var HTML_NS="http://www.w3.org/1999/xhtml";var isNamespaced=(node)=>{let ns=node.namespaceURI;return ns!==null&&ns!=="http://www.w3.org/1999/xhtml"},isForeignObject=(tag)=>tag.length===13&&tag.toLowerCase()==="foreignobject",effectiveNs=(vnode,opts)=>vnode.namespace??opts.namespace??null;function childOpts(vnode,ns,opts){let target=ns==="http://www.w3.org/2000/svg"&&isForeignObject(vnode.tag)?null:ns;return target===(opts.namespace??null)?opts:{...opts,namespace:target}}var NEVER_ASSIGN=new Set(["width","height","href","list","form","tabIndex","download","rowSpan","colSpan","role","popover"]),PROP_ATTR_NAME={className:"class",htmlFor:"for"};function applyProperties(node,props){let namespaced=isNamespaced(node);for(let name in props)setProp2(node,name,props[name],namespaced)}function setProp2(node,name,value,namespaced){if(name==="dangerouslySetInnerHTML"){if(value===void 0)node.replaceChildren();else{let html=value.__html??"";if(html!==node.innerHTML)node.innerHTML=html}return}if(typeof value==="function")return;let usesProp=!namespaced&&!NEVER_ASSIGN.has(name)&&name in node;if(usesProp&&value!=null)try{node[name]=value;return}catch{}if(value==null||value===!1&&name[4]!=="-")if(usesProp){try{node[name]=""}catch{}node.removeAttribute(PROP_ATTR_NAME[name]??name)}else node.removeAttribute(name);else node.setAttribute(name,value)}function applyValueLast(node,value){if(node.tagName==="PROGRESS"&&(value==null||value===0))node.removeAttribute("value");else setProp2(node,"value",value,isNamespaced(node))}class VBase{}var getKey=(child)=>child instanceof VNode2?child.key:void 0,isIterable=(obj)=>obj!=null&&typeof obj!=="string"&&typeof obj[Symbol.iterator]==="function";function childsEqual(a,b){if(a===b)return!0;for(let i=0;i<a.length;i++)if(!a[i].isEqualTo(b[i]))return!1;return!0}function appendChildNodes(parent,childs,opts){for(let child of childs)parent.appendChild(child.toDom(opts))}function addChild(normalizedChildren,child){if(child==null)return;if(isIterable(child))for(let c of child)addChild(normalizedChildren,c);else if(child instanceof VBase)if(child instanceof VFragment)normalizedChildren.push(...child.childs);else normalizedChildren.push(child);else normalizedChildren.push(new VText(child))}class VText extends VBase{constructor(text){super();this.text=String(text)}get nodeType(){return 3}isEqualTo(other){return other instanceof VText&&this.text===other.text}toDom(opts){return opts.document.createTextNode(this.text)}}class VComment extends VBase{constructor(text){super();this.text=text}get nodeType(){return 8}isEqualTo(other){return other instanceof VComment&&this.text===other.text}toDom(opts){return opts.document.createComment(this.text)}}class VFragment extends VBase{constructor(childs){super();this.childs=[],addChild(this.childs,childs)}get nodeType(){return 11}isEqualTo(other){if(!(other instanceof VFragment)||this.childs.length!==other.childs.length)return!1;return childsEqual(this.childs,other.childs)}toDom(opts){let fragment=opts.document.createDocumentFragment();return appendChildNodes(fragment,this.childs,opts),fragment}}class VNode2 extends VBase{constructor(tag,attrs,childs,key,namespace){super();this.tag=tag,this.attrs=attrs??{},this.childs=childs??[],this.key=key!=null?String(key):void 0,this.namespace=typeof namespace==="string"?namespace:null}get nodeType(){return 1}isSameKind(other){return this.tag===other.tag&&this.namespace===other.namespace&&this.key===other.key}isEqualTo(other){if(this===other)return!0;if(!(other instanceof VNode2)||!this.isSameKind(other)||this.childs.length!==other.childs.length)return!1;if(this.attrs!==other.attrs){for(let key in this.attrs)if(this.attrs[key]!==other.attrs[key])return!1;for(let key in other.attrs)if(!Object.hasOwn(this.attrs,key))return!1}return childsEqual(this.childs,other.childs)}toDom(opts){let doc=opts.document,ns=effectiveNs(this,opts),tag=ns!==null&&this.tag===this.tag.toUpperCase()?this.tag.toLowerCase():this.tag,attrs=this.attrs,createOpts=attrs.is!=null?{is:attrs.is}:void 0,node=ns===null?doc.createElement(tag,createOpts):doc.createElementNS(ns,tag,createOpts),cOpts=childOpts(this,ns,opts);if("value"in attrs||"checked"in attrs){let{value,checked,...rest}=attrs;if(applyProperties(node,rest),appendChildNodes(node,this.childs,cOpts),value!==void 0)applyValueLast(node,value);if(checked!==void 0)setProp2(node,"checked",checked,!1)}else applyProperties(node,attrs),appendChildNodes(node,this.childs,cOpts);return node}}function diffProps(a,b){if(a===b)return null;let diff=null;for(let aKey in a)if(!Object.hasOwn(b,aKey))diff??={},diff[aKey]=void 0;else if(a[aKey]!==b[aKey])diff??={},diff[aKey]=b[aKey];for(let bKey in b)if(!Object.hasOwn(a,bKey))diff??={},diff[bKey]=b[bKey];return diff}function morphNode(domNode,source,target,opts){if(source===target||source.isEqualTo(target))return domNode;let type=source.nodeType;if(type===target.nodeType){if(type===3||type===8)return domNode.data=target.text,domNode;if(type===1&&source.isSameKind(target)){let propsDiff=diffProps(source.attrs,target.attrs),hasValue=propsDiff!=null&&"value"in propsDiff,hasChecked=propsDiff!=null&&"checked"in propsDiff;if(propsDiff)if(hasValue||hasChecked){let{value:_v,checked:_c,...rest}=propsDiff;applyProperties(domNode,rest)}else applyProperties(domNode,propsDiff);if(!target.attrs.dangerouslySetInnerHTML){let ns=effectiveNs(target,opts);morphChildren(domNode,source.childs,target.childs,childOpts(target,ns,opts))}if(hasValue)applyValueLast(domNode,propsDiff.value);else if(source.tag==="SELECT"&&target.attrs.value!==void 0)applyValueLast(domNode,target.attrs.value);if(hasChecked)setProp2(domNode,"checked",propsDiff.checked,!1);return domNode}if(type===11)return morphChildren(domNode,source.childs,target.childs,opts),domNode}let newNode=target.toDom(opts);return domNode.parentNode?.replaceChild(newNode,domNode),newNode}function morphChildren(parentDom,oldChilds,newChilds,opts){if(oldChilds.length===0){appendChildNodes(parentDom,newChilds,opts);return}if(newChilds.length===0){parentDom.replaceChildren();return}if(oldChilds.length===newChilds.length){let hasKey=!1;for(let i=0;i<oldChilds.length;i++)if(getKey(oldChilds[i])!=null||getKey(newChilds[i])!=null){hasKey=!0;break}if(!hasKey){let dom=parentDom.firstChild;for(let i=0;i<oldChilds.length;i++){let next=dom.nextSibling;morphNode(dom,oldChilds[i],newChilds[i],opts),dom=next}return}}let domNodes=Array.from(parentDom.childNodes),oldKeyMap=Object.create(null);for(let i=0;i<oldChilds.length;i++){let key=getKey(oldChilds[i]);if(key!=null)oldKeyMap[key]=i}let used=new Uint8Array(oldChilds.length),unkeyedCursor=0;for(let j=0;j<newChilds.length;j++){let newChild=newChilds[j],newKey=getKey(newChild),oldIdx=-1;if(newKey!=null){if(newKey in oldKeyMap&&!used[oldKeyMap[newKey]])oldIdx=oldKeyMap[newKey]}else while(unkeyedCursor<oldChilds.length){if(!used[unkeyedCursor]&&getKey(oldChilds[unkeyedCursor])==null){oldIdx=unkeyedCursor++;break}unkeyedCursor++}if(oldIdx>=0){used[oldIdx]=1;let newDom=morphNode(domNodes[oldIdx],oldChilds[oldIdx],newChild,opts),ref=parentDom.childNodes[j]??null;if(newDom!==ref)parentDom.insertBefore(newDom,ref)}else{let ref=parentDom.childNodes[j]??null;parentDom.insertBefore(newChild.toDom(opts),ref)}}for(let i=oldChilds.length-1;i>=0;i--)if(!used[i]&&domNodes[i].parentNode===parentDom)parentDom.removeChild(domNodes[i])}function render(vnode,container,options,prev){let isFragment=vnode instanceof VFragment;if(prev&&prev.vnode instanceof VFragment===isFragment){let oldDom=isFragment?container:prev.dom,newDom=morphNode(oldDom,prev.vnode,vnode,options);return{vnode,dom:isFragment?container:newDom}}let domNode=vnode.toDom(options);return container.replaceChildren(domNode),{vnode,dom:isFragment?container:domNode}}function h(tagName,properties,children,namespace){let props={},key;if(properties)for(let propName in properties){let propVal=properties[propName];if(propName==="key")key=propVal;else if(propName==="namespace")namespace=namespace??propVal;else props[propName]=propVal}if(namespace==null){let lower=tagName.toLowerCase();if(lower==="svg")namespace="http://www.w3.org/2000/svg",tagName="svg";else if(lower==="math")namespace="http://www.w3.org/1998/Math/MathML",tagName="math"}let c=tagName.charCodeAt(0),tag=namespace==null&&c>=97&&c<=122&&tagName===tagName.toLowerCase()?tagName.toUpperCase():tagName,normalizedChildren=[];return addChild(normalizedChildren,children),new VNode2(tag,props,normalizedChildren,key,namespace)}var DATASET_ATTRS=["nid","cid","eid","vid","si","sk"];class Renderer{constructor(comps){this.comps=comps,this.cache=new WeakMapDomCache,this.renderTag=h}renderFragment(childs){return new VFragment(childs)}renderComment(text){return new VComment(text)}setNullCache(){this.cache=new NullDomCache}renderToDOM(stack,val){let rootNode=document.createElement("div"),rOpts={document};return render(h("DIV",null,[this.renderRoot(stack,val)]),rootNode,rOpts),rootNode.childNodes[0]}renderToString(stack,val,cleanAttrs=!0){let dom=this.renderToDOM(stack,val);if(cleanAttrs){let nodes=dom.querySelectorAll("[data-nid],[data-cid],[data-eid]");for(let{dataset}of nodes)for(let name of DATASET_ATTRS)delete dataset[name]}return dom.innerHTML}renderRoot(stack,val,viewName=null){let comp=this.comps.getCompFor(val);if(comp===null)return null;return this._rValComp(stack,val,comp,comp.getView(viewName).anode,"ROOT",viewName)}renderIt(stack,node,key,viewName){let comp=this.comps.getCompFor(stack.it);return comp?this._rValComp(stack,stack.it,comp,node,key,viewName):null}_rValComp(stack,val,comp,node,key,viewName){let cacheKey=`${viewName??""}\x1F${stack.viewsId??""}\x1F${key}`,cachePath=[node,val];stack._pushDynBindValuesToArray(cachePath,comp);let cachedNode=this.cache.get(cachePath,cacheKey);if(cachedNode)return cachedNode;let view=viewName?comp.getView(viewName):stack.lookupBestView(comp.views,"main"),body=this.renderView(view,stack);if(body==null)return null;let meta=this._renderMetadata({$:"Comp",nid:node?.nodeId??null,cid:comp.id,vid:view.name}),dom=new VFragment([meta,body]);return this.cache.set(cachePath,cacheKey,dom),dom}pushEachEntry(r,nid,attrName,key,dom){r.push(this._renderMetadata({$:"Each",nid,[attrName]:key}),dom)}renderEachWhen(stack,iterInfo,view,nid){let{seq,filter,loopWith,enricher}=iterInfo.eval(stack),r=[],it=stack.it,{iterData,start,end,keys}=unpackLoopResult(loopWith.call(it,seq,makeLoopCtx(stack,filter)),seq),renderOne=(key,value,attrName)=>{let cachePath=enricher?[view,it,value]:[view,value],binds={key,value},cacheKey=`${stack.viewsId??""}\x1F${nid}\x1F${key}`;if(enricher)callEnricher(enricher,it,binds,key,value,iterData);let cachedNode=this.cache.get(cachePath,cacheKey);if(cachedNode)this.pushEachEntry(r,nid,attrName,key,cachedNode);else{let dom=this.renderView(view,stack.enter(value,binds,!1));if(dom!=null)this.pushEachEntry(r,nid,attrName,key,dom);this.cache.set(cachePath,cacheKey,dom)}};if(keys)imKeysIter(seq,renderOne,keys);else getSeqInfo(seq)(seq,(key,value,attrName)=>{if(filter.call(it,key,value,iterData))renderOne(key,value,attrName)},start,end);return r}renderView(view,stack){let n=stack.binds[1];while(n!==null){let b=n[0];if(b.isFrame){if(stack.it!==b.it)break;return console.error("recursion detected",stack.it,b.it),new VComment("RECURSION AVOIDED")}n=n[1]}return view.render(stack,this)}_renderMetadata(info){return new VComment(`§${JSON.stringify(info)}§`)}renderScopeMeta(nid,dom){return new VFragment([this._renderMetadata({$:"Scope",nid}),dom])}}var getSeqInfo=(seq)=>isIndexed(seq)?imIndexedIter:isKeyed(seq)?imKeyedIter:seq?.[SEQ_INFO]??unkIter,normalizeRange=(start,end,size)=>{let s=start==null?0:start<0?size+start:start,e=end==null?size:end<0?size+end:end;return s=s<0?0:s>size?size:s,e=e<0?0:e>size?size:e,[s,e<s?s:e]},callEnricher=(enricher,it,binds,key,value,iterData)=>{enricher.call(it,binds,key,value,iterData),console.assert(binds.key===key&&binds.value===value,"@enrich-with handlers must not overwrite binds.key or binds.value"),binds.key=key,binds.value=value},filterAlwaysTrue=(_v,_k,_seq)=>!0,nullLoopWith=(seq)=>({iterData:{seq}}),unpackLoopResult=(result,seq)=>{let r=result??{};return{iterData:r.iterData??{seq},start:r.start,end:r.end,keys:r.keys}},imKeysIter=(seq,visit,keys)=>{let attrName=isIndexed(seq)?"si":"sk";for(let key of keys)visit(key,seq.get(key),attrName)},makeLoopCtx=(stack,filter)=>({lookup:(name)=>stack.lookupBind(name),filter:(key,value,iterData)=>filter.call(stack.it,key,value,iterData)}),imIndexedIter=(seq,visit,start,end)=>{let[s,e]=normalizeRange(start,end,seq.size);for(let i=s;i<e;i++)visit(i,seq.get(i),"si")},imKeyedIter=(seq,visit,start,end)=>{let[s,e]=normalizeRange(start,end,seq.size),i=0;for(let[k,v]of seq.toSeq().entries()){if(i>=e)break;if(i>=s)visit(k,v,"sk");i++}},unkIter=()=>{},SEQ_INFO=Symbol.for("tutuca.seqInfo");var isMac=(globalThis.navigator?.userAgent??"").toLowerCase().includes("mac");function resolveDynProducer(comp,name){let producerComp,producerProvide,lk=comp?.lookup?.[name];if(lk!=null)producerComp=comp.scope?.lookupComponent(lk.compName),producerProvide=producerComp?.provide?.[lk.provideName];else{let p=comp?.provide?.[name];if(p==null)return null;producerComp=comp,producerProvide=p}if(producerComp==null||producerProvide==null)return null;let pi=producerProvide.val?.toPathItem?.()??null;return{producerCompId:producerComp.id,producerSteps:pi?[pi]:[]}}class BaseNode{render(_stack,_rx){return null}setDataAttr(key,val){console.warn("setDataAttr not implemented for",this,{key,val})}isConstant(){return!1}isWhiteSpace(){return!1}optimize(){}}class TextNode extends BaseNode{constructor(val){super();this.val=val}render(_stack,_rx){return this.val}isWhiteSpace(){for(let i=0;i<this.val.length;i++){let c=this.val.charCodeAt(i);if(!(c===32||c===10||c===9||c===13))return!1}return!0}hasNewLine(){for(let i=0;i<this.val.length;i++){let c=this.val.charCodeAt(i);if(c===10||c===13)return!0}return!1}condenseWhiteSpace(replacement=""){this.val=replacement}isConstant(){return!0}setDataAttr(_key,_val){}}class CommentNode extends TextNode{render(_stack,rx){return rx.renderComment(this.val)}}function optimizeChilds(childs){for(let i=0;i<childs.length;i++){let child=childs[i];if(child.isConstant())childs[i]=new RenderOnceNode(child);else child.optimize()}}function optimizeNode(node){if(node.isConstant())return new RenderOnceNode(node);return node.optimize(),node}class ChildsNode extends BaseNode{constructor(childs){super();this.childs=childs}isConstant(){return this.childs.every((v)=>v.isConstant())}optimize(){optimizeChilds(this.childs)}}class DomNode extends ChildsNode{constructor(tagName,attrs,childs,namespace=null){super(childs);this.tagName=tagName,this.attrs=attrs,this.namespace=namespace}render(stack,rx){let childNodes=Array(this.childs.length);for(let i=0;i<childNodes.length;i++)childNodes[i]=this.childs[i]?.render?.(stack,rx)??null;return rx.renderTag(this.tagName,this.attrs.eval(stack),childNodes,this.namespace)}setDataAttr(key,val){this.attrs.setDataAttr(key,val)}isConstant(){return this.attrs.isConstant()&&super.isConstant()}}class FragmentNode extends ChildsNode{render(stack,rx){return rx.renderFragment(this.childs.map((c)=>c?.render(stack,rx)))}setDataAttr(key,val){for(let child of this.childs)child.setDataAttr(key,val)}}var maybeFragment=(xs)=>xs.length===1?xs[0]:new FragmentNode(xs),VALID_NODE_RE=/^[a-zA-Z][a-zA-Z0-9-]*$/;class ANode extends BaseNode{constructor(nodeId,val){super();this.nodeId=nodeId,this.val=val}toPathStep(ctx){return ctx.applyKey(this.val?.toPathItem?.()??null)}static parse(html,px){let nodes=px.parseHTML(html);if(nodes.length===0)return new CommentNode("Empty View in ANode.parse");if(nodes.length===1)return ANode.fromDOM(nodes[0],px);let childs=[];for(let i=0;i<nodes.length;i++){let child=ANode.fromDOM(nodes[i],px);if(child!==null)childs.push(child)}let trimmed=condenseChildsWhites(childs);if(trimmed.length===0)return new CommentNode("Empty View in ANode.parse");return maybeFragment(trimmed)}static fromDOM(node,px){if(node instanceof px.Text)return new TextNode(node.textContent);else if(node instanceof px.Comment)return new CommentNode(node.textContent);let{childNodes,attributes:attrs,tagName:tag}=node,childs=[];for(let i=0;i<childNodes.length;i++){let child=ANode.fromDOM(childNodes[i],px);if(child!==null)childs.push(child)}let prevTag=px.currentTag;px.currentTag=tag;try{let isPseudoX=attrs[0]?.name==="@x";if(tag==="X"||isPseudoX)return parseXOp(attrs,childs,isPseudoX?1:0,px);else if(tag.charCodeAt(1)===58&&(tag.charCodeAt(0)===88||tag.charCodeAt(0)===120)){let macroName=tag.slice(2).toLowerCase();if(macroName==="slot"){let slotName=attrs.getNamedItem("name")?.value??"_";return px.frame.macroSlots[slotName]??maybeFragment(childs)}let[nAttrs,wrappers]=Attributes.parse(attrs,px,!0);return px.onAttributes(nAttrs,wrappers,null,!0,tag),wrap(px.newMacroNode(macroName,nAttrs.toMacroVars(),childs),px,wrappers)}else if(VALID_NODE_RE.test(tag)){let[nAttrs,wrappers,textChild]=Attributes.parse(attrs,px);if(px.onAttributes(nAttrs,wrappers,textChild,!1,tag),textChild)childs.unshift(new RenderTextNode(null,textChild));let domChilds=tag!=="PRE"?condenseChildsWhites(childs):childs,ns=node.namespaceURI;return wrap(new DomNode(tag,nAttrs,domChilds,ns&&ns!==HTML_NS?ns:null),px,wrappers)}return new CommentNode(`Error: InvalidTagName ${tag}`)}finally{px.currentTag=prevTag}}}function parseXOp(attrs,childs,opIdx,px){if(attrs.length<=opIdx)return maybeFragment(childs);let{name,value}=attrs[opIdx];if(X_OPS[name]?.ignoresChildren&&hasMeaningfulChilds(childs))px.onParseIssue("x-op-ignores-children",{op:name});let asAttr=attrs.getNamedItem("as")?.value??null,as=asAttr===null?null:parseViewName(asAttr,px),node;switch(name){case"slot":node=new SlotNode(null,vp.const(value),maybeFragment(childs));break;case"text":node=px.addNodeIf(RenderTextNode,parseXOpVal(name,value,px,vp.parseText));break;case"render":node=px.addNodeIf(RenderNode,parseXOpVal(name,value,px,vp.parseComponent),as);break;case"render-it":node=px.addNode(RenderItNode,as);break;case"render-each":node=parseRenderEach(px,value,as,attrs);break;case"show":{let val=parseXOpVal(name,value,px,vp.parseBool);node=px.addNodeIf(ShowNode,val,maybeFragment(childs));break}case"hide":{let val=parseXOpVal(name,value,px,vp.parseBool);node=px.addNodeIf(HideNode,val,maybeFragment(childs));break}default:return px.onParseIssue("unknown-x-op",{name,value}),new CommentNode(`Error: InvalidSpecialTagOp ${name}=${value}`)}return processXExtras(node,attrs,name,opIdx+1,px)}function parseXOpVal(opName,value,px,parserFn){let val=parserFn.call(vp,value,px);if(val===null)px.onParseIssue("bad-value",{role:"x-op",op:opName,value});return val}function parseViewName(s,px){return vp.parseText(s,px)??vp.const(s)}function processXExtras(node,attrs,opName,startIdx,px){let{consumed,wrappable}=X_OPS[opName],wrappers=[];for(let i=startIdx;i<attrs.length;i++){let a=attrs[i],aName=a.name;if(consumed.has(aName))continue;let atPrefixed=aName.charCodeAt(0)===64,baseName=atPrefixed?aName.slice(1):aName,wrapper=wrappable?X_OPS[baseName]?.wrapper:null;if(wrapper){if(!atPrefixed)maybeDeprecateBareXDirective(px,opName,baseName);wrappers.push([wrapper,vp.parseBool(a.value,px)]);continue}let issueInfo={op:opName,name:aName,value:a.value};px.onParseIssue("unknown-x-attr",issueInfo)}for(let i=wrappers.length-1;i>=0;i--){let[Cls,val]=wrappers[i],wrapper=px.addNodeIf(Cls,val,node);if(wrapper!==null)node=wrapper}return node}function maybeDeprecateBareXDirective(px,opName,name){px.onDeprecatedSyntax("bare-x-directive",{op:opName,name})}function wrap(node,px,wrappers){if(wrappers)for(let i=wrappers.length-1;i>=0;i--){let wrapperNode=makeWrapperNode(wrappers[i],px);if(wrapperNode)wrapperNode.wrapNode(node),node=wrapperNode}return node}function makeWrapperNode(data,px){let Cls=WRAPPER_NODES[data.name],node=Cls.register?px.addNodeIf(Cls,data.val):data.val&&new Cls(null,data.val);if(node!==null&&data.name==="each")node.iterInfo.enrichWithVal=data.enrichWithVal??null,node.iterInfo.whenVal=data.whenVal??null,node.iterInfo.loopWithVal=data.loopWithVal??null;return node}class MacroNode extends BaseNode{constructor(name,attrs,slots,px){super();this.name=name,this.attrs=attrs,this.slots=slots,this.px=px,this.node=null,this.dataAttrs={}}compile(scope){let{name,attrs,slots}=this;if(this.px.isInsideMacro(name))throw Error(`Recursive macro expansion: ${name}`);let macro=scope.lookupMacro(name);if(macro===null)this.node=new CommentNode(`bad macro: ${name}`);else{let vars={...macro.defaults,...attrs};this.node=macro.expand(this.px.enterMacro(name,vars,slots));for(let key in this.dataAttrs)this.node.setDataAttr(key,this.dataAttrs[key])}}render(stack,rx){return this.node.render(stack,rx)}setDataAttr(key,val){this.dataAttrs[key]=val}isConstant(){return this.node.isConstant()}optimize(){this.node=optimizeNode(this.node)}}class Macro{constructor(defaults,rawView){this.defaults=defaults,this.rawView=rawView}expand(px){return ANode.parse(this.rawView,px)}}class RenderViewId extends ANode{constructor(nodeId,val,viewVal){super(nodeId,val);this.viewVal=viewVal}evalViewName(stack){return this.viewVal?this.viewVal.eval(stack):null}setDataAttr(_key,_val){}}function dynRenderStep(comp,name,key){let p=resolveDynProducer(comp,name);if(!p)return null;return key===void 0?new DynStep(p.producerCompId,p.producerSteps):new DynEachStep(p.producerCompId,p.producerSteps,key)}class RenderNode extends RenderViewId{render(stack,rx){let newStack=stack.enter(this.val.eval(stack),{},!0);return rx.renderIt(newStack,this,"",this.evalViewName(stack))}toPathStep(ctx){if(this.val instanceof DynVal)return dynRenderStep(ctx.comp,this.val.name);return super.toPathStep(ctx)}}class RenderItNode extends RenderViewId{render(stack,rx){let newStack=stack.enter(stack.it,{},!0);return rx.renderIt(newStack,this,"",this.evalViewName(stack))}toPathStep(ctx){let next=ctx.next();if(next===null)return null;let nextNode=next.resolveNode();if(nextNode instanceof EachNode&&next.hasKey){if(nextNode.val instanceof DynVal)return dynRenderStep(ctx.comp,nextNode.val.name,next.key);return new EachRenderItStep(nextNode.val.name,next.key)}return null}}function parseRenderEach(px,value,as,attrs){let seqVal=parseXOpVal("render-each",value,px,vp.parseSequence);if(seqVal===null)return null;let renderIt=px.addNode(RenderItNode,as),attrParser=getAttrParser(px),eachAttr=attrParser.eachAttr=attrParser.pushWrapper("each",value,seqVal),when=attrs.getNamedItem("@when")??attrs.getNamedItem("when");if(when){if(when.name.charCodeAt(0)!==64)maybeDeprecateBareXDirective(px,"render-each","when");attrParser._parseWhen(when.value)}let lWith=attrs.getNamedItem("@loop-with")??attrs.getNamedItem("loop-with");if(lWith){if(lWith.name.charCodeAt(0)!==64)maybeDeprecateBareXDirective(px,"render-each","loop-with");attrParser._parseLoopWith(lWith.value)}let each=px.addNodeIf(EachNode,seqVal);return each.iterInfo.whenVal=eachAttr.whenVal??null,each.iterInfo.loopWithVal=eachAttr.loopWithVal??null,each.fromRenderEach=!0,each.wrapNode(renderIt),each}class RenderTextNode extends ANode{render(stack,_rx){return this.val.eval(stack)}setDataAttr(_key,_val){}}class RenderOnceNode extends BaseNode{constructor(node){super();this.node=node,this._render=(stack,rx)=>{let dom=node.render(stack,rx);return this._render=(_stack,_rx)=>dom,dom}}render(stack,rx){return this._render(stack,rx)}}class WrapperNode extends ANode{constructor(nodeId,val,node=null){super(nodeId,val);this.node=node}wrapNode(node){this.node=node}setDataAttr(key,val){this.node.setDataAttr(key,val)}optimize(){this.node=optimizeNode(this.node)}static register=!1}class ShowNode extends WrapperNode{render(stack,rx){return this.val.eval(stack)?this.node.render(stack,rx):null}}class HideNode extends WrapperNode{render(stack,rx){return this.val.eval(stack)?null:this.node.render(stack,rx)}}class PushViewNameNode extends WrapperNode{render(stack,rx){return this.node.render(stack.pushViewName(this.val.eval(stack)),rx)}}class SlotNode extends WrapperNode{isSlotNode=!0;optimize(){this.node.optimize()}}class ScopeNode extends WrapperNode{render(stack,rx){let binds=this.val.evalAsHandler(stack)?.call(stack.it)??{},dom=this.node.render(stack.enter(stack.it,binds,!1),rx);return rx.renderScopeMeta(this.nodeId,dom)}toPathStep(_ctx){return new ScopeBindStep(this.val)}wrapNode(node){this.node=node,this.node.setDataAttr("data-nid",this.nodeId)}static register=!0}class EachNode extends WrapperNode{constructor(nodeId,val){super(nodeId,val);this.iterInfo=new IterInfo(val,null,null,null)}render(stack,rx){return rx.renderEachWhen(stack,this.iterInfo,this.node,this.nodeId)}toPathStep(ctx){return ctx.hasKey?new EachBindStep(this.iterInfo,ctx.key):null}static register=!0}class IterInfo{constructor(val,whenVal,loopWithVal,enrichWithVal){this.val=val,this.whenVal=whenVal,this.loopWithVal=loopWithVal,this.enrichWithVal=enrichWithVal}eval(stack){let seq=this.val.eval(stack)??[],filter=this.whenVal?.evalAsHandler(stack)??filterAlwaysTrue,loopWith=this.loopWithVal?.evalAsHandler(stack)??nullLoopWith,enricher=this.enrichWithVal?.evalAsHandler(stack)??null;return{seq,filter,loopWith,enricher}}enrichBinds(stack,key){let{seq,filter,loopWith,enricher}=this.eval(stack),value=seq?.get?seq.get(key,null):null,binds={key,value};if(enricher){let{iterData}=unpackLoopResult(loopWith.call(stack.it,seq,makeLoopCtx(stack,filter)),seq);callEnricher(enricher,stack.it,binds,key,value,iterData)}return binds}}function xOp(consumed=[],{wrappable=!1,wrapper=null,ignoresChildren=!1}={}){return{consumed:new Set(consumed),wrappable,wrapper,ignoresChildren}}var X_OPS={slot:xOp(),text:xOp([],{wrappable:!0,ignoresChildren:!0}),render:xOp(["as"],{wrappable:!0,ignoresChildren:!0}),"render-it":xOp(["as"],{wrappable:!0,ignoresChildren:!0}),"render-each":xOp(["as","when","loop-with","@when","@loop-with"],{wrappable:!0,ignoresChildren:!0}),show:xOp([],{wrapper:ShowNode}),hide:xOp([],{wrapper:HideNode})},WRAPPER_NODES={show:ShowNode,hide:HideNode,each:EachNode,scope:ScopeNode,"push-view":PushViewNameNode};class ParseContext{constructor(document2,Text,Comment,nodes,events,macroNodes,frame,parent){this.nodes=nodes??[],this.events=events??[],this.macroNodes=macroNodes??[],this.parent=parent??null,this.frame=frame??{},this.document=document2??globalThis.document,this.Text=Text??globalThis.Text,this.Comment=Comment??globalThis.Comment,this.cacheConstNodes=!0,this.currentTag=null}isInsideMacro(name){return this.frame.macroName===name||this.parent?.isInsideMacro(name)}enterMacro(macroName,macroVars,macroSlots){let{document:document2,Text,Comment,nodes,events,macroNodes}=this;return new ParseContext(document2,Text,Comment,nodes,events,macroNodes,{macroName,macroVars,macroSlots},this)}parseHTML(html){let t=this.document.createElement("template");return t.innerHTML=html,t.content.childNodes}addNodeIf(Class,val,extra){if(val!==null){let nodeId=this.nodes.length,node=new Class(nodeId,val,extra);return this.nodes.push(node),node}return null}addNode(Class,extra){let nodeId=this.nodes.length,node=new Class(nodeId,null,extra);return this.nodes.push(node),node}registerEvents(){let id=this.events.length,events=new NodeEvents(id);return this.events.push(events),events}newMacroNode(macroName,mAttrs,childs){let anySlot=[],slots={_:new FragmentNode(anySlot)};for(let child of childs)if(child.isSlotNode)slots[child.val.val]=child.node;else if(!child.isWhiteSpace())anySlot.push(child);let node=new MacroNode(macroName,mAttrs,slots,this);return this.macroNodes.push(node),node}compile(scope){for(let i=0;i<this.macroNodes.length;i++)this.macroNodes[i].compile(scope)}*genEventNames(){for(let event of this.events)yield*event.genEventNames()}getEventForId(id){return this.events[id]??null}getNodeForId(id){return this.nodes[id]??null}onAttributes(_attrs,_wrapperAttrs,_textChild,_isMacroCall,_tag){}onParseIssue(kind,info){console.warn(`tutuca parse issue [${kind}]`,info)}onDeprecatedSyntax(_kind,_info){}}var _htmlBlockTags="ADDRESS,ARTICLE,ASIDE,BLOCKQUOTE,CAPTION,COL,COLGROUP,DETAILS,DIALOG,DIV,DD,DL,DT,FIELDSET,FIGCAPTION,FIGURE,FOOTER,FORM,H1,H2,H3,H4,H5,H6,HEADER,HGROUP,HR,LEGEND,LI,MAIN,MENU,NAV,OL,P,PRE,SECTION,SUMMARY,TABLE,TBODY,TD,TFOOT,TH,THEAD,TR,UL",HTML_BLOCK_TAGS=new Set(_htmlBlockTags.split(",")),isBlockDomNode=(n)=>{let node=n instanceof FragmentNode?n.childs[0]:n;return node instanceof DomNode&&HTML_BLOCK_TAGS.has(node.tagName)},isEmptyText=(c)=>c instanceof TextNode&&c.val==="",isIgnorableXChild=(c)=>c instanceof CommentNode||(c.isWhiteSpace?.()??!1),hasMeaningfulChilds=(childs)=>childs.some((c)=>!isIgnorableXChild(c));function trimEdgeWhite(node){if(!node.isWhiteSpace?.())return!1;return node.condenseWhiteSpace(),!0}function condenseChildsWhites(childs){if(childs.length===0)return childs;let last=childs.length-1,emptied=trimEdgeWhite(childs[0]);if(last>0&&trimEdgeWhite(childs[last]))emptied=!0;for(let i=1;i<last;i++){let cur=childs[i];if(!(cur.isWhiteSpace?.()&&cur.hasNewLine()))continue;let bothBlock=isBlockDomNode(childs[i-1])&&isBlockDomNode(childs[i+1]);if(cur.condenseWhiteSpace(bothBlock?"":" "),bothBlock)emptied=!0}return emptied?childs.filter((c)=>!isEmptyText(c)):childs}class View{constructor(name,rawView="No View Defined",style="",anode=null,ctx=null){this.name=name,this.anode=anode,this.style=style,this.ctx=ctx,this.rawView=rawView}compile(ctx,scope,cid){if(this.ctx=ctx,this.anode=ANode.parse(this.rawView,ctx),this.anode.setDataAttr("data-cid",cid),this.anode.setDataAttr("data-vid",this.name),this.ctx.compile(scope),ctx.cacheConstNodes)this.anode=optimizeNode(this.anode)}render(stack,rx){if(this.anode===null)throw Error(`tutuca: view "${this.name}" was rendered before it was compiled — its `+`component is not registered in this app/scope. Source: ${String(this.rawView).slice(0,80).replace(/\s+/g," ")}…`);return this.anode.render(stack,rx)}}class NodeEvents{constructor(id){this.id=id,this.handlers=[]}add(name,handlerCall,modifiers){this.handlers.push(new NodeEvent(name,handlerCall,modifiers))}*genEventNames(){for(let handler of this.handlers)yield handler.name}getHandlersFor(eventName){let r=null;for(let handler of this.handlers)if(handler.handlesEventName(eventName))r??=[],r.push(handler);return r}}class NodeEvent{constructor(name,handlerCall,modifiers){this.name=name,this.handlerCall=handlerCall,this.modifierWrapper=compileModifiers(name,modifiers),this.modifiers=modifiers}handlesEventName(name){return this.name===name}getHandlerAndArgs(stack,event){let r=this.handlerCall.getHandlerAndArgs(stack,event);return r[0]=this.modifierWrapper(r[0],event),r}}var fwdIfCtxPred=(pred)=>(w)=>(that,f,args,ctx)=>pred(ctx)?w(that,f,args,ctx):that,fwdIfKey=(keyName)=>fwdIfCtxPred((ctx)=>ctx.e.key===keyName),fwdCtrl=fwdIfCtxPred(({e})=>isMac&&e.metaKey||e.ctrlKey),fwdMeta=fwdIfCtxPred(({e})=>e.metaKey),fwdAlt=fwdIfCtxPred(({e})=>e.altKey),metaWraps={ctrl:fwdCtrl,cmd:fwdCtrl,meta:fwdMeta,alt:fwdAlt},MOD_WRAPPERS_BY_EVENT={keydown:{send:fwdIfKey("Enter"),cancel:fwdIfKey("Escape"),...metaWraps},click:{...metaWraps}},identityModifierWrapper=(f,_ctx)=>f;function compileModifiers(eventName,names){if(names.length===0)return identityModifierWrapper;let wrappers=MOD_WRAPPERS_BY_EVENT[eventName]??{},w=(that,f,args,_ctx)=>f.apply(that,args);for(let name of names){let wrapper=wrappers[name];if(wrapper!==void 0)w=wrapper(w)}return(f,ctx)=>function(...args){return w(this,f,args,ctx)}}class Components{constructor(){this.getComponentSymbol=Symbol("getComponent"),this.byId=new Map}registerComponent(comp){comp.Class.prototype[this.getComponentSymbol]=()=>comp,this.byId.set(comp.id,comp)}getComponentForId(id){return this.byId.get(id)??null}getCompFor(v){return v?.[this.getComponentSymbol]?.()??null}getHandlerFor(v,name,key){return this.getCompFor(v)?.[key][name]??null}getRequestFor(v,name){return this.getCompFor(v)?.scope.lookupRequest(name)??null}compileStyles(){let styles=[];for(let comp of this.byId.values())styles.push(comp.compileStyle());return styles.join(`
2
- `)}}class ComponentStack{constructor(comps=new Components,parent=null){this.comps=comps,this.parent=parent,this.byName={},this.reqsByName={},this.macros={}}enter(){return new ComponentStack(this.comps,this)}registerComponents(comps,opts){let{aliases={}}=opts??{};for(let i=0;i<comps.length;i++){let comp=comps[i];comp.scope=this.enter(),comp.Class.scope=comp.scope,this.comps.registerComponent(comp),this.byName[comp.name]=comp}for(let alias in aliases){let comp=this.byName[aliases[alias]];if(console.assert(this.byName[alias]===void 0,"alias overrides component",alias),comp!==void 0)this.byName[alias]=comp;else console.warn("alias",alias,"to inexistent component",aliases[alias])}}registerMacros(macros){for(let key in macros){let lower=key.toLowerCase();console.assert(this.macros[lower]===void 0,"macro key collision",lower),this.macros[lower]=macros[key]}}getCompFor(v){return this.comps.getCompFor(v)}registerRequestHandlers(handlers){for(let name in handlers)this.reqsByName[name]=new RequestHandler(name,handlers[name])}lookupRequest(name){return this.reqsByName[name]??this.parent?.lookupRequest(name)??null}lookupComponent(name){return this.byName[name]??this.parent?.lookupComponent(name)??null}lookupMacro(name){return this.macros[name]??this.parent?.lookupMacro(name)??null}}class ProvideInfo{constructor(name,val,symbol){this.name=name,this.val=val,this.symbol=symbol}}class LookupInfo{constructor(name,compName,provideName,val){this.name=name,this.compName=compName,this.provideName=provideName,this.val=val,this._sym=void 0}getProducerSymbol(stack){if(this._sym===void 0)this._sym=stack.lookupType(this.compName)?.provide?.[this.provideName]?.symbol??null;return this._sym}}var isString=(v)=>typeof v==="string",_rawSpecKeys="name view style commonStyle globalStyle input receive bubble response alter views provide lookup fields methods statics",KNOWN_SPEC_KEYS=new Set(_rawSpecKeys.split(" ")),_compId=0;class Component{constructor(Class,o){this.id=_compId++,this.name=o.name??"UnkComp",this.Class=Class,this.views={main:new View("main",o.view,o.style)},this.commonStyle=o.commonStyle??"",this.globalStyle=o.globalStyle??"",this.input=o.input??{},this.receive=o.receive??{},this.bubble=o.bubble??{},this.response=o.response??{},this.alter=o.alter??{};for(let name in o.views??{}){let v=o.views[name],{view,style}=isString(v)?{view:v}:v;this.views[name]=new View(name,view,style)}this._rawProvide=o.provide??{},this._rawLookup=o.lookup??{},this.provide={},this.lookup={},this.scope=null,this.spec=o,this.extra={};for(let key of Object.keys(o))if(!KNOWN_SPEC_KEYS.has(key))this.extra[key]=o[key]}compile(ParseContext2){for(let name in this.views)this.views[name].compile(new ParseContext2,this.scope,this.id);let ctx=this.views.main.ctx;for(let key in this._rawProvide){let val=vp.parseProvide(this._rawProvide[key],ctx);if(val)this.provide[key]=new ProvideInfo(key,val,Symbol(key))}for(let key in this._rawLookup){let linfo=this._rawLookup[key],forStr=isString(linfo)?linfo:isString(linfo?.for)?linfo.for:null,[compName,provideName]=forStr===null?[]:forStr.split(".");if(!isString(compName)||!isString(provideName))continue;let defStr=isString(linfo?.default)?linfo.default:null,val=defStr===null?null:vp.parseField(defStr,ctx);this.lookup[key]=new LookupInfo(key,compName,provideName,val)}for(let key in this.lookup)if(this.provide[key]!==void 0)console.warn("name declared in both provide and lookup",this.name,key)}make(args,opts){return this.Class.make(args,opts??{scope:this.scope})}getView(name){return this.views[name]??this.views.main}getEventForId(id,name="main"){return this.getView(name).ctx.getEventForId(id)}getNodeForId(id,name="main"){return this.getView(name).ctx.getNodeForId(id)}compileStyle(){let{id,commonStyle,globalStyle,views}=this,styles=commonStyle?[`[data-cid="${id}"]{${commonStyle}}`]:[];if(globalStyle!=="")styles.push(globalStyle);for(let name in views){let{style}=views[name];if(style!=="")styles.push(`[data-cid="${id}"][data-vid="${name}"]{${style}}`)}return styles.join(`
3
- `)}}var STOP=Symbol("STOP"),NEXT=Symbol("NEXT");function lookup(chain,name,dv=null){let n=chain;while(n!==null){let r=n[0].lookup(name);if(r===STOP)return dv;if(r!==NEXT)return r;n=n[1]}return dv}class BindFrame{constructor(it,binds,isFrame){this.it=it,this.binds=binds,this.isFrame=isFrame}lookup(name){let v=this.binds[name];return v===void 0?this.isFrame?STOP:NEXT:v}}class ObjectFrame{constructor(binds){this.binds=binds}lookup(key){let v=this.binds[key];return v===void 0?NEXT:v}}function computeViewsId(views){let s="",n=views;while(n!==null)s+=n[0],n=n[1];return s==="main"?"":s}class Stack2{constructor(comps,it,binds,dynBinds,views,viewsId,ctx=null){this.comps=comps,this.it=it,this.binds=binds,this.dynBinds=dynBinds,this.views=views,this.viewsId=viewsId,this.ctx=ctx}_pushProvides(){let provide=this.comps.getCompFor(this.it)?.provide;if(provide==null)return this;let dynObj={},has2=!1;for(let k in provide)dynObj[provide[k].symbol]=provide[k].val.eval(this),has2=!0;if(!has2)return this;let newDynBinds=[new ObjectFrame(dynObj),this.dynBinds],{comps,it,binds,views,viewsId,ctx}=this;return new Stack2(comps,it,binds,newDynBinds,views,viewsId,ctx)}static root(comps,it,ctx){let binds=[new BindFrame(it,{},!0),null],dynBinds=[new ObjectFrame({}),null];return new Stack2(comps,it,binds,dynBinds,["main",null],"",ctx)._pushProvides()}enter(it,bindings={},isFrame=!0){let{comps,binds,dynBinds,views,viewsId,ctx}=this,newBinds=[new BindFrame(it,bindings,isFrame),binds],stack=new Stack2(comps,it,newBinds,dynBinds,views,viewsId,ctx);return isFrame?stack._pushProvides():stack}pushViewName(name){let{comps,it,binds,dynBinds,views,ctx}=this,newViews=[name,views];return new Stack2(comps,it,binds,dynBinds,newViews,computeViewsId(newViews),ctx)}_pushDynBindValuesToArray(arr,comp){for(let k in comp.provide)arr.push(this._lookupProvide(comp.provide[k]));for(let k in comp.lookup)arr.push(this._lookupAlias(comp.lookup[k]))}_lookupProvide(p){return lookup(this.dynBinds,p.symbol)??p.val.eval(this)??null}_lookupAlias(lk){let sym=lk.getProducerSymbol(this);return(sym!=null?lookup(this.dynBinds,sym):null)??lk.val?.eval(this)??null}lookupDynamic(name){let comp=this.comps.getCompFor(this.it);if(comp==null)return null;let lk=comp.lookup[name];if(lk!==void 0)return this._lookupAlias(lk);let p=comp.provide[name];return p!==void 0?this._lookupProvide(p):null}lookupBind(name){return lookup(this.binds,name)}lookupType(name){return this.comps.getCompFor(this.it).scope.lookupComponent(name)}lookupFieldRaw(name){return this.it[name]??null}lookupMethod(name){let fn=this.it[name];return fn instanceof Function?fn.call(this.it):null}lookupName(name){return this.ctx.lookupName(name)}getHandlerFor(name,key){return this.comps.getHandlerFor(this.it,name,key)}lookupBestView(views,defaultViewName){let n=this.views;while(n!==null){let view=views[n[0]];if(view!==void 0)return view;n=n[1]}return views[defaultViewName]}}class State{constructor(val){this.val=val,this.changeSubs=[]}onChange(cb){this.changeSubs.push(cb)}set(val,info){let old=this.val;this.val=val;for(let sub of this.changeSubs)sub({val,old,info,timestamp:Date.now()})}update(fn,info){return this.set(fn(this.val),info)}}class Transactor{constructor(comps,rootValue){this.comps=comps,this.transactions=[],this.state=new State(rootValue),this.onTransactionPushed=()=>{},this._observers=[],this._inflight=new Set}pushTransaction(t){this.transactions.push(t),this.onTransactionPushed(t)}observe(cb){return this._observers.push(cb),()=>{let i=this._observers.indexOf(cb);if(i!==-1)this._observers.splice(i,1)}}_emit(record){for(let cb of this._observers)cb(record)}_emitTransaction(transaction,root){if(this._observers.length===0)return;if(transaction._resolvedHandler===void 0)return;let path=transaction.getTransactionPath().pinKeys(root);this._emit({kind:transaction.observeKind,name:transaction.observeName,args:transaction.args??null,path,pathKeys:path.toKeys(),targetPath:transaction.targetPath??transaction.path,handler:transaction._resolvedHandler??null,handlerName:transaction._resolvedHandler?.name||null,matched:transaction._matched??null,before:transaction._before,after:transaction._after,parent:transaction.parentTransaction,timestamp:Date.now()})}_link(child,parent){if(parent){let release=parent.completion.track();child.completion.whenSubtreeSettled().then(release)}return child}pushSend(path,name,args=[],opts={},parent=null){let t=new SendEvent(path,this,name,args,parent,opts);return this.pushTransaction(t),this._link(t,parent)}pushInput(path,name,args=[],opts={},parent=null){let t=new InputDispatchEvent(path,this,name,args,parent,opts);return this.pushTransaction(t),this._link(t,parent)}pushBubble(path,name,args=[],opts={},parent=null,targetPath=null){let newOpts=opts.skipSelf?{...opts,skipSelf:!1}:opts,t=new BubbleEvent(path,this,name,args,parent,newOpts,targetPath);return this.pushTransaction(t),this._link(t,parent)}pushRequest(path,name,args=[],opts={},parent=null){let release=parent?parent.completion.track():null,p=this._runRequest(path,name,args,opts,parent,release);return this._inflight.add(p),p.finally(()=>this._inflight.delete(p)),p}async settle(maxTurns=1e4){while((this.hasPendingTransactions||this._inflight.size)&&maxTurns-- >0){while(this.hasPendingTransactions)this.transactNext();if(this._inflight.size)await Promise.allSettled([...this._inflight])}}async _runRequest(path,name,args=[],opts={},parent=null,release=null){let released=!1,transfer=(t)=>{if(release)released=!0,t.completion.whenSubtreeSettled().then(release)};try{let curRoot=this.state.val,txnPath=path.toTransactionPath(),curLeaf=txnPath.lookup(curRoot),found=this.comps.getRequestFor(curLeaf,name),handler=found??mkReq404(name);if(this._observers.length>0){let reqPath=txnPath.pinKeys(curRoot);this._emit({kind:"request",name,args,path:reqPath,pathKeys:reqPath.toKeys(),targetPath:path,handler:found?.fn??null,handlerName:found?.fn?.name||name,matched:found?"exact":"none",before:curLeaf,after:void 0,parent,timestamp:Date.now()})}let reqCtx=new RequestContext(path,this,parent,curRoot),resHandlerName=opts?.onResName??name,resPath=opts?.livePath?null:txnPath.pinKeys(curRoot),push=(specificName,baseName,singleArg,result,error)=>{let t=new ResponseEvent(path,this,specificName??baseName,specificName?[singleArg]:[result,error],parent,resPath);transfer(t),this.pushTransaction(t)};try{let result=await handler.fn.apply(null,[...args,reqCtx]);push(opts?.onOkName,resHandlerName,result,result,null)}catch(error){push(opts?.onErrorName,resHandlerName,error,null,error)}}finally{if(release&&!released)release()}}get hasPendingTransactions(){return this.transactions.length>0}transactNext(){if(this.hasPendingTransactions)this.transact(this.transactions.shift())}transact(transaction){try{let curState=this.state.val,newState=transaction.run(curState,this.comps);if(newState!==void 0)this.state.set(newState,{transaction}),transaction.afterTransaction(),this._emitTransaction(transaction,curState);else console.warn("undefined new state",{curState,transaction})}finally{transaction._completion?.ensureSelfSettled(),transaction._completion?.releaseSelf()}}transactInputNow(path,event,eventHandler,dragInfo){this.transact(new InputEvent(path,event,eventHandler,this,dragInfo))}}function mkReq404(name){return{fn:()=>{throw Error(`Request not found: ${name}`)}}}function nullHandler(){return this}class Transaction{constructor(path,transactor,parentTransaction=null){this.path=path,this.transactor=transactor,this.parentTransaction=parentTransaction,this._completion=null}get completion(){return this._completion??=new Completion,this._completion}whenSettled(){return this.completion.whenSettled()}whenSubtreeSettled(){return this.completion.whenSubtreeSettled()}run(rootValue,comps){return this.updateRootValue(rootValue,comps)}afterTransaction(){}buildRootStack(root,comps){return Stack2.root(comps,root)}buildStack(root,comps){return this.path.toTransactionPath().buildStack(this.buildRootStack(root,comps))}get observeKind(){return null}get observeName(){return null}callHandler(root,instance,comps){let[handler,args]=this.getHandlerAndArgs(root,instance,comps);return this._resolvedHandler=handler,handler.apply(instance,args)}getHandlerAndArgs(_root,_instance,_comps){return null}getTransactionPath(){return this.path.toTransactionPath()}updateRootValue(curRoot,comps){let txnPath=this.getTransactionPath(),curLeaf=txnPath.lookup(curRoot),newLeaf=this.callHandler(curRoot,curLeaf,comps);return this._before=curLeaf,this._after=newLeaf,this._completion?.markSelfSettled({value:newLeaf,old:curLeaf}),curLeaf!==newLeaf?txnPath.setValue(curRoot,newLeaf):curRoot}lookupName(_name){return null}}var toNullIfNaN=(v)=>Number.isNaN(v)?null:v;function getValue(e){return e.target.type==="checkbox"?e.target.checked:(e instanceof CustomEvent?e.detail:e.target.value)??null}class InputEvent extends Transaction{constructor(path,e,handler,transactor,dragInfo){super(path,transactor);this.e=e,this.handler=handler,this.dragInfo=dragInfo,this._dispatchPath=null}get dispatchPath(){return this._dispatchPath??=this.path.compact(),this._dispatchPath}get observeKind(){return"input"}get observeName(){return this.e?.type??null}buildRootStack(root,comps){return Stack2.root(comps,root,this)}getHandlerAndArgs(root,_instance,comps){let stack=this.buildStack(root,comps),[handler,args]=this.handler.getHandlerAndArgs(stack,this),path=this.dispatchPath;return args.push(new EventContext(path,this.transactor,this)),[handler,args]}lookupName(name){let{e}=this;switch(name){case"value":return getValue(e);case"valueAsInt":return toNullIfNaN(parseInt(getValue(e),10));case"valueAsFloat":return toNullIfNaN(parseFloat(getValue(e)));case"target":return e.target;case"event":return e;case"isAlt":return e.altKey;case"isShift":return e.shiftKey;case"isCtrl":case"isCmd":return isMac&&e.metaKey||e.ctrlKey;case"key":return e.key;case"keyCode":return e.keyCode;case"isUpKey":return e.key==="ArrowUp";case"isDownKey":return e.key==="ArrowDown";case"isSend":return e.key==="Enter";case"isCancel":return e.key==="Escape";case"isTabKey":return e.key==="Tab";case"ctx":return new EventContext(this.dispatchPath,this.transactor,this);case"dragInfo":return this.dragInfo}return null}}class NameArgsTransaction extends Transaction{constructor(path,transactor,name,args,parentTransaction,opts={}){super(path,transactor,parentTransaction);this.name=name,this.args=args,this.opts=opts,this.targetPath=path}handlerProp=null;get observeKind(){return this.handlerProp}get observeName(){return this.name}getHandlerForName(comp){let handlers=comp?.[this.handlerProp],exact=handlers?.[this.name];if(exact)return this._matched="exact",exact;let unknown=handlers?.$unknown;if(unknown)return this._matched="unknown",unknown;return this._matched="none",nullHandler}getHandlerAndArgs(_root,instance,comps){return[this.getHandlerForName(comps.getCompFor(instance)),[...this.args,new EventContext(this.path,this.transactor,this)]]}}class ResponseEvent extends NameArgsTransaction{handlerProp="response";constructor(path,transactor,name,args,parent,txnPath=null){super(path,transactor,name,args,parent);this._txnPath=txnPath}getTransactionPath(){return this._txnPath??super.getTransactionPath()}}class SendEvent extends NameArgsTransaction{handlerProp="receive";run(rootVal,comps){return this.opts.skipSelf?rootVal:this.updateRootValue(rootVal,comps)}afterTransaction(){let{path,name,args,opts,targetPath}=this;if(opts.bubbles&&path.steps.length>0)this.transactor.pushBubble(path.popStep(),name,args,opts,this,targetPath)}}class BubbleEvent extends SendEvent{handlerProp="bubble";constructor(path,transactor,name,args,parent,opts,targetPath){super(path,transactor,name,args,parent,opts);this.targetPath=targetPath??path}stopPropagation(){this.opts.bubbles=!1}}class InputDispatchEvent extends NameArgsTransaction{handlerProp="input"}class Completion{constructor(){this.val=void 0,this.selfSettled=!1,this.subtreeSettled=!1,this.pending=1,this._selfResolve=null,this._selfPromise=null,this._subtreeResolve=null,this._subtreePromise=null,this._selfReleased=!1}whenSettled(){if(this.selfSettled)return Promise.resolve(this.val);return this._selfPromise??=new Promise((res)=>{this._selfResolve=res}),this._selfPromise}whenSubtreeSettled(){if(this.subtreeSettled)return Promise.resolve(this.val);return this._subtreePromise??=new Promise((res)=>{this._subtreeResolve=res}),this._subtreePromise}markSelfSettled(val){if(this.selfSettled)return;this.selfSettled=!0,this.val=val,this._selfResolve?.(val)}ensureSelfSettled(){if(!this.selfSettled)this.markSelfSettled(this.val)}track(){this.pending++;let done=!1;return()=>{if(done)return;done=!0,this._release()}}releaseSelf(){if(this._selfReleased)return;this._selfReleased=!0,this._release()}_release(){if(--this.pending===0)this.subtreeSettled=!0,this._subtreeResolve?.(this.val)}}class Dispatcher{constructor(path,transactor,parentTransaction,root=transactor.state.val){this.path=path,this.transactor=transactor,this.parent=parentTransaction,this.root=root}walkPath(callback){let comps=this.transactor.comps,chain=this.path.toTransactionPath().resolveChain(this.root);for(let i=chain.length-1;i>=0;i--){let comp=comps.getCompFor(chain[i]);if(comp&&callback(comp,chain[i])===!1)return}}get at(){return new PathChanges(this)}send(name,args,opts){return this.sendAtPath(this.path,name,args,opts)}bubble(name,args,opts){return this.send(name,args,{skipSelf:!0,bubbles:!0,...opts})}sendAtPath(path,name,args,opts){return this.transactor.pushSend(path,name,args,opts,this.parent)}request(name,args,opts){return this.requestAtPath(this.path,name,args,opts)}requestAtPath(path,name,args,opts){return this.transactor.pushRequest(path,name,args,opts,this.parent)}inputAtPath(path,name,args,opts){return this.transactor.pushInput(path,name,args,opts,this.parent)}lookupTypeFor(name,inst){return this.transactor.comps.getCompFor(inst).scope.lookupComponent(name)}}class EventContext extends Dispatcher{get name(){return this.parent?.name??null}get targetPath(){return this.parent.targetPath}stopPropagation(){return this.parent.stopPropagation()}}class RequestContext extends Dispatcher{}class PathChanges extends PathBuilder{constructor(dispatcher){super();this.dispatcher=dispatcher}send(name,args,opts){return this.dispatcher.sendAtPath(this.buildPath(),name,args,opts)}bubble(name,args,opts){return this.send(name,args,{skipSelf:!0,bubbles:!0,...opts})}buildPath(){return this.dispatcher.path.concat(this.pathChanges)}}function rootDispatcher(transactor){return new Dispatcher(new Path([]),transactor,null)}var _evs="dragstart dragover dragend touchstart touchmove touchend touchcancel".split(" ");class App{constructor(rootNode,comps,renderer,ParseContext2){this.rootNode=rootNode,this.comps=comps,this.compStack=new ComponentStack(comps),this.transactor=new Transactor(comps,null),this.ParseContext=ParseContext2,this.renderer=renderer,this.maxEventNodeDepth=1/0,this._transactNextBatchId=this._evictCacheId=null,this._eventNames=new Set(_evs),this.dragInfo=this.curDragOver=null,this._touch=null,this.transactor.onTransactionPushed=(_transaction)=>{if(this._transactNextBatchId===null)this._scheduleNextTransactionBatchExecution()},this._compiled=!1,this._renderOpts={document:rootNode.ownerDocument},this._renderState=null,this.rootViewName=null}get state(){return this.transactor.state}handleEvent(e){let{type}=e;if(type[0]==="t"&&type.startsWith("touch")){this._handleTouchEvent(e);return}this._dispatchEvent(e)}_dispatchEvent(e){let{type}=e,isDrag=type==="dragover"||type==="dragstart"||type==="dragend"||type==="drop",{rootNode:root,maxEventNodeDepth:maxDepth,comps,transactor}=this,[path,handlers]=Path.fromEvent(e,root,maxDepth,comps,!isDrag);if(isDrag)this._handleDragEvent(e,type,path);if(path!==null&&handlers!==null)for(let handler of handlers)transactor.transactInputNow(path,e,handler,this.dragInfo)}_handleTouchEvent(e){let{type}=e;if(type==="touchstart"){if(this._touch!==null||e.touches.length!==1)return;let t=e.touches[0],draggable=t.target?.closest?.('[draggable="true"]');if(!draggable)return;this._touch=makeTouchInfo(t.identifier,t.clientX,t.clientY,draggable,!1);return}if(this._touch===null)return;let touch=findTouch(e,this._touch.id);if(touch===null)return;let{rootNode,_touch}=this,{clientX,clientY}=touch,fire=(type2,target)=>{let e2={type:type2,target,clientX,clientY,preventDefault:NOOP};this._dispatchEvent(e2)};if(type==="touchmove"){if(!_touch.active){let dx=clientX-_touch.startX,dy=clientY-_touch.startY;if(dx*dx+dy*dy<100)return;_touch.active=!0,e.preventDefault(),fire("dragstart",_touch.target)}else e.preventDefault(),fire("dragover",hitTest(rootNode,clientX,clientY));return}if(type==="touchend"||type==="touchcancel"){if(_touch.active){if(type==="touchend")fire("drop",hitTest(rootNode,clientX,clientY));fire("dragend",_touch.target)}this._touch=null}}_handleDragEvent(e,type,path){if(type==="dragover"){let dropTarget=getClosestDropTarget(e.target,this.rootNode,1/0);if(dropTarget!==null)e.preventDefault(),this._cleanDragOverAttrs(),this.curDragOver=dropTarget,dropTarget.dataset.draggingover=this.dragInfo?.type??"_external"}else if(type==="dragstart"){e.target.dataset.dragging=1;let rootValue=this.state.val,txnPath=path.compact().toTransactionPath(),value=txnPath.lookup(rootValue),dragType=e.target.dataset.dragtype??"?",stack=path.toTransactionPath().buildStack(this.makeStack(rootValue));this.dragInfo=new DragInfo(txnPath,stack,e,value,dragType,e.target)}else if(type==="drop")e.preventDefault(),this._cleanDragOverAttrs();else{if(this.dragInfo!==null)delete this.dragInfo.node.dataset.dragging,this.dragInfo=null;this._cleanDragOverAttrs()}}makeStack(rootValue){return Stack2.root(this.comps,rootValue)}_cleanDragOverAttrs(){if(this.curDragOver!==null)delete this.curDragOver.dataset.draggingover,this.curDragOver=null}render(){let root=this.state.val,stack=this.makeStack(root),{renderer,rootNode,_renderOpts,_renderState}=this,newState=render(renderer.renderRoot(stack,root,this.rootViewName),rootNode,_renderOpts,_renderState);return this._renderState=newState,newState.dom}onChange(callback){this.transactor.state.onChange(callback)}observe(callback){return this.transactor.observe(callback)}compile(){for(let Comp of this.comps.byId.values()){Comp.compile(this.ParseContext);for(let key in Comp.views)for(let name of Comp.views[key].ctx.genEventNames())this._eventNames.add(name)}this._compiled=!0}subscribeToEvents(eventNames){for(let name of eventNames)this.rootNode.addEventListener(name,this,listenerOpts(name))}recompileStyles(opts){injectCss("tutuca-app",this.comps.compileStyles(),opts?.head??document.head)}start(opts){if(!this._compiled)this.compile();if(this.subscribeToEvents(this._eventNames),this.onChange((info)=>{if(info.val!==info.old)this.render()}),this.recompileStyles(opts),opts?.noCache)this.renderer.setNullCache();else this.startCacheEvictionInterval();this.render()}stop(){this.stopCacheEvictionInterval();for(let name of this._eventNames)this.rootNode.removeEventListener(name,this,listenerOpts(name))}sendAtRoot(name,args,opts){this.transactor.pushSend(new Path([]),name,args,opts)}registerComponents(comps,opts){let scope=this.compStack.enter();return scope.registerComponents(comps,opts),scope}_transactNextBatch(maxRunTimeMs=10){this._transactNextBatchId=null;let startTs=Date.now(),t=this.transactor;while(t.hasPendingTransactions&&Date.now()-startTs<maxRunTimeMs)t.transactNext();if(t.hasPendingTransactions)this._scheduleNextTransactionBatchExecution()}_scheduleNextTransactionBatchExecution(){this._transactNextBatchId=setTimeout(()=>this._transactNextBatch(),0)}startCacheEvictionInterval(intervalMs=30000){this._evictCacheId=setInterval(()=>this.renderer.cache.evict(),intervalMs)}stopCacheEvictionInterval(){clearInterval(this._evictCacheId),this._evictCacheId=null}}function injectCss(nodeId,style,styleTarget=document.head){let styleNode=document.createElement("style"),currentNodeWithId=styleTarget.querySelector(`#${nodeId}`);if(currentNodeWithId)styleTarget.removeChild(currentNodeWithId);styleNode.id=nodeId,styleNode.innerHTML=style,styleTarget.appendChild(styleNode)}var NOOP=()=>{};function findTouch(e,id){for(let t of e.changedTouches)if(t.identifier===id)return t;for(let t of e.touches)if(t.identifier===id)return t;return null}var listenerOpts=(name)=>name==="touchmove"?{passive:!1}:void 0;function makeTouchInfo(id,startX,startY,target,active){return{id,startX,startY,target,active}}function hitTest(rootNode,x,y){let el=rootNode.getRootNode().elementFromPoint?.(x,y)??null;while(el?.shadowRoot){let next=el.shadowRoot.elementFromPoint(x,y);if(next===null||next===el)break;el=next}return el??rootNode}function getClosestDropTarget(target,rootNode,count){let node=target;while(count-- >0&&node!==rootNode){if(node.dataset?.droptarget!==void 0)return node;node=node.parentNode}return null}class DragInfo{constructor(path,stack,e,val,type,node){this.path=path,this.stack=stack,this.e=e,this.val=val,this.type=type,this.node=node}lookupBind(name){return this.stack.lookupBind(name)}}class ParseCtxClassSetCollector extends ParseContext{constructor(...args){super(...args);this.classes=new Set}_addClasses(s){for(let v of s.split(/\s+/))this.classes.add(v)}enterMacro(macroName,macroVars,macroSlots){let{document:document2,Text,Comment,nodes,events,macroNodes}=this,v=new ParseCtxClassSetCollector(document2,Text,Comment,nodes,events,macroNodes,{macroName,macroVars,macroSlots},this);return v.classes=this.classes,v}onAttributes(attrs,_wrapperAttrs,_textChild,_isMacroCall,_tag){if(Array.isArray(attrs.items))for(let attr of attrs.items){if(attr.name!=="class")continue;let{val,thenVal,elseVal}=attr;if(thenVal!==void 0)this._maybeAddVal(thenVal),this._maybeAddVal(elseVal);else this._maybeAddVal(val)}else{let attr=attrs.items.class;if(attr)this._addClasses(attr)}}_maybeAddVal(value){if(!this._maybeAddStrTpl(value)&&typeof value?.val==="string")this._addClasses(value.val)}_maybeAddStrTpl(value){if(value?.vals!==void 0){for(let val of value.vals)if(val instanceof ConstVal&&val.val!=="")this._addClasses(val.val);return!0}return!1}}function collectAppClassesInSet(app){let classes=new Set;for(let Comp of app.comps.byId.values())for(let key in Comp.views){let view=Comp.views[key];for(let name of view.ctx.classes)classes.add(name)}return classes}var OP_KINDS=["send","bubble","request","input"];function phaseOps(phase){let ops=[];for(let type of OP_KINDS)for(let a of phase[type]??[])ops.push({type,...a});for(let a of phase.do??[])ops.push(a);return ops}function resolveArgs(args,self){return typeof args==="function"?args(self)??[]:args??[]}function phaseHasBubble(phase){if(!phase)return!1;if(phase.bubble?.length)return!0;return(phase.do??[]).some((op)=>op.type==="bubble")}function dispatchPhase(dispatcher,targetPath,phase,self){if(!phase)return;for(let op of phaseOps(phase)){let args=resolveArgs(op.args,self);switch(op.type){case"send":dispatcher.sendAtPath(targetPath,op.name,args,op.opts);break;case"bubble":dispatcher.sendAtPath(targetPath,op.name,args,{skipSelf:!0,bubbles:!0,...op.opts});break;case"request":dispatcher.requestAtPath(targetPath,op.name,args,op.opts);break;case"input":dispatcher.inputAtPath(targetPath,op.name,args,op.opts);break}}}var BAD_VALUE=Symbol("BadValue"),nullCoercer=(v)=>v;class Field{constructor(type,name,typeCheck,coercer,defaultValue=null){this.type=type,this.name=name,this.typeCheck=typeCheck,this.coercer=coercer,this.checks=[],this.defaultValue=defaultValue}toDataDef(){let{type,defaultValue:dv}=this;return{type,defaultValue:dv?.toJS?dv.toJS():dv}}getFirstFailingCheck(v){if(!this.typeCheck.isValid(v))return this.typeCheck;for(let check of this.checks)if(!check.isValid(v))return check;return null}isValid(v){return this.getFirstFailingCheck(v)===null}addCheck(check){return this.checks.push(check),this}coerceOr(v,defaultValue=null){if(this.isValid(v))return v;let v1=this.coercer(v);return this.isValid(v1)?v1:defaultValue}coerceOrDefault(v){return this.coerceOr(v,this.defaultValue)}extendProtoForType(_proto,_uname){}extendProto(proto){let{name}=this,uname=name[0].toUpperCase()+name.slice(1),setName=`set${uname}`,that=this;proto[setName]=function(v){let v1=that.coerceOr(v,BAD_VALUE);if(v1===BAD_VALUE)return console.warn("invalid value",v),this;return this.set(name,v1)},proto[`update${uname}`]=function(fn){return this[setName](fn(this.get(name)))},proto[`reset${uname}`]=function(){return this.set(name,that.defaultValue)},this.extendProtoForType(proto,uname)}}class Check{isValid(_v){return!0}getMessage(_v){return"Invalid"}}class CheckTypeAny extends Check{}var CHECK_TYPE_ANY=new CheckTypeAny;class FnCheck extends Check{constructor(isValidFn,getMessageFn){super();this._isValid=isValidFn,this._getMessage=getMessageFn}isValid(v){return this._isValid(v)}getMessage(v){return this._getMessage(v)}}var CHECK_TYPE_INT=new FnCheck((v)=>Number.isInteger(v),()=>"Integer expected"),CHECK_TYPE_FLOAT=new FnCheck((v)=>Number.isFinite(v),()=>"Float expected"),CHECK_TYPE_BOOL=new FnCheck((v)=>typeof v==="boolean",()=>"Boolean expected"),CHECK_TYPE_STRING=new FnCheck((v)=>typeof v==="string",()=>"String expected"),CHECK_TYPE_LIST=new FnCheck((v)=>List.isList(v),()=>"List expected"),CHECK_TYPE_MAP=new FnCheck((v)=>Map2.isMap(v),()=>"Map expected"),CHECK_TYPE_OMAP=new FnCheck((v)=>OrderedMap.isOrderedMap(v),()=>"OrderedMap expected"),CHECK_TYPE_SET=new FnCheck((v)=>Set2.isSet(v),()=>"Set expected"),boolCoercer=(v)=>!!v;class FieldBool extends Field{constructor(name,defaultValue=!1){super("bool",name,CHECK_TYPE_BOOL,boolCoercer,defaultValue)}extendProtoForType(proto,uname){let{name}=this;proto[`toggle${uname}`]=function(){return this.set(name,!this.get(name,!1))},proto[`set${uname}`]=function(v){return this.set(name,!!v)}}}class FieldAny extends Field{constructor(name,defaultValue=null){super("any",name,CHECK_TYPE_ANY,nullCoercer,defaultValue)}toDataDef(){let{defaultValue:dv}=this;return{type:getTypeName(dv)??"any",defaultValue:dv?.toJS?dv.toJS():dv}}}var stringCoercer=(v)=>v?.toString?.()??"";class FieldString extends Field{constructor(name,defaultValue=""){super("text",name,CHECK_TYPE_STRING,stringCoercer,defaultValue)}extendProtoForType(proto,_uname){extendProtoSized(proto,this.name,"","length")}}var intCoercer=(v)=>Number.isFinite(v)?Math.trunc(v):null;class FieldInt extends Field{constructor(name,defaultValue=0){super("int",name,CHECK_TYPE_INT,intCoercer,defaultValue)}}var floatCoercer=(_)=>null;class FieldFloat extends Field{constructor(name,defaultValue=0){super("float",name,CHECK_TYPE_FLOAT,floatCoercer,defaultValue)}}var getTypeName=(v)=>v?.constructor?.getMetaClass?.()?.name;class CheckTypeName{constructor(typeName){this.typeName=typeName}isValid(v){return getTypeName(v)===this.typeName}getMessage(v){let got=getTypeName(v);return`Expected "${this.typeName}", got "${got}"`}}class FieldComp extends Field{constructor(type,name,args){super(type,name,new CheckTypeName(type),nullCoercer,null);this.args=args}toDataDef(){return{component:this.typeName,args:this.args}}}var NONE2=Symbol("NONE");function extendProtoForKeyed(proto,name,uname){extendProtoSized(proto,name,EMPTY_LIST),proto[`setIn${uname}At`]=function(i,v){return this.set(name,this.get(name).set(i,v))},proto[`getIn${uname}At`]=function(i,dval){return this.get(name).get(i,dval)},proto[`updateIn${uname}At`]=function(i,fn){let col=this.get(name),v=col.get(i,NONE2);if(v!==NONE2)return this.set(name,col.set(i,fn(v)));return console.warn("key",i,"not found in",name,col),this},extendDeleteInAt(proto,name,`${uname}At`)}function extendDeleteInAt(proto,name,uname){proto[`deleteIn${uname}`]=function(v){return this.set(name,this.get(name).delete(v))},proto[`removeIn${uname}`]=proto[`deleteIn${uname}`]}var EMPTY_LIST=List(),listCoercer=(v)=>Array.isArray(v)?List(v):null;class FieldList extends Field{constructor(name,defaultValue=EMPTY_LIST){super("list",name,CHECK_TYPE_LIST,listCoercer,defaultValue)}extendProtoForType(proto,uname){let{name}=this;extendProtoForKeyed(proto,name,uname),proto[`pushIn${uname}`]=function(v){return this.set(name,this.get(name).push(v))},proto[`insertIn${uname}At`]=function(i,v){return this.set(name,this.get(name).insert(i,v))}}}var imapCoercer=(v)=>Map2(v);class FieldMap extends Field{constructor(name,defaultValue=Map2()){super("map",name,CHECK_TYPE_MAP,imapCoercer,defaultValue)}extendProtoForType(proto,uname){extendProtoForKeyed(proto,this.name,uname)}}var omapCoercer=(v)=>OrderedMap(v);class FieldOMap extends Field{constructor(name,defaultValue=OrderedMap()){super("omap",name,CHECK_TYPE_OMAP,omapCoercer,defaultValue)}extendProtoForType(proto,uname){extendProtoForKeyed(proto,this.name,uname)}}function extendProtoSized(proto,name,defaultEmpty,propName="size"){proto[`${name}Len`]=function(){return this.get(name,defaultEmpty)[propName]}}var EMPTY_SET2=Set2(),isetCoercer=(v)=>Array.isArray(v)?Set2(v):v instanceof Set?Set2(v):null;class FieldSet extends Field{constructor(name,defaultValue=EMPTY_SET2){super("set",name,CHECK_TYPE_SET,isetCoercer,defaultValue)}extendProtoForType(proto,uname){let{name}=this;extendProtoSized(proto,name,EMPTY_SET2),proto[`addIn${uname}`]=function(v){return this.set(name,this.get(name).add(v))},extendDeleteInAt(proto,name,uname),proto[`hasIn${uname}`]=function(v){return this.get(name).has(v)},proto[`toggleIn${uname}`]=function(v){let current=this.get(name);return this.set(name,current.has(v)?current.delete(v):current.add(v))}}}function mkCompField(field,scope,args){let Comp=scope?.lookupComponent(field.type)??null;if(Comp===null)console.warn(scope?`component field "${field.name}": component "${field.type}" not found in scope`:`component field "${field.name}": cannot resolve component "${field.type}" — built without a registered scope (use ${field.type}.make({}) as the default, or build via a registered component)`);return Comp?.make({...field.args,...args},{scope})??null}class ClassBuilder{constructor(name){let fields={},compFields=new Set;this.name=name,this.fields=fields,this.compFields=compFields,this._methods={},this._statics={make:function(inArgs={},opts={}){let args={},scope=opts.scope??this.scope;for(let key in inArgs){let field=fields[key];if(compFields.has(key))args[key]=mkCompField(field,scope,inArgs[key]);else if(field===void 0)console.warn("extra argument to constructor:",name,key,inArgs);else args[key]=field.coerceOrDefault(inArgs[key])}for(let key of compFields)if(args[key]===void 0)args[key]=mkCompField(fields[key],scope,inArgs[key]);return this(args)}}}build(){let fieldVals={},proto={},{name,_methods,fields}=this;for(let fieldName in fields){let field=fields[fieldName];fieldVals[fieldName]=field.defaultValue,field.extendProto(proto)}let Class={[name]:Record(fieldVals,name)}[name];Object.assign(Class.prototype,proto,_methods);let metaClass={fields,name,methods:_methods};return Object.assign(Class,this._statics,{getMetaClass:()=>metaClass}),Class}methods(proto){for(let k in proto)this._methods[k]=proto[k]}statics(proto){for(let k in proto)this._statics[k]=proto[k]}addField(name,dval,FieldCls){let field=new FieldCls(name,dval);return this.fields[name]=field,field}addCompField(name,type,args){let field=new FieldComp(type,name,args);return this.compFields.add(name),this.fields[name]=field,field}}var FIELD_CLASS=Symbol.for("tutuca.fieldClass"),fieldsByTypeName={text:FieldString,int:FieldInt,float:FieldFloat,bool:FieldBool,list:FieldList,map:FieldMap,omap:FieldOMap,set:FieldSet,any:FieldAny};function classFromData(name,{fields={},methods,statics}){let b=new ClassBuilder(name);for(let field in fields){let value=fields[field],type=typeof value;if(type==="string")b.addField(field,value,FieldString);else if(type==="number")b.addField(field,value,FieldFloat);else if(type==="boolean")b.addField(field,value,FieldBool);else if(List.isList(value)||Array.isArray(value))b.addField(field,List(value),FieldList);else if(Set2.isSet(value)||value instanceof Set)b.addField(field,Set2(value),FieldSet);else if(OrderedMap.isOrderedMap(value))b.addField(field,value,FieldOMap);else if(value?.type&&value?.defaultValue!==void 0){let Field2=fieldsByTypeName[value.type]??FieldAny;b.addField(field,new Field2().coerceOr(value.defaultValue),Field2)}else if(value?.component&&value?.args!==void 0)b.addCompField(field,value.component,value.args);else if(Map2.isMap(value)||value?.constructor===Object)b.addField(field,Map2(value),FieldMap);else{let Field2=value?.[FIELD_CLASS]??FieldAny;b.addField(field,value,Field2)}}if(methods)b.methods(methods);if(statics)b.statics(statics);return b.build()}Component.fromSpec=(opts)=>new Component(classFromData(opts.name,opts),opts);var component=(opts)=>Component.fromSpec(opts);var{raw:css,raw:html}=String,macro=(defaults,rawView)=>new Macro(defaults,rawView);function check(_app){return{error:0,warn:0,hint:0,dummyCheck:!0}}async function test(_opts){return null}function collectIterBindings(){return console.warn("collectIterBindings is a no-op in the core tutuca build; use the tutuca-dev build for a functional implementation"),[]}function tutuca(nodeOrSelector){let rootNode=typeof nodeOrSelector==="string"?document.querySelector(nodeOrSelector):nodeOrSelector,comps=new Components,renderer=new Renderer(comps);return new App(rootNode,comps,renderer,ParseContext)}async function compileClassesToStyle(app,compileClasses,styleId="margaui-css"){let t1=performance.now(),css2=await compileClassesToStyleText(app,compileClasses),t2=performance.now();return injectCss(styleId,css2),t2-t1}async function compileClassesToStyleText(app,compileClasses,Ctx=ParseCtxClassSetCollector){return app.ParseContext=Ctx,app.compile(),await compileClasses(Array.from(collectAppClassesInSet(app)))}export{version,updateIn$1 as updateIn,update$1 as update,tutuca,test,setIn$1 as setIn,set,rootDispatcher,resolveArgs,removeIn,remove,phaseOps,phaseHasBubble,mergeWith$1 as mergeWith,mergeDeepWith$1 as mergeDeepWith,mergeDeep$1 as mergeDeep,merge$1 as merge,macro,isValueObject,isStack,isSet,isSeq,isRecord,isPlainObject,isOrderedSet,isOrderedMap,isOrdered,isOrderedMap as isOMap,isMap,isList,isKeyed,isIndexed,isImmutable,isMap as isIMap,isCollection,isAssociative,is,injectCss,html,hash,hasIn$1 as hasIn,has,getIn$1 as getIn,get,fromJS,dispatchPhase,css,component,compileClassesToStyleText,compileClassesToStyle,collectIterBindings,check,Stack,Set2 as Set,Seq,SEQ_INFO,Repeat,Record,Range,ParseContext,PairSorting,OrderedSet,OrderedMap,OrderedMap as OMap,Map2 as Map,List,Set2 as ISet,Map2 as IMap,FIELD_CLASS,Collection};
1
+ function invariant(condition,error){if(!condition)throw new Error(error)}function assertNotInfinite(size){invariant(size!==1/0,"Cannot perform this action with an infinite size.")}function reduce(collection,reducer,reduction,context,useFirst,reverse){return assertNotInfinite(collection.size),collection.__iterate((v,k,c)=>{useFirst?(useFirst=!1,reduction=v):reduction=reducer.call(context,reduction,v,k,c)},reverse),reduction}var keyMapper=(v,k)=>k,entryMapper=(v,k)=>[k,v],not=predicate=>function(...args){return!predicate.apply(this,args)},neg=predicate=>function(...args){return-predicate.apply(this,args)};function defaultComparator(a,b){return a===void 0&&b===void 0?0:a===void 0?1:b===void 0?-1:a>b?1:a<b?-1:0}var defaultNegComparator=(a,b)=>a<b?1:a>b?-1:0,DONE={done:!0,value:void 0},Iter=class{constructor(next){this.next=next}[Symbol.iterator](){return this}};function makeIterator(next){return new Iter(next)}function makeEntryIterator(next){let entry=[void 0,void 0],result={done:!1,value:void 0};return makeIterator(()=>next(entry)?(result.value=[entry[0],entry[1]],result):DONE)}var EMPTY_ITERATOR=makeIterator(()=>DONE),emptyIterator=()=>EMPTY_ITERATOR;function makeIndexKeys(size){let i=0,result={done:!1,value:void 0};return makeIterator(()=>i===size?DONE:(result.value=i++,result))}function mapEntries(source,transform){return makeEntryIterator(entry=>{let step=source.next();return step.done?!1:(transform(step.value[0],step.value[1],entry),!0)})}function hasIterator(maybeIterable){return Array.isArray(maybeIterable)?!0:!!getIteratorFn(maybeIterable)}var isIterator=maybeIterator=>typeof maybeIterator?.next=="function";function getIterator(iterable){return getIteratorFn(iterable)?.call(iterable)}function getIteratorFn(iterable){let iteratorFn=iterable?.[Symbol.iterator];if(typeof iteratorFn=="function")return iteratorFn}function isEntriesIterable(maybeIterable){let iteratorFn=getIteratorFn(maybeIterable);return iteratorFn&&iteratorFn===maybeIterable.entries}function isKeysIterable(maybeIterable){let iteratorFn=getIteratorFn(maybeIterable);return iteratorFn&&iteratorFn===maybeIterable.keys}var DELETE="delete",SHIFT=5,SIZE=1<<SHIFT,MASK=SIZE-1,NOT_SET={},MakeRef=()=>({value:!1});function SetRef(ref){ref&&(ref.value=!0)}var OwnerID=class{};function ensureSize(iter){return iter.size===void 0&&(iter.size=iter.__iterate(returnTrue)),iter.size}function wrapIndex(iter,index){if(typeof index!="number"){let uint32Index=index>>>0;if(String(uint32Index)!==index||uint32Index===4294967295)return NaN;index=uint32Index}return index<0?ensureSize(iter)+index:index}var returnTrue=()=>!0,isNeg=value=>value<0||Object.is(value,-0),wholeSlice=(begin,end,size)=>(begin===0&&!isNeg(begin)||size!==void 0&&(begin??0)<=-size)&&(end===void 0||size!==void 0&&end>=size),resolveIndex=(index,size,defaultIndex)=>index===void 0?defaultIndex:isNeg(index)?size===1/0?size:Math.max(0,size+index)|0:size===void 0||size===index?index:Math.min(size,index)|0,resolveBegin=(begin,size)=>resolveIndex(begin,size,0),resolveEnd=(end,size)=>resolveIndex(end,size,size),IS_COLLECTION_SYMBOL="@@__IMMUTABLE_ITERABLE__@@",IS_KEYED_SYMBOL="@@__IMMUTABLE_KEYED__@@",IS_INDEXED_SYMBOL="@@__IMMUTABLE_INDEXED__@@",IS_ORDERED_SYMBOL="@@__IMMUTABLE_ORDERED__@@",IS_SEQ_SYMBOL="@@__IMMUTABLE_SEQ__@@",IS_LIST_SYMBOL="@@__IMMUTABLE_LIST__@@",IS_MAP_SYMBOL="@@__IMMUTABLE_MAP__@@",IS_SET_SYMBOL="@@__IMMUTABLE_SET__@@",IS_STACK_SYMBOL="@@__IMMUTABLE_STACK__@@",IS_RECORD_SYMBOL="@@__IMMUTABLE_RECORD__@@";function hasSymbol(v,symbol){return typeof v=="object"&&v!==null&&symbol in v}var isCollection=v=>hasSymbol(v,IS_COLLECTION_SYMBOL),isKeyed=v=>hasSymbol(v,IS_KEYED_SYMBOL),isIndexed=v=>hasSymbol(v,IS_INDEXED_SYMBOL),isAssociative=v=>isKeyed(v)||isIndexed(v),isOrdered=v=>hasSymbol(v,IS_ORDERED_SYMBOL),isSeq=v=>hasSymbol(v,IS_SEQ_SYMBOL),isList=v=>hasSymbol(v,IS_LIST_SYMBOL),isMap=v=>hasSymbol(v,IS_MAP_SYMBOL),isSet=v=>hasSymbol(v,IS_SET_SYMBOL),isStack=v=>hasSymbol(v,IS_STACK_SYMBOL),isRecord=v=>hasSymbol(v,IS_RECORD_SYMBOL),isImmutable=v=>isCollection(v)||isRecord(v),isOrderedMap=v=>isMap(v)&&isOrdered(v),isOrderedSet=v=>isSet(v)&&isOrdered(v),isValueObject=v=>typeof v=="object"&&v!==null&&typeof v.equals=="function"&&typeof v.hashCode=="function";function flipFactory(collection){let flipSequence=makeSequence(collection);return flipSequence._iter=collection,flipSequence.size=collection.size,flipSequence.flip=()=>collection,flipSequence.reverse=function(){let reversedSequence=collection.reverse.call(this);return reversedSequence.flip=()=>collection.reverse(),reversedSequence},flipSequence.has=key=>collection.includes(key),flipSequence.includes=key=>collection.has(key),flipSequence.cacheResult=cacheResultThrough,flipSequence.__iterate=function(fn,reverse){return collection.__iterate((v,k)=>fn(k,v,this),reverse)},flipSequence.__iteratorUncached=reverse=>mapEntries(collection.__iterator(reverse),(k,v,entry)=>{entry[0]=v,entry[1]=k}),flipSequence}function mapFactory(collection,mapper,context){let mappedSequence=makeSequence(collection);return mappedSequence.size=collection.size,mappedSequence.has=key=>collection.has(key),mappedSequence.get=(key,notSetValue)=>{let v=collection.get(key,NOT_SET);return v===NOT_SET?notSetValue:mapper.call(context,v,key,collection)},mappedSequence.__iterate=function(fn,reverse){return collection.__iterate((v,k)=>fn(mapper.call(context,v,k,collection),k,this),reverse)},mappedSequence.__iteratorUncached=reverse=>mapEntries(collection.__iterator(reverse),(k,v,entry)=>{entry[0]=k,entry[1]=mapper.call(context,v,k,collection)}),mappedSequence}function reverseFactory(collection,useKeys){let reversedSequence=makeSequence(collection);return reversedSequence._iter=collection,reversedSequence.size=collection.size,reversedSequence.reverse=()=>collection,collection.flip&&(reversedSequence.flip=function(){let flipSequence=flipFactory(collection);return flipSequence.reverse=()=>collection.flip(),flipSequence}),reversedSequence.get=(key,notSetValue)=>collection.get(useKeys?key:-1-key,notSetValue),reversedSequence.has=key=>collection.has(useKeys?key:-1-key),reversedSequence.includes=value=>collection.includes(value),reversedSequence.cacheResult=cacheResultThrough,reversedSequence.__iterate=function(fn,reverse){let i=0;return reverse&&ensureSize(collection),collection.__iterate((v,k)=>fn(v,useKeys?k:reverse?this.size-++i:i++,this),!reverse)},reversedSequence.__iteratorUncached=function(reverse){let i=0;reverse&&ensureSize(collection);let size=this.size;return mapEntries(collection.__iterator(!reverse),(k,v,entry)=>{entry[0]=useKeys?k:reverse?size-++i:i++,entry[1]=v})},reversedSequence}function sliceFactory(collection,begin,end,useKeys){let originalSize=collection.size;if(wholeSlice(begin,end,originalSize))return collection;if(originalSize===void 0&&(begin<0||end<0))return sliceFactory(collection.toSeq().cacheResult(),begin,end,useKeys);let resolvedBegin=resolveBegin(begin,originalSize),resolvedSize=resolveEnd(end,originalSize)-resolvedBegin,sliceSize;Number.isNaN(resolvedSize)||(sliceSize=Math.max(0,resolvedSize));let sliceSeq=makeSequence(collection);return sliceSeq.size=sliceSize===0?sliceSize:collection.size&&sliceSize||void 0,!useKeys&&isSeq(collection)&&sliceSize>=0&&(sliceSeq.get=function(index,notSetValue){return index=wrapIndex(this,index),index>=0&&index<sliceSize?collection.get(index+resolvedBegin,notSetValue):notSetValue}),sliceSeq.__iterateUncached=function(fn,reverse){if(sliceSize!==0&&reverse)return this.cacheResult().__iterate(fn,reverse);if(sliceSize===0)return 0;let skipped=0,iterations=0;return collection.__iterate((v,k)=>{if(skipped<resolvedBegin){skipped++;return}if(sliceSize!==void 0&&iterations>=sliceSize||(iterations++,fn(v,useKeys?k:iterations-1,this)===!1))return!1},reverse),iterations},sliceSeq.__iteratorUncached=function(reverse){if(sliceSize!==0&&reverse)return this.cacheResult().__iterator(reverse);if(sliceSize===0)return emptyIterator();let iterator=collection.__iterator(reverse),skipped=0,iterations=0;return useKeys?makeIterator(()=>{for(;skipped<resolvedBegin;)skipped++,iterator.next();if(sliceSize!==void 0&&iterations>=sliceSize)return DONE;let step=iterator.next();return step.done||iterations++,step}):makeEntryIterator(entry=>{for(;skipped<resolvedBegin;)skipped++,iterator.next();if(sliceSize!==void 0&&iterations>=sliceSize)return!1;let step=iterator.next();return step.done?!1:(iterations++,entry[0]=iterations-1,entry[1]=step.value[1],!0)})},sliceSeq}function sortFactory(collection,comparator,mapper){comparator||(comparator=defaultComparator);let isKeyedCollection=isKeyed(collection),index=0,entries=collection.toSeq().map((v,k)=>[k,v,index++,mapper?mapper(v,k,collection):v]).valueSeq().toArray();return entries.sort((a,b)=>comparator(a[3],b[3])||a[2]-b[2]).forEach(isKeyedCollection?(v,i)=>{entries[i].length=2}:(v,i)=>{entries[i]=v[1]}),isKeyedCollection?KeyedSeq(entries):isIndexed(collection)?IndexedSeq(entries):SetSeq(entries)}function maxFactory(collection,comparator,mapper){return comparator||(comparator=defaultComparator),mapper?collection.toSeq().map((v,k)=>[v,mapper(v,k,collection)]).reduce((a,b)=>maxCompare(comparator,a[1],b[1])?b:a)?.[0]:collection.reduce((a,b)=>maxCompare(comparator,a,b)?b:a)}function maxCompare(comparator,a,b){let comp=comparator(b,a);return comp===0&&b!==a&&(b==null||Number.isNaN(b))||comp>0}function zipWithFactory(keyIter,zipper,iters,zipAll){let zipSequence=makeSequence(keyIter),sizes=new ArraySeq(iters).map(i=>i.size);return zipSequence.size=zipAll?sizes.max():sizes.min(),zipSequence.__iterate=function(fn,reverse){let iterator=this.__iterator(reverse),iterations=0,step;for(;!(step=iterator.next()).done&&fn(step.value[1],iterations++,this)!==!1;);return iterations},zipSequence.__iteratorUncached=function(reverse){let iterators=iters.map(i=>{let col=Collection(i);return getIterator(reverse?col.reverse():col)}),iterations=0,steps=new Array(iterators.length),values=new Array(iterators.length);return makeEntryIterator(entry=>{let done=zipAll;for(let i=0;i<iterators.length;i++)steps[i]=iterators[i].next(),done=zipAll?done&&steps[i].done:done||steps[i].done;if(done)return!1;for(let i=0;i<steps.length;i++)values[i]=steps[i].value;return entry[0]=iterations++,entry[1]=zipper(...values),!0})},zipSequence}function isArrayLike(value){return Array.isArray(value)||typeof value=="string"?!0:value&&typeof value=="object"&&Number.isInteger(value.length)&&value.length>=0&&(value.length===0?Object.keys(value).length===1:Object.hasOwn(value,value.length-1))}function isPlainObject(value){if(!value||typeof value!="object"||Object.prototype.toString.call(value)!=="[object Object]")return!1;let proto=Object.getPrototypeOf(value);if(proto===null)return!0;let parentProto=proto,nextProto=Object.getPrototypeOf(proto);for(;nextProto!==null;)parentProto=nextProto,nextProto=Object.getPrototypeOf(parentProto);return parentProto===proto}var isDataStructure=value=>typeof value=="object"&&(isImmutable(value)||Array.isArray(value)||isPlainObject(value));function coerceKeyPath(keyPath){if(isArrayLike(keyPath)&&typeof keyPath!="string")return keyPath;if(isOrdered(keyPath))return keyPath.toArray();throw new TypeError(`Invalid keyPath: expected Ordered Collection or Array: ${keyPath}`)}var has=(collection,key)=>isImmutable(collection)?collection.has(key):isDataStructure(collection)&&Object.hasOwn(collection,key);function get(collection,key,notSetValue){return isImmutable(collection)?collection.get(key,notSetValue):has(collection,key)?typeof collection.get=="function"?collection.get(key):collection[key]:notSetValue}function getIn$1(collection,searchKeyPath,notSetValue){let keyPath=coerceKeyPath(searchKeyPath),i=0;for(;i!==keyPath.length;)if(collection=get(collection,keyPath[i++],NOT_SET),collection===NOT_SET)return notSetValue;return collection}var hasIn$1=(collection,keyPath)=>getIn$1(collection,keyPath,NOT_SET)!==NOT_SET;function is(valueA,valueB){if(valueA===valueB||Number.isNaN(valueA)&&Number.isNaN(valueB))return!0;if(!valueA||!valueB)return!1;if(typeof valueA.valueOf=="function"&&typeof valueB.valueOf=="function"){if(valueA=valueA.valueOf(),valueB=valueB.valueOf(),valueA===valueB||Number.isNaN(valueA)&&Number.isNaN(valueB))return!0;if(!valueA||!valueB)return!1}return!!(isValueObject(valueA)&&isValueObject(valueB)&&valueA.equals(valueB))}function toJS(value){if(!value||typeof value!="object")return value;if(!isCollection(value)){if(!isDataStructure(value))return value;value=Seq(value)}if(isKeyed(value)){let result2={};return value.__iterate((v,k)=>{result2[String(k)]=toJS(v)}),result2}let result=[];return value.__iterate(v=>{result.push(toJS(v))}),result}function deepEqual(a,b){if(a===b)return!0;if(!isCollection(b)||a.size!==void 0&&b.size!==void 0&&a.size!==b.size||a.__hash!==void 0&&b.__hash!==void 0&&a.__hash!==b.__hash||isKeyed(a)!==isKeyed(b)||isIndexed(a)!==isIndexed(b)||isOrdered(a)!==isOrdered(b))return!1;if(a.size===0&&b.size===0)return!0;let notAssociative=!isAssociative(a);if(isOrdered(a)){let entries=a.entries();return!!(b.every((v,k)=>{let entry=entries.next().value;return entry&&is(entry[1],v)&&(notAssociative||is(entry[0],k))})&&entries.next().done)}let flipped=!1;if(a.size===void 0)if(b.size===void 0)typeof a.cacheResult=="function"&&a.cacheResult();else{flipped=!0;let _=a;a=b,b=_}let allEqual=!0,bSize=b.__iterate((v,k)=>(notAssociative?!a.has(v):flipped?!is(v,a.get(k,NOT_SET)):!is(a.get(k,NOT_SET),v))?(allEqual=!1,!1):!0);return allEqual&&a.size===bSize}var smi=i32=>i32>>>1&1073741824|i32&3221225471;function hash(o){if(o==null)return hashNullish(o);if(typeof o.hashCode=="function")return smi(o.hashCode(o));let v=valueOf(o);if(v==null)return hashNullish(v);switch(typeof v){case"boolean":return v?1108378657:1108378656;case"number":return hashNumber(v);case"string":return v.length>STRING_HASH_CACHE_MIN_STRLEN?cachedHashString(v):hashString(v);case"object":case"function":return hashJSObj(v);case"symbol":return hashSymbol(v);default:if(typeof v.toString=="function")return hashString(v.toString());throw new Error(`Value type ${typeof v} cannot be hashed.`)}}var hashNullish=nullish=>nullish===null?1108378658:1108378659;function hashNumber(n){if(Number.isNaN(n)||n===1/0)return 0;let hash2=n|0;for(hash2!==n&&(hash2^=n*4294967295);n>4294967295;)n/=4294967295,hash2^=n;return smi(hash2)}function cachedHashString(string){let hashed=stringHashCache[string];return hashed===void 0&&(hashed=hashString(string),STRING_HASH_CACHE_SIZE===STRING_HASH_CACHE_MAX_SIZE&&(STRING_HASH_CACHE_SIZE=0,stringHashCache={}),STRING_HASH_CACHE_SIZE++,stringHashCache[string]=hashed),hashed}function hashString(string){let hashed=0;for(let ii=0;ii<string.length;ii++)hashed=31*hashed+string.charCodeAt(ii)|0;return smi(hashed)}function hashSymbol(sym){let hashed=symbolMap[sym];return hashed!==void 0||(hashed=nextHash(),symbolMap[sym]=hashed),hashed}function hashJSObj(obj){let hashed=weakMap.get(obj);return hashed!==void 0||(hashed=nextHash(),weakMap.set(obj,hashed)),hashed}var valueOf=obj=>obj.valueOf!==Object.prototype.valueOf?obj.valueOf():obj;function nextHash(){let nextHash2=++_objHashUID;return _objHashUID&1073741824&&(_objHashUID=0),nextHash2}var weakMap=new WeakMap,symbolMap=Object.create(null),_objHashUID=0,STRING_HASH_CACHE_MIN_STRLEN=16,STRING_HASH_CACHE_MAX_SIZE=255,STRING_HASH_CACHE_SIZE=0,stringHashCache={};function hashCollection(collection){if(collection.size===1/0)return 0;let ordered=isOrdered(collection),keyed=isKeyed(collection),h2=ordered?1:0;return collection.__iterate(keyed?ordered?(v,k)=>{h2=31*h2+hashMerge(hash(v),hash(k))|0}:(v,k)=>{h2=h2+hashMerge(hash(v),hash(k))|0}:ordered?v=>{h2=31*h2+hash(v)|0}:v=>{h2=h2+hash(v)|0}),murmurHashOfSize(collection.size,h2)}var hashMerge=(a,b)=>a^b+2654435769+(a<<6)+(a>>2)|0;function murmurHashOfSize(size,h2){return h2=Math.imul(h2,3432918353),h2=Math.imul(h2<<15|h2>>>-15,461845907),h2=Math.imul(h2<<13|h2>>>-13,5),h2=(h2+3864292196|0)^size,h2=Math.imul(h2^h2>>>16,2246822507),h2=Math.imul(h2^h2>>>13,3266489909),h2=smi(h2^h2>>>16),h2}function quoteString(value){try{return typeof value=="string"?JSON.stringify(value):String(value)}catch{return JSON.stringify(value)}}var reify=(iter,seq)=>iter===seq?iter:isSeq(iter)?seq:iter.create?iter.create(seq):iter.constructor(seq),reifyValues=(collection,arr)=>reify(collection,(isKeyed(collection)?KeyedCollection:isIndexed(collection)?IndexedCollection:SetCollection)(arr)),defaultZipper=(...values)=>values,Collection=value=>isCollection(value)?value:Seq(value),CollectionImpl=class{size=0;static{this.prototype[IS_COLLECTION_SYMBOL]=!0,this.prototype.__toStringMapper=quoteString,this.prototype[Symbol.iterator]=this.prototype.values,this.prototype.toJSON=this.prototype.toArray,this.prototype.contains=this.prototype.includes}equals(other){return deepEqual(this,other)}hashCode(){return this.__hash??(this.__hash=hashCollection(this))}toArray(){assertNotInfinite(this.size);let array=new Array(this.size||0),useTuples=isKeyed(this),i=0;return this.__iterate((v,k)=>{array[i++]=useTuples?[k,v]:v}),array}toIndexedSeq(){return new ToIndexedSequence(this)}toJS(){return toJS(this)}toKeyedSeq(){return new ToKeyedSequence(this,!0)}toMap(){throw new Error("toMap: not patched — import CollectionConversions")}toObject(){assertNotInfinite(this.size);let object={};return this.__iterate((v,k)=>{object[k]=v}),object}toOrderedMap(){throw new Error("toOrderedMap: not patched — import CollectionConversions")}toOrderedSet(){throw new Error("toOrderedSet: not patched — import CollectionConversions")}toSet(){throw new Error("toSet: not patched — import CollectionConversions")}toSetSeq(){return new ToSetSequence(this)}toSeq(){return isIndexed(this)?this.toIndexedSeq():isKeyed(this)?this.toKeyedSeq():this.toSetSeq()}toStack(){throw new Error("toStack: not patched — import CollectionConversions")}toList(){throw new Error("toList: not patched — import CollectionConversions")}toString(){return"[Collection]"}__toString(head,tail){return this.size===0?`${head}${tail}`:`${head} ${this.toSeq().map(this.__toStringMapper).join(", ")} ${tail}`}concat(...values){let isKeyedCollection=isKeyed(this),iters=[this,...values].map(v=>(isCollection(v)?isKeyedCollection&&(v=KeyedCollection(v)):v=isKeyedCollection?keyedSeqFromValue(v):indexedSeqFromValue(Array.isArray(v)?v:[v]),v)).filter(v=>v.size!==0);if(iters.length===0)return this;if(iters.length===1){let singleton=iters[0];if(singleton===this||isKeyedCollection&&isKeyed(singleton)||isIndexed(this)&&isIndexed(singleton))return singleton}return reify(this,new ConcatSeq(iters))}includes(searchValue){return this.some(value=>is(value,searchValue))}every(predicate,context){assertNotInfinite(this.size);let returnValue=!0;return this.__iterate((v,k,c)=>{if(!predicate.call(context,v,k,c))return returnValue=!1,!1}),returnValue}entries(){return this.__iterator()}filter(predicate,context){let collection=this,useKeys=isKeyed(this),filterSequence=makeSequence(collection);return useKeys&&(filterSequence.has=key=>{let v=collection.get(key,NOT_SET);return v!==NOT_SET&&!!predicate.call(context,v,key,collection)},filterSequence.get=(key,notSetValue)=>{let v=collection.get(key,NOT_SET);return v!==NOT_SET&&predicate.call(context,v,key,collection)?v:notSetValue}),filterSequence.__iterateUncached=function(fn,reverse){let iterations=0;return collection.__iterate((v,k)=>{if(predicate.call(context,v,k,collection))return iterations++,fn(v,useKeys?k:iterations-1,this)},reverse),iterations},filterSequence.__iteratorUncached=function(reverse){let iterator=collection.__iterator(reverse),iterations=0;return makeEntryIterator(entry=>{for(;;){let step=iterator.next();if(step.done)return!1;let k=step.value[0],v=step.value[1];if(predicate.call(context,v,k,collection))return entry[0]=useKeys?k:iterations++,entry[1]=v,!0}})},reify(this,filterSequence)}partition(predicate,context){let isKeyedIter=isKeyed(this),groups=[[],[]];return this.__iterate((v,k)=>{groups[predicate.call(context,v,k,this)?1:0].push(isKeyedIter?[k,v]:v)}),groups.map(arr=>reifyValues(this,arr))}find(predicate,context,notSetValue){let entry=this.findEntry(predicate,context);return entry?entry[1]:notSetValue}forEach(sideEffect,context){return assertNotInfinite(this.size),this.__iterate(context?sideEffect.bind(context):sideEffect)}join(separator){assertNotInfinite(this.size),separator=separator!==void 0?String(separator):",";let joined="",isFirst=!0;return this.__iterate(v=>{isFirst?isFirst=!1:joined+=separator,joined+=v!=null?String(v):""}),joined}keys(){let iterator=this.__iterator(),result={done:!1,value:void 0};return makeIterator(()=>{let step=iterator.next();return step.done?DONE:(result.value=step.value[0],result)})}map(mapper,context){return reify(this,mapFactory(this,mapper,context))}reduce(reducer,initialReduction=NOT_SET,context){return reduce(this,reducer,initialReduction,context,initialReduction===NOT_SET,!1)}reduceRight(reducer,initialReduction=NOT_SET,context){return reduce(this,reducer,initialReduction,context,initialReduction===NOT_SET,!0)}reverse(){return reify(this,reverseFactory(this,isKeyed(this)))}slice(begin,end){return reify(this,sliceFactory(this,begin,end,isKeyed(this)))}some(predicate,context){assertNotInfinite(this.size);let returnValue=!1;return this.__iterate((v,k,c)=>{if(predicate.call(context,v,k,c))return returnValue=!0,!1}),returnValue}sort(comparator){return reify(this,sortFactory(this,comparator))}values(){let iterator=this.__iterator(),result={done:!1,value:void 0};return makeIterator(()=>{let step=iterator.next();return step.done?DONE:(result.value=step.value[1],result)})}butLast(){return this.slice(0,-1)}isEmpty(){return this.size!==void 0?this.size===0:!this.some(()=>!0)}count(predicate,context){return ensureSize(predicate?this.toSeq().filter(predicate,context):this)}countBy(_grouper,_context){throw new Error("countBy: not patched — import CollectionConversions")}entrySeq(){let collection=this;if(collection._cache)return new ArraySeq(collection._cache);let entriesSequence=collection.toSeq().map(entryMapper).toIndexedSeq();return entriesSequence.fromEntrySeq=()=>collection.toSeq(),entriesSequence}filterNot(predicate,context){return this.filter(not(predicate),context)}findEntry(predicate,context,notSetValue){let found=notSetValue;return this.__iterate((v,k,c)=>{if(predicate.call(context,v,k,c))return found=[k,v],!1}),found}findKey(predicate,context){return this.findEntry(predicate,context)?.[0]}findLast(predicate,context,notSetValue){return this.toKeyedSeq().reverse().find(predicate,context,notSetValue)}findLastEntry(predicate,context,notSetValue){return this.toKeyedSeq().reverse().findEntry(predicate,context,notSetValue)}findLastKey(predicate,context){return this.toKeyedSeq().reverse().findKey(predicate,context)}first(notSetValue){return this.find(returnTrue,null,notSetValue)}flatMap(mapper,context){return reify(this,this.toSeq().map((v,k)=>(isKeyed(this)?KeyedCollection:isIndexed(this)?IndexedCollection:SetCollection)(mapper.call(context,v,k,this))).flatten(!0))}flatten(depth){let collection=this,useKeys=isKeyed(this),flatSequence=makeSequence(collection);return flatSequence.__iterateUncached=function(fn,reverse){if(reverse)return this.cacheResult().__iterate(fn,reverse);let iterations=0,stopped=!1;function flatDeep(iter,currentDepth){iter.__iterate((v,k)=>{if((!depth||currentDepth<depth)&&isCollection(v)?flatDeep(v,currentDepth+1):(iterations++,fn(v,useKeys?k:iterations-1,flatSequence)===!1&&(stopped=!0)),stopped)return!1},reverse)}return flatDeep(collection,0),iterations},flatSequence.__iteratorUncached=function(reverse){if(reverse)return this.cacheResult().__iterator(reverse);let iterations=0,stack=[{iterator:collection.__iterator(reverse),depth:0}];return makeEntryIterator(entry=>{for(;stack.length>0;){let frame=stack[stack.length-1],step=frame.iterator.next();if(step.done){stack.pop();continue}let v=step.value[1];if((!depth||frame.depth<depth)&&isCollection(v)){stack.push({iterator:v.__iterator(reverse),depth:frame.depth+1});continue}return entry[0]=useKeys?step.value[0]:iterations++,entry[1]=v,!0}return!1})},reify(this,flatSequence)}fromEntrySeq(){return new FromEntriesSequence(this)}get(searchKey,notSetValue){return this.find((_,key)=>is(key,searchKey),void 0,notSetValue)}getIn(searchKeyPath,notSetValue){return getIn$1(this,searchKeyPath,notSetValue)}groupBy(_grouper,_context){throw new Error("groupBy: not patched — import CollectionConversions")}has(searchKey){return this.get(searchKey,NOT_SET)!==NOT_SET}hasIn(searchKeyPath){return hasIn$1(this,searchKeyPath)}isSubset(iter){let other=typeof iter.includes=="function"?iter:Collection(iter);return this.every(value=>other.includes(value))}isSuperset(iter){return(typeof iter.isSubset=="function"?iter:Collection(iter)).isSubset(this)}keyOf(searchValue){return this.findKey(value=>is(value,searchValue))}keySeq(){return this.toSeq().map(keyMapper).toIndexedSeq()}last(notSetValue){return this.toSeq().reverse().first(notSetValue)}lastKeyOf(searchValue){return this.toKeyedSeq().reverse().keyOf(searchValue)}max(comparator){return maxFactory(this,comparator)}maxBy(mapper,comparator){return maxFactory(this,comparator,mapper)}min(comparator){return maxFactory(this,comparator?neg(comparator):defaultNegComparator)}minBy(mapper,comparator){return maxFactory(this,comparator?neg(comparator):defaultNegComparator,mapper)}rest(){return this.slice(1)}skip(amount){return amount===0?this:this.slice(Math.max(0,amount))}skipLast(amount){return amount===0?this:this.slice(0,-Math.max(0,amount))}skipWhile(predicate,context){let collection=this,useKeys=isKeyed(this),skipSequence=makeSequence(collection);return skipSequence.__iterateUncached=function(fn,reverse){if(reverse)return this.cacheResult().__iterate(fn,reverse);let skipping=!0,iterations=0;return collection.__iterate((v,k)=>{if(!(skipping&&predicate.call(context,v,k,this)))return skipping=!1,iterations++,fn(v,useKeys?k:iterations-1,this)},reverse),iterations},skipSequence.__iteratorUncached=function(reverse){if(reverse)return this.cacheResult().__iterator(reverse);let iterator=collection.__iterator(reverse),iterations=0,seq=this,skipping=!0;return makeEntryIterator(entry=>{for(;;){let step=iterator.next();if(step.done)return!1;let k=step.value[0],v=step.value[1];if(!(skipping&&predicate.call(context,v,k,seq)))return skipping=!1,entry[0]=useKeys?k:iterations++,entry[1]=v,!0}})},reify(this,skipSequence)}skipUntil(predicate,context){return this.skipWhile(not(predicate),context)}sortBy(mapper,comparator){return reify(this,sortFactory(this,comparator,mapper))}take(amount){return this.slice(0,Math.max(0,amount))}takeLast(amount){return this.slice(-Math.max(0,amount))}takeWhile(predicate,context){let collection=this,takeSequence=makeSequence(collection);return takeSequence.__iterateUncached=function(fn,reverse){if(reverse)return this.cacheResult().__iterate(fn,reverse);let iterations=0;return collection.__iterate((v,k)=>predicate.call(context,v,k,this)?(iterations++,fn(v,k,this)):!1,reverse),iterations},takeSequence.__iteratorUncached=function(reverse){if(reverse)return this.cacheResult().__iterator(reverse);let iterator=collection.__iterator(reverse),seq=this,finished=!1;return makeIterator(()=>{if(finished)return DONE;let step=iterator.next();return step.done||predicate.call(context,step.value[1],step.value[0],seq)?step:(finished=!0,DONE)})},reify(this,takeSequence)}takeUntil(predicate,context){return this.takeWhile(not(predicate),context)}update(fn){return fn(this)}valueSeq(){return this.toIndexedSeq()}__iterate(fn,reverse=!1){let iterator=this.__iterator(reverse),iterations=0,step;for(;!(step=iterator.next()).done&&(iterations++,fn(step.value[1],step.value[0],this)!==!1););return iterations}__iterator(_reverse=!1){throw new Error("CollectionImpl does not implement __iterator. Use a subclass instead.")}},KeyedCollection=value=>isKeyed(value)?value:KeyedSeq(value),KeyedCollectionImpl=class extends CollectionImpl{static{this.prototype[IS_KEYED_SYMBOL]=!0,this.prototype.__toStringMapper=(v,k)=>`${quoteString(k)}: ${quoteString(v)}`,this.prototype[Symbol.iterator]=CollectionImpl.prototype.entries,this.prototype.toJSON=function(){assertNotInfinite(this.size);let object={};return this.__iterate((v,k)=>{object[k]=v}),object}}flip(){return reify(this,flipFactory(this))}mapEntries(mapper,context){let iterations=0;return reify(this,this.toSeq().map((v,k)=>mapper.call(context,[k,v],iterations++,this)).fromEntrySeq())}mapKeys(mapper,context){return reify(this,this.toSeq().flip().map((k,v)=>mapper.call(context,k,v,this)).flip())}},IndexedCollection=value=>isIndexed(value)?value:IndexedSeq(value),IndexedCollectionImpl=class extends CollectionImpl{static{this.prototype[IS_INDEXED_SYMBOL]=!0,this.prototype[IS_ORDERED_SYMBOL]=!0}toKeyedSeq(){return new ToKeyedSequence(this,!1)}findIndex(predicate,context){let entry=this.findEntry(predicate,context);return entry?entry[0]:-1}indexOf(searchValue){let key=this.keyOf(searchValue);return key===void 0?-1:key}lastIndexOf(searchValue){let key=this.lastKeyOf(searchValue);return key===void 0?-1:key}splice(index,removeNum=NOT_SET,...values){if(index===void 0)return this;let hasRemoveNum=removeNum!==NOT_SET;if(removeNum=hasRemoveNum?Math.max(removeNum||0,0):0,hasRemoveNum&&!removeNum&&values.length===0)return this;index=resolveBegin(index,index<0?this.count():this.size);let spliced=this.slice(0,index);return reify(this,hasRemoveNum?spliced.concat(values,this.slice(index+removeNum)):spliced)}findLastIndex(predicate,context){let entry=this.findLastEntry(predicate,context);return entry?entry[0]:-1}first(notSetValue){return this.get(0,notSetValue)}get(index,notSetValue){return index=wrapIndex(this,index),index<0||this.size===1/0||this.size!==void 0&&index>this.size?notSetValue:this.find((_,key)=>key===index,void 0,notSetValue)}has(index){return index=wrapIndex(this,index),index>=0&&(this.size!==void 0?this.size===1/0||index<this.size:this.indexOf(index)!==-1)}interpose(separator){let collection=this,interposedSequence=makeSequence(collection);return interposedSequence.size=collection.size&&collection.size*2-1,interposedSequence.__iterateUncached=function(fn,reverse){let iterations=0,isFirst=!0;return collection.__iterate(v=>!isFirst&&fn(separator,iterations++,this)===!1?!1:(isFirst=!1,fn(v,iterations++,this)),reverse),iterations},interposedSequence.__iteratorUncached=function(reverse){let iterator=collection.__iterator(reverse),iterations=0,isFirst=!0,pendingValue,hasPending=!1;return makeEntryIterator(entry=>{if(hasPending)return hasPending=!1,entry[0]=iterations++,entry[1]=pendingValue,!0;let step=iterator.next();if(step.done)return!1;let value=step.value[1];return isFirst?(isFirst=!1,entry[0]=iterations++,entry[1]=value,!0):(pendingValue=value,hasPending=!0,entry[0]=iterations++,entry[1]=separator,!0)})},reify(this,interposedSequence)}interleave(...collections){let thisAndCollections=[this,...collections],zipped=zipWithFactory(this.toSeq(),IndexedSeq.of,thisAndCollections),interleaved=zipped.flatten(!0);return zipped.size&&(interleaved.size=zipped.size*thisAndCollections.length),reify(this,interleaved)}keySeq(){throw new Error("keySeq: not patched — import CollectionConversions")}last(notSetValue){return this.get(-1,notSetValue)}zip(...collections){return this.zipWith(defaultZipper,...collections)}zipAll(...collections){let thisAndCollections=[this,...collections];return reify(this,zipWithFactory(this,defaultZipper,thisAndCollections,!0))}zipWith(zipper,...collections){let thisAndCollections=[this,...collections];return reify(this,zipWithFactory(this,zipper,thisAndCollections))}},SetCollection=value=>isCollection(value)&&!isAssociative(value)?value:SetSeq(value),SetCollectionImpl=class _SetCollectionImpl extends CollectionImpl{static{this.prototype.has=CollectionImpl.prototype.includes,this.prototype.contains=CollectionImpl.prototype.includes,this.prototype.keys=_SetCollectionImpl.prototype.values}get(value,notSetValue){return this.has(value)?value:notSetValue}includes(value){return this.has(value)}keySeq(){return this.valueSeq()}};Collection.Keyed=KeyedCollection;Collection.Indexed=IndexedCollection;Collection.Set=SetCollection;var IndexedCollectionPrototype=IndexedCollectionImpl.prototype,Seq=value=>value==null?emptySequence():isImmutable(value)?value.toSeq():seqFromValue(value),makeSequence=collection=>Object.create((isKeyed(collection)?KeyedSeqImpl:isIndexed(collection)?IndexedSeqImpl:SetSeqImpl).prototype),SeqImpl=class extends CollectionImpl{static{this.prototype[IS_SEQ_SYMBOL]=!0}toSeq(){return this}toString(){return this.__toString("Seq {","}")}cacheResult(){return!this._cache&&this.__iterateUncached&&(this._cache=this.entrySeq().toArray(),this.size=this._cache.length),this}__iterateUncached(fn,reverse){let iterator=this.__iteratorUncached(reverse),iterations=0,step;for(;!(step=iterator.next()).done&&(iterations++,fn(step.value[1],step.value[0],this)!==!1););return iterations}__iterate(fn,reverse){let cache=this._cache;if(cache){let size=cache.length,i=0;for(;i!==size;){let entry=cache[reverse?size-++i:i++];if(fn(entry[1],entry[0],this)===!1)break}return i}return this.__iterateUncached(fn,reverse)}__iterator(reverse){let cache=this._cache;if(cache){let size=cache.length,i=0,result={done:!1,value:void 0};return makeIterator(()=>i===size?DONE:(result.value=cache[reverse?size-++i:i++],result))}return this.__iteratorUncached(reverse)}},seqMixin={cacheResult:SeqImpl.prototype.cacheResult,__iterateUncached:SeqImpl.prototype.__iterateUncached,__iterate:SeqImpl.prototype.__iterate,__iterator:SeqImpl.prototype.__iterator},KeyedSeq=value=>value==null?emptySequence().toKeyedSeq():isCollection(value)?isKeyed(value)?value.toSeq():value.fromEntrySeq():isRecord(value)?value.toSeq():keyedSeqFromValue(value),KeyedSeqImpl=class extends KeyedCollectionImpl{static{this.prototype[IS_SEQ_SYMBOL]=!0,Object.assign(this.prototype,seqMixin)}toSeq(){return this}toKeyedSeq(){return this}},IndexedSeq=value=>value==null?emptySequence():isCollection(value)?isKeyed(value)?value.entrySeq():value.toIndexedSeq():isRecord(value)?value.toSeq().entrySeq():indexedSeqFromValue(value);IndexedSeq.of=(...values)=>IndexedSeq(values);var IndexedSeqImpl=class extends IndexedCollectionImpl{static{this.prototype[IS_SEQ_SYMBOL]=!0,Object.assign(this.prototype,seqMixin)}toSeq(){return this}toIndexedSeq(){return this}toString(){return this.__toString("Seq [","]")}},SetSeq=value=>(isCollection(value)&&!isAssociative(value)?value:IndexedSeq(value)).toSetSeq();SetSeq.of=(...values)=>SetSeq(values);var SetSeqImpl=class extends SetCollectionImpl{static{this.prototype[IS_SEQ_SYMBOL]=!0,Object.assign(this.prototype,seqMixin)}toSeq(){return this}toSetSeq(){return this}};Seq.isSeq=isSeq;Seq.Keyed=KeyedSeq;Seq.Set=SetSeq;Seq.Indexed=IndexedSeq;var ArraySeq=class extends IndexedSeqImpl{constructor(array){super(),this._array=array,this.size=array.length}get(index,notSetValue){return this.has(index)?this._array[wrapIndex(this,index)]:notSetValue}__iterateUncached(fn,reverse){let array=this._array,size=array.length,i=0;for(;i!==size;){let ii=reverse?size-++i:i++;if(fn(array[ii],ii,this)===!1)break}return i}__iteratorUncached(reverse){let array=this._array,size=array.length,i=0;return makeEntryIterator(entry=>{if(i===size)return!1;let ii=reverse?size-++i:i++;return entry[0]=ii,entry[1]=array[ii],!0})}},ObjectSeq=class extends KeyedSeqImpl{static{this.prototype[IS_ORDERED_SYMBOL]=!0}constructor(object){super();let keys=[...Object.keys(object),...Object.getOwnPropertySymbols(object)];this._object=object,this._keys=keys,this.size=keys.length}get(key,notSetValue){return notSetValue!==void 0&&!this.has(key)?notSetValue:this._object[key]}has(key){return Object.hasOwn(this._object,key)}__iterateUncached(fn,reverse){let object=this._object,keys=this._keys,size=keys.length,i=0;for(;i!==size;){let key=keys[reverse?size-++i:i++];if(fn(object[key],key,this)===!1)break}return i}__iteratorUncached(reverse){let object=this._object,keys=this._keys,size=keys.length,i=0;return makeEntryIterator(entry=>{if(i===size)return!1;let key=keys[reverse?size-++i:i++];return entry[0]=key,entry[1]=object[key],!0})}},CollectionSeq=class extends IndexedSeqImpl{constructor(collection){super(),this._collection=collection,this.size=collection.length||collection.size}__iterateUncached(fn,reverse){if(reverse)return this.cacheResult().__iterate(fn,reverse);let iterations=0;for(let value of this._collection){if(fn(value,iterations,this)===!1)break;iterations++}return iterations}__iteratorUncached(reverse){if(reverse)return this.cacheResult().__iterator(reverse);let collection=this._collection,iterator=getIterator(collection);if(!isIterator(iterator))return emptyIterator();let iterations=0;return makeEntryIterator(entry=>{let step=iterator.next();return step.done?!1:(entry[0]=iterations++,entry[1]=step.value,!0)})}},emptySequence=()=>new ArraySeq([]),maybeIndexedSeqFromValue=value=>isArrayLike(value)?new ArraySeq(value):hasIterator(value)?new CollectionSeq(value):void 0;function keyedSeqFromValue(value){let seq=maybeIndexedSeqFromValue(value);if(seq)return seq.fromEntrySeq();if(typeof value=="object")return new ObjectSeq(value);throw new TypeError(`Expected Array or collection object of [k, v] entries, or keyed object: ${value}`)}function indexedSeqFromValue(value){let seq=maybeIndexedSeqFromValue(value);if(seq)return seq;throw new TypeError(`Expected Array or collection object of values: ${value}`)}function seqFromValue(value){let seq=maybeIndexedSeqFromValue(value);if(seq)return isEntriesIterable(value)?seq.fromEntrySeq():isKeysIterable(value)?seq.toSetSeq():seq;if(typeof value=="object")return new ObjectSeq(value);throw new TypeError(`Expected Array or collection object of values, or keyed object: ${value}`)}var ConcatSeq=class extends SeqImpl{constructor(iterables){super();let wrappedIterables=[],size=0,sizeKnown=!0;for(let iterable of iterables)if(iterable._wrappedIterables){for(let wrapped of iterable._wrappedIterables)if(wrappedIterables.push(wrapped),sizeKnown){let s=wrapped.size;s!==void 0?size+=s:sizeKnown=!1}}else if(wrappedIterables.push(iterable),sizeKnown){let s=iterable.size;s!==void 0?size+=s:sizeKnown=!1}this._wrappedIterables=wrappedIterables,this.size=sizeKnown?size:void 0;let first=this._wrappedIterables[0];first[IS_KEYED_SYMBOL]&&(this[IS_KEYED_SYMBOL]=!0),first[IS_INDEXED_SYMBOL]&&(this[IS_INDEXED_SYMBOL]=!0),first[IS_ORDERED_SYMBOL]&&(this[IS_ORDERED_SYMBOL]=!0)}__iterateUncached(fn,reverse){if(this._wrappedIterables.length===0)return 0;if(reverse)return this.cacheResult().__iterate(fn,reverse);let wrappedIterables=this._wrappedIterables,reIndex=!isKeyed(this),index=0,stopped=!1;for(let iterable of wrappedIterables)if(iterable.__iterate((v,k)=>{if(fn(v,reIndex?index++:k,this)===!1)return stopped=!0,!1},reverse),stopped)break;return index}__iteratorUncached(reverse){if(this._wrappedIterables.length===0)return emptyIterator();if(reverse)return this.cacheResult().__iterator(reverse);let wrappedIterables=this._wrappedIterables,reIndex=!isKeyed(this),iterableIdx=0,currentIterator=wrappedIterables[0].__iterator(reverse);function nextStep(){for(;iterableIdx<wrappedIterables.length;){let step=currentIterator.next();if(!step.done)return step;iterableIdx++,iterableIdx<wrappedIterables.length&&(currentIterator=wrappedIterables[iterableIdx].__iterator(reverse))}}if(reIndex){let index=0;return makeEntryIterator(entry=>{let step=nextStep();return step?(entry[0]=index++,entry[1]=step.value[1],!0):!1})}return makeIterator(()=>nextStep()||DONE)}},ToKeyedSequence=class extends KeyedSeqImpl{static{this.prototype[IS_ORDERED_SYMBOL]=!0}constructor(indexed,useKeys){super(),this._iter=indexed,this._useKeys=useKeys,this.size=indexed.size}cacheResult(){return cacheResultThrough.call(this)}get(key,notSetValue){return this._iter.get(key,notSetValue)}has(key){return this._iter.has(key)}valueSeq(){return this._iter.valueSeq()}reverse(){let reversedSequence=reverseFactory(this,!0);return this._useKeys||(reversedSequence.valueSeq=()=>this._iter.toSeq().reverse()),reversedSequence}map(mapper,context){let mappedSequence=mapFactory(this,mapper,context);return this._useKeys||(mappedSequence.valueSeq=()=>this._iter.toSeq().map(mapper,context)),mappedSequence}__iterateUncached(fn,reverse){return this._iter.__iterate(fn,reverse)}__iteratorUncached(reverse){return this._iter.__iterator(reverse)}},ToIndexedSequence=class extends IndexedSeqImpl{constructor(iter){super(),this._iter=iter,this.size=iter.size}cacheResult(){return cacheResultThrough.call(this)}includes(value){return this._iter.includes(value)}__iterateUncached(fn,reverse){let i=0;reverse&&ensureSize(this);let size=this.size;return this._iter.__iterate(v=>{let ii=reverse?size-++i:i++;return fn(v,ii,this)},reverse),i}__iteratorUncached(reverse){let i=0;reverse&&ensureSize(this);let size=this.size;return mapEntries(this._iter.__iterator(reverse),(k,v,entry)=>{entry[0]=reverse?size-++i:i++,entry[1]=v})}},ToSetSequence=class extends SetSeqImpl{constructor(iter){super(),this._iter=iter,this.size=iter.size}cacheResult(){return cacheResultThrough.call(this)}has(key){return this._iter.includes(key)}__iterateUncached(fn,reverse){return this._iter.__iterate(v=>fn(v,v,this),reverse)}__iteratorUncached(reverse){return mapEntries(this._iter.__iterator(reverse),(k,v,entry)=>{entry[0]=v,entry[1]=v})}},FromEntriesSequence=class extends KeyedSeqImpl{constructor(entries){super(),this._iter=entries,this.size=entries.size}cacheResult(){return cacheResultThrough.call(this)}entrySeq(){return this._iter.toSeq()}__iterateUncached(fn,reverse){let iterations=0;return this._iter.__iterate(entry=>{if(entry){validateEntry(entry),iterations++;let indexedCollection=isCollection(entry);return fn(indexedCollection?entry.get(1):entry[1],indexedCollection?entry.get(0):entry[0],this)}},reverse),iterations}__iteratorUncached(reverse){let iterator=this._iter.__iterator(reverse);return makeEntryIterator(out=>{for(;;){let step=iterator.next();if(step.done)return!1;let entry=step.value[1];if(entry){validateEntry(entry);let indexedCollection=isCollection(entry);return out[0]=indexedCollection?entry.get(0):entry[0],out[1]=indexedCollection?entry.get(1):entry[1],!0}}})}};function cacheResultThrough(){return this._iter.cacheResult?(this._iter.cacheResult(),this.size=this._iter.size,this):SeqImpl.prototype.cacheResult.call(this)}function validateEntry(entry){if(entry!==Object(entry))throw new TypeError(`Expected [K, V] tuple: ${entry}`)}var Map2=value=>value==null?emptyMap():isMap(value)&&!isOrdered(value)?value:emptyMap().withMutations(map=>{let iter=KeyedCollection(value);assertNotInfinite(iter.size),iter.forEach((v,k)=>map.set(k,v))}),MapImpl=class extends KeyedCollectionImpl{static{mixin(this,{...mutatorMethods(),...deepPathMethods(),...keyedMergeMethods(),wasAltered,concat:merge,[IS_MAP_SYMBOL]:!0,[DELETE]:this.prototype.remove,removeAll:this.prototype.deleteAll,[Symbol.iterator]:this.prototype.entries,[Symbol.toStringTag]:"Immutable.Map"})}constructor(size,root,ownerID,hash2){super(),this.size=size,this._root=root,this.__ownerID=ownerID,this.__hash=hash2,this.__altered=!1}create(value){return Map2(value)}toString(){return this.__toString("Map {","}")}get(k,notSetValue){return this._root?this._root.get(0,hash(k),k,notSetValue):notSetValue}set(k,v){return updateMap(this,k,v)}remove(k){return updateMap(this,k,NOT_SET)}deleteAll(keys){let collection=Collection(keys);return collection.size===0?this:this.withMutations(map=>{collection.forEach(key=>map.remove(key))})}clear(){return this.size===0?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):emptyMap()}map(mapper,context){return this.withMutations(map=>{map.forEach((value,key)=>{map.set(key,mapper.call(context,value,key,this))})})}keys(){return this._root?mapIteratorGenerator(this._root,!1,0):emptyIterator()}values(){return this._root?mapIteratorGenerator(this._root,!1,1):emptyIterator()}entries(){return this._root?mapIteratorGenerator(this._root,!1):emptyIterator()}__iterator(reverse){return this._root?mapIteratorGenerator(this._root,reverse):emptyIterator()}__iterate(fn,reverse){let iterations=0;return this._root&&this._root.iterate(([key,value])=>(iterations++,fn(value,key,this)),reverse),iterations}__ensureOwner(ownerID){return ownerID===this.__ownerID?this:ownerID?makeMap(this.size,this._root,ownerID,this.__hash):this.size===0?emptyMap():(this.__ownerID=ownerID,this.__altered=!1,this)}};Map2.isMap=isMap;var ArrayMapNode=class _ArrayMapNode{constructor(ownerID,entries){this.ownerID=ownerID,this.entries=entries}get(shift,keyHash,key,notSetValue){return linearGet(this.entries,key,notSetValue)}iterate(fn,reverse){return iterateLinearEntries(this.entries,fn,reverse)}update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){let removed=value===NOT_SET,entries=this.entries,idx=0,len=entries.length;for(;idx<len&&!is(key,entries[idx][0]);idx++);let exists=idx<len;if(exists?entries[idx][1]===value:removed)return this;if(SetRef(didAlter),(removed||!exists)&&SetRef(didChangeSize),removed&&len===1)return;if(!exists&&!removed&&len>=MAX_ARRAY_MAP_SIZE)return createNodes(ownerID,entries,key,value);let isEditable=ownerID&&ownerID===this.ownerID,newEntries=isEditable?entries:entries.slice();return exists?removed?idx===len-1?newEntries.pop():newEntries[idx]=newEntries.pop():newEntries[idx]=[key,value]:newEntries.push([key,value]),isEditable?(this.entries=newEntries,this):new _ArrayMapNode(ownerID,newEntries)}},BitmapIndexedNode=class _BitmapIndexedNode{constructor(ownerID,bitmap,nodes){this.ownerID=ownerID,this.bitmap=bitmap,this.nodes=nodes}iterate(fn,reverse){return iterateNodeArray(this.nodes,fn,reverse)}get(shift,keyHash,key,notSetValue){let bit=1<<((shift===0?keyHash:keyHash>>>shift)&MASK),bitmap=this.bitmap;return(bitmap&bit)===0?notSetValue:this.nodes[popCount(bitmap&bit-1)].get(shift+SHIFT,keyHash,key,notSetValue)}update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){let keyHashFrag=(shift===0?keyHash:keyHash>>>shift)&MASK,bit=1<<keyHashFrag,bitmap=this.bitmap,exists=(bitmap&bit)!==0;if(!exists&&value===NOT_SET)return this;let idx=popCount(bitmap&bit-1),nodes=this.nodes,node=exists?nodes[idx]:void 0,newNode=updateNode(node,ownerID,shift+SHIFT,keyHash,key,value,didChangeSize,didAlter);if(newNode===node)return this;if(!exists&&newNode&&nodes.length>=MAX_BITMAP_INDEXED_SIZE)return expandNodes(ownerID,nodes,bitmap,keyHashFrag,newNode);if(exists&&!newNode&&nodes.length===2&&isLeafNode(nodes[idx^1]))return nodes[idx^1];if(exists&&newNode&&nodes.length===1&&isLeafNode(newNode))return newNode;let isEditable=ownerID&&ownerID===this.ownerID,newBitmap=exists?newNode?bitmap:bitmap^bit:bitmap|bit,newNodes=exists?newNode?setAt(nodes,idx,newNode,isEditable):spliceOut(nodes,idx,isEditable):spliceIn(nodes,idx,newNode,isEditable);return isEditable?(this.bitmap=newBitmap,this.nodes=newNodes,this):new _BitmapIndexedNode(ownerID,newBitmap,newNodes)}},HashArrayMapNode=class _HashArrayMapNode{constructor(ownerID,count,nodes){this.ownerID=ownerID,this.count=count,this.nodes=nodes}iterate(fn,reverse){return iterateNodeArray(this.nodes,fn,reverse)}get(shift,keyHash,key,notSetValue){let idx=(shift===0?keyHash:keyHash>>>shift)&MASK,node=this.nodes[idx];return node?node.get(shift+SHIFT,keyHash,key,notSetValue):notSetValue}update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){let idx=(shift===0?keyHash:keyHash>>>shift)&MASK,removed=value===NOT_SET,nodes=this.nodes,node=nodes[idx];if(removed&&!node)return this;let newNode=updateNode(node,ownerID,shift+SHIFT,keyHash,key,value,didChangeSize,didAlter);if(newNode===node)return this;let newCount=this.count;if(!node)newCount++;else if(!newNode&&(newCount--,newCount<MIN_HASH_ARRAY_MAP_SIZE))return packNodes(ownerID,nodes,newCount,idx);let isEditable=ownerID&&ownerID===this.ownerID,newNodes=setAt(nodes,idx,newNode,isEditable);return isEditable?(this.count=newCount,this.nodes=newNodes,this):new _HashArrayMapNode(ownerID,newCount,newNodes)}},HashCollisionNode=class _HashCollisionNode{constructor(ownerID,keyHash,entries){this.ownerID=ownerID,this.keyHash=keyHash,this.entries=entries}get(shift,keyHash,key,notSetValue){return linearGet(this.entries,key,notSetValue)}iterate(fn,reverse){return iterateLinearEntries(this.entries,fn,reverse)}update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){if(keyHash!==this.keyHash)return value===NOT_SET?this:(SetRef(didAlter),SetRef(didChangeSize),mergeIntoNode(this,ownerID,shift,keyHash,[key,value]));let removed=value===NOT_SET,entries=this.entries,idx=0,len=entries.length;for(;idx<len&&!is(key,entries[idx][0]);idx++);let exists=idx<len;if(exists?entries[idx][1]===value:removed)return this;if(SetRef(didAlter),(removed||!exists)&&SetRef(didChangeSize),removed&&len===2)return new ValueNode(ownerID,this.keyHash,entries[idx^1]);let isEditable=ownerID&&ownerID===this.ownerID,newEntries=isEditable?entries:entries.slice();return exists?removed?idx===len-1?newEntries.pop():newEntries[idx]=newEntries.pop():newEntries[idx]=[key,value]:newEntries.push([key,value]),isEditable?(this.entries=newEntries,this):new _HashCollisionNode(ownerID,this.keyHash,newEntries)}},ValueNode=class _ValueNode{constructor(ownerID,keyHash,entry){this.ownerID=ownerID,this.keyHash=keyHash,this.entry=entry}iterate(fn,_reverse){return fn(this.entry)}get(shift,keyHash,key,notSetValue){return is(key,this.entry[0])?this.entry[1]:notSetValue}update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){let removed=value===NOT_SET,keyMatch=is(key,this.entry[0]);if(keyMatch?value===this.entry[1]:removed)return this;if(SetRef(didAlter),removed){SetRef(didChangeSize);return}return keyMatch?ownerID&&ownerID===this.ownerID?(this.entry[1]=value,this):new _ValueNode(ownerID,this.keyHash,[key,value]):(SetRef(didChangeSize),mergeIntoNode(this,ownerID,shift,hash(key),[key,value]))}};function linearGet(entries,key,notSetValue){for(let ii=0,len=entries.length;ii<len;ii++)if(is(key,entries[ii][0]))return entries[ii][1];return notSetValue}function iterateLinearEntries(entries,fn,reverse){for(let ii=0,maxIndex=entries.length-1;ii<=maxIndex;ii++)if(fn(entries[reverse?maxIndex-ii:ii])===!1)return!1}function iterateNodeArray(nodes,fn,reverse){for(let ii=0,maxIndex=nodes.length-1;ii<=maxIndex;ii++)if(nodes[reverse?maxIndex-ii:ii]?.iterate(fn,reverse)===!1)return!1}function mapIteratorGenerator(node,reverse,entryIndex){let stack={node,index:0,__prev:null},extractValue=entryIndex!==void 0?entry=>entry[entryIndex]:entry=>entry,result={done:!1,value:void 0};return makeIterator(()=>{for(;stack;){let node2=stack.node,index=stack.index++,maxIndex;if(node2.entry){if(index===0)return result.value=extractValue(node2.entry),result}else if(node2.entries){if(maxIndex=node2.entries.length-1,index<=maxIndex)return result.value=extractValue(node2.entries[reverse?maxIndex-index:index]),result}else if(maxIndex=node2.nodes.length-1,index<=maxIndex){let subNode=node2.nodes[reverse?maxIndex-index:index];if(subNode){if(subNode.entry)return result.value=extractValue(subNode.entry),result;stack={node:subNode,index:0,__prev:stack}}continue}stack=stack.__prev}return DONE})}var makeMap=(size,root,ownerID,hash2)=>new MapImpl(size,root,ownerID,hash2),EMPTY_MAP,emptyMap=()=>EMPTY_MAP||(EMPTY_MAP=makeMap(0));function updateMap(map,k,v){let newRoot,newSize;if(map._root){let didChangeSize=MakeRef(),didAlter=MakeRef();if(newRoot=updateNode(map._root,map.__ownerID,0,hash(k),k,v,didChangeSize,didAlter),!didAlter.value)return map;newSize=map.size+(didChangeSize.value?v===NOT_SET?-1:1:0)}else{if(v===NOT_SET)return map;newSize=1,newRoot=new ArrayMapNode(map.__ownerID,[[k,v]])}return map.__ownerID?(map.size=newSize,map._root=newRoot,map.__hash=void 0,map.__altered=!0,map):newRoot?makeMap(newSize,newRoot):emptyMap()}function updateNode(node,ownerID,shift,keyHash,key,value,didChangeSize,didAlter){return node?node.update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter):value===NOT_SET?node:(SetRef(didAlter),SetRef(didChangeSize),new ValueNode(ownerID,keyHash,[key,value]))}var isLeafNode=node=>node.constructor===ValueNode||node.constructor===HashCollisionNode;function mergeIntoNode(node,ownerID,shift,keyHash,entry){if(node.keyHash===keyHash)return new HashCollisionNode(ownerID,keyHash,[node.entry,entry]);let idx1=(shift===0?node.keyHash:node.keyHash>>>shift)&MASK,idx2=(shift===0?keyHash:keyHash>>>shift)&MASK,newNode=new ValueNode(ownerID,keyHash,entry),nodes=idx1===idx2?[mergeIntoNode(node,ownerID,shift+SHIFT,keyHash,entry)]:idx1<idx2?[node,newNode]:[newNode,node];return new BitmapIndexedNode(ownerID,1<<idx1|1<<idx2,nodes)}function createNodes(ownerID,entries,key,value){ownerID||(ownerID=new OwnerID);let node=new ValueNode(ownerID,hash(key),[key,value]);for(let[k,v]of entries)node=node.update(ownerID,0,hash(k),k,v);return node}function packNodes(ownerID,nodes,count,excluding){let bitmap=0,packedII=0,packedNodes=new Array(count);for(let ii=0,bit=1,len=nodes.length;ii<len;ii++,bit<<=1){let node=nodes[ii];node!==void 0&&ii!==excluding&&(bitmap|=bit,packedNodes[packedII++]=node)}return new BitmapIndexedNode(ownerID,bitmap,packedNodes)}function expandNodes(ownerID,nodes,bitmap,including,node){let count=0,expandedNodes=new Array(SIZE);for(let ii=0;bitmap!==0;ii++,bitmap>>>=1)expandedNodes[ii]=bitmap&1?nodes[count++]:void 0;return expandedNodes[including]=node,new HashArrayMapNode(ownerID,count+1,expandedNodes)}function popCount(x){return x-=x>>1&1431655765,x=(x&858993459)+(x>>2&858993459),x=x+(x>>4)&252645135,x+=x>>8,x+=x>>16,x&127}function setAt(array,idx,val,canEdit){let newArray=canEdit?array:array.slice();return newArray[idx]=val,newArray}function spliceIn(array,idx,val,canEdit){let newLen=array.length+1;if(canEdit&&idx+1===newLen)return array[idx]=val,array;let newArray=new Array(newLen),after=0;for(let ii=0;ii<newLen;ii++)ii===idx?(newArray[ii]=val,after=-1):newArray[ii]=array[ii+after];return newArray}function spliceOut(array,idx,canEdit){let newLen=array.length-1;if(canEdit&&idx===newLen)return array.pop(),array;let newArray=new Array(newLen),after=0;for(let ii=0;ii<newLen;ii++)ii===idx&&(after=1),newArray[ii]=array[ii+after];return newArray}var MAX_ARRAY_MAP_SIZE=SIZE/4,MAX_BITMAP_INDEXED_SIZE=SIZE/2,MIN_HASH_ARRAY_MAP_SIZE=SIZE/4;function shallowCopy(from){return Array.isArray(from)?from.slice():{...from}}var merge$1=(collection,...sources)=>mergeWithSources(collection,sources),mergeWith$1=(merger,collection,...sources)=>mergeWithSources(collection,sources,merger),mergeDeepWithSources=(collection,sources,merger)=>mergeWithSources(collection,sources,deepMergerWith(merger)),mergeDeep$1=(collection,...sources)=>mergeDeepWithSources(collection,sources),mergeDeepWith$1=(merger,collection,...sources)=>mergeDeepWithSources(collection,sources,merger);function mergeWithSources(collection,sources,merger){if(!isDataStructure(collection))throw new TypeError(`Cannot merge into non-data-structure value: ${collection}`);if(isImmutable(collection))return typeof merger=="function"&&collection.mergeWith?collection.mergeWith(merger,...sources):collection.merge?collection.merge(...sources):collection.concat(...sources);let isArray=Array.isArray(collection),merged=collection,Collection2=isArray?IndexedCollection:KeyedCollection,mergeItem=isArray?value=>{merged===collection&&(merged=shallowCopy(merged)),merged.push(value)}:(value,key)=>{let hasVal=Object.hasOwn(merged,key),nextVal=hasVal&&merger?merger(merged[key],value,key):value;(!hasVal||nextVal!==merged[key])&&(merged===collection&&(merged=shallowCopy(merged)),merged[key]=nextVal)};for(let source of sources)Collection2(source).forEach(mergeItem);return merged}function deepMergerWith(merger){function deepMerger(oldValue,newValue,key){return isDataStructure(oldValue)&&isDataStructure(newValue)&&areMergeable(oldValue,newValue)?mergeWithSources(oldValue,[newValue],deepMerger):merger?merger(oldValue,newValue,key):newValue}return deepMerger}function areMergeable(oldDataStructure,newDataStructure){let oldSeq=Seq(oldDataStructure),newSeq=Seq(newDataStructure);return isIndexed(oldSeq)===isIndexed(newSeq)&&isKeyed(oldSeq)===isKeyed(newSeq)}function remove(collection,key){if(!isDataStructure(collection))throw new TypeError(`Cannot update non-data-structure value: ${collection}`);if(isImmutable(collection)){if(!collection.remove)throw new TypeError(`Cannot update immutable value without .remove() method: ${collection}`);return collection.remove(key)}if(!Object.hasOwn(collection,key))return collection;let collectionCopy=shallowCopy(collection);return Array.isArray(collectionCopy)?collectionCopy.splice(key,1):delete collectionCopy[key],collectionCopy}function set(collection,key,value){if(!isDataStructure(collection))throw new TypeError(`Cannot update non-data-structure value: ${collection}`);if(isImmutable(collection)){if(!collection.set)throw new TypeError(`Cannot update immutable value without .set() method: ${collection}`);return collection.set(key,value)}if(Object.hasOwn(collection,key)&&value===collection[key])return collection;let collectionCopy=shallowCopy(collection);return collectionCopy[key]=value,collectionCopy}function updateIn$1(collection,keyPath,notSetValue,updater){updater||(updater=notSetValue,notSetValue=void 0);let updatedValue=updateInDeeply(isImmutable(collection),collection,coerceKeyPath(keyPath),0,notSetValue,updater);return updatedValue===NOT_SET?notSetValue:updatedValue}function updateInDeeply(inImmutable,existing,keyPath,i,notSetValue,updater){let wasNotSet=existing===NOT_SET;if(i===keyPath.length){let existingValue=wasNotSet?notSetValue:existing,newValue=updater(existingValue);return newValue===existingValue?existing:newValue}if(!wasNotSet&&!isDataStructure(existing))throw new TypeError(`Cannot update within non-data-structure value in path [${Array.from(keyPath).slice(0,i).map(quoteString)}]: ${existing}`);let key=keyPath[i],nextExisting=wasNotSet?NOT_SET:get(existing,key,NOT_SET),nextUpdated=updateInDeeply(nextExisting===NOT_SET?inImmutable:isImmutable(nextExisting),nextExisting,keyPath,i+1,notSetValue,updater);if(nextUpdated===nextExisting)return existing;if(nextUpdated===NOT_SET)return remove(existing,key);let collection=wasNotSet?inImmutable?emptyMap():{}:existing;return set(collection,key,nextUpdated)}var removeIn=(collection,keyPath)=>updateIn$1(collection,keyPath,()=>NOT_SET),setIn$1=(collection,keyPath,value)=>updateIn$1(collection,keyPath,NOT_SET,()=>value);function update$1(collection,key,notSetValue,updater){return updateIn$1(collection,[key],notSetValue,updater)}function asImmutable(){return this.__ensureOwner()}function asMutable(){return this.__ownerID?this:this.__ensureOwner(new OwnerID)}function wasAltered(){return this.__altered}function withMutations(fn){let mutable=this.asMutable();return fn(mutable),mutable.wasAltered()?mutable.__ensureOwner(this.__ownerID):this}function getIn(searchKeyPath,notSetValue){return getIn$1(this,searchKeyPath,notSetValue)}function hasIn(searchKeyPath){return hasIn$1(this,searchKeyPath)}function deleteIn(keyPath){return removeIn(this,keyPath)}function setIn(keyPath,v){return setIn$1(this,keyPath,v)}function update(key,notSetValue,updater){return typeof key=="function"?key(this):update$1(this,key,notSetValue,updater)}function updateIn(keyPath,notSetValue,updater){return updateIn$1(this,keyPath,notSetValue,updater)}function toObject(){assertNotInfinite(this.size);let object={};return this.__iterate((v,k)=>{object[k]=v}),object}function merge(...iters){return mergeIntoKeyedWith(this,iters)}function mergeWith(merger,...iters){if(typeof merger!="function")throw new TypeError(`Invalid merger function: ${merger}`);return mergeIntoKeyedWith(this,iters,merger)}function mergeIntoKeyedWith(collection,collections,merger){let iters=[];for(let item of collections){let collection2=KeyedCollection(item);collection2.size!==0&&iters.push(collection2)}return iters.length===0?collection:collection.toSeq().size===0&&!collection.__ownerID&&iters.length===1?isRecord(collection)?collection:collection.create(iters[0]):collection.withMutations(collection2=>{let mergeIntoCollection=merger?(value,key)=>{update$1(collection2,key,NOT_SET,oldVal=>oldVal===NOT_SET?value:merger(oldVal,value,key))}:(value,key)=>{collection2.set(key,value)};for(let iter of iters)iter.forEach(mergeIntoCollection)})}function mergeDeep(...iters){return mergeDeepWithSources(this,iters)}function mergeDeepWith(merger,...iters){return mergeDeepWithSources(this,iters,merger)}function mergeIn(keyPath,...iters){return updateIn$1(this,keyPath,emptyMap(),m=>mergeWithSources(m,iters))}function mergeDeepIn(keyPath,...iters){return updateIn$1(this,keyPath,emptyMap(),m=>mergeDeepWithSources(m,iters))}function mixin(Class,methods){Object.assign(Class.prototype,methods)}function mutatorMethods(){return{asImmutable,asMutable,withMutations}}function deepPathMethods(){return{deleteIn,removeIn:deleteIn,mergeDeepIn,mergeIn,setIn,update,updateIn}}function keyedMergeMethods(){return{merge,mergeWith,mergeDeep,mergeDeepWith}}var List=value=>{let empty=emptyList();if(value==null)return empty;if(isList(value))return value;let iter=IndexedCollection(value),size=iter.size;return size===0?empty:(assertNotInfinite(size),size>0&&size<SIZE?makeList(0,size,SHIFT,null,new VNode(iter.toArray())):empty.withMutations(list=>{list.setSize(size),iter.forEach((v,i)=>list.set(i,v))}))};List.of=(...values)=>List(values);var ListImpl=class extends IndexedCollectionImpl{static{mixin(this,{...mutatorMethods(),...deepPathMethods(),wasAltered,[IS_LIST_SYMBOL]:!0,[DELETE]:this.prototype.remove,merge:this.prototype.concat,[Symbol.toStringTag]:"Immutable.List",[Symbol.iterator]:this.prototype.values})}constructor(origin,capacity,level,root,tail,ownerID,hash2){super(),this.size=capacity-origin,this._origin=origin,this._capacity=capacity,this._level=level,this._root=root,this._tail=tail,this.__ownerID=ownerID,this.__hash=hash2,this.__altered=!1}create(value){return List(value)}toString(){return this.__toString("List [","]")}get(index,notSetValue){return index=wrapIndex(this,index),index>=0&&index<this.size?(index+=this._origin,listNodeFor(this,index)?.array[index&MASK]):notSetValue}set(index,value){return updateList(this,index,value)}remove(index){return this.has(index)?index===0?this.shift():index===this.size-1?this.pop():this.splice(index,1):this}insert(index,value){return this.splice(index,0,value)}clear(){return this.size===0?this:this.__ownerID?(this.size=this._origin=this._capacity=0,this._level=SHIFT,this._root=this._tail=this.__hash=void 0,this.__altered=!0,this):emptyList()}push(...values){let oldSize=this.size;return this.withMutations(list=>{setListBounds(list,0,oldSize+values.length);for(let ii=0;ii<values.length;ii++)list.set(oldSize+ii,values[ii])})}pop(){return setListBounds(this,0,-1)}unshift(...values){return this.withMutations(list=>{setListBounds(list,-values.length);for(let ii=0;ii<values.length;ii++)list.set(ii,values[ii])})}shift(){return setListBounds(this,1)}shuffle(random=Math.random){return this.withMutations(mutable=>{let current=mutable.size,destination,tmp;for(;current;)destination=Math.floor(random()*current--),tmp=mutable.get(destination),mutable.set(destination,mutable.get(current)),mutable.set(current,tmp)})}concat(...collections){let seqs=[];for(let collection of collections){let seq=IndexedCollection(typeof collection!="string"&&hasIterator(collection)?collection:[collection]);seq.size!==0&&seqs.push(seq)}return seqs.length===0?this:this.size===0&&!this.__ownerID&&seqs.length===1?List(seqs[0]):this.withMutations(list=>{seqs.forEach(seq=>seq.forEach(value=>list.push(value)))})}setSize(size){return setListBounds(this,0,size)}map(mapper,context){return this.withMutations(list=>{for(let i=0;i<this.size;i++)list.set(i,mapper.call(context,list.get(i),i,this))})}slice(begin,end){let size=this.size;return wholeSlice(begin,end,size)?this:setListBounds(this,resolveBegin(begin,size),resolveEnd(end,size))}__iterate(fn,reverse){let index=reverse?this.size:0;return iterateListCallback(this,value=>fn(value,reverse?--index:index++,this),reverse),reverse?this.size-index:index}__iterator(reverse){let index=reverse?this.size:0,iter=iterateList(this,reverse);return makeEntryIterator(entry=>{let step=iter.next();return step.done?!1:(entry[0]=reverse?--index:index++,entry[1]=step.value,!0)})}values(){return iterateList(this,!1)}keys(){return makeIndexKeys(this.size)}__ensureOwner(ownerID){return ownerID===this.__ownerID?this:ownerID?makeList(this._origin,this._capacity,this._level,this._root,this._tail,ownerID,this.__hash):this.size===0?emptyList():(this.__ownerID=ownerID,this.__altered=!1,this)}};List.isList=isList;var VNode=class _VNode{constructor(array,ownerID){this.array=array,this.ownerID=ownerID}removeBefore(ownerID,level,index){if((index&(1<<level+SHIFT)-1)===0||this.array.length===0)return this;let originIndex=index>>>level&MASK;if(originIndex>=this.array.length)return new _VNode([],ownerID);let removingFirst=originIndex===0,newChild;if(level>0){let oldChild=this.array[originIndex];if(newChild=oldChild?.removeBefore(ownerID,level-SHIFT,index),newChild===oldChild&&removingFirst)return this}if(removingFirst&&!newChild)return this;let editable=editableVNode(this,ownerID);if(!removingFirst)for(let ii=0;ii<originIndex;ii++)editable.array[ii]=void 0;return newChild&&(editable.array[originIndex]=newChild),editable}removeAfter(ownerID,level,index){if(index===(level?1<<level+SHIFT:SIZE)||this.array.length===0)return this;let sizeIndex=index-1>>>level&MASK;if(sizeIndex>=this.array.length)return this;let newChild;if(level>0){let oldChild=this.array[sizeIndex];if(newChild=oldChild?.removeAfter(ownerID,level-SHIFT,index),newChild===oldChild&&sizeIndex===this.array.length-1)return this}let editable=editableVNode(this,ownerID);return editable.array.splice(sizeIndex+1),newChild&&(editable.array[sizeIndex]=newChild),editable}};function iterateList(list,reverse){let left=list._origin,right=list._capacity,tailPos=getTailOffset(right),tail=list._tail,stack=[];pushFrame(list._root,list._level,0);let result={done:!1,value:void 0};return makeIterator(()=>{for(;stack.length>0;){let frame=stack[stack.length-1];if(frame.from===frame.to){stack.pop();continue}let idx=reverse?--frame.to:frame.from++;if(frame.isLeaf)return result.value=frame.array?.[idx],result;let childNode=frame.array?.[idx],childLevel=frame.level-SHIFT,childOffset=frame.offset+(idx<<frame.level);pushFrame(childNode,childLevel,childOffset)}return DONE});function pushFrame(node,level,offset){if(level===0){let array=offset===tailPos?tail?.array:node?.array,from=offset>left?0:left-offset,to=right-offset;to>SIZE&&(to=SIZE),from!==to&&stack.push({array,from,to,isLeaf:!0})}else{let array=node?.array,from=offset>left?0:left-offset>>level,to=(right-offset>>level)+1;to>SIZE&&(to=SIZE),from!==to&&stack.push({array,from,to,level,offset,isLeaf:!1})}}}function iterateListCallback(list,fn,reverse){let left=list._origin,right=list._capacity,tailPos=getTailOffset(right),tail=list._tail,level=list._level,root=list._root;return level===0?iterateLeaf(root,0,left,right,tailPos,tail,fn,reverse):iterateNode(root,level,0,left,right,tailPos,tail,fn,reverse)}function iterateLeaf(node,offset,left,right,tailPos,tail,fn,reverse){let array=offset===tailPos?tail?.array:node?.array,from=offset>left?0:left-offset,to=right-offset;for(to>SIZE&&(to=SIZE);from!==to;){let idx=reverse?--to:from++;if(fn(array?.[idx])===!1)return!1}}function iterateNode(node,level,offset,left,right,tailPos,tail,fn,reverse){let array=node?.array,from=offset>left?0:left-offset>>level,to=(right-offset>>level)+1;to>SIZE&&(to=SIZE);let nextLevel=level-SHIFT;for(;from!==to;){let idx=reverse?--to:from++,nextOffset=offset+(idx<<level);if((nextLevel===0?iterateLeaf(array?.[idx],nextOffset,left,right,tailPos,tail,fn,reverse):iterateNode(array?.[idx],nextLevel,nextOffset,left,right,tailPos,tail,fn,reverse))===!1)return!1}}var makeList=(origin,capacity,level,root,tail,ownerID,hash2)=>new ListImpl(origin,capacity,level,root,tail,ownerID,hash2),emptyList=()=>makeList(0,0,SHIFT);function updateList(list,index,value){if(index=wrapIndex(list,index),Number.isNaN(index))return list;if(index>=list.size||index<0)return list.withMutations(list2=>{index<0?setListBounds(list2,index).set(0,value):setListBounds(list2,0,index+1).set(index,value)});index+=list._origin;let newTail=list._tail,newRoot=list._root,didAlter=MakeRef();return index>=getTailOffset(list._capacity)?newTail=updateVNode(newTail,list.__ownerID,0,index,value,didAlter):newRoot=updateVNode(newRoot,list.__ownerID,list._level,index,value,didAlter),didAlter.value?list.__ownerID?(list._root=newRoot,list._tail=newTail,list.__hash=void 0,list.__altered=!0,list):makeList(list._origin,list._capacity,list._level,newRoot,newTail):list}function updateVNode(node,ownerID,level,index,value,didAlter){let idx=index>>>level&MASK,nodeHas=node&&idx<node.array.length;if(!nodeHas&&value===void 0)return node;let newNode;if(level>0){let lowerNode=node?.array[idx],newLowerNode=updateVNode(lowerNode,ownerID,level-SHIFT,index,value,didAlter);return newLowerNode===lowerNode?node:(newNode=editableVNode(node,ownerID),newNode.array[idx]=newLowerNode,newNode)}return nodeHas&&node.array[idx]===value?node:(didAlter&&SetRef(didAlter),newNode=editableVNode(node,ownerID),value===void 0&&idx===newNode.array.length-1?newNode.array.pop():newNode.array[idx]=value,newNode)}function editableVNode(node,ownerID){return ownerID&&ownerID===node?.ownerID?node:new VNode(node?.array.slice()??[],ownerID)}function listNodeFor(list,rawIndex){if(rawIndex>=getTailOffset(list._capacity))return list._tail;if(rawIndex<1<<list._level+SHIFT){let node=list._root,level=list._level;for(;node&&level>0;)node=node.array[rawIndex>>>level&MASK],level-=SHIFT;return node}}function setListBounds(list,begin,end){begin!==void 0&&(begin|=0),end!==void 0&&(end|=0);let owner=list.__ownerID||new OwnerID,oldOrigin=list._origin,oldCapacity=list._capacity,newOrigin=oldOrigin+begin,newCapacity=end===void 0?oldCapacity:end<0?oldCapacity+end:oldOrigin+end;if(newOrigin===oldOrigin&&newCapacity===oldCapacity)return list;if(newOrigin>=newCapacity)return list.clear();let newLevel=list._level,newRoot=list._root,offsetShift=0;for(;newOrigin+offsetShift<0;)newRoot=new VNode(newRoot?.array.length?[void 0,newRoot]:[],owner),newLevel+=SHIFT,offsetShift+=1<<newLevel;offsetShift&&(newOrigin+=offsetShift,oldOrigin+=offsetShift,newCapacity+=offsetShift,oldCapacity+=offsetShift);let oldTailOffset=getTailOffset(oldCapacity),newTailOffset=getTailOffset(newCapacity);for(;newTailOffset>=1<<newLevel+SHIFT;)newRoot=new VNode(newRoot?.array.length?[newRoot]:[],owner),newLevel+=SHIFT;let oldTail=list._tail,newTail=newTailOffset<oldTailOffset?listNodeFor(list,newCapacity-1):newTailOffset>oldTailOffset?new VNode([],owner):oldTail;if(oldTail&&newTailOffset>oldTailOffset&&newOrigin<oldCapacity&&oldTail.array.length){newRoot=editableVNode(newRoot,owner);let node=newRoot;for(let level=newLevel;level>SHIFT;level-=SHIFT){let idx=oldTailOffset>>>level&MASK;node=node.array[idx]=editableVNode(node.array[idx],owner)}node.array[oldTailOffset>>>SHIFT&MASK]=oldTail}if(newCapacity<oldCapacity&&(newTail=newTail?.removeAfter(owner,0,newCapacity)),newOrigin>=newTailOffset)newOrigin-=newTailOffset,newCapacity-=newTailOffset,newLevel=SHIFT,newRoot=null,newTail=newTail?.removeBefore(owner,0,newOrigin);else if(newOrigin>oldOrigin||newTailOffset<oldTailOffset){for(offsetShift=0;newRoot;){let beginIndex=newOrigin>>>newLevel&MASK;if(beginIndex!==newTailOffset>>>newLevel&MASK)break;beginIndex&&(offsetShift+=(1<<newLevel)*beginIndex),newLevel-=SHIFT,newRoot=newRoot.array[beginIndex]}newRoot&&newOrigin>oldOrigin&&(newRoot=newRoot.removeBefore(owner,newLevel,newOrigin-offsetShift)),newRoot&&newTailOffset<oldTailOffset&&(newRoot=newRoot.removeAfter(owner,newLevel,newTailOffset-offsetShift)),offsetShift&&(newOrigin-=offsetShift,newCapacity-=offsetShift)}return list.__ownerID?(list.size=newCapacity-newOrigin,list._origin=newOrigin,list._capacity=newCapacity,list._level=newLevel,list._root=newRoot,list._tail=newTail,list.__hash=void 0,list.__altered=!0,list):makeList(newOrigin,newCapacity,newLevel,newRoot,newTail)}var getTailOffset=size=>size<SIZE?0:size-1>>>SHIFT<<SHIFT,OrderedMap=value=>value==null?emptyOrderedMap():isOrderedMap(value)?value:emptyOrderedMap().withMutations(map=>{let iter=KeyedCollection(value);assertNotInfinite(iter.size),iter.forEach((v,k)=>map.set(k,v))});OrderedMap.of=(...values)=>OrderedMap(values);var OrderedMapImpl=class extends MapImpl{static{mixin(this,{[IS_ORDERED_SYMBOL]:!0,[DELETE]:this.prototype.remove,[Symbol.iterator]:this.prototype.entries,[Symbol.toStringTag]:"Immutable.OrderedMap",keys:CollectionImpl.prototype.keys,values:CollectionImpl.prototype.values,__iterate:CollectionImpl.prototype.__iterate})}_map;_list;constructor(map,list,ownerID,hash2){super(map?map.size:0,void 0,ownerID,hash2),this._map=map,this._list=list}create(value){return OrderedMap(value)}toString(){return this.__toString("OrderedMap {","}")}get(k,notSetValue){let index=this._map.get(k);return index!==void 0?this._list.get(index)[1]:notSetValue}clear(){return this.size===0?this:this.__ownerID?(this.size=0,this._map.clear(),this._list.clear(),this.__altered=!0,this):emptyOrderedMap()}set(k,v){return updateOrderedMap(this,k,v)}remove(k){return updateOrderedMap(this,k,NOT_SET)}entries(){return this.__iterator(!1)}__iterator(reverse){let listIter=this._list.__iterator(reverse);return makeEntryIterator(entry=>{for(;;){let step=listIter.next();if(step.done)return!1;let e=step.value[1];if(e)return entry[0]=e[0],entry[1]=e[1],!0}})}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;let newMap=this._map.__ensureOwner(ownerID),newList=this._list.__ensureOwner(ownerID);return ownerID?makeOrderedMap(newMap,newList,ownerID,this.__hash):this.size===0?emptyOrderedMap():(this.__ownerID=ownerID,this.__altered=!1,this._map=newMap,this._list=newList,this)}};OrderedMap.isOrderedMap=isOrderedMap;var makeOrderedMap=(map,list,ownerID,hash2)=>new OrderedMapImpl(map,list,ownerID,hash2),emptyOrderedMap=()=>makeOrderedMap(emptyMap(),emptyList());function updateOrderedMap(omap,k,v){let{_map:map,_list:list}=omap,i=map.get(k),has2=i!==void 0,newMap,newList;if(v===NOT_SET){if(!has2)return omap;if(list.size>=SIZE&&list.size>=map.size*2){let entries=[];list.forEach((entry,idx)=>{entry!==void 0&&i!==idx&&entries.push(entry)}),newList=emptyList().withMutations(l=>{for(let j=0;j<entries.length;j++)l.set(j,entries[j])}),newMap=emptyMap().withMutations(m=>{for(let j=0;j<entries.length;j++)m.set(entries[j][0],j)}),omap.__ownerID&&(newMap.__ownerID=newList.__ownerID=omap.__ownerID)}else newMap=map.remove(k),newList=i===list.size-1?list.pop():list.set(i,void 0)}else if(has2){if(v===list.get(i)[1])return omap;newMap=map,newList=list.set(i,[k,v])}else{let newIdx=list.size;newMap=map.set(k,newIdx),newList=list.set(newIdx,[k,v])}return omap.__ownerID?(omap.size=newMap.size,omap._map=newMap,omap._list=newList,omap.__hash=void 0,omap.__altered=!0,omap):makeOrderedMap(newMap,newList)}var Stack=value=>value==null?emptyStack():isStack(value)?value:emptyStack().pushAll(value);Stack.of=(...values)=>Stack(values);var StackImpl=class extends IndexedCollectionImpl{static{mixin(this,{...mutatorMethods(),wasAltered,[IS_STACK_SYMBOL]:!0,shift:this.prototype.pop,unshift:this.prototype.push,unshiftAll:this.prototype.pushAll,[Symbol.toStringTag]:"Immutable.Stack",[Symbol.iterator]:this.prototype.values})}_head;__ownerID;__altered;constructor(size,head,ownerID,hash2){super(),this.size=size,this._head=head,this.__ownerID=ownerID,this.__hash=hash2,this.__altered=!1}create(value){return Stack(value)}toString(){return this.__toString("Stack [","]")}get(index,notSetValue){let head=this._head;for(index=wrapIndex(this,index);head&&index--;)head=head.next;return head?head.value:notSetValue}peek(){return this._head?.value}push(...values){if(values.length===0)return this;let newSize=this.size+values.length,head=this._head;for(let ii=values.length-1;ii>=0;ii--)head={value:values[ii],next:head};return returnStack(this,newSize,head)}pushAll(iter){let collection=IndexedCollection(iter);if(collection.size===0)return this;if(this.size===0&&isStack(collection))return collection;assertNotInfinite(collection.size);let newSize=this.size,head=this._head;return collection.__iterate(value=>{newSize++,head={value,next:head}},!0),returnStack(this,newSize,head)}pop(){return this.slice(1)}clear(){return this.size===0?this:this.__ownerID?(this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):emptyStack()}slice(begin,end){if(wholeSlice(begin,end,this.size))return this;let resolvedBegin=resolveBegin(begin,this.size);if(resolveEnd(end,this.size)!==this.size)return IndexedCollectionImpl.prototype.slice.call(this,begin,end);let newSize=this.size-resolvedBegin,head=this._head;for(;resolvedBegin--;)head=head?.next;return returnStack(this,newSize,head)}__ensureOwner(ownerID){return ownerID===this.__ownerID?this:ownerID?makeStack(this.size,this._head,ownerID,this.__hash):this.size===0?emptyStack():(this.__ownerID=ownerID,this.__altered=!1,this)}__iterate(fn,reverse=!1){if(reverse){let arr=this.toArray(),size=arr.length,i=0;for(;i!==size&&fn(arr[size-++i],size-i,this)!==!1;);return i}let iterations=0,node=this._head;for(;node&&fn(node.value,iterations++,this)!==!1;)node=node.next;return iterations}__iterator(reverse=!1){if(reverse){let arr=this.toArray(),size=arr.length,i=0;return makeEntryIterator(entry=>{if(i===size)return!1;let ii=size-++i;return entry[0]=ii,entry[1]=arr[ii],!0})}let iterations=0,node=this._head;return makeEntryIterator(entry=>node?(entry[0]=iterations++,entry[1]=node.value,node=node.next,!0):!1)}values(){let node=this._head,result={done:!1,value:void 0};return makeIterator(()=>node?(result.value=node.value,node=node.next,result):DONE)}keys(){return makeIndexKeys(this.size)}};Stack.isStack=isStack;function returnStack(stack,newSize,head){return stack.__ownerID?(stack.size=newSize,stack._head=head,stack.__hash=void 0,stack.__altered=!0,stack):makeStack(newSize,head)}var makeStack=(size,head,ownerID,hash2)=>new StackImpl(size,head,ownerID,hash2),EMPTY_STACK,emptyStack=()=>EMPTY_STACK||(EMPTY_STACK=makeStack(0)),Set2=value=>value==null?emptySet():isSet(value)&&!isOrdered(value)?value:emptySet().withMutations(set2=>{let iter=SetCollection(value);assertNotInfinite(iter.size),iter.forEach(v=>set2.add(v))});Set2.of=(...values)=>Set2(values);Set2.fromKeys=value=>Set2(KeyedCollection(value).keySeq());Set2.intersect=sets=>{let setArray=Collection(sets).toArray();return setArray.length?Set2(setArray.pop()).intersect(...setArray):emptySet()};Set2.union=sets=>{let setArray=Collection(sets).toArray();return setArray.length?Set2(setArray.pop()).union(...setArray):emptySet()};var SetImpl=class extends SetCollectionImpl{static{mixin(this,{...mutatorMethods(),[IS_SET_SYMBOL]:!0,[DELETE]:this.prototype.remove,merge:this.prototype.union,concat:this.prototype.union,[Symbol.toStringTag]:"Immutable.Set"})}_map;__ownerID;constructor(map,ownerID){super(),this.size=map?map.size:0,this._map=map,this.__ownerID=ownerID}create(value){return Set2(value)}toString(){return this.__toString("Set {","}")}has(value){return this._map.has(value)}add(value){return updateSet(this,this._map.set(value,value))}remove(value){return updateSet(this,this._map.remove(value))}clear(){return updateSet(this,this._map.clear())}map(mapper,context){let didChanges=!1,newMap=updateSet(this,this._map.mapEntries(([,v])=>{let mapped=mapper.call(context,v,v,this);return mapped!==v&&(didChanges=!0),[mapped,mapped]},context));return didChanges?newMap:this}union(...iters){return iters=iters.filter(x=>x.size!==0),iters.length===0?this:this.size===0&&!this.__ownerID&&iters.length===1&&!isOrdered(this)?Set2(iters[0]):this.withMutations(set2=>{for(let iter of iters)typeof iter=="string"?set2.add(iter):SetCollection(iter).forEach(value=>set2.add(value))})}intersect(...iters){return filterByIters(this,iters,(value,sets)=>!sets.every(iter=>iter.includes(value)))}subtract(...iters){return filterByIters(this,iters,(value,sets)=>sets.some(iter=>iter.includes(value)))}wasAltered(){return this._map.wasAltered()}__iterator(reverse){return this._map.__iterator(reverse)}__empty(){return emptySet()}__make(map,ownerID){return makeSet(map,ownerID)}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;let newMap=this._map.__ensureOwner(ownerID);return ownerID?this.__make(newMap,ownerID):this.size===0?this.__empty():(this.__ownerID=ownerID,this._map=newMap,this)}};Set2.isSet=isSet;var makeSet=(map,ownerID)=>new SetImpl(map,ownerID),EMPTY_SET,emptySet=()=>EMPTY_SET||(EMPTY_SET=makeSet(emptyMap()));function filterByIters(set2,iters,shouldRemove){if(iters.length===0)return set2;let sets=iters.map(iter=>SetCollection(iter));return set2.withMutations(s=>{set2.forEach(value=>{shouldRemove(value,sets)&&s.remove(value)})})}function updateSet(set2,newMap){return set2.__ownerID?(set2.size=newMap.size,set2._map=newMap,set2):newMap===set2._map?set2:newMap.size===0?set2.__empty():set2.__make(newMap)}var OrderedSet=value=>value==null?emptyOrderedSet():isOrderedSet(value)?value:emptyOrderedSet().withMutations(set2=>{let iter=SetCollection(value);assertNotInfinite(iter.size),iter.forEach(v=>set2.add(v))});OrderedSet.of=(...values)=>OrderedSet(values);OrderedSet.fromKeys=value=>OrderedSet(KeyedCollection(value).keySeq());var OrderedSetImpl=class extends SetImpl{static{mixin(this,{[IS_ORDERED_SYMBOL]:!0,[Symbol.toStringTag]:"Immutable.OrderedSet",zip:IndexedCollectionPrototype.zip,zipWith:IndexedCollectionPrototype.zipWith,zipAll:IndexedCollectionPrototype.zipAll})}create(value){return OrderedSet(value)}toString(){return this.__toString("OrderedSet {","}")}__empty(){return emptyOrderedSet()}__make(map,ownerID){return makeOrderedSet(map,ownerID)}};OrderedSet.isOrderedSet=isOrderedSet;var makeOrderedSet=(map,ownerID)=>new OrderedSetImpl(map,ownerID),emptyOrderedSet=()=>makeOrderedSet(emptyOrderedMap()),PairSorting={LeftThenRight:-1,RightThenLeft:1};function throwOnInvalidDefaultValues(defaultValues){if(isRecord(defaultValues))throw new Error("Can not call `Record` with an immutable Record as default values. Use a plain javascript object instead.");if(isImmutable(defaultValues))throw new Error("Can not call `Record` with an immutable Collection as default values. Use a plain javascript object instead.");if(defaultValues===null||typeof defaultValues!="object")throw new Error("Can not call `Record` with a non-object as default values. Use a plain javascript object instead.")}var Record=(defaultValues,name)=>{let hasInitialized;throwOnInvalidDefaultValues(defaultValues);let RecordType=function(values){if(values instanceof RecordType)return values;if(!(this instanceof RecordType))return new RecordType(values);if(!hasInitialized){hasInitialized=!0;let keys=Object.keys(defaultValues),indices=RecordTypePrototype._indices={};RecordTypePrototype._name=name,RecordTypePrototype._keys=keys,RecordTypePrototype._defaultValues=defaultValues;for(let i=0;i<keys.length;i++){let propName=keys[i];indices[propName]=i,RecordTypePrototype[propName]?console.warn(`Cannot define ${recordName(this)} with property "${propName}" since that property name is part of the Record API.`):setProp(RecordTypePrototype,propName)}}return this.__ownerID=void 0,this._values=List().withMutations(l=>{l.setSize(this._keys.length),KeyedCollection(values).forEach((v,k)=>{l.set(this._indices[k],v===this._defaultValues[k]?void 0:v)})}),this},RecordTypePrototype=RecordType.prototype=Object.create(RecordPrototype);return RecordTypePrototype.constructor=RecordType,RecordTypePrototype.create=RecordType,name&&(RecordType.displayName=name),RecordType},RecordImpl=class{static{mixin(this,{...mutatorMethods(),...deepPathMethods(),...keyedMergeMethods(),getIn,hasIn,toObject,toJSON:toObject,[IS_RECORD_SYMBOL]:!0,[DELETE]:this.prototype.remove,[Symbol.iterator]:this.prototype.entries,[Symbol.toStringTag]:"Immutable.Record"})}toString(){let body=this._keys.map(k=>`${k}: ${quoteString(this.get(k))}`).join(", ");return`${recordName(this)} { ${body} }`}equals(other){return this===other||isRecord(other)&&recordSeq(this).equals(recordSeq(other))}hashCode(){return recordSeq(this).hashCode()}has(k){return Object.hasOwn(this._indices,k)}get(k,notSetValue){if(!this.has(k))return notSetValue;let index=this._indices[k],value=this._values.get(index);return value===void 0?this._defaultValues[k]:value}set(k,v){if(this.has(k)){let newValues=this._values.set(this._indices[k],v===this._defaultValues[k]?void 0:v);if(newValues!==this._values&&!this.__ownerID)return makeRecord(this,newValues)}return this}remove(k){return this.set(k)}clear(){let newValues=this._values.clear().setSize(this._keys.length);return this.__ownerID?this:makeRecord(this,newValues)}wasAltered(){return this._values.wasAltered()}toSeq(){return recordSeq(this)}toJS(){return toJS(this)}entries(){return this.__iterator()}__iterate(fn,reverse){return recordSeq(this).__iterate(fn,reverse)}__iterator(reverse){return recordSeq(this).__iterator(reverse)}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;let newValues=this._values.__ensureOwner(ownerID);return ownerID?makeRecord(this,newValues,ownerID):(this.__ownerID=ownerID,this._values=newValues,this)}};Record.isRecord=isRecord;var recordName=record=>record.constructor.displayName||record.constructor.name||"Record",RecordSeq=class extends KeyedSeqImpl{constructor(record){super(),this._record=record,this.size=record._keys.length}get(key,notSetValue){return this._record.get(key,notSetValue)}has(key){return this._record.has(key)}__iterateUncached(fn,reverse){let record=this._record,keys=record._keys,size=keys.length,i=0;for(;i!==size;){let ii=reverse?size-++i:i++,k=keys[ii];if(fn(record.get(k),k,this)===!1)break}return i}__iteratorUncached(reverse){let record=this._record,keys=record._keys,size=keys.length,i=0;return makeEntryIterator(entry=>{if(i===size)return!1;let ii=reverse?size-++i:i++,k=keys[ii];return entry[0]=k,entry[1]=record.get(k),!0})}},recordSeq=record=>new RecordSeq(record);Record.getDescriptiveName=recordName;var RecordPrototype=RecordImpl.prototype;function makeRecord(likeRecord,values,ownerID){let record=Object.create(Object.getPrototypeOf(likeRecord));return record._values=values,record.__ownerID=ownerID,record}function setProp(prototype,name){Object.defineProperty(prototype,name,{get(){return this.get(name)},set(value){invariant(this.__ownerID,"Cannot set on an immutable record."),this.set(name,value)}})}var Range=(start,end,step=1)=>{invariant(step!==0,"Cannot step a Range by 0"),invariant(start!==void 0,"You must define a start value when using Range"),invariant(end!==void 0,"You must define an end value when using Range"),step=Math.abs(step),end<start&&(step=-step);let size=Math.max(0,Math.ceil((end-start)/step-1)+1);return new RangeImpl(start,end,step,size)},RangeImpl=class _RangeImpl extends IndexedSeqImpl{_start;_end;_step;constructor(start,end,step,size){super(),this._start=start,this._end=end,this._step=step,this.size=size}toString(){return this.size===0?"Range []":`Range [ ${this._start}...${this._end}${this._step!==1?` by ${this._step}`:""} ]`}get(index,notSetValue){return this.has(index)?this._start+wrapIndex(this,index)*this._step:notSetValue}includes(searchValue){let possibleIndex=(searchValue-this._start)/this._step;return possibleIndex>=0&&possibleIndex<this.size&&possibleIndex===Math.floor(possibleIndex)}slice(begin,end){return wholeSlice(begin,end,this.size)?this:(begin=resolveBegin(begin,this.size),end=resolveEnd(end,this.size),end<=begin?Range(0,0):Range(this.get(begin,this._end),this.get(end,this._end),this._step))}indexOf(searchValue){let offsetValue=searchValue-this._start;if(offsetValue%this._step===0){let index=offsetValue/this._step;if(index>=0&&index<this.size)return index}return-1}lastIndexOf(searchValue){return this.indexOf(searchValue)}__iterateUncached(fn,reverse=!1){let size=this.size,step=this._step,value=reverse?this._start+(size-1)*step:this._start,i=0;for(;i!==size;){let v=value;value+=reverse?-step:step;let ii=reverse?size-++i:i++;if(fn(v,ii,this)===!1)break}return i}__iteratorUncached(reverse=!1){let size=this.size,step=this._step,value=reverse?this._start+(size-1)*step:this._start,i=0;return makeEntryIterator(entry=>{if(i===size)return!1;let v=value;return value+=reverse?-step:step,entry[0]=reverse?size-++i:i++,entry[1]=v,!0})}values(){let size=this.size,step=this._step,value=this._start,i=0,result={done:!1,value:void 0};return makeIterator(()=>i===size?DONE:(result.value=value,value+=step,i++,result))}keys(){return makeIndexKeys(this.size)}equals(other){return other instanceof _RangeImpl?this._start===other._start&&this._end===other._end&&this._step===other._step:deepEqual(this,other)}static{this.prototype[Symbol.iterator]=this.prototype.values}},Repeat=(value,times)=>{let size=times===void 0?1/0:Math.max(0,times);return new RepeatImpl(value,size)},RepeatImpl=class _RepeatImpl extends IndexedSeqImpl{_value;constructor(value,size){super(),this._value=value,this.size=size}toString(){return this.size===0?"Repeat []":`Repeat [ ${this._value} ${this.size} times ]`}get(index,notSetValue){return this.has(index)?this._value:notSetValue}includes(searchValue){return is(this._value,searchValue)}slice(begin,end){let size=this.size;return wholeSlice(begin,end,size)?this:new _RepeatImpl(this._value,resolveEnd(end,size)-resolveBegin(begin,size))}reverse(){return this}indexOf(searchValue){return is(this._value,searchValue)?0:-1}lastIndexOf(searchValue){return is(this._value,searchValue)?this.size:-1}__iterateUncached(fn,reverse=!1){let size=this.size,i=0;for(;i!==size&&fn(this._value,reverse?size-++i:i++,this)!==!1;);return i}__iteratorUncached(reverse=!1){let size=this.size,val=this._value,i=0;return makeEntryIterator(entry=>i===size?!1:(entry[0]=reverse?size-++i:i++,entry[1]=val,!0))}values(){let size=this.size,val=this._value,i=0,result={done:!1,value:void 0};return makeIterator(()=>i===size?DONE:(i++,result.value=val,result))}keys(){return makeIndexKeys(this.size)}equals(other){return other instanceof _RepeatImpl?this.size===other.size&&is(this._value,other._value):deepEqual(this,other)}static{this.prototype[Symbol.iterator]=this.prototype.values}},fromJS=(value,converter)=>fromJSWith([],converter??defaultConverter,value,"",converter&&converter.length>2?[]:void 0,{"":value});function fromJSWith(stack,converter,value,key,keyPath,parentValue){if(typeof value!="string"&&!isImmutable(value)&&(isArrayLike(value)||hasIterator(value)||isPlainObject(value))){if(stack.includes(value))throw new TypeError("Cannot convert circular structure to Immutable");stack.push(value),keyPath&&key!==""&&keyPath.push(key);let converted=converter.call(parentValue,key,Seq(value).map((v,k)=>fromJSWith(stack,converter,v,k,keyPath,value)),keyPath?.slice());return stack.pop(),keyPath&&keyPath.pop(),converted}return value}var defaultConverter=(k,v)=>isIndexed(v)?v.toList():isKeyed(v)?v.toMap():v.toSet(),asValues=collection=>isKeyed(collection)?collection.valueSeq():collection;function initCollectionConversions(){CollectionImpl.prototype.toMap=function(){return Map2(this.toKeyedSeq())},CollectionImpl.prototype.toOrderedMap=function(){return OrderedMap(this.toKeyedSeq())},CollectionImpl.prototype.toOrderedSet=function(){return OrderedSet(asValues(this))},CollectionImpl.prototype.toSet=function(){return Set2(asValues(this))},CollectionImpl.prototype.toStack=function(){return Stack(asValues(this))},CollectionImpl.prototype.toList=function(){return List(asValues(this))},CollectionImpl.prototype.countBy=function(grouper,context){let groups=Map2().asMutable();return this.__iterate((v,k)=>{groups.update(grouper.call(context,v,k,this),0,a=>a+1)}),groups.asImmutable()},CollectionImpl.prototype.groupBy=function(grouper,context){let isKeyedIter=isKeyed(this),groups=(isOrdered(this)?OrderedMap():Map2()).asMutable();return this.__iterate((v,k)=>{groups.update(grouper.call(context,v,k,this),a=>(a??=[],a.push(isKeyedIter?[k,v]:v),a))}),groups.map(arr=>reifyValues(this,arr)).asImmutable()},IndexedCollectionImpl.prototype.keySeq=function(){return Range(0,this.size)};let patchSort=(Impl,OrderedCtor)=>{Impl.prototype.sort=function(comparator){return OrderedCtor(sortFactory(this,comparator))},Impl.prototype.sortBy=function(mapper,comparator){return OrderedCtor(sortFactory(this,comparator,mapper))}};patchSort(MapImpl,OrderedMap),patchSort(SetImpl,OrderedSet)}var version$1="7.0.0",pkg={version:version$1};initCollectionConversions();var{version}=pkg;var NONE=Symbol("NONE"),Step=class{lookup(_v,dval=null){return dval}setValue(root,_v){return root}enterFrame(stack,_prev,next){return stack.enter(next,{},!0)}toAbstractPathStep(){return this}pinKey(_v){return this}toKey(){return null}},BindStep=class _BindStep extends Step{constructor(binds){super(),this.binds=binds}lookup(v,_dval){return v}setValue(_root,v){return v}enterFrame(stack,_prev,next){return stack.enter(next,{...this.binds},!1)}withIndex(i){return new _BindStep({...this.binds,key:i})}withKey(key){return new _BindStep({...this.binds,key})}toAbstractPathStep(){return null}},ScopeBindStep=class _ScopeBindStep extends BindStep{constructor(val,binds={}){super(binds),this.val=val}enterFrame(stack,_prev,next){let dyn=this.val.evalAsHandler(stack)?.call(stack.it)??{};return stack.enter(next,{...this.binds,...dyn},!1)}withIndex(i){return new _ScopeBindStep(this.val,{...this.binds,key:i})}withKey(key){return new _ScopeBindStep(this.val,{...this.binds,key})}},FieldStep=class extends Step{constructor(field){super(),this.field=field}lookup(v,dval=null){return v?.get?v.get(this.field,dval):dval}setValue(root,v){return root.set(this.field,v)}withIndex(i){return new SeqStep(this.field,i)}withKey(k){return new SeqStep(this.field,k)}toKey(){return{field:this.field}}},SeqStep=class extends Step{constructor(field,key){super(),this.field=field,this.key=key}lookup(v,dval=null){let o=v?.get(this.field,null);return o?.get?o.get(this.key,dval):dval}setValue(root,v){let seq=root?.get(this.field,null);return seq?root.set(this.field,seq.set(this.key,v)):root}enterFrame(stack,_prev,next){return stack.enter(next,{key:this.key},!0)}toKey(){return{field:this.field,key:this.key}}},SeqAccessStep=class extends Step{constructor(seqField,keyField){super(),this.seqField=seqField,this.keyField=keyField}lookup(v,dval=null){let seq=v?.get(this.seqField,NONE),key=v?.get(this.keyField,NONE);return key!==NONE&&seq?.get?seq.get(key,dval):dval}setValue(root,v){let seq=root?.get(this.seqField,NONE),key=root?.get(this.keyField,NONE);return seq===NONE||key===NONE?root:root.set(this.seqField,seq.set(key,v))}pinKey(v){let key=v?.get(this.keyField,NONE);return key===NONE?this:new SeqStep(this.seqField,key)}toKey(){return{field:this.seqField}}},EachBindStep=class extends Step{constructor(iterInfo,key){super(),this.iterInfo=iterInfo,this.key=key}lookup(v,_dval){return v}setValue(_root,v){return v}enterFrame(stack,_prev,next){return stack.enter(next,this.iterInfo.enrichBinds(stack,this.key),!1)}toAbstractPathStep(){return null}},EachRenderItStep=class extends SeqStep{enterFrame(stack,_prev,next){return stack.enter(next,{key:this.key,value:next},!1).enter(next,{},!0)}toAbstractPathStep(){return new SeqStep(this.field,this.key)}};function warnRawDynStep(op,step){console.warn(`Path.${op} reached a DynStep: call toTransactionPath() first`,step)}var DynStep=class extends Step{constructor(producerCompId,producerSteps){super(),this.producerCompId=producerCompId,this.producerSteps=producerSteps,this.interiorCids=new Set}teleportSteps(){return this.producerSteps}lookup(_v,dval=null){return warnRawDynStep("lookup",this),dval}setValue(root,_v){return warnRawDynStep("setValue",this),root}enterFrame(stack,_prev,_next){return warnRawDynStep("enterFrame",this),stack}},DynEachStep=class extends DynStep{constructor(producerCompId,producerSteps,key){super(producerCompId,producerSteps),this.key=key}teleportSteps(){let{producerSteps,key}=this;if(producerSteps.length===0)return producerSteps;let last=producerSteps[producerSteps.length-1];return last instanceof FieldStep?producerSteps.slice(0,-1).concat(new SeqStep(last.field,key)):(console.warn("DynEachStep: seq-access dynamic cannot be iterated",this),producerSteps)}},Path=class _Path{constructor(steps=[]){this.steps=steps}concat(steps){return new _Path(this.steps.concat(steps))}popStep(){return new _Path(this.steps.slice(0,-1))}compact(){let out=[];for(let step of this.steps){let s=step.toAbstractPathStep();s!==null&&(s!==step&&(s._originCid=step._originCid),out.push(s))}return new _Path(out)}toTransactionPath(){let hasDyn=!1;for(let step of this.steps)if(step instanceof DynStep){hasDyn=!0;break}if(!hasDyn)return this;let out=[];for(let step of this.steps)if(step instanceof DynStep){for(;out.length>0&&step.interiorCids.has(out[out.length-1]._originCid);)out.pop();for(let ts of step.teleportSteps())ts._originCid=step.producerCompId,out.push(ts)}else out.push(step);return new _Path(out)}pinKeys(root){let curVal=root,out=null;for(let i=0;i<this.steps.length;i++){let step=this.steps[i],pinned=step.pinKey(curVal);if(pinned!==step&&((out??=this.steps.slice())[i]=pinned),curVal=step.lookup(curVal,NONE),curVal===NONE)break}return out?new _Path(out):this}lookup(v,dval=null){let curVal=v;for(let step of this.steps)if(curVal=step.lookup(curVal,NONE),curVal===NONE)return dval;return curVal}resolveChain(root){let out=[root],curVal=root;for(let step of this.steps){if(curVal=step.lookup(curVal,NONE),curVal===NONE)break;out.push(curVal)}return out}toKeys(){let out=[];for(let step of this.steps){let k=step.toKey();k!==null&&out.push(k)}return out}setValue(root,v){let intermediates=new Array(this.steps.length),curVal=root;for(let i=0;i<this.steps.length;i++)if(intermediates[i]=curVal,curVal=this.steps[i].lookup(curVal,NONE),curVal===NONE)return root;let newVal=v;for(let i=this.steps.length-1;i>=0;i--)newVal=this.steps[i].setValue(intermediates[i],newVal),intermediates[i]=newVal;return newVal}buildStack(stack){let prev=stack.it;for(let step of this.steps){let next=step.lookup(prev,NONE);if(next===NONE)return console.warn("bad PathItem",{root:stack.it,step,path:this}),null;stack=step.enterFrame(stack,prev,next),prev=next}return stack}static fromNodeAndEventName(node,eventName,rootNode,maxDepth,comps,stopOnNoEvent=!0){let pathSteps=[],pendingDyns=[],bubbles=BUBBLING_EVENTS.has(eventName),depth=0,eventIds=[],handlers=null,nodeIds=[],isLeafComponent=!0,crossComponent=(cidNum,vid)=>{let comp=comps.getComponentForId(cidNum),pushStep=!0;if(handlers===null&&(isLeafComponent||bubbles))if(handlers=findHandlers(comp,eventIds,vid,eventName),handlers===null){if(isLeafComponent&&stopOnNoEvent&&!bubbles)return!1}else isLeafComponent||(pathSteps.length=0,pendingDyns.length=0,pushStep=!1);isLeafComponent=!1;for(let dyn of pendingDyns)dyn.interiorCids.add(cidNum);if(pushStep){let step=resolvePathStep(comp,nodeIds,vid);step&&(step._originCid=cidNum,pathSteps.push(step),step instanceof DynStep&&(step.interiorCids.add(cidNum),pendingDyns.push(step)))}for(let i=pendingDyns.length-1;i>=0;i--)pendingDyns[i].producerCompId===cidNum&&pendingDyns.splice(i,1);return eventIds=[],nodeIds=[],!0};for(;node&&node!==rootNode&&depth<maxDepth;){if(node?.dataset){let{eid,cid,vid}=node.dataset;eid!==void 0&&eventIds.push(eid);let metas=metaChain(node.previousSibling),sawComp=!1;for(let m of metas)if(m.$==="Comp"){if(sawComp=!0,!crossComponent(m.cid,m.vid))return NO_EVENT_INFO;nodeIds.push({nid:m.nid})}else nodeIds.push({nid:m.nid,si:m.si,sk:m.sk});if(!sawComp&&cid!==void 0&&!crossComponent(+cid,vid))return NO_EVENT_INFO}depth+=1,node=node.parentNode}return pendingDyns.length>0&&console.warn("event reconstruction: dynamic-var producer not found",pendingDyns),[new _Path(pathSteps.reverse()),handlers]}static fromEvent(e,rNode,maxDepth,comps,stopOnNoEvent=!0){let{type,target}=e;return _Path.fromNodeAndEventName(target,type,rNode,maxDepth,comps,stopOnNoEvent)}};function metaChain(n){let out=[];for(;n?.nodeType===8&&n.textContent[0]==="§";){try{out.push(JSON.parse(n.textContent.slice(1,-1)))}catch(err){console.warn(err,n)}n=n.previousSibling}return out}function findHandlers(comp,eventIds,vid,eventName){for(let eid of eventIds){let handlers=comp.getEventForId(+eid,vid).getHandlersFor(eventName);if(handlers!==null)return handlers}return null}var StepCtx=class _StepCtx{constructor(comp,nodeIds,idx,vid){this.comp=comp,this.nodeIds=nodeIds,this.idx=idx,this.vid=vid}get meta(){return this.nodeIds[this.idx]}get key(){let m=this.meta;return m.si!==void 0?+m.si:m.sk}get hasKey(){let m=this.meta;return m.si!==void 0||m.sk!==void 0}next(){let{idx,nodeIds}=this;return idx+1<nodeIds.length?new _StepCtx(this.comp,nodeIds,idx+1,this.vid):null}resolveNode(){return this.comp.getNodeForId(+this.meta.nid,this.vid)}applyKey(pi){if(pi===null)return null;let m=this.meta;return m.si!==void 0?pi.withIndex(+m.si):m.sk!==void 0?pi.withKey(m.sk):pi}};function resolvePathStep(comp,nodeIds,vid){for(let i=0;i<nodeIds.length;i++){let ctx=new StepCtx(comp,nodeIds,i,vid),step=ctx.resolveNode().toPathStep(ctx);if(step!==null)return step}return null}var NO_EVENT_INFO=[null,null],BUBBLING_EVENTS=new Set(["drop"]),PathBuilder=class{constructor(){this.pathChanges=[]}add(pathChange){return this.pathChanges.push(pathChange),this}field(name){return this.add(new FieldStep(name))}index(name,index){return this.add(new SeqStep(name,index))}key(name,key){return this.add(new SeqStep(name,key))}};var VALID_VAL_ID_RE=/^[a-zA-Z][a-zA-Z0-9_]*\??$/,isValidValId=name=>VALID_VAL_ID_RE.test(name),VALID_FLOAT_RE=/^-?[0-9]+(\.[0-9]+)?$/,STR_TPL_SPLIT_RE=/(\{[^}]+\})/g,mkVal=(name,Cls)=>isValidValId(name)?new Cls(name):null,VAL_TOKEN_RE=/\$'(?:[^'\\]|\\.)*'|'(?:[^'\\]|\\.)*'|\S+/g,tokenizeValue=s=>s.match(VAL_TOKEN_RE)??[],unescapeStr=s=>s.replace(/\\(['\\])/g,"$1"),K_CONST=1,K_STRTPL=2,K_FIELD=4,K_BIND=8,K_DYN=16,K_NAME=32,K_TYPE=64,K_SEQ=256,K_METHOD=1024,G_BOOL=K_FIELD|K_METHOD|K_BIND|K_DYN|K_CONST,G_TEXT=G_BOOL|K_STRTPL,G_COMPONENT=K_FIELD|K_SEQ|K_DYN,G_SEQUENCE=K_FIELD|K_DYN,G_PROVIDE=K_FIELD|K_SEQ,G_FIELD=K_FIELD|K_METHOD|K_CONST|K_SEQ,G_VALUE=K_FIELD|K_METHOD|K_BIND|K_DYN|K_NAME|K_TYPE|K_CONST,G_ALL=G_VALUE|K_STRTPL|K_SEQ;function sizeOf(v){if(v==null)return null;let s=v.size;if(typeof s=="number")return s;let l=v.length;return typeof l=="number"?l:null}var predTruthy=v=>{let n=sizeOf(v);return n===null?!!v:n>0},PREDICATES={"empty?":{name:"empty?",arity:1,fn:v=>v==null||sizeOf(v)===0},"truthy?":{name:"truthy?",arity:1,fn:predTruthy},"falsy?":{name:"falsy?",arity:1,fn:v=>!predTruthy(v)},"null?":{name:"null?",arity:1,fn:v=>v==null},"equals?":{name:"equals?",arity:2,fn:(a,b)=>is(a,b)}};function parseToken(s,px){let c0=s.charCodeAt(0);if(c0===39)return s.length>=2&&s.charCodeAt(s.length-1)===39?new ConstVal(unescapeStr(s.slice(1,-1))):null;if(c0===36&&s.charCodeAt(1)===39)return s.length>=3&&s.charCodeAt(s.length-1)===39?StrTplVal.parse(s.slice(2,-1),px):null;if(s.indexOf("[")!==-1||s.indexOf("]")!==-1)return _parseSeqAccess(s,px);if(s.indexOf("{")!==-1||s.indexOf("}")!==-1)return null;switch(c0){case 94:{let name=s.slice(1),newS=px.frame.macroVars?.[name];if(newS!==void 0){let tokens=tokenizeValue(newS.trim());if(tokens.length!==1)return null;let val=parseToken(tokens[0],px);return val instanceof ConstVal&&(val.fromMacroVar=!0),val}return px.onParseIssue("bad-value",{role:"macro-var",name,value:s}),null}case 36:return mkVal(s.slice(1),MethodVal);case 64:{let dot=s.indexOf(".",1);if(dot===-1)return mkVal(s.slice(1),BindVal);let name=s.slice(1,dot),member=s.slice(dot+1);return isValidValId(name)&&isValidValId(member)?new BindMemberVal(name,member):null}case 42:return mkVal(s.slice(1),DynVal);case 46:return mkVal(s.slice(1),FieldVal)}let num=VALID_FLOAT_RE.test(s)?parseFloat(s):null;return Number.isFinite(num)?new ConstVal(num):s==="true"||s==="false"?new ConstVal(s==="true"):c0>=97&&c0<=122?mkVal(s,NameVal):c0>=65&&c0<=90?mkVal(s,TypeVal):null}function _parseSeqAccess(s,px){let open=s.indexOf("["),close=s.indexOf("]");if(open<1||close!==s.length-1||close<open||s.indexOf("[",open+1)!==-1)return null;let left=parseToken(s.slice(0,open),px),right=parseToken(s.slice(open+1,close),px);return left instanceof FieldVal&&right instanceof FieldVal?new SeqAccessVal(left,right):null}function _parseSingle(s,px,group){let tokens=tokenizeValue(s.trim());if(tokens.length!==1)return null;let val=parseToken(tokens[0],px);return val!==null&&kindOf(val)&group?val:null}function parseBool(s,px){let t=s.trim(),tokens=tokenizeValue(t);if(tokens.length!==1)return tokens.length===0?null:_parsePredicate(t,tokens,px);let val=parseToken(tokens[0],px);return val!==null&&kindOf(val)&G_BOOL?val:null}function parseText(s,px){return _parseSingle(s,px,G_TEXT)}function parseComponent(s,px){return _parseSingle(s,px,G_COMPONENT)}function parseSequence(s,px){return _parseSingle(s,px,G_SEQUENCE)}function parseField(s,px){return _parseSingle(s,px,G_FIELD)}function parseProvide(s,px){return _parseSingle(s,px,G_PROVIDE)}function parseMacroAttr(s,px){return _parseSingle(s,px,G_ALL)}function parseInputHandler(s,px){return _parseHandler(s,px,"input",!0,!0)}function parseAlterHandler(s,px){let r=_parseHandler(s,px,"alter",!1,!1);return r===null?null:r.handlerVal}function _parseHandler(s,px,namespace,allowArgs,report){let tokens=tokenizeValue(s.trim()),headTok=tokens[0]??"",head=headTok===""?null:parseToken(headTok,px),hk=kindOf(head),handlerVal;if(hk&K_METHOD)handlerVal=head;else if(hk&K_NAME)handlerVal=new HandlerNameVal(head.name,namespace);else return report&&px.onParseIssue("bad-value",{role:"handler-name",value:headTok}),null;if(!allowArgs)return tokens.length===1?{handlerVal,args:[]}:null;let args=new Array(tokens.length-1);for(let i=1;i<tokens.length;i++){let val=parseToken(tokens[i],px);val!==null&&kindOf(val)&G_VALUE?args[i-1]=val:(report&&px.onParseIssue("bad-value",{role:"handler-arg",value:tokens[i]}),args[i-1]=NULL_CONST_VAL)}return{handlerVal,args}}function _parsePredicate(s,tokens,px){let predName=tokens[0],pred=PREDICATES[predName];if(pred===void 0)return px.onParseIssue("bad-value",{role:"predicate",value:predName}),null;let arity=tokens.length-1;if(arity!==pred.arity)return px.onParseIssue("bad-value",{role:"predicate-arity",value:s,predicate:predName}),null;let args=new Array(arity);for(let i=0;i<arity;i++){let tok=tokens[i+1],val=parseToken(tok,px);if(val===null||!(kindOf(val)&G_BOOL))return px.onParseIssue("bad-value",{role:"predicate-arg",value:tok}),null;args[i]=val}return new PredicateVal(pred,args)}function kindOf(val){return val===null?0:val instanceof ConstVal||val instanceof StrTplVal?val.kind:val instanceof SeqAccessVal?K_SEQ:val instanceof FieldVal?K_FIELD:val instanceof MethodVal?K_METHOD:val instanceof BindVal?K_BIND:val instanceof DynVal?K_DYN:val instanceof TypeVal?K_TYPE:val instanceof NameVal?K_NAME:0}var BaseVal=class{render(_stack,_rx){}eval(_stack){}toPathItem(){return null}evalAsHandler(stack){return this.eval(stack)}},ConstVal=class extends BaseVal{constructor(val,kind=K_CONST){super(),this.val=val,this.kind=kind}render(_stack,_rx){return this.val}eval(_stack){return this.val}toString(){let v=this.val;return typeof v=="string"?`'${v.replace(/(['\\])/g,"\\$1")}'`:`${v}`}},NULL_CONST_VAL=new ConstVal(null),PredicateVal=class extends BaseVal{constructor(pred,args){super(),this.pred=pred,this.args=args}eval(stack){let n=this.args.length,vals=new Array(n);for(let i=0;i<n;i++)vals[i]=this.args[i].eval(stack);return this.pred.fn(...vals)}toString(){return`${this.pred.name} ${this.args.map(String).join(" ")}`}},VarVal=class extends BaseVal{},StrTplVal=class _StrTplVal extends VarVal{constructor(vals){super(),this.vals=vals,this.kind=this.isLiteral()?K_CONST:K_STRTPL}isLiteral(){for(let v of this.vals)if(!(v instanceof ConstVal)||v.fromMacroVar)return!1;return!0}render(stack,_rx){return this.eval(stack)}eval(stack){let strs=new Array(this.vals.length);for(let i=0;i<this.vals.length;i++)strs[i]=this.vals[i]?.eval(stack,"");return strs.join("")}toLiteralSource(){if(!this.isLiteral())return null;let out="";for(let v of this.vals)out+=v.val;return new ConstVal(out).toString()}static parse(s,px){let parts=unescapeStr(s).split(STR_TPL_SPLIT_RE),vals=new Array(parts.length);for(let i=0;i<parts.length;i++){let part=parts[i],isExpr=part[0]==="{"&&part.at(-1)==="}";vals[i]=isExpr?parseText(part.slice(1,-1),px):new ConstVal(part)}let lo=0,hi=vals.length,isTrimmable=v=>v instanceof ConstVal&&v.val===""&&!v.fromMacroVar;for(;lo<hi&&isTrimmable(vals[lo]);)lo++;for(;hi>lo&&isTrimmable(vals[hi-1]);)hi--;return new _StrTplVal(lo===0&&hi===vals.length?vals:vals.slice(lo,hi))}},NameVal=class extends VarVal{constructor(name){super(),this.name=name}eval(stack){return stack.lookupName(this.name)}toString(){return this.name}},HandlerNameVal=class extends NameVal{constructor(name,namespace){super(name),this.namespace=namespace}eval(stack){return stack.getHandlerFor(this.name,this.namespace)??mk404Handler(this.namespace,this.name)}},mk404Handler=(type,name)=>function(...args){return console.warn("handler not found",{type,name,args},this),this},TypeVal=class extends NameVal{eval(stack){return stack.lookupType(this.name)}},RenderVal=class extends BaseVal{render(stack,_rx){return this.eval(stack)}},RenderNameVal=class extends RenderVal{constructor(name){super(),this.name=name}},BindVal=class extends RenderNameVal{eval(stack){return stack.lookupBind(this.name)}toString(){return`@${this.name}`}},BindMemberVal=class extends BindVal{constructor(name,member){super(name),this.member=member}eval(stack){let v=stack.lookupBind(this.name);return typeof v?.get=="function"?v.get(this.member,null):v?.[this.member]??null}toString(){return`@${this.name}.${this.member}`}},DynVal=class extends RenderNameVal{eval(stack){return stack.lookupDynamic(this.name)}toString(){return`*${this.name}`}},FieldVal=class extends RenderNameVal{eval(stack){return stack.lookupFieldRaw(this.name)}toPathItem(){return new FieldStep(this.name)}toString(){return`.${this.name}`}},MethodVal=class extends RenderNameVal{eval(stack){return stack.lookupMethod(this.name)}evalAsHandler(stack){return stack.lookupFieldRaw(this.name)}toString(){return`$${this.name}`}},SeqAccessVal=class extends RenderVal{constructor(seqVal,keyVal){super(),this.seqVal=seqVal,this.keyVal=keyVal}toPathItem(){return new SeqAccessStep(this.seqVal.name,this.keyVal.name)}eval(stack){let key=this.keyVal.eval(stack);return this.seqVal.eval(stack)?.get(key,null)}toString(){return`${this.seqVal}[${this.keyVal}]`}};var Attributes=class{constructor(items){this.items=items}eval(_stack){return{}}static parse(attributes,px,parseAll=!1){return getAttrParser(px).parse(attributes,parseAll)}isConstant(){return!1}},booleanAttrsRaw="itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly,async,autofocus,autoplay,controls,default,defer,disabled,hidden,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected",booleanAttrs=new Set(booleanAttrsRaw.split(",")),AttrParser=class{constructor(px){this.clear(px)}clear(px){this.px=px,this.attrs=null,this.hasDynamic=!1,this.wrapperAttrs=null,this.textChild=null,this.eachAttr=null,this.ifAttr=null,this.events=null}parseAttr(name,value,parseAll=!1){let val=parseAll?parseMacroAttr(value,this.px):parseText(value,this.px);val!==null?(this.attrs??=[],this.attrs.push(new Attr(name,val)),this.hasDynamic||=!(val instanceof ConstVal)):this.px.onParseIssue("bad-value",{role:"attr",attr:name,value})}pushWrapper(name,raw,val){let node={name,val,raw};return this.wrapperAttrs??=[],this.wrapperAttrs.push(node),node}parseIf(directiveName,value){let dynVal=parseBool(value,this.px);if(dynVal)this.ifAttr=new IfAttr(directiveName.slice(3),dynVal),this.attrs??=[],this.attrs.push(this.ifAttr),this.hasDynamic=!0;else{let info={role:"if",attr:directiveName.slice(3),value};this.px.onParseIssue("bad-value",info)}}parseThen(s){this.ifAttr&&(this.ifAttr.thenVal=parseText(s,this.px)??NOT_SET_VAL)}parseElse(value){this.ifAttr&&(this.ifAttr.elseVal=parseText(value,this.px)??NOT_SET_VAL)}parseEvent(directiveName,value){let[eventName,...modifiers]=directiveName.slice(3).split("+"),handler=EventHandler.parse(value,this.px);handler&&(this.events===null&&(this.events=this.px.registerEvents(),this.attrs??=[],this.attrs.push(new ConstAttr("data-eid",new ConstVal(this.events.id)))),this.events.add(eventName,handler,modifiers))}_parseDirectiveValue(directiveName,s,parserFn){let val=parserFn(s,this.px);if(val===null){let info={role:"directive",directive:directiveName,value:s};this.px.onParseIssue("bad-value",info)}return val}parseDirective(s,directiveName){switch(directiveName){case"dangerouslysetinnerhtml":this.attrs??=[],this.attrs.push(new RawHtmlAttr(this._parseDirectiveValue(directiveName,s,parseText))),this.hasDynamic=!0;return;case"push-view":this.pushWrapper("push-view",s,this._parseDirectiveValue(directiveName,s,parseText));return;case"text":this.textChild=this._parseDirectiveValue(directiveName,s,parseText);return;case"show":this.pushWrapper("show",s,this._parseDirectiveValue(directiveName,s,parseBool));return;case"hide":this.pushWrapper("hide",s,this._parseDirectiveValue(directiveName,s,parseBool));return;case"each":{let val=this._parseDirectiveValue(directiveName,s,parseSequence);this.eachAttr=this.pushWrapper("each",s,val);return}case"enrich-with":this.eachAttr!==null?this.eachAttr.enrichWithVal=this._parseDirectiveValue(directiveName,s,parseAlterHandler):this.pushWrapper("scope",s,this._parseDirectiveValue(directiveName,s,parseAlterHandler));return;case"when":this._parseWhen(s);return;case"loop-with":this._parseLoopWith(s);return;case"then":this.parseThen(s);return;case"else":this.parseElse(s);return}if(directiveName.startsWith("on."))this.parseEvent(directiveName,s);else if(directiveName.startsWith("if."))this.parseIf(directiveName,s);else if(directiveName.startsWith("then."))this.parseThen(s);else if(directiveName.startsWith("else."))this.parseElse(s);else{let info={name:directiveName,value:s};this.px.onParseIssue("unknown-directive",info)}}_parseWhen(s){this.eachAttr!==null&&(this.eachAttr.whenVal=this._parseDirectiveValue("when",s,parseAlterHandler))}_parseLoopWith(s){this.eachAttr!==null&&(this.eachAttr.loopWithVal=this._parseDirectiveValue("loop-with",s,parseAlterHandler))}parse(attributes,parseAll=!1){for(let{name,value}of attributes){let charCode=name.charCodeAt(0);if(charCode===58)this.parseAttr(name===":viewbox"?"viewBox":name.slice(1),value,parseAll);else if(charCode===64)this.parseDirective(value,name.slice(1));else{this.attrs??=[];let constVal=value===""&&booleanAttrs.has(name)?!0:value;this.attrs.push(new ConstAttr(name,new ConstVal(constVal)))}}let{attrs,hasDynamic}=this;return[hasDynamic?new DynAttrs(attrs):ConstAttrs.fromAttrs(attrs??[]),this.wrapperAttrs,this.textChild]}},ConstAttrs=class _ConstAttrs extends Attributes{eval(_stack){return this.items}static fromAttrs(attrs){let attrsObj={};for(let attr of attrs)attrsObj[attr.name]=attr.val.eval(null);return new _ConstAttrs(attrsObj)}setDataAttr(key,val){this.items[key]=val}toMacroVars(){let r={};for(let name in this.items)r[name]=new ConstVal(`${this.items[name]}`).toString();return r}isConstant(){return!0}},DynAttrs=class extends Attributes{eval(stack){let attrs={};for(let i=0;i<this.items.length;i++){let attr=this.items[i];attrs[attr.name]=attr.eval(stack)}return attrs}setDataAttr(key,val){this.items.push(new ConstAttr(key,new ConstVal(val)))}toMacroVars(){let r={};for(let attr of this.items)r[attr.name]=attr.val.toString();return r}},BaseAttr=class{constructor(name){this.name=name}},Attr=class extends BaseAttr{constructor(name,val){super(name),this.val=val}eval(stack){return this.val.eval(stack)}},ConstAttr=class extends Attr{},RawHtmlAttr=class extends Attr{constructor(val){super("dangerouslySetInnerHTML",val??NULL_CONST_VAL)}eval(stack){return{__html:`${this.val.eval(stack)}`}}},NOT_SET_VAL=NULL_CONST_VAL,IfAttr=class extends BaseAttr{constructor(name,condVal){super(name),this.condVal=condVal,this.thenVal=this.elseVal=NOT_SET_VAL}get anyBranchIsSet(){return this.thenVal!==NOT_SET_VAL||this.elseVal!==NOT_SET_VAL}eval(stack){return this.condVal.eval(stack)?this.thenVal.eval(stack):this.elseVal.eval(stack)}},_attrParser=null;function getAttrParser(px){return _attrParser??=new AttrParser(px),_attrParser.clear(px),_attrParser}var EventHandler=class _EventHandler{constructor(handlerVal,args=[]){this.handlerVal=handlerVal,this.args=args}getHandlerAndArgs(stack,_event){let argValues=new Array(this.args.length);for(let i=0;i<argValues.length;i++)argValues[i]=this.args[i].eval(stack);return[this.handlerVal.evalAsHandler(stack),argValues]}static parse(s,px){let r=parseInputHandler(s,px);return r===null?null:new _EventHandler(r.handlerVal,r.args)}},RequestHandler=class{constructor(name,fn){this.name=name,this.fn=fn}};var isWeakKey=k=>k!==null&&(typeof k=="object"||typeof k=="function"),NullDomCache=class{get(_keys,_cacheKey){}set(_keys,_cacheKey,_v){}evict(){return{hit:0,miss:0,badKey:0}}},WeakMapDomCache=class{constructor(){this.hit=this.miss=this.badKey=0,this.keysByLen=new Map}_returnValue(r){return r===void 0?this.miss+=1:this.hit+=1,r}get(keys,cacheKey){let len=keys.length,cur=this.keysByLen.get(len);if(!cur)return this._returnValue(void 0);for(let i=0;i<len-1;i++)if(cur=cur.get(keys[i]),!cur)return this._returnValue(void 0);return this._returnValue(cur.get(keys[len-1])?.[cacheKey])}set(keys,cacheKey,v){let len=keys.length,cur=this.keysByLen.get(len);cur||(cur=new WeakMap,this.keysByLen.set(len,cur));for(let i=0;i<len-1;i++){let key=keys[i],next=cur.get(key);if(!next){if(!isWeakKey(key)){this.badKey+=1;return}next=new WeakMap,cur.set(key,next)}cur=next}let lastKey=keys[len-1],leaf=cur.get(lastKey);leaf?leaf[cacheKey]=v:isWeakKey(lastKey)?cur.set(lastKey,{[cacheKey]:v}):this.badKey+=1}evict(){let{hit,miss,badKey}=this;return this.hit=this.miss=this.badKey=0,this.keysByLen=new Map,{hit,miss,badKey}}};var HTML_NS="http://www.w3.org/1999/xhtml",SVG_NS="http://www.w3.org/2000/svg",MATH_NS="http://www.w3.org/1998/Math/MathML",isNamespaced=node=>{let ns=node.namespaceURI;return ns!==null&&ns!==HTML_NS},isForeignObject=tag=>tag.length===13&&tag.toLowerCase()==="foreignobject",effectiveNs=(vnode,opts)=>vnode.namespace??opts.namespace??null;function childOpts(vnode,ns,opts){let target=ns===SVG_NS&&isForeignObject(vnode.tag)?null:ns;return target===(opts.namespace??null)?opts:{...opts,namespace:target}}var NEVER_ASSIGN=new Set(["width","height","href","list","form","tabIndex","download","rowSpan","colSpan","role","popover"]),PROP_ATTR_NAME={className:"class",htmlFor:"for"};function applyProperties(node,props){let namespaced=isNamespaced(node);for(let name in props)setProp2(node,name,props[name],namespaced)}function setProp2(node,name,value,namespaced){if(name==="dangerouslySetInnerHTML"){if(value===void 0)node.replaceChildren();else{let html2=value.__html??"";html2!==node.innerHTML&&(node.innerHTML=html2)}return}if(typeof value=="function")return;let usesProp=!namespaced&&!NEVER_ASSIGN.has(name)&&name in node;if(usesProp&&value!=null)try{node[name]=value;return}catch{}if(value==null||value===!1&&name[4]!=="-")if(usesProp){try{node[name]=""}catch{}node.removeAttribute(PROP_ATTR_NAME[name]??name)}else node.removeAttribute(name);else node.setAttribute(name,value)}function applyValueLast(node,value){node.tagName==="PROGRESS"&&(value==null||value===0)?node.removeAttribute("value"):setProp2(node,"value",value,isNamespaced(node))}var VBase=class{},getKey=child=>child instanceof VNode2?child.key:void 0,isIterable=obj=>obj!=null&&typeof obj!="string"&&typeof obj[Symbol.iterator]=="function";function childsEqual(a,b){if(a===b)return!0;for(let i=0;i<a.length;i++)if(!a[i].isEqualTo(b[i]))return!1;return!0}function appendChildNodes(parent,childs,opts){for(let child of childs)parent.appendChild(child.toDom(opts))}function addChild(normalizedChildren,child){if(child!=null)if(isIterable(child))for(let c of child)addChild(normalizedChildren,c);else child instanceof VBase?child instanceof VFragment?normalizedChildren.push(...child.childs):normalizedChildren.push(child):normalizedChildren.push(new VText(child))}var VText=class _VText extends VBase{constructor(text){super(),this.text=String(text)}get nodeType(){return 3}isEqualTo(other){return other instanceof _VText&&this.text===other.text}toDom(opts){return opts.document.createTextNode(this.text)}},VComment=class _VComment extends VBase{constructor(text){super(),this.text=text}get nodeType(){return 8}isEqualTo(other){return other instanceof _VComment&&this.text===other.text}toDom(opts){return opts.document.createComment(this.text)}},VFragment=class _VFragment extends VBase{constructor(childs){super(),this.childs=[],addChild(this.childs,childs)}get nodeType(){return 11}isEqualTo(other){return!(other instanceof _VFragment)||this.childs.length!==other.childs.length?!1:childsEqual(this.childs,other.childs)}toDom(opts){let fragment=opts.document.createDocumentFragment();return appendChildNodes(fragment,this.childs,opts),fragment}},VNode2=class _VNode extends VBase{constructor(tag,attrs,childs,key,namespace){super(),this.tag=tag,this.attrs=attrs??{},this.childs=childs??[],this.key=key!=null?String(key):void 0,this.namespace=typeof namespace=="string"?namespace:null}get nodeType(){return 1}isSameKind(other){return this.tag===other.tag&&this.namespace===other.namespace&&this.key===other.key}isEqualTo(other){if(this===other)return!0;if(!(other instanceof _VNode)||!this.isSameKind(other)||this.childs.length!==other.childs.length)return!1;if(this.attrs!==other.attrs){for(let key in this.attrs)if(this.attrs[key]!==other.attrs[key])return!1;for(let key in other.attrs)if(!Object.hasOwn(this.attrs,key))return!1}return childsEqual(this.childs,other.childs)}toDom(opts){let doc=opts.document,ns=effectiveNs(this,opts),tag=ns!==null&&this.tag===this.tag.toUpperCase()?this.tag.toLowerCase():this.tag,attrs=this.attrs,createOpts=attrs.is!=null?{is:attrs.is}:void 0,node=ns===null?doc.createElement(tag,createOpts):doc.createElementNS(ns,tag,createOpts),cOpts=childOpts(this,ns,opts);if("value"in attrs||"checked"in attrs){let{value,checked,...rest}=attrs;applyProperties(node,rest),appendChildNodes(node,this.childs,cOpts),value!==void 0&&applyValueLast(node,value),checked!==void 0&&setProp2(node,"checked",checked,!1)}else applyProperties(node,attrs),appendChildNodes(node,this.childs,cOpts);return node}};function diffProps(a,b){if(a===b)return null;let diff=null;for(let aKey in a)Object.hasOwn(b,aKey)?a[aKey]!==b[aKey]&&(diff??={},diff[aKey]=b[aKey]):(diff??={},diff[aKey]=void 0);for(let bKey in b)Object.hasOwn(a,bKey)||(diff??={},diff[bKey]=b[bKey]);return diff}function morphNode(domNode,source,target,opts){if(source===target||source.isEqualTo(target))return domNode;let type=source.nodeType;if(type===target.nodeType){if(type===3||type===8)return domNode.data=target.text,domNode;if(type===1&&source.isSameKind(target)){let propsDiff=diffProps(source.attrs,target.attrs),hasValue=propsDiff!=null&&"value"in propsDiff,hasChecked=propsDiff!=null&&"checked"in propsDiff;if(propsDiff)if(hasValue||hasChecked){let{value:_v,checked:_c,...rest}=propsDiff;applyProperties(domNode,rest)}else applyProperties(domNode,propsDiff);if(!target.attrs.dangerouslySetInnerHTML){let ns=effectiveNs(target,opts);morphChildren(domNode,source.childs,target.childs,childOpts(target,ns,opts))}return hasValue?applyValueLast(domNode,propsDiff.value):source.tag==="SELECT"&&target.attrs.value!==void 0&&applyValueLast(domNode,target.attrs.value),hasChecked&&setProp2(domNode,"checked",propsDiff.checked,!1),domNode}if(type===11)return morphChildren(domNode,source.childs,target.childs,opts),domNode}let newNode=target.toDom(opts);return domNode.parentNode?.replaceChild(newNode,domNode),newNode}function morphChildren(parentDom,oldChilds,newChilds,opts){if(oldChilds.length===0){appendChildNodes(parentDom,newChilds,opts);return}if(newChilds.length===0){parentDom.replaceChildren();return}if(oldChilds.length===newChilds.length){let hasKey=!1;for(let i=0;i<oldChilds.length;i++)if(getKey(oldChilds[i])!=null||getKey(newChilds[i])!=null){hasKey=!0;break}if(!hasKey){let dom=parentDom.firstChild;for(let i=0;i<oldChilds.length;i++){let next=dom.nextSibling;morphNode(dom,oldChilds[i],newChilds[i],opts),dom=next}return}}let domNodes=Array.from(parentDom.childNodes),oldKeyMap=Object.create(null);for(let i=0;i<oldChilds.length;i++){let key=getKey(oldChilds[i]);key!=null&&(oldKeyMap[key]=i)}let used=new Uint8Array(oldChilds.length),unkeyedCursor=0;for(let j=0;j<newChilds.length;j++){let newChild=newChilds[j],newKey=getKey(newChild),oldIdx=-1;if(newKey!=null)newKey in oldKeyMap&&!used[oldKeyMap[newKey]]&&(oldIdx=oldKeyMap[newKey]);else for(;unkeyedCursor<oldChilds.length;){if(!used[unkeyedCursor]&&getKey(oldChilds[unkeyedCursor])==null){oldIdx=unkeyedCursor++;break}unkeyedCursor++}if(oldIdx>=0){used[oldIdx]=1;let newDom=morphNode(domNodes[oldIdx],oldChilds[oldIdx],newChild,opts),ref=parentDom.childNodes[j]??null;newDom!==ref&&parentDom.insertBefore(newDom,ref)}else{let ref=parentDom.childNodes[j]??null;parentDom.insertBefore(newChild.toDom(opts),ref)}}for(let i=oldChilds.length-1;i>=0;i--)!used[i]&&domNodes[i].parentNode===parentDom&&parentDom.removeChild(domNodes[i])}function render(vnode,container,options,prev){let isFragment=vnode instanceof VFragment;if(prev&&prev.vnode instanceof VFragment===isFragment){let oldDom=isFragment?container:prev.dom,newDom=morphNode(oldDom,prev.vnode,vnode,options);return{vnode,dom:isFragment?container:newDom}}let domNode=vnode.toDom(options);return container.replaceChildren(domNode),{vnode,dom:isFragment?container:domNode}}function h(tagName,properties,children,namespace){let props={},key;if(properties)for(let propName in properties){let propVal=properties[propName];propName==="key"?key=propVal:propName==="namespace"?namespace=namespace??propVal:props[propName]=propVal}if(namespace==null){let lower=tagName.toLowerCase();lower==="svg"?(namespace=SVG_NS,tagName="svg"):lower==="math"&&(namespace=MATH_NS,tagName="math")}let c=tagName.charCodeAt(0),tag=namespace==null&&c>=97&&c<=122&&tagName===tagName.toLowerCase()?tagName.toUpperCase():tagName,normalizedChildren=[];return addChild(normalizedChildren,children),new VNode2(tag,props,normalizedChildren,key,namespace)}var DATASET_ATTRS=["nid","cid","eid","vid","si","sk"],Renderer=class{constructor(comps){this.comps=comps,this.cache=new WeakMapDomCache,this.renderTag=h}renderFragment(childs){return new VFragment(childs)}renderComment(text){return new VComment(text)}setNullCache(){this.cache=new NullDomCache}renderToDOM(stack,val){let rootNode=document.createElement("div"),rOpts={document};return render(h("DIV",null,[this.renderRoot(stack,val)]),rootNode,rOpts),rootNode.childNodes[0]}renderToString(stack,val,cleanAttrs=!0){let dom=this.renderToDOM(stack,val);if(cleanAttrs){let nodes=dom.querySelectorAll("[data-nid],[data-cid],[data-eid]");for(let{dataset}of nodes)for(let name of DATASET_ATTRS)delete dataset[name]}return dom.innerHTML}renderRoot(stack,val,viewName=null){let comp=this.comps.getCompFor(val);return comp===null?null:this._rValComp(stack,val,comp,comp.getView(viewName).anode,"ROOT",viewName)}renderIt(stack,node,key,viewName){let comp=this.comps.getCompFor(stack.it);return comp?this._rValComp(stack,stack.it,comp,node,key,viewName):null}_rValComp(stack,val,comp,node,key,viewName){let cacheKey=`${viewName??""}${stack.viewsId??""}${key}`,cachePath=[node,val];stack._pushDynBindValuesToArray(cachePath,comp);let cachedNode=this.cache.get(cachePath,cacheKey);if(cachedNode)return cachedNode;let view=viewName?comp.getView(viewName):stack.lookupBestView(comp.views,"main"),body=this.renderView(view,stack);if(body==null)return null;let meta=this._renderMetadata({$:"Comp",nid:node?.nodeId??null,cid:comp.id,vid:view.name}),dom=new VFragment([meta,body]);return this.cache.set(cachePath,cacheKey,dom),dom}pushEachEntry(r,nid,attrName,key,dom){r.push(this._renderMetadata({$:"Each",nid,[attrName]:key}),dom)}renderEachWhen(stack,iterInfo,view,nid){let{seq,filter,loopWith,enricher}=iterInfo.eval(stack),r=[],it=stack.it,{iterData,start,end,keys}=unpackLoopResult(loopWith.call(it,seq,makeLoopCtx(stack,filter)),seq),renderOne=(key,value,attrName)=>{let cachePath=enricher?[view,it,value]:[view,value],binds={key,value},cacheKey=`${stack.viewsId??""}${nid}${key}`;enricher&&callEnricher(enricher,it,binds,key,value,iterData);let cachedNode=this.cache.get(cachePath,cacheKey);if(cachedNode)this.pushEachEntry(r,nid,attrName,key,cachedNode);else{let dom=this.renderView(view,stack.enter(value,binds,!1));dom!=null&&this.pushEachEntry(r,nid,attrName,key,dom),this.cache.set(cachePath,cacheKey,dom)}};return keys?imKeysIter(seq,renderOne,keys):getSeqInfo(seq)(seq,(key,value,attrName)=>{filter.call(it,key,value,iterData)&&renderOne(key,value,attrName)},start,end),r}renderView(view,stack){let n=stack.binds[1];for(;n!==null;){let b=n[0];if(b.isFrame){if(stack.it!==b.it)break;return console.error("recursion detected",stack.it,b.it),new VComment("RECURSION AVOIDED")}n=n[1]}return view.render(stack,this)}_renderMetadata(info){return new VComment(`§${JSON.stringify(info)}§`)}renderScopeMeta(nid,dom){return new VFragment([this._renderMetadata({$:"Scope",nid}),dom])}},getSeqInfo=seq=>isIndexed(seq)?imIndexedIter:isKeyed(seq)?imKeyedIter:seq?.[SEQ_INFO]??unkIter,normalizeRange=(start,end,size)=>{let s=start==null?0:start<0?size+start:start,e=end==null?size:end<0?size+end:end;return s=s<0?0:s>size?size:s,e=e<0?0:e>size?size:e,[s,e<s?s:e]},callEnricher=(enricher,it,binds,key,value,iterData)=>{enricher.call(it,binds,key,value,iterData),console.assert(binds.key===key&&binds.value===value,"@enrich-with handlers must not overwrite binds.key or binds.value"),binds.key=key,binds.value=value},filterAlwaysTrue=(_v,_k,_seq)=>!0,nullLoopWith=seq=>({iterData:{seq}}),unpackLoopResult=(result,seq)=>{let r=result??{};return{iterData:r.iterData??{seq},start:r.start,end:r.end,keys:r.keys}},imKeysIter=(seq,visit,keys)=>{let attrName=isIndexed(seq)?"si":"sk";for(let key of keys)visit(key,seq.get(key),attrName)},makeLoopCtx=(stack,filter)=>({lookup:name=>stack.lookupBind(name),filter:(key,value,iterData)=>filter.call(stack.it,key,value,iterData)}),imIndexedIter=(seq,visit,start,end)=>{let[s,e]=normalizeRange(start,end,seq.size);for(let i=s;i<e;i++)visit(i,seq.get(i),"si")},imKeyedIter=(seq,visit,start,end)=>{let[s,e]=normalizeRange(start,end,seq.size),i=0;for(let[k,v]of seq.toSeq().entries()){if(i>=e)break;i>=s&&visit(k,v,"sk"),i++}},unkIter=()=>{},SEQ_INFO=Symbol.for("tutuca.seqInfo");var isMac=(globalThis.navigator?.userAgent??"").toLowerCase().includes("mac");function resolveDynProducer(comp,name){let producerComp,producerProvide,lk=comp?.lookup?.[name];if(lk!=null)producerComp=comp.scope?.lookupComponent(lk.compName),producerProvide=producerComp?.provide?.[lk.provideName];else{let p=comp?.provide?.[name];if(p==null)return null;producerComp=comp,producerProvide=p}if(producerComp==null||producerProvide==null)return null;let pi=producerProvide.val?.toPathItem?.()??null;return{producerCompId:producerComp.id,producerSteps:pi?[pi]:[]}}var BaseNode=class{render(_stack,_rx){return null}setDataAttr(key,val){console.warn("setDataAttr not implemented for",this,{key,val})}isConstant(){return!1}isWhiteSpace(){return!1}optimize(){}},TextNode=class extends BaseNode{constructor(val){super(),this.val=val}render(_stack,_rx){return this.val}isWhiteSpace(){for(let i=0;i<this.val.length;i++){let c=this.val.charCodeAt(i);if(!(c===32||c===10||c===9||c===13))return!1}return!0}hasNewLine(){for(let i=0;i<this.val.length;i++){let c=this.val.charCodeAt(i);if(c===10||c===13)return!0}return!1}condenseWhiteSpace(replacement=""){this.val=replacement}isConstant(){return!0}setDataAttr(_key,_val){}},CommentNode=class extends TextNode{render(_stack,rx){return rx.renderComment(this.val)}};function optimizeChilds(childs){for(let i=0;i<childs.length;i++){let child=childs[i];child.isConstant()?childs[i]=new RenderOnceNode(child):child.optimize()}}function optimizeNode(node){return node.isConstant()?new RenderOnceNode(node):(node.optimize(),node)}var ChildsNode=class extends BaseNode{constructor(childs){super(),this.childs=childs}isConstant(){return this.childs.every(v=>v.isConstant())}optimize(){optimizeChilds(this.childs)}},DomNode=class extends ChildsNode{constructor(tagName,attrs,childs,namespace=null){super(childs),this.tagName=tagName,this.attrs=attrs,this.namespace=namespace}render(stack,rx){let childNodes=new Array(this.childs.length);for(let i=0;i<childNodes.length;i++)childNodes[i]=this.childs[i]?.render?.(stack,rx)??null;return rx.renderTag(this.tagName,this.attrs.eval(stack),childNodes,this.namespace)}setDataAttr(key,val){this.attrs.setDataAttr(key,val)}isConstant(){return this.attrs.isConstant()&&super.isConstant()}},FragmentNode=class extends ChildsNode{render(stack,rx){return rx.renderFragment(this.childs.map(c=>c?.render(stack,rx)))}setDataAttr(key,val){for(let child of this.childs)child.setDataAttr(key,val)}},maybeFragment=xs=>xs.length===1?xs[0]:new FragmentNode(xs),VALID_NODE_RE=/^[a-zA-Z][a-zA-Z0-9-]*$/,ANode=class _ANode extends BaseNode{constructor(nodeId,val){super(),this.nodeId=nodeId,this.val=val}toPathStep(ctx){return ctx.applyKey(this.val?.toPathItem?.()??null)}static parse(html2,px){let nodes=px.parseHTML(html2);if(nodes.length===0)return new CommentNode("Empty View in ANode.parse");if(nodes.length===1)return _ANode.fromDOM(nodes[0],px);let childs=[];for(let i=0;i<nodes.length;i++){let child=_ANode.fromDOM(nodes[i],px);child!==null&&childs.push(child)}let trimmed=condenseChildsWhites(childs);return trimmed.length===0?new CommentNode("Empty View in ANode.parse"):maybeFragment(trimmed)}static fromDOM(node,px){if(node instanceof px.Text)return new TextNode(node.textContent);if(node instanceof px.Comment)return new CommentNode(node.textContent);let{childNodes,attributes:attrs,tagName:tag}=node,childs=[];for(let i=0;i<childNodes.length;i++){let child=_ANode.fromDOM(childNodes[i],px);child!==null&&childs.push(child)}let prevTag=px.currentTag;px.currentTag=tag;try{let isPseudoX=attrs[0]?.name==="@x";if(tag==="X"||isPseudoX)return parseXOp(attrs,childs,isPseudoX?1:0,px);if(tag.charCodeAt(1)===58&&(tag.charCodeAt(0)===88||tag.charCodeAt(0)===120)){let macroName=tag.slice(2).toLowerCase();if(macroName==="slot"){let slotName=attrs.getNamedItem("name")?.value??"_";return px.frame.macroSlots[slotName]??maybeFragment(childs)}let[nAttrs,wrappers]=Attributes.parse(attrs,px,!0);return px.onAttributes(nAttrs,wrappers,null,!0,tag),wrap(px.newMacroNode(macroName,nAttrs.toMacroVars(),childs),px,wrappers)}else if(VALID_NODE_RE.test(tag)){let[nAttrs,wrappers,textChild]=Attributes.parse(attrs,px);px.onAttributes(nAttrs,wrappers,textChild,!1,tag),textChild&&childs.unshift(new RenderTextNode(null,textChild));let domChilds=tag!=="PRE"?condenseChildsWhites(childs):childs,ns=node.namespaceURI,namespace=ns&&ns!==HTML_NS?ns:null;return wrap(new DomNode(tag,nAttrs,domChilds,namespace),px,wrappers)}return new CommentNode(`Error: InvalidTagName ${tag}`)}finally{px.currentTag=prevTag}}};function parseXOp(attrs,childs,opIdx,px){if(attrs.length<=opIdx)return maybeFragment(childs);let{name,value}=attrs[opIdx];X_OPS[name]?.ignoresChildren&&hasMeaningfulChilds(childs)&&px.onParseIssue("x-op-ignores-children",{op:name});let asAttr=attrs.getNamedItem("as")?.value??null,as=asAttr===null?null:parseViewName(asAttr,px),node;switch(name){case"slot":node=new SlotNode(null,new ConstVal(value),maybeFragment(childs));break;case"text":node=px.addNodeIf(RenderTextNode,parseXOpVal(name,value,px,parseText));break;case"render":node=px.addNodeIf(RenderNode,parseXOpVal(name,value,px,parseComponent),as);break;case"render-it":node=px.addNode(RenderItNode,as);break;case"render-each":node=parseRenderEach(px,value,as,attrs);break;case"show":{let val=parseXOpVal(name,value,px,parseBool);node=px.addNodeIf(ShowNode,val,maybeFragment(childs));break}case"hide":{let val=parseXOpVal(name,value,px,parseBool);node=px.addNodeIf(HideNode,val,maybeFragment(childs));break}default:return px.onParseIssue("unknown-x-op",{name,value}),new CommentNode(`Error: InvalidSpecialTagOp ${name}=${value}`)}return processXExtras(node,attrs,name,opIdx+1,px)}function parseXOpVal(opName,value,px,parserFn){let val=parserFn(value,px);return val===null&&px.onParseIssue("bad-value",{role:"x-op",op:opName,value}),val}function parseViewName(s,px){return parseText(s,px)??new ConstVal(s)}function processXExtras(node,attrs,opName,startIdx,px){let{consumed,wrappable}=X_OPS[opName],wrappers=[];for(let i=startIdx;i<attrs.length;i++){let a=attrs[i],aName=a.name;if(consumed.has(aName))continue;let atPrefixed=aName.charCodeAt(0)===64,baseName=atPrefixed?aName.slice(1):aName,wrapper=wrappable?X_OPS[baseName]?.wrapper:null;if(wrapper){atPrefixed||maybeDeprecateBareXDirective(px,opName,baseName),wrappers.push([wrapper,parseBool(a.value,px)]);continue}let issueInfo={op:opName,name:aName,value:a.value};px.onParseIssue("unknown-x-attr",issueInfo)}for(let i=wrappers.length-1;i>=0;i--){let[Cls,val]=wrappers[i],wrapper=px.addNodeIf(Cls,val,node);wrapper!==null&&(node=wrapper)}return node}function maybeDeprecateBareXDirective(px,opName,name){px.onDeprecatedSyntax("bare-x-directive",{op:opName,name})}function wrap(node,px,wrappers){if(wrappers)for(let i=wrappers.length-1;i>=0;i--){let wrapperNode=makeWrapperNode(wrappers[i],px);wrapperNode&&(wrapperNode.wrapNode(node),node=wrapperNode)}return node}function makeWrapperNode(data,px){let Cls=WRAPPER_NODES[data.name],node=Cls.register?px.addNodeIf(Cls,data.val):data.val&&new Cls(null,data.val);return node!==null&&data.name==="each"&&(node.iterInfo.enrichWithVal=data.enrichWithVal??null,node.iterInfo.whenVal=data.whenVal??null,node.iterInfo.loopWithVal=data.loopWithVal??null),node}var MacroNode=class extends BaseNode{constructor(name,attrs,slots,px){super(),this.name=name,this.attrs=attrs,this.slots=slots,this.px=px,this.node=null,this.dataAttrs={}}compile(scope){let{name,attrs,slots}=this;if(this.px.isInsideMacro(name))throw new Error(`Recursive macro expansion: ${name}`);let macro2=scope.lookupMacro(name);if(macro2===null)this.node=new CommentNode(`bad macro: ${name}`);else{let vars={...macro2.defaults,...attrs};this.node=macro2.expand(this.px.enterMacro(name,vars,slots));for(let key in this.dataAttrs)this.node.setDataAttr(key,this.dataAttrs[key])}}render(stack,rx){return this.node.render(stack,rx)}setDataAttr(key,val){this.dataAttrs[key]=val}isConstant(){return this.node.isConstant()}optimize(){this.node=optimizeNode(this.node)}},Macro=class{constructor(defaults,rawView){this.defaults=defaults,this.rawView=rawView}expand(px){return ANode.parse(this.rawView,px)}},RenderViewId=class extends ANode{constructor(nodeId,val,viewVal){super(nodeId,val),this.viewVal=viewVal}evalViewName(stack){return this.viewVal?this.viewVal.eval(stack):null}setDataAttr(_key,_val){}};function dynRenderStep(comp,name,key){let p=resolveDynProducer(comp,name);return p?key===void 0?new DynStep(p.producerCompId,p.producerSteps):new DynEachStep(p.producerCompId,p.producerSteps,key):null}var RenderNode=class extends RenderViewId{render(stack,rx){let newStack=stack.enter(this.val.eval(stack),{},!0);return rx.renderIt(newStack,this,"",this.evalViewName(stack))}toPathStep(ctx){return this.val instanceof DynVal?dynRenderStep(ctx.comp,this.val.name):super.toPathStep(ctx)}},RenderItNode=class extends RenderViewId{render(stack,rx){let newStack=stack.enter(stack.it,{},!0);return rx.renderIt(newStack,this,"",this.evalViewName(stack))}toPathStep(ctx){let next=ctx.next();if(next===null)return null;let nextNode=next.resolveNode();return nextNode instanceof EachNode&&next.hasKey?nextNode.val instanceof DynVal?dynRenderStep(ctx.comp,nextNode.val.name,next.key):new EachRenderItStep(nextNode.val.name,next.key):null}};function parseRenderEach(px,value,as,attrs){let seqVal=parseXOpVal("render-each",value,px,parseSequence);if(seqVal===null)return null;let renderIt=px.addNode(RenderItNode,as),attrParser=getAttrParser(px),eachAttr=attrParser.eachAttr=attrParser.pushWrapper("each",value,seqVal),when=attrs.getNamedItem("@when")??attrs.getNamedItem("when");when&&(when.name.charCodeAt(0)!==64&&maybeDeprecateBareXDirective(px,"render-each","when"),attrParser._parseWhen(when.value));let lWith=attrs.getNamedItem("@loop-with")??attrs.getNamedItem("loop-with");lWith&&(lWith.name.charCodeAt(0)!==64&&maybeDeprecateBareXDirective(px,"render-each","loop-with"),attrParser._parseLoopWith(lWith.value));let each=px.addNodeIf(EachNode,seqVal);return each.iterInfo.whenVal=eachAttr.whenVal??null,each.iterInfo.loopWithVal=eachAttr.loopWithVal??null,each.fromRenderEach=!0,each.wrapNode(renderIt),each}var RenderTextNode=class extends ANode{render(stack,_rx){return this.val.eval(stack)}setDataAttr(_key,_val){}},RenderOnceNode=class extends BaseNode{constructor(node){super(),this.node=node,this._render=(stack,rx)=>{let dom=node.render(stack,rx);return this._render=(_stack,_rx)=>dom,dom}}render(stack,rx){return this._render(stack,rx)}},WrapperNode=class extends ANode{constructor(nodeId,val,node=null){super(nodeId,val),this.node=node}wrapNode(node){this.node=node}setDataAttr(key,val){this.node.setDataAttr(key,val)}optimize(){this.node=optimizeNode(this.node)}static register=!1},ShowNode=class extends WrapperNode{render(stack,rx){return this.val.eval(stack)?this.node.render(stack,rx):null}},HideNode=class extends WrapperNode{render(stack,rx){return this.val.eval(stack)?null:this.node.render(stack,rx)}},PushViewNameNode=class extends WrapperNode{render(stack,rx){return this.node.render(stack.pushViewName(this.val.eval(stack)),rx)}},SlotNode=class extends WrapperNode{isSlotNode=!0;optimize(){this.node.optimize()}},ScopeNode=class extends WrapperNode{render(stack,rx){let binds=this.val.evalAsHandler(stack)?.call(stack.it)??{},dom=this.node.render(stack.enter(stack.it,binds,!1),rx);return rx.renderScopeMeta(this.nodeId,dom)}toPathStep(_ctx){return new ScopeBindStep(this.val)}wrapNode(node){this.node=node,this.node.setDataAttr("data-nid",this.nodeId)}static register=!0},EachNode=class extends WrapperNode{constructor(nodeId,val){super(nodeId,val),this.iterInfo=new IterInfo(val,null,null,null)}render(stack,rx){return rx.renderEachWhen(stack,this.iterInfo,this.node,this.nodeId)}toPathStep(ctx){return ctx.hasKey?new EachBindStep(this.iterInfo,ctx.key):null}static register=!0},IterInfo=class{constructor(val,whenVal,loopWithVal,enrichWithVal){this.val=val,this.whenVal=whenVal,this.loopWithVal=loopWithVal,this.enrichWithVal=enrichWithVal}eval(stack){let seq=this.val.eval(stack)??[],filter=this.whenVal?.evalAsHandler(stack)??filterAlwaysTrue,loopWith=this.loopWithVal?.evalAsHandler(stack)??nullLoopWith,enricher=this.enrichWithVal?.evalAsHandler(stack)??null;return{seq,filter,loopWith,enricher}}enrichBinds(stack,key){let{seq,filter,loopWith,enricher}=this.eval(stack),value=seq?.get?seq.get(key,null):null,binds={key,value};if(enricher){let{iterData}=unpackLoopResult(loopWith.call(stack.it,seq,makeLoopCtx(stack,filter)),seq);callEnricher(enricher,stack.it,binds,key,value,iterData)}return binds}};function xOp(consumed=[],{wrappable=!1,wrapper=null,ignoresChildren=!1}={}){return{consumed:new Set(consumed),wrappable,wrapper,ignoresChildren}}var X_OPS={slot:xOp(),text:xOp([],{wrappable:!0,ignoresChildren:!0}),render:xOp(["as"],{wrappable:!0,ignoresChildren:!0}),"render-it":xOp(["as"],{wrappable:!0,ignoresChildren:!0}),"render-each":xOp(["as","when","loop-with","@when","@loop-with"],{wrappable:!0,ignoresChildren:!0}),show:xOp([],{wrapper:ShowNode}),hide:xOp([],{wrapper:HideNode})},WRAPPER_NODES={show:ShowNode,hide:HideNode,each:EachNode,scope:ScopeNode,"push-view":PushViewNameNode},ParseContext=class _ParseContext{constructor(document2,Text,Comment,nodes,events,macroNodes,frame,parent){this.nodes=nodes??[],this.events=events??[],this.macroNodes=macroNodes??[],this.parent=parent??null,this.frame=frame??{},this.document=document2??globalThis.document,this.Text=Text??globalThis.Text,this.Comment=Comment??globalThis.Comment,this.cacheConstNodes=!0,this.currentTag=null}isInsideMacro(name){return this.frame.macroName===name||this.parent?.isInsideMacro(name)}enterMacro(macroName,macroVars,macroSlots){let{document:document2,Text,Comment,nodes,events,macroNodes}=this,frame={macroName,macroVars,macroSlots};return new _ParseContext(document2,Text,Comment,nodes,events,macroNodes,frame,this)}parseHTML(html2){let t=this.document.createElement("template");return t.innerHTML=html2,t.content.childNodes}addNodeIf(Class,val,extra){if(val!==null){let nodeId=this.nodes.length,node=new Class(nodeId,val,extra);return this.nodes.push(node),node}return null}addNode(Class,extra){let nodeId=this.nodes.length,node=new Class(nodeId,null,extra);return this.nodes.push(node),node}registerEvents(){let id=this.events.length,events=new NodeEvents(id);return this.events.push(events),events}newMacroNode(macroName,mAttrs,childs){let anySlot=[],slots={_:new FragmentNode(anySlot)};for(let child of childs)child.isSlotNode?slots[child.val.val]=child.node:child.isWhiteSpace()||anySlot.push(child);let node=new MacroNode(macroName,mAttrs,slots,this);return this.macroNodes.push(node),node}compile(scope){for(let i=0;i<this.macroNodes.length;i++)this.macroNodes[i].compile(scope)}*genEventNames(){for(let event of this.events)yield*event.genEventNames()}getEventForId(id){return this.events[id]??null}getNodeForId(id){return this.nodes[id]??null}onAttributes(_attrs,_wrapperAttrs,_textChild,_isMacroCall,_tag){}onParseIssue(kind,info){console.warn(`tutuca parse issue [${kind}]`,info)}onDeprecatedSyntax(_kind,_info){}},_htmlBlockTags="ADDRESS,ARTICLE,ASIDE,BLOCKQUOTE,CAPTION,COL,COLGROUP,DETAILS,DIALOG,DIV,DD,DL,DT,FIELDSET,FIGCAPTION,FIGURE,FOOTER,FORM,H1,H2,H3,H4,H5,H6,HEADER,HGROUP,HR,LEGEND,LI,MAIN,MENU,NAV,OL,P,PRE,SECTION,SUMMARY,TABLE,TBODY,TD,TFOOT,TH,THEAD,TR,UL",HTML_BLOCK_TAGS=new Set(_htmlBlockTags.split(",")),isBlockDomNode=n=>{let node=n instanceof FragmentNode?n.childs[0]:n;return node instanceof DomNode&&HTML_BLOCK_TAGS.has(node.tagName)},isEmptyText=c=>c instanceof TextNode&&c.val==="",isIgnorableXChild=c=>c instanceof CommentNode||(c.isWhiteSpace?.()??!1),hasMeaningfulChilds=childs=>childs.some(c=>!isIgnorableXChild(c));function trimEdgeWhite(node){return node.isWhiteSpace?.()?(node.condenseWhiteSpace(),!0):!1}function condenseChildsWhites(childs){if(childs.length===0)return childs;let last=childs.length-1,emptied=trimEdgeWhite(childs[0]);last>0&&trimEdgeWhite(childs[last])&&(emptied=!0);for(let i=1;i<last;i++){let cur=childs[i];if(!(cur.isWhiteSpace?.()&&cur.hasNewLine()))continue;let bothBlock=isBlockDomNode(childs[i-1])&&isBlockDomNode(childs[i+1]);cur.condenseWhiteSpace(bothBlock?"":" "),bothBlock&&(emptied=!0)}return emptied?childs.filter(c=>!isEmptyText(c)):childs}var View=class{constructor(name,rawView="No View Defined",style="",anode=null,ctx=null){this.name=name,this.anode=anode,this.style=style,this.ctx=ctx,this.rawView=rawView}compile(ctx,scope,cid){this.ctx=ctx,this.anode=ANode.parse(this.rawView,ctx),this.anode.setDataAttr("data-cid",cid),this.anode.setDataAttr("data-vid",this.name),this.ctx.compile(scope),ctx.cacheConstNodes&&(this.anode=optimizeNode(this.anode))}render(stack,rx){if(this.anode===null)throw new Error(`tutuca: view "${this.name}" was rendered before it was compiled — its component is not registered in this app/scope. Source: ${String(this.rawView).slice(0,80).replace(/\s+/g," ")}…`);return this.anode.render(stack,rx)}},NodeEvents=class{constructor(id){this.id=id,this.handlers=[]}add(name,handlerCall,modifiers){this.handlers.push(new NodeEvent(name,handlerCall,modifiers))}*genEventNames(){for(let handler of this.handlers)yield handler.name}getHandlersFor(eventName){let r=null;for(let handler of this.handlers)handler.handlesEventName(eventName)&&(r??=[],r.push(handler));return r}},NodeEvent=class{constructor(name,handlerCall,modifiers){this.name=name,this.handlerCall=handlerCall,this.modifierWrapper=compileModifiers(name,modifiers),this.modifiers=modifiers}handlesEventName(name){return this.name===name}getHandlerAndArgs(stack,event){let r=this.handlerCall.getHandlerAndArgs(stack,event);return r[0]=this.modifierWrapper(r[0],event),r}},fwdIfCtxPred=pred=>w=>(that,f,args,ctx)=>pred(ctx)?w(that,f,args,ctx):that,fwdIfKey=keyName=>fwdIfCtxPred(ctx=>ctx.e.key===keyName),fwdCtrl=fwdIfCtxPred(({e})=>isMac&&e.metaKey||e.ctrlKey),fwdMeta=fwdIfCtxPred(({e})=>e.metaKey),fwdAlt=fwdIfCtxPred(({e})=>e.altKey),metaWraps={ctrl:fwdCtrl,cmd:fwdCtrl,meta:fwdMeta,alt:fwdAlt},MOD_WRAPPERS_BY_EVENT={keydown:{send:fwdIfKey("Enter"),cancel:fwdIfKey("Escape"),...metaWraps},click:{...metaWraps}},identityModifierWrapper=(f,_ctx)=>f;function compileModifiers(eventName,names){if(names.length===0)return identityModifierWrapper;let wrappers=MOD_WRAPPERS_BY_EVENT[eventName]??{},w=(that,f,args,_ctx)=>f.apply(that,args);for(let name of names){let wrapper=wrappers[name];wrapper!==void 0&&(w=wrapper(w))}return(f,ctx)=>function(...args){return w(this,f,args,ctx)}}var Components=class{constructor(){this.getComponentSymbol=Symbol("getComponent"),this.byId=new Map}registerComponent(comp){comp.Class.prototype[this.getComponentSymbol]=()=>comp,this.byId.set(comp.id,comp)}getComponentForId(id){return this.byId.get(id)??null}getCompFor(v){return v?.[this.getComponentSymbol]?.()??null}getHandlerFor(v,name,key){return this.getCompFor(v)?.[key][name]??null}getRequestFor(v,name){return this.getCompFor(v)?.scope.lookupRequest(name)??null}compileStyles(){let styles=[];for(let comp of this.byId.values())styles.push(comp.compileStyle());return styles.join(`
2
+ `)}},ComponentStack=class _ComponentStack{constructor(comps=new Components,parent=null){this.comps=comps,this.parent=parent,this.byName={},this.reqsByName={},this.macros={}}enter(){return new _ComponentStack(this.comps,this)}registerComponents(comps,opts){let{aliases={}}=opts??{};for(let i=0;i<comps.length;i++){let comp=comps[i];comp.scope=this.enter(),comp.Class.scope=comp.scope,this.comps.registerComponent(comp),this.byName[comp.name]=comp}for(let alias in aliases){let comp=this.byName[aliases[alias]];console.assert(this.byName[alias]===void 0,"alias overrides component",alias),comp!==void 0?this.byName[alias]=comp:console.warn("alias",alias,"to inexistent component",aliases[alias])}}registerMacros(macros){for(let key in macros){let lower=key.toLowerCase();console.assert(this.macros[lower]===void 0,"macro key collision",lower),this.macros[lower]=macros[key]}}getCompFor(v){return this.comps.getCompFor(v)}registerRequestHandlers(handlers){for(let name in handlers)this.reqsByName[name]=new RequestHandler(name,handlers[name])}lookupRequest(name){return this.reqsByName[name]??this.parent?.lookupRequest(name)??null}lookupComponent(name){return this.byName[name]??this.parent?.lookupComponent(name)??null}lookupMacro(name){return this.macros[name]??this.parent?.lookupMacro(name)??null}},ProvideInfo=class{constructor(name,val,symbol){this.name=name,this.val=val,this.symbol=symbol}},LookupInfo=class{constructor(name,compName,provideName,val){this.name=name,this.compName=compName,this.provideName=provideName,this.val=val,this._sym=void 0}getProducerSymbol(stack){return this._sym===void 0&&(this._sym=stack.lookupType(this.compName)?.provide?.[this.provideName]?.symbol??null),this._sym}},isString=v=>typeof v=="string",_rawSpecKeys="name view style commonStyle globalStyle input receive bubble response alter views provide lookup fields methods statics",KNOWN_SPEC_KEYS=new Set(_rawSpecKeys.split(" ")),_compId=0,Component=class{constructor(Class,o){this.id=_compId++,this.name=o.name??"UnkComp",this.Class=Class,this.views={main:new View("main",o.view,o.style)},this.commonStyle=o.commonStyle??"",this.globalStyle=o.globalStyle??"",this.input=o.input??{},this.receive=o.receive??{},this.bubble=o.bubble??{},this.response=o.response??{},this.alter=o.alter??{};for(let name in o.views??{}){let v=o.views[name],{view,style}=isString(v)?{view:v}:v;this.views[name]=new View(name,view,style)}this._rawProvide=o.provide??{},this._rawLookup=o.lookup??{},this.provide={},this.lookup={},this.scope=null,this.spec=o,this.extra={};for(let key of Object.keys(o))KNOWN_SPEC_KEYS.has(key)||(this.extra[key]=o[key])}compile(ParseContext2){for(let name in this.views)this.views[name].compile(new ParseContext2,this.scope,this.id);let ctx=this.views.main.ctx;for(let key in this._rawProvide){let val=parseProvide(this._rawProvide[key],ctx);val&&(this.provide[key]=new ProvideInfo(key,val,Symbol(key)))}for(let key in this._rawLookup){let linfo=this._rawLookup[key],forStr=isString(linfo)?linfo:isString(linfo?.for)?linfo.for:null,[compName,provideName]=forStr===null?[]:forStr.split(".");if(!isString(compName)||!isString(provideName))continue;let defStr=isString(linfo?.default)?linfo.default:null,val=defStr===null?null:parseField(defStr,ctx);this.lookup[key]=new LookupInfo(key,compName,provideName,val)}for(let key in this.lookup)this.provide[key]!==void 0&&console.warn("name declared in both provide and lookup",this.name,key)}make(args,opts){return this.Class.make(args,opts??{scope:this.scope})}getView(name){return this.views[name]??this.views.main}getEventForId(id,name="main"){return this.getView(name).ctx.getEventForId(id)}getNodeForId(id,name="main"){return this.getView(name).ctx.getNodeForId(id)}compileStyle(){let{id,commonStyle,globalStyle,views}=this,styles=commonStyle?[`[data-cid="${id}"]{${commonStyle}}`]:[];globalStyle!==""&&styles.push(globalStyle);for(let name in views){let{style}=views[name];style!==""&&styles.push(`[data-cid="${id}"][data-vid="${name}"]{${style}}`)}return styles.join(`
3
+ `)}};var STOP=Symbol("STOP"),NEXT=Symbol("NEXT");function lookup(chain,name,dv=null){let n=chain;for(;n!==null;){let r=n[0].lookup(name);if(r===STOP)return dv;if(r!==NEXT)return r;n=n[1]}return dv}var BindFrame=class{constructor(it,binds,isFrame){this.it=it,this.binds=binds,this.isFrame=isFrame}lookup(name){let v=this.binds[name];return v===void 0?this.isFrame?STOP:NEXT:v}},ObjectFrame=class{constructor(binds){this.binds=binds}lookup(key){let v=this.binds[key];return v===void 0?NEXT:v}};function computeViewsId(views){let s="",n=views;for(;n!==null;)s+=n[0],n=n[1];return s==="main"?"":s}var Stack2=class _Stack{constructor(comps,it,binds,dynBinds,views,viewsId,ctx=null){this.comps=comps,this.it=it,this.binds=binds,this.dynBinds=dynBinds,this.views=views,this.viewsId=viewsId,this.ctx=ctx}_pushProvides(){let provide=this.comps.getCompFor(this.it)?.provide;if(provide==null)return this;let dynObj={},has2=!1;for(let k in provide)dynObj[provide[k].symbol]=provide[k].val.eval(this),has2=!0;if(!has2)return this;let newDynBinds=[new ObjectFrame(dynObj),this.dynBinds],{comps,it,binds,views,viewsId,ctx}=this;return new _Stack(comps,it,binds,newDynBinds,views,viewsId,ctx)}static root(comps,it,ctx){let binds=[new BindFrame(it,{},!0),null],dynBinds=[new ObjectFrame({}),null],views=["main",null];return new _Stack(comps,it,binds,dynBinds,views,"",ctx)._pushProvides()}enter(it,bindings={},isFrame=!0){let{comps,binds,dynBinds,views,viewsId,ctx}=this,newBinds=[new BindFrame(it,bindings,isFrame),binds],stack=new _Stack(comps,it,newBinds,dynBinds,views,viewsId,ctx);return isFrame?stack._pushProvides():stack}pushViewName(name){let{comps,it,binds,dynBinds,views,ctx}=this,newViews=[name,views];return new _Stack(comps,it,binds,dynBinds,newViews,computeViewsId(newViews),ctx)}_pushDynBindValuesToArray(arr,comp){for(let k in comp.provide)arr.push(this._lookupProvide(comp.provide[k]));for(let k in comp.lookup)arr.push(this._lookupAlias(comp.lookup[k]))}_lookupProvide(p){return lookup(this.dynBinds,p.symbol)??p.val.eval(this)??null}_lookupAlias(lk){let sym=lk.getProducerSymbol(this);return(sym!=null?lookup(this.dynBinds,sym):null)??lk.val?.eval(this)??null}lookupDynamic(name){let comp=this.comps.getCompFor(this.it);if(comp==null)return null;let lk=comp.lookup[name];if(lk!==void 0)return this._lookupAlias(lk);let p=comp.provide[name];return p!==void 0?this._lookupProvide(p):null}lookupBind(name){return lookup(this.binds,name)}lookupType(name){return this.comps.getCompFor(this.it).scope.lookupComponent(name)}lookupFieldRaw(name){return this.it[name]??null}lookupMethod(name){let fn=this.it[name];return fn instanceof Function?fn.call(this.it):null}lookupName(name){return this.ctx.lookupName(name)}getHandlerFor(name,key){return this.comps.getHandlerFor(this.it,name,key)}lookupBestView(views,defaultViewName){let n=this.views;for(;n!==null;){let view=views[n[0]];if(view!==void 0)return view;n=n[1]}return views[defaultViewName]}};var State=class{constructor(val){this.val=val,this.changeSubs=[]}onChange(cb){this.changeSubs.push(cb)}set(val,info){let old=this.val;this.val=val;for(let sub of this.changeSubs)sub({val,old,info,timestamp:Date.now()})}update(fn,info){return this.set(fn(this.val),info)}},Transactor=class{constructor(comps,rootValue){this.comps=comps,this.transactions=[],this.state=new State(rootValue),this.onTransactionPushed=()=>{},this._observers=[],this._inflight=new Set}pushTransaction(t){this.transactions.push(t),this.onTransactionPushed(t)}observe(cb){return this._observers.push(cb),()=>{let i=this._observers.indexOf(cb);i!==-1&&this._observers.splice(i,1)}}_emit(record){for(let cb of this._observers)cb(record)}_emitTransaction(transaction,root){if(this._observers.length===0||transaction._resolvedHandler===void 0)return;let path=transaction.getTransactionPath().pinKeys(root);this._emit({kind:transaction.observeKind,name:transaction.observeName,args:transaction.args??null,path,pathKeys:path.toKeys(),targetPath:transaction.targetPath??transaction.path,handler:transaction._resolvedHandler??null,handlerName:transaction._resolvedHandler?.name||null,matched:transaction._matched??null,before:transaction._before,after:transaction._after,parent:transaction.parentTransaction,timestamp:Date.now()})}_link(child,parent){if(parent){let release=parent.completion.track();child.completion.whenSubtreeSettled().then(release)}return child}pushSend(path,name,args=[],opts={},parent=null){let t=new SendEvent(path,this,name,args,parent,opts);return this.pushTransaction(t),this._link(t,parent)}pushInput(path,name,args=[],opts={},parent=null){let t=new InputDispatchEvent(path,this,name,args,parent,opts);return this.pushTransaction(t),this._link(t,parent)}pushBubble(path,name,args=[],opts={},parent=null,targetPath=null){let newOpts=opts.skipSelf?{...opts,skipSelf:!1}:opts,t=new BubbleEvent(path,this,name,args,parent,newOpts,targetPath);return this.pushTransaction(t),this._link(t,parent)}pushRequest(path,name,args=[],opts={},parent=null){let release=parent?parent.completion.track():null,p=this._runRequest(path,name,args,opts,parent,release);return this._inflight.add(p),p.finally(()=>this._inflight.delete(p)),p}async settle(maxTurns=1e4){for(;(this.hasPendingTransactions||this._inflight.size)&&maxTurns-- >0;){for(;this.hasPendingTransactions;)this.transactNext();this._inflight.size&&await Promise.allSettled([...this._inflight])}}async _runRequest(path,name,args=[],opts={},parent=null,release=null){let released=!1,transfer=t=>{release&&(released=!0,t.completion.whenSubtreeSettled().then(release))};try{let curRoot=this.state.val,txnPath=path.toTransactionPath(),curLeaf=txnPath.lookup(curRoot),found=this.comps.getRequestFor(curLeaf,name),handler=found??mkReq404(name);if(this._observers.length>0){let reqPath=txnPath.pinKeys(curRoot);this._emit({kind:"request",name,args,path:reqPath,pathKeys:reqPath.toKeys(),targetPath:path,handler:found?.fn??null,handlerName:found?.fn?.name||name,matched:found?"exact":"none",before:curLeaf,after:void 0,parent,timestamp:Date.now()})}let reqCtx=new RequestContext(path,this,parent,curRoot),resHandlerName=opts?.onResName??name,resPath=opts?.livePath?null:txnPath.pinKeys(curRoot),push=(specificName,baseName,singleArg,result,error)=>{let resArgs=specificName?[singleArg]:[result,error],t=new ResponseEvent(path,this,specificName??baseName,resArgs,parent,resPath);transfer(t),this.pushTransaction(t)};try{let result=await handler.fn.apply(null,[...args,reqCtx]);push(opts?.onOkName,resHandlerName,result,result,null)}catch(error){push(opts?.onErrorName,resHandlerName,error,null,error)}}finally{release&&!released&&release()}}get hasPendingTransactions(){return this.transactions.length>0}transactNext(){this.hasPendingTransactions&&this.transact(this.transactions.shift())}transact(transaction){try{let curState=this.state.val,newState=transaction.run(curState,this.comps);newState!==void 0?(this.state.set(newState,{transaction}),transaction.afterTransaction(),this._emitTransaction(transaction,curState)):console.warn("undefined new state",{curState,transaction})}finally{transaction._completion?.ensureSelfSettled(),transaction._completion?.releaseSelf()}}transactInputNow(path,event,eventHandler,dragInfo){this.transact(new InputEvent(path,event,eventHandler,this,dragInfo))}};function mkReq404(name){return{fn:()=>{throw new Error(`Request not found: ${name}`)}}}function nullHandler(){return this}var Transaction=class{constructor(path,transactor,parentTransaction=null){this.path=path,this.transactor=transactor,this.parentTransaction=parentTransaction,this._completion=null}get completion(){return this._completion??=new Completion,this._completion}whenSettled(){return this.completion.whenSettled()}whenSubtreeSettled(){return this.completion.whenSubtreeSettled()}run(rootValue,comps){return this.updateRootValue(rootValue,comps)}afterTransaction(){}buildRootStack(root,comps){return Stack2.root(comps,root)}buildStack(root,comps){return this.path.toTransactionPath().buildStack(this.buildRootStack(root,comps))}get observeKind(){return null}get observeName(){return null}callHandler(root,instance,comps){let[handler,args]=this.getHandlerAndArgs(root,instance,comps);return this._resolvedHandler=handler,handler.apply(instance,args)}getHandlerAndArgs(_root,_instance,_comps){return null}getTransactionPath(){return this.path.toTransactionPath()}updateRootValue(curRoot,comps){let txnPath=this.getTransactionPath(),curLeaf=txnPath.lookup(curRoot),newLeaf=this.callHandler(curRoot,curLeaf,comps);return this._before=curLeaf,this._after=newLeaf,this._completion?.markSelfSettled({value:newLeaf,old:curLeaf}),curLeaf!==newLeaf?txnPath.setValue(curRoot,newLeaf):curRoot}lookupName(_name){return null}},toNullIfNaN=v=>Number.isNaN(v)?null:v;function getValue(e){return e.target.type==="checkbox"?e.target.checked:(e instanceof CustomEvent?e.detail:e.target.value)??null}var InputEvent=class extends Transaction{constructor(path,e,handler,transactor,dragInfo){super(path,transactor),this.e=e,this.handler=handler,this.dragInfo=dragInfo,this._dispatchPath=null}get dispatchPath(){return this._dispatchPath??=this.path.compact(),this._dispatchPath}get observeKind(){return"input"}get observeName(){return this.e?.type??null}buildRootStack(root,comps){return Stack2.root(comps,root,this)}getHandlerAndArgs(root,_instance,comps){let stack=this.buildStack(root,comps),[handler,args]=this.handler.getHandlerAndArgs(stack,this),path=this.dispatchPath;return args.push(new EventContext(path,this.transactor,this)),[handler,args]}lookupName(name){let{e}=this;switch(name){case"value":return getValue(e);case"valueAsInt":return toNullIfNaN(parseInt(getValue(e),10));case"valueAsFloat":return toNullIfNaN(parseFloat(getValue(e)));case"target":return e.target;case"event":return e;case"isAlt":return e.altKey;case"isShift":return e.shiftKey;case"isCtrl":case"isCmd":return isMac&&e.metaKey||e.ctrlKey;case"key":return e.key;case"keyCode":return e.keyCode;case"isUpKey":return e.key==="ArrowUp";case"isDownKey":return e.key==="ArrowDown";case"isSend":return e.key==="Enter";case"isCancel":return e.key==="Escape";case"isTabKey":return e.key==="Tab";case"ctx":return new EventContext(this.dispatchPath,this.transactor,this);case"dragInfo":return this.dragInfo}return null}},NameArgsTransaction=class extends Transaction{constructor(path,transactor,name,args,parentTransaction,opts={}){super(path,transactor,parentTransaction),this.name=name,this.args=args,this.opts=opts,this.targetPath=path}handlerProp=null;get observeKind(){return this.handlerProp}get observeName(){return this.name}getHandlerForName(comp){let handlers=comp?.[this.handlerProp],exact=handlers?.[this.name];if(exact)return this._matched="exact",exact;let unknown=handlers?.$unknown;return unknown?(this._matched="unknown",unknown):(this._matched="none",nullHandler)}getHandlerAndArgs(_root,instance,comps){return[this.getHandlerForName(comps.getCompFor(instance)),[...this.args,new EventContext(this.path,this.transactor,this)]]}},ResponseEvent=class extends NameArgsTransaction{handlerProp="response";constructor(path,transactor,name,args,parent,txnPath=null){super(path,transactor,name,args,parent),this._txnPath=txnPath}getTransactionPath(){return this._txnPath??super.getTransactionPath()}},SendEvent=class extends NameArgsTransaction{handlerProp="receive";run(rootVal,comps){return this.opts.skipSelf?rootVal:this.updateRootValue(rootVal,comps)}afterTransaction(){let{path,name,args,opts,targetPath}=this;opts.bubbles&&path.steps.length>0&&this.transactor.pushBubble(path.popStep(),name,args,opts,this,targetPath)}},BubbleEvent=class extends SendEvent{handlerProp="bubble";constructor(path,transactor,name,args,parent,opts,targetPath){super(path,transactor,name,args,parent,opts),this.targetPath=targetPath??path}stopPropagation(){this.opts.bubbles=!1}},InputDispatchEvent=class extends NameArgsTransaction{handlerProp="input"},Completion=class{constructor(){this.val=void 0,this.selfSettled=!1,this.subtreeSettled=!1,this.pending=1,this._selfResolve=null,this._selfPromise=null,this._subtreeResolve=null,this._subtreePromise=null,this._selfReleased=!1}whenSettled(){return this.selfSettled?Promise.resolve(this.val):(this._selfPromise??=new Promise(res=>{this._selfResolve=res}),this._selfPromise)}whenSubtreeSettled(){return this.subtreeSettled?Promise.resolve(this.val):(this._subtreePromise??=new Promise(res=>{this._subtreeResolve=res}),this._subtreePromise)}markSelfSettled(val){this.selfSettled||(this.selfSettled=!0,this.val=val,this._selfResolve?.(val))}ensureSelfSettled(){this.selfSettled||this.markSelfSettled(this.val)}track(){this.pending++;let done=!1;return()=>{done||(done=!0,this._release())}}releaseSelf(){this._selfReleased||(this._selfReleased=!0,this._release())}_release(){--this.pending===0&&(this.subtreeSettled=!0,this._subtreeResolve?.(this.val))}},Dispatcher=class{constructor(path,transactor,parentTransaction,root=transactor.state.val){this.path=path,this.transactor=transactor,this.parent=parentTransaction,this.root=root}walkPath(callback){let comps=this.transactor.comps,chain=this.path.toTransactionPath().resolveChain(this.root);for(let i=chain.length-1;i>=0;i--){let comp=comps.getCompFor(chain[i]);if(comp&&callback(comp,chain[i])===!1)return}}get at(){return new PathChanges(this)}send(name,args,opts){return this.sendAtPath(this.path,name,args,opts)}bubble(name,args,opts){return this.send(name,args,{skipSelf:!0,bubbles:!0,...opts})}sendAtPath(path,name,args,opts){return this.transactor.pushSend(path,name,args,opts,this.parent)}request(name,args,opts){return this.requestAtPath(this.path,name,args,opts)}requestAtPath(path,name,args,opts){return this.transactor.pushRequest(path,name,args,opts,this.parent)}inputAtPath(path,name,args,opts){return this.transactor.pushInput(path,name,args,opts,this.parent)}lookupTypeFor(name,inst){return this.transactor.comps.getCompFor(inst).scope.lookupComponent(name)}},EventContext=class extends Dispatcher{get name(){return this.parent?.name??null}get targetPath(){return this.parent.targetPath}stopPropagation(){return this.parent.stopPropagation()}},RequestContext=class extends Dispatcher{},PathChanges=class extends PathBuilder{constructor(dispatcher){super(),this.dispatcher=dispatcher}send(name,args,opts){return this.dispatcher.sendAtPath(this.buildPath(),name,args,opts)}bubble(name,args,opts){return this.send(name,args,{skipSelf:!0,bubbles:!0,...opts})}buildPath(){return this.dispatcher.path.concat(this.pathChanges)}};function rootDispatcher(transactor){return new Dispatcher(new Path([]),transactor,null)}var _evs="dragstart dragover dragend touchstart touchmove touchend touchcancel".split(" "),App=class{constructor(rootNode,comps,renderer,ParseContext2){this.rootNode=rootNode,this.comps=comps,this.compStack=new ComponentStack(comps),this.transactor=new Transactor(comps,null),this.ParseContext=ParseContext2,this.renderer=renderer,this.maxEventNodeDepth=1/0,this._transactNextBatchId=this._evictCacheId=null,this._eventNames=new Set(_evs),this.dragInfo=this.curDragOver=null,this._touch=null,this.transactor.onTransactionPushed=_transaction=>{this._transactNextBatchId===null&&this._scheduleNextTransactionBatchExecution()},this._compiled=!1,this._renderOpts={document:rootNode.ownerDocument},this._renderState=null,this.rootViewName=null}get state(){return this.transactor.state}handleEvent(e){let{type}=e;if(type[0]==="t"&&type.startsWith("touch")){this._handleTouchEvent(e);return}this._dispatchEvent(e)}_dispatchEvent(e){let{type}=e,isDrag=type==="dragover"||type==="dragstart"||type==="dragend"||type==="drop",{rootNode:root,maxEventNodeDepth:maxDepth,comps,transactor}=this,[path,handlers]=Path.fromEvent(e,root,maxDepth,comps,!isDrag);if(isDrag&&this._handleDragEvent(e,type,path),path!==null&&handlers!==null)for(let handler of handlers)transactor.transactInputNow(path,e,handler,this.dragInfo)}_handleTouchEvent(e){let{type}=e;if(type==="touchstart"){if(this._touch!==null||e.touches.length!==1)return;let t=e.touches[0],draggable=t.target?.closest?.('[draggable="true"]');if(!draggable)return;this._touch=makeTouchInfo(t.identifier,t.clientX,t.clientY,draggable,!1);return}if(this._touch===null)return;let touch=findTouch(e,this._touch.id);if(touch===null)return;let{rootNode,_touch}=this,{clientX,clientY}=touch,fire=(type2,target)=>{let e2={type:type2,target,clientX,clientY,preventDefault:NOOP};this._dispatchEvent(e2)};if(type==="touchmove"){if(_touch.active)e.preventDefault(),fire("dragover",hitTest(rootNode,clientX,clientY));else{let dx=clientX-_touch.startX,dy=clientY-_touch.startY;if(dx*dx+dy*dy<100)return;_touch.active=!0,e.preventDefault(),fire("dragstart",_touch.target)}return}(type==="touchend"||type==="touchcancel")&&(_touch.active&&(type==="touchend"&&fire("drop",hitTest(rootNode,clientX,clientY)),fire("dragend",_touch.target)),this._touch=null)}_handleDragEvent(e,type,path){if(type==="dragover"){let dropTarget=getClosestDropTarget(e.target,this.rootNode,1/0);dropTarget!==null&&(e.preventDefault(),this._cleanDragOverAttrs(),this.curDragOver=dropTarget,dropTarget.dataset.draggingover=this.dragInfo?.type??"_external")}else if(type==="dragstart"){e.target.dataset.dragging=1;let rootValue=this.state.val,txnPath=path.compact().toTransactionPath(),value=txnPath.lookup(rootValue),dragType=e.target.dataset.dragtype??"?",stack=path.toTransactionPath().buildStack(this.makeStack(rootValue));this.dragInfo=new DragInfo(txnPath,stack,e,value,dragType,e.target)}else type==="drop"?(e.preventDefault(),this._cleanDragOverAttrs()):(this.dragInfo!==null&&(delete this.dragInfo.node.dataset.dragging,this.dragInfo=null),this._cleanDragOverAttrs())}makeStack(rootValue){return Stack2.root(this.comps,rootValue)}_cleanDragOverAttrs(){this.curDragOver!==null&&(delete this.curDragOver.dataset.draggingover,this.curDragOver=null)}render(){let root=this.state.val,stack=this.makeStack(root),{renderer,rootNode,_renderOpts,_renderState}=this,newState=render(renderer.renderRoot(stack,root,this.rootViewName),rootNode,_renderOpts,_renderState);return this._renderState=newState,newState.dom}onChange(callback){this.transactor.state.onChange(callback)}observe(callback){return this.transactor.observe(callback)}compile(){for(let Comp of this.comps.byId.values()){Comp.compile(this.ParseContext);for(let key in Comp.views)for(let name of Comp.views[key].ctx.genEventNames())this._eventNames.add(name)}this._compiled=!0}subscribeToEvents(eventNames){for(let name of eventNames)this.rootNode.addEventListener(name,this,listenerOpts(name))}recompileStyles(opts){injectCss("tutuca-app",this.comps.compileStyles(),opts?.head??document.head)}start(opts){this._compiled||this.compile(),this.subscribeToEvents(this._eventNames),this.onChange(info=>{info.val!==info.old&&this.render()}),this.recompileStyles(opts),opts?.noCache?this.renderer.setNullCache():this.startCacheEvictionInterval(),this.render()}stop(){this.stopCacheEvictionInterval();for(let name of this._eventNames)this.rootNode.removeEventListener(name,this,listenerOpts(name))}sendAtRoot(name,args,opts){this.transactor.pushSend(new Path([]),name,args,opts)}registerComponents(comps,opts){let scope=this.compStack.enter();return scope.registerComponents(comps,opts),scope}_transactNextBatch(maxRunTimeMs=10){this._transactNextBatchId=null;let startTs=Date.now(),t=this.transactor;for(;t.hasPendingTransactions&&Date.now()-startTs<maxRunTimeMs;)t.transactNext();t.hasPendingTransactions&&this._scheduleNextTransactionBatchExecution()}_scheduleNextTransactionBatchExecution(){this._transactNextBatchId=setTimeout(()=>this._transactNextBatch(),0)}startCacheEvictionInterval(intervalMs=3e4){this._evictCacheId=setInterval(()=>this.renderer.cache.evict(),intervalMs)}stopCacheEvictionInterval(){clearInterval(this._evictCacheId),this._evictCacheId=null}};function injectCss(nodeId,style,styleTarget=document.head){let styleNode=document.createElement("style"),currentNodeWithId=styleTarget.querySelector(`#${nodeId}`);currentNodeWithId&&styleTarget.removeChild(currentNodeWithId),styleNode.id=nodeId,styleNode.innerHTML=style,styleTarget.appendChild(styleNode)}var NOOP=()=>{};function findTouch(e,id){for(let t of e.changedTouches)if(t.identifier===id)return t;for(let t of e.touches)if(t.identifier===id)return t;return null}var listenerOpts=name=>name==="touchmove"?{passive:!1}:void 0;function makeTouchInfo(id,startX,startY,target,active){return{id,startX,startY,target,active}}function hitTest(rootNode,x,y){let el=rootNode.getRootNode().elementFromPoint?.(x,y)??null;for(;el?.shadowRoot;){let next=el.shadowRoot.elementFromPoint(x,y);if(next===null||next===el)break;el=next}return el??rootNode}function getClosestDropTarget(target,rootNode,count){let node=target;for(;count-- >0&&node!==rootNode;){if(node.dataset?.droptarget!==void 0)return node;node=node.parentNode}return null}var DragInfo=class{constructor(path,stack,e,val,type,node){this.path=path,this.stack=stack,this.e=e,this.val=val,this.type=type,this.node=node}lookupBind(name){return this.stack.lookupBind(name)}};var ParseCtxClassSetCollector=class _ParseCtxClassSetCollector extends ParseContext{constructor(...args){super(...args),this.classes=new Set}_addClasses(s){for(let v of s.split(/\s+/))this.classes.add(v)}enterMacro(macroName,macroVars,macroSlots){let{document:document2,Text,Comment,nodes,events,macroNodes}=this,frame={macroName,macroVars,macroSlots},v=new _ParseCtxClassSetCollector(document2,Text,Comment,nodes,events,macroNodes,frame,this);return v.classes=this.classes,v}onAttributes(attrs,_wrapperAttrs,_textChild,_isMacroCall,_tag){if(Array.isArray(attrs.items))for(let attr of attrs.items){if(attr.name!=="class")continue;let{val,thenVal,elseVal}=attr;thenVal!==void 0?(this._maybeAddVal(thenVal),this._maybeAddVal(elseVal)):this._maybeAddVal(val)}else{let attr=attrs.items.class;attr&&this._addClasses(attr)}}_maybeAddVal(value){!this._maybeAddStrTpl(value)&&typeof value?.val=="string"&&this._addClasses(value.val)}_maybeAddStrTpl(value){if(value?.vals!==void 0){for(let val of value.vals)val instanceof ConstVal&&val.val!==""&&this._addClasses(val.val);return!0}return!1}};function collectAppClassesInSet(app){let classes=new Set;for(let Comp of app.comps.byId.values())for(let key in Comp.views){let view=Comp.views[key];for(let name of view.ctx.classes)classes.add(name)}return classes}var OP_KINDS=["send","bubble","request","input"];function phaseOps(phase){let ops=[];for(let type of OP_KINDS)for(let a of phase[type]??[])ops.push({type,...a});for(let a of phase.do??[])ops.push(a);return ops}function resolveArgs(args,self){return typeof args=="function"?args(self)??[]:args??[]}function phaseHasBubble(phase){return phase?phase.bubble?.length?!0:(phase.do??[]).some(op=>op.type==="bubble"):!1}function dispatchPhase(dispatcher,targetPath,phase,self){if(phase)for(let op of phaseOps(phase)){let args=resolveArgs(op.args,self);switch(op.type){case"send":dispatcher.sendAtPath(targetPath,op.name,args,op.opts);break;case"bubble":dispatcher.sendAtPath(targetPath,op.name,args,{skipSelf:!0,bubbles:!0,...op.opts});break;case"request":dispatcher.requestAtPath(targetPath,op.name,args,op.opts);break;case"input":dispatcher.inputAtPath(targetPath,op.name,args,op.opts);break}}}var BAD_VALUE=Symbol("BadValue"),nullCoercer=v=>v,Field=class{constructor(type,name,typeCheck,coercer,defaultValue=null){this.type=type,this.name=name,this.typeCheck=typeCheck,this.coercer=coercer,this.checks=[],this.defaultValue=defaultValue}toDataDef(){let{type,defaultValue:dv}=this;return{type,defaultValue:dv?.toJS?dv.toJS():dv}}getFirstFailingCheck(v){if(!this.typeCheck.isValid(v))return this.typeCheck;for(let check2 of this.checks)if(!check2.isValid(v))return check2;return null}isValid(v){return this.getFirstFailingCheck(v)===null}addCheck(check2){return this.checks.push(check2),this}coerceOr(v,defaultValue=null){if(this.isValid(v))return v;let v1=this.coercer(v);return this.isValid(v1)?v1:defaultValue}coerceOrDefault(v){return this.coerceOr(v,this.defaultValue)}extendProtoForType(_proto,_uname){}extendProto(proto){let{name}=this,uname=name[0].toUpperCase()+name.slice(1),setName=`set${uname}`,that=this;proto[setName]=function(v){let v1=that.coerceOr(v,BAD_VALUE);return v1===BAD_VALUE?(console.warn("invalid value",v),this):this.set(name,v1)},proto[`update${uname}`]=function(fn){return this[setName](fn(this.get(name)))},proto[`reset${uname}`]=function(){return this.set(name,that.defaultValue)},this.extendProtoForType(proto,uname)}},Check=class{isValid(_v){return!0}getMessage(_v){return"Invalid"}},CheckTypeAny=class extends Check{},CHECK_TYPE_ANY=new CheckTypeAny,FnCheck=class extends Check{constructor(isValidFn,getMessageFn){super(),this._isValid=isValidFn,this._getMessage=getMessageFn}isValid(v){return this._isValid(v)}getMessage(v){return this._getMessage(v)}},CHECK_TYPE_INT=new FnCheck(v=>Number.isInteger(v),()=>"Integer expected"),CHECK_TYPE_FLOAT=new FnCheck(v=>Number.isFinite(v),()=>"Float expected"),CHECK_TYPE_BOOL=new FnCheck(v=>typeof v=="boolean",()=>"Boolean expected"),CHECK_TYPE_STRING=new FnCheck(v=>typeof v=="string",()=>"String expected"),CHECK_TYPE_LIST=new FnCheck(v=>List.isList(v),()=>"List expected"),CHECK_TYPE_MAP=new FnCheck(v=>Map2.isMap(v),()=>"Map expected"),CHECK_TYPE_OMAP=new FnCheck(v=>OrderedMap.isOrderedMap(v),()=>"OrderedMap expected"),CHECK_TYPE_SET=new FnCheck(v=>Set2.isSet(v),()=>"Set expected"),boolCoercer=v=>!!v,FieldBool=class extends Field{constructor(name,defaultValue=!1){super("bool",name,CHECK_TYPE_BOOL,boolCoercer,defaultValue)}extendProtoForType(proto,uname){let{name}=this;proto[`toggle${uname}`]=function(){return this.set(name,!this.get(name,!1))},proto[`set${uname}`]=function(v){return this.set(name,!!v)}}},FieldAny=class extends Field{constructor(name,defaultValue=null){super("any",name,CHECK_TYPE_ANY,nullCoercer,defaultValue)}toDataDef(){let{defaultValue:dv}=this;return{type:getTypeName(dv)??"any",defaultValue:dv?.toJS?dv.toJS():dv}}},stringCoercer=v=>v?.toString?.()??"",FieldString=class extends Field{constructor(name,defaultValue=""){super("text",name,CHECK_TYPE_STRING,stringCoercer,defaultValue)}extendProtoForType(proto,_uname){extendProtoSized(proto,this.name,"","length")}},intCoercer=v=>Number.isFinite(v)?Math.trunc(v):null,FieldInt=class extends Field{constructor(name,defaultValue=0){super("int",name,CHECK_TYPE_INT,intCoercer,defaultValue)}},floatCoercer=_=>null,FieldFloat=class extends Field{constructor(name,defaultValue=0){super("float",name,CHECK_TYPE_FLOAT,floatCoercer,defaultValue)}},getTypeName=v=>v?.constructor?.getMetaClass?.()?.name,CheckTypeName=class{constructor(typeName){this.typeName=typeName}isValid(v){return getTypeName(v)===this.typeName}getMessage(v){let got=getTypeName(v);return`Expected "${this.typeName}", got "${got}"`}},FieldComp=class extends Field{constructor(type,name,args){super(type,name,new CheckTypeName(type),nullCoercer,null),this.args=args}toDataDef(){return{component:this.typeName,args:this.args}}},NONE2=Symbol("NONE");function extendProtoForKeyed(proto,name,uname){extendProtoSized(proto,name,EMPTY_LIST),proto[`setIn${uname}At`]=function(i,v){return this.set(name,this.get(name).set(i,v))},proto[`getIn${uname}At`]=function(i,dval){return this.get(name).get(i,dval)},proto[`updateIn${uname}At`]=function(i,fn){let col=this.get(name),v=col.get(i,NONE2);return v!==NONE2?this.set(name,col.set(i,fn(v))):(console.warn("key",i,"not found in",name,col),this)},extendDeleteInAt(proto,name,`${uname}At`)}function extendDeleteInAt(proto,name,uname){proto[`deleteIn${uname}`]=function(v){return this.set(name,this.get(name).delete(v))},proto[`removeIn${uname}`]=proto[`deleteIn${uname}`]}var EMPTY_LIST=List(),listCoercer=v=>Array.isArray(v)?List(v):null,FieldList=class extends Field{constructor(name,defaultValue=EMPTY_LIST){super("list",name,CHECK_TYPE_LIST,listCoercer,defaultValue)}extendProtoForType(proto,uname){let{name}=this;extendProtoForKeyed(proto,name,uname),proto[`pushIn${uname}`]=function(v){return this.set(name,this.get(name).push(v))},proto[`insertIn${uname}At`]=function(i,v){return this.set(name,this.get(name).insert(i,v))}}},imapCoercer=v=>Map2(v),FieldMap=class extends Field{constructor(name,defaultValue=Map2()){super("map",name,CHECK_TYPE_MAP,imapCoercer,defaultValue)}extendProtoForType(proto,uname){extendProtoForKeyed(proto,this.name,uname)}},omapCoercer=v=>OrderedMap(v),FieldOMap=class extends Field{constructor(name,defaultValue=OrderedMap()){super("omap",name,CHECK_TYPE_OMAP,omapCoercer,defaultValue)}extendProtoForType(proto,uname){extendProtoForKeyed(proto,this.name,uname)}};function extendProtoSized(proto,name,defaultEmpty,propName="size"){proto[`${name}Len`]=function(){return this.get(name,defaultEmpty)[propName]}}var EMPTY_SET2=Set2(),isetCoercer=v=>Array.isArray(v)?Set2(v):v instanceof Set?Set2(v):null,FieldSet=class extends Field{constructor(name,defaultValue=EMPTY_SET2){super("set",name,CHECK_TYPE_SET,isetCoercer,defaultValue)}extendProtoForType(proto,uname){let{name}=this;extendProtoSized(proto,name,EMPTY_SET2),proto[`addIn${uname}`]=function(v){return this.set(name,this.get(name).add(v))},extendDeleteInAt(proto,name,uname),proto[`hasIn${uname}`]=function(v){return this.get(name).has(v)},proto[`toggleIn${uname}`]=function(v){let current=this.get(name);return this.set(name,current.has(v)?current.delete(v):current.add(v))}}};function mkCompField(field,scope,args){let Comp=scope?.lookupComponent(field.type)??null;return Comp===null&&console.warn(scope?`component field "${field.name}": component "${field.type}" not found in scope`:`component field "${field.name}": cannot resolve component "${field.type}" — built without a registered scope (use ${field.type}.make({}) as the default, or build via a registered component)`),Comp?.make({...field.args,...args},{scope})??null}var ClassBuilder=class{constructor(name){let fields={},compFields=new Set;this.name=name,this.fields=fields,this.compFields=compFields,this._methods={},this._statics={make:function(inArgs={},opts={}){let args={},scope=opts.scope??this.scope;for(let key in inArgs){let field=fields[key];compFields.has(key)?args[key]=mkCompField(field,scope,inArgs[key]):field===void 0?console.warn("extra argument to constructor:",name,key,inArgs):args[key]=field.coerceOrDefault(inArgs[key])}for(let key of compFields)args[key]===void 0&&(args[key]=mkCompField(fields[key],scope,inArgs[key]));return this(args)}}}build(){let fieldVals={},proto={},{name,_methods,fields}=this;for(let fieldName in fields){let field=fields[fieldName];fieldVals[fieldName]=field.defaultValue,field.extendProto(proto)}let Class={[name]:Record(fieldVals,name)}[name];Object.assign(Class.prototype,proto,_methods);let metaClass={fields,name,methods:_methods};return Object.assign(Class,this._statics,{getMetaClass:()=>metaClass}),Class}methods(proto){for(let k in proto)this._methods[k]=proto[k]}statics(proto){for(let k in proto)this._statics[k]=proto[k]}addField(name,dval,FieldCls){let field=new FieldCls(name,dval);return this.fields[name]=field,field}addCompField(name,type,args){let field=new FieldComp(type,name,args);return this.compFields.add(name),this.fields[name]=field,field}},FIELD_CLASS=Symbol.for("tutuca.fieldClass"),fieldsByTypeName={text:FieldString,int:FieldInt,float:FieldFloat,bool:FieldBool,list:FieldList,map:FieldMap,omap:FieldOMap,set:FieldSet,any:FieldAny};function classFromData(name,{fields={},methods,statics}){let b=new ClassBuilder(name);for(let field in fields){let value=fields[field],type=typeof value;if(type==="string")b.addField(field,value,FieldString);else if(type==="number")b.addField(field,value,FieldFloat);else if(type==="boolean")b.addField(field,value,FieldBool);else if(List.isList(value)||Array.isArray(value))b.addField(field,List(value),FieldList);else if(Set2.isSet(value)||value instanceof Set)b.addField(field,Set2(value),FieldSet);else if(OrderedMap.isOrderedMap(value))b.addField(field,value,FieldOMap);else if(value?.type&&value?.defaultValue!==void 0){let Field2=fieldsByTypeName[value.type]??FieldAny;b.addField(field,new Field2().coerceOr(value.defaultValue),Field2)}else if(value?.component&&value?.args!==void 0)b.addCompField(field,value.component,value.args);else if(Map2.isMap(value)||value?.constructor===Object)b.addField(field,Map2(value),FieldMap);else{let Field2=value?.[FIELD_CLASS]??FieldAny;b.addField(field,value,Field2)}}return methods&&b.methods(methods),statics&&b.statics(statics),b.build()}Component.fromSpec=opts=>new Component(classFromData(opts.name,opts),opts);var component=opts=>Component.fromSpec(opts);var css=String.raw,html=String.raw,macro=(defaults,rawView)=>new Macro(defaults,rawView);function check(_app){return{error:0,warn:0,hint:0,dummyCheck:!0}}async function test(_opts){return null}function collectIterBindings(){return console.warn("collectIterBindings is a no-op in the core tutuca build; use the tutuca-dev build for a functional implementation"),[]}function tutuca(nodeOrSelector){let rootNode=typeof nodeOrSelector=="string"?document.querySelector(nodeOrSelector):nodeOrSelector,comps=new Components,renderer=new Renderer(comps);return new App(rootNode,comps,renderer,ParseContext)}async function compileClassesToStyle(app,compileClasses,styleId="margaui-css"){let t1=performance.now(),css2=await compileClassesToStyleText(app,compileClasses),t2=performance.now();return injectCss(styleId,css2),t2-t1}async function compileClassesToStyleText(app,compileClasses,Ctx=ParseCtxClassSetCollector){return app.ParseContext=Ctx,app.compile(),await compileClasses(Array.from(collectAppClassesInSet(app)))}export{Collection,FIELD_CLASS,Map2 as IMap,Set2 as ISet,List,Map2 as Map,OrderedMap as OMap,OrderedMap,OrderedSet,PairSorting,ParseContext,Range,Record,Repeat,SEQ_INFO,Seq,Set2 as Set,Stack,check,collectIterBindings,compileClassesToStyle,compileClassesToStyleText,component,css,dispatchPhase,fromJS,get,getIn$1 as getIn,has,hasIn$1 as hasIn,hash,html,injectCss,is,isAssociative,isCollection,isMap as isIMap,isImmutable,isIndexed,isKeyed,isList,isMap,isOrderedMap as isOMap,isOrdered,isOrderedMap,isOrderedSet,isPlainObject,isRecord,isSeq,isSet,isStack,isValueObject,macro,merge$1 as merge,mergeDeep$1 as mergeDeep,mergeDeepWith$1 as mergeDeepWith,mergeWith$1 as mergeWith,phaseHasBubble,phaseOps,remove,removeIn,resolveArgs,rootDispatcher,set,setIn$1 as setIn,test,tutuca,update$1 as update,updateIn$1 as updateIn,version};