tutuca 0.13.2 → 0.13.3

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
- var isPlainObject=value=>{if(value===null||typeof value!="object")return!1;let proto=Object.getPrototypeOf(value);return proto===Object.prototype||proto===null},seqSize=seq=>seq==null?0:typeof seq.length=="number"?seq.length:typeof seq.size=="number"?seq.size:isPlainObject(seq)?Object.keys(seq).length:0,seqGet=(seq,key,dval=null)=>seq==null?dval:seq instanceof Map?seq.has(key)?seq.get(key):dval:seq instanceof Set?seq.has(key)?key:dval:Object.hasOwn(seq,key)?seq[key]:typeof seq.get=="function"?seq.get(key,dval):dval,isIndexedSeq=seq=>Array.isArray(seq),isKeyedSeq=seq=>seq instanceof Map||isPlainObject(seq),isSetSeq=seq=>seq instanceof Set;function*seqEntries(seq){if(seq instanceof Map)yield*seq.entries();else if(seq instanceof Set)for(let value of seq)yield[value,value];else if(isPlainObject(seq))yield*Object.entries(seq);else if(Array.isArray(seq))for(let i=0;i<seq.length;i++)yield[i,seq[i]]}var NOTHING=Symbol.for("immer-nothing"),DRAFTABLE=Symbol.for("immer-draftable"),DRAFT_STATE=Symbol.for("immer-state"),errors=[function(plugin){return`The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`},function(thing){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`},"This object has been frozen and should not be mutated",function(data){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+data},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(thing){return`'current' expects a draft, got: ${thing}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(thing){return`'original' expects a draft, got: ${thing}`}];function die(error,...args){{let e=errors[error],msg=typeof e=="function"?e.apply(null,args):e;throw new Error(`[Immer] ${msg}`)}throw new Error(`[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`)}var getPrototypeOf=Object.getPrototypeOf;function isDraft(value){return!!value&&!!value[DRAFT_STATE]}function isDraftable(value){return value?isPlainObject2(value)||Array.isArray(value)||!!value[DRAFTABLE]||!!value.constructor?.[DRAFTABLE]||isMap(value)||isSet(value):!1}var objectCtorString=Object.prototype.constructor.toString(),cachedCtorStrings=new WeakMap;function isPlainObject2(value){if(!value||typeof value!="object")return!1;let proto=Object.getPrototypeOf(value);if(proto===null||proto===Object.prototype)return!0;let Ctor=Object.hasOwnProperty.call(proto,"constructor")&&proto.constructor;if(Ctor===Object)return!0;if(typeof Ctor!="function")return!1;let ctorString=cachedCtorStrings.get(Ctor);return ctorString===void 0&&(ctorString=Function.toString.call(Ctor),cachedCtorStrings.set(Ctor,ctorString)),ctorString===objectCtorString}function each(obj,iter,strict=!0){getArchtype(obj)===0?(strict?Reflect.ownKeys(obj):Object.keys(obj)).forEach(key=>{iter(key,obj[key],obj)}):obj.forEach((entry,index)=>iter(index,entry,obj))}function getArchtype(thing){let state=thing[DRAFT_STATE];return state?state.type_:Array.isArray(thing)?1:isMap(thing)?2:isSet(thing)?3:0}function has(thing,prop){return getArchtype(thing)===2?thing.has(prop):Object.prototype.hasOwnProperty.call(thing,prop)}function set(thing,propOrOldValue,value){let t=getArchtype(thing);t===2?thing.set(propOrOldValue,value):t===3?thing.add(value):thing[propOrOldValue]=value}function is(x,y){return x===y?x!==0||1/x===1/y:x!==x&&y!==y}function isMap(target){return target instanceof Map}function isSet(target){return target instanceof Set}function latest(state){return state.copy_||state.base_}function shallowCopy(base,strict){if(isMap(base))return new Map(base);if(isSet(base))return new Set(base);if(Array.isArray(base))return Array.prototype.slice.call(base);let isPlain=isPlainObject2(base);if(strict===!0||strict==="class_only"&&!isPlain){let descriptors=Object.getOwnPropertyDescriptors(base);delete descriptors[DRAFT_STATE];let keys=Reflect.ownKeys(descriptors);for(let i=0;i<keys.length;i++){let key=keys[i],desc=descriptors[key];desc.writable===!1&&(desc.writable=!0,desc.configurable=!0),(desc.get||desc.set)&&(descriptors[key]={configurable:!0,writable:!0,enumerable:desc.enumerable,value:base[key]})}return Object.create(getPrototypeOf(base),descriptors)}else{let proto=getPrototypeOf(base);if(proto!==null&&isPlain)return{...base};let obj=Object.create(proto);return Object.assign(obj,base)}}function freeze(obj,deep=!1){return isFrozen(obj)||isDraft(obj)||!isDraftable(obj)||(getArchtype(obj)>1&&Object.defineProperties(obj,{set:dontMutateMethodOverride,add:dontMutateMethodOverride,clear:dontMutateMethodOverride,delete:dontMutateMethodOverride}),Object.freeze(obj),deep&&Object.values(obj).forEach(value=>freeze(value,!0))),obj}function dontMutateFrozenCollections(){die(2)}var dontMutateMethodOverride={value:dontMutateFrozenCollections};function isFrozen(obj){return obj===null||typeof obj!="object"?!0:Object.isFrozen(obj)}var plugins={};function getPlugin(pluginKey){let plugin=plugins[pluginKey];return plugin||die(0,pluginKey),plugin}var currentScope;function getCurrentScope(){return currentScope}function createScope(parent_,immer_){return{drafts_:[],parent_,immer_,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function usePatchesInScope(scope,patchListener){patchListener&&(getPlugin("Patches"),scope.patches_=[],scope.inversePatches_=[],scope.patchListener_=patchListener)}function revokeScope(scope){leaveScope(scope),scope.drafts_.forEach(revokeDraft),scope.drafts_=null}function leaveScope(scope){scope===currentScope&&(currentScope=scope.parent_)}function enterScope(immer2){return currentScope=createScope(currentScope,immer2)}function revokeDraft(draft){let state=draft[DRAFT_STATE];state.type_===0||state.type_===1?state.revoke_():state.revoked_=!0}function processResult(result,scope){scope.unfinalizedDrafts_=scope.drafts_.length;let baseDraft=scope.drafts_[0];return result!==void 0&&result!==baseDraft?(baseDraft[DRAFT_STATE].modified_&&(revokeScope(scope),die(4)),isDraftable(result)&&(result=finalize(scope,result),scope.parent_||maybeFreeze(scope,result)),scope.patches_&&getPlugin("Patches").generateReplacementPatches_(baseDraft[DRAFT_STATE].base_,result,scope.patches_,scope.inversePatches_)):result=finalize(scope,baseDraft,[]),revokeScope(scope),scope.patches_&&scope.patchListener_(scope.patches_,scope.inversePatches_),result!==NOTHING?result:void 0}function finalize(rootScope,value,path){if(isFrozen(value))return value;let useStrictIteration=rootScope.immer_.shouldUseStrictIteration(),state=value[DRAFT_STATE];if(!state)return each(value,(key,childValue)=>finalizeProperty(rootScope,state,value,key,childValue,path),useStrictIteration),value;if(state.scope_!==rootScope)return value;if(!state.modified_)return maybeFreeze(rootScope,state.base_,!0),state.base_;if(!state.finalized_){state.finalized_=!0,state.scope_.unfinalizedDrafts_--;let result=state.copy_,resultEach=result,isSet2=!1;state.type_===3&&(resultEach=new Set(result),result.clear(),isSet2=!0),each(resultEach,(key,childValue)=>finalizeProperty(rootScope,state,result,key,childValue,path,isSet2),useStrictIteration),maybeFreeze(rootScope,result,!1),path&&rootScope.patches_&&getPlugin("Patches").generatePatches_(state,path,rootScope.patches_,rootScope.inversePatches_)}return state.copy_}function finalizeProperty(rootScope,parentState,targetObject,prop,childValue,rootPath,targetIsSet){if(childValue==null||typeof childValue!="object"&&!targetIsSet)return;let childIsFrozen=isFrozen(childValue);if(!(childIsFrozen&&!targetIsSet)){if(childValue===targetObject&&die(5),isDraft(childValue)){let path=rootPath&&parentState&&parentState.type_!==3&&!has(parentState.assigned_,prop)?rootPath.concat(prop):void 0,res=finalize(rootScope,childValue,path);if(set(targetObject,prop,res),isDraft(res))rootScope.canAutoFreeze_=!1;else return}else targetIsSet&&targetObject.add(childValue);if(isDraftable(childValue)&&!childIsFrozen){if(!rootScope.immer_.autoFreeze_&&rootScope.unfinalizedDrafts_<1||parentState&&parentState.base_&&parentState.base_[prop]===childValue&&childIsFrozen)return;finalize(rootScope,childValue),(!parentState||!parentState.scope_.parent_)&&typeof prop!="symbol"&&(isMap(targetObject)?targetObject.has(prop):Object.prototype.propertyIsEnumerable.call(targetObject,prop))&&maybeFreeze(rootScope,childValue)}}}function maybeFreeze(scope,value,deep=!1){!scope.parent_&&scope.immer_.autoFreeze_&&scope.canAutoFreeze_&&freeze(value,deep)}function createProxyProxy(base,parent){let isArray=Array.isArray(base),state={type_:isArray?1:0,scope_:parent?parent.scope_:getCurrentScope(),modified_:!1,finalized_:!1,assigned_:{},parent_:parent,base_:base,draft_:null,copy_:null,revoke_:null,isManual_:!1},target=state,traps=objectTraps;isArray&&(target=[state],traps=arrayTraps);let{revoke,proxy}=Proxy.revocable(target,traps);return state.draft_=proxy,state.revoke_=revoke,proxy}var objectTraps={get(state,prop){if(prop===DRAFT_STATE)return state;let source=latest(state);if(!has(source,prop))return readPropFromProto(state,source,prop);let value=source[prop];return state.finalized_||!isDraftable(value)?value:value===peek(state.base_,prop)?(prepareCopy(state),state.copy_[prop]=createProxy(value,state)):value},has(state,prop){return prop in latest(state)},ownKeys(state){return Reflect.ownKeys(latest(state))},set(state,prop,value){let desc=getDescriptorFromProto(latest(state),prop);if(desc?.set)return desc.set.call(state.draft_,value),!0;if(!state.modified_){let current2=peek(latest(state),prop),currentState=current2?.[DRAFT_STATE];if(currentState&&currentState.base_===value)return state.copy_[prop]=value,state.assigned_[prop]=!1,!0;if(is(value,current2)&&(value!==void 0||has(state.base_,prop)))return!0;prepareCopy(state),markChanged(state)}return state.copy_[prop]===value&&(value!==void 0||prop in state.copy_)||Number.isNaN(value)&&Number.isNaN(state.copy_[prop])||(state.copy_[prop]=value,state.assigned_[prop]=!0),!0},deleteProperty(state,prop){return peek(state.base_,prop)!==void 0||prop in state.base_?(state.assigned_[prop]=!1,prepareCopy(state),markChanged(state)):delete state.assigned_[prop],state.copy_&&delete state.copy_[prop],!0},getOwnPropertyDescriptor(state,prop){let owner=latest(state),desc=Reflect.getOwnPropertyDescriptor(owner,prop);return desc&&{writable:!0,configurable:state.type_!==1||prop!=="length",enumerable:desc.enumerable,value:owner[prop]}},defineProperty(){die(11)},getPrototypeOf(state){return getPrototypeOf(state.base_)},setPrototypeOf(){die(12)}},arrayTraps={};each(objectTraps,(key,fn)=>{arrayTraps[key]=function(){return arguments[0]=arguments[0][0],fn.apply(this,arguments)}});arrayTraps.deleteProperty=function(state,prop){return isNaN(parseInt(prop))&&die(13),arrayTraps.set.call(this,state,prop,void 0)};arrayTraps.set=function(state,prop,value){return prop!=="length"&&isNaN(parseInt(prop))&&die(14),objectTraps.set.call(this,state[0],prop,value,state[0])};function peek(draft,prop){let state=draft[DRAFT_STATE];return(state?latest(state):draft)[prop]}function readPropFromProto(state,source,prop){let desc=getDescriptorFromProto(source,prop);return desc?"value"in desc?desc.value:desc.get?.call(state.draft_):void 0}function getDescriptorFromProto(source,prop){if(!(prop in source))return;let proto=getPrototypeOf(source);for(;proto;){let desc=Object.getOwnPropertyDescriptor(proto,prop);if(desc)return desc;proto=getPrototypeOf(proto)}}function markChanged(state){state.modified_||(state.modified_=!0,state.parent_&&markChanged(state.parent_))}function prepareCopy(state){state.copy_||(state.copy_=shallowCopy(state.base_,state.scope_.immer_.useStrictShallowCopy_))}var Immer2=class{constructor(config){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(base,recipe,patchListener)=>{if(typeof base=="function"&&typeof recipe!="function"){let defaultBase=recipe;recipe=base;let self=this;return function(base2=defaultBase,...args){return self.produce(base2,draft=>recipe.call(this,draft,...args))}}typeof recipe!="function"&&die(6),patchListener!==void 0&&typeof patchListener!="function"&&die(7);let result;if(isDraftable(base)){let scope=enterScope(this),proxy=createProxy(base,void 0),hasError=!0;try{result=recipe(proxy),hasError=!1}finally{hasError?revokeScope(scope):leaveScope(scope)}return usePatchesInScope(scope,patchListener),processResult(result,scope)}else if(!base||typeof base!="object"){if(result=recipe(base),result===void 0&&(result=base),result===NOTHING&&(result=void 0),this.autoFreeze_&&freeze(result,!0),patchListener){let p=[],ip=[];getPlugin("Patches").generateReplacementPatches_(base,result,p,ip),patchListener(p,ip)}return result}else die(1,base)},this.produceWithPatches=(base,recipe)=>{if(typeof base=="function")return(state,...args)=>this.produceWithPatches(state,draft=>base(draft,...args));let patches,inversePatches;return[this.produce(base,recipe,(p,ip)=>{patches=p,inversePatches=ip}),patches,inversePatches]},typeof config?.autoFreeze=="boolean"&&this.setAutoFreeze(config.autoFreeze),typeof config?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(config.useStrictShallowCopy),typeof config?.useStrictIteration=="boolean"&&this.setUseStrictIteration(config.useStrictIteration)}createDraft(base){isDraftable(base)||die(8),isDraft(base)&&(base=current(base));let scope=enterScope(this),proxy=createProxy(base,void 0);return proxy[DRAFT_STATE].isManual_=!0,leaveScope(scope),proxy}finishDraft(draft,patchListener){let state=draft&&draft[DRAFT_STATE];(!state||!state.isManual_)&&die(9);let{scope_:scope}=state;return usePatchesInScope(scope,patchListener),processResult(void 0,scope)}setAutoFreeze(value){this.autoFreeze_=value}setUseStrictShallowCopy(value){this.useStrictShallowCopy_=value}setUseStrictIteration(value){this.useStrictIteration_=value}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(base,patches){let i;for(i=patches.length-1;i>=0;i--){let patch=patches[i];if(patch.path.length===0&&patch.op==="replace"){base=patch.value;break}}i>-1&&(patches=patches.slice(i+1));let applyPatchesImpl=getPlugin("Patches").applyPatches_;return isDraft(base)?applyPatchesImpl(base,patches):this.produce(base,draft=>applyPatchesImpl(draft,patches))}};function createProxy(value,parent){let draft=isMap(value)?getPlugin("MapSet").proxyMap_(value,parent):isSet(value)?getPlugin("MapSet").proxySet_(value,parent):createProxyProxy(value,parent);return(parent?parent.scope_:getCurrentScope()).drafts_.push(draft),draft}function current(value){return isDraft(value)||die(10,value),currentImpl(value)}function currentImpl(value){if(!isDraftable(value)||isFrozen(value))return value;let state=value[DRAFT_STATE],copy,strict=!0;if(state){if(!state.modified_)return state.base_;state.finalized_=!0,copy=shallowCopy(value,state.scope_.immer_.useStrictShallowCopy_),strict=state.scope_.immer_.shouldUseStrictIteration()}else copy=shallowCopy(value,!0);return each(copy,(key,childValue)=>{set(copy,key,currentImpl(childValue))},strict),state&&(state.finalized_=!1),copy}var immer=new Immer2,produce=immer.produce;var NONE=Symbol("NONE"),readKey=(value,key,dval=null)=>value==null?dval:value instanceof Map?value.has(key)?value.get(key):dval:value instanceof Set?value.has(key)?key:dval:Object.hasOwn(value,key)?value[key]:dval,writeKey=(value,key,next)=>{value instanceof Map?value.set(key,next):value instanceof Set?(value.delete(key),value.add(next)):value[key]=next},writeSeqKey=(value,key,next)=>{value instanceof Map||value instanceof Set||Array.isArray(value)||Object.hasOwn(value,key)?writeKey(value,key,next):typeof value?.set=="function"?value.set(key,next):writeKey(value,key,next)},Step=class{lookup(_v,dval=null){return dval}setDraftValue(_root,_v){}enterFrame(stack,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}enterFrame(stack,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,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 readKey(v,this.field,dval)}setDraftValue(root,v){writeKey(root,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){return seqGet(readKey(v,this.field,null),this.key,dval)}setDraftValue(root,v){let seq=readKey(root,this.field,null);seq!=null&&writeSeqKey(seq,this.key,v)}enterFrame(stack,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=readKey(v,this.seqField,NONE),key=readKey(v,this.keyField,NONE);return key!==NONE&&seq!==NONE?seqGet(seq,key,dval):dval}setDraftValue(root,v){let seq=readKey(root,this.seqField,NONE),key=readKey(root,this.keyField,NONE);seq!==NONE&&key!==NONE&&writeSeqKey(seq,key,v)}pinKey(v){let key=readKey(v,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}enterFrame(stack,next){return stack.enter(next,this.iterInfo.enrichBinds(stack,this.key),!1)}toAbstractPathStep(){return null}},EachRenderItStep=class extends SeqStep{enterFrame(stack,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}enterFrame(stack,_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){return this.steps.length===0?v:produce(root,draft=>{let parent=draft;for(let i=0;i<this.steps.length-1;i++)if(parent=this.steps[i].lookup(parent,NONE),parent===NONE)return;this.steps.at(-1).setDraftValue(parent,v)})}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,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]}};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 isMac=(globalThis.navigator?.userAgent??"").toLowerCase().includes("mac");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_SEQ=256,K_METHOD=1024,K_EVENT=2048,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_CONST,G_HANDLER_ARG=G_VALUE&~K_NAME|K_EVENT,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:isPlainObject(v)?Object.keys(v).length: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}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)=>Object.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===101&&/^e(\.[a-zA-Z][a-zA-Z0-9_]*)+$/.exec(s)!==null?new EventMemberVal(s.split(".").slice(1)):c0>=97&&c0<=122?mkVal(s,NameVal):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 parseReceiveHandler(s,px){return _parseHandler(s,px,"receive",!0,!0,!1)}function parseAlterHandler(s,px){let r=_parseHandler(s,px,"alter",!1,!1,!0);return r===null?null:r.handlerVal}function _parseHandler(s,px,namespace,allowArgs,report,allowMethod){let tokens=tokenizeValue(s.trim()),headTok=tokens[0]??"",head=headTok===""?null:parseToken(headTok,px),hk=kindOf(head),handlerVal;if(hk&K_METHOD&&allowMethod)handlerVal=head;else{if(hk&K_METHOD)return report&&px.onParseIssue("event-method-handler",{name:head.name,role:"handler-name",value:headTok}),null;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_HANDLER_ARG?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 NameVal?K_NAME:val instanceof EventMemberVal?K_EVENT: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}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(stack,this.namespace,this.name)}},mk404Handler=(stack,type,name)=>function(...args){let transactor=stack?.ctx?.transactor;return transactor?transactor.refuse("NO_HANDLER",{namespace:type,name,argCount:args.length}):console.warn("handler not found",{type,name}),this},keyIs=k=>e=>e.key===k,macCtrl=e=>isMac&&e.metaKey||e.ctrlKey,nullSafe=fn=>(e,stack)=>{let info=stack.lookupDragInfo();return info==null?null:fn(info)},EVENT_CONVENIENCES={value:e=>getValue(e),valueAsInt:e=>toNullIfNaN(parseInt(getValue(e),10)),valueAsFloat:e=>toNullIfNaN(parseFloat(getValue(e))),isAlt:e=>e.altKey,isShift:e=>e.shiftKey,isCtrl:macCtrl,isCmd:macCtrl,isUpKey:keyIs("ArrowUp"),isDownKey:keyIs("ArrowDown"),isSend:keyIs("Enter"),isCancel:keyIs("Escape"),isTabKey:keyIs("Tab"),dragInfo:(_e,stack)=>stack.lookupDragInfo(),dragType:nullSafe(info=>info.type),dragValue:nullSafe(info=>info.val),dragKey:nullSafe(info=>info.lookupBind("key"))},EventMemberVal=class extends BaseVal{constructor(members){super(),this.members=members}eval(stack){let e=stack.lookupEvent();if(e==null)return null;if(this.members.length===1){let convenience=EVENT_CONVENIENCES[this.members[0]];if(convenience!==void 0)return convenience(e,stack)}let v=e;for(let member of this.members){if(v==null)return null;v=v[member]}return v??null}toString(){return`e.${this.members.join(".")}`}},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 seqGet(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 seqGet(this.seqVal.eval(stack),key,null)}toString(){return`${this.seqVal}[${this.keyVal}]`}};var Attributes=class{constructor(items){this.items=items}static parse(attributes,px,parseAll=!1){return new AttrParser(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(","));function parseDirectiveValue(px,directiveName,source,parser){let val=parser(source,px);return val===null&&px.onParseIssue("bad-value",{role:"directive",directive:directiveName,value:source}),val}function parseIterationDirectives(attributes,px){let parseNamed=name=>{let attr=attributes.getNamedItem(`@${name}`);return attr?parseDirectiveValue(px,name,attr.value,parseAlterHandler):null};return{whenVal:parseNamed("when"),loopWithVal:parseNamed("loop-with")}}var AttrParser=class{constructor(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){return parseDirectiveValue(this.px,directiveName,s,parserFn)}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)}},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=parseReceiveHandler(s,px);return r===null?null:new _EventHandler(r.handlerVal,r.args)}};var SEQ_INFO=Symbol.for("tutuca.seqInfo"),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]},nativeIndexedIter=(seq,visit,start,end)=>{let[s,e]=normalizeRange(start,end,seqSize(seq));for(let i=s;i<e;i++)visit(i,seq[i],"si")},nativeKeyedIter=(seq,visit,start,end)=>{let[s,e]=normalizeRange(start,end,seqSize(seq)),i=0;for(let[key,value]of seqEntries(seq)){if(i>=e)break;i>=s&&visit(key,value,"sk"),i++}},unknownIter=()=>{},getSeqInfo=seq=>isIndexedSeq(seq)?nativeIndexedIter:isKeyedSeq(seq)||isSetSeq(seq)?nativeKeyedIter:seq?.[SEQ_INFO]??unknownIter,filterAlwaysTrue=(_key,_value,_iterData)=>!0,nullLoopWith=seq=>({iterData:{seq}}),unpackLoopResult=(result,seq)=>{let value=result??{};return{iterData:value.iterData??{seq},start:value.start,end:value.end,keys:value.keys}},makeLoopCtx=(stack,filter)=>({lookup:name=>stack.lookupBind(name),filter:(key,value,iterData)=>filter.call(stack.it,key,value,iterData)}),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};function bindsForKey({seq,it,loopWith,enricher,ctx},key){let value=seqGet(seq,key,null),binds={key,value};if(enricher){let{iterData}=unpackLoopResult(loopWith.call(it,seq,ctx),seq);callEnricher(enricher,it,binds,key,value,iterData)}return binds}var visitKeys=(seq,keys,visit)=>{let attrName=isIndexedSeq(seq)?"si":"sk";for(let key of keys)visit(key,seqGet(seq,key),attrName)};function walkLoopBindings({seq,it,filter,loopWith,enricher,ctx},visit){let{iterData,start,end,keys}=unpackLoopResult(loopWith.call(it,seq,ctx),seq),visitOne=(key,value,attrName)=>{let binds={key,value};enricher&&callEnricher(enricher,it,binds,key,value,iterData),visit(key,value,attrName,binds)};keys?visitKeys(seq,keys,visitOne):getSeqInfo(seq)(seq,(key,value,attrName)=>{filter.call(it,key,value,iterData)&&visitOne(key,value,attrName)},start,end)}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)setProp(node,name,props[name],namespaced)}function setProp(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"):setProp(node,"value",value,isNamespaced(node))}var VBase=class{},getKey=child=>child instanceof VNode?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}},VNode=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&&setProp(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&&setProp(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 VNode(tag,props,normalizedChildren,key,namespace)}function resolveDynProducer(comp,name){let own=comp?.provide?.[name],producerComp=own!=null?comp:comp?.scope?.lookupProvider(name)??null,producerProvide=own??producerComp?.provide?.[name];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;if(wrappable&&aName.charCodeAt(0)===64){let wrapper=X_OPS[aName.slice(1)]?.wrapper;if(wrapper){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 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),{whenVal,loopWithVal}=parseIterationDirectives(attrs,px),each2=px.addNodeIf(EachNode,seqVal);return each2.iterInfo.whenVal=whenVal,each2.iterInfo.loopWithVal=loopWithVal,each2.fromRenderEach=!0,each2.wrapNode(renderIt),each2}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),ctx=makeLoopCtx(stack,filter);return bindsForKey({seq,it:stack.it,loopWith,enricher,ctx},key)}};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"],{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)}},_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,fwdIfEventPred=pred=>fwdIfCtxPred(({e})=>pred(e)),fwdIfKey=keyName=>fwdIfEventPred(keyIs(keyName)),fwdCtrl=fwdIfEventPred(macCtrl),fwdMeta=fwdIfEventPred(e=>e.metaKey),fwdAlt=fwdIfEventPred(e=>e.altKey),MOD_WRAPPERS_FOR_ANY_EVENT={ctrl:fwdCtrl,cmd:fwdCtrl,meta:fwdMeta,alt:fwdAlt},MOD_WRAPPERS_BY_EVENT={keydown:{send:fwdIfKey("Enter"),cancel:fwdIfKey("Escape")}},MOD_EFFECTS={prevent:e=>e.preventDefault?.(),stop:e=>e.stopPropagation?.()},NO_WRAPPERS={},identityModifierWrapper=(f,_ctx)=>f;function compileModifiers(eventName,names){if(names.length===0)return identityModifierWrapper;let wrappers=MOD_WRAPPERS_BY_EVENT[eventName]??NO_WRAPPERS,effects=[];for(let name of names){let effect=MOD_EFFECTS[name];effect!==void 0&&effects.push(effect)}let w=effects.length===0?(that,f,args,_ctx)=>f.apply(that,args):(that,f,args,ctx)=>{for(let effect of effects)effect(ctx.e);return f.apply(that,args)};for(let name of names){let wrapper=wrappers[name]??MOD_WRAPPERS_FOR_ANY_EVENT[name];wrapper!==void 0&&(w=wrapper(w))}return(f,ctx)=>function(...args){return w(this,f,args,ctx)}}var COMPONENT=Symbol.for("tutuca.component"),Components=class{constructor(){this.byId=new Map}registerComponent(Comp){this.byId.set(Comp[COMPONENT].id,Comp)}getComponentForId(id){return this.byId.get(id)??null}getCompFor(v){let Comp=v?.constructor;return Comp?.[COMPONENT]?Comp:null}getHandlerFor(v,name,key){return this.getCompFor(v)?.[key][name]??null}getIntentChainFor(v,name){return this.getCompFor(v)?.scope.lookupIntentChain(name)??[]}compileStyles(){let styles=[];for(let Comp of this.byId.values())styles.push(Comp[COMPONENT].compileStyle());return styles.join(`
1
+ var isPlainObject=value=>{if(value===null||typeof value!="object")return!1;let proto=Object.getPrototypeOf(value);return proto===Object.prototype||proto===null},seqSize=seq=>seq==null?0:typeof seq.length=="number"?seq.length:typeof seq.size=="number"?seq.size:isPlainObject(seq)?Object.keys(seq).length:0,seqGet=(seq,key,dval=null)=>seq==null?dval:seq instanceof Map?seq.has(key)?seq.get(key):dval:seq instanceof Set?seq.has(key)?key:dval:Object.hasOwn(seq,key)?seq[key]:typeof seq.get=="function"?seq.get(key,dval):dval,isIndexedSeq=seq=>Array.isArray(seq),isKeyedSeq=seq=>seq instanceof Map||isPlainObject(seq),isSetSeq=seq=>seq instanceof Set;function*seqEntries(seq){if(seq instanceof Map)yield*seq.entries();else if(seq instanceof Set)for(let value of seq)yield[value,value];else if(isPlainObject(seq))yield*Object.entries(seq);else if(Array.isArray(seq))for(let i=0;i<seq.length;i++)yield[i,seq[i]]}var NOTHING=Symbol.for("immer-nothing"),DRAFTABLE=Symbol.for("immer-draftable"),DRAFT_STATE=Symbol.for("immer-state"),errors=[function(plugin){return`The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`},function(thing){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`},"This object has been frozen and should not be mutated",function(data){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+data},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(thing){return`'current' expects a draft, got: ${thing}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(thing){return`'original' expects a draft, got: ${thing}`}];function die(error,...args){{let e=errors[error],msg=typeof e=="function"?e.apply(null,args):e;throw new Error(`[Immer] ${msg}`)}throw new Error(`[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`)}var getPrototypeOf=Object.getPrototypeOf;function isDraft(value){return!!value&&!!value[DRAFT_STATE]}function isDraftable(value){return value?isPlainObject2(value)||Array.isArray(value)||!!value[DRAFTABLE]||!!value.constructor?.[DRAFTABLE]||isMap(value)||isSet(value):!1}var objectCtorString=Object.prototype.constructor.toString(),cachedCtorStrings=new WeakMap;function isPlainObject2(value){if(!value||typeof value!="object")return!1;let proto=Object.getPrototypeOf(value);if(proto===null||proto===Object.prototype)return!0;let Ctor=Object.hasOwnProperty.call(proto,"constructor")&&proto.constructor;if(Ctor===Object)return!0;if(typeof Ctor!="function")return!1;let ctorString=cachedCtorStrings.get(Ctor);return ctorString===void 0&&(ctorString=Function.toString.call(Ctor),cachedCtorStrings.set(Ctor,ctorString)),ctorString===objectCtorString}function each(obj,iter,strict=!0){getArchtype(obj)===0?(strict?Reflect.ownKeys(obj):Object.keys(obj)).forEach(key=>{iter(key,obj[key],obj)}):obj.forEach((entry,index)=>iter(index,entry,obj))}function getArchtype(thing){let state=thing[DRAFT_STATE];return state?state.type_:Array.isArray(thing)?1:isMap(thing)?2:isSet(thing)?3:0}function has(thing,prop){return getArchtype(thing)===2?thing.has(prop):Object.prototype.hasOwnProperty.call(thing,prop)}function set(thing,propOrOldValue,value){let t=getArchtype(thing);t===2?thing.set(propOrOldValue,value):t===3?thing.add(value):thing[propOrOldValue]=value}function is(x,y){return x===y?x!==0||1/x===1/y:x!==x&&y!==y}function isMap(target){return target instanceof Map}function isSet(target){return target instanceof Set}function latest(state){return state.copy_||state.base_}function shallowCopy(base,strict){if(isMap(base))return new Map(base);if(isSet(base))return new Set(base);if(Array.isArray(base))return Array.prototype.slice.call(base);let isPlain=isPlainObject2(base);if(strict===!0||strict==="class_only"&&!isPlain){let descriptors=Object.getOwnPropertyDescriptors(base);delete descriptors[DRAFT_STATE];let keys=Reflect.ownKeys(descriptors);for(let i=0;i<keys.length;i++){let key=keys[i],desc=descriptors[key];desc.writable===!1&&(desc.writable=!0,desc.configurable=!0),(desc.get||desc.set)&&(descriptors[key]={configurable:!0,writable:!0,enumerable:desc.enumerable,value:base[key]})}return Object.create(getPrototypeOf(base),descriptors)}else{let proto=getPrototypeOf(base);if(proto!==null&&isPlain)return{...base};let obj=Object.create(proto);return Object.assign(obj,base)}}function freeze(obj,deep=!1){return isFrozen(obj)||isDraft(obj)||!isDraftable(obj)||(getArchtype(obj)>1&&Object.defineProperties(obj,{set:dontMutateMethodOverride,add:dontMutateMethodOverride,clear:dontMutateMethodOverride,delete:dontMutateMethodOverride}),Object.freeze(obj),deep&&Object.values(obj).forEach(value=>freeze(value,!0))),obj}function dontMutateFrozenCollections(){die(2)}var dontMutateMethodOverride={value:dontMutateFrozenCollections};function isFrozen(obj){return obj===null||typeof obj!="object"?!0:Object.isFrozen(obj)}var plugins={};function getPlugin(pluginKey){let plugin=plugins[pluginKey];return plugin||die(0,pluginKey),plugin}var currentScope;function getCurrentScope(){return currentScope}function createScope(parent_,immer_){return{drafts_:[],parent_,immer_,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function usePatchesInScope(scope,patchListener){patchListener&&(getPlugin("Patches"),scope.patches_=[],scope.inversePatches_=[],scope.patchListener_=patchListener)}function revokeScope(scope){leaveScope(scope),scope.drafts_.forEach(revokeDraft),scope.drafts_=null}function leaveScope(scope){scope===currentScope&&(currentScope=scope.parent_)}function enterScope(immer2){return currentScope=createScope(currentScope,immer2)}function revokeDraft(draft){let state=draft[DRAFT_STATE];state.type_===0||state.type_===1?state.revoke_():state.revoked_=!0}function processResult(result,scope){scope.unfinalizedDrafts_=scope.drafts_.length;let baseDraft=scope.drafts_[0];return result!==void 0&&result!==baseDraft?(baseDraft[DRAFT_STATE].modified_&&(revokeScope(scope),die(4)),isDraftable(result)&&(result=finalize(scope,result),scope.parent_||maybeFreeze(scope,result)),scope.patches_&&getPlugin("Patches").generateReplacementPatches_(baseDraft[DRAFT_STATE].base_,result,scope.patches_,scope.inversePatches_)):result=finalize(scope,baseDraft,[]),revokeScope(scope),scope.patches_&&scope.patchListener_(scope.patches_,scope.inversePatches_),result!==NOTHING?result:void 0}function finalize(rootScope,value,path){if(isFrozen(value))return value;let useStrictIteration=rootScope.immer_.shouldUseStrictIteration(),state=value[DRAFT_STATE];if(!state)return each(value,(key,childValue)=>finalizeProperty(rootScope,state,value,key,childValue,path),useStrictIteration),value;if(state.scope_!==rootScope)return value;if(!state.modified_)return maybeFreeze(rootScope,state.base_,!0),state.base_;if(!state.finalized_){state.finalized_=!0,state.scope_.unfinalizedDrafts_--;let result=state.copy_,resultEach=result,isSet2=!1;state.type_===3&&(resultEach=new Set(result),result.clear(),isSet2=!0),each(resultEach,(key,childValue)=>finalizeProperty(rootScope,state,result,key,childValue,path,isSet2),useStrictIteration),maybeFreeze(rootScope,result,!1),path&&rootScope.patches_&&getPlugin("Patches").generatePatches_(state,path,rootScope.patches_,rootScope.inversePatches_)}return state.copy_}function finalizeProperty(rootScope,parentState,targetObject,prop,childValue,rootPath,targetIsSet){if(childValue==null||typeof childValue!="object"&&!targetIsSet)return;let childIsFrozen=isFrozen(childValue);if(!(childIsFrozen&&!targetIsSet)){if(childValue===targetObject&&die(5),isDraft(childValue)){let path=rootPath&&parentState&&parentState.type_!==3&&!has(parentState.assigned_,prop)?rootPath.concat(prop):void 0,res=finalize(rootScope,childValue,path);if(set(targetObject,prop,res),isDraft(res))rootScope.canAutoFreeze_=!1;else return}else targetIsSet&&targetObject.add(childValue);if(isDraftable(childValue)&&!childIsFrozen){if(!rootScope.immer_.autoFreeze_&&rootScope.unfinalizedDrafts_<1||parentState&&parentState.base_&&parentState.base_[prop]===childValue&&childIsFrozen)return;finalize(rootScope,childValue),(!parentState||!parentState.scope_.parent_)&&typeof prop!="symbol"&&(isMap(targetObject)?targetObject.has(prop):Object.prototype.propertyIsEnumerable.call(targetObject,prop))&&maybeFreeze(rootScope,childValue)}}}function maybeFreeze(scope,value,deep=!1){!scope.parent_&&scope.immer_.autoFreeze_&&scope.canAutoFreeze_&&freeze(value,deep)}function createProxyProxy(base,parent){let isArray=Array.isArray(base),state={type_:isArray?1:0,scope_:parent?parent.scope_:getCurrentScope(),modified_:!1,finalized_:!1,assigned_:{},parent_:parent,base_:base,draft_:null,copy_:null,revoke_:null,isManual_:!1},target=state,traps=objectTraps;isArray&&(target=[state],traps=arrayTraps);let{revoke,proxy}=Proxy.revocable(target,traps);return state.draft_=proxy,state.revoke_=revoke,proxy}var objectTraps={get(state,prop){if(prop===DRAFT_STATE)return state;let source=latest(state);if(!has(source,prop))return readPropFromProto(state,source,prop);let value=source[prop];return state.finalized_||!isDraftable(value)?value:value===peek(state.base_,prop)?(prepareCopy(state),state.copy_[prop]=createProxy(value,state)):value},has(state,prop){return prop in latest(state)},ownKeys(state){return Reflect.ownKeys(latest(state))},set(state,prop,value){let desc=getDescriptorFromProto(latest(state),prop);if(desc?.set)return desc.set.call(state.draft_,value),!0;if(!state.modified_){let current2=peek(latest(state),prop),currentState=current2?.[DRAFT_STATE];if(currentState&&currentState.base_===value)return state.copy_[prop]=value,state.assigned_[prop]=!1,!0;if(is(value,current2)&&(value!==void 0||has(state.base_,prop)))return!0;prepareCopy(state),markChanged(state)}return state.copy_[prop]===value&&(value!==void 0||prop in state.copy_)||Number.isNaN(value)&&Number.isNaN(state.copy_[prop])||(state.copy_[prop]=value,state.assigned_[prop]=!0),!0},deleteProperty(state,prop){return peek(state.base_,prop)!==void 0||prop in state.base_?(state.assigned_[prop]=!1,prepareCopy(state),markChanged(state)):delete state.assigned_[prop],state.copy_&&delete state.copy_[prop],!0},getOwnPropertyDescriptor(state,prop){let owner=latest(state),desc=Reflect.getOwnPropertyDescriptor(owner,prop);return desc&&{writable:!0,configurable:state.type_!==1||prop!=="length",enumerable:desc.enumerable,value:owner[prop]}},defineProperty(){die(11)},getPrototypeOf(state){return getPrototypeOf(state.base_)},setPrototypeOf(){die(12)}},arrayTraps={};each(objectTraps,(key,fn)=>{arrayTraps[key]=function(){return arguments[0]=arguments[0][0],fn.apply(this,arguments)}});arrayTraps.deleteProperty=function(state,prop){return isNaN(parseInt(prop))&&die(13),arrayTraps.set.call(this,state,prop,void 0)};arrayTraps.set=function(state,prop,value){return prop!=="length"&&isNaN(parseInt(prop))&&die(14),objectTraps.set.call(this,state[0],prop,value,state[0])};function peek(draft,prop){let state=draft[DRAFT_STATE];return(state?latest(state):draft)[prop]}function readPropFromProto(state,source,prop){let desc=getDescriptorFromProto(source,prop);return desc?"value"in desc?desc.value:desc.get?.call(state.draft_):void 0}function getDescriptorFromProto(source,prop){if(!(prop in source))return;let proto=getPrototypeOf(source);for(;proto;){let desc=Object.getOwnPropertyDescriptor(proto,prop);if(desc)return desc;proto=getPrototypeOf(proto)}}function markChanged(state){state.modified_||(state.modified_=!0,state.parent_&&markChanged(state.parent_))}function prepareCopy(state){state.copy_||(state.copy_=shallowCopy(state.base_,state.scope_.immer_.useStrictShallowCopy_))}var Immer2=class{constructor(config){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(base,recipe,patchListener)=>{if(typeof base=="function"&&typeof recipe!="function"){let defaultBase=recipe;recipe=base;let self=this;return function(base2=defaultBase,...args){return self.produce(base2,draft=>recipe.call(this,draft,...args))}}typeof recipe!="function"&&die(6),patchListener!==void 0&&typeof patchListener!="function"&&die(7);let result;if(isDraftable(base)){let scope=enterScope(this),proxy=createProxy(base,void 0),hasError=!0;try{result=recipe(proxy),hasError=!1}finally{hasError?revokeScope(scope):leaveScope(scope)}return usePatchesInScope(scope,patchListener),processResult(result,scope)}else if(!base||typeof base!="object"){if(result=recipe(base),result===void 0&&(result=base),result===NOTHING&&(result=void 0),this.autoFreeze_&&freeze(result,!0),patchListener){let p=[],ip=[];getPlugin("Patches").generateReplacementPatches_(base,result,p,ip),patchListener(p,ip)}return result}else die(1,base)},this.produceWithPatches=(base,recipe)=>{if(typeof base=="function")return(state,...args)=>this.produceWithPatches(state,draft=>base(draft,...args));let patches,inversePatches;return[this.produce(base,recipe,(p,ip)=>{patches=p,inversePatches=ip}),patches,inversePatches]},typeof config?.autoFreeze=="boolean"&&this.setAutoFreeze(config.autoFreeze),typeof config?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(config.useStrictShallowCopy),typeof config?.useStrictIteration=="boolean"&&this.setUseStrictIteration(config.useStrictIteration)}createDraft(base){isDraftable(base)||die(8),isDraft(base)&&(base=current(base));let scope=enterScope(this),proxy=createProxy(base,void 0);return proxy[DRAFT_STATE].isManual_=!0,leaveScope(scope),proxy}finishDraft(draft,patchListener){let state=draft&&draft[DRAFT_STATE];(!state||!state.isManual_)&&die(9);let{scope_:scope}=state;return usePatchesInScope(scope,patchListener),processResult(void 0,scope)}setAutoFreeze(value){this.autoFreeze_=value}setUseStrictShallowCopy(value){this.useStrictShallowCopy_=value}setUseStrictIteration(value){this.useStrictIteration_=value}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(base,patches){let i;for(i=patches.length-1;i>=0;i--){let patch=patches[i];if(patch.path.length===0&&patch.op==="replace"){base=patch.value;break}}i>-1&&(patches=patches.slice(i+1));let applyPatchesImpl=getPlugin("Patches").applyPatches_;return isDraft(base)?applyPatchesImpl(base,patches):this.produce(base,draft=>applyPatchesImpl(draft,patches))}};function createProxy(value,parent){let draft=isMap(value)?getPlugin("MapSet").proxyMap_(value,parent):isSet(value)?getPlugin("MapSet").proxySet_(value,parent):createProxyProxy(value,parent);return(parent?parent.scope_:getCurrentScope()).drafts_.push(draft),draft}function current(value){return isDraft(value)||die(10,value),currentImpl(value)}function currentImpl(value){if(!isDraftable(value)||isFrozen(value))return value;let state=value[DRAFT_STATE],copy,strict=!0;if(state){if(!state.modified_)return state.base_;state.finalized_=!0,copy=shallowCopy(value,state.scope_.immer_.useStrictShallowCopy_),strict=state.scope_.immer_.shouldUseStrictIteration()}else copy=shallowCopy(value,!0);return each(copy,(key,childValue)=>{set(copy,key,currentImpl(childValue))},strict),state&&(state.finalized_=!1),copy}var immer=new Immer2,produce=immer.produce;var NONE=Symbol("NONE"),readKey=(value,key,dval=null)=>value==null?dval:value instanceof Map?value.has(key)?value.get(key):dval:value instanceof Set?value.has(key)?key:dval:Object.hasOwn(value,key)?value[key]:dval,writeKey=(value,key,next)=>{value instanceof Map?value.set(key,next):value instanceof Set?(value.delete(key),value.add(next)):value[key]=next},writeSeqKey=(value,key,next)=>{value instanceof Map||value instanceof Set||Array.isArray(value)||Object.hasOwn(value,key)?writeKey(value,key,next):typeof value?.set=="function"?value.set(key,next):writeKey(value,key,next)},Step=class{lookup(_v,dval=null){return dval}setDraftValue(_root,_v){}enterFrame(stack,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}enterFrame(stack,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,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 readKey(v,this.field,dval)}setDraftValue(root,v){writeKey(root,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){return seqGet(readKey(v,this.field,null),this.key,dval)}setDraftValue(root,v){let seq=readKey(root,this.field,null);seq!=null&&writeSeqKey(seq,this.key,v)}enterFrame(stack,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=readKey(v,this.seqField,NONE),key=readKey(v,this.keyField,NONE);return key!==NONE&&seq!==NONE?seqGet(seq,key,dval):dval}setDraftValue(root,v){let seq=readKey(root,this.seqField,NONE),key=readKey(root,this.keyField,NONE);seq!==NONE&&key!==NONE&&writeSeqKey(seq,key,v)}pinKey(v){let key=readKey(v,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}enterFrame(stack,next){return stack.enter(next,this.iterInfo.enrichBinds(stack,this.key),!1)}toAbstractPathStep(){return null}},EachRenderItStep=class extends SeqStep{enterFrame(stack,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}enterFrame(stack,_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){return this.steps.length===0?v:produce(root,draft=>{let parent=draft;for(let i=0;i<this.steps.length-1;i++)if(parent=this.steps[i].lookup(parent,NONE),parent===NONE)return;this.steps.at(-1).setDraftValue(parent,v)})}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,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]}};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 isMac=(globalThis.navigator?.userAgent??"").toLowerCase().includes("mac");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_SEQ=256,K_METHOD=1024,K_EVENT=2048,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_CONST,G_HANDLER_ARG=G_VALUE&~K_NAME|K_EVENT,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:isPlainObject(v)?Object.keys(v).length: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}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)=>Object.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===101&&/^e(\.[a-zA-Z][a-zA-Z0-9_]*)+$/.exec(s)!==null?new EventMemberVal(s.split(".").slice(1)):c0>=97&&c0<=122?mkVal(s,NameVal):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}var parseText=(s,px)=>_parseSingle(s,px,G_TEXT),parseComponent=(s,px)=>_parseSingle(s,px,G_COMPONENT),parseSequence=(s,px)=>_parseSingle(s,px,G_SEQUENCE),parseField=(s,px)=>_parseSingle(s,px,G_FIELD),parseProvide=(s,px)=>_parseSingle(s,px,G_PROVIDE),parseMacroAttr=(s,px)=>_parseSingle(s,px,G_ALL),parseReceiveHandler=(s,px)=>_parseHandler(s,px,"receive",!0,!0,!1),parseAlterHandler=(s,px)=>_parseHandler(s,px,"alter",!1,!1,!0)?.handlerVal??null;function _parseHandler(s,px,namespace,allowArgs,report,allowMethod){let tokens=tokenizeValue(s.trim()),headTok=tokens[0]??"",head=headTok===""?null:parseToken(headTok,px),hk=kindOf(head),handlerVal;if(hk&K_METHOD&&allowMethod)handlerVal=head;else{if(hk&K_METHOD)return report&&px.onParseIssue("event-method-handler",{name:head.name,role:"handler-name",value:headTok}),null;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_HANDLER_ARG?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 NameVal?K_NAME:val instanceof EventMemberVal?K_EVENT: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}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(stack,this.namespace,this.name)}},mk404Handler=(stack,type,name)=>function(...args){let transactor=stack?.ctx?.transactor;return transactor?transactor.refuse("NO_HANDLER",{namespace:type,name,argCount:args.length}):console.warn("handler not found",{type,name}),this},keyIs=k=>e=>e.key===k,macCtrl=e=>isMac&&e.metaKey||e.ctrlKey,nullSafe=fn=>(e,stack)=>{let info=stack.lookupDragInfo();return info==null?null:fn(info)},EVENT_CONVENIENCES={value:e=>getValue(e),valueAsInt:e=>toNullIfNaN(parseInt(getValue(e),10)),valueAsFloat:e=>toNullIfNaN(parseFloat(getValue(e))),isAlt:e=>e.altKey,isShift:e=>e.shiftKey,isCtrl:macCtrl,isCmd:macCtrl,isUpKey:keyIs("ArrowUp"),isDownKey:keyIs("ArrowDown"),isSend:keyIs("Enter"),isCancel:keyIs("Escape"),isTabKey:keyIs("Tab"),dragInfo:(_e,stack)=>stack.lookupDragInfo(),dragType:nullSafe(info=>info.type),dragValue:nullSafe(info=>info.val),dragKey:nullSafe(info=>info.lookupBind("key"))},EventMemberVal=class extends BaseVal{constructor(members){super(),this.members=members}eval(stack){let e=stack.lookupEvent();if(e==null)return null;if(this.members.length===1){let convenience=EVENT_CONVENIENCES[this.members[0]];if(convenience!==void 0)return convenience(e,stack)}let v=e;for(let member of this.members){if(v==null)return null;v=v[member]}return v??null}toString(){return`e.${this.members.join(".")}`}},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 seqGet(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 seqGet(this.seqVal.eval(stack),key,null)}toString(){return`${this.seqVal}[${this.keyVal}]`}};var Attributes=class{constructor(items){this.items=items}static parse(attributes,px,parseAll=!1){return new AttrParser(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(","));function parseDirectiveValue(px,directiveName,source,parser){let val=parser(source,px);return val===null&&px.onParseIssue("bad-value",{role:"directive",directive:directiveName,value:source}),val}function parseIterationDirectives(attributes,px){let parseNamed=name=>{let attr=attributes.getNamedItem(`@${name}`);return attr?parseDirectiveValue(px,name,attr.value,parseAlterHandler):null};return{whenVal:parseNamed("when"),loopWithVal:parseNamed("loop-with")}}var AttrParser=class{constructor(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){return parseDirectiveValue(this.px,directiveName,s,parserFn)}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)}},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=parseReceiveHandler(s,px);return r===null?null:new _EventHandler(r.handlerVal,r.args)}};var SEQ_INFO=Symbol.for("tutuca.seqInfo"),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]},nativeIndexedIter=(seq,visit,start,end)=>{let[s,e]=normalizeRange(start,end,seqSize(seq));for(let i=s;i<e;i++)visit(i,seq[i],"si")},nativeKeyedIter=(seq,visit,start,end)=>{let[s,e]=normalizeRange(start,end,seqSize(seq)),i=0;for(let[key,value]of seqEntries(seq)){if(i>=e)break;i>=s&&visit(key,value,"sk"),i++}},unknownIter=()=>{},getSeqInfo=seq=>isIndexedSeq(seq)?nativeIndexedIter:isKeyedSeq(seq)||isSetSeq(seq)?nativeKeyedIter:seq?.[SEQ_INFO]??unknownIter,filterAlwaysTrue=(_key,_value,_iterData)=>!0,nullLoopWith=seq=>({iterData:{seq}}),unpackLoopResult=(result,seq)=>{let value=result??{};return{iterData:value.iterData??{seq},start:value.start,end:value.end,keys:value.keys}},makeLoopCtx=(stack,filter)=>({lookup:name=>stack.lookupBind(name),filter:(key,value,iterData)=>filter.call(stack.it,key,value,iterData)}),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};function bindsForKey({seq,it,loopWith,enricher,ctx},key){let value=seqGet(seq,key,null),binds={key,value};if(enricher){let{iterData}=unpackLoopResult(loopWith.call(it,seq,ctx),seq);callEnricher(enricher,it,binds,key,value,iterData)}return binds}var visitKeys=(seq,keys,visit)=>{let attrName=isIndexedSeq(seq)?"si":"sk";for(let key of keys)visit(key,seqGet(seq,key),attrName)};function walkLoopBindings({seq,it,filter,loopWith,enricher,ctx},visit){let{iterData,start,end,keys}=unpackLoopResult(loopWith.call(it,seq,ctx),seq),visitOne=(key,value,attrName)=>{let binds={key,value};enricher&&callEnricher(enricher,it,binds,key,value,iterData),visit(key,value,attrName,binds)};keys?visitKeys(seq,keys,visitOne):getSeqInfo(seq)(seq,(key,value,attrName)=>{filter.call(it,key,value,iterData)&&visitOne(key,value,attrName)},start,end)}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".split(" ")),PROP_ATTR_NAME={className:"class",htmlFor:"for"};function applyProperties(node,props){let namespaced=isNamespaced(node);for(let name in props)setProp(node,name,props[name],namespaced)}function setProp(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"):setProp(node,"value",value,isNamespaced(node))}var VBase=class{},getKey=child=>child instanceof VNode?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}},VNode=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&&setProp(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&&setProp(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){if(vnode==null)return container.replaceChildren(),{vnode:null,dom:null};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 VNode(tag,props,normalizedChildren,key,namespace)}function resolveDynProducer(comp,name){let own=comp?.provide?.[name],producerComp=own!=null?comp:comp?.scope?.lookupProvider(name)??null,producerProvide=own??producerComp?.provide?.[name];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;if(wrappable&&aName.charCodeAt(0)===64){let wrapper=X_OPS[aName.slice(1)]?.wrapper;if(wrapper){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 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),{whenVal,loopWithVal}=parseIterationDirectives(attrs,px),each2=px.addNodeIf(EachNode,seqVal);return each2.iterInfo.whenVal=whenVal,each2.iterInfo.loopWithVal=loopWithVal,each2.fromRenderEach=!0,each2.wrapNode(renderIt),each2}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),ctx=makeLoopCtx(stack,filter);return bindsForKey({seq,it:stack.it,loopWith,enricher,ctx},key)}};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"],{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)}},_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,fwdIfEventPred=pred=>fwdIfCtxPred(({e})=>pred(e)),fwdIfKey=keyName=>fwdIfEventPred(keyIs(keyName)),fwdCtrl=fwdIfEventPred(macCtrl),fwdMeta=fwdIfEventPred(e=>e.metaKey),fwdAlt=fwdIfEventPred(e=>e.altKey),MOD_WRAPPERS_FOR_ANY_EVENT={ctrl:fwdCtrl,cmd:fwdCtrl,meta:fwdMeta,alt:fwdAlt},MOD_WRAPPERS_BY_EVENT={keydown:{send:fwdIfKey("Enter"),cancel:fwdIfKey("Escape")}},MOD_EFFECTS={prevent:e=>e.preventDefault?.(),stop:e=>e.stopPropagation?.()},NO_WRAPPERS={},identityModifierWrapper=(f,_ctx)=>f;function compileModifiers(eventName,names){if(names.length===0)return identityModifierWrapper;let wrappers=MOD_WRAPPERS_BY_EVENT[eventName]??NO_WRAPPERS,effects=[];for(let name of names){let effect=MOD_EFFECTS[name];effect!==void 0&&effects.push(effect)}let w=effects.length===0?(that,f,args,_ctx)=>f.apply(that,args):(that,f,args,ctx)=>{for(let effect of effects)effect(ctx.e);return f.apply(that,args)};for(let name of names){let wrapper=wrappers[name]??MOD_WRAPPERS_FOR_ANY_EVENT[name];wrapper!==void 0&&(w=wrapper(w))}return(f,ctx)=>function(...args){return w(this,f,args,ctx)}}var COMPONENT=Symbol.for("tutuca.component"),Components=class{constructor(){this.byId=new Map}registerComponent(Comp){this.byId.set(Comp[COMPONENT].id,Comp)}getComponentForId(id){return this.byId.get(id)??null}getCompFor(v){let Comp=v?.constructor;return Comp?.[COMPONENT]?Comp:null}getHandlerFor(v,name,key){return this.getCompFor(v)?.[key][name]??null}getIntentChainFor(v,name){return this.getCompFor(v)?.scope.lookupIntentChain(name)??[]}compileStyles(){let styles=[];for(let Comp of this.byId.values())styles.push(Comp[COMPONENT].compileStyle());return styles.join(`
2
2
  `)}},ComponentStack=class _ComponentStack{constructor(comps=new Components,parent=null){this.comps=comps,this.parent=parent,this.byName={},this.intentsByName={},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[COMPONENT].scope=this.enter(),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)}registerIntentHandlers(handlers){for(let name in handlers){let fns=handlers[name];this.intentsByName[name]=Array.isArray(fns)?fns:[fns]}}lookupIntentChain(name){let here=this.intentsByName[name]??[],up=this.parent?.lookupIntentChain(name)??[];return up.length===0?here:here.concat(up)}lookupComponent(name){return this.byName[name]??this.parent?.lookupComponent(name)??null}lookupProvider(name){for(let compName in this.byName){let Comp=this.byName[compName];if(Comp.provide?.[name]!==void 0)return Comp}return this.parent?.lookupProvider(name)??null}lookupMacro(name){return this.macros[name]??this.parent?.lookupMacro(name)??null}},ProvideInfo=class{constructor(val){this.val=val}},LookupInfo=class{constructor(val){this.val=val}},isString=v=>typeof v=="string",isTypeName=s=>{let c=s.charCodeAt(0);return c>=65&&c<=90},_rawSpecKeys="name view style commonStyle globalStyle receive intent 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.receive=o.receive??{},this.intent=o.intent??{},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.provideType={},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){if(isTypeName(key)){this._rawProvide[key]==="self"&&(this.provideType[key]=this.Class);continue}let val=parseProvide(this._rawProvide[key],ctx);val&&(this.provide[key]=new ProvideInfo(val))}for(let entry of this._rawLookup){let name=isString(entry)?entry:isString(entry?.name)?entry.name:null;if(name===null)continue;let defStr=isString(entry?.default)?entry.default:null;this.lookup[name]=new LookupInfo(defStr===null?null:parseField(defStr,ctx))}for(let key in this.lookup)this.provide[key]!==void 0&&console.warn("name declared in both provide and lookup",this.name,key)}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"),DEFAULT_ROUTE=["dyn","lex"];function routeLookup(route,lex,dyn){for(let i=0;i<route.length;i++){let leg=route[i];if(leg==="dyn"){let v=dyn();if(v!=null)return v}else if(leg==="lex"){let v=lex();if(v!=null)return v}else console.warn("unknown lookup route leg",leg,'- expected "dyn" or "lex"')}return null}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 Stack=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 comp=this.comps.getCompFor(this.it);if(comp==null)return this;let{provide,provideType}=comp,dynObj={},has2=!1;for(let k in provide)dynObj[k]=provide[k].val.eval(this),has2=!0;for(let k in provideType)dynObj[k]=provideType[k],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.lookupDynamic(k));for(let k in comp.lookup)arr.push(this.lookupDynamic(k))}lookupDynamic(name){let v=lookup(this.dynBinds,name);return v??this.comps.getCompFor(this.it)?.lookup[name]?.val?.eval(this)??null}lookupBind(name){return lookup(this.binds,name)}lookupFieldRaw(name){return this.it[name]??null}lookupMethod(name){let fn=this.it[name];return fn instanceof Function?fn.call(this.it):null}lookupEvent(){return this.ctx?.event??null}lookupDragInfo(){return this.ctx?.dragInfo??null}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 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.defaultValue=defaultValue}isValid(v){return this.typeCheck(v)}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)}},CHECK_TYPE_ANY=_v=>!0,CHECK_TYPE_INT=Number.isInteger,CHECK_TYPE_FLOAT=Number.isFinite,CHECK_TYPE_BOOL=v=>typeof v=="boolean",CHECK_TYPE_STRING=v=>typeof v=="string",CHECK_TYPE_LIST=Array.isArray,CHECK_TYPE_OBJECT=isPlainObject,CHECK_TYPE_MAP=v=>v instanceof Map,CHECK_TYPE_SET=v=>v instanceof Set,FieldBool=class extends Field{constructor(name,defaultValue=!1){super("bool",name,CHECK_TYPE_BOOL,v=>!!v,defaultValue)}},FieldAny=class extends Field{constructor(name,defaultValue=null){super("any",name,CHECK_TYPE_ANY,nullCoercer,defaultValue)}},FieldString=class extends Field{constructor(name,defaultValue=""){super("text",name,CHECK_TYPE_STRING,v=>v?.toString?.()??"",defaultValue)}},FieldInt=class extends Field{constructor(name,defaultValue=0){super("int",name,CHECK_TYPE_INT,v=>Number.isFinite(v)?Math.trunc(v):null,defaultValue)}},FieldFloat=class extends Field{constructor(name,defaultValue=0){super("float",name,CHECK_TYPE_FLOAT,_=>null,defaultValue)}},metaOf=v=>v?.constructor?.[COMPONENT]??v?.constructor?.getMetaClass?.(),getTypeName=v=>metaOf(v)?.name??null,FieldComp=class extends Field{constructor(type,name,args){super(type,name,v=>getTypeName(v)===type,nullCoercer,null),this.args=args}},FieldList=class extends Field{constructor(name,defaultValue=[]){super("list",name,CHECK_TYPE_LIST,v=>Array.isArray(v)?[...v]:null,defaultValue)}},FieldObject=class extends Field{constructor(name,defaultValue={}){super("object",name,CHECK_TYPE_OBJECT,v=>isPlainObject(v)?{...v}:null,defaultValue)}},FieldMap=class extends Field{constructor(name,defaultValue=new Map){super("map",name,CHECK_TYPE_MAP,v=>v instanceof Map?new Map(v):Array.isArray(v)||isPlainObject(v)?new Map(Array.isArray(v)?v:Object.entries(v)):null,defaultValue)}},FieldSet=class extends Field{constructor(name,defaultValue=new Set){super("set",name,CHECK_TYPE_SET,v=>v instanceof Set||Array.isArray(v)?new Set(v):null,defaultValue)}};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){this.name=name,this.fields={},this.compFields=new Set,this._methods={},this._statics={}}build(){let{name,fields,compFields,_methods}=this,defaults=Object.fromEntries(Object.entries(fields).map(([fieldName,field])=>[fieldName,field.defaultValue])),Class={[name]:class{constructor(values={}){Object.assign(this,defaults,values)}}}[name];Class[DRAFTABLE]=!0,Object.assign(Class.prototype,_methods);let metaClass={fields,name,methods:_methods};return Object.assign(Class,{getMetaClass:()=>metaClass,make(inArgs={},opts={}){let args={},scope=opts.scope??this[COMPONENT]?.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 freeze(new this(args),!0)}},this._statics),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,object:FieldObject,map:FieldMap,set:FieldSet,any:FieldAny};function fieldFromDescriptor(name,value){let FieldCls=fieldsByTypeName[value.type]??FieldAny,probe=new FieldCls(name);return[FieldCls,probe.coerceOr(value.defaultValue,probe.defaultValue)]}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,Number.isInteger(value)?FieldInt:FieldFloat);else if(type==="boolean")b.addField(field,value,FieldBool);else if(Array.isArray(value))b.addField(field,[...value],FieldList);else if(value instanceof Set)b.addField(field,new Set(value),FieldSet);else if(value instanceof Map)b.addField(field,new Map(value),FieldMap);else if(value?.type&&Object.hasOwn(value,"defaultValue")){let[FieldCls,dval]=fieldFromDescriptor(field,value);b.addField(field,dval,FieldCls)}else if(value?.component&&value?.args!==void 0)b.addCompField(field,value.component,value.args);else if(isPlainObject(value))b.addField(field,{...value},FieldObject);else{let FieldCls=value?.[FIELD_CLASS]??FieldAny;b.addField(field,value,FieldCls)}}return methods&&b.methods(methods),statics&&b.statics(statics),b.build()}function validateDraftFields(current2,draft){let meta=metaOf(current2);if(meta)for(let[name,field]of Object.entries(meta.fields)){let value=draft[name];if(field.isValid(value))continue;let coerced=field.coerceOr(value,BAD_VALUE);coerced!==BAD_VALUE?draft[name]=coerced:(console.warn(`invalid value for ${meta.name}.${name}`,value),draft[name]=current2[name])}}var META_KEYS="name id fields methods views receive intent alter provide provideType lookup spec extra commonStyle globalStyle scope _rawProvide _rawLookup".split(" "),RESERVED_COMPONENT_STATICS=new Set([...META_KEYS,"make","getMetaClass",...Object.getOwnPropertyNames(Component.prototype)]);function assertNoReservedComponentStatics(statics={}){for(let name in statics)if(RESERVED_COMPONENT_STATICS.has(name))throw new TypeError(`component static "${name}" is reserved by the framework`)}Component.fromSpec=opts=>{assertNoReservedComponentStatics(opts.statics);let Class=classFromData(opts.name,opts),comp=new Component(Class,opts),metaClass=Class.getMetaClass();comp.fields=metaClass.fields,comp.methods=metaClass.methods,Class.getMetaClass=()=>comp,Class[COMPONENT]=comp;for(let key of META_KEYS)Object.hasOwn(Class,key)||Object.defineProperty(Class,key,{get(){return comp[key]},set(v){comp[key]=v},configurable:!0});for(let key of Object.getOwnPropertyNames(Component.prototype))key!=="constructor"&&!Object.hasOwn(Class,key)&&(Class[key]=(...args)=>comp[key](...args));return Class};var component=opts=>Component.fromSpec(opts);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()})}},Transactor=class{constructor(comps,rootValue){this.comps=comps,this.transactions=[],this.state=new State(rootValue),this.onTransactionPushed=()=>{},this._observers=[],this.refusals=[],this._refusalObservers=[],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)}refuse(kind,info={}){let record={kind,info,timestamp:Date.now()};this.refusals.push(record),this.refusals.length>REFUSAL_RING_CAP&&this.refusals.shift(),console.warn(`tutuca refusal [${kind}]`,info);for(let cb of this._refusalObservers)cb(record);return record}observeRefusals(cb){return this._refusalObservers.push(cb),()=>{let i=this._refusalObservers.indexOf(cb);i!==-1&&this._refusalObservers.splice(i,1)}}_emitRecord(root,{kind,name,args,path,targetPath,handler,handlerName,matched,before,after,parent}){if(this._observers.length===0)return;let pinned=path.pinKeys(root);this._emit({kind,name,args:args??null,path:pinned,pathKeys:pinned.toKeys(),targetPath,handler:handler??null,handlerName:handlerName??(handler?.name||null),matched:matched??null,before,after,parent,timestamp:Date.now()})}_emitTransaction(transaction,root){this._observers.length!==0&&transaction._resolvedHandler!==void 0&&this._emitRecord(root,{kind:transaction.observeKind,name:transaction.observeName,args:transaction.args,path:transaction.getTransactionPath(),targetPath:transaction.targetPath??transaction.path,handler:transaction._resolvedHandler,matched:transaction._matched,before:transaction._before,after:transaction._after,parent:transaction.parentTransaction})}_link(child,parent){if(parent){let release=parent.completion.track();child.completion.whenSubtreeSettled().then(release)}return child}pushSend(path,name,args=[],parent=null,origin=null){let t=new SendEvent(path,this,name,args,parent);return t.origin=origin===null?null:origin.toTransactionPath().pinKeys(this.state.val),this.pushTransaction(t),this._link(t,parent)}pushIntent(path,name,args=[],opts={},parent=null){let release=parent?parent.completion.track():null,walk=new IntentWalk(this,path,name,args,opts,parent,release);return walk.advance(),walk}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])}}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.ensureWalkAdvanced?.(),transaction._completion?.ensureSelfSettled(),transaction._completion?.releaseSelf()}}transactInputNow(path,event,eventHandler,dragInfo){this.transact(new InputEvent(path,event,eventHandler,this,dragInfo))}};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()}afterTransaction(){}stop(){warnNotIntent("stop")}forward(_opts){console.warn('ctx.forward() needs a "receive" or "intent" handler - ignored')}get observeKind(){return null}get observeName(){return null}callHandler(root,instance,draft,comps){let[handler,args]=this.getHandlerAndArgs(root,instance,comps);return this._resolvedHandler=handler,handler.apply(instance,[draft,...args])}getHandlerAndArgs(_root,_instance,_comps){return null}getTransactionPath(){return this.path.toTransactionPath().compact()}run(curRoot,comps){let txnPath=this.getTransactionPath(),curLeaf=txnPath.lookup(curRoot),newLeaf=produce(curLeaf,draft=>{let result=this.callHandler(curRoot,curLeaf,draft,comps);return(result===void 0||result===draft)&&validateDraftFields(curLeaf,draft),result});return this._before=curLeaf,this._after=newLeaf,this._completion?.markSelfSettled({value:newLeaf,old:curLeaf}),curLeaf!==newLeaf?txnPath.setValue(curRoot,newLeaf):curRoot}},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"receive"}get observeName(){return this.e?.type??null}forward(opts){this._forward=opts??{}}afterTransaction(){let f=this._forward;if(f===void 0)return;this._forward=void 0;let{args=this._handlerArgs??[],...rest}=f,name=(this.handler?.handlerCall?.handlerVal??this.handler?.handlerVal)?.name;if(name===void 0){this.transactor.refuse("FORWARD_NO_NAME",{});return}this.transactor.pushIntent(this.dispatchPath,name,args,rest,this)}getHandlerAndArgs(root,_instance,comps){let stack=this.path.toTransactionPath().buildStack(Stack.root(comps,root,this)),[handler,args]=this.handler.getHandlerAndArgs(stack,this);this._handlerArgs=[...args];let path=this.dispatchPath;return args.push(new EventContext(path,this.transactor,this)),[handler,args]}get event(){return this.e}},NameArgsTransaction=class extends Transaction{constructor(path,transactor,name,args,parentTransaction){super(path,transactor,parentTransaction),this.name=name,this.args=args,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)]]}},SendEvent=class extends NameArgsTransaction{handlerProp="receive";get observeKind(){return this._isAnswer?"answer":"receive"}forward(opts){this._forward=opts??{}}afterTransaction(){let f=this._forward;if(f===void 0)return;this._forward=void 0;let{args=this.args,...rest}=f;this.transactor.pushIntent(this.path,this.name,args,rest,this)}},IntentEvent=class extends NameArgsTransaction{handlerProp="intent";constructor(path,transactor,walk){super(path,transactor,walk.name,walk.args,walk.parent),this.walk=walk,this.targetPath=walk.origin}forward(opts){this.walk.amend(opts,this.path)}stop(){this.walk.finish(null,null)}afterTransaction(){this.ensureWalkAdvanced()}ensureWalkAdvanced(){this._advanced||(this._advanced=!0,this.walk.advance())}},PASS=Symbol.for("tutuca.intent.pass"),REFUSAL_RING_CAP=200,INTENT_DEPTH=64,IntentWalk=class{constructor(transactor,path,name,args,opts,parent,release){this.transactor=transactor,this.name=name,this.args=args,this.route=opts?.route??DEFAULT_ROUTE,this.parent=parent,this.release=release,this.origin=path,this.answerPath=opts?.livePath?null:path.toTransactionPath().pinKeys(transactor.state.val),this.legIndex=0,this.dynAt=path,this.hops=0,this.ended=!1}advance(){if(!this.ended){if(this.hops++>=INTENT_DEPTH)return this.exhaust("intentDepth");for(;this.legIndex<this.route.length;){let leg=this.route[this.legIndex];if(leg==="dyn"){if(this.dynAt.steps.length===0){this.legIndex++;continue}this.dynAt=this.dynAt.popStep(),this.transactor.pushTransaction(new IntentEvent(this.dynAt,this.transactor,this));return}if(leg==="lex")return this.legIndex++,this._tryLex();console.warn("unknown intent route leg",leg,'- expected "dyn" or "lex"'),this.legIndex++}this.exhaust("noHandler")}}_tryLex(){let root=this.transactor.state.val,txnPath=this.origin.toTransactionPath(),leaf=txnPath.lookup(root),chain=this.transactor.comps.getIntentChainFor(leaf,this.name);if(this.transactor._emitRecord(root,{kind:"intent",name:this.name,args:this.args,path:txnPath,targetPath:this.origin,handler:chain[0],handlerName:chain[0]?.name||this.name,matched:chain.length>0?"exact":"none",before:leaf,after:void 0,parent:this.parent}),chain.length===0)return this.advance();let p=this._runLex(chain,0);this.transactor._inflight.add(p),p.finally(()=>this.transactor._inflight.delete(p))}async _runLex(chain,i){if(this.ended)return;if(i>=chain.length)return this.advance();let ctx=new Dispatcher(this.origin,this.transactor,this.parent);try{let res=await chain[i].apply(null,[...this.args,ctx]);if(res===PASS)return this._runLex(chain,i+1);this.answer("Ok",res)}catch(error){this.answer("Error",error)}}answer(suffix,value){this.finish(`${this.name}${suffix}`,[value])}amend(opts,from){opts?.args!==void 0&&(this.args=opts.args),opts?.route!==void 0&&(this.route=opts.route,this.legIndex=0,this.dynAt=from??this.dynAt)}exhaust(reason){if(this.ended)return;let{name,args}=this,comp=this.transactor.comps.getCompFor(this.origin.toTransactionPath().lookup(this.transactor.state.val)),declares=n=>comp?.receive?.[n]!==void 0;declares(`${name}Unhandled`)?this.finish(`${name}Unhandled`,args):declares(`${name}Error`)?this.finish(`${name}Error`,[reason]):(declares(`${name}Ok`)&&console.warn(`intent "${name}" was not answered (${reason}) and this component declares only "${name}Ok" - add "${name}Unhandled" or "${name}Error" to handle it`),this.finish(null,null))}finish(name,args){if(this.ended)return;if(this.ended=!0,name===null)return this.release?.();let path=this.answerPath??this.origin,t=new SendEvent(path,this.transactor,name,args,this.parent);t._isAnswer=!0,this.transactor.pushTransaction(t),this.release&&t.completion.whenSubtreeSettled().then(this.release)}},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)}_stack(){return this._stackMemo??=this.path.toTransactionPath().buildStack(Stack.root(this.transactor.comps,this.root,this.parent)),this._stackMemo}lookup(name,opts){return routeLookup(opts?.route??DEFAULT_ROUTE,()=>this._lookupLex(name),()=>this._stack()?.lookupDynamic(name)??null)}_lookupLex(name){let Comp=null;return this.walkPath(c=>(Comp=c,!1)),Comp?.scope?.lookupComponent(name)??null}lookupType(name,opts){let route=opts?.route??DEFAULT_ROUTE,v=this.lookup(name,{route});return v==null?(this.transactor.refuse("TYPE_NOT_FOUND",{name,route}),null):v?.[COMPONENT]==null?(this.transactor.refuse("TYPE_NOT_COMPONENT",{name,got:typeof v}),null):v}send(name,args){return this.sendAtPath(this.path,name,args)}sendAtPath(path,name,args){return this.transactor.pushSend(path,name,args,this.parent,this.path)}intent(name,args,opts){return this.intentAtPath(this.path,name,args,opts)}intentAtPath(path,name,args,opts){return this.transactor.pushIntent(path,name,args,opts,this.parent)}},EventContext=class extends Dispatcher{get name(){return this.parent?.name??null}get targetPath(){return this.parent.targetPath}reply(value){return this.parent.walk===void 0?warnNotIntent("reply"):this.parent.walk.answer("Ok",value)}fail(error){return this.parent.walk===void 0?warnNotIntent("fail"):this.parent.walk.answer("Error",error)}sendReply(name,args){let origin=this.parent?.origin??null;return origin==null?(this.transactor.refuse("NO_SENDER",{name}),null):this.sendAtPath(origin,name,args)}stop(){return this.parent.stop()}forward(opts){return this.parent.forward(opts)}};function warnNotIntent(verb){console.warn(`ctx.${verb}() is only meaningful in an "intent" handler - ignored`)}var PathChanges=class extends PathBuilder{constructor(dispatcher){super(),this.dispatcher=dispatcher}send(name,args){return this.dispatcher.sendAtPath(this.buildPath(),name,args)}intent(name,args,opts){return this.dispatcher.intentAtPath(this.buildPath(),name,args,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.fromNodeAndEventName(e.target,type,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,value=path.compact().toTransactionPath().lookup(rootValue),dragType=e.target.dataset.dragtype??"?",stack=path.toTransactionPath().buildStack(this.makeStack(rootValue));this.dragInfo=new DragInfo(stack,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 Stack.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()){let meta=Comp[COMPONENT];meta.compile(this.ParseContext);for(let key in meta.views)for(let name of meta.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){this.transactor.pushSend(new Path([]),name,args)}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(stack,val,type,node){this.stack=stack,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 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 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,renderOne=(key,value,attrName,binds)=>{let cachePath=enricher?[view,it,value]:[view,value],cacheKey=`${stack.viewsId??""}${nid}${key}`,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 walkLoopBindings({seq,it,filter,loopWith,enricher,ctx:makeLoopCtx(stack,filter)},renderOne),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])}};var OP_KINDS=["send","intent"];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 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);break;case"intent":dispatcher.intentAtPath(targetPath,op.name,args,op.opts);break}}}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{COMPONENT,FIELD_CLASS,PASS,ParseContext,SEQ_INFO,check,collectIterBindings,compileClassesToStyle,compileClassesToStyleText,component,css,dispatchPhase,html,injectCss,macro,phaseOps,resolveArgs,rootDispatcher,test,tutuca};
3
+ `)}};var STOP=Symbol("STOP"),NEXT=Symbol("NEXT"),DEFAULT_ROUTE=["dyn","lex"];function routeLookup(route,lex,dyn){for(let i=0;i<route.length;i++){let leg=route[i];if(leg==="dyn"){let v=dyn();if(v!=null)return v}else if(leg==="lex"){let v=lex();if(v!=null)return v}else console.warn("unknown lookup route leg",leg,'- expected "dyn" or "lex"')}return null}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 Stack=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 comp=this.comps.getCompFor(this.it);if(comp==null)return this;let{provide,provideType}=comp,dynObj={},has2=!1;for(let k in provide)dynObj[k]=provide[k].val.eval(this),has2=!0;for(let k in provideType)dynObj[k]=provideType[k],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.lookupDynamic(k));for(let k in comp.lookup)arr.push(this.lookupDynamic(k))}lookupDynamic(name){let v=lookup(this.dynBinds,name);return v??this.comps.getCompFor(this.it)?.lookup[name]?.val?.eval(this)??null}lookupBind(name){return lookup(this.binds,name)}lookupFieldRaw(name){return this.it[name]??null}lookupMethod(name){let fn=this.it[name];return fn instanceof Function?fn.call(this.it):null}lookupEvent(){return this.ctx?.event??null}lookupDragInfo(){return this.ctx?.dragInfo??null}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 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.defaultValue=defaultValue}isValid(v){return this.typeCheck(v)}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)}},CHECK_TYPE_ANY=_v=>!0,CHECK_TYPE_INT=Number.isInteger,CHECK_TYPE_FLOAT=Number.isFinite,CHECK_TYPE_BOOL=v=>typeof v=="boolean",CHECK_TYPE_STRING=v=>typeof v=="string",CHECK_TYPE_LIST=Array.isArray,CHECK_TYPE_OBJECT=isPlainObject,CHECK_TYPE_MAP=v=>v instanceof Map,CHECK_TYPE_SET=v=>v instanceof Set,COERCE_NONE=_v=>null,COERCE_BOOL=v=>!!v,COERCE_STRING=v=>v?.toString?.()??"",COERCE_INT=v=>Number.isFinite(v)?Math.trunc(v):null,COERCE_LIST=v=>Array.isArray(v)?[...v]:null,COERCE_OBJECT=v=>isPlainObject(v)?{...v}:null,COERCE_MAP=v=>v instanceof Map?new Map(v):Array.isArray(v)||isPlainObject(v)?new Map(Array.isArray(v)?v:Object.entries(v)):null,COERCE_SET=v=>v instanceof Set||Array.isArray(v)?new Set(v):null,FieldBool=class extends Field{constructor(name,defaultValue=!1){super("bool",name,CHECK_TYPE_BOOL,COERCE_BOOL,defaultValue)}},FieldAny=class extends Field{constructor(name,defaultValue=null){super("any",name,CHECK_TYPE_ANY,nullCoercer,defaultValue)}},FieldString=class extends Field{constructor(name,defaultValue=""){super("text",name,CHECK_TYPE_STRING,COERCE_STRING,defaultValue)}},FieldInt=class extends Field{constructor(name,defaultValue=0){super("int",name,CHECK_TYPE_INT,COERCE_INT,defaultValue)}},FieldFloat=class extends Field{constructor(name,defaultValue=0){super("float",name,CHECK_TYPE_FLOAT,COERCE_NONE,defaultValue)}},metaOf=v=>v?.constructor?.[COMPONENT]??v?.constructor?.getMetaClass?.(),getTypeName=v=>metaOf(v)?.name??null,FieldComp=class extends Field{constructor(type,name,args){super(type,name,v=>getTypeName(v)===type,nullCoercer,null),this.args=args}},FieldList=class extends Field{constructor(name,defaultValue=[]){super("list",name,CHECK_TYPE_LIST,COERCE_LIST,defaultValue)}},FieldObject=class extends Field{constructor(name,defaultValue={}){super("object",name,CHECK_TYPE_OBJECT,COERCE_OBJECT,defaultValue)}},FieldMap=class extends Field{constructor(name,defaultValue=new Map){super("map",name,CHECK_TYPE_MAP,COERCE_MAP,defaultValue)}},FieldSet=class extends Field{constructor(name,defaultValue=new Set){super("set",name,CHECK_TYPE_SET,COERCE_SET,defaultValue)}};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){this.name=name,this.fields={},this.compFields=new Set,this._methods={},this._statics={}}build(){let{name,fields,compFields,_methods}=this,defaults=Object.fromEntries(Object.entries(fields).map(([fieldName,field])=>[fieldName,field.defaultValue])),Class={[name]:class{constructor(values={}){Object.assign(this,defaults,values)}}}[name];Class[DRAFTABLE]=!0,Object.assign(Class.prototype,_methods);let metaClass={fields,name,methods:_methods};return Object.assign(Class,{getMetaClass:()=>metaClass,make(inArgs={},opts={}){let args={},scope=opts.scope??this[COMPONENT]?.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 freeze(new this(args),!0)}},this._statics),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,object:FieldObject,map:FieldMap,set:FieldSet,any:FieldAny};function fieldFromDescriptor(name,value){let FieldCls=fieldsByTypeName[value.type]??FieldAny,probe=new FieldCls(name);return[FieldCls,probe.coerceOr(value.defaultValue,probe.defaultValue)]}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(Array.isArray(value))b.addField(field,[...value],FieldList);else if(value instanceof Set)b.addField(field,new Set(value),FieldSet);else if(value instanceof Map)b.addField(field,new Map(value),FieldMap);else if(value?.type&&Object.hasOwn(value,"defaultValue")){let[FieldCls,dval]=fieldFromDescriptor(field,value);b.addField(field,dval,FieldCls)}else if(value?.component&&value?.args!==void 0)b.addCompField(field,value.component,value.args);else if(isPlainObject(value))b.addField(field,{...value},FieldObject);else{let FieldCls=value?.[FIELD_CLASS]??FieldAny;b.addField(field,value,FieldCls)}}return methods&&b.methods(methods),statics&&b.statics(statics),b.build()}function validateDraftFields(current2,draft){let meta=metaOf(current2);if(meta)for(let[name,field]of Object.entries(meta.fields)){let value=draft[name];if(field.isValid(value))continue;let coerced=field.coerceOr(value,BAD_VALUE);coerced!==BAD_VALUE?draft[name]=coerced:(console.warn(`invalid value for ${meta.name}.${name}`,value),draft[name]=current2[name])}}var META_KEYS="name id fields methods views receive intent alter provide provideType lookup spec extra commonStyle globalStyle scope _rawProvide _rawLookup".split(" "),RESERVED_COMPONENT_STATICS=new Set([...META_KEYS,"make","getMetaClass",...Object.getOwnPropertyNames(Component.prototype)]);function assertNoReservedComponentStatics(statics={}){for(let name in statics)if(RESERVED_COMPONENT_STATICS.has(name))throw new TypeError(`component static "${name}" is reserved by the framework`)}Component.fromSpec=opts=>{assertNoReservedComponentStatics(opts.statics);let Class=classFromData(opts.name,opts),comp=new Component(Class,opts),metaClass=Class.getMetaClass();comp.fields=metaClass.fields,comp.methods=metaClass.methods,Class.getMetaClass=()=>comp,Class[COMPONENT]=comp;for(let key of META_KEYS)Object.hasOwn(Class,key)||Object.defineProperty(Class,key,{get(){return comp[key]},set(v){comp[key]=v},configurable:!0});for(let key of Object.getOwnPropertyNames(Component.prototype))key!=="constructor"&&!Object.hasOwn(Class,key)&&(Class[key]=(...args)=>comp[key](...args));return Class};var component=opts=>Component.fromSpec(opts);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()})}},Transactor=class{constructor(comps,rootValue){this.comps=comps,this.transactions=[],this.state=new State(rootValue),this.onTransactionPushed=()=>{},this._observers=[],this.refusals=[],this._refusalObservers=[],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)}refuse(kind,info={}){let record={kind,info,timestamp:Date.now()};this.refusals.push(record),this.refusals.length>REFUSAL_RING_CAP&&this.refusals.shift(),console.warn(`tutuca refusal [${kind}]`,info);for(let cb of this._refusalObservers)cb(record);return record}observeRefusals(cb){return this._refusalObservers.push(cb),()=>{let i=this._refusalObservers.indexOf(cb);i!==-1&&this._refusalObservers.splice(i,1)}}_emitRecord(root,{kind,name,args,path,targetPath,handler,handlerName,matched,before,after,parent}){if(this._observers.length===0)return;let pinned=path.pinKeys(root);this._emit({kind,name,args:args??null,path:pinned,pathKeys:pinned.toKeys(),targetPath,handler:handler??null,handlerName:handlerName??(handler?.name||null),matched:matched??null,before,after,parent,timestamp:Date.now()})}_emitTransaction(transaction,root){this._observers.length!==0&&transaction._resolvedHandler!==void 0&&this._emitRecord(root,{kind:transaction.observeKind,name:transaction.observeName,args:transaction.args,path:transaction.getTransactionPath(),targetPath:transaction.targetPath??transaction.path,handler:transaction._resolvedHandler,matched:transaction._matched,before:transaction._before,after:transaction._after,parent:transaction.parentTransaction})}_link(child,parent){if(parent){let release=parent.completion.track();child.completion.whenSubtreeSettled().then(release)}return child}pushSend(path,name,args=[],parent=null,origin=null){let t=new SendEvent(path,this,name,args,parent);return t.origin=origin===null?null:origin.toTransactionPath().pinKeys(this.state.val),this.pushTransaction(t),this._link(t,parent)}pushIntent(path,name,args=[],opts={},parent=null){let release=parent?parent.completion.track():null,walk=new IntentWalk(this,path,name,args,opts,parent,release);return walk.advance(),walk}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])}}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.ensureWalkAdvanced?.(),transaction._completion?.ensureSelfSettled(),transaction._completion?.releaseSelf()}}transactInputNow(path,event,eventHandler,dragInfo){this.transact(new InputEvent(path,event,eventHandler,this,dragInfo))}};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()}afterTransaction(){}stop(){warnNotIntent("stop")}forward(_opts){console.warn('ctx.forward() needs a "receive" or "intent" handler - ignored')}get observeKind(){return null}get observeName(){return null}callHandler(root,instance,draft,comps){let[handler,args]=this.getHandlerAndArgs(root,instance,comps);return this._resolvedHandler=handler,handler.apply(instance,[draft,...args])}getHandlerAndArgs(_root,_instance,_comps){return null}getTransactionPath(){return this.path.toTransactionPath().compact()}run(curRoot,comps){let txnPath=this.getTransactionPath(),curLeaf=txnPath.lookup(curRoot),newLeaf=produce(curLeaf,draft=>{let result=this.callHandler(curRoot,curLeaf,draft,comps);return(result===void 0||result===draft)&&validateDraftFields(curLeaf,draft),result});return this._before=curLeaf,this._after=newLeaf,this._completion?.markSelfSettled({value:newLeaf,old:curLeaf}),curLeaf!==newLeaf?txnPath.setValue(curRoot,newLeaf):curRoot}},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"receive"}get observeName(){return this.e?.type??null}forward(opts){this._forward=opts??{}}afterTransaction(){let f=this._forward;if(f===void 0)return;this._forward=void 0;let{args=this._handlerArgs??[],...rest}=f,name=(this.handler?.handlerCall?.handlerVal??this.handler?.handlerVal)?.name;if(name===void 0){this.transactor.refuse("FORWARD_NO_NAME",{});return}this.transactor.pushIntent(this.dispatchPath,name,args,rest,this)}getHandlerAndArgs(root,_instance,comps){let stack=this.path.toTransactionPath().buildStack(Stack.root(comps,root,this)),[handler,args]=this.handler.getHandlerAndArgs(stack,this);this._handlerArgs=[...args];let path=this.dispatchPath;return args.push(new EventContext(path,this.transactor,this)),[handler,args]}get event(){return this.e}},NameArgsTransaction=class extends Transaction{constructor(path,transactor,name,args,parentTransaction){super(path,transactor,parentTransaction),this.name=name,this.args=args,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)]]}},SendEvent=class extends NameArgsTransaction{handlerProp="receive";get observeKind(){return this._isAnswer?"answer":"receive"}forward(opts){this._forward=opts??{}}afterTransaction(){let f=this._forward;if(f===void 0)return;this._forward=void 0;let{args=this.args,...rest}=f;this.transactor.pushIntent(this.path,this.name,args,rest,this)}},IntentEvent=class extends NameArgsTransaction{handlerProp="intent";constructor(path,transactor,walk){super(path,transactor,walk.name,walk.args,walk.parent),this.walk=walk,this.targetPath=walk.origin}forward(opts){this.walk.amend(opts,this.path)}stop(){this.walk.finish(null,null)}afterTransaction(){this.ensureWalkAdvanced()}ensureWalkAdvanced(){this._advanced||(this._advanced=!0,this.walk.advance())}},PASS=Symbol.for("tutuca.intent.pass"),REFUSAL_RING_CAP=200,INTENT_DEPTH=64,IntentWalk=class{constructor(transactor,path,name,args,opts,parent,release){this.transactor=transactor,this.name=name,this.args=args,this.route=opts?.route??DEFAULT_ROUTE,this.parent=parent,this.release=release,this.origin=path,this.answerPath=opts?.livePath?null:path.toTransactionPath().pinKeys(transactor.state.val),this.legIndex=0,this.dynAt=path,this.hops=0,this.ended=!1}advance(){if(!this.ended){if(this.hops++>=INTENT_DEPTH)return this.exhaust("intentDepth");for(;this.legIndex<this.route.length;){let leg=this.route[this.legIndex];if(leg==="dyn"){if(this.dynAt.steps.length===0){this.legIndex++;continue}this.dynAt=this.dynAt.popStep(),this.transactor.pushTransaction(new IntentEvent(this.dynAt,this.transactor,this));return}if(leg==="lex")return this.legIndex++,this._tryLex();console.warn("unknown intent route leg",leg,'- expected "dyn" or "lex"'),this.legIndex++}this.exhaust("noHandler")}}_tryLex(){let root=this.transactor.state.val,txnPath=this.origin.toTransactionPath(),leaf=txnPath.lookup(root),chain=this.transactor.comps.getIntentChainFor(leaf,this.name);if(this.transactor._emitRecord(root,{kind:"intent",name:this.name,args:this.args,path:txnPath,targetPath:this.origin,handler:chain[0],handlerName:chain[0]?.name||this.name,matched:chain.length>0?"exact":"none",before:leaf,after:void 0,parent:this.parent}),chain.length===0)return this.advance();let p=this._runLex(chain,0);this.transactor._inflight.add(p),p.finally(()=>this.transactor._inflight.delete(p))}async _runLex(chain,i){if(this.ended)return;if(i>=chain.length)return this.advance();let ctx=new Dispatcher(this.origin,this.transactor,this.parent);try{let res=await chain[i].apply(null,[...this.args,ctx]);if(res===PASS)return this._runLex(chain,i+1);this.answer("Ok",res)}catch(error){this.answer("Error",error)}}answer(suffix,value){this.finish(`${this.name}${suffix}`,[value])}amend(opts,from){opts?.args!==void 0&&(this.args=opts.args),opts?.route!==void 0&&(this.route=opts.route,this.legIndex=0,this.dynAt=from??this.dynAt)}exhaust(reason){if(this.ended)return;let{name,args}=this,comp=this.transactor.comps.getCompFor(this.origin.toTransactionPath().lookup(this.transactor.state.val)),declares=n=>comp?.receive?.[n]!==void 0;declares(`${name}Unhandled`)?this.finish(`${name}Unhandled`,args):declares(`${name}Error`)?this.finish(`${name}Error`,[reason]):(declares(`${name}Ok`)&&console.warn(`intent "${name}" was not answered (${reason}) and this component declares only "${name}Ok" - add "${name}Unhandled" or "${name}Error" to handle it`),this.finish(null,null))}finish(name,args){if(this.ended)return;if(this.ended=!0,name===null)return this.release?.();let path=this.answerPath??this.origin,t=new SendEvent(path,this.transactor,name,args,this.parent);t._isAnswer=!0,this.transactor.pushTransaction(t),this.release&&t.completion.whenSubtreeSettled().then(this.release)}},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)}_stack(){return this._stackMemo??=this.path.toTransactionPath().buildStack(Stack.root(this.transactor.comps,this.root,this.parent)),this._stackMemo}lookup(name,opts){return routeLookup(opts?.route??DEFAULT_ROUTE,()=>this._lookupLex(name),()=>this._stack()?.lookupDynamic(name)??null)}_lookupLex(name){let Comp=null;return this.walkPath(c=>(Comp=c,!1)),Comp?.scope?.lookupComponent(name)??null}lookupType(name,opts){let route=opts?.route??DEFAULT_ROUTE,v=this.lookup(name,{route});return v==null?(this.transactor.refuse("TYPE_NOT_FOUND",{name,route}),null):v?.[COMPONENT]==null?(this.transactor.refuse("TYPE_NOT_COMPONENT",{name,got:typeof v}),null):v}send(name,args){return this.sendAtPath(this.path,name,args)}sendAtPath(path,name,args){return this.transactor.pushSend(path,name,args,this.parent,this.path)}intent(name,args,opts){return this.intentAtPath(this.path,name,args,opts)}intentAtPath(path,name,args,opts){return this.transactor.pushIntent(path,name,args,opts,this.parent)}},EventContext=class extends Dispatcher{get name(){return this.parent?.name??null}get targetPath(){return this.parent.targetPath}reply(value){return this.parent.walk===void 0?warnNotIntent("reply"):this.parent.walk.answer("Ok",value)}fail(error){return this.parent.walk===void 0?warnNotIntent("fail"):this.parent.walk.answer("Error",error)}sendReply(name,args){let origin=this.parent?.origin??null;return origin==null?(this.transactor.refuse("NO_SENDER",{name}),null):this.sendAtPath(origin,name,args)}stop(){return this.parent.stop()}forward(opts){return this.parent.forward(opts)}};function warnNotIntent(verb){console.warn(`ctx.${verb}() is only meaningful in an "intent" handler - ignored`)}var PathChanges=class extends PathBuilder{constructor(dispatcher){super(),this.dispatcher=dispatcher}send(name,args){return this.dispatcher.sendAtPath(this.buildPath(),name,args)}intent(name,args,opts){return this.dispatcher.intentAtPath(this.buildPath(),name,args,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.fromNodeAndEventName(e.target,type,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,value=path.compact().toTransactionPath().lookup(rootValue),dragType=e.target.dataset.dragtype??"?",stack=path.toTransactionPath().buildStack(this.makeStack(rootValue));this.dragInfo=new DragInfo(stack,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 Stack.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()){let meta=Comp[COMPONENT];meta.compile(this.ParseContext);for(let key in meta.views)for(let name of meta.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){this.transactor.pushSend(new Path([]),name,args)}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(stack,val,type,node){this.stack=stack,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 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 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,renderOne=(key,value,attrName,binds)=>{let cachePath=enricher?[view,it,value]:[view,value],cacheKey=`${stack.viewsId??""}${nid}${key}`,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 walkLoopBindings({seq,it,filter,loopWith,enricher,ctx:makeLoopCtx(stack,filter)},renderOne),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])}};var OP_KINDS=["send","intent"];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 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);break;case"intent":dispatcher.intentAtPath(targetPath,op.name,args,op.opts);break}}}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{COMPONENT,FIELD_CLASS,PASS,ParseContext,SEQ_INFO,check,collectIterBindings,compileClassesToStyle,compileClassesToStyleText,component,css,dispatchPhase,html,injectCss,macro,phaseOps,resolveArgs,rootDispatcher,test,tutuca};