tutuca 0.15.0 → 1.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/CHANGELOG.md +132 -0
  2. package/LICENSE +1 -1
  3. package/README.md +64 -170
  4. package/{dist → deps}/immer.js +674 -249
  5. package/dist/tutuca.js +2342 -4057
  6. package/dist/tutuca.min.js +3 -3
  7. package/package.json +78 -96
  8. package/src/component.js +66 -0
  9. package/src/css/classes.js +77 -0
  10. package/src/dev/formatters.js +393 -0
  11. package/src/dev/jsonml.js +35 -0
  12. package/src/dev/panel.js +400 -0
  13. package/src/dev/summary.js +239 -0
  14. package/src/dev/vdom-formatters.js +102 -0
  15. package/src/drag.js +23 -0
  16. package/src/embed/element.js +111 -0
  17. package/src/env.js +30 -0
  18. package/src/events.js +85 -0
  19. package/src/history/bar.js +198 -0
  20. package/src/history/index.js +149 -0
  21. package/src/host.js +360 -0
  22. package/src/lint/index.js +470 -0
  23. package/src/meta.js +12 -0
  24. package/src/optimize.js +58 -0
  25. package/src/paths.js +205 -0
  26. package/src/playground/element.js +360 -0
  27. package/src/playground/index.js +5 -0
  28. package/src/playground/sources.js +107 -0
  29. package/src/playground/ui/playground.js +287 -0
  30. package/src/schema.js +460 -0
  31. package/src/scope.js +92 -0
  32. package/src/storybook/index.js +80 -0
  33. package/src/storybook/runner.js +452 -0
  34. package/src/storybook/stories.js +208 -0
  35. package/src/storybook/stress.js +76 -0
  36. package/src/storybook/ui/common.js +37 -0
  37. package/src/storybook/ui/link.js +80 -0
  38. package/src/storybook/ui/panels.js +32 -0
  39. package/src/storybook/ui/story-panel.js +432 -0
  40. package/src/storybook/ui/storybook.js +191 -0
  41. package/src/storybook/ui/stress-panel.js +231 -0
  42. package/src/sync/automerge.js +159 -0
  43. package/src/sync/codec.js +206 -0
  44. package/src/sync/diff.js +153 -0
  45. package/src/sync/index.js +97 -0
  46. package/src/sync/migrate.js +184 -0
  47. package/src/sync/ops.js +160 -0
  48. package/src/sync/remote.js +206 -0
  49. package/src/tag.js +24 -0
  50. package/src/tasks.js +244 -0
  51. package/src/test/driver.js +141 -0
  52. package/src/test/pbt.js +589 -0
  53. package/src/tutuca.js +66 -0
  54. package/src/vdom.js +349 -0
  55. package/src/view.js +354 -0
  56. package/src/walk.js +79 -0
  57. package/dist/chai.js +0 -4210
  58. package/dist/tutuca-cli.js +0 -16315
  59. package/dist/tutuca-components.js +0 -2232
  60. package/dist/tutuca-dev.ext.js +0 -8476
  61. package/dist/tutuca-dev.js +0 -13220
  62. package/dist/tutuca-dev.min.js +0 -5
  63. package/dist/tutuca-extra.ext.js +0 -4261
  64. package/dist/tutuca-extra.js +0 -4964
  65. package/dist/tutuca-extra.min.js +0 -3
  66. package/dist/tutuca-storybook.js +0 -970
  67. package/dist/tutuca.ext.js +0 -4183
  68. package/skill/margaui/SKILL.md +0 -105
  69. package/skill/margaui/components/accordion.md +0 -127
  70. package/skill/margaui/components/alert.md +0 -174
  71. package/skill/margaui/components/aura.md +0 -97
  72. package/skill/margaui/components/avatar.md +0 -220
  73. package/skill/margaui/components/badge.md +0 -193
  74. package/skill/margaui/components/breadcrumbs.md +0 -103
  75. package/skill/margaui/components/button.md +0 -322
  76. package/skill/margaui/components/calendar.md +0 -67
  77. package/skill/margaui/components/card.md +0 -373
  78. package/skill/margaui/components/carousel.md +0 -387
  79. package/skill/margaui/components/chat.md +0 -171
  80. package/skill/margaui/components/checkbox.md +0 -101
  81. package/skill/margaui/components/collapse.md +0 -172
  82. package/skill/margaui/components/countdown.md +0 -165
  83. package/skill/margaui/components/diff.md +0 -53
  84. package/skill/margaui/components/divider.md +0 -107
  85. package/skill/margaui/components/dock.md +0 -173
  86. package/skill/margaui/components/drawer.md +0 -184
  87. package/skill/margaui/components/dropdown.md +0 -388
  88. package/skill/margaui/components/fab.md +0 -346
  89. package/skill/margaui/components/fieldset.md +0 -88
  90. package/skill/margaui/components/file-input.md +0 -84
  91. package/skill/margaui/components/filter.md +0 -52
  92. package/skill/margaui/components/footer.md +0 -583
  93. package/skill/margaui/components/hero.md +0 -135
  94. package/skill/margaui/components/hover-3d.md +0 -129
  95. package/skill/margaui/components/hover-gallery.md +0 -49
  96. package/skill/margaui/components/indicator.md +0 -265
  97. package/skill/margaui/components/input.md +0 -389
  98. package/skill/margaui/components/join.md +0 -100
  99. package/skill/margaui/components/kbd.md +0 -127
  100. package/skill/margaui/components/label.md +0 -102
  101. package/skill/margaui/components/link.md +0 -96
  102. package/skill/margaui/components/list.md +0 -182
  103. package/skill/margaui/components/loading.md +0 -105
  104. package/skill/margaui/components/mask.md +0 -168
  105. package/skill/margaui/components/megamenu.md +0 -131
  106. package/skill/margaui/components/menu.md +0 -887
  107. package/skill/margaui/components/mockup-browser.md +0 -39
  108. package/skill/margaui/components/mockup-code.md +0 -81
  109. package/skill/margaui/components/mockup-phone.md +0 -39
  110. package/skill/margaui/components/mockup-window.md +0 -33
  111. package/skill/margaui/components/modal.md +0 -196
  112. package/skill/margaui/components/navbar.md +0 -282
  113. package/skill/margaui/components/otp.md +0 -171
  114. package/skill/margaui/components/pagination.md +0 -122
  115. package/skill/margaui/components/progress.md +0 -135
  116. package/skill/margaui/components/radial-progress.md +0 -67
  117. package/skill/margaui/components/radio.md +0 -133
  118. package/skill/margaui/components/range.md +0 -134
  119. package/skill/margaui/components/rating.md +0 -170
  120. package/skill/margaui/components/select.md +0 -225
  121. package/skill/margaui/components/skeleton.md +0 -64
  122. package/skill/margaui/components/stack.md +0 -142
  123. package/skill/margaui/components/stat.md +0 -254
  124. package/skill/margaui/components/status.md +0 -73
  125. package/skill/margaui/components/steps.md +0 -138
  126. package/skill/margaui/components/swap.md +0 -152
  127. package/skill/margaui/components/tab.md +0 -248
  128. package/skill/margaui/components/table.md +0 -1018
  129. package/skill/margaui/components/text-rotate.md +0 -91
  130. package/skill/margaui/components/textarea.md +0 -85
  131. package/skill/margaui/components/theme-controller.md +0 -266
  132. package/skill/margaui/components/timeline.md +0 -1356
  133. package/skill/margaui/components/toast.md +0 -165
  134. package/skill/margaui/components/toggle.md +0 -135
  135. package/skill/margaui/components/tooltip.md +0 -181
  136. package/skill/margaui/components/validator.md +0 -163
  137. package/skill/tutuca/SKILL.md +0 -56
  138. package/skill/tutuca/advanced.md +0 -292
  139. package/skill/tutuca/cli.md +0 -239
  140. package/skill/tutuca/component-design.md +0 -168
  141. package/skill/tutuca/core.md +0 -935
  142. package/skill/tutuca/iteration.md +0 -207
  143. package/skill/tutuca/macros.md +0 -86
  144. package/skill/tutuca/margaui.md +0 -175
  145. package/skill/tutuca/messages-and-intents.md +0 -414
  146. package/skill/tutuca/patterns/README.md +0 -48
  147. package/skill/tutuca/patterns/add-a-story.md +0 -26
  148. package/skill/tutuca/patterns/bind-text-and-attributes.md +0 -30
  149. package/skill/tutuca/patterns/conditional-attribute-value.md +0 -29
  150. package/skill/tutuca/patterns/coordinate-components.md +0 -54
  151. package/skill/tutuca/patterns/edit-through-a-dynamic-target.md +0 -32
  152. package/skill/tutuca/patterns/enrich-each-item.md +0 -25
  153. package/skill/tutuca/patterns/file-input.md +0 -39
  154. package/skill/tutuca/patterns/filter-a-list.md +0 -25
  155. package/skill/tutuca/patterns/filter-and-paginate.md +0 -60
  156. package/skill/tutuca/patterns/handle-events.md +0 -45
  157. package/skill/tutuca/patterns/iterate-a-list.md +0 -18
  158. package/skill/tutuca/patterns/paginate-a-list.md +0 -29
  159. package/skill/tutuca/patterns/render-a-child-component.md +0 -21
  160. package/skill/tutuca/patterns/reuse-markup-with-macros.md +0 -36
  161. package/skill/tutuca/patterns/share-state-across-the-tree.md +0 -53
  162. package/skill/tutuca/patterns/show-or-hide-content.md +0 -23
  163. package/skill/tutuca/patterns/switch-between-views.md +0 -30
  164. package/skill/tutuca/patterns/tabbed-interface.md +0 -43
  165. package/skill/tutuca/semantics.md +0 -219
  166. package/skill/tutuca/storybook.md +0 -270
  167. package/skill/tutuca/styles.md +0 -48
  168. package/skill/tutuca/testing.md +0 -345
  169. package/skill/tutuca-source/SKILL.md +0 -33
  170. package/skill/tutuca-source/tutuca.ext.js +0 -4183
@@ -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,path2){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,path2),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,path2,isSet2),useStrictIteration),maybeFreeze(rootScope,result,!1),path2&&rootScope.patches_&&getPlugin("Patches").generatePatches_(state,path2,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 path2=rootPath&&parentState&&parentState.type_!==3&&!has(parentState.assigned_,prop)?rootPath.concat(prop):void 0,res=finalize(rootScope,childValue,path2);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"),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)&&typeof value?.set=="function"?value.set(key,next):writeKey(value,key,next),Step=class{setDraftValue(_root,_v){}enterFrame(stack,next,renderPath){return stack.enter(next,{},!0,renderPath)}toAbstractPathStep(){return this}pinKey(_v){return this}toKey(){return null}},BindStep=class extends Step{constructor(binds){super(),this.binds=binds}lookup(v){return v}enterFrame(stack,next,renderPath){return stack.enter(next,{...this.binds},!1,renderPath)}toAbstractPathStep(){return null}},ScopeBindStep=class extends BindStep{constructor(val,binds={}){super(binds),this.val=val}enterFrame(stack,next,renderPath){let dyn=this.val.evalAsHandler(stack)?.call(stack.it)??{};return stack.enter(next,{...this.binds,...dyn},!1,renderPath)}},FieldStep=class extends Step{constructor(field){super(),this.field=field}lookup(v){return seqGet(v,this.field,NONE)}setDraftValue(root,v){writeKey(root,this.field,v)}toKey(){return{field:this.field}}},SeqStep=class extends Step{constructor(field,key){super(),this.field=field,this.key=key}lookup(v){return seqGet(seqGet(v,this.field,null),this.key,NONE)}setDraftValue(root,v){let seq=seqGet(root,this.field,null);seq!=null&&writeSeqKey(seq,this.key,v)}enterFrame(stack,next,renderPath){return stack.enter(next,{key:this.key},!0,renderPath)}toKey(){return{field:this.field,key:this.key}}},SeqAccessStep=class extends Step{constructor(seqField,keyField){super(),this.seqField=seqField,this.keyField=keyField}lookup(v){let seq=seqGet(v,this.seqField,NONE),key=seqGet(v,this.keyField,NONE);return key!==NONE&&seq!==NONE?seqGet(seq,key,NONE):NONE}setDraftValue(root,v){let seq=seqGet(root,this.seqField,NONE),key=seqGet(root,this.keyField,NONE);seq!==NONE&&key!==NONE&&writeSeqKey(seq,key,v)}pinKey(v){let key=seqGet(v,this.keyField,NONE);return key===NONE?this:new SeqStep(this.seqField,key)}toKey(){return{field:this.seqField}}},EachBindStep=class extends Step{constructor(eachNode,key){super(),this.eachNode=eachNode,this.key=key}lookup(v){return v}enterFrame(stack,next,renderPath){return stack.enter(next,this.eachNode.enrichBinds(stack,this.key),!1,renderPath)}toAbstractPathStep(){return null}},EachRenderItStep=class extends SeqStep{enterFrame(stack,next,renderPath){return stack.enter(next,{key:this.key,value:next},!1,renderPath).enter(next,{},!0,renderPath)}toAbstractPathStep(){return new SeqStep(this.field,this.key)}};function stepToJson(step){return step instanceof SeqStep?{f:step.field,k:step.key}:step instanceof FieldStep?{f:step.field}:step instanceof SeqAccessStep?{f:step.seqField,a:step.keyField}:null}function stepFromJson(j){return j==null||typeof j.f!="string"?null:j.k!==void 0?new SeqStep(j.f,j.k):j.a!==void 0?new SeqAccessStep(j.f,j.a):new FieldStep(j.f)}function pathToJson(path2){let out=[];for(let step of path2.steps){let j=stepToJson(step);if(j===null)return null;out.push(j)}return out}function pathFromJson(j){if(!Array.isArray(j))return null;let steps=[];for(let item of j){let step=stepFromJson(item);if(step===null)return null;steps.push(step)}return new Path(steps)}var Path=class _Path{constructor(steps=[]){this.steps=steps}concat(steps){return new _Path(this.steps.concat(steps))}compact(){let out=[];for(let step of this.steps){let s=step.toAbstractPathStep();s!==null&&out.push(s)}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),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),curVal===NONE)return dval;return curVal}resolveChain(root){let out=[root],curVal=root;for(let step of this.steps){if(curVal=step.lookup(curVal),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),parent===NONE)return;this.steps.at(-1).setDraftValue(parent,v)})}};function walkItems(stack,items,renderPath,path2){let prev=stack.it;for(let step of items){let next=step.lookup(prev);if(next===NONE)return console.warn("bad PathItem",{root:stack.it,step,path:path2}),null;renderPath=renderPath.pushItem(step),stack=step.enterFrame(stack,next,renderPath),prev=next}return[stack,renderPath]}var EMPTY_PATH=new Path([]),DispatchPath=class _DispatchPath{constructor(frames=[{base:EMPTY_PATH,items:[]}]){this.frames=frames}static ofSteps(steps){return new _DispatchPath([{base:EMPTY_PATH,items:steps.slice()}])}get top(){return this.frames[this.frames.length-1]}_withTopItems(items){let frames=this.frames.slice();return frames[frames.length-1]={base:this.top.base,items},new _DispatchPath(frames)}concat(steps){return this._withTopItems(this.top.items.concat(steps))}pushItem(step){return this.concat([step])}pushFrame(base){return new _DispatchPath(this.frames.concat({base,items:[]}))}canPop(){return this.frames.length>1||this.frames[0].items.length>0}popStep(){let{top}=this;return top.items.length>0?this._withTopItems(top.items.slice(0,-1)):this.frames.length>1?new _DispatchPath(this.frames.slice(0,-1)):this}compact(){return new _DispatchPath(this.frames.map(({base,items})=>({base,items:new Path(items).compact().steps})))}get addressKey(){return this._addressKey??=renderPathText(this.toTransactionPath().compact()),this._addressKey}toTransactionPath(){let{base,items}=this.top;return base.concat(items)}buildStack(stack){let renderPath=new _DispatchPath;for(let i=0;i<this.frames.length;i++){let{base,items}=this.frames[i];if(i>0||base.steps.length>0){let baseValue=base.lookup(stack.root,NONE);if(baseValue===NONE)return console.warn("bad frame base",{base,path:this}),null;renderPath=renderPath.pushFrame(base),stack=stack.enter(baseValue,{},!0,renderPath)}let walked=walkItems(stack,items,renderPath,this);if(walked===null)return null;[stack,renderPath]=walked}return stack}static fromNodeAndEventName(node,eventName,rootNode,comps,stopOnNoEvent=!0){let parts=[],bubbles=BUBBLING_EVENTS.has(eventName),eventIds=[],handlers=null,nodeRefs=[],isLeafComponent=!0,crossComponent=(cidNum,vid)=>{let comp=comps.getComponentForId(cidNum),pushPart=!0;if(handlers===null&&(isLeafComponent||bubbles))if(handlers=findHandlers(comp,eventIds,vid,eventName),handlers===null){if(isLeafComponent&&stopOnNoEvent&&!bubbles)return!1}else isLeafComponent||(parts.length=0,pushPart=!1);if(isLeafComponent=!1,pushPart){let part=resolvePathPart(comp,nodeRefs,vid);part&&parts.push(part)}return eventIds=[],nodeRefs=[],!0};for(;node&&node!==rootNode;){if(node?.dataset){let{eid,cid,vid,rp}=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;nodeRefs.push({nid:m.nid,base:pathFromJson(m.base)})}else nodeRefs.push({nid:m.nid,si:m.si,sk:m.sk});if(!sawComp&&cid!==void 0){if(!crossComponent(+cid,vid))return NO_EVENT_INFO;if(rp!==void 0){let base=parseRenderPath(rp);base!==null&&nodeRefs.push({base})}}}node=node.parentNode}parts.reverse();let path2=new _DispatchPath;for(let part of parts)path2=part.base!==void 0?path2.pushFrame(part.base):path2.pushItem(part.step);return[path2,handlers]}};function keyedPath(path2,key){let steps=path2.steps,last=steps[steps.length-1];return last instanceof SeqStep||last instanceof FieldStep?new Path(steps.slice(0,-1).concat(new SeqStep(last.field,key))):null}function renderPathText(path2){return JSON.stringify(pathToJson(path2))}function parseRenderPath(text){try{return pathFromJson(JSON.parse(text))}catch(err){return console.warn("bad render path",err,text),null}}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)}};function resolvePathPart(comp,nodeRefs,vid){for(let i=0;i<nodeRefs.length;i++){let ref=nodeRefs[i];if(ref.base!=null)return{base:ref.base};if(ref.nid===void 0||ref.nid===null)continue;let ctx=new StepCtx(comp,nodeRefs,i,vid),step=ctx.resolveNode()?.toPathStep(ctx)??null;if(step!==null)return{step}}return null}var NO_EVENT_INFO=[null,null],BUBBLING_EVENTS=new Set(["drop"]),path=()=>new PathBuilder,PathBuilder=class{constructor(){this.pathChanges=[]}toPath(){return new Path(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"),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)}var kindOf=val=>val?.kind??0,BaseVal=class{kind=0;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}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(" ")}`}},StrTplVal=class _StrTplVal extends BaseVal{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}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 BaseVal{kind=K_NAME;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{kind=K_EVENT;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(".")}`}},SigilNameVal=class extends BaseVal{constructor(name){super(),this.name=name}toString(){return this.sigil+this.name}},BindVal=class extends SigilNameVal{kind=K_BIND;sigil="@";eval(stack){return stack.lookupBind(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 SigilNameVal{kind=K_DYN;sigil="*";eval(stack){return stack.lookupDynamic(this.name)}},FieldVal=class extends SigilNameVal{kind=K_FIELD;sigil=".";eval(stack){return stack.lookupFieldRaw(this.name)}toPathItem(){return new FieldStep(this.name)}},MethodVal=class extends SigilNameVal{kind=K_METHOD;sigil="$";eval(stack){return stack.lookupMethod(this.name)}evalAsHandler(stack){return stack.lookupFieldRaw(this.name)}},SeqAccessVal=class extends BaseVal{kind=K_SEQ;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}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}var ITER_DIRECTIVES={when:"whenVal","loop-with":"loopWithVal","enrich-with":"enrichWithVal"},parseIterDirective=(px,name,s)=>parseDirectiveValue(px,name,s,parseAlterHandler);function parseIterationDirectives(attributes,px){let parseNamed=name=>{let attr=attributes.getNamedItem(`@${name}`);return attr?parseIterDirective(px,name,attr.value):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)}}parseBranch(slot,name,s){if(this.ifAttr===null)return this._orphan(name,s,"if");this.ifAttr[slot]=parseText(s,this.px)??NOT_SET_VAL}parseIter(name,s){let val=parseIterDirective(this.px,name,s);this.eachAttr!==null?this.eachAttr[ITER_DIRECTIVES[name]]=val:name==="enrich-with"?this.pushWrapper("scope",s,val):this._orphan(name,s,"each")}_orphan(name,value,needs){this.px.onParseIssue("orphan-directive",{name,value,needs})}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))}parseDirective(s,directiveName){switch(directiveName){case"dangerouslysetinnerhtml":this.attrs??=[],this.attrs.push(new RawHtmlAttr(parseDirectiveValue(this.px,directiveName,s,parseText))),this.hasDynamic=!0;return;case"push-view":this.pushWrapper("push-view",s,parseDirectiveValue(this.px,directiveName,s,parseText));return;case"text":this.textChild=parseDirectiveValue(this.px,directiveName,s,parseText);return;case"show":this.pushWrapper("show",s,parseDirectiveValue(this.px,directiveName,s,parseBool));return;case"hide":this.pushWrapper("hide",s,parseDirectiveValue(this.px,directiveName,s,parseBool));return;case"each":{let val=parseDirectiveValue(this.px,directiveName,s,parseSequence);this.eachAttr=this.pushWrapper("each",s,val);return}case"when":case"loop-with":case"enrich-with":this.parseIter(directiveName,s);return;case"then":this.parseBranch("thenVal",directiveName,s);return;case"else":this.parseBranch("elseVal",directiveName,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.parseBranch("thenVal",directiveName,s);else if(directiveName.startsWith("else."))this.parseBranch("elseVal",directiveName,s);else{let info={name:directiveName,value:s};this.px.onParseIssue("unknown-directive",info)}}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);return applyAttrs(node,attrs,()=>appendChildNodes(node,this.childs,cOpts)),node}};function applyAttrs(node,attrs,placeChildren){let hasValue="value"in attrs,hasChecked="checked"in attrs;if(hasValue||hasChecked){let{value:_v,checked:_c,...rest}=attrs;applyProperties(node,rest)}else applyProperties(node,attrs);placeChildren(),hasValue&&applyValueLast(node,attrs.value),hasChecked&&setProp(node,"checked",attrs.checked,isNamespaced(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),placeChildren=()=>{if(target.attrs.dangerouslySetInnerHTML)return;let ns=effectiveNs(target,opts);morphChildren(domNode,source.childs,target.childs,childOpts(target,ns,opts))};return propsDiff?applyAttrs(domNode,propsDiff,placeChildren):placeChildren(),!(propsDiff&&"value"in propsDiff)&&source.tag==="SELECT"&&target.attrs.value!==void 0&&applyValueLast(domNode,target.attrs.value),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 renderTarget(val,stack){if(val instanceof DynVal){let loc=stack.lookupDynamicLocated(val.name);return loc?.path==null?[loc?.value??null,stack.renderPath,null]:[loc.value,stack.renderPath.pushFrame(loc.path),loc.path]}let step=val.toPathItem?.()??null;if(step===null)return[val.eval(stack),stack.renderPath,null];let path2=stack.renderPath.pushItem(step);return[val.eval(stack),path2,stack.pendingFrame?path2.toTransactionPath():null]}var BaseNode=class{render(_stack,_rx){return null}setDataAttr(_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}},CommentNode=class extends TextNode{render(_stack,rx){return rx.renderComment(this.val)}};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(){let{childs}=this;for(let i=0;i<childs.length;i++)childs[i]=optimizeNode(childs[i])}},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);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 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.nodeType===3)return new TextNode(node.textContent);if(node.nodeType===8)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]=new AttrParser(px).parse(attrs,!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]=new AttrParser(px).parse(attrs);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}},RenderNode=class extends RenderViewId{render(stack,rx){let[value,renderPath,base]=renderTarget(this.val,stack),newStack=stack.enter(value,{},!0,renderPath,!1);return rx.renderIt(newStack,this,this.evalViewName(stack),base)}toPathStep(ctx){return this.val instanceof DynVal?null:super.toPathStep(ctx)}},RenderItNode=class extends RenderViewId{render(stack,rx){let base=stack.pendingFrame?stack.renderPath.toTransactionPath():null,newStack=stack.enter(stack.it,{},!0,stack.renderPath,!1);return rx.renderIt(newStack,this,this.evalViewName(stack),base)}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?null: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)}},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}render(stack,rx){return rx.renderEachWhen(stack,this)}evalIter(stack){let{whenVal,loopWithVal,enrichWithVal}=this.iterInfo;return{seq:this.val.eval(stack)??[],filter:whenVal?.evalAsHandler(stack)??filterAlwaysTrue,loopWith:loopWithVal?.evalAsHandler(stack)??nullLoopWith,enricher:enrichWithVal?.evalAsHandler(stack)??null}}enrichBinds(stack,key){let{seq,filter,loopWith,enricher}=this.evalIter(stack),ctx=makeLoopCtx(stack,filter);return bindsForKey({seq,it:stack.it,loopWith,enricher,ctx},key)}toPathStep(ctx){return ctx.hasKey?new EachBindStep(this,ctx.key):null}itemStep(key){return this.val instanceof FieldVal?new SeqStep(this.val.name,key):null}static register=!0},IterInfo=class{constructor(){this.whenVal=null,this.loopWithVal=null,this.enrichWithVal=null}};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{constructor(document2=globalThis.document){this.document=document2,this.nodes=[],this.events=[],this.macroNodes=[],this.parent=null,this.frame={},this.currentTag=null}isInsideMacro(name){return this.frame.macroName===name||this.parent?.isInsideMacro(name)}enterMacro(macroName,macroVars,macroSlots){let child=Object.create(Object.getPrototypeOf(this));return Object.assign(child,this,{frame:{macroName,macroVars,macroSlots},parent:this,currentTag:null})}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(),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=""){this.name=name,this.rawView=rawView,this.style=style,this.anode=null,this.ctx=null}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),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.name===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}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 STOP=Symbol("STOP"),NEXT=Symbol("NEXT"),DEFAULT_ROUTE=["dyn","lex"],isTypeName=s=>{let c=s.charCodeAt(0);return c>=65&&c<=90};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}},DynFrame=class{constructor(binds,types){this.binds=binds,this.types=types}lookup(name){let v=(isTypeName(name)?this.types:this.binds)[name];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(fields){Object.assign(this,fields)}_with(patch){return new _Stack({...this,...patch})}_pushProvides(){let comp=this.comps.getCompFor(this.it);if(comp==null)return this;let{provide,provideType}=comp,binds={},types={},has2=!1,base=this._publishBase();for(let k in provide){let step=provide[k].toPathItem?.()??null;if(step===null)continue;let value=provide[k].eval(this);binds[k]={value,path:base===null?null:base.concat([step])},has2=!0}for(let k in provideType)types[k]=provideType[k],has2=!0;return has2?this._with({dynBinds:[new DynFrame(binds,types),this.dynBinds]}):this}_publishBase(){let base=this.renderPath.toTransactionPath().compact();return base.lookup(this.root,NOT_FOUND)===this.it?base:null}static root(comps,it,ctx=null){return new _Stack({comps,root:it,it,binds:[new BindFrame(it,{},!0),null],dynBinds:[new DynFrame({},{}),null],views:["main",null],viewsId:"",renderPath:new DispatchPath,pendingFrame:!1,ctx})._pushProvides()}enter(it,bindings={},isFrame=!0,renderPath=this.renderPath,pendingFrame=null){let stack=this._with({it,binds:[new BindFrame(it,bindings,isFrame),this.binds],renderPath,pendingFrame:pendingFrame??(isFrame?!1:this.pendingFrame)});return isFrame?stack._pushProvides():stack}pushViewName(name){let views=[name,this.views];return this._with({views,viewsId:computeViewsId(views)})}_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))}lookupDynamicLocated(name){if(isTypeName(name))return null;let v=lookup(this.dynBinds,name);if(v!=null)return v;let comp=this.comps.getCompFor(this.it);if(comp==null)return null;let path2=comp.scope?.lookupPath?.(name)??null;if(path2!==null){let value2=path2.lookup(this.root,NOT_FOUND);if(value2!==NOT_FOUND)return{value:value2,path:path2}}let dval=comp.lookup[name]??null;if(dval===null)return null;let step=dval.toPathItem?.()??null,value=dval.eval(this);return step===null?{value,path:null}:{value,path:this.renderPath.toTransactionPath().concat([step])}}lookupDynamic(name){return isTypeName(name)?lookup(this.dynBinds,name):this.lookupDynamicLocated(name)?.value??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?.e??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]}},NOT_FOUND=Symbol("NOT_FOUND");var COMPONENT=Symbol.for("tutuca.component"),Components=class{constructor(){this.byId=new Map}registerComponent(Comp){this.byId.set(Comp.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.compileStyle());return styles.join(`
2
- `)}},ComponentStack=class _ComponentStack{constructor(comps=new Components,parent=null){this.comps=comps,this.parent=parent,this.byName={},this.intentsByName={},this.macros={},this.paths={}}enter(){return new _ComponentStack(this.comps,this)}registerComponents(comps,opts){let{aliases={},paths}=opts??{};paths&&this.registerPaths(paths);for(let i=0;i<comps.length;i++){let Comp=comps[i];Comp.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])}}registerPaths(paths){for(let name in paths){if(isTypeName(name)){console.warn("registerPaths: a type name has no path",name);continue}this.paths[name]=paths[name].toPath()}}lookupPath(name){return this.paths[name]??this.parent?.lookupPath(name)??null}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}hasProvider(name){for(let compName in this.byName)if(this.byName[compName].provide?.[name]!==void 0)return!0;return this.parent?.hasProvider(name)??!1}lookupMacro(name){return this.macros[name]??this.parent?.lookupMacro(name)??null}},isString=v=>typeof v=="string",_rawSpecKeys="name view style commonStyle globalStyle receive intent alter views provide lookup fields methods statics",KNOWN_SPEC_KEYS=new Set(_rawSpecKeys.split(" ")),_compId=0;function initComponent(Class,o){Class[COMPONENT]=Class,Class.id=_compId++,Class.views={main:new View("main",o.view,o.style)},Class.commonStyle=o.commonStyle??"",Class.globalStyle=o.globalStyle??"",Class.receive=o.receive??{},Class.intent=o.intent??{},Class.alter=o.alter??{};for(let name in o.views??{}){let v=o.views[name],{view,style}=isString(v)?{view:v}:v;Class.views[name]=new View(name,view,style)}Class._rawProvide=o.provide??{},Class._rawLookup=o.lookup??[],Class.provide={},Class.provideType={},Class.lookup={},Class.scope=null,Class.spec=o,Class.extra={};for(let key of Object.keys(o))KNOWN_SPEC_KEYS.has(key)||(Class.extra[key]=o[key]);return Object.assign(Class,COMPONENT_METHODS)}var COMPONENT_METHODS={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);continue}let val=parseProvide(this._rawProvide[key],ctx);val&&(this.provide[key]=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]=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,viewName){return this.getView(viewName).ctx.getEventForId(id)},getNodeForId(id,viewName){return this.getView(viewName).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 BAD_VALUE=Symbol("BadValue"),COERCE_NONE=_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,FIELD_TYPES={any:[_v=>!0,COERCE_NONE,()=>null],text:[v=>typeof v=="string",v=>v?.toString?.()??"",()=>""],int:[Number.isInteger,v=>Number.isFinite(v)?Math.trunc(v):null,()=>0],float:[Number.isFinite,COERCE_NONE,()=>0],bool:[v=>typeof v=="boolean",v=>!!v,()=>!1],list:[Array.isArray,v=>Array.isArray(v)?[...v]:null,()=>[]],object:[isPlainObject,v=>isPlainObject(v)?{...v}:null,()=>({})],map:[v=>v instanceof Map,COERCE_MAP,()=>new Map],set:[v=>v instanceof Set,v=>v instanceof Set||Array.isArray(v)?new Set(v):null,()=>new Set]},Field=class{constructor(type,name,defaultValue,[typeCheck,coercer,makeDefault]=FIELD_TYPES[type]){this.type=type,this.name=name,this.typeCheck=typeCheck,this.coercer=coercer,this.defaultValue=defaultValue===void 0?makeDefault():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)}},metaOf=v=>v?.constructor?.getMetaClass?.(),getTypeName=v=>metaOf(v)?.name??null,FieldComp=class extends Field{constructor(type,name,args){super(type,name,null,[v=>getTypeName(v)===type,COERCE_NONE,()=>null]),this.args=args}};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}function fieldFromSpec(name,value){let type=typeof value;if(type==="string")return new Field("text",name,value);if(type==="number")return new Field("float",name,value);if(type==="boolean")return new Field("bool",name,value);if(Array.isArray(value))return new Field("list",name,[...value]);if(value instanceof Set)return new Field("set",name,new Set(value));if(value instanceof Map)return new Field("map",name,new Map(value));if(value?.type&&Object.hasOwn(value,"defaultValue")){let t=value.type in FIELD_TYPES?value.type:"any",probe=new Field(t,name);return new Field(t,name,probe.coerceOr(value.defaultValue,probe.defaultValue))}return value?.component&&value?.args!==void 0?new FieldComp(value.component,name,value.args):isPlainObject(value)?new Field("object",name,{...value}):new Field("any",name,value)}function classFromData(name,{fields:spec={},methods={},statics={}}){let fields={};for(let key in spec)fields[key]=fieldFromSpec(key,spec[key]);let defaults=Object.fromEntries(Object.entries(fields).map(([key,field])=>[key,field.defaultValue])),Class={[name]:class{constructor(values={}){Object.assign(this,defaults,values)}}}[name];return Class[DRAFTABLE]=!0,Object.assign(Class.prototype,methods),Object.assign(Class,{fields,methods,getMetaClass:()=>Class,make(inArgs={},opts={}){let args={},scope=opts.scope??this.scope;for(let key in inArgs){let field=fields[key];field===void 0?console.warn("extra argument to constructor:",name,key,inArgs):field instanceof FieldComp?args[key]=mkCompField(field,scope,inArgs[key]):args[key]=field.coerceOrDefault(inArgs[key])}for(let key in fields)fields[key]instanceof FieldComp&&args[key]===void 0&&(args[key]=mkCompField(fields[key],scope,void 0));return freeze(new this(args),!0)}},statics),Class}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 RESERVED_COMPONENT_STATICS=new Set([..."name id fields methods views receive intent alter provide provideType lookup spec extra commonStyle globalStyle scope _rawProvide _rawLookup make getMetaClass".split(" "),...Object.keys(COMPONENT_METHODS)]);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`)}function component(opts){return assertNoReservedComponentStatics(opts.statics),initComponent(classFromData(opts.name??"UnkComp",opts),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 subscribe(this._observers,cb)}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 subscribe(this._refusalObservers,cb)}_emitRecord(root,{kind,name,args,path:path2,targetPath,handler,handlerName,matched,before,after,parent}){if(this._observers.length===0)return;let pinned=path2.pinKeys(root),record={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()};for(let cb of this._observers)cb(record)}_emitTransaction(transaction,root){this._observers.length!==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})}pushSend(path2,name,args=[],parent=null,origin=null,txnPath=null){let t=new SendEvent(path2,this,name,args,parent);return t.txnPath=txnPath,t.origin=origin,t.originPinned=origin===null?null:origin.toTransactionPath().pinKeys(this.state.val),this.pushTransaction(t),parent&&t.completion.carry(parent.completion.track()),t}pushIntent(path2,name,args=[],opts={},parent=null){let release=parent?parent.completion.track():null,walk=new IntentWalk(this,path2,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.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?.finish()}}transactInputNow(path2,event,eventHandler,dragInfo){this.transact(new InputEvent(path2,event,eventHandler,this,dragInfo))}};function nullHandler(){return this}function subscribe(list,cb){return list.push(cb),()=>{let i=list.indexOf(cb);i!==-1&&list.splice(i,1)}}function warnUnknownLeg(what,leg){return console.warn(`unknown ${what} route leg`,leg,'- expected "dyn" or "lex"'),null}var Transaction=class{constructor(path2,transactor,parentTransaction=null){this.path=path2,this.txnPath=null,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()}callHandler(root,instance,draft,comps){let[handler,args]=this.getHandlerAndArgs(root,instance,comps);return this._resolvedHandler=handler,handler.apply(instance,[draft,...args])}forward(opts){this._forward=opts??{}}afterTransaction(){let f=this._forward;if(f===void 0)return;this._forward=void 0;let name=this._forwardName();if(name===void 0){this.transactor.refuse("FORWARD_NO_NAME",{});return}let{args=this._forwardArgs(),...rest}=f;this.transactor.pushIntent(this._forwardPath(),name,args,rest,this)}getTransactionPath(){return this.txnPath??this.path.toTransactionPath()}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(path2,e,handler,transactor,dragInfo){super(path2,transactor),this.e=e,this.handler=handler,this.dragInfo=dragInfo,this._dispatchPath=null}get dispatchPath(){return this._dispatchPath??=this.path.compact(),this._dispatchPath}getTransactionPath(){return this.dispatchPath.toTransactionPath()}get observeKind(){return"receive"}get observeName(){return this.e?.type??null}_forwardName(){return(this.handler?.handlerCall?.handlerVal??this.handler?.handlerVal)?.name}_forwardArgs(){return this._handlerArgs??[]}_forwardPath(){return this.dispatchPath}getHandlerAndArgs(root,_instance,comps){let stack=this.path.buildStack(Stack.root(comps,root,this)),[handler,args]=this.handler.getHandlerAndArgs(stack,this);this._handlerArgs=[...args];let path2=this.dispatchPath;return args.push(new EventContext(path2,this.transactor,this)),[handler,args]}},NameArgsTransaction=class extends Transaction{constructor(path2,transactor,name,args,parentTransaction){super(path2,transactor,parentTransaction),this.name=name,this.args=args,this.targetPath=path2}handlerProp=null;get observeKind(){return this.handlerProp}get observeName(){return this.name}_forwardName(){return this.name}_forwardArgs(){return this.args}_forwardPath(){return this.path}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"}},IntentEvent=class extends NameArgsTransaction{handlerProp="intent";constructor(path2,transactor,walk){super(path2,transactor,walk.name,walk.args,walk.parent),this.walk=walk,this.targetPath=walk.origin}forward(opts){this.walk.amend(opts,this.path)}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,path2,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=path2,this.answerPath=opts?.livePath?null:path2.toTransactionPath().pinKeys(transactor.state.val),this.legIndex=0,this.dynAt=path2,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.canPop()){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();warnUnknownLeg("intent",leg),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 t=new SendEvent(this.origin,this.transactor,name,args,this.parent);t.txnPath=this.answerPath,t._isAnswer=!0,this.transactor.pushTransaction(t),this.release&&t.completion.carry(this.release)}},Completion=class{constructor(){this.val=void 0,this.selfSettled=!1,this.subtreeSettled=!1,this.pending=0,this._selfResolve=null,this._selfPromise=null,this._subtreeResolve=null,this._subtreePromise=null,this._releaseSelf=this.track()}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))}finish(){this.markSelfSettled(this.val),this._releaseSelf()}track(){this.pending++;let done=!1;return()=>{done||(done=!0,--this.pending===0&&(this.subtreeSettled=!0,this._subtreeResolve?.(this.val)))}}carry(release){this.whenSubtreeSettled().then(release)}},Dispatcher=class{constructor(path2,transactor,parentTransaction){this.path=path2,this.transactor=transactor,this.parent=parentTransaction,this.root=transactor.state.val}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.buildStack(Stack.root(this.transactor.comps,this.root,this.parent)),this._stackMemo}lookup(name,opts){for(let leg of opts?.route??DEFAULT_ROUTE){let v=leg==="dyn"?this._stack()?.lookupDynamic(name)??null:leg==="lex"?this._lookupLex(name):warnUnknownLeg("lookup",leg);if(v!=null)return v}return null}_lookupLex(name){let Comp=null;this.walkPath(c=>(Comp=c,!1));let scope=Comp?.scope;return scope==null?null:isTypeName(name)?scope.lookupComponent(name)??null:scope.lookupPath(name)?.lookup(this.root)??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(path2,name,args){return this.transactor.pushSend(path2,name,args,this.parent,this.path)}intent(name,args,opts){return this.intentAtPath(this.path,name,args,opts)}intentAtPath(path2,name,args,opts){return this.transactor.pushIntent(path2,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.transactor.pushSend(origin,name,args,this.parent,this.path,this.parent.originPinned)}stop(){return this.parent.walk===void 0?warnNotIntent("stop"):this.parent.walk.finish(null,null)}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 DispatchPath,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._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,comps,transactor}=this,[path2,handlers]=DispatchPath.fromNodeAndEventName(e.target,type,rootNode,comps,!isDrag);if(isDrag&&this._handleDragEvent(e,type,path2),path2!==null&&handlers!==null)for(let handler of handlers)transactor.transactInputNow(path2,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,path2){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=path2.compact().toTransactionPath().lookup(rootValue),dragType=e.target.dataset.dragtype??"?",stack=path2.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()){Comp.compile(this.ParseContext);for(let key in Comp.views)for(let name of Comp.views[key].ctx.genEventNames())this._eventNames.add(name)}this._compiled=!0}subscribeToEvents(eventNames){for(let name of eventNames)this.rootNode.addEventListener(name,this,listenerOpts(name))}recompileStyles(opts){injectCss("tutuca-app",this.comps.compileStyles(),opts?.head??document.head)}start(opts){this._compiled||this.compile(),this.subscribeToEvents(this._eventNames),this.onChange(info=>{info.val!==info.old&&this.render()}),this.recompileStyles(opts),opts?.noCache?this.renderer.setNullCache():this.startCacheEvictionInterval(),this.render()}stop(){this.stopCacheEvictionInterval(),clearTimeout(this._transactNextBatchId),this._transactNextBatchId=null;for(let name of this._eventNames)this.rootNode.removeEventListener(name,this,listenerOpts(name))}sendAtRoot(name,args){this.transactor.pushSend(new DispatchPath,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 isWeakKey=k=>k!==null&&(typeof k=="object"||typeof k=="function"),NullDomCache=class{get(_keys,_cacheKey){}set(_keys,_cacheKey,_v){}evict(){}},WeakMapDomCache=class{constructor(){this.keysByLen=new Map}get(keys,cacheKey){let len=keys.length,cur=this.keysByLen.get(len);if(cur){for(let i=0;i<len-1;i++)if(cur=cur.get(keys[i]),!cur)return;return 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))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})}evict(){this.keysByLen=new Map}};function stampRenderBase(vdom,text){return vdom instanceof VNode?new VNode(vdom.tag,{...vdom.attrs,"data-rp":text},vdom.childs,vdom.key,vdom.namespace):vdom instanceof VFragment?new VFragment(vdom.childs.map(c=>stampRenderBase(c,text))):vdom}var Renderer=class{constructor(comps){this.comps=comps,this.cache=new WeakMapDomCache}renderTag(tag,attrs,childs,namespace){return h(tag,attrs,childs,namespace)}renderFragment(childs){return new VFragment(childs)}renderComment(text){return new VComment(text)}setNullCache(){this.cache=new NullDomCache}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,viewName,base=null){let comp=this.comps.getCompFor(stack.it);return comp?this._rValComp(stack,stack.it,comp,node,"",viewName,base):null}_rValComp(stack,val,comp,node,key,viewName,base=null){let cacheKey=`${viewName??""}${stack.viewsId??""}${key}${stack.renderPath.addressKey}`,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 baseJson=base===null?null:pathToJson(base),meta=this._renderMetadata({$:"Comp",nid:node?.nodeId??null,cid:comp.id,vid:view.name,...baseJson===null?null:{base:baseJson}}),dom=new VFragment([meta,baseJson===null?body:stampRenderBase(body,JSON.stringify(baseJson))]);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,each2){let{val:seqVal,node:view,nodeId:nid}=each2,{seq,filter,loopWith,enricher}=each2.evalIter(stack),seqPath=seqVal instanceof DynVal?stack.lookupDynamicLocated(seqVal.name)?.path??null:null,r=[],it=stack.it,renderOne=(key,value,attrName,binds)=>{let itemBase=seqPath===null?null:keyedPath(seqPath,key),itemStep=itemBase===null?each2.itemStep(key):null,itemPath=itemBase!==null?stack.renderPath.pushFrame(itemBase):itemStep!==null?stack.renderPath.pushItem(itemStep):stack.renderPath,cachePath=enricher?[view,it,value]:[view,value],cacheKey=`${stack.viewsId??""}${nid}${key}${itemPath.addressKey}`,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,itemPath,itemBase!==null));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),devOnly=(name,result)=>(console.warn(`${name} is a no-op in the core tutuca build; import tutuca/dev for the real one`),result);function check(_app){return devOnly("check",{error:0,warn:0,hint:0})}async function test(_opts){return devOnly("test",null)}function collectIterBindings(){return devOnly("collectIterBindings",[])}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)}export{COMPONENT,PASS,ParseContext,SEQ_INFO,check,collectIterBindings,component,css,dispatchPhase,html,injectCss,macro,path,phaseOps,resolveArgs,rootDispatcher,test,tutuca};
1
+ /*! tutuca 1.0.0-beta.2 | MIT License | Copyright (c) 2025-2026 Mariano Guerra
2
+ * immer 11.1.21 | MIT License | Copyright (c) 2017 Michel Weststrate */
3
+ 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=isFunction(e)?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 O=Object,getPrototypeOf=O.getPrototypeOf,CONSTRUCTOR="constructor",PROTOTYPE="prototype",CONFIGURABLE="configurable",ENUMERABLE="enumerable",WRITABLE="writable",VALUE="value",isDraft=value=>!!value&&!!value[DRAFT_STATE];function isDraftable(value){return value?isPlainObject(value)||isArray(value)||!!value[DRAFTABLE]||!!value[CONSTRUCTOR]?.[DRAFTABLE]||isMap(value)||isSet(value):!1}var objectCtorString=O[PROTOTYPE][CONSTRUCTOR].toString(),cachedCtorStrings=new WeakMap;function isPlainObject(value){if(!value||!isObjectish(value))return!1;let proto=getPrototypeOf(value);if(proto===null||proto===O[PROTOTYPE])return!0;let Ctor=O.hasOwnProperty.call(proto,CONSTRUCTOR)&&proto[CONSTRUCTOR];if(Ctor===Object)return!0;if(!isFunction(Ctor))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):O.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_:isArray(thing)?1:isMap(thing)?2:isSet(thing)?3:0}var has=(thing,prop,type=getArchtype(thing))=>type===2?thing.has(prop):O[PROTOTYPE].hasOwnProperty.call(thing,prop),get=(thing,prop,type=getArchtype(thing))=>type===2?thing.get(prop):thing[prop],set=(thing,propOrOldValue,value,type=getArchtype(thing))=>{type===2?thing.set(propOrOldValue,value):type===3?thing.add(value):thing[propOrOldValue]=value};function is(x,y){return x===y?x!==0||1/x===1/y:x!==x&&y!==y}var isArray=Array.isArray,isMap=target=>target instanceof Map,isSet=target=>target instanceof Set,isObjectish=target=>typeof target=="object",isFunction=target=>typeof target=="function",isBoolean=target=>typeof target=="boolean";function isArrayIndex(value){let n=+value;return Number.isInteger(n)&&String(n)===value}var latest=state=>state.copy_||state.base_;var getFinalValue=state=>state.modified_?state.copy_:state.base_;function shallowCopy(base,strict){if(isMap(base))return new Map(base);if(isSet(base))return new Set(base);if(isArray(base))return Array[PROTOTYPE].slice.call(base);let isPlain=isPlainObject(base);if(strict===!0||strict==="class_only"&&!isPlain){let descriptors=O.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 O.create(getPrototypeOf(base),descriptors)}else{let proto=getPrototypeOf(base);if(proto!==null&&isPlain)return{...base};let obj=O.create(proto);return O.assign(obj,base)}}function freeze(obj,deep=!1){return isFrozen(obj)||isDraft(obj)||!isDraftable(obj)||(getArchtype(obj)>1&&O.defineProperties(obj,{set:dontMutateMethodOverride,add:dontMutateMethodOverride,clear:dontMutateMethodOverride,delete:dontMutateMethodOverride}),O.freeze(obj),deep&&each(obj,(_key,value)=>{freeze(value,!0)},!1)),obj}function dontMutateFrozenCollections(){die(2)}var dontMutateMethodOverride={[VALUE]:dontMutateFrozenCollections};function isFrozen(obj){return obj===null||!isObjectish(obj)?!0:O.isFrozen(obj)}var PluginMapSet="MapSet",PluginPatches="Patches",PluginArrayMethods="ArrayMethods",plugins={};function getPlugin(pluginKey){let plugin=plugins[pluginKey];return plugin||die(0,pluginKey),plugin}var isPluginLoaded=pluginKey=>!!plugins[pluginKey];var currentScope,getCurrentScope=()=>currentScope,createScope=(parent_,immer_)=>({drafts_:[],parent_,immer_,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:isPluginLoaded(PluginMapSet)?getPlugin(PluginMapSet):void 0,arrayMethodsPlugin_:isPluginLoaded(PluginArrayMethods)?getPlugin(PluginArrayMethods):void 0});function usePatchesInScope(scope2,patchListener){patchListener&&(scope2.patchPlugin_=getPlugin(PluginPatches),scope2.patches_=[],scope2.inversePatches_=[],scope2.patchListener_=patchListener)}function revokeScope(scope2){leaveScope(scope2),scope2.drafts_.forEach(revokeDraft),scope2.drafts_=null}function leaveScope(scope2){scope2===currentScope&&(currentScope=scope2.parent_)}var enterScope=immer2=>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,scope2){scope2.unfinalizedDrafts_=scope2.drafts_.length;let baseDraft=scope2.drafts_[0];if(result!==void 0&&result!==baseDraft){baseDraft[DRAFT_STATE].modified_&&(revokeScope(scope2),die(4)),isDraftable(result)&&(result=finalize(scope2,result));let{patchPlugin_}=scope2;patchPlugin_&&patchPlugin_.generateReplacementPatches_(baseDraft[DRAFT_STATE].base_,result,scope2)}else result=finalize(scope2,baseDraft);return maybeFreeze(scope2,result,!0),revokeScope(scope2),scope2.patches_&&scope2.patchListener_(scope2.patches_,scope2.inversePatches_),result!==NOTHING?result:void 0}function finalize(rootScope,value){if(isFrozen(value))return value;let state=value[DRAFT_STATE];if(!state)return handleValue(value,rootScope.handledSet_,rootScope);if(!isSameScope(state,rootScope))return value;if(!state.modified_)return state.base_;if(!state.finalized_){let{callbacks_}=state;if(callbacks_)for(;callbacks_.length>0;)callbacks_.pop()(rootScope);generatePatchesAndFinalize(state,rootScope)}return state.copy_}function maybeFreeze(scope2,value,deep=!1){!scope2.parent_&&scope2.immer_.autoFreeze_&&scope2.canAutoFreeze_&&freeze(value,deep)}function markStateFinalized(state){state.finalized_=!0,state.scope_.unfinalizedDrafts_--}var isSameScope=(state,rootScope)=>state.scope_===rootScope,EMPTY_LOCATIONS_RESULT=[];function updateDraftInParent(parent,draftValue,finalizedValue,originalKey){let parentCopy=latest(parent),parentType=parent.type_;if(originalKey!==void 0&&get(parentCopy,originalKey,parentType)===draftValue){set(parentCopy,originalKey,finalizedValue,parentType);return}if(!parent.draftLocations_){let draftLocations=parent.draftLocations_=new Map;each(parentCopy,(key,value)=>{if(isDraft(value)){let keys=draftLocations.get(value)||[];keys.push(key),draftLocations.set(value,keys)}})}let locations=parent.draftLocations_.get(draftValue)??EMPTY_LOCATIONS_RESULT;for(let location of locations)set(parentCopy,location,finalizedValue,parentType)}function registerChildFinalizationCallback(parent,child,key){parent.callbacks_.push(function(rootScope){let state=child;if(!state||!isSameScope(state,rootScope))return;rootScope.mapSetPlugin_?.fixSetContents(state);let finalizedValue=getFinalValue(state);updateDraftInParent(parent,state.draft_??state,finalizedValue,key),generatePatchesAndFinalize(state,rootScope)})}function generatePatchesAndFinalize(state,rootScope){if(state.modified_&&!state.finalized_&&(state.type_===3||state.type_===1&&state.allIndicesReassigned_||(state.assigned_?.size??0)>0)){let{patchPlugin_}=rootScope;if(patchPlugin_){let basePath=patchPlugin_.getPath(state);basePath&&patchPlugin_.generatePatches_(state,basePath,rootScope)}markStateFinalized(state)}}function handleCrossReference(target,key,value){let{scope_}=target;if(isDraft(value)){let state=value[DRAFT_STATE];isSameScope(state,scope_)&&state.callbacks_.push(function(){prepareCopy(target);let finalizedValue=getFinalValue(state);updateDraftInParent(target,value,finalizedValue,key)})}else isDraftable(value)&&target.callbacks_.push(function(){let targetCopy=latest(target);target.type_===3?targetCopy.has(value)&&handleValue(value,scope_.handledSet_,scope_):get(targetCopy,key,target.type_)===value&&scope_.drafts_.length>1&&(target.assigned_.get(key)??!1)===!0&&target.copy_&&handleValue(get(target.copy_,key,target.type_),scope_.handledSet_,scope_)})}function handleValue(target,handledSet,rootScope){return!rootScope.immer_.autoFreeze_&&rootScope.unfinalizedDrafts_<1||isDraft(target)||handledSet.has(target)||!isDraftable(target)||isFrozen(target)||(handledSet.add(target),each(target,(key,value)=>{if(isDraft(value)){let state=value[DRAFT_STATE];if(isSameScope(state,rootScope)){let updatedValue=getFinalValue(state);set(target,key,updatedValue,target.type_),markStateFinalized(state)}}else isDraftable(value)&&handleValue(value,handledSet,rootScope)})),target}function createProxyProxy(base,parent){let baseIsArray=isArray(base),state={type_:baseIsArray?1:0,scope_:parent?parent.scope_:getCurrentScope(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:parent,base_:base,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0},target=state,traps=objectTraps;baseIsArray&&(target=[state],traps=arrayTraps);let{revoke,proxy}=Proxy.revocable(target,traps);return state.draft_=proxy,state.revoke_=revoke,[proxy,state]}var objectTraps={get(state,prop){if(prop===DRAFT_STATE)return state;let arrayPlugin=state.scope_.arrayMethodsPlugin_,isArrayWithStringProp=state.type_===1&&typeof prop=="string";if(isArrayWithStringProp&&arrayPlugin?.isArrayOperationMethod(prop))return arrayPlugin.createMethodInterceptor(state,prop);let source=latest(state);if(!has(source,prop,state.type_))return readPropFromProto(state,source,prop);let value=source[prop];if(state.finalized_||!isDraftable(value)||isArrayWithStringProp&&state.operationMethod&&arrayPlugin?.isMutatingArrayMethod(state.operationMethod)&&isArrayIndex(prop))return value;if(value===peek(state.base_,prop)||isRelocatedBaseRef(state,prop,value)){prepareCopy(state);let childKey=state.type_===1?+prop:prop,childDraft=createProxy(state.scope_,value,state,childKey);return state.copy_[childKey]=childDraft}return 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_.delete(prop),!0;if(is(value,current2)&&(value!==void 0||has(state.base_,prop,state.type_)))return!0;prepareCopy(state),markChanged(state)}return state.copy_[prop]===value&&(value!==void 0||has(state.copy_,prop,state.type_))||Number.isNaN(value)&&Number.isNaN(state.copy_[prop])||(state.copy_[prop]=value,state.assigned_.set(prop,!0),handleCrossReference(state,prop,value)),!0},deleteProperty(state,prop){return prepareCopy(state),peek(state.base_,prop)!==void 0||prop in state.base_?(state.assigned_.set(prop,!1),markChanged(state)):state.assigned_.delete(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={};for(let key in objectTraps){let fn=objectTraps[key];arrayTraps[key]=function(){let args=arguments;return args[0]=args[0][0],fn.apply(this,args)}}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 isRelocatedBaseRef(state,prop,value){return state.type_!==1||!state.allIndicesReassigned_||state.assigned_?.get(prop)||!isDraftable(value)||value[DRAFT_STATE]?!1:state.baseRefs_.has(value)}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.assigned_=new Map,state.copy_=shallowCopy(state.base_,state.scope_.immer_.useStrictShallowCopy_))}var Immer2=class{constructor(config){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(base,recipe,patchListener)=>{if(isFunction(base)&&!isFunction(recipe)){let defaultBase=recipe;recipe=base;let self=this;return function(base2=defaultBase,...args){return self.produce(base2,draft=>recipe.call(this,draft,...args))}}isFunction(recipe)||die(6),patchListener!==void 0&&!isFunction(patchListener)&&die(7);let result;if(isDraftable(base)){let scope2=enterScope(this),proxy=createProxy(scope2,base,void 0),hasError=!0;try{result=recipe(proxy),hasError=!1}finally{hasError?revokeScope(scope2):leaveScope(scope2)}return usePatchesInScope(scope2,patchListener),processResult(result,scope2)}else if(!base||!isObjectish(base)){if(result=recipe(base),result===void 0&&(result=base),result===NOTHING&&(result=void 0),this.autoFreeze_&&freeze(result,!0),patchListener){let p=[],ip=[];getPlugin(PluginPatches).generateReplacementPatches_(base,result,{patches_:p,inversePatches_:ip}),patchListener(p,ip)}return result}else die(1,base)},this.produceWithPatches=(base,recipe)=>{if(isFunction(base))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]},isBoolean(config?.autoFreeze)&&this.setAutoFreeze(config.autoFreeze),isBoolean(config?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(config.useStrictShallowCopy),isBoolean(config?.useStrictIteration)&&this.setUseStrictIteration(config.useStrictIteration)}createDraft(base){isDraftable(base)||die(8),isDraft(base)&&(base=current(base));let scope2=enterScope(this),proxy=createProxy(scope2,base,void 0);return proxy[DRAFT_STATE].isManual_=!0,leaveScope(scope2),proxy}finishDraft(draft,patchListener){let state=draft&&draft[DRAFT_STATE];(!state||!state.isManual_)&&die(9);let{scope_:scope2}=state;return usePatchesInScope(scope2,patchListener),processResult(void 0,scope2)}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(PluginPatches).applyPatches_;return isDraft(base)?applyPatchesImpl(base,patches):this.produce(base,draft=>applyPatchesImpl(draft,patches))}};function createProxy(rootScope,value,parent,key){let[draft,state]=isMap(value)?getPlugin(PluginMapSet).proxyMap_(value,parent):isSet(value)?getPlugin(PluginMapSet).proxySet_(value,parent):createProxyProxy(value,parent);return(parent?.scope_??getCurrentScope()).drafts_.push(draft),state.callbacks_=parent?.callbacks_??[],state.key_=key,parent&&key!==void 0?registerChildFinalizationCallback(parent,state,key):state.callbacks_.push(function(rootScope2){rootScope2.mapSetPlugin_?.fixSetContents(state);let{patchPlugin_}=rootScope2;state.modified_&&patchPlugin_&&patchPlugin_.generatePatches_(state,[],rootScope2)}),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 _globalIterator=globalThis.Iterator,hasIteratorFrom=typeof _globalIterator?.from=="function";var immer=new Immer2,produce=immer.produce;var DROP_EVENTS=new Set(["dragenter","dragover","dragleave","drop"]),DRAG_EVENTS=["dragstart","dragend",...DROP_EVENTS],Drag=class{constructor(path,type,node,value){this.path=path,this.type=type,this.node=node,this.value=value}keyIn(receiver){return this.path.sourceKeyIn(receiver)}};var specSym=Symbol("TutucaSpec"),scopeSym=Symbol("TutucaScope"),idSym=Symbol("TutucaId"),specOf=v=>v?.[specSym],idOf=v=>v?.[idSym];function holds(fn){try{return!!fn()}catch{return!1}}var scopeOf=v=>v?.[scopeSym]??null,isComponent=v=>specOf(v)!==void 0,brokenInvariants=instance=>{let{invariants}=specOf(instance);return Object.keys(invariants).filter(name=>!holds(()=>invariants[name].call(instance)))},findInvalidFields=(value,prev,check={fields:!0,invariants:!0})=>collectInvalid(value,prev,check,[],[]),collectInvalid=(value,prev,check,issues,path)=>{if(value===prev||value===null||typeof value!="object")return issues;let prevAt=key=>prev!==null&&typeof prev=="object"?prev[key]:void 0;if(!isComponent(value)){for(let key of Object.keys(value))collectInvalid(value[key],prevAt(key),check,issues,[...path,key]);return issues}let{name:component2,fields}=specOf(value),scope2=scopeOf(value),report=(field2,reason)=>issues.push({path:[...path,field2],component:component2,field:field2,value:value[field2],reason});for(let field2 of check.fields?Object.keys(value):[])Object.hasOwn(fields,field2)||report(field2,"undeclared");for(let field2 in fields)check.fields&&!fields[field2].isValid(value[field2],scope2,value)&&report(field2,"invalid"),collectInvalid(value[field2],prevAt(field2),check,issues,[...path,field2]);for(let name of check.invariants?brokenInvariants(value):[])issues.push({path,component:component2,field:null,value,reason:`invariant:${name}`});return issues},lengthOf=v=>typeof v=="object"&&!Array.isArray(v)?Object.keys(v).length:v.length,CHECKS={int:v=>Number.isInteger(v),min:(v,min)=>v>=min,max:(v,max)=>v<=max,minLength:(v,n)=>lengthOf(v)>=n,maxLength:(v,n)=>lengthOf(v)<=n,pattern:(v,re)=>re.test(v),where:(v,preds)=>preds.every(({pred})=>pred(v))},NoDefaultError=class extends Error{},SYNC_LEVELS=["shared","local","none"],syncsAt=(type,level)=>SYNC_LEVELS.indexOf(type.syncLevel)<=SYNC_LEVELS.indexOf(level),AnyType=class{static kind="any";constructor(defaultValue){this.defaultValue=defaultValue,this.constraints={},this.generator=void 0,this.syncLevel="shared"}with(changes){return Object.assign(Object.create(Object.getPrototypeOf(this)),this,changes)}constrain(changes){return this.with({constraints:{...this.constraints,...changes}})}default(defaultValue){return this.with({defaultValue})}int(){return this.constrain({int:!0})}min(min){return this.constrain({min})}max(max){return this.constrain({max})}len(minLength,maxLength=1/0){return this.constrain({minLength,maxLength})}match(pattern){return this.constrain({pattern})}where(pred,name=pred.name){return this.constrain({where:[...this.constraints.where??[],{pred,name}]})}arb(generator){return this.with({generator})}sync(level){if(!SYNC_LEVELS.includes(level))throw new Error(`sync level must be one of ${SYNC_LEVELS.join(", ")}, got ${String(level)}`);return this.with({syncLevel:level})}children(){return[]}make(value,scope2,owner){if(this.isValid(value,scope2,owner))return value;let made=this.makeDefault(scope2,owner);if(!this.meetsConstraints(made))throw new NoDefaultError("has no default that meets its constraints");return made}makeDefault(_scope,_owner){let v=this.defaultValue;return typeof v=="function"?v():Array.isArray(v)?[...v]:v!==null&&typeof v=="object"?{...v}:v}isValid(value,scope2,owner){return value===void 0?!1:this.isValidValue(value,scope2,owner)&&this.meetsConstraints(value)}meetsConstraints(value){for(let key in this.constraints)if(!CHECKS[key](value,this.constraints[key]))return!1;return!0}isValidValue(_value,_scope,_owner){return!0}},StringType=class extends AnyType{static kind="string";constructor(defaultValue=""){super(defaultValue)}isValidValue(value){return typeof value=="string"}},BooleanType=class extends AnyType{static kind="boolean";constructor(defaultValue=!1){super(defaultValue)}isValidValue(value){return typeof value=="boolean"}},NumberType=class extends AnyType{static kind="number";constructor(defaultValue=0){super(defaultValue)}min(min){let type=super.min(min);return this.defaultValue<min?type.default(min):type}max(max){let type=super.max(max);return this.defaultValue>max?type.default(max):type}isValidValue(value){return Number.isFinite(value)}},EnumType=class extends AnyType{static kind="enum";constructor(...members){super(members[0]),this.members=members}isValidValue(value){return this.members.includes(value)}},OptionType=class extends AnyType{static kind="option";constructor(valueType){super(null),this.valueType=valueType}children(){return[this.valueType]}isValidValue(value,scope2,owner){return value===null||this.valueType.isValid(value,scope2,owner)}},ArrayType=class extends AnyType{static kind="array";constructor(valueType=new AnyType(null)){super([]),this.valueType=valueType}children(){return[this.valueType]}isValidValue(value,scope2){return Array.isArray(value)&&value.every(v=>this.valueType.isValid(v,scope2))}},isRecord=v=>typeof v=="object"&&v!==null&&!Array.isArray(v),MapType=class extends AnyType{static kind="map";constructor(valueType=new AnyType(null)){super({}),this.valueType=valueType}children(){return[this.valueType]}isValidValue(value,scope2){return isRecord(value)&&Object.values(value).every(v=>this.valueType.isValid(v,scope2))}},RecordType=class extends AnyType{static kind="record";constructor(shape){super(void 0),this.shape=shape}children(){return Object.values(this.shape)}makeDefault(scope2,owner){if(this.defaultValue!==void 0)return super.makeDefault(scope2,owner);let entries=Object.entries(this.shape).map(([k,type])=>{try{return[k,type.make(void 0,scope2)]}catch(error){let Wrapped=error instanceof NoDefaultError?NoDefaultError:Error;throw new Wrapped(`${k}: ${error.message}`,{cause:error})}});return Object.fromEntries(entries)}isValidValue(value,scope2){return!isRecord(value)||Object.keys(value).some(k=>!Object.hasOwn(this.shape,k))?!1:Object.entries(this.shape).every(([k,type])=>type.isValid(value[k],scope2))}},UnionType=class extends AnyType{static kind="oneOf";constructor(...types){super(void 0),this.types=types}children(){return this.types}makeDefault(scope2,owner){return this.defaultValue!==void 0?super.makeDefault(scope2,owner):this.types[0].make(void 0,scope2,owner)}isValidValue(value,scope2,owner){return this.types.some(type=>type.isValid(value,scope2,owner))}},IndexType=class extends AnyType{static kind="index";constructor(fieldName){super(void 0),this.fieldName=fieldName}keysIn(owner){let items=owner?.[this.fieldName];return Array.isArray(items)?items.map((_,i)=>i):isRecord(items)?Object.keys(items):[]}makeDefault(_scope,owner){let[first]=this.keysIn(owner);if(first===void 0)throw new NoDefaultError(`${this.fieldName} has no key for a required t.index(), use t.option`);return first}isValidValue(value,_scope,owner){return owner===void 0?Number.isInteger(value)||typeof value=="string":this.keysIn(owner).includes(value)}},ComponentType=class extends AnyType{static kind="component";constructor(names){super(void 0),this.names=names===void 0?[]:[names].flat()}get name(){return this.names[0]}makeDefault(scope2){if(this.name===void 0)throw new NoDefaultError("required t.component() has no default, pass a component or name it");if(scope2===null)throw new NoDefaultError(`no scope to make ${this.name} in, use scope.components to create it`);return scope2.make(this.name)}isValidValue(value,scope2){return isComponent(value)?this.names.length===0||scope2===null?!0:this.names.some(name=>scope2.lookupByName(name)===specOf(value)):!1}},unwrapOption=type=>type instanceof OptionType?unwrapOption(type.valueType):type,typeArgs=(t2,text)=>t2 instanceof EnumType?t2.members.map(text):t2 instanceof IndexType?[text(t2.fieldName)]:t2 instanceof ComponentType?t2.names.map(text):t2 instanceof RecordType?Object.entries(t2.shape).map(([k,v])=>`${k}: ${typeText(v)}`):t2.children().filter(c=>c.constructor!==AnyType).map(typeText),typeText=t2=>{if(t2 instanceof OptionType)return`${typeText(t2.valueType)}?`;let text=v=>v instanceof RegExp?String(v):JSON.stringify(v),args=typeArgs(t2,text),{where=[],...rest}=t2.constraints,constraints=Object.entries(rest).map(([k,v])=>v===!0?`.${k}()`:`.${k}(${text(v)})`);for(let{name}of where)constraints.push(`.where(${name})`);let sync=t2.syncLevel==="shared"?"":`.sync(${text(t2.syncLevel)})`,{defaultValue:d}=t2,value=d==null?"":typeof d=="function"?" = ƒ":` = ${text(d)}`;return`${t2.constructor.kind}${args.length>0?`(${args.join(", ")})`:""}${constraints.join("")}${sync}${value}`},ctor=Type=>(...args)=>new Type(...args),t={any:(defaultValue=null)=>new AnyType(defaultValue),string:ctor(StringType),boolean:ctor(BooleanType),number:ctor(NumberType),enum:ctor(EnumType),option:ctor(OptionType),array:ctor(ArrayType),map:ctor(MapType),record:ctor(RecordType),oneOf:ctor(UnionType),index:ctor(IndexType),component:ctor(ComponentType)},MessageSpec=class{constructor(name,entry){let spec=typeof entry=="function"?{run:entry}:entry,{run:run2,args,sourceKey:sourceKey2,pre,post,emits}=spec;Object.assign(this,{name,run:run2,args,sourceKey:sourceKey2,pre,post,emits})}},toMessages=on=>{let messages=Object.create(null);for(let key in on){let entry=on[key],isSpec=typeof entry=="function"||typeof entry=="object"&&entry!==null;messages[key]=isSpec?new MessageSpec(key,entry):entry}return messages},toAnswers=answers=>{let out=Object.create(null);for(let ask in answers){let outcomes=answers[ask];if(typeof outcomes!="object"||outcomes===null){out[ask]=outcomes;continue}out[ask]=Object.create(null);for(let outcome in outcomes){let entry=outcomes[outcome],isSpec=typeof entry=="function"||typeof entry=="object"&&entry!==null;out[ask][outcome]=isSpec?new MessageSpec(`${ask}.${outcome}`,entry):entry}}return out},messageIssues=(message,prev,next,args,info)=>{let issues=[],scope2=scopeOf(prev);message.args!==void 0&&(args.length!==message.args.length?issues.push("args"):message.args.forEach((type,i)=>{type.isValid(args[i],scope2,prev)||issues.push(`arg:${i}`)}));let{sourceKey:sourceKey2,emitted}=info;if(message.sourceKey!==void 0&&!message.sourceKey.isValid(sourceKey2,scope2,prev)&&issues.push("sourceKey"),message.pre!==void 0&&!holds(()=>message.pre.call(prev,prev,args,info))&&issues.push("pre"),message.post!==void 0&&!holds(()=>message.post.call(prev,prev,next,args,info))&&issues.push("post"),message.emits!==void 0)for(let{kind,name}of emitted)message.emits[kind]?.includes(name)||issues.push(`emits:${kind}:${name}`);return issues};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",VBase=class{},VText=class _VText extends VBase{constructor(text){super(),this.text=String(text)}isEqualTo(other){return other instanceof _VText&&this.text===other.text}},VComment=class _VComment extends VBase{constructor(text){super(),this.text=text}isEqualTo(other){return other instanceof _VComment&&this.text===other.text}},DYNAMIC_ONLY=new Set(["value","checked","is","dangerouslySetInnerHTML"]),Shape=class{constructor(tag2,namespace,attrs){if(namespace==null){let lower=tag2.toLowerCase();(lower==="svg"||lower==="math")&&(namespace=lower==="svg"?SVG_NS:MATH_NS,tag2=lower)}let staticAttrs={},names=[];for(let[name,isStatic,value]of attrs)isStatic&&!DYNAMIC_ONLY.has(name)?staticAttrs[name]=value:names.push(name);this.tag=tag2,this.namespace=typeof namespace=="string"?namespace:null,this.staticAttrs=staticAttrs,this.names=names,this.valueIdx=names.indexOf("value"),this.checkedIdx=names.indexOf("checked"),this.isIdx=names.indexOf("is"),this.htmlIdx=names.indexOf("dangerouslySetInnerHTML")}},VNode=class _VNode extends VBase{constructor(shape,values,childs,key){super(),this.shape=shape,this.values=values,this.childs=childs,this.key=key!=null?String(key):void 0}get tag(){return this.shape.tag}get namespace(){return this.shape.namespace}get attrs(){let attrs={...this.shape.staticAttrs};return this.shape.names.forEach((name,i)=>{attrs[name]=this.values[i]}),attrs}isSameKind(other){return this.shape===other.shape&&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;let a=this.values,b=other.values;for(let i=0;i<a.length;i++)if(a[i]!==b[i])return!1;return childsEqual(this.childs,other.childs)}},VFragment=class _VFragment extends VBase{constructor(childs,key){super(),this.key=key!=null?String(key):void 0,this.childs=childs}isEqualTo(other){return other instanceof _VFragment&&this.key===other.key&&childsEqual(this.childs,other.childs)}};function addChild(childs,child){if(child!=null)if(typeof child!="string"&&typeof child[Symbol.iterator]=="function")for(let c of child)addChild(childs,c);else child instanceof VBase?childs.push(child):childs.push(new VText(child))}var toVChilds=value=>{let childs=[];return addChild(childs,value),childs},getKey=child=>child.key;function childsEqual(a,b){if(a.length!==b.length)return!1;for(let i=0;i<a.length;i++)if(a[i]!==b[i]&&!a[i].isEqualTo(b[i]))return!1;return!0}var isNamespaced=node=>node.namespaceURI!==null&&node.namespaceURI!==HTML_NS,isForeignObject=tag2=>tag2.length===13&&tag2.toLowerCase()==="foreignobject",childNs=(shape,ns)=>ns===SVG_NS&&isForeignObject(shape.tag)?null:ns,NEVER_ASSIGN_STR="width height href list form tabIndex download rowSpan colSpan role popover",NEVER_ASSIGN=new Set(NEVER_ASSIGN_STR.split(" ")),PROP_ATTR_NAME={className:"class",htmlFor:"for"};function setProp(node,name,value,namespaced){if(name==="dangerouslySetInnerHTML"){if(value===void 0)node.replaceChildren();else{let html=value.__html??"";html!==node.innerHTML&&(node.innerHTML=html)}return}if(typeof value=="function")return;let usesProp=!namespaced&&!NEVER_ASSIGN.has(name)&&name in node;if(usesProp&&value!=null)try{node[name]=value;return}catch{}if(value==null||value===!1&&name[4]!=="-")if(usesProp){try{node[name]=""}catch{}node.removeAttribute(PROP_ATTR_NAME[name]??name)}else node.removeAttribute(name);else node.setAttribute(name,value)}function applyValueLast(node,value){node.tagName==="PROGRESS"&&(value==null||value===0)?node.removeAttribute("value"):setProp(node,"value",value,isNamespaced(node))}var owned=new WeakSet,own=node=>(owned.add(node),node),ownedChildNodes=parent=>Array.from(parent.childNodes).filter(n=>owned.has(n));function nextOwnedSibling(node){let next=node.nextSibling;for(;next!==null&&!owned.has(next);)next=next.nextSibling;return next}function toDom(vnode,doc,ns){if(vnode instanceof VFragment){let node2=doc.createDocumentFragment();return appendChildNodes(node2,vnode.childs,doc,ns),node2}if(vnode instanceof VText)return own(doc.createTextNode(vnode.text));if(vnode instanceof VComment)return own(doc.createComment(vnode.text));let{shape,values}=vnode,{names,staticAttrs,valueIdx,checkedIdx}=shape,elNs=shape.namespace??ns,is2=shape.isIdx===-1?null:values[shape.isIdx],createOpts=is2!=null?{is:is2}:void 0,node=elNs===null?doc.createElement(shape.tag,createOpts):doc.createElementNS(elNs,shape.tag,createOpts);own(node);let namespaced=isNamespaced(node);for(let name in staticAttrs)setProp(node,name,staticAttrs[name],namespaced);for(let i=0;i<names.length;i++)i!==valueIdx&&i!==checkedIdx&&setProp(node,names[i],values[i],namespaced);return appendChildNodes(node,vnode.childs,doc,childNs(shape,elNs)),valueIdx!==-1&&values[valueIdx]!==void 0&&applyValueLast(node,values[valueIdx]),checkedIdx!==-1&&values[checkedIdx]!==void 0&&setProp(node,"checked",values[checkedIdx],!1),node}function appendChildNodes(parent,childs,doc,ns){for(let child of childs)parent.appendChild(toDom(child,doc,ns))}function morphNode(domNode,source,target,doc,ns){if(source===target||source.isEqualTo(target))return domNode;if(source instanceof VText&&target instanceof VText||source instanceof VComment&&target instanceof VComment)return domNode.data=target.text,domNode;if(source instanceof VNode&&target instanceof VNode&&source.isSameKind(target)){let{shape}=target,{names,valueIdx,checkedIdx,htmlIdx}=shape,a=source.values,b=target.values,namespaced=isNamespaced(domNode);for(let i=0;i<names.length;i++)i!==valueIdx&&i!==checkedIdx&&a[i]!==b[i]&&setProp(domNode,names[i],b[i],namespaced);if(htmlIdx===-1||!b[htmlIdx]){let elNs=shape.namespace??ns;morphChildren(domNode,source.childs,target.childs,doc,childNs(shape,elNs))}if(valueIdx!==-1){let reselect=domNode.tagName==="SELECT"&&b[valueIdx]!==void 0;(a[valueIdx]!==b[valueIdx]||reselect)&&applyValueLast(domNode,b[valueIdx])}return checkedIdx!==-1&&a[checkedIdx]!==b[checkedIdx]&&setProp(domNode,"checked",b[checkedIdx],!1),domNode}let newNode=toDom(target,doc,ns);return domNode.parentNode.replaceChild(newNode,domNode),newNode}function domWidth(vnode){return vnode instanceof VFragment?vnode.childs.reduce((n,child)=>n+domWidth(child),0):1}function mountBefore(parent,vnode,doc,ns,before){let dom=toDom(vnode,doc,ns),nodes=vnode instanceof VFragment?Array.from(dom.childNodes):[dom];return parent.insertBefore(dom,before),nodes}function morphChildren(parentDom,oldChilds,newChilds,doc,ns,domNodes=ownedChildNodes(parentDom),before=null){let oldGroups=[],oldKeyMap=new Map,offset=0;for(let i=0;i<oldChilds.length;i++){let width=domWidth(oldChilds[i]);oldGroups.push(domNodes.slice(offset,offset+width)),offset+=width;let key=getKey(oldChilds[i]);if(key!=null){if(oldKeyMap.has(key))throw new Error(`Duplicate sibling key: ${key}`);oldKeyMap.set(key,i)}}let used=new Uint8Array(oldChilds.length),unkeyedCursor=0,matches=newChilds.map(child=>{let key=getKey(child),index=-1;if(key!=null){let previous=oldKeyMap.get(key);if(previous===-1||previous!==void 0&&used[previous])throw new Error(`Duplicate sibling key: ${key}`);index=previous??-1,previous===void 0&&oldKeyMap.set(key,-1)}else for(;unkeyedCursor<oldChilds.length;){let candidate=unkeyedCursor++;if(getKey(oldChilds[candidate])==null){index=candidate;break}}return index>=0&&(used[index]=1),index}),newGroups=new Array(newChilds.length);for(let j=newChilds.length-1;j>=0;j--){let target=newChilds[j],index=matches[j],source=oldChilds[index],oldNodes=oldGroups[index],nodes;if(source instanceof VFragment&&target instanceof VFragment)nodes=morphChildren(parentDom,source.childs,target.childs,doc,ns,oldNodes,before);else if(source&&!(source instanceof VFragment)&&!(target instanceof VFragment)){let node=morphNode(oldNodes[0],source,target,doc,ns);nextOwnedSibling(node)!==before&&parentDom.insertBefore(node,before),nodes=[node]}else if(nodes=mountBefore(parentDom,target,doc,ns,before),oldNodes)for(let node of oldNodes)parentDom.removeChild(node);newGroups[j]=nodes,nodes.length&&(before=nodes[0])}for(let i=0;i<oldChilds.length;i++)if(!used[i])for(let node of oldGroups[i])parentDom.removeChild(node);return newGroups.flat()}function render(doc,container,childs,prev){prev?morphChildren(container,prev,childs,doc,null):(container.replaceChildren(),appendChildNodes(container,childs,doc,null))}var META_CLOSE="§/§",META_END=new VComment(META_CLOSE),wrapMeta=(meta,node)=>[new VComment(`§${JSON.stringify(meta)}§`),node,META_END],isMetaOpen=text=>text.startsWith("§{")&&text.endsWith("§"),parseMeta=text=>JSON.parse(text.slice(1,-1));function isConstant(node){switch(node.constructor.kind){case"constant":return!0;case"element":return node.plan.constant;case"cond":return isConstant(node.source)&&isConstant(node.thenVal)&&isConstant(node.elseVal);default:return!1}}function planElement(node){let{tagName,attrs,childs,eid}=node,shapeAttrs=[],exprs=new Map,namespace=null,keyExpr=null;for(let[name,value]of attrs)if(name==="key")keyExpr=value;else if(name==="namespace"){if(!isConstant(value))throw new Error(`<${tagName}> namespace must be a constant`);namespace=value.eval(null)}else{let isStatic=isConstant(value);shapeAttrs.push([name,isStatic,isStatic?value.eval(null):void 0]),exprs.set(name,value)}eid!==null&&shapeAttrs.push(["data-eid",!0,eid]);let shape=new Shape(tagName,namespace,shapeAttrs),valueExprs=shape.names.map(name=>exprs.get(name)),constant=attrs.every(([,v])=>isConstant(v))&&childs.every(isConstant),prebuilt=childs.map(c=>isConstant(c)?toVChilds(c.eval(null)):null),vnode=constant?new VNode(shape,valueExprs.map(v=>v.eval(null)),prebuilt.flat(),keyExpr?.eval(null)):null;return{constant,shape,valueExprs,keyExpr,childs:prebuilt,vnode}}var jsonText=v=>{try{return JSON.stringify(v)??String(v)}catch{return String(v)}},keyText=key=>typeof key=="string"?`.${key}`:`[${jsonText(key)}]`,opText=op=>`.${op.name}${op.t==="item"?`[${jsonText(op.key)}]`:op.t==="seqItem"?`[${op.keyName}]`:""}`,UpdatePath=class _UpdatePath{constructor(keys=[]){this.keys=keys}getIn(root){let v=root;for(let key of this.keys)v=v?.[key];return v}setIn(root,v){if(this.keys.length===0)return v;let parent=new _UpdatePath(this.keys.slice(0,-1)).getIn(root);return parent[this.keys.at(-1)]=v,root}toString(){return this.keys.map(keyText).join("")||"·"}},Frame=class _Frame{constructor(keys,item=null,provider=null,isComponent2=!1){this.keys=keys,this.item=item,this.provider=provider,this.isComponent=isComponent2}get accessKeys(){return this.item===null?this.keys:[...this.keys,this.item]}asComponent(){return new _Frame(this.keys,this.item,this.provider,!0)}forItem(key){return new _Frame(this.accessKeys,key,this.provider,!1)}toMeta(){let{provider:p}=this;return{t:"frame",p:p===null?null:{v:p.name,d:p.depth,k:p.keys},k:this.keys,i:this.item}}static fromMeta({p,k,i}){let provider=p===null?null:{name:p.v,depth:p.d,keys:p.k};return new _Frame(k,i,provider)}toString(){return`${this.keys.map(keyText).join("")}${this.item===null?"":`[${jsonText(this.item)}]`}`}},frameText=frame=>JSON.stringify(frame.toMeta()),DispatchPath=class _DispatchPath{constructor(frames=[]){this.frames=frames}get isRootPath(){return this.frames.length===0}concat(frames){return new _DispatchPath([...this.frames,...frames])}toParentPath(){return new _DispatchPath(this.frames.slice(0,-1))}toComponentPath(){let end=this.frames.length;for(;end>0&&!this.frames[end-1].isComponent;)end--;return new _DispatchPath(this.frames.slice(0,end))}resolve(){let prefixes=[[]];for(let frame of this.frames){let{provider}=frame,start=provider===null?prefixes.at(-1):[...prefixes[provider.depth],...provider.keys];prefixes.push([...start,...frame.accessKeys])}return new UpdatePath(prefixes.at(-1))}toUpdatePath(){return this.toComponentPath().resolve()}toString(){return this.frames.join("")||"·"}startsWith(prefix){return prefix.frames.length>this.frames.length?!1:prefix.frames.every((f,i)=>frameText(f)===frameText(this.frames[i]))}sourceKeyIn(receiver){let i=receiver.frames.length;if(i>=this.frames.length||!this.startsWith(receiver))return null;for(;i<this.frames.length-1&&!this.frames[i].isComponent;)i++;return this.frames[i].item}},Selector=class{constructor(ops=[]){this.ops=ops}toString(){return this.ops.map(opText).join("")||"·"}freeze(value){let frames=[];for(let op of this.ops){let item=op.t==="item"?op.key:op.t==="seqItem"?value[op.keyName]:null,frame=new Frame([op.name],item??null,null,!0);frames.push(frame),value=new UpdatePath(frame.accessKeys).getIn(value)}return frames}},Target=class{constructor(base,selector=new Selector){this.base=base,this.selector=selector}freeze(root){return this.base.concat(this.selector.freeze(this.base.resolve().getIn(root)))}address(root){return Address.at(this.freeze(root),root)}},Address=class _Address{constructor(path,id,isHost=!1){this.path=path,this.updatePath=path.toUpdatePath(),this.id=id,this.isHost=isHost}static at(path,root){return new _Address(path,idOf(path.toUpdatePath().getIn(root)))}resolve(root){let instance=this.updatePath.getIn(root);if(!isComponent(instance))return{orphaned:!0};let found=idOf(instance);return found===this.id?{instance}:{stale:found}}ancestors(root){let hops=[];for(let p=this.path.toComponentPath();!p.isRootPath;)p=p.toParentPath().toComponentPath(),hops.push(_Address.at(p,root));return hops}toString(){return this.isHost?"host":`${this.updatePath}#${this.id}`}},HOST=new Address(new DispatchPath,void 0,!0),PathBuilder=class{constructor(){this.ops=[]}item(name,key){return this.add({t:"item",name,key})}field(name){return this.add({t:"field",name})}seqItem(name,keyName){return this.add({t:"seqItem",name,keyName})}add(op){return this.ops.push(op),this}},selectorFrom=(fn,self)=>{let pb=new PathBuilder;return fn.call(self,pb),new Selector(pb.ops)};var renderView=(instance,ctx,viewName)=>{let spec=specOf(instance),view=ctx.getBestViewFor(spec,viewName);return wrapMeta({t:"component"},view.eval(ctx.with({component:instance})))},AstNode=class{static kind="node";childNodes(){return[]}accept(walker){walker[this.constructor.kind](this)}},Field=class extends AstNode{static kind="field";constructor(name){super(),this.name=name}eval(ctx){return ctx.it[this.name]}toFrame(_ctx){return new Frame([this.name],null,null,!0)}},field=name=>new Field(name),SeqItem=class extends AstNode{static kind="seqItem";constructor(seqName,keyName){super(),this.seqName=seqName,this.keyName=keyName}eval(ctx){let key=ctx.it[this.keyName];return ctx.it[this.seqName][key]}toFrame(ctx){return new Frame([this.seqName],ctx.it[this.keyName]??null,null,!0)}},seqItem=(seqName,keyName)=>new SeqItem(seqName,keyName),Provided=class extends AstNode{static kind="provided";constructor(name){super(),this.name=name}eval(ctx){return ctx.dynBinds[this.name]?.value}toFrame(ctx){let{depth,keys}=ctx.dynBinds[this.name];return new Frame([],null,{name:this.name,depth,keys},!0)}},provided=name=>new Provided(name),nextEid=0,DomNode=class extends AstNode{static kind="element";constructor(tagName,attrs,childs,handlers){super(),this.tagName=tagName,this.attrs=attrs,this.childs=childs,this.handlers=handlers,this.eid=handlers.length>0?nextEid++:null,this.plan=planElement(this)}eval(ctx){let{shape,valueExprs,keyExpr,childs,vnode}=this.plan;if(vnode!==null)return vnode;let values=valueExprs.map(v=>v.eval(ctx)),vchilds=[];for(let i=0;i<this.childs.length;i++)addChild(vchilds,childs[i]??this.childs[i].eval(ctx));return new VNode(shape,values,vchilds,keyExpr?.eval(ctx))}childNodes(){return[...this.attrs.map(([,v])=>v),...this.childs,...this.handlers.map(h2=>h2.action)]}},h=(tagName,attrs,...childs)=>{let props=[],handlers=[];for(let key in attrs){let value=attrs[key];key.startsWith("on:")?handlers.push({name:key.slice(3),action:value}):props.push([key,toExpr(value)])}return new DomNode(tagName,props,childs.flat(1/0).map(toExpr),handlers)},Cond=class extends AstNode{static kind="cond";constructor(source,thenVal,elseVal){super(),this.source=source,this.thenVal=thenVal,this.elseVal=elseVal}eval(ctx){return(this.source.eval(ctx)?this.thenVal:this.elseVal).eval(ctx)}childNodes(){return[this.source,this.thenVal,this.elseVal]}},$if=(source,thenVal,elseVal)=>new Cond(toExpr(source),toExpr(thenVal),toExpr(elseVal)),Const=class extends AstNode{static kind="constant";constructor(value){super(),this.value=value}eval(_ctx){return this.value}},toExpr=v=>v instanceof AstNode?v:new Const(v),XRender=class extends AstNode{static kind="render";constructor(source,viewName){super(),this.source=source,this.viewName=viewName}eval(ctx){let child=this.source.eval(ctx),frame=this.source.toFrame(ctx);return wrapMeta(frame.toMeta(),renderView(child,ctx.enterFrame(child),this.viewName))}childNodes(){return[this.source]}},render2=(source,viewName)=>new XRender(toExpr(source),viewName),entriesOf=items=>Array.isArray(items)?items.entries():Object.entries(items);function*filteredEntries(self,filter,items,state){for(let entry of entriesOf(items))(filter===void 0||filter.call(self,entry[0],entry[1],state))&&(yield entry)}var XEach=class extends AstNode{static kind="each";constructor(source,child,loopName){super(),this.source=source,this.child=child,this.loopName=loopName}eval(ctx){let loop=this.loopName===void 0?{}:ctx.spec.loops[this.loopName],self=ctx.component,nodes=[],items=this.source.eval(ctx),state=loop.prepare===void 0?null:loop.prepare.call(self,items),entries=loop.iter?loop.iter.call(self,items,state):filteredEntries(self,loop.filter,items,state),sourceFrame=this.source.toFrame(ctx);for(let[key,value]of entries){let frame=sourceFrame.forItem(key),fragmentKey=loop.key===void 0?key:loop.key.call(self,key,value,state),base={value,key},binds=loop.enrich?{...loop.enrich.call(self,base,state),value,key}:base,dom=this.evalItem(ctx.enterFrame(value,binds),loop);nodes.push(new VFragment(toVChilds(wrapMeta(frame.toMeta(),dom)),fragmentKey))}return new VFragment(nodes)}evalItem(ctx,_loop){return this.child.eval(ctx)}childNodes(){return[this.source,this.child]}},each2=(source,child,loopName)=>new XEach(toExpr(source),toExpr(child),loopName),XRenderEach=class extends XEach{static kind="renderEach";constructor(source,loopName){super(source,null,loopName)}evalItem(ctx,loop){return renderView(ctx.it,ctx.forItemView(ctx.it),loop.view)}childNodes(){return[this.source]}},renderEach=(source,loopName)=>new XRenderEach(toExpr(source),loopName),XRenderIt=class extends AstNode{static kind="renderIt";constructor(viewName){super(),this.viewName=viewName}eval(ctx){let it=ctx.lookupBind("value");return renderView(it,ctx.forItemView(it),this.viewName)}},renderIt=viewName=>new XRenderIt(viewName),XScope=class extends AstNode{static kind="scope";constructor(scopeName,child){super(),this.scopeName=scopeName,this.child=child}eval(ctx){let{bind}=ctx.spec.scopes[this.scopeName],{value:_value,...binds}=bind.call(ctx.component);return this.child.eval(ctx.enterScope(binds))}childNodes(){return[this.child]}},scope=(scopeName,child)=>new XScope(scopeName,toExpr(child)),XPushView=class extends AstNode{static kind="pushView";constructor(viewNameVal,child){super(),this.viewNameVal=viewNameVal,this.child=child}eval(ctx){let viewName=this.viewNameVal.eval(ctx);return this.child.eval(ctx.pushView(viewName))}childNodes(){return[this.viewNameVal,this.child]}},pushView=(source,child)=>new XPushView(toExpr(source),toExpr(child)),Send=class extends AstNode{static kind="action";constructor(name,args){super(),this.name=name,this.args=args}childNodes(){return this.args}},send=(name,...args)=>new Send(name,args.map(toExpr)),TargetValue=class extends AstNode{static kind="targetValue";eval(ctx){let target=ctx.node??ctx.event.target;return target.type==="checkbox"?target.checked:target.value}},targetValue=()=>new TargetValue,SourceKey=class extends AstNode{static kind="sourceKey";eval(ctx){return ctx.sourceKey}},sourceKey=()=>new SourceKey,DragKey=class extends AstNode{static kind="dragKey";eval(ctx){return ctx.drag?.keyIn(ctx.path)??null}},dragKey=()=>new DragKey,LookupBindName=class extends AstNode{static kind="lookupBind";constructor(name){super(),this.name=name}eval(ctx){return ctx.lookupBind(this.name)}},lookupBind=name=>new LookupBindName(name),RenderContext=class _RenderContext{constructor({it,binds,dynBinds,viewStack,depth,component:component2}){this.it=it,this.component=component2,this.binds=binds,this.dynBinds=dynBinds,this.viewStack=viewStack,this.depth=depth}get spec(){return specOf(this.component)}static root(component2){let empty={it:null,binds:{},dynBinds:{},viewStack:[],depth:-1};return new _RenderContext({...empty,component:component2}).enterFrame(component2)}with(changes){return new _RenderContext({...this,...changes})}enterFrame(it,binds={}){let depth=this.depth+1;return this.with({it,binds,dynBinds:this.mergeDynBinds(it,depth),depth})}forItemView(it){return this.with({it,binds:{}})}enterScope(scopeBinds){return this.with({binds:{...this.binds,...scopeBinds}})}pushView(viewName){return this.with({viewStack:[viewName,...this.viewStack]})}mergeDynBinds(it,depth){if(!isComponent(it))return this.dynBinds;let{provides}=specOf(it),newDynBinds={...this.dynBinds};for(let key in provides){let suffix=new DispatchPath(selectorFrom(provides[key],it).freeze(it)).resolve();newDynBinds[key]={value:suffix.getIn(it),depth,keys:suffix.keys}}return newDynBinds}lookupBind(name){return this.binds[name]??null}getBestViewFor(spec,viewName){let candidates=viewName===void 0?this.viewStack:[viewName,...this.viewStack];for(let name of candidates){let view=spec.views[name];if(view!==void 0)return view}return spec.views.main}};var Walker=class{visit(node){node.accept(this)}node(node){for(let c of node.childNodes())this.visit(c)}field(node){this.node(node)}seqItem(node){this.node(node)}provided(node){this.node(node)}constant(node){this.node(node)}targetValue(node){this.node(node)}sourceKey(node){this.node(node)}dragKey(node){this.node(node)}lookupBind(node){this.node(node)}render(node){this.node(node)}renderIt(node){this.render(node)}cond(node){this.node(node)}pushView(node){this.node(node)}each(node){this.node(node)}renderEach(node){this.each(node)}scope(node){this.node(node)}action(node){this.node(node)}element(node){for(let[name,value]of node.attrs)this.attr(node,name,value);for(let c of node.childs)this.child(node,c);for(let h2 of node.handlers)this.handler(node,h2)}attr(_node,_name,value){this.visit(value)}child(_node,child){this.visit(child)}handler(_node,handler){this.visit(handler.action)}},Collect=class extends Walker{eventHandlers=new Map;element(node){node.eid!==null&&this.eventHandlers.set(node.eid,node.handlers),super.element(node)}handler(_node,_handler){}};var nextId=1,ComponentSpec=class{constructor({name,fields,methods,views,on,answers,loops,scopes,provides,invariants}){this.name=name,this.fields=fields,this.methods=methods,this.proto=Object.create(null,Object.getOwnPropertyDescriptors(methods)),Object.assign(this.proto,{[DRAFTABLE]:!0,[specSym]:this}),this.views=views,this.on=on,this.answers=answers,this.loops=loops,this.scopes=scopes,this.provides=provides,this.invariants=invariants;let collect=new Collect;for(let key in views)collect.visit(views[key]);if(this.eventHandlers=collect.eventHandlers,this.eventNames=new Set([...this.eventHandlers.values()].flat().map(h2=>h2.name)),this.eventNames.has("drop"))for(let name2 of DRAG_EVENTS)this.eventNames.add(name2)}make(args={},scope2=null){let state=Object.create(this.proto);state[idSym]=nextId++,scope2!==null&&(state[scopeSym]=scope2);for(let key in this.fields)try{state[key]=this.fields[key].make(args[key],scope2,state)}catch(error){let Wrapped=error instanceof NoDefaultError?NoDefaultError:Error;throw new Wrapped(`${this.name}.${key}: ${error.message}`,{cause:error})}return state}},ownEntries=record=>Object.assign(Object.create(null),record),component=opts=>{let{name,fields={},methods={},view,views={}}=opts,sources=view===void 0?views:{...views,main:view},exprs=ownEntries({});for(let key in sources)exprs[key]=toExpr(sources[key]);if(!("main"in exprs))throw new Error(`Component ${name} has no main view`);return new ComponentSpec({name,fields,methods,views:exprs,on:toMessages(opts.on),answers:toAnswers(opts.answers),loops:ownEntries(opts.loops),scopes:ownEntries(opts.scopes),provides:ownEntries(opts.provides),invariants:ownEntries(opts.invariants)})};var browserEnv={now:()=>Date.now(),random:()=>Math.random(),uuid:()=>globalThis.crypto.randomUUID()},testEnv=({seed=1,start=Date.UTC(2026,0,1)}={})=>{let time=start,state=seed>>>0,ids=0;return{now:()=>time,advance(ms){time+=ms},random(){state=state+1831565813>>>0;let x=state;return x=Math.imul(x^x>>>15,x|1),x^=x+Math.imul(x^x>>>7,x|61),((x^x>>>14)>>>0)/4294967296},uuid:()=>`00000000-0000-4000-8000-${(++ids).toString(16).padStart(12,"0")}`}};var META_TYPES=new Set(["component","frame"]);function*enclosingNodeMeta(node){let closed=0;for(let n=node.previousSibling;n;n=n.previousSibling){if(n.nodeType!==8)continue;let data=n.data;if(data===META_CLOSE){closed++;continue}if(!isMetaOpen(data))continue;if(closed>0){closed--;continue}let meta;try{meta=parseMeta(data)}catch(err){console.error("bad meta comment",err,n,node);continue}META_TYPES.has(meta?.t)&&(yield meta)}}var walkUp=(node,rootNode)=>{let metas=[],components=[],eids=[];for(;node&&node!==rootNode;){let eid=node.getAttribute?.("data-eid");eid!=null&&eids.push({eid:parseInt(eid,10),node,level:components.length});for(let meta of enclosingNodeMeta(node))meta.t==="component"&&components.push(metas.length),metas.push(meta);node=node.parentNode}return node===rootNode?{metas,components,eids}:null},pathFrom=metas=>{let frames=[];for(let meta of[...metas].reverse())meta.t==="frame"?frames.push(Frame.fromMeta(meta)):frames.length>0&&frames.push(frames.pop().asComponent());return new DispatchPath(frames)},pathOf=(node,rootNode)=>{let walk=walkUp(node,rootNode);return walk===null||walk.components.length===0?null:pathFrom(walk.metas)},getEventInfoFor=(target,type,rootNode,rootComponent,bubbles=!1)=>{let walk=walkUp(target,rootNode);if(walk===null)return null;let levels=bubbles?walk.components.length:Math.min(1,walk.components.length);for(let level=0;level<levels;level++){let eids=walk.eids.filter(e=>e.level===level);if(eids.length===0)continue;let start=level===0?0:walk.components[level-1]+1,to=Address.at(pathFrom(walk.metas.slice(start)),rootComponent),{eventHandlers}=specOf(to.updatePath.getIn(rootComponent));for(let{eid,node}of eids)for(let handler of eventHandlers.get(eid)??[])if(handler.name===type)return{handler,to,node}}return null};var Scope=class _Scope{constructor(onRegister,parent=null,name=null){this.onRegister=onRegister,this.parent=parent,this.name=name,this.path=parent===null?[]:[...parent.path,name],this.children=Object.create(null),this.byName=Object.create(null),this.askHandlers=Object.create(null),this.components=new Proxy(Object.create(null),{get:(_target,name2)=>this.factory(name2)})}enter(name){if(typeof name!="string"||name===""||name.includes("/"))throw new Error(`scope.enter needs a name without "/", got ${String(name)}`);return this.children[name]??=new _Scope(this.onRegister,this,name),this.children[name]}refFor(spec){for(let s=this;s!==null;s=s.parent)for(let name in s.byName)if(s.byName[name]===spec&&this.lookupByName(name)===spec)return[...this.path,name].join("/");throw new Error(`Component ${spec.name} is not registered in scope /${this.path.join("/")}`)}resolveRef(ref){let keys=ref.split("/"),name=keys.pop(),scope2=this;for(let key of keys)if(scope2=scope2.children[key],scope2===void 0)throw new Error(`No scope ${keys.join("/")} for ${ref}`);return{scope:scope2,name}}register(comps){let factories={};for(let name in comps){let spec=comps[name];this.byName[name]=spec,this.onRegister(spec,name),factories[name]=this.factory(name)}return factories}factory(name){return args=>this.make(name,args)}lookup(getter){let scope2=this;for(;scope2!==null;){let v=getter(scope2);if(v!==void 0)return v;scope2=scope2.parent}return null}registerAskHandlers(handlers){Object.assign(this.askHandlers,handlers)}lookupAskHandler(name){return this.lookup(scope2=>scope2.askHandlers[name])}lookupByName(name){return this.lookup(scope2=>scope2.byName[name])}allSpecs(){let specs={};for(let s=this;s!==null;s=s.parent)for(let name in s.byName)specs[name]??=s.byName[name];return specs}make(name,args){let spec=this.lookupByName(name);if(spec===null)throw new Error(`Component ${String(name)} is not registered`);return spec.make(args,this)}};var call=(message,instance,next,args,ctx)=>{ctx.handled={message,args},ctx.emitted=[];let result=message.run.call(instance,next,args,ctx);return result===void 0?next:result},unhandled=(ctx,name,instance)=>{console.warn("handler",name,"not found on",instance,{ctx}),ctx.unhandled.push(name)},run=(instance,next,handlerName,args,ctx)=>{let handler=specOf(instance).on[handlerName];return handler!==void 0?call(handler,instance,next,args,ctx):(unhandled(ctx,handlerName,instance),next)},requests=0,defaultNextRequest=()=>++requests,MessageContext=class{constructor(task,env,scope2,nextRequest=defaultNextRequest){this.task=task,this.env=env,this.nextRequest=nextRequest,this.request=task.request??null,this.scope=scope2,this.path=task.to.path.toComponentPath(),this.address=new Address(this.path,task.to.id),this.tasks=[],this.event=task.event,this.node=task.node??null,this.drag=task.drag??null;let through=task.from.isHost?task.to:task.from;this.sourceKey=through.path.sourceKeyIn(this.path),this.isStopNextSet=!1,this.handled=null,this.emitted=[],this.unhandled=[],this.nextHop=null}now(){return this.env.now()}random(){return this.env.random()}uuid(){return this.env.uuid()}notify(name,args=[]){this.emitted.push({kind:"notify",name,args}),this.path.isRootPath?unhandled(this,name,null):this.push(NotifyTask,name,args,null)}ask(name,args=[]){this.emitted.push({kind:"ask",name,args});let request=this.nextRequest(),task=new AskTask(name,args,this.address,null,this.task);return task.to=this.address,task.request=request,this.tasks.push(task),request}stopNext(){this.isStopNextSet=!0}sendAt(name,args,pathBuilderFn){this.emitted.push({kind:"sendAt",name,args}),this.push(Task,name,args,new Target(this.path,selectorFrom(pathBuilderFn)))}forwardAt(pathBuilderFn){this.sendAt(this.task.name,this.task.args,pathBuilderFn)}reply(name,args=[]){if(this.emitted.push({kind:"reply",name,args}),this.task.from.isHost)return unhandled(this,name,null);let task=new Task(name,args,this.address,null,this.task);task.to=this.task.from,this.tasks.push(task)}readOnly(){return Object.freeze({scope:this.scope,path:this.path,sourceKey:this.sourceKey,now:()=>this.now(),random:()=>this.random(),uuid:()=>this.uuid()})}push(TaskClass,name,args,target){this.tasks.push(new TaskClass(name,args,this.address,target,this.task))}},Task=class{constructor(name,args,from,target,parent){this.name=name,this.args=args,this.from=from,this.target=target,this.parent=parent,this.event=null,this.to=null}prepare(root){this.to??=this.target.address(root)}run(instance,next,ctx){return run(instance,next,this.name,this.args,ctx)}},NotifyTask=class _NotifyTask extends Task{constructor(name,args,from,target,parent,handled=!1,hops=null){super(name,args,from,target,parent),this.handled=handled,this.hops=hops,this.to=hops?.[0]??null}prepare(){}start(root){this.hops=this.from.ancestors(root),this.to=this.hops[0]}run(instance,next,ctx){let message=specOf(instance).on[this.name],handled=this.handled||message!==void 0,result=message===void 0?next:call(message,instance,next,this.args,ctx);if(ctx.isStopNextSet)return result;if(ctx.path.isRootPath)return handled||unhandled(ctx,this.name,instance),result;let{name,args,from,hops}=this;return ctx.nextHop=new _NotifyTask(name,args,from,null,this,handled,hops.slice(1)),result}},AskTask=class extends Task{start(instance,ctx){let handler=scopeOf(instance)?.lookupAskHandler(this.name);if(!handler)return{now:this.makeAnswer("unhandled",[])};let result;try{result=handler(this.args,ctx.readOnly())}catch(err){return{now:this.makeAnswer("error",[err])}}return result instanceof Promise?{later:result.then(r=>this.makeAnswer("ok",[r]),error=>this.makeAnswer("error",[error]))}:{now:this.makeAnswer("ok",[result])}}makeAnswer(outcome,args){let answer=new AnswerTask(this.name,outcome,args,this.request,HOST,this);return answer.to=this.from,answer}},ANSWER_OUTCOMES=["ok","error","unhandled"],AnswerTask=class extends Task{constructor(ask,outcome,args,request,from,parent){super(`${ask}.${outcome}`,args,from,null,parent),this.ask=ask,this.outcome=outcome,this.request=request}run(instance,next,ctx){let handler=specOf(instance).answers[this.ask]?.[this.outcome];return handler!==void 0?call(handler,instance,next,this.args,ctx):(unhandled(ctx,this.name,instance),next)}},EventTask=class extends Task{constructor(e,{handler,to,node=null},drag=null){super(handler.action.name,[],HOST,null,null),this.event=e,this.node=node,this.drag=drag,this.handler=handler,this.to=to}run(instance,next,ctx){return this.args=this.handler.action.args.map(arg=>arg.eval(ctx)),run(instance,next,this.name,this.args,ctx)}};var Host=class{constructor({document,rootNode,dev=!1,env=browserEnv}){this.document=document,this.rootNode=rootNode,this.dev=dev,this.env=env,this.rootComponent=null,this.registrations=new Set,this.componentNames=new Set,this.tasks=[],this._requests=0,this.nextRequest=()=>++this._requests,this.scope=new Scope((spec,name)=>{this.registrations.add(spec),this.componentNames.add(name),this.addEventListeners(spec.eventNames)}),this.onNotify=(_type,_info)=>{},this.pushTask=this.pushTask.bind(this),this.handleTasks=this.handleTasks.bind(this),this._curVDom=null,this._settledRoot=null,this._taskTickTimeoutId=null,this._handlingTasks=!1,this._eventsAdded=new Set,this.drag=null,this._dragOver=null,this.engines=[],this._committing=!1,this._deferred=[]}start(rootComponent){this.rootComponent=rootComponent,this._settledRoot=rootComponent,this.checkState(null,null),this.render()}checkState(task,prevRoot){this.dev&&this.reportInvalid(prevRoot,{fields:!0,invariants:task===null},{task})}checkSettled(){if(!this.dev||this._settledRoot===this.rootComponent)return;let prevRoot=this._settledRoot;this._settledRoot=this.rootComponent;let check={fields:!1,invariants:!0};this.reportInvalid(prevRoot,check,{task:null,settled:!0})}reportInvalid(prevRoot,check,info){let issues=findInvalidFields(this.rootComponent,prevRoot,check);issues.length>0&&this.notify("stateInvalid",{...info,issues})}checkMessage(task,ctx,prev,next){if(!this.dev||ctx.handled===null)return;let{message,args}=ctx.handled,issues=messageIssues(message,prev,next,args,ctx);issues.length>0&&this.notify("messageInvalid",{task,message:message.name,issues})}render(){let ctx=RenderContext.root(this.rootComponent),curVDom=this._curVDom,newVDom=toVChilds(renderView(this.rootComponent,ctx));render(this.document,this.rootNode,newVDom,curVDom),this._curVDom=newVDom,this.notify("render",{ctx,newVDom,curVDom})}handleEvent(e){if(this.rootComponent===null)return;let{type}=e,bubbles=DROP_EVENTS.has(type);type==="dragstart"?this.startDrag(e):bubbles&&this.dragOver(e);let info;try{info=getEventInfoFor(e.target,type,this.rootNode,this.rootComponent,bubbles)}catch(error){info=null,this.notify("eventFailed",{event:e,error})}info!==null&&(this.arrive(new EventTask(e,info,this.drag)),this.handleTasks()),type==="dragend"&&this.endDrag()}startDrag(e){let node=e.target.closest?.('[draggable="true"]'),path=node?pathOf(node,this.rootNode):null;if(path===null)return;this.endDrag();let value=path.resolve().getIn(this.rootComponent);this.drag=new Drag(path,node.getAttribute("data-dragtype"),node,value),node.setAttribute("data-dragging",""),e.dataTransfer&&(e.dataTransfer.setData("text/plain",""),e.dataTransfer.effectAllowed="move")}dragOver(e){if(e.type==="drop")e.preventDefault(),this.markDragOver(null);else if(e.type==="dragleave")this.rootNode.contains(e.relatedTarget??null)||this.markDragOver(null);else{let info=getEventInfoFor(e.target,"drop",this.rootNode,this.rootComponent,!0);info!==null&&(e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="move")),this.markDragOver(info?.node??null)}}markDragOver(node){node!==this._dragOver&&(this._dragOver!==null&&this._dragOver.removeAttribute("data-draggingover"),this._dragOver=node,node!==null&&node.setAttribute("data-draggingover",this.drag?.type??"external"))}endDrag(){this.markDragOver(null),this.drag!==null&&this.drag.node.removeAttribute("data-dragging"),this.drag=null}addEventListeners(eventNames){for(let eventName of eventNames)this._eventsAdded.has(eventName)||(this._eventsAdded.add(eventName),this.rootNode.addEventListener(eventName,this))}arrive(task){let{tasks}=this,i=0,ahead=t2=>t2 instanceof EventTask||t2 instanceof NotifyTask&&t2.hops!==null;for(;i<tasks.length&&ahead(tasks[i]);)i++;tasks.splice(i,0,task),this._handlingTasks||this.scheduleNextTaskTick()}pushTask(task){this.tasks.push(task),this._handlingTasks||this.scheduleNextTaskTick()}scheduleNextTaskTick(){this._taskTickTimeoutId===null&&(this._taskTickTimeoutId=setTimeout(this.handleTasks,0))}clearTasks(){this.tasks.length=0,this.cancelTick()}cancelTick(){clearTimeout(this._taskTickTimeoutId),this._taskTickTimeoutId=null}stop(){this.clearTasks(),this.detachSync(),this.rootComponent=null}attachSync(...engines){for(let engine of engines)this.engines.push(engine),engine.attach?.({host:this,root:()=>this.rootComponent,apply:(producer,info=null)=>this.applyExternal(producer,engine,info)})}detachSync(){for(let engine of this.engines.splice(0))engine.detach?.()}prepareEngines(prev,next,task,source=null){if(prev===next)return()=>{};let change={prev,next,task},prepared=[];for(let engine of this.engines)if(engine!==source)try{prepared.push([engine,engine.prepare?.(change)])}catch(error){if(task!==null)throw error;this.notify("syncFailed",{engine,error})}return()=>{this._committing=!0;try{for(let[engine,p]of prepared)try{engine.commit(change,p)}catch(error){this.notify("syncFailed",{engine,error})}}finally{this._committing=!1}for(;this._deferred.length>0;)this._deferred.shift()()}}applyExternal(producer,source=null,info=null){if(this._committing){this._deferred.push(()=>this.applyExternal(producer,source,info));return}let curRoot=this.rootComponent;if(curRoot===null)return;let newRoot=produce(curRoot,producer);if(newRoot===curRoot)return;let commit=this.prepareEngines(curRoot,newRoot,null,source);this.rootComponent=newRoot,commit(),this.checkState(null,curRoot),this.notify("externalApplied",{source,info,curRoot,newRoot}),!this._handlingTasks&&(this.render(),this.checkSettled())}handleTasks(){if(this._handlingTasks)return;if(this.rootComponent===null)return this.clearTasks();this._handlingTasks=!0,this.cancelTick();let t1=Date.now(),oldRootComponent=this.rootComponent;try{for(;this.tasks.length>0;){let task=this.tasks.shift();try{this.handleTask(task)}catch(error){this.notify("taskFailed",{task,error})}if(Date.now()-t1>16)break}}finally{try{oldRootComponent!==this.rootComponent&&this.render()}catch(error){this.notify("renderFailed",{error})}finally{this._handlingTasks=!1,this.tasks.length>0?this.scheduleNextTaskTick():this.checkSettled()}}}handleTask(task){let curRoot=this.rootComponent;if(task instanceof NotifyTask&&task.hops===null){if(this.receiver(task,task.from,curRoot)===null)return;task.start(curRoot)}let{to}=task,path=to.updatePath,instance=this.receiver(task,to,curRoot);if(instance===null)return;if(task instanceof AskTask)return this.startAsk(task,instance);let ctx,newRoot;try{newRoot=produce(curRoot,rootDraft=>{let leafDraft=path.getIn(rootDraft);ctx=new MessageContext(task,this.env,scopeOf(instance),this.nextRequest);let newLeaf=task.run(instance,leafDraft,ctx);return path.setIn(rootDraft,newLeaf)})}catch(error){for(let message of ctx?.unhandled??[])this.notify("unhandled",{task,message});throw error}for(let child of ctx.tasks)child.prepare(newRoot);let commit=this.prepareEngines(curRoot,newRoot,task);this.rootComponent=newRoot,commit();for(let child of ctx.tasks)this.pushTask(child);ctx.nextHop!==null&&this.tasks.unshift(ctx.nextHop);for(let message of ctx.unhandled)this.notify("unhandled",{task,message});this.checkState(task,curRoot),this.checkMessage(task,ctx,instance,path.getIn(newRoot)),this.notify("taskHandled",{task,path,instance,curRoot,newRoot})}receiver(task,address,root){let path=address.updatePath,found=address.resolve(root);return found.instance!==void 0?found.instance:(task instanceof NotifyTask&&address===task.to?(console.assert(!1,"a notification lost its hop",task),this.notify("lost",{task,path})):found.orphaned?this.notify("orphaned",{task,path}):this.notify("stale",{task,path,id:address.id,found:found.stale}),null)}startAsk(task,instance){let ctx=new MessageContext(task,this.env,scopeOf(instance),this.nextRequest),{now,later}=task.start(instance,ctx);now!==void 0&&this.tasks.unshift(now),later!==void 0&&later.then(reply=>this.pushTask(reply));let root=this.rootComponent;this.notify("taskHandled",{task,path:task.to.updatePath,instance,curRoot:root,newRoot:root})}notify(type,info){setTimeout(()=>this.onNotify(type,info),0)}};var isAttrs=v=>v!==null&&typeof v=="object"&&Object.getPrototypeOf(v)===Object.prototype,split=args=>isAttrs(args[0])?[args[0],args.slice(1)]:[{},args],build=(name,args)=>{let[attrs,childs]=split(args);return h(name,attrs,...childs)},tag=new Proxy(Object.create(null),{get:(_target,name)=>(...args)=>build(name,args)}),button=(...args)=>{let[attrs,childs]=split(args);return h("button",{type:"button",...attrs},...childs)};export{$if,ANSWER_OUTCOMES,Address,AnswerTask,AnyType,ArrayType,AskTask,AstNode,BooleanType,Collect,ComponentSpec,ComponentType,Cond,Const,DRAG_EVENTS,DROP_EVENTS,DispatchPath,DomNode,Drag,DragKey,EnumType,EventTask,Field,Frame,HOST,Host,IndexType,LookupBindName,MapType,MessageContext,MessageSpec,NoDefaultError,NotifyTask,NumberType,OptionType,Provided,RecordType,RenderContext,SYNC_LEVELS,Scope,Selector,Send,SeqItem,SourceKey,StringType,Target,TargetValue,Task,UnionType,UpdatePath,Walker,XEach,XPushView,XRender,XRenderEach,XRenderIt,XScope,browserEnv,button,component,dragKey,each2 as each,field,findInvalidFields,h,idOf,idSym,isComponent,isRecord,lookupBind,messageIssues,provided,pushView,render2 as render,renderEach,renderIt,scope,scopeOf,scopeSym,selectorFrom,send,seqItem,sourceKey,specOf,specSym,syncsAt,t,tag,targetValue,testEnv,toAnswers,toMessages,typeText,unwrapOption};