@wcstack/state 4.9.0 → 4.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +33 -12
- package/README.md +33 -12
- package/dist/auto.min.js +1 -1
- package/dist/auto.min.js.map +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/manifest.esm.js +29 -31
- package/dist/parser.esm.js +4 -1
- package/dist/split/auto.js +1 -1
- package/dist/split/chunks/chunk-65B2K2XD.js +2 -0
- package/dist/split/chunks/{chunk-J3PTKUWV.js.map → chunk-65B2K2XD.js.map} +1 -1
- package/dist/split/chunks/{chunk-ISBASPV2.js → chunk-FFXJVUTT.js} +2 -2
- package/dist/split/chunks/{chunk-LWRYFYOC.js → chunk-FT7OW7CG.js} +2 -2
- package/dist/split/chunks/chunk-GU7IAIWW.js +2 -0
- package/dist/split/chunks/chunk-GU7IAIWW.js.map +1 -0
- package/dist/split/chunks/chunk-IWY3I2DG.js +2 -0
- package/dist/split/chunks/{chunk-47I6RYV3.js.map → chunk-IWY3I2DG.js.map} +1 -1
- package/dist/split/chunks/{chunk-FQUDP3XK.js → chunk-JCQTA35B.js} +2 -2
- package/dist/split/chunks/chunk-MZVF2WEY.js +2 -0
- package/dist/split/chunks/{chunk-P3JKSHRN.js → chunk-PTFWXISY.js} +2 -2
- package/dist/split/chunks/{chunk-BCL75PFH.js → chunk-SJRJALR4.js} +2 -2
- package/dist/split/chunks/chunk-TB52U4QV.js +2 -0
- package/dist/split/chunks/chunk-TB52U4QV.js.map +1 -0
- package/dist/split/chunks/chunk-UE6JK2ZA.js +2 -0
- package/dist/split/chunks/chunk-UE6JK2ZA.js.map +1 -0
- package/dist/split/core.js +1 -1
- package/dist/split/features/devtools.js +1 -1
- package/dist/split/features/diagnostics.js +1 -1
- package/dist/split/features/diagnostics.js.map +1 -1
- package/dist/split/features/formats.js +1 -1
- package/dist/split/features/formats.js.map +1 -1
- package/dist/split/features/list-keys.js +1 -1
- package/dist/split/features/native-commands.js +1 -1
- package/dist/split/features/recursion.js +1 -1
- package/dist/split/features/scopes.js +1 -1
- package/dist/split/features/ssr.js +1 -1
- package/dist/split/features/temporal.js +1 -1
- package/dist/wcs-manifest.json +9 -6
- package/package.json +1 -1
- package/dist/split/chunks/chunk-47I6RYV3.js +0 -2
- package/dist/split/chunks/chunk-EBIQH2HE.js +0 -2
- package/dist/split/chunks/chunk-EBIQH2HE.js.map +0 -1
- package/dist/split/chunks/chunk-J3PTKUWV.js +0 -2
- package/dist/split/chunks/chunk-SOFOV2OG.js +0 -2
- package/dist/split/chunks/chunk-SOFOV2OG.js.map +0 -1
- package/dist/split/chunks/chunk-TS2HEHBQ.js +0 -2
- package/dist/split/chunks/chunk-YIDHPXYQ.js +0 -2
- package/dist/split/chunks/chunk-YIDHPXYQ.js.map +0 -1
- /package/dist/split/chunks/{chunk-ISBASPV2.js.map → chunk-FFXJVUTT.js.map} +0 -0
- /package/dist/split/chunks/{chunk-LWRYFYOC.js.map → chunk-FT7OW7CG.js.map} +0 -0
- /package/dist/split/chunks/{chunk-FQUDP3XK.js.map → chunk-JCQTA35B.js.map} +0 -0
- /package/dist/split/chunks/{chunk-TS2HEHBQ.js.map → chunk-MZVF2WEY.js.map} +0 -0
- /package/dist/split/chunks/{chunk-P3JKSHRN.js.map → chunk-PTFWXISY.js.map} +0 -0
- /package/dist/split/chunks/{chunk-BCL75PFH.js.map → chunk-SJRJALR4.js.map} +0 -0
package/dist/auto.min.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["Pattern","constructor","path","last","parent","this","children","getter","setter","underGetter","dependents","sources","crossSources","slot","rootValue","UNSET","eqIndexWatchers","eqIndexKeys","indexWatchers","eqSubs","pinned","dead","markup","mark","dependentSet","Set","lists","slice","w","push","depth","length","tail","addDependent","has","add","dropDependent","delete","d","splice","indexOf","forget","clear","isUnder","ancestor","p","Symbol","DIRTY","FAILED","PatternTable","onCreate","byPath","Map","peek","get","i","lastIndexOf","set","all","values","drop","literalCache","parsePath","cached","literal","segs","split","indexes","s","c","charCodeAt","Number","pattern","join","parsed","size","StateRow","list","index","item","cache","view","bindings","alive","StateList","parentRow","arr","rows","extra","queued","stale","shared","EMPTY","hooks","chain","prev","fn","a","first","answered","r","handled","known","taken","installed","loadFeatures","state","names","$features","load","Array","isArray","missing","filter","n","requireFeature","feature","what","Error","raiseError","message","subject","candidates","explain","report","error","rest","reportError","console","cause","text","id","args","render","map","JSON","stringify","String","raise","Token","name","subscribers","subscribe","unsubscribe","emit","results","readNames","value","key","reserved","seen","TRANSITION_RUNNER_KEY","for","getTransitionRunner","source","candidate","globalThis","protocol","version","run","accepts","runTransition","mutate","types","runner","ELSE_KEYWORD","EVENT_TOKEN_NAMESPACE","CLASS_NAMESPACE","ATTR_NAMESPACE","INDEX_PARAM","NUMBER_LITERAL","parseFilterArgsWithLiterals","argsText","literals","current","inQuote","hasQuote","firstQuoteStart","lastQuoteEnd","flush","arg","startLimit","endLimit","trimStart","trimEnd","finalizeArg","quoted","test","toLiteral","char","trimFn","trim","outsideQuotes","found","quote","indexOfOutsideQuotes","splitOutsideQuotes","separator","parts","start","splitFilters","part","filterIOType","pos","filtersText","filters","filterTextList","sourceText","filterText","openParenIndex","closeParenIndex","pop","lastIndexOfOutsideQuotes","trailing","filterName","substring","includes","modifiers","parseFilters","cacheFilterInfos","recursionUnsupported","parseStatePart","statePart","stateAndPath","statePathName","isLoopRelative","startsWith","body","some","segment","segmentCount","checkPathLikeGetPathInfo","outFilters","DECLARATIONS","BEHAVIOR_KEYS","unbound","evals","upsert","m","k","make","v","newSet","newArray","twice","WeakMap","isThenable","then","sameValueZero","b","unsubEq","sub","dig","rowAt","row","ctxRow","ctx","Engine","target","strategy","slotCount","readonlyDepth","dropped","delegated","blockKey","element","errors","rendered","frames","depthNow","top","rootLists","rootBindings","queue","dirtyLists","staleLists","scheduled","draining","listsByArray","carried","unsettled","fedBack","codeWrote","feeding","unchainFn","renderedFn","rp","rr","drainFn","drain","deliverFn","handler","proxy","rootEqSubs","loose","api","$untracked","f","untracked","$eqIndex","level","watchIndex","read","g","watchers","listP","readUntracked","$eq","eq","$eqPath","keyPath","kp","$dependOn","resolve","track","$getAll","getAll","$setAll","options","setAll","$resolve","checkArity","rowOf","write","$postUpdate","resetRow","touched","mirror","rekeyEqUnder","landed","patterns","onPatternCreated","loadTarget","engine","getOwnPropertyDescriptor","_t","Reflect","configurable","receiver","t","dollar","bound","trap","Proxy","registerAccessors","o","Object","prototype","getPrototypeOf","getOwnPropertyNames","markupAccessor","findIndex","j","childList","l","sync","trySync","failAt","anchor","unfile","old","next","oe","ne","rowRemoved","end","byItem","indexChanged","reconcile","same","x","listSynced","schedule","keys","sel","before","after","invalidateUnder","onIndexChange","subs","e","was","idx","readData","readGetter","epoch","reads","Math","min","evalGetter","frame","outer","call","prune","unlink","sweep","parents","q","commands","subscribeEq","forSubtree","rekeyEqIndex","invalidate","occurrence","beforeWrite","callAt","guard","is","syncListsUnder","sharing","direct","suffix","dup","holdsTwice","land","mp","down","deps","up","forListsUnder","enqueueBound","ls","forAllLists","forRowsUnder","written","changed","onWrite","delegate","type","root","addEventListener","parentNode","cancelBubble","block","dispatch","reset","bs","enqueue","resetList","watchRendered","$behavior","mustache","directional","ns","$commandTokens","freeze","commandNamespace","events","deliver","tokens","$eventTokens","on","$on","entries","token","eventTokens","declare","indexesOf","out","unshift","fireEventToken","event","command","emitCommand","invoke","apply","slots","enqueueSlots","fv","rv","walkDependents","visit","visitGetter","forAllRows","getterReached","register","unregister","queueMicrotask","dropWork","cutLoop","max","paths","noticed","maxDepth","setTimeout","MAX_RENDER_CHAIN","pass","update","owner","applyBinding","pending","drained","fail","node","typeName","noteRendered","$renderedCallback","callHook","hook","$errorCallback","binding","failed","bindingType","kind","forMatches","walk","lp","targets","spread","exact","config","bindAttributeName","commentForPrefix","commentIfPrefix","commentElseIfPrefix","commentElsePrefix","tagNames","ssr","locale","document","documentElement","lang","enableContractAnalyzer","STRUCTURAL_BINDING_TYPE_SET","KEYWORDS_WITHOUT_MODIFIERS","EXPLICIT_PROPERTY_REJECTED_HEADS","parseBindTextsForElement","bindText","splitBindTexts","separatorIndex","propPart","keyword","stateResult","propName","propSegments","propModifiers","inFilters","propResult","propText","modifierParts","propModifiersText","parsePropPart","head","FORMATS_FILTER_NAMES","definitions","resolvedByKey","registerFilters","hasFilter","optionsRequired","fnName","optionMustBeNumber","valueMustBeNumber","valueMustBeDate","validateNumberString","isNaN","numberOption","requiredNumberOption","firstLiteral","opt","numeric","op","factory","arity","coreFilters","not","lt","le","gt","ge","falsy","truthy","boolean","pipe","fs","buildFilters","filterArgsKey","resolved","definition","unknownFilter","filterFn","resolveFilter","TRUSTED_TYPES_POLICY_SLOT","getTrustedTypesPolicy","isHtmlSink","prop","trustHtml","trustedTypes","isHTML","policy","create","createHTML","LEDGER_KEY","named","WeakSet","autoNaming","naming","namingLimit","bindableByClass","registryOf","el","customElementRegistry","customElements","whenDefined","attach","later","tag","localName","isConnected","cls","upgrade","decl","wcBindable","isInteger","properties","inputs","semantics","readBindable","cleanups","failSpec","attachProperty","spec","bd","input","init","outputOnly","Binding","K_CUSTOM","adopt","ro","detail","applying","authority","seed","snapshot","Promise","noBindable","BUBBLING","TYPE_NAMES","HOLD","initialOf","initial","checked","elementValue","applyTo","writeBack","cur","NaN","isContent","data","removeAttribute","SELECTED","innerHTML","classList","toggle","setAttribute","style","removeProperty","setProperty","reselect","Block","nodes","plan","lead","hits","nodePaths","nodeAt","contains","own","listener","headAt","insertBefore","ref","nextSibling","removeNodes","remove","removeContiguous","dispose","RowView","super","lazy","slotBinding","listFor","lastBlock","takeBlock","buildBlock","at","build","scratch","adopted","single","createDocumentFragment","fragment","cloneNode","childNodes","limit","nodeType","ledger","counter","assigned","warned","warn","nameBlock","specs","nested","ForView","iv","attachChain","branches","br","attachSpec","h","custom","bubbles","removeEventListener","attachEvent","method","nativeCommand","WeakRef","deref","attachCommand","prevent","preventDefault","stop","stopPropagation","attachEventToken","brow","exclude","attachSpread","hostBinding","attachCustomOrPlain","twoWay","IfView","rowViews","_n","viewOf","keep","firstChild","replaceChildren","views","src","Int32Array","anyKept","next0","Uint8Array","fill","tails","lo","hi","mid","lisKeep","frag","appendChild","bindAttr","blank","INITS","SYNCS","COMMAND_PREFIX","boundPattern","expandPath","loop","declared","isOuter","setsContent","notAfterIf","elementSpecs","mods","find","isInit","flags","handlerThrew","getAttribute","toLowerCase","isTwoWay","specFor","MUSTACHE","splitMustache","lastIndex","exec","ownerDocument","createTextNode","expr","textSpec","parseBindTextForEmbeddedNode","directive","chainAnchorText","readChain","walked","walkBindings","page","onFor","onIf","onElement","onText","anchorFor","createComment","replaceWith","ssrMark","child","hasAttribute","compilePlan","into","componentScope","COMMENT_BINDING","templateContent","createRange","selectNodeContents","content","cloneContents","template","asRow","importNode","stripInsignificantWhitespace","previousSibling","pathOf","used","shifts","isSlotKind","sort","NO_TEXT","strip","engines","mount","container","mountSubtree","subtree","range","BINDER_KEY","PENDING_KEY","TAKEN_KEY","early","bind","getRootNode","drainBinds","waiting","binder","getBinder","globals","pendingQueue","takenSet","flushPendingBinds","DirtyStrategy","loads","readyByRoot","enroll","getBindingsReady","els","any","initializePromise","connectedCallbackPromise","reject","HTMLElementBase","HTMLElement","WcsState","started","claimed","loaded","receiveInitial","resolveConnected","rejectConnected","catch","resolveInitialize","hasConnectedCallbackPromise","connectedCallback","connected","rerun","claim","lenient","ShadowRoot","loadState","built","disconnectedCallback","disconnected","setInitialState","receive","createState","mutability","callback","createStateAsync","querySelectorAll","script","parse","textContent","async","url","URL","baseURI","href","res","fetch","ok","status","json","default","loadSrc","querySelector","blocked","effectiveDirective","blob","createObjectURL","Blob","encodeURIComponent","revokeObjectURL","loadInnerScript","host","loading","other","flatMap","refs","registries","nullishPassthrough","valid","defaultLocale","Intl","getCanonicalLocales","STYLES","dateOptions","loc","styleInvalid","registered","toFixed","explicit","toLocaleString","upper","toUpperCase","lower","capitalize","charAt","numberedOpts","opt2","padStart","opt1","padEnd","repeat","reverse","truncate","maxLength","round","optValue","pow","floor","ceil","percent","unit","date","format","dateStyle","Date","toLocaleDateString","time","timeStyle","toLocaleTimeString","datetime","ymd","year","getFullYear","toString","month","getMonth","day","getDate","hms","hours","getHours","minutes","getMinutes","seconds","getSeconds","mul","div","mod","abs","clamp","int","parseInt","float","parseFloat","defaults","fallback","coalesce","number","string","nullIfEmpty","currency","code","NumberFormat","supportedValuesOf","currencyInvalid","formats","install","editDistance","curr","cost","didYouMean","folded","best","bestDistance","distance","LINT_HINT","CODES","codeOf","MOVED","NAMESPACES","CSP_GUIDE","SENTENCES","modifier","where","given","allowed","over","sentence","LINT_CODES","GUIDES","RENAMED_FILTERS","inc","dec","fix","uc","lc","cap","rep","rev","pad","null","to","hasOwn","removedFilter","re","replace","_","due","settled","findDescriptor","keysOf","wildcardForm","under","seg","done","todo","readers","rowGetter","loops","near","missingSegment","check","watch","note","wrapped","posting","declaredKeys","wrappedTokens","loud","said","explained","toldThis","USES_THIS","toldRoots","describeState","secondRoot","phase","others","esc","trustedTypesReported","_engine","TypeError","property","warnedDetail","reason","hasOwnProperty","REMOVED_DECLARATIONS","REMOVED_APIS","$trackDependency","$untrackDependency","diagnostics","$scan","removedDeclarations","$recursion","endsWith","step","families","bad","why","RegExp","checkRecursion","onHandlersThis","recheck","post","watchPostUpdate","defineProperty","watchCommands","ROOT","INDEX_PATH","PROTOTYPE_NAMES","taskSeq","pinged","ping","nextTask","thisTask","MessageChannel","ch","port1","onmessage","unref","port2","postMessage","stack","WatchRuntime","watches","active","cutTask","reported","activate","prime","eachRow","held","hit","getterOf","deactivate","wp","batch","cut","real","compareRows","saved","chainCut","task","fresh","ia","ib","STATUS","ERROR","internalWrite","hasAccessorOrMethod","StreamRuntime","startAll","abortAll","restart","controller","abort","stopAll","eager","kept","untrack","checkArgs","ctrl","AbortController","consume","signal","live","aborted","put","acc","producer","chunk","fold","getReader","reader","cancel","asyncIterator","it","return","runtimes","rt","parseWatches","$watch","stream","$stream","def","parseStreams","temporal","keysByTarget","merging","SEGMENT","$listKeys","isPlain","proto","keyed","keyOf","merged","updates","changes","fp","listKeys","ORPHAN","wired","grafted","REJECTED","NOT_RUN","PREFIX","PATH_APIS","rootEngineCreated","graft","release","settle","callLifecycle","chroot","hydrated","prefix","chrootOf","defs","defineProperties","orphan","giveUp","claimVolume","problem","every","validPath","instances","byEngine","claimDcc","mode","streams","members","bindables","states","ensure","shadow","attachShadow","inner","ready","Dcc","stateElement","define","hostBindings","readonlyWiring","WIRED","hosts","mounts","UNWIRED","INERT","headOf","wiredInMarkup","heads","wireLate","scope","parentElement","E","warnOnce","surface","mountKey","whole","H","info","synth","C","component","hp","from","across","skip","mountUnder","through","reaches","reached","byP","byRow","exports","answer","exporting","exportAccessors","cp","warnShadowed","exporter","tree","touch","refresh","cpath","crow","crossed","hr","exportReached","attr","binds","matches","added","takesOver","reconnect","resume","methods","_self","bindMethods","independent","base","made","inPlace","wire","adoptScope","enumerable","$stateReadyCallback","broken","claimComponent","watchRoot","Element","mine","light","wiring","marked","wiredOnServer","onRootFailed","finally","original","star","ds","getOwnPropertyDescriptors","frozen","isFrozen","writable","melt","scopes","rootMoved","dccEngineCreated","dispatchEvent","CustomEvent","dccWritten","_row","_value","guardAncestorWrite","guardReadonlyMount","hasMounts","NAME","registering","checkPath","nodePath","suffixOf","nodeList","depthOf","ancestors","enter","listPath","rootP","declareRecursion","matchers","owners","had","created","wrap","guardExpansion","recursion","recursionSettled","VERSION","majorMinor","Ssr","stateData","templates","hydrateProps","getTemplate","verifyVersion","defineSsr","registry","BUILDER","isServer","isMark","startsMark","anchors","enginesByRoot","rawTexts","attrs","attributes","append","beside","anchorElement","region","blocks","branch","open","close","lastOf","visitView","visitBlock","RAW","RAW_ATTR","raw","protectTexts","ids","byAnchor","createTreeWalker","acceptNode","scoped","nextNode","cs","createElement","svg","namespaceURI","createElementNS","doc","multiple","selectedIndex","disabled","toggleAttribute","selected","defaultValue","forms","previousElementSibling","IMPL","deferred","enters","nodesOf","flat","concat","prepare","decodeURIComponent","copy","replaceChild","isBlank","forEach","prepend","mend","undo","comments","currentNode","none","es","isIfAnchor","fits","nodeName","isFor","shift","snap","wirings","wiringOf","asIs","restore","legacy","edits","defaultChecked","Event","typed","hydrate","installBuilder","tags","HOOK","sink","address","absolutePathInfo","pathInfo","listIndex","nodeIds","nodeSeq","ledgers","now","idOf","replaceNode","absoluteAddress","engineOf","summary","rootNode","commandTokenNames","eventTokenNames","staticDependency","dynamicDependency","watchPaths","keyedListPaths","batches","devtoolsElement","tokenName","subscriberCount","wrapTokens","devtoolsWritten","oldValue","hasOldValue","devtoolsDrained","addresses","devtoolsFailed","NATIVE_COMMANDS","dialog","form","textarea","select","audio","video","nativeCommandsOf","features","installFeatures","listeners","_setSink","onEvent","onSourceRegistered","onSourceUnregistered","addListener","createRegistry","random","packageVersion","getStateElements","overlays","keyedSubscriptions","lastValue","tracked","attached","registerSource","installBinder"],"sources":["../src/pattern.ts","../src/list.ts","../src/hooks.ts","../src/parser/raiseError.ts","../src/messages.ts","../src/token.ts","../src/protocol/transitionRunner.ts","../src/parser/define.ts","../src/parser/parseFilterArgs.ts","../src/parser/utils.ts","../src/parser/parseFilters.ts","../src/parser/parseStatePart.ts","../src/engine.ts","../src/config.ts","../src/parser/parsePropPart.ts","../src/parser/types.ts","../src/parser/parseBindTextsForElement.ts","../src/filters/registry.ts","../src/filters/errorMessages.ts","../src/filters/options.ts","../src/filters/core.ts","../src/dom/filters.ts","../src/trustedTypes.ts","../src/dom/naming.ts","../src/dom/wc.ts","../src/dom/view.ts","../src/dom/plan.ts","../src/parser/parseBindTextForEmbeddedNode.ts","../src/dom/mount.ts","../src/protocol/binder.ts","../src/dom/binder.ts","../src/strategy/dirty.ts","../src/element.ts","../src/filters/formats.ts","../src/features/formats.ts","../src/diagnostics/guidance.ts","../src/diagnostics/messages.ts","../src/diagnostics/explain.ts","../src/features/diagnostics.ts","../src/temporal/watch.ts","../src/temporal/stream.ts","../src/features/temporal.ts","../src/features/list-keys.ts","../src/scopes/volume.ts","../src/scopes/dcc.ts","../src/scopes/component.ts","../src/features/scopes.ts","../src/recursion/recursion.ts","../src/features/recursion.ts","../src/version.ts","../package.json","../src/ssr/element.ts","../src/ssr/ssr.ts","../src/features/ssr.ts","../src/devtools/devtools.ts","../src/features/devtools.ts","../src/native/commands.ts","../src/auto.ts","../src/features/all.ts","../src/features/native-commands.ts"],"sourcesContent":["/**\n * Path patterns.\n *\n * A pattern is the authoring-level path with every list position written as `*`\n * (`data.*.label`). Each engine interns its patterns once; everything at run time\n * refers to the Pattern object, never to a path string. A concrete location is a\n * pattern plus the row that owns its last wildcard — there is no address object.\n */\n\nexport const WILDCARD = \"*\";\n\nexport class Pattern {\n readonly path: string;\n readonly parent: Pattern | null;\n readonly last: string;\n /** Number of `*` segments. 0 = a location on the root, n = a location inside a depth-n row. */\n readonly depth: number;\n /** Segments after the last `*` (all segments when depth is 0). Read from the row item / the root. */\n readonly tail: readonly string[];\n /** `lists[k]` is the list pattern whose rows the k-th wildcard (1-based) ranges over. */\n readonly lists: readonly (Pattern | null)[];\n children: Pattern[] = [];\n\n // --- filled in by the engine ---\n getter: (() => unknown) | null = null;\n setter: ((value: unknown) => void) | null = null;\n /** true when some proper ancestor is an accessor (read through it instead of walking data). */\n underGetter = false;\n /** Getter patterns whose evaluation read this pattern. */\n readonly dependents: Pattern[] = [];\n /** Patterns this getter read (union over its evaluations). */\n sources: Pattern[] = [];\n /** Sources read from a row other than the evaluating row's own chain (fan out on change). */\n crossSources: Set<Pattern> | null = null;\n /** Cache slot of a row-level getter on its rows. -1 when not a row-level getter. */\n slot = -1;\n /** Root-level getter cache (depth 0). */\n rootValue: unknown = UNSET;\n /** `$eqIndex(this path)` watchers: getters keyed on the index of their row at `level`. */\n eqIndexWatchers: { getter: Pattern; level: number }[] | null = null;\n /** On a list pattern: the `$eqIndex` registrations over its rows (re-keyed on reorder). */\n eqIndexKeys: { source: Pattern; getter: Pattern }[] | null = null;\n /** On a list pattern: getters that read the index (`$k`) of this list's rows. */\n indexWatchers: Pattern[] | null = null;\n /** `$eq(this path, key)` subscriptions: getter occurrences keyed by the value they wait for. */\n eqSubs: Map<unknown, Set<EqSub>> | null = null;\n /**\n * Something outside a path's read or write holds it (a binding, a list, an add-on: Engine.pattern):\n * never swept. A pattern only a path made (`this[\"users.\" + id]`) goes when it holds nothing (Engine.sweep).\n */\n pinned = false;\n /** Swept: out of the table (a later use of its path makes a new one). */\n dead = false;\n /** Its accessor is the engine's own for an index path (Engine.markupAccessor), not the author's or an add-on's. */\n markup = false;\n /** Scratch of Engine.prune: the evaluation that read it. */\n mark = 0;\n\n private readonly dependentSet = new Set<Pattern>();\n\n constructor(path: string, last: string, parent: Pattern | null) {\n this.path = path;\n this.parent = parent;\n this.last = last;\n // the parent's list table, plus our own when we are a wildcard segment\n const lists: (Pattern | null)[] = parent === null ? [null] : parent.lists.slice();\n const w = last === WILDCARD;\n if (w) lists.push(parent);\n this.depth = lists.length - 1;\n this.tail = w ? [] : parent === null ? [last] : [...parent.tail, last];\n this.lists = lists;\n }\n\n addDependent(getter: Pattern): void {\n if (this.dependentSet.has(getter)) return;\n this.dependentSet.add(getter);\n this.dependents.push(getter);\n getter.sources.push(this);\n }\n\n /** `getter` reads this no more (its side, `sources`, is the caller's). */\n dropDependent(getter: Pattern): void {\n this.dependentSet.delete(getter);\n const d = this.dependents;\n d.splice(d.indexOf(getter), 1);\n }\n\n /** A re-set replaced the state: forget its accessors and everything learned from them. */\n forget(): void {\n this.getter = null;\n this.setter = null;\n this.slot = -1;\n this.rootValue = UNSET;\n this.dependents.length = 0;\n this.dependentSet.clear();\n this.sources.length = 0;\n this.crossSources = null;\n this.eqIndexWatchers = null;\n this.eqIndexKeys = null;\n this.indexWatchers = null;\n this.eqSubs = null;\n }\n\n /** true when `this` is `ancestor` or lies under it. */\n isUnder(ancestor: Pattern): boolean {\n let p: Pattern | null = this;\n while (p !== null) {\n if (p === ancestor) return true;\n p = p.parent;\n }\n return false;\n }\n}\n\n/** One getter occurrence subscribed under a key of a `$eq` source. */\nexport interface EqSub {\n getter: Pattern;\n row: import(\"./list\").StateRow | null;\n}\n\n/** Sentinel for \"no cached value\". */\nexport const UNSET: unique symbol = Symbol(\"unset\") as never;\n/** Sentinel for \"cached value is stale\" (dirty strategy). */\nexport const DIRTY: unique symbol = Symbol(\"dirty\") as never;\n/**\n * Sentinel for \"evaluated, but it threw\" (or stale with its readers dropped by a cut drain):\n * someone read it, so a change of its sources must reach it.\n */\nexport const FAILED: unique symbol = Symbol(\"failed\") as never;\n\nexport class PatternTable {\n private readonly byPath = new Map<string, Pattern>();\n private readonly onCreate: ((p: Pattern) => void) | null;\n\n constructor(onCreate: ((p: Pattern) => void) | null = null) {\n this.onCreate = onCreate;\n }\n\n peek(path: string): Pattern | undefined {\n return this.byPath.get(path);\n }\n\n get(path: string): Pattern {\n let p = this.byPath.get(path);\n if (p !== undefined) return p;\n const i = path.lastIndexOf(\".\");\n const parent = i < 0 ? null : this.get(path.slice(0, i));\n p = new Pattern(path, path.slice(i + 1), parent);\n this.onCreate?.(p);\n this.byPath.set(path, p);\n if (parent) parent.children.push(p);\n return p;\n }\n\n all(): IterableIterator<Pattern> {\n return this.byPath.values();\n }\n\n drop(p: Pattern): void {\n this.byPath.delete(p.path);\n }\n}\n\n/**\n * A concrete path (`data.3.label`, `data.*.label`, `selectedIndex`) split into its\n * pattern and the explicit indexes it carries. `*` segments take their index from the\n * evaluation context, so they are returned as `-1`. A leading numeric segment is a key of\n * the root (`2024.total`), never an index: the root is not a list.\n */\nexport interface ParsedPath {\n pattern: string;\n indexes: number[] | null;\n}\n\nconst literalCache = new Map<string, ParsedPath>();\n\nexport function parsePath(path: string): ParsedPath {\n const cached = literalCache.get(path);\n if (cached !== undefined) return cached;\n let literal = true;\n const segs = path.split(\".\");\n const indexes: number[] = [];\n for (let i = 0; i < segs.length; i++) {\n const s = segs[i];\n const c = s.charCodeAt(0);\n if (i > 0 && c >= 48 && c <= 57) {\n literal = false;\n indexes.push(Number(s));\n segs[i] = WILDCARD;\n } else if (s === WILDCARD) indexes.push(-1);\n }\n if (!literal) return { pattern: segs.join(\".\"), indexes };\n const parsed: ParsedPath = { pattern: path, indexes: null };\n // literal paths (no explicit index) are few and reused: keep them — up to a bound, as a key built\n // from data (`this[\"users.\" + id]`) makes a new one each time\n if (literalCache.size > 4095) literalCache.clear();\n literalCache.set(path, parsed);\n return parsed;\n}\n","import type { Pattern } from \"./pattern\";\nimport type { Binding, ForView, RowView } from \"./dom/view\";\n\n/**\n * One element of a list, owned by its StateList. The row is the whole address of\n * everything under `list.*`: the value (`item`), the position (`index`), the getter\n * cache and the bindings that render it hang off this object — no ledger keyed by an\n * address. Dropping the row drops all of it.\n */\nexport class StateRow {\n readonly list: StateList;\n index: number;\n item: unknown;\n /** Getter cache by slot (row-level getters of this engine). */\n cache: unknown[] | null = null;\n /** The rendering of this row by its list's first for view (see StateList.extra for the others). */\n view: RowView | null = null;\n /**\n * Binding objects whose location is in this row (pattern depth = this row's depth), wherever\n * they render. Row views' slot bindings are not here: they are reached through the views.\n */\n bindings: Binding[] | null = null;\n /** `$eq` subscriptions of getters evaluated at this row (dropped with the row). */\n eqSubs: import(\"./engine\").EqEntry[] | null = null;\n /** Nested lists under this row, by list pattern. */\n children: Map<Pattern, StateList> | null = null;\n alive = true;\n\n constructor(list: StateList, index: number, item: unknown) {\n this.list = list;\n this.index = index;\n this.item = item;\n }\n}\n\nexport class StateList {\n readonly pattern: Pattern;\n readonly parentRow: StateRow | null;\n /** Depth of this list's rows (1 for a root list). */\n readonly depth: number;\n /** The array the rows were last reconciled against. */\n arr: unknown[] | null = null;\n rows: StateRow[] = [];\n /** The first for view that renders this list, if any (its row views are on row.view). */\n view: ForView | null = null;\n /** Further for views rendering the same list (each keeps its row views by row). */\n extra: ForView[] | null = null;\n /** Queued for a view update in the current drain. */\n queued = false;\n /** Its pattern reads through a getter that changed: re-synced at the next drain pass. */\n stale = false;\n /** Another list has the same array (a getter returning it, an index path): writes reach both. */\n shared = false;\n\n constructor(pattern: Pattern, parentRow: StateRow | null) {\n this.pattern = pattern;\n this.parentRow = parentRow;\n this.depth = pattern.depth + 1;\n }\n}\n\nexport interface ReconcileHooks {\n /** A kept row changed position. */\n indexChanged(row: StateRow): void;\n /** A row left the list (it marks it dead). */\n rowRemoved(row: StateRow): void;\n}\n\ntype Bucket = StateRow | StateRow[];\n\n/**\n * Brings `list.rows` in line with `next`, reusing rows by item identity.\n * Returns the previous rows (for $eqIndex re-keying) or null when nothing changed.\n * DOM is not touched here; the list's view catches up in the drain.\n */\nexport function reconcile(list: StateList, next: unknown, hooks: ReconcileHooks): StateRow[] | null {\n const arr = Array.isArray(next) ? next : EMPTY;\n if (arr === list.arr) return null;\n const old = list.rows;\n const n = arr.length;\n const o = old.length;\n const rows: StateRow[] = new Array(n);\n\n let start = 0;\n while (start < n && start < o && old[start].item === arr[start]) {\n rows[start] = old[start];\n start++;\n }\n let oe = o - 1;\n let ne = n - 1;\n while (oe >= start && ne >= start && old[oe].item === arr[ne]) {\n rows[ne] = old[oe];\n oe--;\n ne--;\n }\n\n if (start > oe) {\n for (let i = start; i <= ne; i++) rows[i] = new StateRow(list, i, arr[i]);\n } else if (start > ne) {\n for (let i = start; i <= oe; i++) hooks.rowRemoved(old[i]);\n } else {\n // a row whose item is where it was keeps its place: among equal items (a board of 0 / 1), handing\n // the rows out in order would move every one after the first change\n const end = oe < ne ? oe : ne;\n for (let i = start; i <= end; i++) if (old[i].item === arr[i]) rows[i] = old[i];\n const byItem = new Map<unknown, Bucket>();\n // filled from the end, so a bucket hands out its first row with pop(): shift() moves the whole\n // array, and over a long run of equal items the reconcile went quadratic\n for (let i = oe; i >= start; i--) {\n const row = old[i];\n if (i <= end && rows[i] === row) continue;\n const b = byItem.get(row.item);\n if (b === undefined) byItem.set(row.item, row);\n else if (Array.isArray(b)) b.push(row);\n else byItem.set(row.item, [b, row]);\n }\n for (let i = start; i <= ne; i++) {\n if (rows[i] !== undefined) continue;\n const item = arr[i];\n const b = byItem.get(item);\n let row: StateRow | undefined;\n if (b !== undefined) {\n if (Array.isArray(b)) {\n row = b.pop();\n if (b.length === 0) byItem.delete(item);\n } else {\n row = b;\n byItem.delete(item);\n }\n }\n rows[i] = row ?? new StateRow(list, i, item);\n }\n for (const b of byItem.values()) {\n if (Array.isArray(b)) for (const r of b) hooks.rowRemoved(r);\n else hooks.rowRemoved(b);\n }\n }\n\n // positions: only rows from `start` on can have moved\n for (let i = start; i < n; i++) {\n const row = rows[i];\n if (row.index !== i) {\n row.index = i;\n hooks.indexChanged(row);\n }\n }\n list.rows = rows;\n list.arr = arr;\n return old;\n}\n\n/** What a list whose value is not an array reconciles against (engine: an index there is a key). */\nexport const EMPTY: unknown[] = [];\n","/**\n * The places the core calls into add-ons (docs/state-engine-rewrite/addons-plan.ja.md §1.2).\n *\n * Add-ons ship as separate entries of the same build as the core (`features/*`): they reach\n * the core's internals directly, and the core only calls out through these slots. A slot is\n * empty until an installed feature fills it (the object starts with none: a list of null slots\n * would be the core's bytes), so a page without the feature pays one `?.` check. A feature\n * restoring a slot may set it to null.\n * Slots are added with the first feature that needs them; several features share one through\n * chain / first. The slots `element` and `detail` keep their names (a DevTools-facing field and a DOM\n * name share them); the others are shortened by the build. An empty slot is read through\n * Object.prototype: a page that polluted it (a value under `element`, say) breaks the core loudly\n * there, as it does wherever the core reads a plain object's keys (`$behavior`); not defended.\n */\nimport type { Engine } from \"./engine\";\nimport type { Pattern } from \"./pattern\";\nimport type { StateList, StateRow } from \"./list\";\nimport type { Binding, RowPlan, Spec } from \"./dom/view\";\n\nexport interface Hooks {\n /** Diagnostics: extra text for an error message (did-you-mean, lint pointer, how to fix). */\n explain?: ((message: string, subject?: string, candidates?: Iterable<string>) => string) | null;\n /** Diagnostics: the full sentence of a numbered core message (`src/messages.ts`). */\n render?: ((id: number, args: readonly unknown[]) => string) | null;\n /**\n * A write before it is applied (`element`: an element wrote it back, not code); true = the\n * add-on handled it ($listKeys, a read-only mount dropping an element's write).\n */\n beforeWrite?: ((engine: Engine, p: Pattern, row: StateRow | null, value: unknown, element: boolean) => boolean) | null;\n /** A write landed: `direct` for a data write (then `old` is the value before, `value` the new one). */\n /** `element`: an element wrote it (a binding's write-back or its initial value), not code. */\n written?: ((engine: Engine, p: Pattern, row: StateRow | null, old: unknown, value: unknown, direct: boolean, element?: boolean) => void) | null;\n /** A change reached a getter occurrence whose cached value was current (it may now differ). */\n getterReached?: ((engine: Engine, g: Pattern, row: StateRow | null) => void) | null;\n /** A list was reconciled with a new value; `old` are its rows before. */\n listSynced?: ((engine: Engine, list: StateList, old: StateRow[]) => void) | null;\n /** A drain ended (after its report and `$renderedCallback`). */\n drained?: ((engine: Engine) => void) | null;\n /** A state object was received (construction, or a re-set before it replaces the old one). */\n declare?: ((engine: Engine, target: Record<string, any>) => void) | null;\n /**\n * A root engine's lifecycle: \"mounting\" (created, its page not bound yet), \"back\" (its `<wcs-state>`\n * connected again, before `$connectedCallback` runs again: it holds its root again, unless another\n * one bound it meanwhile), \"connected\" (after `$connectedCallback`, and on reconnect), \"disconnected\",\n * \"reset\" (after a re-set).\n */\n element?: ((engine: Engine, phase: \"mounting\" | \"back\" | \"connected\" | \"disconnected\" | \"reset\") => void) | null;\n /**\n * A `<wcs-state>` an add-on takes over instead of it becoming a root (a volume, a DCC\n * definition): asked when it connects; the core then only loads its state.\n */\n claim?: ((el: HTMLElement, root: Node) => Claimed | null) | null;\n /** A `$` name the core does not know. */\n dollar?: ((engine: Engine, key: string) => unknown) | null;\n /** A binding failed to apply (reported after the drain, before `$errorCallback` / the console). */\n failed?: ((engine: Engine, error: unknown, binding: Binding) => void) | null;\n /**\n * A plain property binding on a custom element, made and not yet registered or applied (a\n * component mount's wiring, `state.x: path`); true = an add-on took it over.\n */\n hostBinding?: ((binding: Binding, ro: boolean) => boolean) | null;\n /** An element whose content an add-on binds (a Light DOM component): the walker leaves it. */\n componentScope?: ((el: Element) => boolean) | null;\n /**\n * The page walker replaced a structural template with its anchor (`source` is the template),\n * bound a mustache text node (`source` is its expression), or is about to bind an element\n * (`source` is its specs, which the hook may take some out of): SSR records the first two, and\n * on the server leaves `outerHTML:` to the client.\n */\n ssrMark?: ((engine: Engine, node: Node, source: Element | string | Spec[]) => void) | null;\n /**\n * A block is about to be cloned from `plan` for the view anchored at `anchor`: an add-on may\n * hand over existing nodes instead (SSR hydration) — the block's top-level nodes, already where\n * the block renders (the view inserts nothing), with the plan's nodes in them in `plan.scratch`.\n */\n adopt?: ((plan: RowPlan, anchor: Node, isFor: boolean) => ChildNode[] | null) | null;\n /**\n * A Light DOM component's engine is about to bind `root` (its host): SSR hands over the server's\n * nodes there too; the function returned is called when the walk is done.\n */\n adoptScope?: ((root: Node, engine: Engine) => (() => void) | null) | null;\n /** A path a binding (or, with `watch`, a `$watch` key) names: diagnostics checks it exists. */\n declared?: ((engine: Engine, p: Pattern, watch?: boolean) => void) | null;\n /** `<wcs-state>` was defined in `registry`: an add-on defines its own tags there (`<wcs-ssr>`). */\n tags?: ((registry: CustomElementRegistry) => void) | null;\n /** A wc-bindable property's event read with the default getter (`e.detail`): diagnostics checks its shape. */\n detail?: ((el: Element, name: string, detail: unknown) => void) | null;\n /** The handler `path` of a delegated `on<type>:` threw (reported already): diagnostics says when `currentTarget` is why. */\n handlerThrew?: ((engine: Engine, path: string, type: string) => void) | null;\n /**\n * `command.<method>:` on an element with no wc-bindable declaration: how a native element's\n * method is called (native-commands), or null for a custom element. The add-on throws for a\n * method a native element may not be commanded to run.\n */\n nativeCommand?: ((el: Element, method: string) => NativeCall | null) | null;\n /** The split auto entry: loads and installs add-ons of its build by name (a state's `$features`). */\n load?: ((names: string[]) => Promise<void>) | null;\n /**\n * An event an add-on (or the core) reports for the DevTools protocol (a `$watch` handler fired or\n * threw, a `$watch` chain or an update loop cut, a path that does not resolve): `event` is the\n * protocol's payload, its keys quoted (`{ \"type\": \"state:watch-fired\", \"path\": … }`). Called as\n * `hooks.noticed?.(engine, {…})`, the payload is built only while the slot is filled.\n */\n noticed?: ((engine: Engine, event: Record<string, unknown>) => void) | null;\n}\n\n/** Calls a native element's command method with what the token was emitted with. */\nexport type NativeCall = (target: Element, args: unknown[]) => unknown;\n\n/** What an add-on does with a `<wcs-state>` it claimed. */\nexport interface Claimed {\n /** Where the state comes from, when not from the element's own sources. */\n load?(): Promise<Record<string, any>>;\n /**\n * The loaded state; `connectedCallbackPromise` resolves when this is done, and `built` is called\n * once its bindings are built (before `$connectedCallback`: getBindingsReady resolves then, as for a\n * root). When it (or the load) throws, the core reports the failure and rejects the promise with\n * it — a DCC definition, a component mount: 3.x's README promises it for their configuration\n * errors, and 4.0 also rejects where 3.x did not (a component whose root failed: 3.x left it\n * unsettled; a second mount in one scope: 3.x resolved it) — or resolves it, for a lenient claim.\n */\n start(state: Record<string, any>, built: () => void): Promise<void> | void;\n /** A failure resolves `connectedCallbackPromise` instead (a volume settles without grafting, as 3.x). */\n lenient?: boolean;\n connected(): void;\n disconnected(): void;\n /** `setInitialState` after the start. */\n reset(state: Record<string, any>): void;\n}\n\nexport const hooks: Hooks = {};\n\ntype HookFn = (...args: any[]) => any;\n\n/*\n * A feature fills a slot by assigning it (`hooks.written = chain(hooks.written, fn)`), never by\n * its name as a string: the slot names are shortened by the build (mangle.mjs) like any internal\n * property.\n */\n\n/** A slot several features share: `fn` runs after whatever is there. */\nexport function chain<F extends HookFn>(prev: F | null | undefined, fn: F): F {\n return prev == null ? fn : ((...a: unknown[]) => { prev(...a); fn(...a); }) as F;\n}\n\n/** A slot whose first answer wins (`answered` tells one): `fn` is asked when what is there does not answer. */\nexport function first<F extends HookFn>(answered: (r: unknown) => boolean, prev: F | null | undefined, fn: F): F {\n return prev == null ? fn : ((...a: unknown[]) => { const r = prev(...a); return answered(r) ? r : fn(...a); }) as F;\n}\n\n/** `beforeWrite`: the first feature that handles the write. */\nexport const handled = (r: unknown): boolean => r === true;\n/** `dollar`: the first feature that knows the `$` name (a value, possibly null or false). */\nexport const known = (r: unknown): boolean => r !== undefined;\n/** `claim`: the first feature that takes the `<wcs-state>`. */\nexport const taken = (r: unknown): boolean => r != null;\n\n/** An add-on entry: `installFeatures([temporal, diagnostics])` before the state is defined. */\nexport interface Feature {\n readonly name: string;\n /** The slots of the build it comes from: it fills only those (the core checks they are its own). */\n readonly hooks: object;\n install(): void;\n}\n\nconst installed = new Set<string>();\n\nexport function installFeatures(features: readonly Feature[]): void {\n for (const f of features) {\n if (installed.has(f.name)) continue;\n // An add-on of another copy of the engine — another version (a vendor directory replaced in place),\n // or the same files under another URL (esm.run) — fills that copy's slots: its name would pass\n // requireFeature, and a `$watch` would never run, without a word (docs/seam-apps.md, prod-booking)\n if (f.hooks !== hooks) {\n throw new Error(`[@wcstack/state] [wcs/feature-foreign] The add-on \"${f.name}\" is from another copy of @wcstack/state (another version, or another URL): load the core and its add-ons from one build`);\n }\n installed.add(f.name);\n f.install();\n }\n}\n\n/**\n * A state's `$features` before its engine is made: the missing add-ons, loaded where an entry can\n * load them (`hooks.load`); undefined when there is nothing to wait for. The engine then checks\n * every name (a bundle or the full build only checks).\n */\nexport function loadFeatures(state: Record<string, any>): Promise<void> | undefined {\n const names = state.$features;\n if (hooks.load != null && Array.isArray(names)) {\n const missing = names.filter((n) => !installed.has(n));\n if (missing.length > 0) return hooks.load(missing);\n }\n}\n\n/** The barrier: a declaration that needs a feature the page did not install. */\nexport function requireFeature(feature: string, what: string): void {\n if (!installed.has(feature)) {\n throw new Error(`[@wcstack/state] [wcs/feature-not-installed] ${what} needs the add-on @wcstack/state/features/${feature}`);\n }\n}\n","import { hooks } from \"../hooks\";\n\n/**\n * Throws `[@wcstack/state] <message>`. The core's messages state the fact (a number and values); the\n * diagnostics add-on, when installed, appends the guidance (the nearest of `candidates` to\n * `subject`, how to fix it, the lint pointer).\n */\nexport function raiseError(message: string, subject?: string, candidates?: Iterable<string>): never {\n throw new Error(`[@wcstack/state] ${message}${hooks.explain?.(message, subject, candidates) ?? \"\"}`);\n}\n\n/**\n * Reports an error the engine caught or found — a getter, a filter, a handler or a callback of the\n * page that threw, a `<wcs-state>` that failed to initialize, an update loop cut — through the\n * platform's `reportError()`, so the page's error handlers (`window.onerror`, an `error` listener)\n * see it as an uncaught error, and the console shows it. A production error reporter heard none of\n * them when they went to `console.error` (docs/seam-apps.md, prod-booking). `message` says where\n * (the element, the binding): the reported Error carries both, with the original as its `cause`.\n * Where there is no `reportError()` (happy-dom, Node) it is `console.error` with the arguments as\n * before.\n */\nexport function report(error: unknown, message?: string, ...rest: unknown[]): void {\n if (typeof reportError !== \"function\") console.error(...(message === undefined ? [error] : [message, error]), ...rest);\n else reportError(message === undefined ? error : new Error(`${message} ${error}`, { cause: error }));\n}\n","/**\n * The core's messages, by number. The prose lives in the diagnostics add-on\n * (`src/diagnostics/messages.ts`); without it a message reads `[@wcstack/state] #108 \"a|b(\"` —\n * the message number and the values it would have shown. With it (the full `auto` bundle installs\n * it) the message is the code shared with lint and the VS Code extension and the full sentence\n * (`[wcs/binding-syntax] Invalid filter format: …`), followed by the guidance.\n *\n * The hundreds of a number name its code (the diagnostics add-on's `CODES`, in the core up to\n * 4.0.0-rc.3): 1xx binding-syntax, 2xx template-syntax, …; 1–99 carry no code. Numbers are only\n * ever added, so a number read on a page keeps its meaning across versions. `M` is a const enum:\n * the build inlines the numbers.\n *\n * Kept as full text in the core, not numbered: the barriers a page without add-ons meets on\n * purpose (`[wcs/feature-not-installed]`, a formatting filter without the formats add-on).\n */\nimport { hooks } from \"./hooks\";\nimport { raiseError } from \"./parser/raiseError\";\n\nexport const enum M {\n // no code\n ScanRemoved = 1,\n GetterWithoutSetter = 2,\n NoRow = 3,\n ParentNotObject = 4,\n NotAMethod = 5,\n GetAllNoCommonLevel = 6,\n EqIndexNoRow = 7,\n Readonly = 8,\n SetAllNeedsIndexes = 9,\n SetAllSpreadLength = 10,\n DrainNotSettled = 11,\n BindingFailed = 12,\n LoadFailed = 13,\n ElementFailed = 14,\n NotInitialized = 15,\n NoScript = 16,\n TokenSubscriberThrew = 17,\n TokenListNotArray = 18,\n TokenEntryEmpty = 19,\n TokenEntryReserved = 20,\n TokenEntryDuplicated = 21,\n OnNotObject = 22,\n OnEntryUndeclared = 23,\n OnEntryNotFunction = 24,\n NamingLimit = 25,\n FilterOptionsRequired = 26,\n FilterOptionNotNumber = 27,\n FilterValueNotNumber = 28,\n FilterValueNotDate = 29,\n FilterValueNotArray = 30,\n DirectionalSyncDisabled = 31,\n SelectorRemoved = 32,\n ModifierUnknown = 33,\n ModifierTwice = 34,\n ModifierValue = 35,\n EventInitNone = 36,\n InitUnsupported = 37,\n MemberUndeclared = 38,\n InitIncompatible = 39,\n SyncConnectNeedsOutput = 40,\n RenderChain = 41,\n InlineBlocked = 42,\n InlineFailed = 43,\n OptionInvalid = 44,\n BehaviorChanged = 45,\n FeaturesNotArray = 46,\n SecondRoot = 47,\n LocaleInvalid = 48,\n InitFailed = 49,\n ConnectedFailed = 50,\n DisconnectedFailed = 51,\n FilterStyleInvalid = 52,\n FilterCurrencyInvalid = 53,\n // [wcs/binding-syntax]\n BindTextNoColon = 101,\n StructuralTakesNoModifiers = 102,\n ElseTakesNoValue = 103,\n SpreadNoPath = 104,\n SpreadNoFilters = 105,\n LeadingDotNamespace = 106,\n UnterminatedQuote = 107,\n FilterUnclosed = 108,\n FilterUnopened = 109,\n FilterParenOrder = 110,\n FilterTrailing = 111,\n FilterEmpty = 112,\n FilterNameHasModifiersInput = 113,\n FilterNameHasModifiersOutput = 114,\n OneModifierList = 115,\n NoPropertyName = 116,\n TooManySegments = 117,\n EmptySegment = 119,\n UnsafeSegment = 120,\n ForNoFilters = 121,\n NamespaceNeedsName = 122,\n // [wcs/template-syntax]\n StructuralNotSingle = 201,\n ElseWithoutIf = 202,\n OuterInTemplate = 203,\n TemplateHandedOver = 204,\n // [wcs/binding-path-missing]\n PathMissing = 301,\n // [wcs/binding-type-expectation]\n ClassNeedsBoolean = 401,\n // [wcs/filter-unknown]\n FilterUnknown = 501,\n // [wcs/filter-arity]\n FilterTooFewArgs = 601,\n FilterTooManyArgs = 602,\n // [wcs/getter-cycle]\n GetterCycle = 701,\n // [wcs/getter-depth-exceeded]\n GetterDepth = 801,\n // [wcs/index-arity]\n IndexArityExact = 901,\n IndexArityAtMost = 902,\n // [wcs/index-param-range]\n IndexParamRange = 1001,\n // [wcs/recursion-unsupported]\n RecursionUnsupported = 1101,\n // [wcs/token-misconfigured]\n CommandRightSide = 1201,\n NoBindable = 1202,\n NoCommand = 1203,\n NoProperty = 1204,\n NativeNoCommand = 1205,\n // [wcs/token-undeclared]\n EventTokenUndeclared = 1301,\n CommandTokenUndeclared = 1302,\n // [wcs/wildcard-rank]\n WildcardNoLoop = 1401,\n WildcardRelative = 1402,\n WildcardOtherList = 1403,\n // [wcs/spread-no-bindable]\n SpreadNoBindable = 1501,\n // [wcs/declaration-alias]\n DeclarationRemoved = 1601,\n // [wcs/name-alias]\n ApiRemoved = 1701,\n}\n\n/** A message without the `[@wcstack/state]` prefix: the code and the full sentence with diagnostics, else the number and the values. */\nexport function text(id: M, args: readonly unknown[] = []): string {\n return hooks.render?.(id, args) ?? `#${id}${args.map((a) => ` ${typeof a === \"string\" ? JSON.stringify(a) : String(a)}`).join(\"\")}`;\n}\n\n/** Throws message `id` (`subject` / `candidates` feed the diagnostics add-on's did-you-mean). */\nexport function raise(id: M, args?: readonly unknown[], subject?: string, candidates?: Iterable<string>): never {\n raiseError(text(id, args), subject, candidates);\n}\n","/**\n * The command-token / event-token pub/sub primitive (the same shape as @wcstack/state's\n * `Token`). A subscriber that throws is reported and the others still receive the call.\n */\nimport { raise, M, text } from \"./messages\";\nimport { report } from \"./parser/raiseError\";\n\nexport type TokenSubscriber = (...args: unknown[]) => unknown;\n\nexport class Token {\n readonly name: string;\n private readonly subscribers = new Set<TokenSubscriber>();\n\n constructor(name: string) {\n this.name = name;\n }\n\n get size(): number {\n return this.subscribers.size;\n }\n\n subscribe(fn: TokenSubscriber): () => void {\n this.subscribers.add(fn);\n return () => {\n this.subscribers.delete(fn);\n };\n }\n\n unsubscribe(fn: TokenSubscriber): boolean {\n return this.subscribers.delete(fn);\n }\n\n emit(...args: unknown[]): unknown[] {\n const results: unknown[] = [];\n for (const fn of this.subscribers) {\n try {\n results.push(fn(...args));\n } catch (error) {\n results.push(undefined);\n report(error, `[@wcstack/state] ${text(M.TokenSubscriberThrew, [this.name])}`);\n }\n }\n return results;\n }\n}\n\nfunction readNames(value: unknown, key: string, reserved?: string): string[] {\n if (value === undefined) return [];\n if (!Array.isArray(value)) raise(M.TokenListNotArray, [key]);\n const seen = new Set<string>();\n for (const name of value) {\n if (typeof name !== \"string\" || name === \"\") raise(M.TokenEntryEmpty, [key]);\n if (name === reserved) raise(M.TokenEntryReserved, [key, name, reserved]);\n if (seen.has(name)) raise(M.TokenEntryDuplicated, [key, name]);\n seen.add(name);\n }\n return value as string[];\n}\n\n/**\n * `$commandTokens` → the frozen `$command` namespace (name → Token). On a re-set, a name\n * the previous state declared keeps its token: elements subscribed to it keep receiving.\n */\nexport function commandNamespace(target: Record<string, any>, prev?: Readonly<Record<string, Token>>): Readonly<Record<string, Token>> {\n const ns: Record<string, Token> = {};\n for (const name of readNames(target.$commandTokens, \"$commandTokens\", \"$command\")) ns[name] = prev?.[name] ?? new Token(name);\n return Object.freeze(ns);\n}\n\n/**\n * `$eventTokens` + `$on` → name → Token, with each `$on` handler subscribed as\n * `(state, event, ...listIndexes)` through `deliver`.\n */\nexport function eventTokens(\n target: Record<string, any>,\n deliver: (handler: (...args: unknown[]) => unknown, args: unknown[]) => unknown,\n): Map<string, Token> {\n const tokens = new Map<string, Token>();\n for (const name of readNames(target.$eventTokens, \"$eventTokens\")) tokens.set(name, new Token(name));\n const on = target.$on;\n if (on === undefined) return tokens;\n if (on === null || typeof on !== \"object\") raise(M.OnNotObject);\n for (const [name, handler] of Object.entries(on)) {\n const token = tokens.get(name);\n if (token === undefined) raise(M.OnEntryUndeclared, [name]);\n if (typeof handler !== \"function\") raise(M.OnEntryNotFunction, [name]);\n token.subscribe((...args) => deliver(handler as (...a: unknown[]) => unknown, args));\n }\n return tokens;\n}\n","// ===========================================================================\n// AUTO-GENERATED FILE - DO NOT EDIT.\n// Generated from /protocol/transition-runner.ts by scripts/sync-protocol-types.mjs.\n// Run `node scripts/sync-protocol-types.mjs` after editing the source.\n// ===========================================================================\n\n// transition-runner protocol — how a package that mutates the DOM hands that\n// mutation to whoever is arbitrating view transitions on the page.\n//\n// @wcstack/state and @wcstack/router must not depend on @wcstack/view-transition\n// (zero runtime dependencies, independently publishable), so the arbiter installs\n// itself on a well-known global symbol and the participants look it up lazily.\n// No arbiter installed means the mutation is invoked directly, synchronously —\n// byte-for-byte the behavior these packages had before the protocol existed.\n//\n// docs/view-transition-design.md §4 is the normative description.\n//\n// SINGLE SOURCE OF TRUTH: edit only this file (/protocol/transition-runner.ts), then run\n// `node scripts/sync-protocol-types.mjs` to regenerate the per-package copies\n// (packages/<pkg>/src/protocol/transitionRunner.ts). Those copies are generated — do not edit them.\n\n/**\n * Global key the arbiter installs itself under. `Symbol.for` so independently\n * loaded copies of this file (two CDN bundles on one page) still agree.\n */\nexport const TRANSITION_RUNNER_KEY = Symbol.for(\"wcstack.transition-runner\");\n\n/** Who is asking. Backs the arbiter's `for=` participant gate. */\nexport type TransitionSource = \"router\" | \"state\";\n\n/** `view-transition-name` assignment policy the arbiter declares for participants. */\nexport type TransitionNaming = \"manual\" | \"auto\";\n\nexport interface IWcsTransitionRunOptions {\n /** Participant id, for the `for=` gate and for diagnostics. */\n readonly source?: string;\n /** Transition types, where the environment supports `startViewTransition({ types })`. */\n readonly types?: readonly string[];\n}\n\nexport interface IWcsTransitionRunner {\n readonly protocol: \"wcs-transition-runner\";\n /** Integer protocol version. All versions >= 1 are participant-compatible. */\n readonly version: number;\n /** `\"auto\"` licenses a participant to assign `view-transition-name` itself. */\n readonly naming: TransitionNaming;\n /** Upper bound on auto-assigned names; past it a participant stops naming. */\n readonly namingLimit: number;\n /** Whether this participant animates at all. */\n accepts(source: string): boolean;\n /**\n * Invoke `mutate` inside a view transition when one is possible.\n *\n * Contract (docs/view-transition-design.md §4):\n * - `mutate` is invoked exactly once, whatever happens to the transition.\n * - The promise resolves once `mutate` has run — never waits for the animation.\n * - When no transition is started, `mutate` runs synchronously inside `run()`.\n * - It rejects only if `mutate` threw.\n */\n run(mutate: () => void, options?: IWcsTransitionRunOptions): Promise<void>;\n}\n\n/**\n * The installed arbiter, or null when there is none, it speaks a version this\n * reader does not, or it does not accept this participant.\n *\n * Looked up on every call rather than cached: the tag can be added, removed, or\n * reconfigured at any point in a page's life, and a stale cache would either\n * animate what the author just switched off or miss what they switched on.\n */\nexport function getTransitionRunner(source: string): IWcsTransitionRunner | null {\n const candidate = (globalThis as Record<symbol, unknown>)[TRANSITION_RUNNER_KEY] as\n | IWcsTransitionRunner\n | undefined;\n if (candidate === undefined || candidate === null) return null;\n if (candidate.protocol !== \"wcs-transition-runner\") return null;\n if (typeof candidate.version !== \"number\" || candidate.version < 1) return null;\n if (typeof candidate.run !== \"function\") return null;\n if (typeof candidate.accepts !== \"function\" || !candidate.accepts(source)) return null;\n return candidate;\n}\n\n/**\n * Run `mutate` under the installed arbiter, or directly when there is none.\n *\n * Returns `undefined` in the no-arbiter case instead of a resolved promise: the\n * state drain calls this on every batch, and awaiting is a caller's choice, not\n * an allocation the common path should pay for. `await` accepts both.\n */\nexport function runTransition(\n source: string,\n mutate: () => void,\n types?: readonly string[],\n): Promise<void> | undefined {\n const runner = getTransitionRunner(source);\n if (runner === null) {\n mutate();\n return undefined;\n }\n return runner.run(mutate, { source, types });\n}\n","/**\n * Constants of the `data-wcs` binding grammar, copied from `@wcstack/state`\n * (`src/define.ts` / `src/errorGuidance.ts`). The values are the syntax contract\n * (`[prop][#mod]: [path][|filter...]`) and must stay identical to the current engine.\n */\n\n/** Path segment delimiter. */\nexport const DELIMITER = '.';\n/** Separator between the bindings of one attribute value. */\nexport const BINDING_SEPARATOR = ';';\n/** Separator between the left side (property) and the right side (path). */\nexport const PROP_VALUE_SEPARATOR = ':';\n/** Separator between the property and its modifier list. */\nexport const MODIFIER_SEPARATOR = '#';\n/** Separator of the filter pipeline. */\nexport const FILTER_SEPARATOR = '|';\n\nexport const ELSE_KEYWORD = 'else';\nexport const SPREAD_PROP = '...';\nexport const EVENT_PROP_PREFIX = 'on';\nexport const EVENT_TOKEN_NAMESPACE = 'eventToken';\n/** `<wcs-state mount>` left side `state.<key>: path` (volume injection). */\nexport const VOLUME_INJECTION_PROP = 'state';\nexport const COMMAND_NAMESPACE = 'command';\nexport const CLASS_NAMESPACE = 'class';\nexport const ATTR_NAMESPACE = 'attr';\nexport const STYLE_NAMESPACE = 'style';\n\n/**\n * Segment-count ceiling of one path. The current engine enforces it in `getPathInfo`\n * (first intern only) with a `[wcs/binding-syntax]` diagnostic; the parser port keeps the\n * same check inline on the string.\n */\nexport const MAX_PATH_SEGMENTS = 512;\n\n/** `$1` … `$128`, no leading zero: a loop index parameter (anything else after the `$` is not one). */\nexport const INDEX_PARAM = /^\\$[1-9]\\d{0,2}$/;\nexport const MAX_INDEX_PARAM = 128;\n\n/** Recursive wildcard — only meaningful in `$recursion` declarations, never in a binding path. */\nexport const RECURSION_WILDCARD = '**';\n","/**\n * フィルタ引数リストのパース。`filter(a, b)` の `a, b` 部分を受け取る。\n *\n * トリムの規則は「**クォートの外側だけ**」。`fix( 2 )` のような書き癖を吸収するために\n * 素の引数は前後をトリムするが、クォートは「ここは literal」という宣言なので中身の\n * 空白は残す。両方まとめてトリムしていたため `pad(5, ' ')` が空文字パディング\n * (=無変化)に化けており、空白区切りの `join(' / ')` も指定できなかった。\n *\n * Port of `@wcstack/state` `src/bindTextParser/parseFilterArgs.ts` (behaviour unchanged).\n */\nimport { raise, M } from \"../messages\";\n\n/** 引数 1 つを確定する。クォート由来の文字が入った範囲より外側だけをトリムする。 */\nfunction finalizeArg(text: string, firstQuoteStart: number, lastQuoteEnd: number): string {\n // 先頭側: 最初のクォート文字より前だけが削れる(クォートが無ければ全体が対象)\n const startLimit = firstQuoteStart === -1 ? text.length : firstQuoteStart;\n // 末尾側: 最後のクォート文字より後ろだけが削れる(クォートが無ければ全体が対象)\n const endLimit = lastQuoteEnd === -1 ? 0 : lastQuoteEnd;\n // (`trim` removes what `\\s` matches: WhiteSpace and LineTerminator)\n return text.slice(startLimit - text.slice(0, startLimit).trimStart().length, endLimit + text.slice(endLimit).trimEnd().length);\n}\n\n/** 引用符の無い引数の型(要件 B9): true / false / null / 数値は型付き、それ以外は文字列 */\nconst NUMBER_LITERAL = /^[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$/;\nfunction toLiteral(text: string, quoted: boolean): unknown {\n if (quoted) return text;\n if (text === \"true\") return true;\n if (text === \"false\") return false;\n if (text === \"null\") return null;\n return NUMBER_LITERAL.test(text) ? Number(text) : text;\n}\n\n/**\n * 引数の原文と、その型付きの値(要件 B9)を一緒に返す。原文は引用符を外したもの。\n *\n * 末尾の空引数だけが落ちる(`\"a,\"` → 1 個、`\",a\"` → 2 個、`\",\"` → 1 個)。`filter()` を\n * 「引数 0 個」と読むための規則で、先頭・中間の空引数は位置を保つために残す。\n */\nexport function parseFilterArgsWithLiterals(argsText: string): { args: string[]; literals: unknown[] } {\n const args: string[] = [];\n const literals: unknown[] = [];\n let current = '';\n let inQuote: string | null = null;\n let hasQuote = false;\n let firstQuoteStart = -1;\n let lastQuoteEnd = -1;\n\n /** Ends an argument; only the last one is dropped when empty (and not quoted). */\n const flush = (last?: boolean): void => {\n const arg = finalizeArg(current, firstQuoteStart, lastQuoteEnd);\n if (!last || arg || hasQuote) {\n args.push(arg);\n literals.push(toLiteral(arg, hasQuote));\n }\n current = '';\n hasQuote = false;\n firstQuoteStart = -1;\n lastQuoteEnd = -1;\n };\n\n for (let i = 0; i < argsText.length; i++) {\n const char = argsText[i];\n\n if (inQuote) {\n if (char === inQuote) {\n inQuote = null;\n } else {\n if (firstQuoteStart === -1) {\n firstQuoteStart = current.length;\n }\n current += char;\n lastQuoteEnd = current.length;\n }\n } else if (char === '\"' || char === \"'\") {\n inQuote = char;\n hasQuote = true;\n } else if (char === ',') {\n flush();\n } else {\n current += char;\n }\n }\n\n if (inQuote !== null) {\n // 閉じていない引用符は受理しない(要件 B2)。以前は黙って閉じたことにしていた\n raise(M.UnterminatedQuote, [inQuote, argsText]);\n }\n flush(true);\n\n return { args, literals };\n}\n","export const trimFn = (s: string): string => s.trim();\n\n/**\n * The positions of `char` in `text` that are outside quotes (`'` / `\"`), in order (要件 B1).\n * 閉じていない引用符はそのまま末尾まで続く扱い — 不正な引用符はフィルタ引数の段で名指しで落ちる。\n */\nfunction outsideQuotes(text: string, char: string): number[] {\n const found: number[] = [];\n let quote: string | null = null;\n for (let i = 0; i < text.length; i++) {\n const c = text[i];\n if (quote !== null) {\n if (c === quote) quote = null;\n } else if (c === \"'\" || c === '\"') {\n quote = c;\n } else if (c === char) {\n found.push(i);\n }\n }\n return found;\n}\n\n/** `text` の中で、引用符(`'` / `\"`)の外にある最初の `char` の位置。無ければ -1(要件 B1)。 */\nexport const indexOfOutsideQuotes = (text: string, char: string): number => outsideQuotes(text, char)[0] ?? -1;\n\n/**\n * `text` の中で、引用符の外にある**最後の** `char` の位置。無ければ -1(要件 B1)。\n * フィルタの閉じ括弧を探す用(`a|foo(')')` の引用符内の `)` を終端と誤認しないため)。\n */\nexport const lastIndexOfOutsideQuotes = (text: string, char: string): number => outsideQuotes(text, char).pop() ?? -1;\n\n/**\n * `separator` で区切る。ただし引用符の中は区切らない(要件 B1): `join(';')` や `join('|')` の\n * 区切り文字は引数であって、バインディングやフィルタの区切りではない。\n */\nexport function splitOutsideQuotes(text: string, separator: string): string[] {\n const parts: string[] = [];\n let start = 0;\n for (const i of outsideQuotes(text, separator)) {\n parts.push(text.slice(start, i));\n start = i + 1;\n }\n parts.push(text.slice(start));\n return parts;\n}\n","import { FILTER_SEPARATOR, MODIFIER_SEPARATOR } from \"./define\";\nimport { parseFilterArgsWithLiterals } from \"./parseFilterArgs\";\nimport { raise, M } from \"../messages\";\nimport { FilterIOType, ParsedFilter } from \"./types\";\nimport { indexOfOutsideQuotes, lastIndexOfOutsideQuotes, splitOutsideQuotes, trimFn } from \"./utils\";\n\n// format: filterName(arg1,arg2) or filterName\n\n/**\n * 文法の段(要件 D16): 名前と引数だけを読む。**実関数は引かない** — フィルタ名の解決\n * (別名も含む)はエンジン側の仕事。未知のフィルタもここでは落とさない。\n *\n * Port of `@wcstack/state` `src/bindTextParser/parseFilters.ts` (behaviour unchanged; the\n * tooling-only `clearFilterFnCacheForTooling` is dropped).\n *\n * @param filterTextList 個々のフィルタの原文(`|` で切った後)\n * @param filterIOType 入力(左辺)/ 出力(右辺)。実関数は引かないが、助言の出し分けに使う\n * @param sourceText 診断に埋める原文。呼び出し側は**その辺の全文**(`propPart` / `statePart`)を\n * 渡すこと。`|` より後ろだけを渡すと、`textContent: a|` のように末尾が空の形で\n * 空文字になり、つなぎ直し(`filterTextList.join(\"|\")`)と同じで文脈が消える。\n * 省略時のつなぎ直しは、原文を持たない直接の呼び出し用のフォールバック\n */\nexport function parseFilters(filterTextList: string[], filterIOType: FilterIOType, sourceText?: string): ParsedFilter[] {\n const source = sourceText ?? filterTextList.join(\"|\");\n return filterTextList.map((filterText) => {\n // 括弧も引用符の外だけで探す(要件 B1)。素の `indexOf` / `lastIndexOf` だと\n // `foo(')')` の引用符内の `)` を終端に取り、「閉じ括弧が無い」ではなく\n // 「引用符が閉じていない」という見当違いの診断になっていた\n const openParenIndex = indexOfOutsideQuotes(filterText, '(');\n let closeParenIndex = lastIndexOfOutsideQuotes(filterText, ')');\n if (closeParenIndex === -1) {\n // 引用符の外に閉じ括弧が無い = 引用符が閉じていない形(`join('x)`)か、本当に無いか。\n // 前者で「閉じ括弧が無い」と言うのは見当違いなので素の探索へ落とし、引数の段の\n // `[wcs/binding-syntax] unterminated ' quote` に診断させる\n closeParenIndex = filterText.lastIndexOf(')');\n }\n // check parentheses\n if (openParenIndex !== -1 && closeParenIndex === -1) {\n raise(M.FilterUnclosed, [filterText]);\n }\n if (closeParenIndex !== -1 && openParenIndex === -1) {\n raise(M.FilterUnopened, [filterText]);\n }\n if (closeParenIndex !== -1 && closeParenIndex < openParenIndex) {\n // `foo)1(` — 以前は `substring` が start > end で引数を入れ替えるため、フィルタ名\n // `foo)1` として受理されていた\n raise(M.FilterParenOrder, [filterText]);\n }\n if (closeParenIndex !== -1 && filterText.slice(closeParenIndex + 1).trim().length > 0) {\n // 閉じ括弧の後ろの残余を**黙って捨てていた**。`n|fix(2)uc` は `uc` が消えて診断ゼロで\n // 通っていた。実害は「`|` の打ち忘れでフィルタが 1 本消えても無診断」\n const trailing = filterText.slice(closeParenIndex + 1).trim();\n raise(M.FilterTrailing, [filterText, trailing]);\n }\n const filterName = (openParenIndex === -1 ? filterText : filterText.substring(0, openParenIndex)).trim();\n if (filterName.length === 0) {\n // 空のフィルタ(`x|`・`x||y`・`x|(1)`)は文法の誤り。解析の段で名指しで落とす — 未知の\n // フィルタとは別物で、実関数の解決まで持ち越すと tooling の解析が素通りする\n raise(M.FilterEmpty, [source]);\n }\n if (filterName.includes(MODIFIER_SEPARATOR)) {\n // フィルタ名に `#` が飲まれた形。`[wcs/filter-unknown] filter not found: trim#ro` だと\n // 診断が指す先が実際の誤りと違う(要件 B4 の並び)。\n // 助言は辺で分ける — **修飾子は左辺にしか存在しない**ので、右辺で「修飾子をフィルタより\n // 前に書け」と言うと成立しない直し方(`textContent#ro|trim: x`)を勧めることになる\n const [, modifiers] = filterName.split(MODIFIER_SEPARATOR);\n raise(filterIOType === \"input\" ? M.FilterNameHasModifiersInput : M.FilterNameHasModifiersOutput, [filterName, modifiers]);\n }\n if (openParenIndex === -1) {\n // no arguments\n return { filterName, args: [], literals: [] };\n }\n const argsText = filterText.substring(openParenIndex + 1, closeParenIndex);\n return { filterName, ...parseFilterArgsWithLiterals(argsText) };\n });\n}\n\n/**\n * One side of a binding split at its first `|` outside quotes: the text before it (trimmed) and its\n * parsed filters. `cache` is keyed by the text after the `|`: the same text gives **the same array**\n * (callers must not change it); a failed parse is not cached. The diagnostics quote the whole side\n * (`part`): the text after the `|` alone is empty for `a|`.\n */\nexport function splitFilters(part: string, filterIOType: FilterIOType, cache: Map<string, ParsedFilter[]>): [string, ParsedFilter[]] {\n // 引用符の中の `|` はフィルタの区切りではない(要件 B1 — `join('|')`)\n const pos = indexOfOutsideQuotes(part, FILTER_SEPARATOR);\n if (pos === -1) return [part.trim(), []];\n const filtersText = part.slice(pos + 1).trim();\n let filters = cache.get(filtersText);\n if (filters === undefined) {\n filters = parseFilters(splitOutsideQuotes(filtersText, FILTER_SEPARATOR).map(trimFn), filterIOType, part);\n cache.set(filtersText, filters);\n }\n return [part.slice(0, pos).trim(), filters];\n}\n","import { DELIMITER, MAX_PATH_SEGMENTS, RECURSION_WILDCARD } from \"./define\";\nimport { splitFilters } from \"./parseFilters\";\nimport { raise, M } from \"../messages\";\nimport { ParsedBinding, ParsedFilter } from \"./types\";\n\n// 解析の段の形(フィルタは名前と引数だけ — 実関数はエンジンが引く。要件 D16)。\n// `@wcstack/state` はここで `statePathInfo`(`getPathInfo` の intern 結果)も返していたが、\n// 新エンジンはパスを自分で解決するので文字列だけを返す。\nexport type StatePartParseResult = Pick<ParsedBinding, 'statePathName' | 'outFilters'>;\n\n/**\n * 出力フィルタ列の解析結果のキャッシュ(鍵は `|` より後ろの原文)。同じ原文は**同じ配列**を返す —\n * 消費側は返された `outFilters` を変更しないこと。落ちた解析は載らない。\n * (`@wcstack/state` の tooling 専用の解放口 `clearStatePartCacheForTooling` は移植しない)\n */\nconst cacheFilterInfos = new Map<string, ParsedFilter[]>();\n/** Tooling (`clearParserCaches`): a long-running process drops what it parsed. */\nexport const clearStatePartCache = (): void => cacheFilterInfos.clear();\n\n/**\n * `getPathInfo` が初回 intern で行っていた文字列だけで決まる検査の移植(順序も同じ:\n * `**` → セグメント数)。`getPathInfo` は `**` のパスを intern しないので毎回落ち、\n * 上限超えのパスも intern されないので毎回落ちる — 状態を持たない検査と同値。\n */\nfunction checkPathLikeGetPathInfo(path: string): void {\n if (path.includes(RECURSION_WILDCARD)) {\n recursionUnsupported(path);\n }\n const segmentCount = path.split(DELIMITER).length;\n if (segmentCount > MAX_PATH_SEGMENTS) {\n raise(M.TooManySegments, [path, segmentCount]);\n }\n}\n\n// format: statePath|filter|filter\n// statePath-format: path.to.property (e.g., user.name.first, users.*.name, users.0.name, not include @)\n// filters-format: filterName or filterName(arg1,arg2)\n\n/** Port of `@wcstack/state` `src/bindTextParser/parseStatePart.ts` (no `statePathInfo`). */\n/** `**` outside the places a `$recursion` declaration gives it meaning. */\nexport function recursionUnsupported(path: string): never {\n raise(M.RecursionUnsupported, [path]);\n}\n\nexport function parseStatePart(statePart: string): StatePartParseResult {\n const [stateAndPath, filters] = splitFilters(statePart, \"output\", cacheFilterInfos);\n if (stateAndPath.includes(\"@\")) {\n // 名前次元は v2 で撤去(docs/state-mount-design.md D16 / §9)。パスは 1 本のツリー。\n raise(M.SelectorRemoved, [stateAndPath]);\n }\n const statePathName = stateAndPath;\n // 右辺も左辺(`parsePropPart`)と同じ規準で空セグメントを弾く(要件 B1)。\n //\n // **判定の前にループ相対の短縮形を正規化する。** `.` で始まる右辺は `for` 行の相対パスで\n // (展開はエンジンの仕事 — パーサは展開前の原文をそのまま返す)、先頭の空セグメント 1 つは正当。\n // とくに **`.` 単独は「行そのもの」を指す正規の書き方**(`state: .`)— 「先頭は許すが末尾は拒否」と\n // 素朴に書くと `\".\"` は `[\"\", \"\"]` = 先頭かつ末尾なので落ちる。取り除いた残りが空でも通すこと\n const isLoopRelative = statePathName.startsWith(DELIMITER);\n const body = isLoopRelative ? statePathName.slice(DELIMITER.length) : statePathName;\n const hasEmptySegment = body.length > 0 && body.split(DELIMITER).some((segment) => segment.length === 0);\n if (hasEmptySegment || (!isLoopRelative && body.length === 0)) {\n raise(M.EmptySegment, [statePart]);\n }\n checkPathLikeGetPathInfo(statePathName);\n return {\n statePathName,\n outFilters: filters,\n };\n}\n","import { DIRTY, Pattern, PatternTable, parsePath, WILDCARD, type EqSub } from \"./pattern\";\nimport { StateList, StateRow, reconcile, EMPTY, type ReconcileHooks } from \"./list\";\nimport type { Strategy } from \"./strategy/types\";\nimport type { Binding } from \"./dom/view\";\nimport { commandNamespace, eventTokens, type Token } from \"./token\";\nimport { runTransition } from \"./protocol/transitionRunner\";\nimport { raise, M, text } from \"./messages\";\nimport { recursionUnsupported } from \"./parser/parseStatePart\";\nimport { hooks, requireFeature } from \"./hooks\";\nimport { INDEX_PARAM, MAX_INDEX_PARAM } from \"./parser/define\";\nimport { report } from \"./parser/raiseError\";\n\n/** Declarations an add-on serves: without it installed they fail instead of doing nothing. */\nconst DECLARATIONS: [string, string][] = [[\"$watch\", \"temporal\"], [\"$stream\", \"temporal\"], [\"$listKeys\", \"list-keys\"], [\"$recursion\", \"recursion\"]];\n\n/**\n * The options of `$behavior` (each true by default): what an engine reads them as is `mustache` / `guard` / `directional`.\n * The tooling manifest publishes the same list (`behaviorOptions`, public/manifest.ts — public-surface.test.ts pins\n * them equal; the manifest does not import the engine).\n */\nexport const BEHAVIOR_KEYS: readonly string[] = [\"enableMustache\", \"sameValueGuard\", \"enableDirectionalInitialSync\"];\n\n/** `**` binds a depth only where a path is read: an assignment, $resolve, $postUpdate and $dependOn refuse it. */\nfunction unbound(path: string): string {\n if (path.includes(\"**\")) recursionUnsupported(path);\n return path;\n}\n\n/** `$1` … `$128`, no leading zero (parser/define.ts — the tooling manifest reads them there too). */\nexport { INDEX_PARAM, MAX_INDEX_PARAM };\n\ninterface Frame {\n getter: Pattern;\n row: StateRow | null;\n untracked: number;\n /** The evaluation this frame runs (`$eq` tells its keys from an earlier evaluation's). */\n epoch: number;\n /** What a root getter's evaluation read (Engine.prune). */\n reads: Pattern[];\n}\n\n/** Getter evaluations so far (each frame takes the next: an evaluation's identity). */\nlet evals = 0;\n\n/** A `$eq` subscription of a getter occurrence, kept on its row (or the engine, at the root). */\nexport interface EqEntry {\n source: Pattern;\n key: unknown;\n sub: EqSub;\n epoch: number;\n}\n\n/** A drain that keeps producing work this many times in a row is an update loop. */\nexport const MAX_DRAIN_PASSES = 32;\n/**\n * Drains in a row that rendering itself started (an element's write-back, a write in\n * `$renderedCallback`) beyond this many are an update loop (as @wcstack/state 3.3.x).\n */\nexport const MAX_RENDER_CHAIN = 100;\n/** Nested getter evaluations deeper than this are a runaway chain. */\nconst MAX_GETTER_DEPTH = 128;\n\nexport type Visit = (getter: Pattern, row: StateRow | null) => boolean;\n\n/** The value of `k` in `m`, made and set first when there is none (`make`: a shared factory, not a closure per call). */\nfunction upsert<K, V>(m: { get(k: K): V | undefined; set(k: K, v: V): unknown }, k: K, make: () => V): V {\n let v = m.get(k);\n if (v === undefined) m.set(k, (v = make()));\n return v;\n}\nconst newSet = <T>(): Set<T> => new Set<T>();\nconst newArray = <T>(): T[] => [];\n\n/**\n * Whether an array holds one object at two positions (F26, `items: [o, o]`), found when a write into a\n * row's object first needs it: once per array, so the writes after it stay O(1). An element written in\n * place drops the answer.\n */\nconst twice = new WeakMap<unknown[], boolean>();\nfunction holdsTwice(arr: unknown[]): boolean {\n let v = twice.get(arr);\n if (v === undefined) {\n const seen = new Set<unknown>();\n twice.set(arr, v = arr.some((x) => Object(x) === x && (seen.has(x) || !seen.add(x))));\n }\n return v;\n}\n\n/** A promise, or anything with a then(). */\nexport function isThenable(r: any): r is PromiseLike<unknown> {\n return r !== null && typeof r === \"object\" && typeof r.then === \"function\";\n}\n\n/** Map-key equality: Object.is, except +0 and -0 are equal (keys of a Map). */\nfunction sameValueZero(a: unknown, b: unknown): boolean {\n return a === b || (a !== a && b !== b);\n}\n\n/** Drops a `$eq` subscription; a key nobody waits for any more leaves the map (it may be a row's item). */\nfunction unsubEq(source: Pattern, key: unknown, sub: EqSub): void {\n const set = source.eqSubs?.get(key);\n if (set !== undefined && set.delete(sub) && set.size === 0) source.eqSubs!.delete(key);\n}\n\nfunction dig(v: any, segs: readonly string[]): unknown {\n for (let i = 0; i < segs.length; i++) {\n if (v == null) return undefined;\n v = v[segs[i]];\n }\n return v;\n}\n\n/** The row at `depth` on the chain of `row` (itself or an ancestor), or null. */\nexport function rowAt(row: StateRow | null, depth: number): StateRow | null {\n while (row !== null && row.list.depth > depth) row = row.list.parentRow;\n return row !== null && row.list.depth === depth ? row : null;\n}\n\n/** The context row of `p`'s list at depth `k` — null when the context is a row of another list. */\nfunction ctxRow(ctx: StateRow | null, p: Pattern, k: number): StateRow | null {\n const r = rowAt(ctx, k);\n return r !== null && r.list.pattern === p.lists[k] ? r : null;\n}\n\n/**\n * One engine per <wcs-state>. It owns everything reachable from its state: the\n * patterns, the lists and their rows, the bindings, the update queue. Nothing is keyed\n * by the state element, because nothing is shared between engines.\n */\nexport class Engine implements ReconcileHooks {\n target!: Record<string, any>;\n /** `$behavior` (fixed at construction): `{{ }}` text, the same-value guard, direction-aware initial sync. */\n mustache!: boolean;\n guard!: boolean;\n directional!: boolean;\n readonly patterns: PatternTable;\n readonly strategy: Strategy;\n readonly proxy: Record<string, any>;\n /** Number of row-level getter slots. */\n slotCount = 0;\n /** Evaluation context: the row a getter / method / setter runs for. */\n ctx: StateRow | null = null;\n /** Writes throw while > 0: a readonly createState callback, or a getter being evaluated. */\n readonlyDepth = 0;\n /**\n * Top-level keys a re-set dropped (the old state had them, the new one lacks them): they read as\n * undefined, not as keys never declared (read; the diagnostics add-on reads it too). Kept here — the\n * author's state object is not written to (it may be frozen, or a Proxy that refuses).\n */\n readonly dropped = new Set<string>();\n /** The node the bindings were mounted on (delegated listeners live here); none before the mount. */\n root?: Node;\n /** Delegated event types → the property (per engine) their element handlers are stored under. */\n private readonly delegated = new Map<string, symbol>();\n /** Property (per engine) on a block's top node(s) holding the block, for delegated events. */\n readonly blockKey = Symbol(\"wcs.block\");\n /** The <wcs-state> element (`this.$stateElement`). */\n element: unknown = null;\n /**\n * A mounted component's (scopes add-on): a function read off the proxy itself, made to run on it\n * when called detached — the proxy is `element.state`, and `const { toggle } = element.state`\n * works (3.x #331). Undefined (or no answer): as it is.\n */\n declare bound?: (fn: (...args: any[]) => unknown) => unknown;\n /** `$command`: the command tokens declared in `$commandTokens`. */\n commands!: Readonly<Record<string, Token>>;\n /** The event tokens declared in `$eventTokens`, with the `$on` handlers subscribed. */\n events!: Map<string, Token>;\n /** Binding failures of the current drain, reported after it (`$errorCallback` or console). */\n private errors: [unknown, Binding][] = [];\n /** Paths applied in the current drain, for `$renderedCallback` (collected only when declared). */\n rendered: Map<string, number[][]> | null = null;\n private frames: Frame[] = [];\n private depthNow = 0;\n private top: Frame | null = null;\n readonly rootLists = new Map<Pattern, StateList>();\n readonly rootBindings = new Map<Pattern, Set<Binding>>();\n private queue: Binding[] = [];\n private dirtyLists: StateList[] = [];\n /** Lists over a changed getter, re-synced at the start of the next drain pass. */\n private staleLists: StateList[] = [];\n private scheduled = false;\n private draining = false;\n /** The lists over each array (only while more than one list has it do writes mirror). */\n private readonly listsByArray = new WeakMap<unknown[], StateList[]>();\n /** Drains in a row that rendering started (MAX_RENDER_CHAIN); a pause between tasks ends it. */\n private chain = 0;\n /**\n * For the drain the write-backs of an apply an arbiter deferred start: its place in that apply's\n * chain (0: none). The pause before the apply ends the task's chain, not this one. Only what the\n * apply writes synchronously is carried: an async `$renderedCallback` writing after an `await`\n * starts a task chain again, so such a loop runs one lap per arbiter task and is never cut.\n */\n private carried = 0;\n /** This chain was reported as not settling within a drain (#11): reported once a chain. */\n private unsettled = false;\n /** Since the last drain started: a write rendering fed back / a write from code (which ends a chain). */\n private fedBack = false;\n private codeWrote = false;\n /**\n * Inside `$renderedCallback` (until an async one settles) or a `$watch` handler: its writes are\n * reactions, fed back like an element's (MAX_RENDER_CHAIN).\n */\n feeding = 0;\n private readonly unchainFn = () => {\n this.chain = 0;\n this.unsettled = false;\n };\n private readonly renderedFn = () => {\n this.feeding--;\n };\n // out-parameters of resolve()\n private rp: Pattern | null = null;\n private rr: StateRow | null = null;\n\n private readonly drainFn = () => this.drain();\n private readonly deliverFn = (handler: (...a: unknown[]) => unknown, args: unknown[]) => handler(this.proxy, ...args);\n /** `$eq` subscriptions of root-level getters. */\n private readonly rootEqSubs: EqEntry[] = [];\n /** Patterns made, or no longer read by a root getter, since the last sweep: what it looks at. */\n private loose: Pattern[] = [];\n /** The `$` functions of the state (`this.$eq`, …), by name. */\n private readonly api: Record<string, unknown> = {\n $untracked: (fn: () => unknown) => {\n const f = this.top;\n if (f === null) return fn();\n f.untracked++;\n try {\n return fn();\n } finally {\n f.untracked--;\n }\n },\n $eqIndex: (path: string, level = 1) => {\n const row = rowAt(this.ctx, level);\n if (row === null) raise(M.EqIndexNoRow, [path]);\n const source = this.pattern(path);\n // a getter (or a path under one) changes without a write: an ordinary tracked read, and the\n // row's index is read as `$1` reads it (a moved row compares again)\n if (source.getter !== null || source.underGetter) {\n this.watchIndex(level);\n return row.index === this.read(source, null);\n }\n const f = this.top;\n if (f !== null) {\n const g = f.getter;\n const watchers = source.eqIndexWatchers ?? (source.eqIndexWatchers = []);\n if (!watchers.some((w) => w.getter === g && w.level === level)) {\n watchers.push({ getter: g, level });\n const listP = g.lists[level]!;\n (listP.eqIndexKeys ?? (listP.eqIndexKeys = [])).push({ source, getter: g });\n }\n }\n return row.index === this.readUntracked(source, null);\n },\n $eq: (path: string, key: unknown) => this.eq(path, key),\n $eqPath: (path: string, keyPath: string) => {\n const kp = this.pattern(keyPath);\n return this.eq(path, this.readUntracked(kp, rowAt(this.ctx, kp.depth)));\n },\n $dependOn: (path: string) => {\n this.resolve(unbound(path), this.ctx);\n if (this.top !== null && this.top.untracked === 0) this.track(this.rp!, this.rr, this.top);\n },\n $getAll: (path: string, indexes?: number[]) => this.getAll(path, indexes),\n $setAll: (path: string, indexes: number[], value: unknown, options?: { spread?: boolean }) =>\n this.setAll(path, indexes, value, options),\n // $resolve(path, indexes) reads; $resolve(path, indexes, value) writes (the argument count decides)\n $resolve: (...args: unknown[]) => {\n const path = unbound(args[0] as string);\n const indexes = (args[1] ?? []) as number[];\n const p = this.pattern(path, true);\n this.checkArity(\"$resolve\", path, p, indexes, true);\n const row = this.rowOf(p, indexes, null);\n if (args.length < 3) return this.read(p, row);\n this.write(p, row, args[2]);\n },\n $postUpdate: (path: string) => {\n this.resolve(unbound(path), this.ctx);\n const p = this.rp!;\n const row = this.rr;\n // changed in place: an element is what its array holds now\n if (p.last === WILDCARD && row !== null) {\n row.item = row.list.arr![row.index];\n twice.delete(row.list.arr!);\n this.strategy.resetRow(row);\n }\n this.touched(p, row);\n if (row !== null) this.mirror(row, p, undefined, row.item, false);\n // the value before is not known: the `$eq` / `$eqIndex` occurrences under every key change\n if (p.depth === 0) this.rekeyEqUnder(p, undefined, undefined, true);\n this.landed(p, row, undefined, undefined, false);\n },\n };\n\n constructor(target: Record<string, any>, strategy: Strategy) {\n this.strategy = strategy;\n this.patterns = new PatternTable((p) => {\n this.loose.push(p);\n this.onPatternCreated(p);\n });\n this.loadTarget(target);\n const engine = this;\n // the handler reads engine.target, not the proxy's target (a stand-in): a re-set swaps the state.\n // So do `in`, `delete`, `Object.keys(this)`, `instanceof` (the forwarded traps below); a descriptor\n // is reported configurable, as the stand-in has none (a frozen state's would break the invariants)\n const handler: ProxyHandler<object> = {\n getOwnPropertyDescriptor(_t, key) {\n const d = Reflect.getOwnPropertyDescriptor(engine.target, key);\n if (d) d.configurable = true;\n return d;\n },\n get(_t, key, receiver) {\n const t = engine.target;\n if (typeof key === \"symbol\") return Reflect.get(t, key);\n if (key.charCodeAt(0) === 36 /* $ */) return engine.dollar(key);\n if (key.indexOf(\".\") < 0) {\n const p = engine.patterns.peek(key);\n if (p === undefined || p.getter === null) {\n const v = t[key];\n // (a view of the proxy — the readonly createStateAsync's — gets it as it is)\n if (typeof v === \"function\") return (receiver === engine.proxy && engine.bound?.(v)) || v;\n }\n // a known top-level key: no path to parse\n if (p !== undefined && p.depth === 0) return engine.read(p, null);\n }\n engine.resolve(key, engine.ctx);\n return engine.read(engine.rp!, engine.rr);\n },\n set(_t, key, value) {\n if (typeof key === \"symbol\") return Reflect.set(engine.target, key, value);\n engine.resolve(unbound(key), engine.ctx);\n engine.write(engine.rp!, engine.rr, value);\n return true;\n },\n };\n for (const trap of [\"has\", \"ownKeys\", \"deleteProperty\", \"defineProperty\", \"getPrototypeOf\"]) {\n (handler as any)[trap] = (_t: object, ...a: unknown[]) => (Reflect as any)[trap](engine.target, ...a);\n }\n this.proxy = new Proxy({}, handler);\n }\n\n // ---------------------------------------------------------------- patterns\n\n /**\n * The pattern of `path`, pinned: whoever asks keeps it (a binding, a list, an add-on). `loose`: a\n * path read or written (the proxy, `$resolve`, `$getAll`), swept once it holds nothing.\n */\n pattern(path: string, loose?: boolean): Pattern {\n const p = this.patterns.get(path);\n if (!loose) p.pinned = true;\n return p;\n }\n\n private registerAccessors(target: object): void {\n const seen = new Set<string>();\n for (let o: object | null = target; o !== null && o !== Object.prototype; o = Object.getPrototypeOf(o)) {\n for (const key of Object.getOwnPropertyNames(o)) {\n if (seen.has(key)) continue;\n seen.add(key);\n const d = Object.getOwnPropertyDescriptor(o, key)!;\n if (d.get === undefined && d.set === undefined) continue;\n const p = this.pattern(key);\n p.getter = d.get ?? null;\n p.setter = d.set ?? null;\n if (p.getter !== null && p.depth > 0) p.slot = this.slotCount++;\n }\n }\n // accessors registered after their descendants were created: recompute\n for (const p of this.patterns.all()) this.onPatternCreated(p);\n }\n\n private onPatternCreated(p: Pattern): void {\n // (the recursion add-on makes its `**` templates without this, while the state registers)\n if (p.path.includes(\"**\")) recursionUnsupported(p.path);\n // a path through an object's prototype would read and write every object's (once per path)\n if (p.last === \"__proto__\" || p.last === \"prototype\") raise(M.UnsafeSegment, [p.path]);\n const parent = p.parent;\n p.underGetter = parent !== null && p.last !== WILDCARD && parent.depth === p.depth &&\n (parent.getter !== null || parent.underGetter);\n if (p.getter === null) this.markupAccessor(p);\n }\n\n /**\n * Markup names two things the tree does not hold, as `this[...]` reads them: an explicit index\n * (`items.0.v`, the row at that index now) and a loop index (`items.*.$1`, `$1` in a row).\n * Their patterns (only markup makes them: the proxy parses an index into a row) read — and an\n * index path writes — as the proxy resolves them, so the reads are tracked like a getter's.\n * Where a number is a key of an object (`sales.2024.total`), the path resolves to the pattern\n * itself (rowOf): it is read and written through its parent.\n */\n private markupAccessor(p: Pattern): void {\n const path = p.path;\n const last = p.last;\n if (INDEX_PARAM.test(last)) {\n p.getter = function (this: any) {\n return this[last];\n };\n } else {\n const segs = path.split(\".\");\n // (a leading numeric segment is a root key, not an index: parsePath)\n const i = segs.findIndex((s, j) => j > 0 && s.charCodeAt(0) >= 48 && s.charCodeAt(0) <= 57);\n // none, or a `*` after it: a row of a list over the index path (`for: groups.0.items`) reads its\n // own item, and a write through the index reaches it as a list with the same array (mirror)\n if (i < 0 || segs.indexOf(WILDCARD, i) >= 0) return;\n // (the parent read from the context row: the occurrence's, the setter's — at p.depth)\n p.getter = () => {\n this.resolve(path, this.ctx);\n if (this.rp !== p) return this.read(this.rp!, this.rr);\n return (this.read(p.parent!, this.ctx) as any)?.[last];\n };\n p.setter = (v: unknown) => {\n this.resolve(path, this.ctx);\n if (this.rp !== p) return this.write(this.rp!, this.rr, v);\n const o = this.read(p.parent!, this.ctx) as any;\n if (o == null) raise(M.ParentNotObject, [path, o]);\n o[last] = v;\n };\n }\n p.markup = true;\n if (p.depth > 0) p.slot = this.slotCount++;\n }\n\n // ---------------------------------------------------------------- lists\n\n /** The list of list pattern `p` in `row` (null: a root list), made on first use, synced. */\n childList(row: StateRow | null, p: Pattern): StateList {\n const m = row === null ? this.rootLists : (row.children ??= new Map());\n let l = m.get(p);\n if (l === undefined) m.set(p, (l = new StateList(p, row)));\n // (the list holds it: a path's read made it loose, `users.3.name` through `users`)\n p.pinned = true;\n this.sync(l);\n return l;\n }\n\n /** Syncs `l`; a failure (a missing key, a getter that throws) is its for binding's, and it keeps its rows. */\n private trySync(l: StateList): void {\n try {\n this.sync(l);\n } catch (error) {\n this.failAt(error, l.pattern.path, l.view?.anchor ?? null, \"for\");\n }\n }\n\n /** Reconciles a list's rows with the current value of its pattern. */\n sync(l: StateList): void {\n const value = this.readUntracked(l.pattern, l.parentRow);\n const before = l.arr;\n if (value === before) return;\n // out of the lists over its array before (filed again under the new one below)\n this.unfile(l);\n const old = reconcile(l, value, this);\n if (old === null) return;\n // filed under its array: lists that share an array mirror writes\n // (a value that is not an array reconciles against a stand-in: nothing to share)\n if (l.arr === value) {\n const same = upsert(this.listsByArray, value as unknown[], newArray<StateList>);\n same.push(l);\n // (the rows it kept are up to date: a write into an object reached every list showing it, F26)\n if (same.length > 1) for (const x of same) x.shared = true;\n }\n hooks.listSynced?.(this, l, old);\n if ((l.view !== null || l.extra !== null) && !l.queued) {\n l.queued = true;\n this.dirtyLists.push(l);\n this.schedule();\n }\n const keys = l.pattern.eqIndexKeys;\n if (keys !== null) {\n for (const { source, getter } of keys) {\n const sel = this.readUntracked(source, null) as number;\n const before = old[sel];\n const after = l.rows[sel];\n if (before === after) continue;\n if (before !== undefined && before.alive) this.invalidateUnder(getter, before);\n if (after !== undefined) this.invalidateUnder(getter, after);\n }\n }\n }\n\n indexChanged(row: StateRow): void {\n this.strategy.onIndexChange(this, row);\n }\n\n rowRemoved(row: StateRow): void {\n row.alive = false;\n const subs = row.eqSubs;\n if (subs !== null) {\n for (const e of subs) unsubEq(e.source, e.key, e.sub);\n row.eqSubs = null;\n }\n // the rows of its nested lists go with it, and the lists leave the ledger of their arrays\n if (row.children !== null) {\n for (const l of row.children.values()) {\n this.unfile(l);\n for (const r of l.rows) this.rowRemoved(r);\n }\n }\n }\n\n /** Takes `l` out of the lists over its array; one left alone with it no longer mirrors. */\n private unfile(l: StateList): void {\n const was = this.listsByArray.get(l.arr!);\n if (was === undefined) return;\n was.splice(was.indexOf(l) >>> 0, 1);\n l.shared = false;\n if (was.length === 1) was[0].shared = false;\n }\n\n // ---------------------------------------------------------------- resolve / read\n\n /** Splits a concrete path into (pattern, row) — written to this.rp / this.rr. */\n resolve(path: string, ctx: StateRow | null): void {\n const parsed = parsePath(path);\n const p = (this.rp = this.pattern(parsed.pattern, true));\n const idx = parsed.indexes;\n this.rr = p.depth === 0 ? null : idx === null ? ctxRow(ctx, p, p.depth) : this.rowOf(p, idx, ctx, path);\n }\n\n /**\n * The row at p.depth addressed by `idx` (one index per `*`; -1 takes the one of `ctx`). The pattern\n * it is at goes to this.rp — set last: finding the row can sync a list over a getter, whose\n * evaluation resolves paths too. An index of `path` (the proxy's) into an object that is not an\n * array (`sales.2024.total`) is a key: the pattern keeps it as written (into null or a string, it\n * has no row).\n */\n private rowOf(p: Pattern, idx: readonly number[], ctx: StateRow | null, path?: string): StateRow | null {\n let row: StateRow | null = null;\n for (let k = 1, j = 0, v; k <= p.depth; k++) {\n const listP = p.lists[k]!;\n const list = this.childList(row, listP);\n let i = idx[j++];\n if (i < 0) i = ctxRow(ctx, p, k)?.index ?? -1;\n else if (path && list.arr === EMPTY && Object((v = this.readUntracked(listP, row))) === v) {\n const segs = p.path.split(\".\");\n const n = listP.path.split(\".\").length;\n segs[n] = path.split(\".\")[n];\n p = this.pattern(segs.join(\".\"), true);\n k--;\n continue;\n }\n row = list.rows[i] ?? null;\n if (row === null) break;\n }\n this.rp = p;\n return row;\n }\n\n /** Raw data read (no getter, no tracking). `row` is the row at p.depth. */\n readData(p: Pattern, row: StateRow | null): unknown {\n return p.depth === 0 ? dig(this.target, p.tail) : row === null ? undefined : dig(row.item, p.tail);\n }\n\n /** Tracked read. `row` is the row at p.depth (null at the root). */\n read(p: Pattern, row: StateRow | null): unknown {\n const f = this.top;\n if (f !== null && f.untracked === 0) this.track(p, row, f);\n if (p.getter !== null) return this.strategy.readGetter(this, p, row);\n if (p.underGetter) {\n const parent = this.read(p.parent!, row) as any;\n return parent == null ? undefined : parent[p.last];\n }\n // (`then` / `toJSON` are probes — await, JSON.stringify — not reads of the state: undefined)\n if (p.parent === null && !(p.last in this.target) && !this.dropped.has(p.last) && p.last !== \"then\" && p.last !== \"toJSON\") {\n raise(M.PathMissing, [p.path], p.last, Object.keys(this.target));\n }\n return this.readData(p, row);\n }\n\n readUntracked(p: Pattern, row: StateRow | null): unknown {\n const f = this.top;\n if (f === null) return this.read(p, row);\n f.untracked++;\n try {\n return this.read(p, row);\n } finally {\n f.untracked--;\n }\n }\n\n private track(p: Pattern, row: StateRow | null, f: Frame): void {\n const g = f.getter;\n p.addDependent(g);\n // a root getter's reads (once each, but around a nested one): what it no longer reads goes (prune)\n if (g.depth === 0) {\n if (p.mark !== f.epoch) {\n p.mark = f.epoch;\n f.reads.push(p);\n }\n } else if (p.depth > 0 && rowAt(row, Math.min(p.depth, g.depth)) !== rowAt(f.row, Math.min(p.depth, g.depth))) {\n (g.crossSources ?? (g.crossSources = new Set())).add(p);\n }\n }\n\n /** Evaluates a getter occurrence with dependency tracking. Caching is the strategy's. */\n evalGetter(g: Pattern, row: StateRow | null): unknown {\n // frames are reused by depth: an evaluation allocates nothing of its own\n for (let i = 0; i < this.depthNow; i++) {\n const f = this.frames[i];\n if (f.getter === g && f.row === row) raise(M.GetterCycle, [g.path]);\n }\n if (this.depthNow >= MAX_GETTER_DEPTH) raise(M.GetterDepth, [g.path]);\n const depth = this.depthNow++;\n this.readonlyDepth++;\n const frame = (this.frames[depth] ??= { getter: g, row, untracked: 0, epoch: 0, reads: [] });\n frame.getter = g;\n frame.row = row;\n frame.untracked = 0;\n frame.epoch = ++evals;\n frame.reads.length = 0;\n const outer = this.top;\n this.top = frame;\n const prev = this.ctx;\n this.ctx = row;\n try {\n const v = g.getter!.call(this.proxy);\n if (g.depth === 0) this.prune(g, frame);\n return v;\n } finally {\n this.readonlyDepth--;\n this.depthNow--;\n this.top = outer;\n this.ctx = prev;\n frame.row = null;\n }\n }\n\n /**\n * A root getter evaluated (without throwing): the top-level sources it did not read this time are no\n * longer its sources. Its one occurrence is the whole getter, so what it reads is what it depends on\n * (a row getter's sources stay the union over its rows). A key built from data it read before\n * (`this[\"users.\" + this.selectedId]`) then holds nothing, and is swept. One holding an array stays:\n * a write into an object that array shares with the one the getter returns reaches the rows of the\n * list over the getter through it (mirror — F26, 3.x #362).\n */\n private prune(g: Pattern, f: Frame): void {\n const e = f.epoch;\n for (const s of f.reads) s.mark = e;\n g.sources = g.sources.filter((s) => s.mark === e || s.depth > 0 ||\n (!s.underGetter && Array.isArray(s.getter !== null ? s.rootValue : this.readData(s, null))) || this.unlink(s, g));\n }\n\n /** `getter` reads `s` no more (its side is the caller's): `s` may hold nothing now. False (filtered out). */\n private unlink(s: Pattern, getter: Pattern): false {\n s.dropDependent(getter);\n this.loose.push(s);\n return false;\n }\n\n /**\n * After a drain: the patterns only a path made that hold nothing now leave the table, so it grows\n * with the state's shape, not with every key a path was ever built with. A pattern stays while it\n * is pinned (Engine.pattern: `$eqIndex`'s source among them), at the top level (the state's own\n * keys), has children, is read by a getter, is `$eq`'s source, or has an accessor that is not the\n * engine's own for an index path at the top level (one in a row has a cache slot).\n */\n private sweep(): void {\n for (let c = this.loose; c.length > 0; c = this.loose) {\n this.loose = [];\n const parents = new Set<Pattern>();\n for (const p of c) {\n if (p.pinned || p.dead || p.parent === null || p.children.length > 0 || p.dependents.length > 0 ||\n (p.getter !== null && !(p.markup && p.slot < 0)) || p.eqSubs !== null) continue;\n p.dead = true;\n this.patterns.drop(p);\n parents.add(p.parent);\n // an index path's accessor read its parent\n for (const s of p.sources) this.unlink(s, p);\n }\n for (const q of parents) if (!(q.children = q.children.filter((x) => !x.dead)).length) this.loose.push(q);\n }\n }\n\n /** The getter evaluating now reads the index of its row at level `n`: a move of that row re-evaluates it. */\n private watchIndex(n: number): void {\n const f = this.top;\n if (f !== null && f.untracked === 0) {\n const g = f.getter;\n const listP = g.lists[n];\n if (listP) {\n const w = listP.indexWatchers ?? (listP.indexWatchers = []);\n if (!w.includes(g)) w.push(g);\n }\n }\n }\n\n private dollar(key: string): unknown {\n const c = key.charCodeAt(1);\n if (c >= 48 && c <= 57) {\n const n = key.length === 2 ? c - 48 : INDEX_PARAM.test(key) ? +key.slice(1) : 0;\n if (n < 1 || n > MAX_INDEX_PARAM) {\n raise(M.IndexParamRange, [key]);\n }\n this.watchIndex(n);\n return rowAt(this.ctx, n)?.index;\n }\n const fn = this.api[key];\n if (fn !== undefined) return fn;\n // (the 3.x names 4.0 removed, $trackDependency and $untrackDependency, are the diagnostics add-on's)\n switch (key) {\n case \"$stateElement\":\n return this.element;\n case \"$command\":\n return this.commands;\n }\n return hooks.dollar?.(this, key);\n }\n\n /**\n * `$eq(path, key)`: is the value of `path` equal to `key`? Inside a getter the occurrence\n * subscribes under `key` instead of depending on `path`: a write to `path` re-evaluates\n * only the occurrences keyed under its old and its new value. A `path` that is a getter\n * (or under one) changes without a write, so it falls back to an ordinary tracked read.\n */\n private eq(path: string, key: unknown): boolean {\n this.resolve(path, this.ctx);\n const source = this.rp!;\n const row = this.rr;\n if (source.getter !== null || source.underGetter || source.depth > 0) return sameValueZero(this.read(source, row), key);\n const f = this.top;\n if (f !== null && f.untracked === 0) this.subscribeEq(source, key, f);\n return sameValueZero(this.readUntracked(source, null), key);\n }\n\n /**\n * Subscribes the occurrence evaluating in `f` under `key`. A key it subscribed in an earlier\n * evaluation and not in this one moved; one of this evaluation stays (`$eq(p, a) || $eq(p, b)`).\n */\n private subscribeEq(source: Pattern, key: unknown, f: Frame): void {\n const getter = f.getter;\n const row = f.row;\n const list = row === null ? this.rootEqSubs : (row.eqSubs ?? (row.eqSubs = []));\n for (let i = 0; i < list.length; i++) {\n const e = list[i];\n if (e.sub.getter !== getter || e.source !== source) continue;\n if (sameValueZero(e.key, key)) {\n e.epoch = f.epoch;\n return;\n }\n if (e.epoch !== f.epoch) {\n unsubEq(source, e.key, e.sub);\n list.splice(i--, 1);\n }\n }\n const sub: EqSub = { getter, row };\n upsert((source.eqSubs ??= new Map()), key, newSet<EqSub>).add(sub);\n list.push({ source, key, sub, epoch: f.epoch });\n }\n\n /**\n * A root write to `p` (or an object above a `$eq` / `$eqIndex` source): re-key every source at or\n * under it. `all` (`$postUpdate`, which knows no value before): every key.\n */\n private rekeyEqUnder(p: Pattern, before: unknown, after: unknown, all?: boolean): void {\n this.forSubtree(p, (q) => {\n const map = q.eqSubs;\n if (map === null && q.eqIndexWatchers === null) return;\n const rest = q === p ? [] : q.path.slice(p.path.length + 1).split(\".\");\n const b = dig(before, rest);\n const a = dig(after, rest);\n if (q.eqIndexWatchers !== null) this.rekeyEqIndex(q, b, a, all);\n // the occurrences keyed under the value before and the value after\n if (map !== null) for (const k of all ? map.keys() : [b, a]) {\n const set = map.get(k);\n if (set === undefined) continue;\n for (const sub of set) {\n if (sub.row !== null && !sub.row.alive) {\n unsubEq(q, k, sub);\n continue;\n }\n this.strategy.invalidate(this, sub.getter, sub.row);\n }\n }\n });\n }\n\n // ---------------------------------------------------------------- write\n\n /**\n * `occurrence`: an event-semantics write, applied even when equal to the current value.\n * `element`: an element wrote it back (a two-way input, a wc-bindable event), not code.\n */\n write(p: Pattern, row: StateRow | null, value: unknown, occurrence = false, element = false): void {\n if (this.readonlyDepth > 0) raise(M.Readonly);\n if (element || this.feeding > 0) this.fedBack = true;\n else this.codeWrote = true;\n if (hooks.beforeWrite?.(this, p, row, value, element)) return;\n // a setter's write is not a data write: the add-ons hear of it without old and new values\n if (p.setter !== null) {\n // a setter that throws after it wrote: what it wrote still lands (3.x #361), and the error\n // propagates. One that throws before writing anything lands as well, as one that returns\n // without writing does (3.x notifies in `finally` too): `$watch` hears of it, a getter recomputes\n try {\n this.callAt(p.setter, row, [value]);\n } finally {\n this.landed(p, row, undefined, undefined, false, element);\n }\n return;\n }\n if (p.getter !== null) raise(M.GetterWithoutSetter, [p.path]);\n if (p.depth > 0 && row === null) raise(M.NoRow, [p.path]);\n // under a getter, the value before is read through it (the data has no such path)\n const old = p.underGetter ? this.readUntracked(p, row) : this.readData(p, row);\n if (!occurrence && this.guard && Object.is(old, value) && Object(value) !== value) return;\n if (p.last === WILDCARD) {\n // element write: the position keeps its row, the row takes the new value\n const r = row!;\n (r.list.arr as unknown[])[r.index] = value;\n twice.delete(r.list.arr!);\n r.item = value;\n this.strategy.resetRow(r);\n } else {\n const parent = (p.tail.length === 1\n ? (p.depth === 0 ? this.target : row!.item)\n : this.readUntracked(p.parent!, row)) as any;\n if (parent == null) raise(M.ParentNotObject, [p.path, parent]);\n parent[p.last] = value;\n }\n this.syncListsUnder(p, row);\n if (row !== null) this.mirror(row, p, old, value);\n if (p.depth === 0) this.rekeyEqUnder(p, old, value);\n this.landed(p, row, old, value, true, element);\n }\n\n /** The lists over `l`'s array now (`l` among them), none of a removed row. */\n private sharing(l: StateList): StateList[] {\n return (this.listsByArray.get(l.arr!) ?? []).filter((m) => m.arr === l.arr && (m.parentRow === null || m.parentRow.alive));\n }\n\n /**\n * A write into row `row` of a list whose array another list has too (`for: shown` over a getter\n * returning `todos`, `for: groups.0.items`): the other list's row at the same position shows it.\n *\n * A write into the row's object (not the element) reaches it wherever else it is (F26, `get\n * shown()` filtering `todos`). From the array holding it (the list's own, or one its getter read\n * at a data path), the write goes to the getters that read that array and returned one holding the\n * object (a filter, a sort, a slice: evaluated again), on down their dependents, and to the rows\n * holding the object in the lists over those arrays. A getter whose array does not hold the object\n * is not reached: it read the array, not the object (the dependency boundary).\n */\n private mirror(row: StateRow, p: Pattern, old: unknown, value: unknown, direct = true): void {\n const l = row.list;\n const suffix = p.path.slice(l.pattern.path.length + 2);\n // a write into the row's object, which its array holds at another position too (F26): those rows show it\n const dup = suffix !== \"\" && holdsTwice(l.arr!);\n // another list has its array, or it is over a getter or a getter reads it: its object may be in\n // another array too. A plain list pays these checks only\n if (!dup && !l.shared && l.pattern.getter === null && !l.pattern.dependents.length) return;\n const o = row.item;\n const land = (m: StateList, r: StateRow | undefined): void => {\n if (r === undefined || r === row) return;\n const mp = this.pattern(`${m.pattern.path}.*${suffix}`, true);\n if (suffix === \"\") {\n r.item = value;\n this.strategy.resetRow(r);\n }\n if (direct) this.syncListsUnder(mp, r);\n else this.touched(mp, r);\n this.landed(mp, r, old, value, direct);\n };\n for (const m of this.sharing(l)) {\n land(m, m.rows[row.index]);\n if (dup) for (const r of m.rows) if (r.item === o && r.index !== row.index) land(m, r);\n }\n if (suffix === \"\") return;\n // (a leaf write: the row's item is an object. The lists over its own array were reached above)\n const seen = new Set<unknown>([l.arr]);\n const has = (a: unknown): a is unknown[] => Array.isArray(a) && a.includes(o);\n const down = (arr: unknown, deps: Pattern[]): void => {\n if (!seen.has(arr) && seen.add(arr)) for (const m of this.listsByArray.get(arr as unknown[]) ?? []) for (const r of m.rows) if (r.item === o) land(m, r);\n // each getter once (a cycle across evaluations ends). One passing the array on (`get shown()\n // { return this.todos }`) is not evaluated again: the lists over it were reached already. One\n // reached before (earlier in the batch, or just now through a getter it reads) is evaluated again\n // in the drain, its list synced then: the rows it keeps are those its list shows now\n for (const g of deps) {\n let v = g.rootValue;\n const stale = v === DIRTY;\n if (stale) v = this.rootLists.get(g)?.arr;\n if ((stale || has(v)) && !seen.has(g.dependents) && seen.add(g.dependents)) {\n if (!stale && v !== arr) this.strategy.invalidate(this, g, null);\n down(v, g.dependents);\n }\n }\n };\n const up = (g: Pattern): void => {\n for (const s of g.sources) {\n if (seen.has(s) || !seen.add(s)) continue;\n if (s.getter !== null) up(s);\n else if (!s.underGetter) {\n const a = this.readData(s, null);\n if (has(a)) down(a, s.dependents);\n }\n }\n };\n if (l.pattern.getter !== null) up(l.pattern);\n else down(l.arr!, l.pattern.dependents);\n }\n\n /**\n * `$postUpdate`: what is at `p` changed in place. Its lists are synced as a write syncs them, and\n * their rows (and the rows of the lists over the same arrays) show it again: a write reaches a\n * row's bindings through the row it replaced, an in-place change through none.\n */\n private touched(p: Pattern, row: StateRow | null): void {\n this.forListsUnder(p, row, (l) => {\n this.sync(l);\n for (const m of l.shared ? this.sharing(l) : [l]) {\n const e = this.pattern(`${m.pattern.path}.*`);\n for (const r of m.rows) {\n this.enqueueBound(e, r);\n this.touched(e, r);\n }\n }\n });\n }\n\n private syncListsUnder(p: Pattern, row: StateRow | null): void {\n const ls = row === null ? this.rootLists : row.children;\n if (ls !== null) for (const l of ls.values()) if (l.pattern.isUnder(p)) this.sync(l);\n }\n\n /** The lists of `row` (the root lists at null) whose pattern is `p` or under it. */\n private forListsUnder(p: Pattern, row: StateRow | null, fn: (l: StateList) => void): void {\n const ls = row === null ? this.rootLists : row.children;\n if (ls !== null) for (const l of ls.values()) if (l.pattern.isUnder(p)) fn(l);\n }\n\n /**\n * `$eqIndex(source, level)` compares the index of the row at `level`: when `source` changes, the\n * getter's occurrences under the rows at that level with the old or the new index change (`all`:\n * under every row).\n */\n private rekeyEqIndex(source: Pattern, before: unknown, after: unknown, all?: boolean): void {\n for (const { getter, level } of source.eqIndexWatchers!) {\n this.forAllLists(getter.lists[level]!, (l) => {\n for (const k of all ? l.rows.keys() : [before, after]) {\n const r = typeof k === \"number\" ? l.rows[k] : undefined;\n if (r !== undefined) this.invalidateUnder(getter, r);\n }\n });\n }\n }\n\n /** Invalidates getter `g`'s occurrences at or under `row` (row.depth <= g.depth). */\n private invalidateUnder(g: Pattern, row: StateRow): void {\n if (row.list.depth === g.depth) this.strategy.invalidate(this, g, row);\n else this.forRowsUnder(row, g, (r) => this.strategy.invalidate(this, g, r));\n }\n\n /** A write landed at (p, row): the add-ons hear of it, then its dependents. */\n private landed(p: Pattern, row: StateRow | null, old: unknown, value: unknown, direct: boolean, element?: boolean): void {\n hooks.written?.(this, p, row, old, value, direct, element);\n this.changed(p, row);\n }\n\n changed(p: Pattern, row: StateRow | null): void {\n this.strategy.onWrite(this, p, row);\n this.schedule();\n }\n\n /**\n * One listener per event type on the root, dispatching to the delegated element handlers.\n * Returns the property the element's handler is stored under (one symbol per engine and\n * type, so two engines never run each other's handlers).\n */\n delegate(type: string): symbol {\n const known = this.delegated.get(type);\n if (known !== undefined) return known;\n const key = Symbol(`wcs.on${type}`);\n this.delegated.set(type, key);\n const root = this.root!;\n const blockKey = this.blockKey;\n root.addEventListener(type, (e) => {\n for (let n = e.target as any; n !== null && n !== root; n = n.parentNode) {\n // a handler stored on the element (a root-level one, or one a block pinned)\n const fn = n[key];\n if (fn !== undefined) {\n fn(e);\n if (e.cancelBubble) return;\n }\n // a block's top node: the handlers of the block's elements the event passed\n const block = n[blockKey];\n if (block !== undefined && block.alive && block.dispatch(type, e)) return;\n }\n });\n return key;\n }\n\n // ---------------------------------------------------------------- re-set\n\n /**\n * `setInitialState` on an initialized element: the state is replaced whole and every\n * binding is re-applied to it before this returns. Not a write: no `$renderedCallback`.\n * Everything learned from the old state goes (accessors, dependencies, caches, `$eq`\n * keys); rows are kept where their list's array is the same instance.\n */\n reset(target: Record<string, any>): void {\n const old = this.target;\n // a key the old state had (or an earlier re-set dropped) and this one lacks is empty (B8), as a\n // missing path under a key is — not a key never declared, which fails on read: its bindings, lists\n // and getters read undefined, until it is written. Its accessors too: those on a class state's\n // prototype, which for…in does not list, are the top-level patterns with a getter\n const dropped = this.dropped;\n for (const p of this.patterns.all()) if (p.parent === null && p.getter !== null) dropped.add(p.last);\n this.loadTarget(target);\n for (const k in old) if (k[0] !== \"$\") dropped.add(k);\n for (const k of dropped) if (k in target) dropped.delete(k);\n for (const bs of this.rootBindings.values()) for (const b of bs) this.enqueue(b);\n for (const l of this.rootLists.values()) this.resetList(l);\n this.rendered = null;\n try {\n this.drain();\n } finally {\n this.watchRendered();\n }\n hooks.element?.(this, \"reset\");\n }\n\n /** Takes in a state object: at construction, and on a re-set (everything learned from the old one goes). */\n private loadTarget(target: Record<string, any>): void {\n for (const [key, feature] of DECLARATIONS) if (target[key] !== undefined) requireFeature(feature, key);\n // (the 3.x declarations 4.0 removed — $scan, $streams, $updatedCallback — are the diagnostics add-on's)\n const f = target.$features;\n if (f !== undefined) {\n if (!Array.isArray(f)) raise(M.FeaturesNotArray);\n for (const name of f) requireFeature(name, \"$features\");\n }\n // an options object: null and an array are not one (as for bootstrapState's options)\n const c = target.$behavior === undefined ? {} : target.$behavior;\n if (typeof c !== \"object\" || !c || Array.isArray(c)) raise(M.OptionInvalid, [\"state\", \"$behavior\"]);\n for (const key in c) if (!BEHAVIOR_KEYS.includes(key) || typeof c[key] !== \"boolean\") raise(M.OptionInvalid, [\"$behavior\", key]);\n const [mustache, guard, directional] = BEHAVIOR_KEYS.map((key) => c[key] ?? true);\n // a re-set keeps the engine, and what was built by the old options\n if (this.target !== undefined && (mustache !== this.mustache || guard !== this.guard || directional !== this.directional)) raise(M.BehaviorChanged);\n // (read before anything is taken in: a malformed declaration leaves a re-set's old state in place)\n const commands = commandNamespace(target, this.commands);\n const events = eventTokens(target, this.deliverFn);\n this.mustache = mustache;\n this.guard = guard;\n this.directional = directional;\n hooks.declare?.(this, target);\n this.target = target;\n this.slotCount = 0;\n for (const p of this.patterns.all()) p.forget();\n this.rootEqSubs.length = 0;\n this.registerAccessors(target);\n this.commands = commands;\n this.events = events;\n }\n\n private resetList(l: StateList): void {\n // a list that cannot be read (its getter throws) fails alone: the re-set goes on (and ends with its hook)\n this.trySync(l);\n const element = this.pattern(`${l.pattern.path}.*`);\n for (const row of l.rows) {\n row.cache = null;\n row.eqSubs = null;\n this.enqueueBound(element, row);\n if (row.children !== null) for (const c of row.children.values()) this.resetList(c);\n }\n }\n\n // ---------------------------------------------------------------- tokens\n\n /** The loop indexes of `row`, outermost first (`$1`, `$2`, …). */\n indexesOf(row: StateRow | null): number[] {\n const out: number[] = [];\n for (let r = row; r !== null; r = r.list.parentRow) out.unshift(r.index);\n return out;\n }\n\n /** An element event wired with `eventToken.<prop>: <name>` — the token is resolved at fire time. */\n fireEventToken(name: string, event: Event, row: StateRow | null): void {\n const token = this.events.get(name);\n if (token === undefined) raise(M.EventTokenUndeclared, [name], name, this.events.keys());\n token.emit(event, ...this.indexesOf(row));\n }\n\n /** The `$command.<name>` token (declared in `$commandTokens`). */\n command(name: string): Token {\n const token = this.commands[name];\n if (token === undefined) raise(M.CommandTokenUndeclared, [name], name, Object.keys(this.commands));\n return token;\n }\n\n /** `onclick: $command.<name>` — emits the token with (event, ...listIndexes). */\n emitCommand(name: string, event: Event, row: StateRow | null): void {\n this.command(name).emit(event, ...this.indexesOf(row));\n }\n\n // ---------------------------------------------------------------- methods\n\n invoke(name: string, event: Event, row: StateRow | null): unknown {\n // a dotted name is a path (a volume method lives under its mount path)\n const fn = name.includes(\".\") ? this.readUntracked(this.pattern(name), null) : this.target[name];\n if (typeof fn !== \"function\") raise(M.NotAMethod, [name]);\n return this.callAt(fn, row, [event, ...this.indexesOf(row)]);\n }\n\n /** Calls `fn` on the proxy with the evaluation context at `row`. */\n private callAt(fn: (...args: any[]) => unknown, row: StateRow | null, args: unknown[]): unknown {\n const prev = this.ctx;\n this.ctx = row;\n try {\n return fn.apply(this.proxy, args);\n } finally {\n this.ctx = prev;\n }\n }\n\n // ---------------------------------------------------------------- change walk\n\n /** Queues the bindings on `p` (and patterns under it) in the scope of `row`. */\n enqueueBound(p: Pattern, row: StateRow | null): void {\n // a list over a getter (or under one) is re-synced in the drain: a data write syncs its\n // lists right away, but a getter's value is only known when it is read again\n if (p.getter !== null) {\n const ls = row === null ? this.rootLists : row.children;\n if (ls !== null) {\n for (const l of ls.values()) {\n if (!l.stale && l.pattern.isUnder(p)) {\n l.stale = true;\n this.staleLists.push(l);\n }\n }\n }\n }\n if (row === null) {\n this.forSubtree(p, (q) => {\n const bs = this.rootBindings.get(q);\n if (bs !== undefined) for (const b of bs) this.enqueue(b);\n });\n return;\n }\n const bs = row.bindings;\n if (bs !== null) for (let i = 0; i < bs.length; i++) if (bs[i].pattern.isUnder(p)) this.enqueue(bs[i]);\n // slot bindings of the row's renderings\n const view = row.view;\n if (view !== null && view.slots !== null) view.enqueueSlots(this, p);\n const extra = row.list.extra;\n if (extra !== null) {\n for (const fv of extra) {\n const rv = fv.map!.get(row);\n if (rv !== undefined && rv.slots !== null) rv.enqueueSlots(this, p);\n }\n }\n }\n\n /** Reaches every getter occurrence that read `p` (or a pattern under it) at `row`. */\n walkDependents(p: Pattern, row: StateRow | null, visit: Visit): void {\n this.forSubtree(p, (q) => {\n const deps = q.dependents;\n for (let i = 0; i < deps.length; i++) {\n const g = deps[i];\n if (g.depth === 0) this.visitGetter(g, null, visit);\n else if (row === null || q.depth === 0 || g.lists[1] !== q.lists[1] || (g.crossSources !== null && g.crossSources.has(q))) {\n this.forAllRows(g.lists[g.depth]!, (r) => this.visitGetter(g, r, visit));\n } else if (g.depth <= q.depth) {\n const r = rowAt(row, g.depth);\n if (r !== null) this.visitGetter(g, r, visit);\n } else this.forRowsUnder(row, g, (r) => this.visitGetter(g, r, visit));\n }\n });\n }\n\n visitGetter(g: Pattern, row: StateRow | null, visit: Visit): void {\n if (!visit(g, row)) return;\n hooks.getterReached?.(this, g, row);\n this.enqueueBound(g, row);\n this.walkDependents(g, row, visit);\n }\n\n forSubtree(p: Pattern, fn: (q: Pattern) => void): void {\n fn(p);\n const c = p.children;\n for (let i = 0; i < c.length; i++) this.forSubtree(c[i], fn);\n }\n\n /** Every row of every list instance of list pattern `listP`. */\n forAllRows(listP: Pattern, fn: (row: StateRow) => void): void {\n this.forAllLists(listP, (l) => {\n for (const r of l.rows) fn(r);\n });\n }\n\n /** Every list instance of list pattern `listP`. */\n private forAllLists(listP: Pattern, fn: (l: StateList) => void): void {\n if (listP.depth === 0) {\n const l = this.rootLists.get(listP);\n if (l !== undefined) fn(l);\n return;\n }\n this.forAllRows(listP.lists[listP.depth]!, (parent) => {\n const l = parent.children?.get(listP);\n if (l !== undefined) fn(l);\n });\n }\n\n /** Rows at g.depth at or under `row` (row.depth <= g.depth). */\n forRowsUnder(row: StateRow, g: Pattern, fn: (row: StateRow) => void): void {\n if (row.list.depth === g.depth) return fn(row);\n const l = row.children?.get(g.lists[row.list.depth + 1]!);\n if (l !== undefined) for (const r of l.rows) this.forRowsUnder(r, g, fn);\n }\n\n // ---------------------------------------------------------------- bindings & drain\n\n /** Registers a binding where a change of its location finds it: its row, or the root table. */\n register(b: Binding): void {\n const row = b.row;\n if (row !== null) {\n (row.bindings ?? (row.bindings = [])).push(b);\n return;\n }\n upsert(this.rootBindings, b.pattern, newSet<Binding>).add(b);\n }\n\n unregister(b: Binding): void {\n const row = b.row;\n if (row === null) {\n this.rootBindings.get(b.pattern)?.delete(b);\n return;\n }\n // a row that left its list takes its registrations with it\n const bs = row.bindings;\n if (row.alive && bs !== null) bs.splice(bs.indexOf(b) >>> 0, 1);\n }\n\n enqueue(b: Binding): void {\n if (b.queued) return;\n b.queued = true;\n this.queue.push(b);\n this.schedule();\n }\n\n schedule(): void {\n if (this.scheduled) return;\n this.scheduled = true;\n queueMicrotask(this.drainFn);\n }\n\n /** Drops the queued work of a cut update loop: what it would have shown waits for the next change. */\n private dropWork(): void {\n for (const b of this.queue) b.queued = false;\n for (const l of this.dirtyLists) l.queued = false;\n for (const l of this.staleLists) l.stale = false;\n this.queue = [];\n this.dirtyLists = [];\n this.staleLists = [];\n this.strategy.dropped(this);\n }\n\n /**\n * Cuts an update loop past `max` (`id`: its message): reported with the paths its queued work\n * would have rendered (the console, and DevTools as `state:render-chain-limit`), then dropped.\n */\n private cutLoop(id: M, max: number): void {\n const paths = [...new Set([...this.queue, ...this.dirtyLists, ...this.staleLists].map((x) => x.pattern.path))];\n report(paths, `[@wcstack/state] ${text(id)}`);\n hooks.noticed?.(this, { \"type\": \"state:render-chain-limit\", \"maxDepth\": max, \"paths\": paths });\n this.dropWork();\n }\n\n drain(): void {\n this.scheduled = false;\n // a drain only rendering fed (no write from code since the last) continues a chain: the carried\n // one of a deferred apply, or the task's\n const carried = this.carried;\n this.carried = 0;\n let chain = 0;\n if (!this.fedBack || this.codeWrote) this.unchainFn();\n else if (carried > 0) chain = carried;\n else if ((chain = ++this.chain) === 1) setTimeout(this.unchainFn, 0);\n this.fedBack = this.codeWrote = false;\n if (chain > MAX_RENDER_CHAIN) {\n if (chain === MAX_RENDER_CHAIN + 1) this.cutLoop(M.RenderChain, MAX_RENDER_CHAIN);\n else this.dropWork();\n return;\n }\n this.draining = true;\n try {\n for (let pass = 0; this.queue.length > 0 || this.dirtyLists.length > 0 || this.staleLists.length > 0; pass++) {\n if (pass >= MAX_DRAIN_PASSES) {\n // (once a chain: a reaction that starts the same loop again in each drain is not reported again)\n if (this.unsettled) this.dropWork();\n else this.cutLoop(M.DrainNotSettled, MAX_DRAIN_PASSES);\n this.unsettled = true;\n break;\n }\n const stale = this.staleLists;\n if (stale.length > 0) {\n this.staleLists = [];\n for (const l of stale) {\n l.stale = false;\n this.trySync(l);\n }\n }\n const lists = this.dirtyLists;\n const q = this.queue;\n this.dirtyLists = [];\n this.queue = [];\n // a pass that changes structure — a list's rows, an `if` branch — goes to the page's\n // view-transition arbiter, if any (transition-runner protocol); one that only updates\n // values is applied right here, as with no arbiter (a value change is CSS transitions'\n // job, and a transition per keystroke left the page unclickable — docs/seam-apps.md,\n // router-admin). Queued entries stay marked until applied, so a write meanwhile folds\n // into them\n const apply = (): void => {\n // list views first (they build rows), then bindings\n for (const l of lists) {\n l.queued = false;\n for (const v of [l.view, ...(l.extra ?? [])]) {\n if (v === null || !v.alive) continue;\n // a row that fails to build (a binding refused as it is attached) fails this view\n // alone: the rest of the pass is still applied (nothing stays queued)\n try {\n v.update();\n } catch (error) {\n this.failAt(error, l.pattern.path, v.anchor, \"for\");\n }\n }\n }\n // `if` / `elseif` conditions first: a branch one closes takes its bindings with it, so\n // they are not applied with the value that closes it (a condition over a getter is\n // queued after the bindings on the path it reads — docs/seam-apps.md, router-auth)\n for (let k = 0; k < 2; k++) {\n for (let i = 0; i < q.length; i++) {\n const b = q[i];\n // applied since it was queued (a row slot, when its row was built)\n if (!b.queued || (b.chain === null) === (k === 0)) continue;\n b.queued = false;\n if (b.owner === null || b.owner.alive) this.applyBinding(b);\n }\n }\n // applied later by the arbiter, outside any drain: report its failures now, and the drain\n // what it fed back starts (a write-back, `$renderedCallback`) is the next of this drain's chain\n if (!this.draining) {\n this.report();\n if (this.scheduled) this.carried = chain + 1;\n }\n };\n const pending = lists.length > 0 || q.some((b) => b.chain !== null) ? runTransition(\"state\", apply) : apply();\n if (pending !== undefined) pending.then(undefined, report);\n }\n } finally {\n this.draining = false;\n }\n // (writes made while applying are this drain's own passes)\n this.fedBack = this.codeWrote = false;\n this.report();\n hooks.drained?.(this);\n this.sweep();\n // (as is the one a carried drain's reactions start)\n if (carried > 0 && this.scheduled) this.carried = chain + 1;\n }\n\n // ---------------------------------------------------------------- apply, hooks, reports\n\n /** A binding that failed to apply: reported after the drain. */\n fail(error: unknown, b: Binding): void {\n this.errors.push([error, b]);\n }\n\n /**\n * A failure of what has no Binding object, reported like a binding's: a list that failed to sync\n * or render (its `for`), a binding refused as it was attached in a row.\n */\n failAt(error: unknown, path: string, node: Node | null, type: string): void {\n this.fail(error, { pattern: { path }, node, typeName: () => type } as unknown as Binding);\n }\n\n applyBinding(b: Binding): void {\n try {\n b.apply();\n } catch (error) {\n this.errors.push([error, b]);\n return;\n }\n if (this.rendered !== null) this.noteRendered(b.pattern, b.row);\n }\n\n /** Records an applied binding for `$renderedCallback`. */\n noteRendered(p: Pattern, row: StateRow | null): void {\n const list = upsert(this.rendered!, p.path, newArray<number[]>);\n if (row !== null) list.push(this.indexesOf(row));\n }\n\n /** Starts collecting applied paths when the state declares `$renderedCallback`. */\n watchRendered(): void {\n this.rendered = typeof this.target.$renderedCallback === \"function\" ? new Map() : null;\n }\n\n /** `$renderedCallback` for the paths applied since the last report, then binding failures. */\n report(): void {\n const rendered = this.rendered;\n if (rendered !== null && rendered.size > 0) {\n this.rendered = new Map();\n const paths = [...rendered.keys()];\n const indexes: Record<string, number[][]> = {};\n for (const [p, l] of rendered) if (l.length > 0) indexes[p] = l;\n this.feeding++;\n let r: any;\n try {\n r = this.callHook(\"$renderedCallback\", [paths, indexes]);\n } catch (e) {\n report(e);\n }\n if (isThenable(r)) {\n r.then(this.renderedFn, (e: unknown) => {\n this.renderedFn();\n report(e);\n });\n } else {\n this.feeding--;\n }\n }\n if (this.errors.length === 0) return;\n const errors = this.errors;\n this.errors = [];\n const hook = this.target.$errorCallback;\n for (const [error, binding] of errors) {\n hooks.failed?.(this, error, binding);\n const path = binding.pattern.path;\n const type = binding.typeName();\n if (typeof hook === \"function\") {\n // quoted keys: the author reads them (mangle.mjs shortens the unquoted ones)\n try {\n const r = this.callHook(\"$errorCallback\", [error, { \"path\": path, \"bindingType\": type, \"node\": binding.node }]) as any;\n if (isThenable(r)) r.then(undefined, report);\n } catch (e) {\n report(e);\n }\n } else {\n // (the binding's member and kind name it as written; the node points at it)\n report(error, `[@wcstack/state] ${text(M.BindingFailed, binding.name ? [type, path, binding.name, binding.kind] : [type, path])}`, binding.node);\n }\n }\n }\n\n /** Runs a lifecycle hook with the writable proxy; returns its result (awaited by the caller or not). */\n callHook(name: string, args: unknown[] = []): unknown {\n const fn = this.target[name];\n return typeof fn === \"function\" ? this.callAt(fn, null, args) : undefined;\n }\n\n // ---------------------------------------------------------------- $getAll / $setAll / $resolve\n\n /** Calls fn for every row at p.depth that matches `indexes` (a prefix over p's wildcards). */\n private forMatches(p: Pattern, indexes: readonly number[], fn: (row: StateRow | null, idx: number[]) => void): void {\n if (p.depth === 0) {\n fn(null, []);\n return;\n }\n const idx: number[] = [];\n const walk = (k: number, parent: StateRow | null): void => {\n const lp = p.lists[k]!;\n // the list itself is read too: a getter over $getAll sees the first row of an empty list\n this.read(lp, parent);\n const list = this.childList(parent, lp);\n const visit = (r: StateRow): void => {\n idx.push(r.index);\n if (k === p.depth) fn(r, idx);\n else walk(k + 1, r);\n idx.pop();\n };\n for (const r of k - 1 < indexes.length ? [list.rows[indexes[k - 1]]] : list.rows) if (r !== undefined) visit(r);\n };\n walk(1, null);\n }\n\n private getAll(path: string, indexes?: number[]): unknown[] {\n const p = this.pattern(path, true);\n if (indexes !== undefined) this.checkArity(\"$getAll\", path, p, indexes, false);\n // by default the loop context, on the wildcard levels the path shares with it\n let idx = indexes;\n if (idx === undefined) {\n idx = [];\n const ctx = this.ctx;\n if (ctx !== null && p.depth > 0) {\n for (let k = 1; k <= p.depth; k++) {\n const r = ctxRow(ctx, p, k);\n if (r === null) break;\n idx.push(r.index);\n }\n if (idx.length === 0) raise(M.GetAllNoCommonLevel, [path]);\n }\n }\n const out: unknown[] = [];\n this.forMatches(p, idx, (row) => out.push(this.read(p, row)));\n return out;\n }\n\n private setAll(path: string, indexes: number[], value: unknown, options?: { spread?: boolean }): number {\n if (!Array.isArray(indexes)) raise(M.SetAllNeedsIndexes, [path]);\n if (this.readonlyDepth > 0) raise(M.Readonly);\n const p = this.pattern(path, true);\n this.checkArity(\"$setAll\", path, p, indexes, false);\n const targets: [StateRow | null, number[]][] = [];\n this.forMatches(p, indexes, (row, idx) => targets.push([row, idx.slice()]));\n const spread = options?.spread === true;\n if (spread && (!Array.isArray(value) || value.length !== targets.length)) {\n raise(M.SetAllSpreadLength, [path, targets.length]);\n }\n let written = 0;\n for (let i = 0; i < targets.length; i++) {\n const [row, idx] = targets[i];\n const v = typeof value === \"function\"\n ? (value as (cur: unknown, ...i: number[]) => unknown)(this.readUntracked(p, row), ...idx)\n : spread ? (value as unknown[])[i] : value;\n if (v === undefined) continue;\n this.write(p, row, v);\n written++;\n }\n return written;\n }\n\n /** `$resolve` takes exactly one index per `*`; `$getAll` / `$setAll` at most one (fewer expands the rest). */\n private checkArity(api: string, path: string, p: Pattern, indexes: readonly number[], exact: boolean): void {\n const n = indexes.length;\n if (n > p.depth || (exact && n < p.depth)) {\n raise(exact ? M.IndexArityExact : M.IndexArityAtMost, [api, path, p.depth, n]);\n }\n }\n}\n","import { raise, M } from \"./messages\";\n\n/**\n * Page-wide configuration (`bootstrapState(config)`): how this page spells wcstack markup (the tag\n * names, the binding attribute, the anchor comments — fixed before the first definition, the same\n * on the server) and the locale default. How a state tree behaves is its own `$behavior` (engine.ts).\n */\nexport interface Config {\n bindAttributeName: string;\n /** The text of a `for` template's anchor comment. */\n commentForPrefix: string;\n /** The texts of an `if` / `elseif` / `else` chain's anchor comments. */\n commentIfPrefix: string;\n commentElseIfPrefix: string;\n commentElsePrefix: string;\n tagNames: { state: string; ssr: string };\n locale: string;\n /** Opt-in `analyzeContract()` (dev time); off, it returns at once. */\n enableContractAnalyzer: boolean;\n}\n\nexport const config: Config = {\n bindAttributeName: \"data-wcs\",\n commentForPrefix: \"wcs-for\",\n commentIfPrefix: \"wcs-if\",\n commentElseIfPrefix: \"wcs-elseif\",\n commentElsePrefix: \"wcs-else\",\n tagNames: { state: \"wcs-state\", ssr: \"wcs-ssr\" },\n locale: typeof document !== \"undefined\" ? document.documentElement?.lang || \"en\" : \"en\",\n enableContractAnalyzer: false,\n};\n\nexport type PartialConfig = Partial<Omit<Config, \"tagNames\">> & { tagNames?: Partial<Config[\"tagNames\"]> };\n\n/**\n * Applies the options given; an undefined value is left out. An option `bootstrapState` does not\n * have (a key 4.0 moved to the state's `$behavior` or removed included), a value of another type\n * than its default (null, or an array for an object, included) or a tag name it does not define\n * throws, and then nothing is applied — the same rule as every package's bootstrap.\n */\nexport function setConfig(partial: PartialConfig): void {\n const options = config as unknown as Record<string, unknown>;\n const tags = config.tagNames as Record<string, string>;\n const given = Object.entries(partial).filter(([, value]) => value !== undefined);\n const givenTags = Object.entries(partial.tagNames ?? {}).filter(([, tag]) => tag !== undefined);\n for (const [key, value] of given) {\n const current = options[key];\n if (!Object.hasOwn(options, key) || value === null || typeof value !== typeof current || Array.isArray(value) !== Array.isArray(current)) {\n raise(M.OptionInvalid, [\"bootstrapState\", key]);\n }\n }\n for (const [name, tag] of givenTags) {\n if (!Object.hasOwn(tags, name) || typeof tag !== \"string\") raise(M.OptionInvalid, [\"bootstrapState\", `tagNames.${name}`]);\n }\n for (const [key, value] of given) {\n if (key !== \"tagNames\") {\n options[key] = value;\n }\n }\n for (const [name, tag] of givenTags) tags[name] = tag as string;\n}\n\n/** The current configuration (read-only view). */\nexport const getConfig = (): Readonly<Config> => config;\n","import { DELIMITER, MODIFIER_SEPARATOR } from \"./define\";\nimport { splitFilters } from \"./parseFilters\";\nimport { raise, M } from \"../messages\";\nimport { ParsedBinding, ParsedFilter } from \"./types\";\nimport { trimFn } from \"./utils\";\n\n// 解析の段の形(フィルタは名前と引数だけ — 実関数はエンジンが引く。要件 D16)\nexport type PropPartParseResult = Pick<ParsedBinding, 'propName' | 'propSegments' | 'propModifiers' | 'inFilters'>;\n\n/**\n * 入力フィルタ列の解析結果のキャッシュ(鍵は `|` より後ろの原文)。同じ原文は**同じ配列**を返す —\n * 消費側は返された `inFilters` を変更しないこと。落ちた解析は載らない。\n * (`@wcstack/state` の tooling 専用の解放口 `clearPropPartCacheForTooling` は移植しない)\n */\nconst cacheFilterInfos = new Map<string, ParsedFilter[]>();\n/** Tooling (`clearParserCaches`): a long-running process drops what it parsed. */\nexport const clearPropPartCache = (): void => cacheFilterInfos.clear();\n\n// format: propName#moodifier1,modifier2\n// propName-format: path.to.property (e.g., textContent, style.color, not include :)\n// special path:\n// 'attr.attributeName' for attributes (e.g., attr.href, attr.data-id)\n// 'style.propertyName' for style properties (e.g., style.backgroundColor, style.fontSize)\n// 'class.className' for class names (e.g., class.active, class.hidden)\n// 'onclick', 'onchange' etc. for event listeners\n\n/** Port of `@wcstack/state` `src/bindTextParser/parsePropPart.ts` (behaviour unchanged). */\nexport function parsePropPart(propPart: string): PropPartParseResult {\n const [propText, filters] = splitFilters(propPart, \"input\", cacheFilterInfos);\n\n // **不変条件**: ここから下の `split` は素で走らせてよい。`propText` は「引用符外の最初の `|`\n // より前」のスライスであり、引用符を含みうるのは入力フィルタの引数(`|` の後ろ)だけなので、\n // `#` も `,` も `.` も引用符の中に現れない。**修飾子の値に引用符を許す拡張(例\n // `value#fmt('a,b'): x`)を入れるなら、この 3 つも `splitOutsideQuotes` に替えること**。\n const modifierParts = propText.split(MODIFIER_SEPARATOR).map(trimFn);\n if (modifierParts.length > 2) {\n // 修飾子の並びは 1 つだけ(要件 B2)。`value#ro#wo` は以前 `ro` だけを残して黙って捨てていた\n raise(M.OneModifierList, [propText]);\n }\n const [propName, propModifiersText] = modifierParts;\n const propSegments = propName.split(DELIMITER).map(trimFn);\n // 明示のプロパティ形(`.name:` — 要件 B5 / D34)だけは先頭の空セグメントが正しい形。\n // それ以外で空のセグメントが残るのは書き間違い: 左辺が空(`\": x\"` / `\"#ro: x\"` / `\"|trim: x\"`)だと\n // `element[\"\"] = value` の expando ができて完全に沈黙し、末尾が空(`\"foo.: x\"`)だと適用の段で\n // 素の TypeError になる。どちらも解析の段で名指しで落とす(`.: x` 等は D34 の検査が受け持つ)\n const isExplicitProperty = propSegments.length > 1 && propSegments[0] === '';\n if (!isExplicitProperty && (propName.length === 0 || propSegments.some((segment) => segment.length === 0))) {\n raise(M.NoPropertyName, [propPart]);\n }\n const propModifiers = propModifiersText\n ? propModifiersText.split(',').map(trimFn)\n : [];\n return {\n propName,\n propSegments,\n propModifiers,\n inFilters: filters,\n };\n}\n","export type BindingType = 'text' | 'prop' | 'event' | 'for' | 'if' | 'elseif' | 'else' | 'radio' | 'checkbox' | 'spread';\n\n/** Left side (input) or right side (output) of a binding — only used to pick the diagnostic wording. */\nexport type FilterIOType = 'input' | 'output';\n\n/**\n * A filter as the grammar reads it: name and arguments only. The filter function is resolved\n * later by the engine (the parser never looks names up, so unknown names pass here).\n *\n * Field names are the ones of `@wcstack/state`'s `IParsedFilter`:\n * - `filterName` — the name as written (no alias resolution).\n * - `args` — the raw argument texts, quotes removed (format filters read these).\n * - `literals` — the typed value of each argument (requirement B9): unquoted `true` / `false` /\n * `null` / numbers are typed, everything else (and every quoted argument) is the string.\n * Always the same length and order as `args`.\n */\nexport interface ParsedFilter {\n filterName: string;\n args: string[];\n literals: unknown[];\n}\n\n/** Parse result of one binding (DOM independent). */\nexport interface ParsedBinding {\n propName: string;\n propSegments: string[];\n propModifiers: string[];\n statePathName: string;\n inFilters: ParsedFilter[];\n outFilters: ParsedFilter[];\n bindingType: BindingType;\n}\n\n/** Bindings that must be the only binding of their attribute value. */\nexport const STRUCTURAL_BINDING_TYPE_SET: ReadonlySet<BindingType> = new Set<BindingType>([\n 'if',\n 'elseif',\n 'else',\n 'for',\n]);\n","import {\n ATTR_NAMESPACE,\n BINDING_SEPARATOR,\n CLASS_NAMESPACE,\n COMMAND_NAMESPACE,\n DELIMITER,\n ELSE_KEYWORD,\n EVENT_PROP_PREFIX,\n EVENT_TOKEN_NAMESPACE,\n FILTER_SEPARATOR,\n MODIFIER_SEPARATOR,\n PROP_VALUE_SEPARATOR,\n SPREAD_PROP,\n STYLE_NAMESPACE,\n VOLUME_INJECTION_PROP,\n} from \"./define\";\nimport { parsePropPart } from \"./parsePropPart\";\nimport { parseStatePart, type StatePartParseResult } from \"./parseStatePart\";\nimport { raise, M } from \"../messages\";\nimport { ParsedBinding, STRUCTURAL_BINDING_TYPE_SET } from \"./types\";\nimport { indexOfOutsideQuotes, splitOutsideQuotes, trimFn } from \"./utils\";\n\n// format: propPart:statePart; propPart:statePart; ...\n// special-propPart:\n// if: statePart (single binding for conditional rendering)\n// else: (single binding for conditional rendering, and statePart is ignored)\n// elseif: statePart only (single binding for conditional rendering)\n// for: statePart only (single binding for loop rendering)\n// onclick: statePart, onchange: statePart etc. (event listeners)\n// ...: statePart (spread — the engine expands it into the target's wcBindable properties)\n\n/** 左辺に修飾子も入力フィルタも取らない束縛(構造ディレクティブと spread)— 付いていれば拒否する(要件 B4) */\nconst KEYWORDS_WITHOUT_MODIFIERS = new Set<string>([ELSE_KEYWORD, 'if', 'elseif', 'for', SPREAD_PROP]);\n\n/**\n * 明示のプロパティ形(`.name:`)の先頭に置けない語 — 名前空間として読まれる語(要件 B5)。\n * `state`(`VOLUME_INJECTION_PROP`)も含む: `<wcs-state mount>` 上の左辺 `state.<key>:` は\n * 注入の宣言(要件 B14③)なので、`.state.taxRate:` はプロパティか注入か曖昧になる。\n */\nconst EXPLICIT_PROPERTY_REJECTED_HEADS = new Set<string>([\n CLASS_NAMESPACE, ATTR_NAMESPACE, STYLE_NAMESPACE, COMMAND_NAMESPACE, EVENT_TOKEN_NAMESPACE,\n VOLUME_INJECTION_PROP,\n]);\n\n/**\n * `data-wcs` の値をバインディングごとに区切る(前後の空白は残す — tooling が位置を数えられるように)。\n * 引用符の中の `;` は区切りではない(要件 B1 — `join(';')`)。\n */\nexport function splitBindTexts(bindText: string): string[] {\n return splitOutsideQuotes(bindText, BINDING_SEPARATOR);\n}\n\n/**\n * `data-wcs` 属性値 1 つを解析する。Port of `@wcstack/state`\n * `src/bindTextParser/parseBindTextsForElement.ts` — same signature (text only: no decision\n * here needs the element), same results minus `statePathInfo`, same diagnostics.\n *\n * The parser does NOT: expand the loop-relative shorthand (`.name` / `.`), expand `...:`\n * spread into the target's properties, resolve filter names/functions, or check the\n * `if`/`elseif`/`else` sibling order — the engine does those.\n */\nexport function parseBindTextsForElement(bindText: string): ParsedBinding[] {\n const bindTexts = splitBindTexts(bindText).map(trimFn).filter(s => s.length > 0);\n const results = bindTexts.map((bindText): ParsedBinding => {\n // 左辺と右辺の区切りも引用符の外だけで探す(要件 B1)。`value|defaults(':'): path` の\n // 引数の中の `:` を区切りとして拾っていた\n const separatorIndex = indexOfOutsideQuotes(bindText, PROP_VALUE_SEPARATOR);\n if (separatorIndex === -1) {\n raise(M.BindTextNoColon, [bindText]);\n }\n const propPart = bindText.slice(0, separatorIndex).trim();\n const statePart = bindText.slice(separatorIndex + 1).trim();\n // 種別は修飾子・入力フィルタより前の名前で決める(要件 B4)。以前は左辺全体との完全一致で\n // 判定していたので、`radio#ro:` が汎用プロパティに落ちていた。\n // **不変条件**: ここは素の `split` でよい — 取り出すのは最初の区切りより前の**先頭**片で、\n // 引用符を含みうるのは入力フィルタの引数(引用符外の最初の `|` より後ろ)だけなので、\n // `#` も `|` も引用符の中では出会わない。**修飾子の値に引用符を許す拡張を入れるなら\n // `indexOfOutsideQuotes` に替えること**(`parsePropPart.ts` の同じ注記と対)。\n const keyword = propPart.split(MODIFIER_SEPARATOR)[0].split(FILTER_SEPARATOR)[0].trim();\n if (KEYWORDS_WITHOUT_MODIFIERS.has(keyword)) {\n if (keyword !== propPart) {\n raise(M.StructuralTakesNoModifiers, [bindText, keyword]);\n }\n let stateResult: StatePartParseResult;\n if (keyword === ELSE_KEYWORD) {\n if (statePart.length > 0) {\n // else は値を取らない(要件 B2)。以前は右辺を黙って捨てていた\n raise(M.ElseTakesNoValue, [bindText]);\n }\n stateResult = { statePathName: '#else', outFilters: [] };\n } else if (keyword === SPREAD_PROP) {\n // 空の右辺は spread 専用の語彙で先に落とす。`parseStatePart` の一般の空パス診断\n // (「the right side of a binding must name a state path」)より、ここでは\n // 「spread target path is required」のほうが直し方を指している\n if (statePart.length === 0) {\n raise(M.SpreadNoPath, [bindText]);\n }\n stateResult = parseStatePart(statePart);\n if (stateResult.outFilters.length > 0) {\n raise(M.SpreadNoFilters, [bindText]);\n }\n } else {\n stateResult = parseStatePart(statePart);\n // a row of `for: p` is `p.<index>`: the rows of a filtered list would name other elements (#370)\n if (keyword === 'for' && stateResult.outFilters.length > 0) {\n raise(M.ForNoFilters, [bindText]);\n }\n }\n return {\n propName: keyword,\n propSegments: [keyword],\n propModifiers: [],\n inFilters: [],\n ...stateResult,\n bindingType: keyword === SPREAD_PROP ? 'spread' : keyword as ParsedBinding['bindingType'],\n };\n }\n // `class` / `attr` は名前を伴ってはじめて束縛になる(`class.done:` / `attr.href:`)。名前の無い\n // `class:` / `attr:` は要素の(存在しない)`class` / `attr` プロパティへの書き込みになり、何も起きず\n // 何も報告されなかった(`.class:` は B5 で拒否済み)。`style:` は `el.style = \"…\"` が cssText に\n // 届くので受ける\n if (keyword === CLASS_NAMESPACE || keyword === ATTR_NAMESPACE) {\n raise(M.NamespaceNeedsName, [bindText, keyword]);\n }\n const stateResult = parseStatePart(statePart);\n const propResult = parsePropPart(propPart);\n const [head] = propResult.propSegments;\n // 左辺の先頭ドット(`.online:`)は明示のプロパティ形(要件 B5・3.x 計画 D34)。ドットの無い形と\n // 同じ束縛だが、`on` で始まってもイベントにはならない(`online:` は \"line\" イベントを待つ)。\n // 名前空間の語(`.class.x` / `.command.x` …)はプロパティか名前空間か曖昧なので受けない\n if (head === '' && propResult.propSegments.length > 1) {\n const propSegments = propResult.propSegments.slice(1);\n if (propSegments.includes('') || EXPLICIT_PROPERTY_REJECTED_HEADS.has(propSegments[0])) {\n raise(M.LeadingDotNamespace, [propPart]);\n }\n return {\n ...propResult,\n propName: propSegments.join(DELIMITER),\n propSegments,\n ...stateResult,\n bindingType: 'prop',\n };\n }\n return {\n ...propResult,\n ...stateResult,\n // 修飾子(`#ro`・`#onchange` …)と入力フィルタは radio / checkbox のハンドラが読む(要件 B4)。\n // eventToken.<prop>: <name> は要素 dispatch を state へ流す pub/sub 配線。\n // 値適用ではないため bindingType 'event' として listener attach 経路に乗せる。\n bindingType: keyword === 'radio' || keyword === 'checkbox' ? keyword\n : head === EVENT_TOKEN_NAMESPACE || head.startsWith(EVENT_PROP_PREFIX) ? 'event' : 'prop',\n };\n });\n // check for sigle binding for 'if', 'elseif', 'else', 'for'\n if (results.length > 1) {\n const isIncludeSingleBinding = results.some(r => STRUCTURAL_BINDING_TYPE_SET.has(r.bindingType));\n if (isIncludeSingleBinding) {\n // lint 側の単独バインディング検査(bindingValidator の structuralMustBeSingle)が\n // 同じケースを検出するため誘導を付ける(三面同語彙)。\n raise(M.StructuralNotSingle, [bindText]);\n }\n }\n return results;\n}\n","/**\n * filters/registry.ts — the filter registry, ported from `@wcstack/state` (`core/filterRegistry.ts`).\n *\n * The grammar (`path|filter(args)`) only produces names and arguments; the functions are looked up\n * here when the bindings are planned. The core set (`./core`) and the formats add-on (`./formats`)\n * each put their filters in with an install call; this module knows neither implementation, so a\n * page that skips the add-on does not carry its code.\n *\n * Differences from the source, all decided:\n * - one registry, not an input / output pair (the source registered the same table in both);\n * - no aliases (`inc dec fix uc lc cap pad rep rev null` are not carried over);\n * - every registered filter has arity bounds (the source allowed them to be absent);\n * - the core set is registered like any other (the source hard-wired `not` into the registry).\n */\nimport { raiseError } from \"../parser/raiseError\";\nimport { raise, M } from \"../messages\";\n\nexport type FilterFn = (value: unknown) => unknown;\n\n/**\n * Builds the function for one use of a filter. `options` are the argument texts (unquoted),\n * `literals` their typed values (requirement B9 — only filters that compare or return an argument\n * read them).\n */\nexport type FilterFactory = (options: string[], literals: readonly unknown[]) => FilterFn;\n\n/** A filter as an install call hands it to the registry: the factory and its [min, max] argument count (B3). */\nexport interface FilterDefinition {\n factory: FilterFactory;\n arity: readonly [number, number];\n}\n\n/**\n * The formats add-on's filters (37: up to 4.0.0-rc.3 the 23 display ones, then the core's\n * arithmetic, conversion and missing-value 14). Only the names live here (not the code), so that a\n * page without the add-on can still say where one of them comes from instead of calling it a typo.\n * A test keeps this list equal to the add-on's table.\n */\nexport const FORMATS_FILTER_NAMES: readonly string[] = [\n \"toFixed\", \"locale\",\n \"upper\", \"lower\", \"capitalize\", \"trim\", \"slice\", \"padStart\", \"padEnd\", \"repeat\", \"reverse\", \"truncate\", \"join\",\n \"round\", \"floor\", \"ceil\", \"percent\", \"unit\",\n \"date\", \"time\", \"datetime\", \"ymd\", \"hms\",\n \"add\", \"sub\", \"mul\", \"div\", \"mod\", \"abs\", \"clamp\", \"int\", \"float\", \"defaults\", \"coalesce\", \"number\", \"string\", \"nullIfEmpty\",\n \"currency\",\n];\n\n/**\n * A `Map`, not a plain object: bracket access on an object lets the `Object.prototype` members\n * through as filters (`|toString` / `|constructor` / `|valueOf`), which then fail with a\n * meaningless TypeError instead of `[wcs/filter-unknown]`.\n */\nconst definitions = new Map<string, FilterDefinition>();\n\n/** Name + arguments → the function already built for them (each is built once). */\nconst resolvedByKey = new Map<string, FilterFn>();\n\n/**\n * The key of one argument list: **both the raw texts and the typed values** (B3 / B9).\n * - Raw texts alone would make `defaults(0)` and `defaults('0')` the same `[\"0\"]`, sharing one\n * function between two filters of different types.\n * - Typed values alone would fold `1` / `1.0` / `01` / `+1` into the same number, although the\n * factories that read the raw text (`truncate` / `unit` / `join` / `ymd` / `padStart` …) answer\n * them differently.\n * - A structural key, never `args.join(\",\")`: `['a,b']` and `['a', 'b']` are different arguments.\n */\nexport function filterArgsKey(args: readonly string[], literals: readonly unknown[]): string {\n return `${JSON.stringify(args)}${JSON.stringify(literals)}`;\n}\n\n/** Called by the install functions. Idempotent — a name registered again replaces the previous one. */\nexport function registerFilters(map: Record<string, FilterDefinition>): void {\n for (const name of Object.keys(map)) {\n // a copy: the registry keeps what was registered\n definitions.set(name, { ...map[name] });\n }\n // A new registration can change the answers already built (a page installs once; tests and\n // tooling swap registrations)\n resolvedByKey.clear();\n}\n\nexport function hasFilter(name: string): boolean {\n return definitions.has(name);\n}\n\n/** The registered names, which the did-you-mean suggestion reads. */\nexport function knownFilterNames(): string[] {\n return [...definitions.keys()];\n}\n\n/** Drops the functions already built (tooling that clears its parser caches). */\nexport function clearFilterResolutionCache(): void {\n resolvedByKey.clear();\n}\n\n/**\n * `[wcs/filter-unknown]`. A formatting filter on a page without the formats add-on is not a typo:\n * that barrier is kept as full text, since it is met on pages without add-ons (the diagnostics\n * add-on adds the nearest name to either).\n */\nfunction unknownFilter(name: string, known: Iterable<string>): never {\n if (FORMATS_FILTER_NAMES.includes(name)) {\n raiseError(`[wcs/filter-unknown] filter not found: ${name}. \"${name}\" is in the formats add-on — install it with installFeatures([formats]) from \"@wcstack/state/features/formats\".`, name, known);\n }\n raise(M.FilterUnknown, [name], name, known);\n}\n\n/**\n * The function for one use of a filter (binding planning). An unknown name or a wrong argument count\n * fails here, by name — the parser never rejects a filter.\n */\nexport function resolveFilter(name: string, options: string[], literals: readonly unknown[]): FilterFn {\n const key = `${name}${filterArgsKey(options, literals)}`;\n const resolved = resolvedByKey.get(key);\n if (typeof resolved !== \"undefined\") {\n return resolved;\n }\n const definition = definitions.get(name);\n if (definition === undefined) {\n unknownFilter(name, definitions.keys());\n }\n // Same vocabulary as lint's wcs/filter-arity\n const [min, max] = definition.arity;\n if (options.length < min) raise(M.FilterTooFewArgs, [name, min, options.length]);\n if (options.length > max) raise(M.FilterTooManyArgs, [name, max, options.length]);\n const filterFn = definition.factory(options, literals);\n resolvedByKey.set(key, filterFn);\n return filterFn;\n}\n","/**\n * filters/errorMessages.ts — the filters' error messages, ported from `@wcstack/state`\n * (`formats/errorMessages.ts`). Numbered core messages (src/messages.ts): the sentences, the same\n * as the source's, are the diagnostics add-on's.\n */\n\nimport { raise, M } from \"../messages\";\n\n/** The filter requires an option but none was given (the factory-side guard; arity usually fires first). */\nexport function optionsRequired(fnName: string): never {\n raise(M.FilterOptionsRequired, [fnName]);\n}\n\n/** A numeric option is not a number. */\nexport function optionMustBeNumber(fnName: string): never {\n raise(M.FilterOptionNotNumber, [fnName]);\n}\n\n/** A date filter's style is not one of full / long / medium / short. */\nexport function styleInvalid(fnName: string, value: string): never {\n raise(M.FilterStyleInvalid, [fnName, value]);\n}\n\n/** `currency`'s code is not a currency Intl knows. */\nexport function currencyInvalid(value: string): never {\n raise(M.FilterCurrencyInvalid, [value]);\n}\n\n/** The value given to a numeric filter is not a number (the message says what it was). */\nexport function valueMustBeNumber(fnName: string, value: unknown): never {\n raise(M.FilterValueNotNumber, [fnName, value]);\n}\n\n/** The value given to a date filter is not a Date (the message says what it was). */\nexport function valueMustBeDate(fnName: string, value: unknown): never {\n raise(M.FilterValueNotDate, [fnName, value]);\n}\n\n/** The value given to an array filter is not an array. */\nexport function valueMustBeArray(fnName: string): never {\n raise(M.FilterValueNotArray, [fnName]);\n}\n","/**\n * filters/options.ts — option parsing shared by the core set and the formats add-on, ported\n * verbatim from `@wcstack/state` (`formats/builtinFilters.ts`).\n *\n * Numeric options are read **once, when the filter is built**: the checks stay in one place and the\n * `Number()` conversion stays off the apply path.\n */\nimport { optionMustBeNumber, optionsRequired } from \"./errorMessages\";\n\n/** `\"\"` and anything `Number()` cannot read are rejected (so `lt('')` is an error, not `lt(0)`). */\nexport function validateNumberString(value: string): boolean {\n if (!value || isNaN(Number(value))) {\n return false;\n }\n return true;\n}\n\n/** One numeric option, converted: non-numeric → `optionMustBeNumber`. */\nexport function numberOption(value: string, fnName: string): number {\n if (!validateNumberString(value)) {optionMustBeNumber(fnName);}\n return Number(value);\n}\n\n/** A required numeric option: missing → `optionsRequired`, non-numeric → `optionMustBeNumber`. */\nexport function requiredNumberOption(options: readonly string[] | undefined, index: number, fnName: string): number {\n return numberOption(options?.[index] ?? optionsRequired(fnName), fnName);\n}\n\n/**\n * The typed literal of the first argument (requirement B9): an unquoted `true` / `false` / `null` /\n * number arrives typed, a quoted argument as a string. Without literals (tooling calling a factory\n * directly) the raw option text stands in.\n */\nexport function firstLiteral(opt: string, literals: readonly unknown[] | undefined): unknown {\n return literals !== undefined && literals.length > 0 ? literals[0] : opt;\n}\n","/**\n * filters/core.ts — the core filter set (10): the conditions a binding tests, as opposed to the\n * values the formats add-on (`./formats`) computes and shows. Ported from `@wcstack/state`\n * (`formats/builtinFilters.ts`) with the semantics unchanged.\n *\n * - conditions: `eq ne not lt le gt ge truthy falsy boolean`\n *\n * The arithmetic (`add sub mul div mod abs clamp`), conversion (`number string int float`) and\n * missing-value (`defaults coalesce nullIfEmpty`) filters were here up to 4.0.0-rc.3; they are the\n * formats add-on's since, for the core's size target.\n *\n * `installCoreFilters()` puts them in the registry; the engine calls it before it plans bindings\n * (`else:` is built with an injected `not`, so the core set is never optional).\n */\nimport { optionMustBeNumber, optionsRequired, valueMustBeNumber } from \"./errorMessages\";\nimport { firstLiteral, requiredNumberOption, validateNumberString } from \"./options\";\nimport { registerFilters, type FilterDefinition, type FilterFn } from \"./registry\";\n\n/** Equality — compares with the option (a typed literal compares as itself, B9). */\nconst eq = (options: string[], literals?: readonly unknown[]): FilterFn => {\n const opt = options?.[0] ?? optionsRequired('eq');\n const literal = firstLiteral(opt, literals);\n return (value: unknown): boolean => {\n if (typeof value === 'number') {\n // A typed literal that is not a string compares as itself (B9): a number is never equal to\n // `true` / `false` / `null`, so `selectedId|eq(null)` is false once the id is a number instead\n // of throwing on every apply. Only an unquoted non-number (`eq(abc)`) still reports the type\n // mismatch, and it has to stay here: `eq` accepts values of any type (`status|eq(active)` is\n // valid), so it cannot be rejected at construction the way `lt` / `add` can.\n if (typeof literal !== 'string') {return value === literal;}\n if (!validateNumberString(opt)) {optionMustBeNumber('eq');}\n return value === Number(opt);\n }\n if (typeof value === 'string') {\n return value === opt;\n }\n // Booleans, null and the rest compare with the typed literal: eq(true) matches true (B9)\n return value === literal;\n };\n};\n\n/** Inequality — the negation of `eq`, with the same typing rules (B9). */\nconst ne = (options: string[], literals?: readonly unknown[]): FilterFn => {\n const opt = options?.[0] ?? optionsRequired('ne');\n const literal = firstLiteral(opt, literals);\n return (value: unknown): boolean => {\n if (typeof value === 'number') {\n if (typeof literal !== 'string') {return value !== literal;}\n if (!validateNumberString(opt)) {optionMustBeNumber('ne');}\n return value !== Number(opt);\n }\n if (typeof value === 'string') {\n return value !== opt;\n }\n return value !== literal;\n };\n};\n\n/**\n * Inverts truthiness (lenient `!value`). `else:` is built as the `if` condition plus an injected\n * `not`, and `if:` coerces with `Boolean()`; a strict `not` made `else:` throw — rendering neither\n * branch — whenever the condition was a falsy non-boolean (`0` / `\"\"` / `undefined` / `null`).\n */\nconst not = (): FilterFn => (value: unknown): boolean => !value;\n\n/**\n * A comparison or arithmetic filter: one numeric option, a number value (`lt` … `ge` here, `add` …\n * `mod` in the formats add-on).\n */\nexport const numeric = (name: string, op: (value: number, opt: number) => unknown): FilterDefinition => ({\n factory: (options: string[]): FilterFn => {\n const opt = requiredNumberOption(options, 0, name);\n return (value: unknown): unknown => {\n if (typeof value !== 'number') {valueMustBeNumber(name, value);}\n return op(value, opt);\n };\n },\n arity: [1, 1],\n});\n\n/** JavaScript's truthiness, the same as `boolean` (B10). */\nconst truthy = (): FilterFn => (value: unknown): boolean => !!value;\n\n/** JavaScript's falsiness (`!value`: false, null, undefined, 0, -0, 0n, '' and NaN — B10). */\nconst falsy = (): FilterFn => (value: unknown): boolean => !value;\n\nconst boolean = (): FilterFn => (value: unknown): boolean => Boolean(value);\n\n/**\n * The core set: factory and [min, max] argument count (B3 — the same bounds lint uses).\n *\n * The key order is the source's (`builtinFilterMeta`, which lint reads): the did-you-mean\n * suggestion breaks ties by registration order (see `installFormats` for the order the full\n * build registers).\n */\nexport const coreFilters: Readonly<Record<string, FilterDefinition>> = {\n eq: { factory: eq, arity: [1, 1] },\n ne: { factory: ne, arity: [1, 1] },\n not: { factory: not, arity: [0, 0] },\n lt: numeric('lt', (value, opt) => value < opt),\n le: numeric('le', (value, opt) => value <= opt),\n gt: numeric('gt', (value, opt) => value > opt),\n ge: numeric('ge', (value, opt) => value >= opt),\n falsy: { factory: falsy, arity: [0, 0] },\n truthy: { factory: truthy, arity: [0, 0] },\n boolean: { factory: boolean, arity: [0, 0] },\n};\n\nlet installed = false;\n\n/** Puts the core set in the registry. Idempotent; the engine calls it before planning any binding. */\nexport function installCoreFilters(): void {\n if (installed) return;\n installed = true;\n registerFilters(coreFilters);\n}\n","import type { ParsedFilter } from \"../parser/index\";\nimport { resolveFilter, type FilterFn } from \"../filters/registry\";\nimport { installCoreFilters } from \"../filters/core\";\n\nexport type { FilterFn };\n\n/** `v` through the filters `fs` (none when null). */\nexport function pipe(fs: FilterFn[] | null, v: unknown): unknown {\n if (fs !== null) for (let i = 0; i < fs.length; i++) v = fs[i](v);\n return v;\n}\n\n/**\n * Resolves a binding's parsed filters to functions (at plan time, once per binding spec).\n * The core filters (the conditions) are always available; the others come with the formats add-on\n * (`installFeatures([formats])`; the full build installs it).\n */\nexport function buildFilters(parsed: readonly ParsedFilter[]): FilterFn[] | null {\n if (parsed.length === 0) return null;\n installCoreFilters(); // idempotent\n return parsed.map((f) => resolveFilter(f.filterName, f.args, f.literals));\n}\n","/**\n * Trusted Types for the HTML sinks (`html:`, `innerHTML:`, `outerHTML:`, `srcdoc:`).\n * The policy lives on the same global slot as @wcstack/state, so a page that installed\n * one for the current engine keeps working:\n * globalThis[Symbol.for(\"wcstack.trustedTypes.policy\")] = trustedTypes.createPolicy(…)\n * No identity policy is ever created here — that would defeat the CSP.\n */\nexport interface TrustedTypesPolicy {\n createHTML?(input: string): unknown;\n}\n\nexport const TRUSTED_TYPES_POLICY_SLOT = Symbol.for(\"wcstack.trustedTypes.policy\");\n\ntype Slot = { [key: symbol]: unknown };\n\nexport function getTrustedTypesPolicy(): TrustedTypesPolicy | null {\n const value = (globalThis as Slot)[TRUSTED_TYPES_POLICY_SLOT];\n return value !== null && typeof value === \"object\" ? (value as TrustedTypesPolicy) : null;\n}\n\nexport function setTrustedTypesPolicy(policy: TrustedTypesPolicy | null): void {\n (globalThis as Slot)[TRUSTED_TYPES_POLICY_SLOT] = policy;\n}\n\nexport function isHtmlSink(prop: string): boolean {\n return prop === \"innerHTML\" || prop === \"outerHTML\" || prop === \"srcdoc\";\n}\n\n/**\n * A value for an HTML sink: a TrustedHTML (the page made it with its own policy) as it is, anything\n * else — an array or another object too, which the sink would turn into markup — as a string\n * (null / undefined: empty) passed through the installed policy (if any).\n */\nexport function trustHtml(value: unknown): unknown {\n if ((globalThis as any).trustedTypes?.isHTML(value)) return value;\n const s = value == null ? \"\" : String(value);\n const policy = getTrustedTypesPolicy();\n const create = policy?.createHTML;\n return typeof create === \"function\" ? create.call(policy, s) : s;\n}\n","import { getTransitionRunner } from \"../protocol/transitionRunner\";\nimport { M, text } from \"../messages\";\n\n/**\n * Automatic `view-transition-name` (docs/view-transition-design.md §6), as @wcstack/state\n * does it: when the page's arbiter declares `naming=\"auto\"`, the first element of every\n * row and `if` branch built gets a unique name. A name must be on the element before the\n * browser snapshots the old state, so it is given when the block is built, never renamed,\n * and capped (each named element is a snapshot group of its own).\n *\n * The ledger is per document (a `Symbol.for` slot shared with @wcstack/state), so two\n * bundles on one page never mint the same name.\n */\ninterface Ledger {\n counter: number;\n assigned: number;\n warned: boolean;\n}\n\nconst LEDGER_KEY = Symbol.for(\"wcstack.state.view-transition-naming\");\nconst named = new WeakSet<Element>();\n\n/** The naming cap when the arbiter names automatically, or -1 (the author names). */\nexport function autoNaming(): number {\n const runner = getTransitionRunner(\"state\");\n return runner !== null && runner.naming === \"auto\" ? runner.namingLimit : -1;\n}\n\n/** Names the first element of `nodes` (`wcs-row-3`, `wcs-branch-7`), within the cap. */\nexport function nameBlock(first: ChildNode, nodes: ChildNode[] | null, kind: \"row\" | \"branch\", limit: number): void {\n let el: Element | null = null;\n if (nodes === null) el = first.nodeType === 1 ? (first as Element) : null;\n else for (let i = 0; i < nodes.length && el === null; i++) if (nodes[i].nodeType === 1) el = nodes[i] as Element;\n const style = (el as HTMLElement | null)?.style;\n if (el === null || style === undefined || named.has(el)) return;\n const ledger = ((globalThis as any)[LEDGER_KEY] ??= { counter: 0, assigned: 0, warned: false }) as Ledger;\n if (ledger.assigned >= limit) {\n if (!ledger.warned) {\n ledger.warned = true;\n console.warn(`[@wcstack/state] ${text(M.NamingLimit, [limit])}`);\n }\n return;\n }\n named.add(el);\n ledger.assigned++;\n style.setProperty(\"view-transition-name\", `wcs-${kind}-${++ledger.counter}`);\n style.setProperty(\"view-transition-class\", `wcs-${kind}`);\n}\n","/**\n * Wiring to custom elements that declare the wc-bindable protocol:\n * static wcBindable = { protocol: \"wc-bindable\", version: 1,\n * properties: [{ name, event, getter?, semantics? }], // element → state\n * inputs: [{ name, attribute? }], // state → element\n * commands: [{ name, async? }] } // state invokes\n * Property bindings take their direction and initial authority from the declaration;\n * `command.<m>:` subscribes a method to a command token; `eventToken.<p>:` fires an event\n * token when the element dispatches that property's event; `...:` spreads a state object\n * over every declared property and input.\n */\nimport type { Engine } from \"../engine\";\nimport { raise, M } from \"../messages\";\nimport { hooks } from \"../hooks\";\nimport type { StateRow } from \"../list\";\nimport { adopt, Binding, failSpec, K_CUSTOM, type Block, type Spec } from \"./view\";\nimport { pipe } from \"./filters\";\nimport { report } from \"../parser/raiseError\";\n// (view.ts imports this module too: the cycle is fine, everything here is used at call time)\n\ninterface PropertyDecl {\n event: string;\n getter: ((e: Event) => unknown) | null;\n /** `semantics: \"event\"`: an occurrence, written even when equal to the current value. */\n occurrence: boolean;\n}\n\nexport interface Bindable {\n properties: Map<string, PropertyDecl>;\n /** The settable members. Their `attribute` hint is not used: the element reflects its own attributes. */\n inputs: Set<string>;\n commands: Set<string>;\n}\n\nconst bindableByClass = new WeakMap<CustomElementConstructor, Bindable | null>();\n\n/** The element's wc-bindable declaration (null when it has none), cached per class. */\nexport function readBindable(cls: CustomElementConstructor): Bindable | null {\n if (bindableByClass.has(cls)) return bindableByClass.get(cls)!;\n const decl = (cls as any).wcBindable;\n let out: Bindable | null = null;\n if (decl !== null && typeof decl === \"object\" && decl.protocol === \"wc-bindable\" && Number.isInteger(decl.version) && decl.version >= 1) {\n out = { properties: new Map(), inputs: new Set(), commands: new Set() };\n for (const p of decl.properties ?? []) {\n out.properties.set(p.name, { event: p.event, getter: typeof p.getter === \"function\" ? p.getter : null, occurrence: p.semantics === \"event\" });\n }\n for (const i of decl.inputs ?? []) out.inputs.add(i.name);\n for (const c of decl.commands ?? []) if (c !== null && typeof c === \"object\" && typeof c.name === \"string\") out.commands.add(c.name);\n }\n bindableByClass.set(cls, out);\n return out;\n}\n\n/** The registry that defines `el`: a scoped one (`attachShadow({ customElementRegistry })`) or the global one. */\nexport const registryOf = (el: Element): CustomElementRegistry =>\n ((el as any).customElementRegistry as CustomElementRegistry | null | undefined) ?? customElements;\n\n/**\n * Runs `attach` (for spec `s`) once the element's class is defined (at once when it already is) and\n * upgraded, unless its block went away in the meantime (`pending`). A native element has no definition to wait\n * for: it is attached at once (and refused there, as a custom element with no declaration is).\n */\nexport function whenDefined(engine: Engine, s: Spec, el: Element, owner: Block | null, attach: (bindable: Bindable | null) => void, later = false): void {\n const tag = el.localName;\n if (!tag.includes(\"-\")) return attach(null);\n const r = registryOf(el);\n // a row built in a fragment takes the registry of the shadow root it goes into (a scoped one)\n // when it is placed, in this drain: wait for that before waiting for a definition\n if (!later && !el.isConnected && r.get(tag) === undefined && \"customElementRegistry\" in el) {\n queueMicrotask(() => whenDefined(engine, s, el, owner, attach, true));\n return;\n }\n const run = (): void => {\n const cls = r.get(tag);\n r.upgrade(el);\n attach(cls ? readBindable(cls) : null);\n };\n if (!later && r.get(tag) !== undefined) return run();\n // a row gone while it waited for its registry waits for nothing (its block's cleanups have run)\n if (owner !== null && !owner.alive) return;\n // later, outside any drain: a failure is the binding's; it and what was applied are reported by\n // a drain (one for every element the definition upgrades: one `$renderedCallback`)\n pending(r.whenDefined(tag), owner, () => {\n try {\n run();\n } catch (error) {\n failSpec(engine, error, s, el);\n }\n engine.schedule();\n });\n}\n\n/**\n * Runs `fn` once `p` settles, unless `owner` went away first. Its own scope: the reaction holds\n * only `f`, so a removed row of a tag never defined keeps nothing alive.\n */\nfunction pending(p: Promise<unknown>, owner: Block | null, fn: () => void): void {\n let f: (() => void) | null = fn;\n if (owner !== null) (owner.cleanups ??= []).push(() => {\n f = null;\n });\n void p.then(() => f?.());\n}\n\n/** A property binding on a member of a custom element's wc-bindable declaration. */\nexport function attachProperty(engine: Engine, spec: Spec, el: Element, name: string, pattern = spec.pattern!,\n row: StateRow | null, owner: Block | null, bd: Bindable): Binding {\n const out = bd.properties.get(name) ?? null;\n const input = bd.inputs.has(name);\n // enableDirectionalInitialSync off (3.x opt-out): no member checks (and no init= / sync=, see\n // plan.ts); state wins every initial sync, output-only included\n const directional = engine.directional;\n if (directional && out === null && !input) raise(M.MemberUndeclared, [name]);\n // what the member's shape allows: output-only takes element / none, input-only state / none, two-way any\n const init = spec.init;\n const refused = out === null ? init === \"element\" || init === \"auto\" : !input && (init === \"state\" || init === \"auto\");\n if (refused) raise(M.InitIncompatible, [init, name]);\n if (spec.sync === \"connect\" && out === null) raise(M.SyncConnectNeedsOutput, [name]);\n const outputOnly = directional && out !== null && !input;\n const b = new Binding(engine, K_CUSTOM, el, name, pattern, row, owner, spec.filters, undefined);\n b.inFilters = spec.inFilters;\n // state → element (every member but an output-only one)\n adopt(engine, b, !outputOnly);\n // element → state (a declared property)\n if (out !== null && !spec.ro) {\n el.addEventListener(out.event, (e) => {\n let v: unknown;\n if (out.getter !== null) v = out.getter(e);\n else {\n v = (e as CustomEvent).detail;\n // the protocol's default getter: diagnostics tells the two shapes it can see are wrong\n if (!out.occurrence) hooks.detail?.(el, name, v);\n }\n if (b.applying && Object.is(v, b.value)) return; // our own write echoing back\n v = pipe(b.inFilters, v);\n // the element already shows this value: the apply this write causes must not echo it\n // back to the element it came from\n if (b.filters === null) b.value = v;\n engine.write(b.pattern, b.row, v, out.occurrence, true);\n });\n }\n // initial authority: output-only members seed state from the element, others the other way\n const authority = init ?? (outputOnly ? \"element\" : \"state\");\n if (authority === \"state\") {\n if (!outputOnly) engine.applyBinding(b);\n } else if (authority === \"element\" || authority === \"auto\") {\n const seed = (): void => {\n if (owner !== null && !owner.alive) return;\n if (authority === \"auto\" && engine.readUntracked(b.pattern, b.row) !== undefined) {\n if (!outputOnly) engine.applyBinding(b);\n return;\n }\n const snapshot = (el as any)[name];\n if (b.filters === null) b.value = snapshot; // seeded from the element: nothing to write back\n engine.write(b.pattern, b.row, snapshot, false, true);\n };\n if (spec.sync === \"connect\" && !el.isConnected) void Promise.resolve().then(seed);\n else seed();\n }\n return b;\n}\n\nfunction noBindable(id: M, el: Element, what: string): never {\n raise(id, [el.localName, what]);\n}\n\n/**\n * `command.<method>: $command.<token>` — the element's method subscribes to the token. A native\n * element (no declaration) is called the way the native-commands add-on says, when installed.\n */\nexport function attachCommand(engine: Engine, spec: Spec, el: Element, owner: Block | null, bd: Bindable | null): void {\n const method = spec.name;\n // (the path, \"$command.<token>\")\n const token = engine.command(spec.token!.slice(9));\n const call = bd === null ? hooks.nativeCommand?.(el, method) : null;\n if (!call) {\n if (bd === null) noBindable(M.NoBindable, el, `command.${method}`);\n if (!bd.commands.has(method)) raise(M.NoCommand, [el.localName, method]);\n }\n const ref = new WeakRef(el);\n const fn = (...args: unknown[]): unknown => {\n const target = ref.deref() as any;\n if (target === undefined) {\n unsubscribe();\n return undefined;\n }\n // detached for now (a route hidden with its nodes kept): not called, still subscribed\n return target.isConnected ? (call ? call(target, args) : target[method](...args)) : undefined;\n };\n const unsubscribe = token.subscribe(fn);\n if (owner !== null) (owner.cleanups ??= []).push(unsubscribe);\n}\n\n/** `eventToken.<property>: <token>` — the property's event fires the event token. */\nexport function attachEventToken(engine: Engine, spec: Spec, el: Element, row: StateRow | null, bd: Bindable | null): void {\n const prop = spec.name;\n if (bd === null) noBindable(M.NoBindable, el, `eventToken.${prop}`);\n const decl = bd.properties.get(prop);\n if (decl === undefined) raise(M.NoProperty, [el.localName, prop]);\n const name = spec.token!;\n el.addEventListener(decl.event, (e) => {\n if (spec.prevent) e.preventDefault();\n if (spec.stop) e.stopPropagation();\n try {\n engine.fireEventToken(name, e, row);\n } catch (error) {\n report(error);\n }\n });\n}\n\n/** `...: path` — one property binding per declared property and input (explicit bindings win). */\nexport function attachSpread(engine: Engine, spec: Spec, el: Element, row: StateRow | null, owner: Block | null, bd: Bindable | null): void {\n if (bd === null) noBindable(M.SpreadNoBindable, el, `\"...: ${spec.pattern!.path}\"`);\n const names = new Set([...bd.properties.keys(), ...bd.inputs]);\n for (const name of names) {\n if (spec.exclude?.includes(name)) continue;\n const p = engine.pattern(`${spec.pattern!.path}.${name}`);\n const r = p.depth === 0 ? null : row;\n attachProperty(engine, { ...spec, init: null, sync: null }, el, name, p, r, owner, bd);\n }\n}\n","import { rowAt, type Engine } from \"../engine\";\nimport type { Pattern } from \"../pattern\";\nimport type { StateList, StateRow } from \"../list\";\nimport { pipe, type FilterFn } from \"./filters\";\nimport { isHtmlSink, trustHtml } from \"../trustedTypes\";\nimport { autoNaming, nameBlock } from \"./naming\";\nimport { raise, M } from \"../messages\";\nimport { hooks } from \"../hooks\";\n\n/**\n * `on*:` bindings of bubbling events are delegated: one listener per event type on the root\n * (so `event.currentTarget` is the root — decided 2026-09-25), which runs the handlers of the\n * elements the event passed, innermost first. Inside a block the handler is not attached to the\n * element at all: the block's top node carries the block, which finds its handlers from its plan\n * when an event passes (Block.dispatch). Outside any block (a root-level element), where a\n * block's content can shift before the element (see compilePlan), and on a custom element, the\n * handler is stored on the element. A custom element may dispatch such an event without bubbling\n * (the root never hears it): that one is heard on the element. A non-bubbling event type gets a\n * listener on the element itself.\n *\n * `on*#direct:` is not delegated: a listener on the element itself, as 3.x (`currentTarget` is the\n * element) — `#stop` stops the page's own listeners on its ancestors, an ancestor's\n * `stopPropagation()` does not keep it from running, and an element moved under another root still\n * runs it. In a block (a row, a branch) it is attached with the block and removed when the block\n * goes. It runs where the DOM puts it: an outer `#direct` runs before the delegated handlers inside\n * it (they run at the root), so an inner `#stop` stops it only if the inner one is `#direct` too.\n */\nexport function attachEvent(engine: Engine, node: Node, s: Spec, row: StateRow | null, block: Block | null): void {\n const fn = s.listener!;\n const h = (e: Event): void => fn(e, row);\n if (s.delegated) {\n const key = engine.delegate(s.name);\n const prev = (node as any)[key];\n // two of one type on one element (`onclick: a; onclick: b`): both run\n (node as any)[key] = prev === undefined ? h : (e: Event): void => {\n prev(e);\n h(e);\n };\n if (s.custom) node.addEventListener(s.name, (e) => e.bubbles || h(e));\n } else {\n node.addEventListener(s.name, h);\n if (s.direct && block !== null) (block.cleanups ??= []).push(() => node.removeEventListener(s.name, h));\n }\n}\n\n/** Events that bubble: the only ones a delegated listener can see. */\nexport const BUBBLING = new Set([\"click\", \"dblclick\", \"input\", \"change\", \"submit\", \"keydown\", \"keyup\", \"mousedown\", \"mouseup\", \"pointerdown\", \"pointerup\"]);\n\nimport { attachCommand, attachEventToken, attachProperty, attachSpread, whenDefined, type Bindable } from \"./wc\";\n\nexport const K_TEXT = 0;\nexport const K_PROP = 1;\nexport const K_CLASS = 2;\nexport const K_ATTR = 3;\nexport const K_STYLE = 4;\nexport const K_EVENT = 5;\nexport const K_FOR = 6;\nexport const K_IF = 7;\nexport const K_HTML = 8;\nexport const K_RADIO = 9;\nexport const K_CHECKBOX = 10;\n/** A property of a custom element (direction and authority from its wc-bindable declaration). */\nexport const K_CUSTOM = 11;\nexport const K_COMMAND = 12;\nexport const K_EVTTOKEN = 13;\nexport const K_SPREAD = 14;\n\n\nexport interface BranchSpec {\n /** Index into the plan's node paths: the anchor this branch renders before. */\n node: number;\n plan: RowPlan;\n /** null for `else:`. */\n pattern: Pattern | null;\n filters: FilterFn[] | null;\n}\n\nexport interface Spec {\n /** Index into the plan's node paths (unused at the root). */\n node: number;\n kind: number;\n /** Property / class / attribute / style name, or the event type. */\n name: string;\n pattern: Pattern | null;\n filters: FilterFn[] | null;\n /** What the DOM already shows, so the first apply can skip a no-op write. */\n initial: unknown;\n /** Event handler, run for the row of the block the element is in (null outside rows). */\n listener: ((e: Event, row: StateRow | null) => void) | null;\n /** An event binding whose type bubbles: dispatched from the root listener. */\n delegated: boolean;\n /** `on*#direct:`: a listener on the element itself (see attachEvent). */\n direct: boolean;\n /** The row plan of a nested `for`. */\n plan: RowPlan | null;\n /** The branches of an `if` / `elseif` / `else` chain. */\n branches: BranchSpec[] | null;\n /** Input filters (left side), applied to what the element writes back. */\n inFilters: FilterFn[] | null;\n /** The event that writes the element's value back to state (two-way, radio, checkbox), or null. */\n twoWay: string | null;\n /** On a custom element: the binding is resolved when the element's class is defined. */\n custom: boolean;\n /** `#init=` / `#sync=` (binding authority on wc-bindable members). */\n init: string | null;\n sync: string | null;\n /** `#ro`: the element never writes back. */\n ro: boolean;\n prevent: boolean;\n stop: boolean;\n /** The path a command / event token binding names: `$command.<token>` / the event token's name. */\n token: string | null;\n /** Spread: members bound explicitly after it on the same element (last wins). */\n exclude: string[] | null;\n /**\n * In a row plan: the index of this binding among the row's slots (-1 = a Binding object is\n * built with the row). A slot binding reads its own row and needs nothing from the element,\n * so the row keeps only its node and value until a change reaches it.\n */\n slot: number;\n}\n\nexport interface RowPlan {\n fragment: DocumentFragment;\n /** The single top-level node (when `single`), cloned directly instead of the fragment. */\n root: Node | null;\n /** Reused per block creation (nodes are handed to bindings before the next block). */\n scratch: Node[];\n /** The child-index path of every bound node (from the fragment). */\n nodePaths: number[][];\n /** The node paths a block resolves when it is built (the others serve only delegated events). */\n build: number[];\n /** The delegated event specs found through the block (by their node paths) when an event passes. */\n events: Spec[];\n /** The specs bound as a block is built (all but `events`). */\n specs: Spec[];\n /** The block renders exactly one top-level node. */\n single: boolean;\n /** Some spec builds a nested view (for / if): the scratch nodes must be copied first. */\n nested: boolean;\n /** The slot specs of a row plan, by slot index (empty for a branch plan). */\n lazy: Spec[];\n}\n\n/**\n * A binding's type as the parser classifies it (@wcstack/state 3.x reports the same in\n * `$errorCallback`'s info, the console and DevTools): `class.` / `attr.` / `style.` / `command.`\n * and HTML are properties, `eventToken.` is an event.\n */\nconst TYPE_NAMES = [\"text\", \"prop\", \"prop\", \"prop\", \"prop\", \"event\", \"for\", \"if\", \"prop\", \"radio\", \"checkbox\", \"prop\", \"prop\", \"event\", \"spread\"];\n\n/** A binding refused as it is attached fails alone (reported as its own failure). */\nexport const failSpec = (engine: Engine, error: unknown, s: Spec, node: Node): void =>\n engine.failAt(error, s.pattern?.path ?? s.token!, node, TYPE_NAMES[s.kind]);\n\n/** A binding's first value when #init= leaves the element as it is: its first apply only records the value. */\nconst HOLD: unique symbol = Symbol() as never;\n\n/**\n * The first value of a binding on an element with no wc-bindable declaration. `#init=none` and\n * `element`, and `auto` over an undefined state value, leave the element as it is (3.3): the\n * value is still read (a getter must be, for a change to reach it) and applied from the next change.\n */\nexport function initialOf(engine: Engine, s: Spec, row: StateRow | null): unknown {\n const init = s.init;\n return init === null || init === \"state\" || (init === \"auto\" && engine.readUntracked(s.pattern!, row) !== undefined) ? s.initial : HOLD;\n}\n\nexport class Binding {\n queued = false;\n declare readonly engine: Engine;\n declare readonly kind: number;\n declare readonly node: Node;\n declare readonly name: string;\n declare readonly pattern: Pattern;\n /** Row at pattern.depth (null for a root-level pattern). */\n declare readonly row: StateRow | null;\n /** The block that renders this binding (null at the root). */\n declare readonly owner: Block | null;\n declare readonly filters: FilterFn[] | null;\n /** Input filters for the value the element writes back. */\n inFilters: FilterFn[] | null = null;\n /** The `if` chain an `if`/`elseif` condition drives. */\n declare readonly chain: IfView | null;\n declare value: unknown;\n /** Set while state writes the element (an event it fires synchronously is our own echo). */\n applying = false;\n\n constructor(engine: Engine, kind: number, node: Node, name: string, pattern: Pattern,\n row: StateRow | null, owner: Block | null, filters: FilterFn[] | null, initial: unknown, chain: IfView | null = null) {\n this.engine = engine;\n this.kind = kind;\n this.node = node;\n this.name = name;\n this.pattern = pattern;\n this.row = row;\n this.owner = owner;\n this.filters = filters;\n this.value = initial;\n this.chain = chain;\n }\n\n typeName(): string {\n return TYPE_NAMES[this.kind];\n }\n\n apply(): void {\n if (this.chain !== null) {\n this.chain.update();\n return;\n }\n const v = pipe(this.filters, this.engine.read(this.pattern, this.row));\n // the same object may have changed in place ($postUpdate, an array assigned again): shown\n // again — but an element input keeps the object it already has, and an HTML sink the markup it\n // parsed (a TrustedHTML does not change: parsing it again would rebuild the nodes). A radio is\n // set again: checking another one of its group unchecked it.\n if (v === this.value && this.kind !== K_RADIO && (typeof v !== \"object\" || v === null || this.kind === K_CUSTOM || this.kind === K_HTML || isHtmlSink(this.name))) return;\n if (this.value === HOLD) {\n this.value = v;\n return;\n }\n const n = this.node as any;\n if (this.kind === K_CUSTOM) {\n if (v === undefined) {\n // an element input keeps its own value when state has no opinion (B8)\n this.value = v;\n return;\n }\n this.value = v;\n this.applying = true;\n try {\n if (n[this.name] !== v) n[this.name] = v;\n } finally {\n this.applying = false;\n }\n return;\n }\n if (this.kind === K_RADIO) n.checked = v !== undefined && this.elementValue() === v;\n else if (this.kind === K_CHECKBOX) n.checked = Array.isArray(v) && v.includes(this.elementValue());\n else applyTo(this.kind, n, this.name, v);\n this.value = v;\n }\n\n /** The element's own value (radio / checkbox), through the input filters. */\n elementValue(): unknown {\n return pipe(this.inFilters, (this.node as any).value);\n }\n\n /** Writes the element's value back to state (two-way, radio, checkbox). */\n writeBack(): void {\n const n = this.node as any;\n const engine = this.engine;\n let v: unknown;\n if (this.kind === K_RADIO) {\n if (!n.checked) return;\n v = this.elementValue();\n } else if (this.kind === K_CHECKBOX) {\n const e = this.elementValue();\n const cur = engine.readUntracked(this.pattern, this.row);\n const arr = Array.isArray(cur) ? cur : [];\n const has = arr.includes(e);\n // checked and listed, or neither: nothing to write\n if (n.checked ? has : !has) return;\n v = has ? arr.filter((x) => x !== e) : [...arr, e];\n } else {\n v = pipe(this.inFilters, n[this.name]);\n // the element shows its own value now, not the last applied one: the next apply runs (NaN\n // equals nothing) — a write in the same drain may put that value back (a reset, a validation)\n this.value = NaN;\n }\n engine.write(this.pattern, this.row, v, false, true);\n }\n}\n\n/** A property that is the element's content (its children are a value). */\nexport const isContent = (name: string): boolean => name === \"textContent\" || name === \"innerText\" || name === \"innerHTML\";\n\n/**\n * Writes `v` to the element: the kinds that need nothing but the node and the name (the\n * ones a row slot can hold).\n */\nexport function applyTo(kind: number, n: any, name: string, v: unknown): void {\n switch (kind) {\n case K_TEXT:\n n.data = v == null ? \"\" : String(v);\n return;\n case K_PROP:\n // display surfaces: undefined and null both mean \"no value\" (B8); other properties are element inputs\n if (isContent(name)) {\n // a string, as a browser's setter makes it (happy-dom — the server's DOM — writes 0 as \"\", and\n // throws on a number for innerText); innerHTML keeps a TrustedHTML as it is\n n[name] = name === \"innerHTML\" ? trustHtml(v) : v == null ? \"\" : String(v);\n } else if (isHtmlSink(name)) {\n // srcdoc without a value: the attribute goes (the frame shows its src again, as attr.srcdoc:\n // did); outerHTML: undefined writes nothing (\"\" would take the element itself out)\n if (v == null && name === \"srcdoc\") n.removeAttribute(name);\n else if (v !== undefined) n[name] = trustHtml(v);\n } else if (v !== undefined) {\n // undefined: an element input keeps its own value when state has no opinion (B8);\n // never re-write what the element already shows (keeps the caret while typing)\n if (n[name] !== v && !(name === \"value\" && n.value === String(v))) n[name] = v;\n // a select's value may name an option not rendered yet: kept for reselect\n if ((name === \"value\" || name === \"selectedIndex\") && n.localName === \"select\") n[SELECTED] = [name, v];\n }\n return;\n case K_HTML:\n n.innerHTML = trustHtml(v);\n return;\n case K_CLASS:\n if (v != null && typeof v !== \"boolean\") {\n raise(M.ClassNeedsBoolean, [name, typeof v]);\n }\n n.classList.toggle(name, v === true);\n return;\n case K_ATTR:\n if (v == null) n.removeAttribute(name);\n else n.setAttribute(name, String(v));\n return;\n case K_STYLE:\n // the property as CSS writes it (background-color, --gap), or as the DOM does\n // (backgroundColor, which setProperty ignores; 3.x wrote style[name])\n if (!name.includes(\"-\")) n.style[name] = v == null ? \"\" : String(v);\n else if (v == null) n.style.removeProperty(name);\n else n.style.setProperty(name, String(v));\n return;\n }\n}\n\n/** A select's last bound `value` / `selectedIndex`: [name, value]. */\nconst SELECTED: unique symbol = Symbol() as never;\n\n/**\n * A view rendered options into `parent`: the select's bound value is applied again. A block binds\n * its plan in document order, so a select's value there comes before the options a `for` inside\n * it renders, and names none of them; so does a value applied before a later change renders more\n * options (3.3 applies it after the options). (On the page a select's children are bound first.)\n */\nfunction reselect(parent: Node): void {\n const sel: any = (parent as Element).localName === \"optgroup\" ? parent.parentNode : parent;\n const r = sel?.[SELECTED];\n if (r !== undefined) sel[r[0]] = r[1];\n}\n\n/**\n * One rendering of a plan: a list row (RowView) or the content of an `if` branch.\n * It owns its nodes, its bindings and the structural views nested in it.\n */\nexport class Block {\n alive = true;\n /** The row this block renders in (its own row for a RowView; the enclosing row, or null, for an if branch). */\n declare readonly row: StateRow | null;\n declare readonly first: ChildNode;\n /** All top-level nodes when the plan renders more than one. */\n declare readonly nodes: ChildNode[] | null;\n /** The Binding objects built with this block, unregistered when it goes (allocated on first use). */\n bindings: Binding[] | null = null;\n children: (ForView | IfView)[] | null = null;\n /** Run when the block goes away (token unsubscriptions); allocated on first use. */\n cleanups: (() => void)[] | null = null;\n /** The view anchored at the block's first top-level node: it renders before the block's first node. */\n lead: ForView | IfView | null = null;\n declare readonly plan: RowPlan;\n\n constructor(row: StateRow | null, first: ChildNode, nodes: ChildNode[] | null, plan: RowPlan) {\n this.row = row;\n this.first = first;\n this.nodes = nodes;\n this.plan = plan;\n }\n\n /**\n * An event of `type` reached this block's top node: runs the handlers of the block's\n * elements it passed, innermost first. Returns true when one of them stopped it.\n */\n dispatch(type: string, e: Event): boolean {\n const target = e.target as Node;\n const plan = this.plan;\n // the specs are in document order (an element's own together): the elements the event passed\n // are met outermost first, so each one's handlers go in front — innermost first\n const hits: Spec[][] = [];\n let last: Node | null = null;\n for (const s of plan.events) {\n if (s.name !== type) continue;\n const path = plan.nodePaths[s.node];\n const n = nodeAt(this.nodes === null ? this.first : this.nodes[path[0]], path, 1);\n if (!n.contains(target)) continue;\n if (n !== last) hits.unshift([]);\n hits[0].push(s);\n last = n;\n }\n // stopPropagation stops the elements further out, not the rest of the same element's (as the DOM)\n for (const own of hits) {\n for (const s of own) s.listener!(e, this.row);\n if (e.cancelBubble) return true;\n }\n return false;\n }\n\n get last(): ChildNode {\n return this.nodes === null ? this.first : this.nodes[this.nodes.length - 1];\n }\n\n /**\n * The block's first node. A view nested at the block's top level renders before its anchor, so\n * the block spans from here to its last top-level node, the rows and branches of those views\n * included.\n */\n head(): ChildNode {\n const v = this.lead;\n return (v === null ? null : v.headAt(this.first)) ?? this.first;\n }\n\n insertBefore(parent: Node, ref: Node | null): void {\n const last = this.last;\n for (let n = this.head(); ; ) {\n const next = n.nextSibling!;\n parent.insertBefore(n, ref);\n if (n === last) return;\n n = next;\n }\n }\n\n removeNodes(): void {\n if (this.nodes === null) this.first.remove();\n else removeContiguous(this.head(), this.last);\n }\n\n /** Stops the block: runs its cleanups, unregisters its bindings, disposes the views nested in it. */\n dispose(engine: Engine): void {\n this.alive = false;\n if (this.cleanups !== null) for (const c of this.cleanups) c();\n const bs = this.bindings;\n if (bs !== null) for (let i = 0; i < bs.length; i++) engine.unregister(bs[i]);\n if (this.children !== null) for (const c of this.children) c.dispose();\n }\n}\n\n/**\n * The rendering of one row by one for view. Its slot bindings (plan.lazy) are kept as\n * node / value pairs and become Binding objects only when a change first reaches them:\n * creating a row allocates no Binding for them and registers nothing — a change of the\n * row finds them through the row's views (Engine.enqueueBound).\n */\nexport class RowView extends Block {\n /** Position in the view's previous order (set during an update). */\n pos = 0;\n /** [node0, value0, node1, value1, …] by slot; the value is the last one applied. */\n declare readonly slots: unknown[] | null;\n /** The Binding objects the slots became (sparse, allocated on first use). */\n bound: (Binding | undefined)[] | null = null;\n\n constructor(row: StateRow, first: ChildNode, nodes: ChildNode[] | null, plan: RowPlan) {\n super(row, first, nodes, plan);\n this.slots = plan.lazy.length === 0 ? null : new Array(plan.lazy.length * 2);\n }\n\n /** The Binding object of slot k (built on first use; from then on it holds the value). */\n slotBinding(engine: Engine, k: number): Binding {\n const bound = (this.bound ??= new Array(this.plan.lazy.length));\n let b = bound[k];\n if (b === undefined) {\n const s = this.plan.lazy[k];\n const slots = this.slots!;\n b = bound[k] = new Binding(engine, s.kind, slots[2 * k] as Node, s.name, s.pattern!, this.row, this, s.filters, slots[2 * k + 1]);\n }\n return b;\n }\n\n /** Queues the slot bindings on `p` or under it. */\n enqueueSlots(engine: Engine, p: Pattern): void {\n const lazy = this.plan.lazy;\n for (let k = 0; k < lazy.length; k++) if (lazy[k].pattern!.isUnder(p)) engine.enqueue(this.slotBinding(engine, k));\n }\n\n override dispose(engine: Engine): void {\n const row = this.row!;\n if (row.view === this) row.view = null;\n super.dispose(engine);\n }\n}\n\n/**\n * The list whose rows `p` ranges over, in the context of `row`. A path that fails to read\n * (a missing top-level key) is reported as the `for` binding's failure and the list starts\n * empty: it was created before the read, so a later write of the path fills it.\n */\nexport function listFor(engine: Engine, p: Pattern, row: StateRow | null, anchor: Node): StateList {\n const parent = rowAt(row, p.depth);\n try {\n return engine.childList(parent, p);\n } catch (error) {\n engine.failAt(error, p.path, anchor, \"for\");\n return parent === null ? engine.rootLists.get(p)! : parent.children!.get(p)!;\n }\n}\n\n/**\n * Records `b` in its block (unregistered when the block goes) and, unless it only carries\n * element → state, registers it where a change of its location finds it.\n */\nexport function adopt(engine: Engine, b: Binding, register: boolean): void {\n if (register) engine.register(b);\n const owner = b.owner;\n if (owner !== null) (owner.bindings ??= []).push(b);\n}\n\n/** The block built by the last buildBlock call (taken right after it; saves an allocation per row). */\nlet lastBlock: Block | null = null;\n\n/** The block the last buildBlock call built; released here so a removed tree is not kept alive. */\nfunction takeBlock(): Block {\n const b = lastBlock!;\n lastBlock = null;\n return b;\n}\n\n/** The auto-naming cap for the blocks being built (-1: none), read once per view update. */\nlet naming = -1;\n\n/**\n * Clones the plan in the context of `row`, binds it and applies the initial values\n * (off-document). `fv`: the for view the block is a row of (null for an if branch).\n * Returns the node to insert: the block's element, or a fragment of its nodes.\n */\nexport function buildBlock(engine: Engine, plan: RowPlan, row: StateRow | null, fv: ForView | null, at: Node | null = null): Node {\n const paths = plan.nodePaths;\n const build = plan.build;\n const nodes = plan.scratch;\n let first: ChildNode;\n let all: ChildNode[] | null = null;\n // SSR hydration: the server's nodes, where they are (the add-on put the plan's nodes in them in\n // `nodes`); the view then inserts an empty fragment\n const adopted = hooks.adopt?.(plan, fv === null ? at! : fv.anchor, fv !== null);\n const single = !adopted && plan.single;\n // a single plan clones the block's element itself; paths start at the fragment, so skip their first step\n const top = adopted ? document.createDocumentFragment() : (single ? plan.root! : plan.fragment).cloneNode(true);\n if (!adopted) for (let b = 0; b < build.length; b++) {\n const i = build[b];\n nodes[i] = nodeAt(top, paths[i], single ? 1 : 0);\n }\n if (single) {\n first = top as ChildNode;\n } else {\n all = adopted || [...top.childNodes] as ChildNode[];\n first = all[0];\n }\n let block: Block;\n let rv: RowView | null = null;\n if (fv !== null) {\n block = rv = new RowView(row!, first, all, plan);\n if (fv.map === null) row!.view = rv;\n else fv.map.set(row!, rv);\n } else {\n block = new Block(row, first, all, plan);\n }\n if (naming >= 0) nameBlock(first, all, fv !== null ? \"row\" : \"branch\", naming);\n if (plan.events.length > 0) {\n // delegated events find the block through its top node(s)\n const key = engine.blockKey;\n if (all === null) (first as any)[key] = block;\n else for (const n of all) if (n.nodeType === 1) (n as any)[key] = block;\n }\n const specs = plan.specs;\n const rendered = engine.rendered;\n // the scratch array is ours until a nested view builds a block of another plan: take\n // every node we need before that can happen\n const own = plan.nested ? nodes.slice(0, paths.length) : nodes;\n const slots = rv === null ? null : rv.slots;\n if (slots !== null) {\n // every slot has its node before anything runs: an element bound earlier in the row can\n // write state (wc-bindable seeding) and so reach a slot further on\n const lazy = plan.lazy;\n for (let k = 0; k < lazy.length; k++) {\n slots[2 * k] = own[lazy[k].node];\n slots[2 * k + 1] = lazy[k].initial;\n }\n }\n for (let i = 0; i < specs.length; i++) {\n const s = specs[i];\n const node = own[s.node];\n const k = s.slot;\n if (k >= 0 && slots !== null) {\n // a slot: the node and the value are all the row keeps\n const b = rv!.bound?.[k];\n if (b !== undefined) {\n // already reached by a change during this build: it is a Binding now, applied here (and\n // so no longer queued: the drain skips it)\n b.queued = false;\n engine.applyBinding(b);\n continue;\n }\n try {\n const v = pipe(s.filters, engine.read(s.pattern!, row));\n if (v !== s.initial) {\n applyTo(s.kind, node, s.name, v);\n slots[2 * k + 1] = v;\n }\n if (rendered !== null) engine.noteRendered(s.pattern!, row);\n } catch (error) {\n engine.fail(error, rv!.slotBinding(engine, k));\n }\n continue;\n }\n switch (s.kind) {\n case K_FOR: {\n const view = new ForView(engine, s.plan!, listFor(engine, s.pattern!, row, node), node as Comment);\n (block.children ??= []).push(view);\n if (node === first) block.lead = view;\n view.update();\n break;\n }\n case K_IF: {\n const iv = attachChain(engine, s.branches!.map((br) => ({ plan: br.plan, pattern: br.pattern, filters: br.filters, anchor: own[br.node] })), row, block);\n (block.children ??= []).push(iv);\n if (node === first) block.lead = iv;\n break;\n }\n default:\n // (the delegated events found through the block are not among the specs: nothing per row)\n // A binding refused as it is attached (an undeclared token or member, a failing `#init=auto`\n // read) fails alone: the row is still built whole, so its view's records stay right\n try {\n attachSpec(engine, s, node, row, block);\n } catch (error) {\n failSpec(engine, error, s, node);\n }\n }\n }\n lastBlock = block;\n return top;\n}\n\n/**\n * Binds a spec that builds no view to `node`, in `block` (null: a root-level element). A\n * delegated event that reaches here is stored on the element (attachEvent).\n */\nexport function attachSpec(engine: Engine, s: Spec, node: Node, row: StateRow | null, block: Block | null): void {\n const el = node as Element;\n switch (s.kind) {\n case K_EVENT:\n attachEvent(engine, node, s, row, block);\n return;\n case K_COMMAND:\n whenDefined(engine, s, el, block, (bd) => attachCommand(engine, s, el, block, bd));\n return;\n case K_EVTTOKEN:\n whenDefined(engine, s, el, block, (bd) => attachEventToken(engine, s, el, row, bd));\n return;\n }\n const p = s.pattern!;\n const brow = rowAt(row, p.depth);\n if (s.kind === K_SPREAD) {\n whenDefined(engine, s, el, block, (bd) => attachSpread(engine, s, el, brow, block, bd));\n return;\n }\n if (s.custom && s.kind === K_PROP) {\n whenDefined(engine, s, el, block, (bd) => attachCustomOrPlain(engine, s, el, brow, block, bd));\n return;\n }\n const b = new Binding(engine, s.kind, node, s.name, p, brow, block, s.filters, initialOf(engine, s, brow));\n b.inFilters = s.inFilters;\n adopt(engine, b, true);\n engine.applyBinding(b);\n if (s.twoWay !== null) node.addEventListener(s.twoWay, () => b.writeBack());\n}\n\n/** A property binding on a custom element: wc-bindable members get direction and authority, others are plain. */\nexport function attachCustomOrPlain(engine: Engine, s: Spec, el: Element, row: StateRow | null, owner: Block | null, bd: Bindable | null): void {\n if (bd !== null) {\n attachProperty(engine, s, el, s.name, s.pattern!, row, owner, bd);\n return;\n }\n const b = new Binding(engine, K_PROP, el, s.name, s.pattern!, row, owner, s.filters, initialOf(engine, s, row));\n b.inFilters = s.inFilters;\n if (hooks.hostBinding?.(b, s.ro)) return;\n adopt(engine, b, true);\n engine.applyBinding(b);\n}\n\nexport interface Branch {\n plan: RowPlan;\n pattern: Pattern | null;\n filters: FilterFn[] | null;\n anchor: Node;\n}\n\n/**\n * Builds an `if` chain: one condition binding per `if`/`elseif` (each drives the whole\n * chain) and the initial render. `owner` is the enclosing block (null at the root).\n */\nexport function attachChain(engine: Engine, branches: Branch[], row: StateRow | null, owner: Block | null): IfView {\n const iv = new IfView(engine, branches, row);\n let first: Binding | null = null;\n for (const br of branches) {\n if (br.pattern === null) continue;\n const p = br.pattern;\n const b = new Binding(engine, K_IF, br.anchor, \"if\", p, rowAt(row, p.depth), owner, null, undefined, iv);\n adopt(engine, b, true);\n if (owner === null) iv.rootBindings.push(b);\n first ??= b;\n }\n // the first branch is the `if:`: it always has a condition\n engine.applyBinding(first!);\n return iv;\n}\n\nexport class IfView {\n alive = true;\n current: Block | null = null;\n index = -1;\n /** Condition bindings of a root-level chain (a nested chain's belong to its block). */\n readonly rootBindings: Binding[] = [];\n declare readonly engine: Engine;\n declare readonly branches: Branch[];\n declare readonly row: StateRow | null;\n\n constructor(engine: Engine, branches: Branch[], row: StateRow | null) {\n this.engine = engine;\n this.branches = branches;\n this.row = row;\n }\n\n /** The first node this chain renders before anchor `n` (the shown branch's, if `n` is its anchor). */\n headAt(n: Node): ChildNode | null {\n return this.current !== null && this.branches[this.index].anchor === n ? this.current.head() : null;\n }\n\n /** Renders the first branch whose condition holds (JavaScript truthiness), or nothing. */\n update(): void {\n const engine = this.engine;\n let index = -1;\n for (let i = 0; i < this.branches.length; i++) {\n const br = this.branches[i];\n // `else:` (no condition) always holds\n if (br.pattern === null || pipe(br.filters, engine.read(br.pattern, rowAt(this.row, br.pattern.depth)))) {\n index = i;\n break;\n }\n }\n if (index === this.index) return;\n naming = autoNaming();\n if (this.current !== null) {\n this.current.removeNodes();\n this.current.dispose(engine);\n this.current = null;\n }\n this.index = index;\n if (index >= 0) {\n const br = this.branches[index];\n const top = buildBlock(engine, br.plan, this.row, null, br.anchor);\n this.current = takeBlock();\n const parent = br.anchor.parentNode!;\n parent.insertBefore(top, br.anchor);\n reselect(parent);\n }\n }\n\n dispose(): void {\n this.alive = false;\n for (const b of this.rootBindings) this.engine.unregister(b);\n if (this.current !== null) this.current.dispose(this.engine);\n }\n}\n\nexport class ForView {\n alive = true;\n rowViews: RowView[] = [];\n declare readonly engine: Engine;\n declare readonly plan: RowPlan;\n declare readonly list: StateList;\n declare readonly anchor: Comment;\n /**\n * The row views by row when another for view already renders this list (the list's first\n * view keeps them on row.view instead).\n */\n declare readonly map: Map<StateRow, RowView> | null;\n\n constructor(engine: Engine, plan: RowPlan, list: StateList, anchor: Comment) {\n this.engine = engine;\n this.plan = plan;\n this.list = list;\n this.anchor = anchor;\n if (list.view === null) {\n list.view = this;\n this.map = null;\n } else {\n (list.extra ??= []).push(this);\n this.map = new Map();\n }\n }\n\n /** The first node this view renders (before its anchor), or null with no rows. */\n headAt(_n: Node): ChildNode | null {\n return this.rowViews.length === 0 ? null : this.rowViews[0].head();\n }\n\n /** This view's rendering of `row`, or null. */\n viewOf(row: StateRow): RowView | null {\n return this.map === null ? row.view : this.map.get(row) ?? null;\n }\n\n private drop(rv: RowView): void {\n const map = this.map;\n if (map !== null && map.get(rv.row!) === rv) map.delete(rv.row!);\n rv.dispose(this.engine);\n }\n\n /** Brings the DOM in line with list.rows, moving kept rows as little as possible. */\n update(): void {\n const engine = this.engine;\n const rows = this.list.rows;\n const old = this.rowViews;\n naming = autoNaming();\n const n = rows.length;\n const o = old.length;\n const anchor = this.anchor;\n const parent = anchor.parentNode!;\n\n if (n === 0) {\n if (o > 0) {\n const first = old[0].head();\n const last = old[o - 1].last;\n // the rows are all the parent holds but the anchor and text (a <tbody> of rows, its whitespace):\n // one call empties it and puts those back — faster than a Range in Chromium (10,000 rows: 14 %; node\n // by node is 5 % slower than one) and linear in happy-dom. An element beside them would be put back\n // too (a custom element reconnected, an iframe reloaded): then node by node\n let keep: Node[] | null = [];\n for (let x = parent.firstChild; x !== null; x = x === first ? last.nextSibling : x.nextSibling) {\n if (x === first) continue;\n if (x !== anchor && x.nodeType !== 3) {\n keep = null;\n break;\n }\n keep.push(x);\n }\n if (keep !== null) parent.replaceChildren(...keep);\n else removeContiguous(first, last);\n for (let i = 0; i < o; i++) this.drop(old[i]);\n }\n this.rowViews = [];\n return;\n }\n\n const views: RowView[] = new Array(n);\n let s = 0;\n while (s < n && s < o && this.viewOf(rows[s]) === old[s]) {\n views[s] = old[s];\n s++;\n }\n let oe = o - 1;\n let ne = n - 1;\n while (oe >= s && ne >= s && this.viewOf(rows[ne]) === old[oe]) {\n views[ne] = old[oe];\n oe--;\n ne--;\n }\n for (let i = s; i <= oe; i++) {\n const rv = old[i];\n const row = rv.row!;\n if (!row.alive || this.viewOf(row) !== rv) {\n rv.removeNodes();\n this.drop(rv);\n } else {\n rv.pos = i;\n }\n }\n if (s <= ne) {\n const m = ne - s + 1;\n const src = new Int32Array(m);\n let anyKept = false;\n // no rows before: none kept (the first render builds every row)\n if (o > 0) for (let i = 0; i < m; i++) {\n const rv = this.viewOf(rows[s + i]);\n if (rv !== null && rv.alive) {\n src[i] = rv.pos;\n anyKept = true;\n } else {\n src[i] = -1;\n }\n }\n const next0: Node = ne + 1 < n ? views[ne + 1].head() : anchor;\n if (!anyKept) {\n const frag = document.createDocumentFragment();\n for (let i = s; i <= ne; i++) {\n frag.appendChild(buildBlock(engine, this.plan, rows[i], this));\n views[i] = takeBlock() as RowView;\n }\n parent.insertBefore(frag, next0);\n } else {\n const keep = lisKeep(src);\n let next: Node = next0;\n for (let i = m - 1; i >= 0; i--) {\n const row = rows[s + i];\n let rv = this.viewOf(row);\n if (rv === null || !rv.alive) {\n parent.insertBefore(buildBlock(engine, this.plan, row, this), next);\n rv = takeBlock() as RowView;\n } else if (keep[i] === 0) {\n rv.insertBefore(parent, next);\n }\n views[s + i] = rv;\n next = rv.head();\n }\n }\n }\n this.rowViews = views;\n reselect(parent);\n }\n\n dispose(): void {\n this.alive = false;\n const list = this.list;\n if (list.view === this) {\n list.view = null;\n } else if (list.extra !== null) {\n const i = list.extra.indexOf(this);\n if (i >= 0) list.extra.splice(i, 1);\n if (list.extra.length === 0) list.extra = null;\n }\n for (const rv of this.rowViews) rv.dispose(this.engine);\n this.map?.clear();\n }\n}\n\n/** The node `path` leads to from `n`, following its steps from `j` on. */\nfunction nodeAt(n: Node, path: number[], j: number): Node {\n for (; j < path.length; j++) {\n n = n.firstChild!;\n for (let k = path[j]; k > 0; k--) n = n.nextSibling!;\n }\n return n;\n}\n\nfunction removeContiguous(first: ChildNode, last: ChildNode): void {\n // node by node, not a Range's deleteContents(): happy-dom's (the DOM of @wcstack/testing and of SSR)\n // is quadratic — a list of 1,000 rows took 13 s to empty\n for (let n = first, next; n !== last; n = next) {\n next = n.nextSibling!;\n n.remove();\n }\n last.remove();\n}\n\n/** Marks the entries (>= 0) that form a longest increasing subsequence of `src`. */\nexport function lisKeep(src: Int32Array): Uint8Array {\n const n = src.length;\n const keep = new Uint8Array(n);\n const prev = new Int32Array(n).fill(-1);\n const tails: number[] = [];\n for (let i = 0; i < n; i++) {\n const v = src[i];\n if (v < 0) continue;\n let lo = 0;\n let hi = tails.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (src[tails[mid]] < v) lo = mid + 1;\n else hi = mid;\n }\n if (lo > 0) prev[i] = tails[lo - 1];\n tails[lo] = i;\n }\n let k = tails.length > 0 ? tails[tails.length - 1] : -1;\n while (k >= 0) {\n keep[k] = 1;\n k = prev[k];\n }\n return keep;\n}\n","import { INDEX_PARAM, isThenable, type Engine } from \"../engine\";\nimport type { StateRow } from \"../list\";\nimport { UNSET, type Pattern } from \"../pattern\";\nimport { config } from \"../config\";\nimport { parseBindTextForEmbeddedNode, parseBindTextsForElement, type ParsedBinding } from \"../parser/index\";\nimport { buildFilters, type FilterFn } from \"./filters\";\nimport { raise, M } from \"../messages\";\nimport { hooks } from \"../hooks\";\nimport { isHtmlSink } from \"../trustedTypes\";\nimport {\n K_ATTR, K_CHECKBOX, K_CLASS, K_COMMAND, K_EVENT, K_EVTTOKEN, K_FOR, K_HTML, K_IF, K_PROP, K_RADIO, K_SPREAD, K_STYLE, K_TEXT, BUBBLING,\n isContent, type Branch, type BranchSpec, type RowPlan, type Spec,\n} from \"./view\";\nimport { report } from \"../parser/raiseError\";\n\n/** The binding attribute (`bindAttributeName`, default data-wcs). */\nexport const bindAttr = (): string => config.bindAttributeName;\n\n/** `.label` / `.` inside a `for: data` template → `data.*.label` / `data.*`. */\nexport function expandPath(path: string, list: Pattern | null): string {\n if (path.charCodeAt(0) !== 46 /* . */) return path;\n if (list === null) raise(M.WildcardRelative, [path]);\n return path === \".\" ? `${list.path}.*` : `${list.path}.*${path}`;\n}\n\nfunction blank(): Spec {\n return {\n node: 0, kind: K_PROP, name: \"\", pattern: null, filters: null, initial: UNSET, listener: null, plan: null, branches: null,\n inFilters: null, twoWay: null, custom: false, init: null, sync: null, ro: false, prevent: false, stop: false, token: null, exclude: null,\n slot: -1, delegated: false, direct: false,\n };\n}\n\n/** Native elements whose property flows back to state (custom elements come with wc-bindable). */\nfunction isTwoWay(el: Element, prop: string): boolean {\n const tag = el.localName;\n if (tag === \"input\") {\n const type = (el.getAttribute(\"type\") || \"text\").toLowerCase();\n if (type === \"button\") return false;\n if ((type === \"radio\" || type === \"checkbox\") && prop === \"checked\") return true;\n return prop === \"value\" || prop === \"valueAsNumber\" || prop === \"valueAsDate\";\n }\n return (tag === \"select\" || tag === \"textarea\") && prop === \"value\";\n}\n\ninterface Flags {\n ro: boolean;\n prevent: boolean;\n stop: boolean;\n /** `#onchange` → \"change\": the event that writes back instead of the default. */\n event: string | null;\n init: string | null;\n sync: string | null;\n}\n\nconst INITS = [\"state\", \"element\", \"auto\", \"none\"];\nconst SYNCS = [\"call\", \"connect\"];\n\n/** `#ro`, `#prevent`, `#stop`, `#onchange`, `#init=…`, `#sync=…` (`#direct`: specFor). */\nfunction flags(engine: Engine, mods: string[]): Flags {\n const on = mods.find((m) => m.startsWith(\"on\"));\n // (the keys are compared, never used as property names: the build renames `init` / `sync`)\n let init: string | null = null;\n let sync: string | null = null;\n for (const m of mods) {\n const i = m.indexOf(\"=\");\n if (i < 0) continue;\n if (!engine.directional) raise(M.DirectionalSyncDisabled);\n const key = m.slice(0, i).trim();\n const value = m.slice(i + 1).trim();\n const isInit = key === \"init\";\n if (!isInit && key !== \"sync\") raise(M.ModifierUnknown, [key, m]);\n if ((isInit ? init : sync) !== null) raise(M.ModifierTwice, [key]);\n if (!(isInit ? INITS : SYNCS).includes(value)) raise(M.ModifierValue, [key, value]);\n if (isInit) init = value;\n else sync = value;\n }\n return {\n ro: mods.includes(\"ro\"), prevent: mods.includes(\"prevent\"), stop: mods.includes(\"stop\"),\n event: on ? on.slice(2) : null, init, sync,\n };\n}\n\nconst COMMAND_PREFIX = \"$command.\";\n\n/** The pattern of a path a binding names (shown to the diagnostics add-on). */\nexport function boundPattern(engine: Engine, path: string, list: Pattern | null): Pattern {\n // `$1` is the loop index: a row pattern of the innermost loop answers it (Engine.markupAccessor)\n if (INDEX_PARAM.test(path)) {\n if (list === null) raise(M.WildcardNoLoop, [path, Number(path.slice(1))]);\n path = `${list.path}.*.${path}`;\n }\n const p = engine.pattern(expandPath(path, list));\n // each \"*\" is the row of the enclosing loop at its level, never a row of another list (F32)\n const d = list === null ? 0 : list.depth + 1;\n if (p.depth > d) raise(M.WildcardNoLoop, [p.path, p.depth, d]);\n for (let k = 1; k <= p.depth; k++) {\n const loop = k === d ? list! : list!.lists[k]!;\n if (p.lists[k] !== loop) raise(M.WildcardOtherList, [p.path, p.lists[k]!.path, loop.path]);\n }\n hooks.declared?.(engine, p);\n return p;\n}\n\n/**\n * A binding that replaces its element with the value (`outerHTML:` / `outerText:`, the properties —\n * not `class.outerHTML:`, `attr.outerText:` or an `on…:` event of that name).\n */\nexport const isOuter = (s: Spec): boolean => s.kind === K_PROP && (s.name === \"outerHTML\" || s.name === \"outerText\");\n\n/**\n * A binding after which the element's children are not markup to bind: it sets the element's content\n * (they are a value), or replaces the element (they are out of the page).\n */\nexport const setsContent = (s: Spec): boolean =>\n s.kind === K_HTML || isOuter(s) || (s.kind === K_PROP && isContent(s.name));\n\n/** An `elseif:` / `else:` template with no `if:` before it. */\nexport function notAfterIf(type: string): never {\n raise(M.ElseWithoutIf, [type]);\n}\n\nexport function specFor(engine: Engine, b: ParsedBinding, list: Pattern | null, el: Element, node: number): Spec {\n const f = flags(engine, b.propModifiers);\n const custom = el.localName.includes(\"-\");\n const segs = b.propSegments;\n const path = b.statePathName;\n\n if (b.bindingType === \"event\") {\n if (f.init !== null && f.init !== \"none\") raise(M.EventInitNone);\n if (segs[0] === \"eventToken\") {\n return { ...blank(), node, kind: K_EVTTOKEN, name: segs.slice(1).join(\".\"), token: path, custom, prevent: f.prevent, stop: f.stop };\n }\n // `onclick: $command.x` emits a command token; `onclick: method` calls a state method\n const command = path.startsWith(COMMAND_PREFIX) ? path.slice(COMMAND_PREFIX.length) : null;\n const { prevent, stop } = f;\n const type = b.propName.slice(2);\n // `#direct`: a listener on the element itself, as 3.x (see attachEvent). (A custom element's\n // `change` / `click` may be dispatched without bubbling: see attachEvent too)\n const direct = b.propModifiers.includes(\"direct\");\n const delegated = !direct && BUBBLING.has(type);\n if (delegated) engine.delegate(type);\n // (a delegated handler's failure: the diagnostics add-on says when event.currentTarget, the root there, is why)\n const fail = (error: unknown): void => {\n report(error);\n if (delegated) hooks.handlerThrew?.(engine, path, type);\n };\n return {\n ...blank(), node, kind: K_EVENT, name: type, delegated, custom, direct,\n listener(e: Event, row: StateRow | null) {\n if (prevent) e.preventDefault();\n if (stop) e.stopPropagation();\n try {\n if (command !== null) engine.emitCommand(command, e, row);\n else {\n // an async handler's failure is reported like a sync one's (not left unhandled)\n const r = engine.invoke(path, e, row) as any;\n if (isThenable(r)) r.then(undefined, fail);\n }\n } catch (error) {\n fail(error);\n }\n },\n };\n }\n if (b.bindingType === \"spread\") {\n return { ...blank(), node, kind: K_SPREAD, pattern: boundPattern(engine, path, list), custom };\n }\n if (segs[0] === \"command\" && segs.length > 1) {\n if (!path.startsWith(COMMAND_PREFIX)) raise(M.CommandRightSide, [b.propName, path]);\n return { ...blank(), node, kind: K_COMMAND, name: segs.slice(1).join(\".\"), token: path, custom };\n }\n\n const pattern = boundPattern(engine, path, list);\n const spec: Spec = {\n ...blank(), node, kind: K_PROP, name: b.propName, pattern,\n filters: buildFilters(b.outFilters), inFilters: buildFilters(b.inFilters), ro: f.ro, init: f.init, sync: f.sync,\n };\n if (b.bindingType === \"radio\" || b.bindingType === \"checkbox\") {\n if (f.init === \"element\" || f.init === \"auto\") raise(M.InitUnsupported, [b.bindingType, f.init]);\n spec.kind = b.bindingType === \"radio\" ? K_RADIO : K_CHECKBOX;\n if (!f.ro) spec.twoWay = f.event ?? \"input\";\n return spec;\n }\n if (segs.length > 1) {\n const name = segs.slice(1).join(\".\");\n const head = segs[0];\n if (head === \"class\" || head === \"attr\" || head === \"style\") {\n // a namespace takes no initial authority: #init= is ignored (as in 3.3)\n spec.init = null;\n spec.name = name;\n if (head === \"class\") {\n spec.kind = K_CLASS;\n spec.initial = el.classList.contains(name);\n } else {\n // (an iframe's srcdoc attribute is an HTML sink: written as the property, through the policy)\n spec.kind = head === \"attr\" ? (name === \"srcdoc\" && el.localName === \"iframe\" ? K_PROP : K_ATTR) : K_STYLE;\n }\n return spec;\n }\n }\n if (b.propName === \"html\") {\n spec.kind = K_HTML;\n return spec;\n }\n spec.name = b.propName === \"text\" ? \"textContent\" : b.propName;\n // an HTML sink is never a wc-bindable member: written at once, through the policy\n spec.custom = custom && !isHtmlSink(spec.name);\n if (!custom && !f.ro && isTwoWay(el, spec.name)) spec.twoWay = f.event ?? (el.localName === \"select\" ? \"change\" : \"input\");\n return spec;\n}\n\n/**\n * The specs of one element's data-wcs, in order. A spread is told which members are bound\n * explicitly after it (last wins).\n */\nexport function elementSpecs(engine: Engine, text: string, list: Pattern | null, el: Element, node: number): Spec[] {\n const specs = parseBindTextsForElement(text).map((b) => specFor(engine, b, list, el, node));\n for (let i = 0; i < specs.length; i++) {\n if (specs[i].kind !== K_SPREAD) continue;\n specs[i].exclude = specs.slice(i + 1).filter((s) => s.kind === K_PROP).map((s) => s.name);\n }\n return specs;\n}\n\nconst MUSTACHE = /\\{\\{([\\s\\S]+?)\\}\\}/g;\n\n/** Replaces a text node holding `{{ … }}` with static text nodes and empty bound ones. */\nexport function splitMustache(t: Text): { node: Text; expr: string }[] {\n const s = t.data;\n const out: { node: Text; expr: string }[] = [];\n let last = 0;\n MUSTACHE.lastIndex = 0;\n for (let m = MUSTACHE.exec(s); m !== null; m = MUSTACHE.exec(s)) {\n // where the match starts (not `m.index`: `index` is a name the build shortens)\n const at = MUSTACHE.lastIndex - m[0].length;\n // (a string is inserted as a text node of t's document)\n if (at > last) t.before(s.slice(last, at));\n const bound = t.ownerDocument.createTextNode(\"\");\n t.before(bound);\n out.push({ node: bound, expr: m[1].trim() });\n last = MUSTACHE.lastIndex;\n }\n if (out.length === 0) return out;\n if (last < s.length) t.before(s.slice(last));\n t.remove();\n return out;\n}\n\nexport function textSpec(engine: Engine, expr: string, list: Pattern | null, node: number): Spec {\n const b = parseBindTextForEmbeddedNode(expr);\n return { ...blank(), node, kind: K_TEXT, pattern: boundPattern(engine, b.statePathName, list), filters: buildFilters(b.outFilters), initial: \"\" };\n}\n\n/** The structural directive on a template (`for` / `if` / `elseif` / `else`), or null. */\nexport function directive(el: Element): ParsedBinding | null {\n const text = el.getAttribute(bindAttr());\n if (text === null) return null;\n const b = parseBindTextsForElement(text)[0];\n return b !== undefined && (b.bindingType === \"for\" || b.bindingType === \"if\" || b.bindingType === \"elseif\" || b.bindingType === \"else\") ? b : null;\n}\n\nexport interface ChainPart {\n el: HTMLTemplateElement;\n pattern: Pattern | null;\n filters: FilterFn[] | null;\n}\n\n/** The anchor text of a chain's `k`-th template: `if`, then `elseif`, and `else` (no path). */\nexport const chainAnchorText = (k: number, part: ChainPart): string =>\n k === 0 ? config.commentIfPrefix : part.pattern === null ? config.commentElsePrefix : config.commentElseIfPrefix;\n\n/**\n * Reads an `if` chain starting at `first` (an `if:` template): the `elseif:` / `else:` templates\n * that follow it in the tree, across whitespace and comments. The walker skips the ones taken (each\n * is out of the tree, its anchor in its place).\n */\nexport function readChain(engine: Engine, first: Element, list: Pattern | null): ChainPart[] {\n const part = (el: Element, b: ParsedBinding): ChainPart => ({\n el: el as HTMLTemplateElement,\n pattern: b.bindingType === \"else\" ? null : boundPattern(engine, b.statePathName, list),\n filters: b.bindingType === \"else\" ? null : buildFilters(b.outFilters),\n });\n const parts = [part(first, directive(first)!)];\n for (let c = first.nextSibling; c !== null; c = c.nextSibling) {\n if ((c.nodeType === 3 && (c as Text).data.trim() === \"\") || c.nodeType === 8) continue;\n if (c.nodeType !== 1 || (c as Element).localName !== \"template\") break;\n const b = directive(c as Element);\n if (b === null || (b.bindingType !== \"elseif\" && b.bindingType !== \"else\")) break;\n parts.push(part(c as Element, b));\n if (b.bindingType === \"else\") break;\n }\n return parts;\n}\n\n/**\n * The elements a page walk has visited: each is bound once, however often it is handed over. SSR\n * hydration adds the top-level nodes of the server's rows and branches (a text's too): their blocks\n * bind them where they are, and the walk passes them by.\n */\nexport const walked = new WeakSet<Node>();\n\n/**\n * Walks `children` and what they contain for bindings, by the same markup rules for the page\n * (`page`: the mount — it skips script / style, enters `<wcs-state>`, and marks anchors for SSR)\n * and for a template's content (a plan). Structural templates are compiled and replaced by\n * their anchors; the rest is handed to the callbacks.\n */\nexport function walkBindings(engine: Engine, children: ChildNode[], list: Pattern | null, page: boolean,\n onFor: (anchor: Comment, p: Pattern, plan: RowPlan) => void,\n onIf: (branches: Branch[]) => void,\n onElement: (el: Element, specs: Spec[]) => void,\n onText: (node: Text, expr: string) => void): void {\n // a structural template leaves the tree: its anchor takes its place\n const anchorFor = (el: Element, type: string): Comment => {\n const anchor = document.createComment(type);\n el.replaceWith(anchor);\n if (page) hooks.ssrMark?.(engine, anchor, el);\n return anchor;\n };\n const walk = (children: ChildNode[]): void => {\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n // (out of the tree: an `elseif:` / `else:` template its chain's anchor replaced)\n if (child.parentNode === null) continue;\n if (child.nodeType === 1) {\n const el = child as Element;\n const tag = el.localName;\n // `data-wcs-ignore` (the bind attribute + \"-ignore\"): neither the element nor anything in it is read\n // as bindings — markup the page did not write (user content a server template put there; README,\n // \"Markup you did not write\")\n if (el.hasAttribute(bindAttr() + \"-ignore\")) continue;\n if (page) {\n // walked before (a subtree handed over again): left alone — its text and rows show\n // values now, which are not markup\n if (tag === \"script\" || tag === \"style\" || walked.has(el)) continue;\n walked.add(el);\n // markup written inside a <wcs-state> is part of the page (its own attributes are not bindings)\n if (tag === config.tagNames.state) {\n walk([...el.childNodes]);\n continue;\n }\n }\n // a template with no structural directive binds like any element (its content stays inert)\n const d = tag === \"template\" ? directive(el) : null;\n if (d !== null) {\n if (d.bindingType === \"for\") {\n const p = boundPattern(engine, d.statePathName, list);\n const plan = compilePlan(engine, el as HTMLTemplateElement, p, true);\n onFor(anchorFor(el, config.commentForPrefix), p, plan);\n } else if (d.bindingType === \"if\") {\n onIf(readChain(engine, el, list).map((part, k) => {\n const plan = compilePlan(engine, part.el, list, false);\n return { plan, pattern: part.pattern, filters: part.filters, anchor: anchorFor(part.el, chainAnchorText(k, part)) };\n }));\n } else {\n notAfterIf(d.bindingType);\n }\n continue;\n }\n const text = el.getAttribute(bindAttr());\n const specs = text === null ? null : elementSpecs(engine, text, list, el, 0);\n // What a binding puts in an element is a value, not markup. An element whose content a\n // binding sets (`textContent:` / `innerHTML:` / `html:`) is not walked at all — whenever the\n // value lands (a custom element's waits for its definition), and if it fails — nor one a\n // binding replaces (`outerHTML:` / `outerText:`: its children leave the page). Nor is the\n // content of a <noscript> or an <iframe>: raw text to a page that runs scripts (a server may\n // have rendered a value there). A Light DOM component's content is bound by its own engine\n const into = tag !== \"noscript\" && tag !== \"iframe\" && !specs?.some(setsContent) && !hooks.componentScope?.(el);\n // On the page an element's children are bound before it: what its bindings then put anywhere\n // in it (a custom element rendering a value into a child of its own) is never walked — nor\n // after an error in them, which leaves the walk with the element bound (it is before the\n // error in document order). A plan keeps document order (Block.dispatch relies on it): its\n // bindings change nothing in it\n try {\n if (page && into) walk([...el.childNodes]);\n } finally {\n if (specs !== null) onElement(el, specs);\n }\n if (!page && into) walk([...el.childNodes]);\n } else if (child.nodeType === 3 && engine.mustache && (child as Text).data.includes(\"{{\") && !walked.has(child)) {\n for (const { node, expr } of splitMustache(child as Text)) onText(node, expr);\n } else if (child.nodeType === 8) {\n // a comment binding, as 3.x (`$behavior.enableMustache` aside): a text binding in its place —\n // not in a <textarea> / <title>, where a browser's parser makes it text (a server's DOM may not)\n const m = COMMENT_BINDING.exec((child as Comment).data);\n const p = m && (child.parentNode as Element).localName;\n if (p !== null && p !== \"textarea\" && p !== \"title\") {\n const t = document.createTextNode(\"\");\n child.replaceWith(t);\n onText(t, m![1]);\n }\n }\n }\n };\n walk(children);\n}\n\n/**\n * `<!--@@: expr-->` / `<!--@@wcs-text: expr-->` (3.x's comment binding: a text binding that renders\n * nothing before it is bound — no FOUC, no element added); no other keyword (a router's `@@route:`,\n * 3.x's SSR marks). `expr` is a `{{ }}` expression (across lines, as a mustache's: SSR restores both\n * as this).\n */\nconst COMMENT_BINDING = /^\\s*@@\\s*(?:wcs-text)?\\s*:\\s*([\\s\\S]+?)\\s*$/;\n\n/**\n * A template's content. A `<template>` inside `<svg>` is an SVG element (the HTML parser makes it\n * so) and has no `.content`: its children are its content (a copy of them: the template keeps them).\n */\nexport const templateContent = (t: HTMLTemplateElement): DocumentFragment => {\n const r = document.createRange();\n r.selectNodeContents(t);\n return t.content ?? r.cloneContents();\n};\n\n/**\n * Compiles a template into a plan: the fragment to clone, the child-index path of every\n * bound node, and one spec per binding. Paths are resolved to patterns here, once —\n * blocks never parse or resolve anything. `list` is the enclosing `for` (for `.` paths).\n */\nexport function compilePlan(engine: Engine, template: HTMLTemplateElement, list: Pattern | null, asRow: boolean): RowPlan {\n const frag = document.importNode(templateContent(template), true);\n const targets: Node[] = [];\n const specs: Spec[] = [];\n const target = (node: Node): number => targets.push(node) - 1;\n\n walkBindings(engine, [...frag.childNodes], list, false,\n (anchor, p, plan) => {\n specs.push({ ...blank(), node: target(anchor), kind: K_FOR, pattern: p, plan });\n },\n (chain) => {\n const branches: BranchSpec[] = chain.map((br) => ({ node: target(br.anchor), plan: br.plan, pattern: br.pattern, filters: br.filters }));\n specs.push({ ...blank(), node: branches[0].node, kind: K_IF, branches });\n },\n (el, own) => {\n const n = target(el);\n for (const s of own) {\n // a row or a branch keeps its nodes by position: a binding that replaces its element (once —\n // the element is out of the page after) has no place in one\n if (isOuter(s)) raise(M.OuterInTemplate, [s.name]);\n s.node = n;\n }\n specs.push(...own);\n // the plan holds the bindings: blocks cloned from it carry nothing left to bind\n el.removeAttribute(bindAttr());\n },\n (node, expr) => {\n specs.push(textSpec(engine, expr, list, target(node)));\n });\n\n // Whitespace that never renders is not part of a block: at the top level, and inside\n // elements whose content model has no text (table parts, select). Bound text nodes start\n // empty: keep them.\n stripInsignificantWhitespace(frag, new Set(targets), true);\n\n const nodePaths = targets.map((t) => pathOf(frag, t));\n // one node cloned alone — not a structural anchor, whose view inserts before it (it needs a parent)\n const single = frag.childNodes.length === 1 && frag.firstChild!.nodeType !== 8;\n const nested = specs.some((s) => s.kind === K_FOR || s.kind === K_IF);\n const lazy: Spec[] = [];\n const used = new Set<number>();\n const events: Spec[] = [];\n // what a block binds as it is built (the delegated events it finds by path are not among them)\n const own: Spec[] = [];\n // in a row plan, the row's own locations bound by kinds that need only the node are slots (see RowView)\n const d = asRow ? list!.depth + 1 : -1;\n for (const s of specs) {\n // a node used only by delegated events is never resolved when a block is built (a custom\n // element's are attached: it may dispatch them without bubbling)\n if (s.kind === K_EVENT && s.delegated && !s.custom && !shifts(targets[s.node], frag)) {\n events.push(s);\n continue;\n }\n own.push(s);\n const p = s.pattern;\n if (p !== null && p.depth === d && p.lists[d] === list && isSlotKind(s)) s.slot = lazy.push(s) - 1;\n if (s.kind === K_IF) for (const br of s.branches!) used.add(br.node);\n else used.add(s.node);\n }\n const build = [...used].sort((a, b) => a - b);\n return { fragment: frag, root: single ? frag.firstChild : null, nodePaths, build, events, specs: own, single, nested, scratch: [], lazy };\n}\n\n/**\n * Whether the path to `n` from its block's top node can change once the block renders: a\n * structural anchor before it on the way (its view renders before the anchor) or a custom element\n * above it (a Light DOM component may add children). Such an element's delegated events are not\n * found by path: they are stored on the element as its block is built.\n */\nfunction shifts(n: Node, top: Node): boolean {\n for (; n.parentNode !== top; n = n.parentNode!) {\n if ((n.parentNode as Element).localName.includes(\"-\")) return true;\n for (let s = n.previousSibling; s; s = s.previousSibling) if (s.nodeType === 8) return true;\n }\n return false;\n}\n\nfunction isSlotKind(s: Spec): boolean {\n // a slot applies its first value as it is built: #init= needs a Binding (HOLD)\n if (s.init !== null) return false;\n switch (s.kind) {\n case K_TEXT:\n case K_CLASS:\n case K_ATTR:\n case K_STYLE:\n case K_HTML:\n return true;\n case K_PROP:\n return !s.custom && s.twoWay === null;\n default:\n return false;\n }\n}\n\n/** Elements whose children never render as text: whitespace between their children is noise. */\nconst NO_TEXT = new Set([\"table\", \"thead\", \"tbody\", \"tfoot\", \"tr\", \"colgroup\", \"select\", \"optgroup\", \"datalist\"]);\n\nfunction stripInsignificantWhitespace(parent: Node, keep: Set<Node>, strip: boolean): void {\n for (let n = parent.firstChild; n !== null;) {\n const next = n.nextSibling;\n if (n.nodeType === 3) {\n if (strip && !keep.has(n) && (n as Text).data.trim() === \"\") n.remove();\n } else if (n.nodeType === 1) {\n stripInsignificantWhitespace(n, keep, NO_TEXT.has((n as Element).localName));\n }\n n = next;\n }\n}\n\nfunction pathOf(root: Node, node: Node): number[] {\n const path: number[] = [];\n for (let n: Node = node; n !== root; n = n.parentNode!) {\n let i = 0;\n for (let s = n.previousSibling; s !== null; s = s.previousSibling) i++;\n path.unshift(i);\n }\n return path;\n}\n","import { parseStatePart } from \"./parseStatePart\";\nimport { ParsedBinding } from \"./types\";\n\n/**\n * テキストバインディング(mustache `{{ expr }}` / コメント `<!--@@: expr-->`・`<!--@@wcs-text: expr-->`)の式を解析する。\n * 式全体が `path[|filters]` — `;` は**分割しない**(属性経路との規定差)。\n * Port of `@wcstack/state` `src/bindTextParser/parseBindTextForEmbeddedNode.ts`.\n */\nexport function parseBindTextForEmbeddedNode(bindText: string): ParsedBinding {\n const stateResult = parseStatePart(bindText);\n return {\n propName: 'textContent',\n propSegments: ['textContent'],\n propModifiers: [],\n inFilters: [],\n ...stateResult,\n bindingType: 'text',\n };\n}\n","import type { Engine } from \"../engine\";\nimport { hooks } from \"../hooks\";\nimport { directive, textSpec, walkBindings } from \"./plan\";\nimport { raise, M } from \"../messages\";\nimport { attachChain, attachSpec, ForView, listFor } from \"./view\";\nimport { report } from \"../parser/raiseError\";\n\n/**\n * The engine mounted on each root (document, shadow root): the binder's lookup. A root's while its\n * `<wcs-state>` is in the page (src/element.ts): the root node outlives the content it bound.\n */\nexport const engines = new WeakMap<Node, Engine>();\n\n/**\n * Binds everything under `root` to `engine` and renders it. An element walked once is left\n * alone after (walkBindings): the binder protocol hands route content over on every insertion.\n */\nexport function mount(engine: Engine, root: Document | ShadowRoot | Element): void {\n const container: Node = root.nodeType === 9 ? (root as Document).body : root;\n engine.root = root;\n engines.set(root, engine);\n walk(engine, [...container.childNodes]);\n engine.report();\n}\n\n/**\n * Binds a subtree that entered the document after the mount (the binder protocol). It never throws\n * for markup reasons (the protocol): an error in the markup is reported, and what is before it in\n * document order (the elements it is in too) stays bound. A structural template handed over itself (a\n * route's top-level node) is rendered only when the caller carries its range (`range`: the router\n * takes everything up to its end mark along, the rows rendered beside the template included);\n * otherwise it is refused (#204): what it renders would sit beside it, where whoever inserted it\n * does not reach (an older router removes only its own nodes, `<wcs-head>` its one element). An\n * `if:` template handed over reads its `elseif:` / `else:` siblings into one chain (readChain), and\n * those, handed over next, are out of the document by then (their anchors took their place).\n */\nexport function mountSubtree(engine: Engine, subtree: Element, range?: boolean): void {\n try {\n const d = subtree.localName === \"template\" ? directive(subtree) : null;\n if (d !== null && !range) raise(M.TemplateHandedOver, [d.bindingType]);\n walk(engine, [subtree]);\n } catch (e) {\n report(e);\n }\n engine.report();\n}\n\nfunction walk(engine: Engine, children: ChildNode[]): void {\n walkBindings(engine, children, null, true,\n (anchor, p, plan) => {\n new ForView(engine, plan, listFor(engine, p, null, anchor), anchor).update();\n },\n (branches) => {\n attachChain(engine, branches, null, null);\n },\n (el, specs) => {\n hooks.ssrMark?.(engine, el, specs);\n for (const spec of specs) attachSpec(engine, spec, el, null, null);\n },\n (node, expr) => {\n hooks.ssrMark?.(engine, node, expr);\n attachSpec(engine, textSpec(engine, expr, null, 0), node, null, null);\n });\n}\n","// ===========================================================================\n// AUTO-GENERATED FILE - DO NOT EDIT.\n// Generated from /protocol/binder.ts by scripts/sync-protocol-types.mjs.\n// Run `node scripts/sync-protocol-types.mjs` after editing the source.\n// ===========================================================================\n\n// binder protocol — how a package that inserts DOM hands those nodes to whoever\n// owns data bindings on the page.\n//\n// The dual of transition-runner: that one hands a *mutation* to whoever animates\n// it, this one hands *new nodes* to whoever binds them.\n//\n// A `data-wcs` binding exists only for nodes @wcstack/state walked when it built\n// its bindings. Nodes that arrive later — the content of a route that was not\n// active at that moment, a <wcs-head> child reflected into <head> — were never\n// walked, so their bindings silently do nothing, however often they are inserted.\n// @wcstack/router must not depend on @wcstack/state (zero runtime dependencies,\n// independently publishable), so state installs a binder on a well-known global\n// symbol and inserters look it up lazily.\n//\n// No binder installed means nothing happens — byte-for-byte the behavior these\n// packages had before the protocol existed.\n//\n// docs/binder-protocol-design.md is the normative description.\n//\n// SINGLE SOURCE OF TRUTH: edit only this file (/protocol/binder.ts), then run\n// `node scripts/sync-protocol-types.mjs` to regenerate the per-package copies\n// (packages/<pkg>/src/protocol/binder.ts). Those copies are generated — do not edit them.\n\n/**\n * Global key the binder installs itself under. `Symbol.for` so independently\n * loaded copies of this file (two CDN bundles on one page) still agree.\n */\nexport const BINDER_KEY = Symbol.for(\"wcstack.binder\");\n\n/**\n * What the caller declares about a subtree it hands over (the second argument of `bind`; additive\n * since version 1 — a binder that predates it ignores it, and leaving it out keeps the old contract).\n */\nexport interface IWcsBindOptions {\n /**\n * The caller carries the range the subtree sits in: on removal it takes everything from its own\n * start mark up to its end mark along — what the binder rendered beside the subtree included, as\n * the rows a structural template handed over at the top of the content renders before its anchor —\n * and puts it all back on reinsertion. Only with this may a binder render such a template: without\n * it, what the binder rendered beside the subtree would be left behind, so @wcstack/state 4.0\n * refuses one (#204). @wcstack/state 3.x ignores the option and renders no structural template\n * handed over itself, with or without it (docs/binder-protocol-design.md §2, §9-5, §9-6).\n */\n readonly range?: boolean;\n}\n\nexport interface IWcsBinder {\n readonly protocol: \"wcs-binder\";\n /** Integer protocol version. All versions >= 1 are participant-compatible. */\n readonly version: number;\n /**\n * Take a subtree that has just entered the document and bind whatever\n * declarations it carries.\n *\n * Contract (docs/binder-protocol-design.md §2):\n * - Synchronous. Initial values are applied before this returns, so the\n * caller never shows one frame of unbound markup.\n * - Idempotent. A subtree that is already bound is left alone, so a caller\n * may hand over the same nodes on every insertion without tracking which\n * ones are new.\n * - Binding survives later relocation, so this need not be called again when\n * the same nodes are moved (measured: design doc §8-3).\n * - Never throws for markup reasons; a subtree with no declarations is a\n * no-op.\n * - `options` (optional) is what the caller declares about the subtree\n * ({@link IWcsBindOptions}).\n */\n bind(subtree: Node, options?: IWcsBindOptions): void;\n}\n\n/**\n * The installed binder, or null when there is none or it speaks a version this\n * reader does not.\n *\n * Looked up on every call rather than cached, for the same reason\n * transition-runner does: the page's composition can change at any point, and a\n * stale cache would keep calling into a binder that is no longer there.\n */\nexport function getBinder(): IWcsBinder | null {\n const candidate = (globalThis as Record<symbol, unknown>)[BINDER_KEY] as IWcsBinder | undefined;\n if (candidate === undefined || candidate === null) return null;\n if (candidate.protocol !== \"wcs-binder\") return null;\n if (typeof candidate.version !== \"number\" || candidate.version < 1) return null;\n if (typeof candidate.bind !== \"function\") return null;\n return candidate;\n}\n\n/**\n * Subtrees offered before a binder existed, and the set of everything a binder\n * has taken. Both live on global symbols so that independently loaded copies of\n * this file — the router's and state's — share one queue.\n *\n * The queue is needed because of load order: the router's auto bundle runs\n * before state's, so `<wcs-head>` reflects its children into `<head>` while\n * there is still nothing to bind them. Offering them to a binder that arrives\n * later is the difference between working and silently blank.\n */\nconst PENDING_KEY = Symbol.for(\"wcstack.binder.pending\");\nconst TAKEN_KEY = Symbol.for(\"wcstack.binder.taken\");\n\nfunction pendingQueue(): Node[] {\n const globals = globalThis as Record<symbol, unknown>;\n let queue = globals[PENDING_KEY] as Node[] | undefined;\n if (queue === undefined) {\n queue = [];\n globals[PENDING_KEY] = queue;\n }\n return queue;\n}\n\nfunction takenSet(): WeakSet<Node> {\n const globals = globalThis as Record<symbol, unknown>;\n let taken = globals[TAKEN_KEY] as WeakSet<Node> | undefined;\n if (taken === undefined) {\n taken = new WeakSet<Node>();\n globals[TAKEN_KEY] = taken;\n }\n return taken;\n}\n\n/**\n * Hand `subtree` to the installed binder, or hold it for one that arrives later.\n *\n * Returns whether a binder took it *now*. A `false` does not yet mean the markup\n * is doomed — check {@link wasBoundBy} once module scripts have run.\n *\n * `options` goes to the binder with the subtree. A subtree held for a later binder\n * is handed over without it: that binder's first walk of the page binds what is\n * still in place there.\n */\nexport function bindSubtree(subtree: Node, options?: IWcsBindOptions): boolean {\n const binder = getBinder();\n if (binder === null) {\n pendingQueue().push(subtree);\n return false;\n }\n takenSet().add(subtree);\n binder.bind(subtree, options);\n return true;\n}\n\n/** Whether any binder has taken this subtree. */\nexport function wasBoundBy(subtree: Node): boolean {\n return takenSet().has(subtree);\n}\n\n/**\n * Bind everything offered before this binder existed. Called by the binder right\n * after it installs itself.\n */\nexport function flushPendingBinds(): void {\n const binder = getBinder();\n if (binder === null) return;\n const queue = pendingQueue();\n if (queue.length === 0) return;\n const pending = queue.splice(0, queue.length);\n const taken = takenSet();\n for (const subtree of pending) {\n taken.add(subtree);\n binder.bind(subtree);\n }\n}\n","import { BINDER_KEY, flushPendingBinds, type IWcsBinder, type IWcsBindOptions } from \"../protocol/binder\";\nimport { engines, mountSubtree } from \"./mount\";\n\n/**\n * The binder protocol's provider (docs/binder-protocol-design.md): a package that inserts\n * DOM after the mount — the router's route content, `<wcs-head>`'s clones in <head> —\n * hands the subtree over, and it is bound to the engine of its root, synchronously.\n * Only what is handed over is bound (no scan of every insertion), and binding twice is a\n * no-op, so the router may hand the same nodes over on every insertion.\n */\n\n/**\n * Subtrees handed over before their root's engine finished its first mount, or while it was out of the\n * page, with what the caller declared (a range: a route's top-level template is rendered then).\n */\nconst early = new Map<Element, IWcsBindOptions | undefined>();\n\nexport function bind(subtree: Node, options?: IWcsBindOptions): void {\n // not in a document (it left, or was replaced, as a chain's `else:` template by its anchor): nothing to bind\n if (subtree.nodeType !== 1 || !subtree.isConnected) return;\n // (a root taken out of the page lets go of its root node: it binds what waited here when it is back.\n // A component's, whose <wcs-state> alone left, is still registered: not one to bind to either)\n const engine = engines.get(subtree.getRootNode());\n // (once each: the router hands the same nodes over on every insertion. One handed over early is\n // walked by the first mount where it is: the declaration is not needed then)\n if (engine === undefined || (engine.element as Node | null)?.isConnected === false) early.set(subtree as Element, options);\n else mountSubtree(engine, subtree as Element, options?.range);\n}\n\n/**\n * After an engine's first mount, and when a root is back in the page: binds what was handed over\n * too early — to this binder before the mount or while the root was out, or (queued by the\n * protocol) before any binder existed.\n */\nexport function drainBinds(): void {\n // (one that left the document meanwhile is dropped: handed over again if it comes back)\n const waiting = [...early];\n early.clear();\n for (const [subtree, options] of waiting) bind(subtree, options);\n flushPendingBinds();\n}\n\n/** Installs the binder on the protocol's global slot, unless another copy already has it. */\nexport function installBinder(): void {\n const slot = globalThis as Record<symbol, unknown>;\n if (slot[BINDER_KEY] === undefined) slot[BINDER_KEY] = { protocol: \"wcs-binder\", version: 1, bind } satisfies IWcsBinder;\n}\n","import type { Engine } from \"../engine\";\nimport { DIRTY, FAILED, UNSET, type Pattern } from \"../pattern\";\nimport type { StateRow } from \"../list\";\nimport type { Strategy } from \"./types\";\nimport { hooks } from \"../hooks\";\n\n/**\n * Push invalidation: a write walks its dependents immediately, marks their caches\n * DIRTY and queues their bindings. A cache already DIRTY (or never computed) stops the\n * walk — whatever depends on it was reached when it was marked.\n */\nexport class DirtyStrategy implements Strategy {\n readonly name = \"dirty\";\n\n private readonly mark = (g: Pattern, row: StateRow | null): boolean => {\n // UNSET: nobody read it; DIRTY: already reached. FAILED was read (and threw): reach it.\n if (g.depth === 0) {\n const v = g.rootValue;\n if (v === UNSET || v === DIRTY) return false;\n g.rootValue = DIRTY;\n return true;\n }\n const c = row === null ? null : row.cache;\n if (c === null) return false;\n const v = c[g.slot];\n if (v === UNSET || v === DIRTY) return false;\n c[g.slot] = DIRTY;\n return true;\n };\n\n onWrite(engine: Engine, p: Pattern, row: StateRow | null): void {\n // a write through a getter's setter: the written occurrence itself is stale\n if (p.getter !== null) this.mark(p, row);\n engine.enqueueBound(p, row);\n engine.walkDependents(p, row, this.mark);\n }\n\n onIndexChange(engine: Engine, row: StateRow): void {\n const watchers = row.list.pattern.indexWatchers;\n if (watchers === null) return;\n for (const g of watchers) {\n // the row itself (a row getter reading its own index): no closure per moved row\n if (g.depth === row.list.depth) engine.visitGetter(g, row, this.mark);\n else engine.forRowsUnder(row, g, (r) => engine.visitGetter(g, r, this.mark));\n }\n }\n\n invalidate(engine: Engine, g: Pattern, row: StateRow | null): void {\n this.mark(g, row);\n hooks.getterReached?.(engine, g, row);\n engine.enqueueBound(g, row);\n engine.walkDependents(g, row, this.mark);\n }\n\n readGetter(engine: Engine, g: Pattern, row: StateRow | null): unknown {\n const root = g.depth === 0;\n if (!root && row === null) return undefined;\n const c = root ? null : (row!.cache ??= new Array(engine.slotCount).fill(UNSET));\n let v = c === null ? g.rootValue : c[g.slot];\n // a getter made after the row's cache (a recursive family, a mounted key, a binder's subtree) has\n // no entry yet — nor one whose slot lies before a later getter's written past the end (a hole)\n if (v !== UNSET && v !== DIRTY && v !== FAILED && (c === null || g.slot in c)) return v;\n v = FAILED;\n try {\n return (v = engine.evalGetter(g, c === null ? null : row));\n } finally {\n if (c === null) g.rootValue = v;\n else c[g.slot] = v;\n }\n }\n\n resetRow(row: StateRow): void {\n row.cache = null;\n }\n\n dropped(engine: Engine): void {\n // DIRTY says \"its readers were reached\", and they were dropped: FAILED is reached again\n for (const g of engine.patterns.all()) {\n if (g.getter === null) continue;\n if (g.depth === 0) {\n if (g.rootValue === DIRTY) g.rootValue = FAILED;\n } else {\n engine.forAllRows(g.lists[g.depth]!, (r) => {\n const c = r.cache;\n if (c !== null && c[g.slot] === DIRTY) c[g.slot] = FAILED;\n });\n }\n }\n }\n}\n","import type { IWritableConfig } from \"./public/types\";\nimport { Engine } from \"./engine\";\nimport { engines, mount } from \"./dom/mount\";\nimport { drainBinds, installBinder } from \"./dom/binder\";\nimport { DirtyStrategy } from \"./strategy/dirty\";\nimport { config, setConfig } from \"./config\";\nimport type { Strategy } from \"./strategy/types\";\nimport { raise, M, text } from \"./messages\";\nimport { hooks, loadFeatures, requireFeature, type Claimed } from \"./hooks\";\nimport { report } from \"./parser/raiseError\";\n\nlet makeStrategy: () => Strategy = () => new DirtyStrategy();\n\n/** Chooses the invalidation strategy of every engine created from now on. */\nexport function configure(factory: () => Strategy): void {\n makeStrategy = factory;\n}\n\nlet loads = 0;\n\nasync function loadInnerScript(script: HTMLScriptElement): Promise<Record<string, any>> {\n // an import a Content-Security-Policy blocked rejects without saying why: the violation event\n // is the only witness (docs/csp.md §9)\n let blocked = false;\n const seen = (e: SecurityPolicyViolationEvent): void => {\n if (e.effectiveDirective.startsWith(\"script-src\")) blocked = true;\n };\n document.addEventListener(\"securitypolicyviolation\", seen);\n // a server (@wcstack/server) removes createObjectURL: a data: URL, unique so no load is cached\n const blob = typeof URL.createObjectURL === \"function\";\n const url = blob\n ? URL.createObjectURL(new Blob([script.text], { type: \"application/javascript\" }))\n : \"data:text/javascript;charset=utf-8,\" + encodeURIComponent(`${script.text}\\n//${++loads}`);\n try {\n const mod = await import(/* @vite-ignore */ url);\n return (mod.default ?? {}) as Record<string, any>;\n } catch (e) {\n // Firefox fires the violation a task after the rejection (Chromium and WebKit before it)\n await new Promise((r) => setTimeout(r));\n throw new Error(`[@wcstack/state] ${blocked ? text(M.InlineBlocked) : text(M.InlineFailed, [e instanceof Error ? e.message : String(e)])}`, { cause: e });\n } finally {\n document.removeEventListener(\"securitypolicyviolation\", seen);\n if (blob) URL.revokeObjectURL(url);\n }\n}\n\nasync function loadSrc(src: string): Promise<Record<string, any>> {\n const url = new URL(src, document.baseURI).href;\n if (/\\.json(?:[?#]|$)/.test(url)) {\n const res = await fetch(url);\n if (!res.ok) raise(M.LoadFailed, [src, res.status]);\n return (await res.json()) as Record<string, any>;\n }\n // on the server, the renderer's local module for the URL (protocol/ssr-snapshot.ts, resolveModule):\n // Node's loader reads no http: URL\n const mod = await import(/* @vite-ignore */ (globalThis as any)[Symbol.for(\"wcstack.ssr.resolveModule\")]?.(url) ?? url);\n return (mod.default ?? {}) as Record<string, any>;\n}\n\n/**\n * The root `<wcs-state>` elements of each root node (and the one a component mount or a DCC definition\n * has in its shadow root): a new list whenever one connects, without the ones no longer in the page.\n */\nconst readyByRoot = new WeakMap<Node, WcsState[]>();\n\n/**\n * Puts `el` among the `<wcs-state>` elements of `root` (a new list, without the ones that left) — or,\n * taken out of it, takes it off: the list holds nothing of a page that went.\n */\nfunction enroll(el: WcsState, root: Node = el.getRootNode()): void {\n readyByRoot.set(root, [...(readyByRoot.get(root) ?? []), el].filter((e, i, a) => e.isConnected && a.lastIndexOf(e) === i));\n}\n\n/**\n * Resolves when the bindings of `root` are built — by any `<wcs-state>` in it now, whatever its\n * `$connectedCallback` does then, as 3.x — and rejects, with the first failure, only when every one\n * failed before building them. A stray one (a second root, #47; one that fails to load) changes\n * nothing while another binds the root; one taken out of the page (or moved to another root) counts\n * no more (a root replaced: the new one decides). With none in it — none ever, or only ones that left —\n * it resolves at once: there is nothing to wait for (a page without state).\n */\nexport function getBindingsReady(root: Node): Promise<void> {\n const list = readyByRoot.get(root) ?? [];\n const els = list.filter((e) => e.getRootNode() === root);\n return Promise.any(els.map((el) => el.initializePromise.then((): unknown => el.bound || el.connectedCallbackPromise))).then(\n () => {},\n // none, or every one failed: one connected since (the list is a new one) may still bind the root\n // (quoted: `errors` is a name the build shortens, an AggregateError's is not)\n (e: AggregateError) => (els.length ? readyByRoot.get(root) !== list ? getBindingsReady(root) : Promise.reject(e[\"errors\"][0]) : undefined),\n );\n}\n\n/**\n * The base of the package's elements: HTMLElement, or — where there is none (Node without a DOM)\n * — an inert class, so the entries can be imported headless (a tool reading the manifest, a\n * server framework importing at the top level), as 3.x. Making an element stays a browser's.\n */\nexport const HTMLElementBase = (typeof HTMLElement === \"undefined\" ? class {} : HTMLElement) as typeof HTMLElement;\n\n/**\n * `<wcs-state>` — one engine per element, bound to the element's root node.\n * State resolution order: `state` (id of a JSON script) → `src` → `json` → inner\n * `<script type=\"module\">` → wait for `setInitialState()`.\n */\nexport class WcsState extends HTMLElementBase {\n static getBindingsReady = getBindingsReady;\n /** Servers (@wcstack/server) wait on connectedCallbackPromise when this is set. */\n static hasConnectedCallbackPromise = true;\n\n engine: Engine | null = null;\n readonly connectedCallbackPromise: Promise<void>;\n /**\n * Resolves once the state is loaded and bound (before `$connectedCallback`) — and also when\n * initialization fails: the failure is delivered on connectedCallbackPromise.\n */\n readonly initializePromise: Promise<void>;\n private resolveInitialize!: () => void;\n private resolveConnected!: () => void;\n private rejectConnected!: (e: unknown) => void;\n private started = false;\n /** Initialization failed before the page was bound: `setInitialState` refuses (#14). */\n private failed = false;\n private initial: Record<string, any> | null = null;\n /** Taken over by an add-on (a volume, a DCC definition): it never becomes a root. */\n private claimed: Claimed | null = null;\n /** A claimed element's state is loaded: `setInitialState` from now on is the add-on's re-set. */\n private loaded = false;\n /** The root's bindings are built (getBindingsReady resolves, whatever `$connectedCallback` does). */\n bound?: boolean;\n private receiveInitial: ((state: Record<string, any>) => void) | null = null;\n\n constructor() {\n super();\n this.connectedCallbackPromise = new Promise<void>((resolve, reject) => {\n this.resolveConnected = resolve;\n this.rejectConnected = reject;\n });\n this.connectedCallbackPromise.catch(() => {});\n this.initializePromise = new Promise<void>((resolve) => {\n this.resolveInitialize = resolve;\n });\n }\n\n connectedCallback(): void {\n if (this.started) {\n if (this.claimed !== null) {\n this.claimed.connected();\n return;\n }\n enroll(this);\n const engine = this.engine;\n if (engine !== null) {\n // back in the page: it holds its root again (unless another <wcs-state> bound it meanwhile),\n // binds what was handed over while it was out, and the add-ons hear of it (the volumes that\n // connected meanwhile graft) — then $connectedCallback runs again\n const root = engine.root;\n if (root === this.getRootNode() && !engines.has(root)) engines.set(root, engine);\n drainBinds();\n hooks.element?.(engine, \"back\");\n this.rerun(\"$connectedCallback\", M.ConnectedFailed, () => {\n if (this.isConnected) hooks.element?.(engine, \"connected\");\n });\n }\n return;\n }\n this.started = true;\n const root = this.getRootNode();\n const claimed = hooks.claim?.(this, root);\n if (claimed) {\n this.claimed = claimed;\n // the `<wcs-state>` of the shadow root it binds (a component's, a DCC definition's) is that\n // root's, as 3.x: getBindingsReady there waits for it — until its bindings are built, as a\n // root's — and fails with it (a volume never fails)\n if (!claimed.lenient && this.parentNode instanceof ShadowRoot) enroll(this);\n void (claimed.load === undefined ? this.loadState() : claimed.load()).then((state) => {\n this.loaded = true;\n return claimed.start(state, () => this.built());\n }).then(() => {\n this.resolveInitialize();\n this.resolveConnected();\n }, (e) => this.fail(e, claimed.lenient));\n return;\n }\n void this.start(root);\n enroll(this);\n }\n\n disconnectedCallback(): void {\n if (this.claimed !== null) {\n this.claimed.disconnected();\n return;\n }\n const engine = this.engine;\n if (engine === null) return;\n // out of the page, it lets go of its root (it holds it again when it is back): what outlives the\n // page's content — its root node, the document — does not keep its state and the DOM it bound\n // (a root that failed before its mount has none: enroll takes the root it is in now)\n const root = engine.root;\n if (engines.get(root!) === engine) engines.delete(root!);\n enroll(this, root);\n this.rerun(\"$disconnectedCallback\", M.DisconnectedFailed);\n hooks.element?.(engine, \"disconnected\");\n }\n\n /**\n * Supplies the initial state; on an initialized element, replaces the whole state and\n * re-applies every binding to it before returning (not a write: no `$renderedCallback`).\n */\n setInitialState(state: Record<string, any>): void {\n if (this.failed) raise(M.ElementFailed);\n // (until a claimed element's state is loaded, this supplies it like a root's)\n if (this.loaded) {\n this.claimed!.reset(state);\n return;\n }\n if (this.engine !== null) {\n this.engine.reset(state);\n return;\n }\n if (this.receiveInitial !== null) {\n const receive = this.receiveInitial;\n this.receiveInitial = null;\n receive(state);\n } else {\n this.initial = state;\n }\n }\n\n /** Runs `callback` with a state proxy; its writes are applied in the next drain. */\n createState(mutability: \"readonly\" | \"writable\", callback: (state: Record<string, any>) => void): void {\n const engine = this.engine;\n if (engine === null) raise(M.NotInitialized);\n if (mutability === \"readonly\") engine.readonlyDepth++;\n try {\n callback(engine.proxy);\n } finally {\n if (mutability === \"readonly\") engine.readonlyDepth--;\n }\n }\n\n /** `createState` whose callback may await; a readonly proxy stays readonly across its awaits. */\n async createStateAsync(mutability: \"readonly\" | \"writable\", callback: (state: Record<string, any>) => Promise<void>): Promise<void> {\n const engine = this.engine;\n if (engine === null) raise(M.NotInitialized);\n await callback(mutability === \"writable\" ? engine.proxy : new Proxy(engine.proxy, {\n // as in createState(\"readonly\"), the writes of $setAll and $resolve (path, indexes, value) refuse;\n // read with this view as the receiver, a method comes as it is and runs on this view\n get(t, k, receiver) {\n const v = Reflect.get(t, k, receiver);\n return k === \"$setAll\" || k === \"$resolve\" ? (...a: unknown[]) => (a.length > 2 && raise(M.Readonly), v(...a)) : v;\n },\n set() {\n raise(M.Readonly);\n },\n }));\n }\n\n private async loadState(): Promise<Record<string, any>> {\n // a parser that inserts the element before its children (a server render) has added them by now\n await 0;\n const id = this.getAttribute(\"state\");\n if (id !== null) {\n // a JSON script of that id (an element of user content with the same id, earlier, is not it)\n const find = (r: Node): HTMLScriptElement | undefined =>\n [...(r as Document).querySelectorAll<HTMLScriptElement>('script[type=\"application/json\"]')].find((x) => x.id === id);\n const script = find(this.getRootNode()) ?? find(document);\n if (script === undefined) return Promise.reject(new Error(`[@wcstack/state] ${text(M.NoScript, [id])}`));\n return Promise.resolve(JSON.parse(script.textContent || \"{}\"));\n }\n const src = this.getAttribute(\"src\");\n if (src !== null) return loadSrc(src);\n const json = this.getAttribute(\"json\");\n if (json !== null) return Promise.resolve(JSON.parse(json));\n const script = this.querySelector('script[type=\"module\"]') as HTMLScriptElement | null;\n if (script !== null) return loadInnerScript(script);\n if (this.initial !== null) return Promise.resolve(this.initial);\n return new Promise((resolve) => {\n this.receiveInitial = resolve;\n });\n }\n\n private async start(root: Node): Promise<void> {\n try {\n // what an add-on serves: a volume, a component mount, a DCC definition, server rendering\n const host = (root as ShadowRoot).host;\n if (this.hasAttribute(\"mount\") || this.hasAttribute(\"bind-component\") || host?.hasAttribute(\"data-wc-definition\")) {\n requireFeature(\"scopes\", \"<wcs-state>\");\n }\n const state = await this.loadState();\n const loading = loadFeatures(state);\n if (loading) await loading;\n // taken out of its root while it loaded (the page's content replaced, or moved to another root):\n // nothing is mounted on the root it left. It starts again where it is now, or when it connects\n // again. A state given by setInitialState() is kept for that; a state= / src= / json= / inline\n // script source is read again (a fetch runs again, an inline module is evaluated again)\n if (this.getRootNode() !== root) {\n this.initial = state;\n this.started = false;\n if (this.isConnected) this.connectedCallback();\n return;\n }\n if (this.hasAttribute(\"enable-ssr\")) requireFeature(\"ssr\", \"enable-ssr\");\n // one state tree per root: another <wcs-state> already bound this root (and still does —\n // whatever its $connectedCallback did then), or a component's took it\n const other = engines.get(root)?.element as WcsState | undefined;\n if (other?.isConnected && (other.bound || other.claimed)) raise(M.SecondRoot);\n const engine = new Engine(state, makeStrategy());\n engine.element = this;\n this.engine = engine;\n hooks.element?.(engine, \"mounting\");\n mount(engine, root as Document | ShadowRoot);\n drainBinds();\n engine.watchRendered();\n this.built();\n await engine.callHook(\"$connectedCallback\");\n if (this.isConnected) hooks.element?.(engine, \"connected\");\n this.resolveConnected();\n } catch (e) {\n // (a root that bound its page and whose $connectedCallback then failed has not: re-set stays open)\n this.failed = !this.bound;\n this.fail(e);\n }\n }\n\n /** The bindings are built (before `$connectedCallback`): getBindingsReady resolves, initializePromise too. */\n private built(): void {\n this.bound = true;\n this.resolveInitialize();\n }\n\n /**\n * Initialization failed: reported once, the element (and where its state comes from) before what\n * was thrown, as 3.5 — `<wcs-state src=\"./state.js\"> failed to initialize.`, or, once its\n * bindings were built, `… $connectedCallback failed.` — and connectedCallbackPromise rejects with\n * it, or resolves for a claim that is `lenient` (a volume).\n */\n private fail(e: unknown, lenient?: boolean): void {\n this.report(this.bound ? M.ConnectedFailed : M.InitFailed, e);\n this.resolveInitialize();\n if (lenient) this.resolveConnected();\n else this.rejectConnected(e);\n }\n\n /** Reports a failure once: the element (and where its state comes from), then what was thrown. */\n private report(id: M, e: unknown): void {\n const at = [\"mount\", \"bind-component\", \"state\", \"src\"].flatMap((n) => (this.hasAttribute(n) ? [n, this.getAttribute(n)] : []));\n report(e, `[@wcstack/state] ${text(id, [this.localName, ...at])}`);\n }\n\n /**\n * Runs a lifecycle callback of a root that connected before (on reconnect, on disconnect) at once: a\n * failure — thrown or rejected — is reported as a first connection's is, never thrown out of the\n * element's callback.\n */\n private rerun(name: string, id: M, then?: () => void): void {\n void (async () => this.engine!.callHook(name))().then(then, (e) => this.report(id, e));\n }\n}\n\n/**\n * The registries `<wcs-state>` was defined in: an add-on installed later defines its tags there\n * too. Weak: a server creates a registry per render, and holding them would keep every render's\n * registry (and every constructor defined in it) alive.\n */\nlet refs: WeakRef<CustomElementRegistry>[] = [];\n\n/**\n * The registries still alive (dead references are dropped). A registry deref() returned stays\n * alive until the end of this job, so the second deref() of each kept reference finds it.\n */\nexport function registries(): CustomElementRegistry[] {\n refs = refs.filter((r) => r.deref());\n return refs.map((r) => r.deref()!);\n}\n\n/**\n * Registers `<wcs-state>` (and the installed add-ons' tags) in `registry` — a scoped registry\n * does not inherit the global one, so a tree using one needs its own definitions.\n */\nexport function define(registry: CustomElementRegistry = customElements): void {\n installBinder();\n if (!registries().includes(registry)) refs.push(new WeakRef(registry));\n const tag = config.tagNames.state;\n if (registry.get(tag) === undefined) registry.define(tag, class extends WcsState {});\n hooks.tags?.(registry);\n}\n\n/** Applies `config` and registers `<wcs-state>`. The core only: install the add-ons first. */\nexport function bootstrapState(partial?: IWritableConfig, registry?: CustomElementRegistry): void {\n if (partial) setConfig(partial);\n define(registry);\n}\n\n/**\n * Waits for the bindings under `root` (3.x built them here; the new engine builds them when the\n * root's `<wcs-state>` loads its state, so this only waits — the same as getBindingsReady).\n */\nexport const buildBindings = (root: Document | ShadowRoot): Promise<void> => getBindingsReady(root);\n","/**\n * filters/formats.ts — the formats add-on (38 filters): the values a binding computes and shows, as\n * opposed to the conditions the core set (`./core`) tests. Ported from `@wcstack/state`\n * (`formats/builtinFilters.ts`) with the semantics unchanged.\n *\n * - number display: `toFixed round floor ceil percent unit locale currency`\n * - string shaping: `upper lower capitalize trim slice padStart padEnd repeat reverse truncate join`\n * (`substr` was removed in 4.0: `slice(start, start + length)`)\n * - date and time: `date time datetime ymd hms`\n * - arithmetic: `add sub mul div mod abs clamp`\n * - conversions: `number string int float`\n * - missing values: `defaults coalesce nullIfEmpty`\n *\n * (The last three groups were the core's up to 4.0.0-rc.3.)\n *\n * `installFormats()` puts them in the registry. Without it, one of these filters fails when the\n * bindings are planned with `[wcs/filter-unknown]` naming this add-on (never passes silently).\n * The locale-dependent five (`locale currency date time datetime`) read `config.locale` as their default.\n */\nimport { config } from \"../config\";\nimport { currencyInvalid, optionsRequired, styleInvalid, valueMustBeArray, valueMustBeDate, valueMustBeNumber } from \"./errorMessages\";\nimport { firstLiteral, numberOption, requiredNumberOption } from \"./options\";\nimport { registerFilters, type FilterDefinition, type FilterFactory, type FilterFn } from \"./registry\";\nimport { coreFilters, numeric } from \"./core\";\nimport { M, text } from \"../messages\";\n\n/**\n * Extends the display-side empty-value contract (requirement B8) to the filters that build their\n * result with `String(value)`: those turn `undefined` / `null` into the *characters* \"undefined\" /\n * \"null\", so `attr.title: x|trim` wrote `title=\"undefined\"` where `attr.title: x` removes the\n * attribute. This family passes an absent value straight through and leaves the decision to the\n * apply side (attribute removed, class cleared, style cleared, text emptied).\n *\n * Deliberately **not** wrapped: the filters that reject a value of the wrong type (the number and\n * array families) — their throw is confined to the one binding and reported, a different quality of\n * failure from painting the word \"undefined\" into the page. The date family is wrapped (since 4.7):\n * a date usually arrives later (a fetch, a route) and is absent until then, and no value put in\n * front (`coalesce`) could stand for a missing date — every load reported a failure\n * (docs/seam-apps.md, prod-booking). A value of another type still throws.\n */\nconst nullishPassthrough = (factory: (options: string[]) => FilterFn): FilterFactory =>\n (options: string[]): FilterFn => {\n const filterFn = factory(options);\n // `== null` matches both null and undefined (deliberately loose)\n return (value: unknown): unknown => (value == null ? value : filterFn(value));\n };\n\n/** Fixed decimals (default 0). */\nconst toFixed = (options: string[]): FilterFn => {\n const opt = numberOption(options?.[0] ?? \"0\", 'toFixed');\n return (value: unknown): string => {\n if (typeof value !== 'number') {valueMustBeNumber('toFixed', value);}\n return value.toFixed(opt);\n };\n};\n\n/** Rounds to the given decimals (default 0). */\nconst round = (options: string[]): FilterFn => {\n const optValue = Math.pow(10, numberOption(options?.[0] ?? '0', 'round'));\n return (value: unknown): number => {\n if (typeof value !== 'number') {valueMustBeNumber('round', value);}\n return Math.round(value * optValue) / optValue;\n };\n};\n\n/** Rounds down to the given decimals (default 0). */\nconst floor = (options: string[]): FilterFn => {\n const optValue = Math.pow(10, numberOption(options?.[0] ?? '0', 'floor'));\n return (value: unknown): number => {\n if (typeof value !== 'number') {valueMustBeNumber('floor', value);}\n return Math.floor(value * optValue) / optValue;\n };\n};\n\n/** Rounds up to the given decimals (default 0). */\nconst ceil = (options: string[]): FilterFn => {\n const optValue = Math.pow(10, numberOption(options?.[0] ?? '0', 'ceil'));\n return (value: unknown): number => {\n if (typeof value !== 'number') {valueMustBeNumber('ceil', value);}\n return Math.ceil(value * optValue) / optValue;\n };\n};\n\n/** `0.123` → `\"12%\"` with the given decimals (default 0). */\nconst percent = (options: string[]): FilterFn => {\n const opt = numberOption(options?.[0] ?? '0', 'percent');\n return (value: unknown): string => {\n if (typeof value !== 'number') {valueMustBeNumber('percent', value);}\n return `${(value * 100).toFixed(opt)}%`;\n };\n};\n\n/**\n * Appends a CSS unit (or any suffix). Accepts strings as well as numbers **on purpose**: the useful\n * chains run through `toFixed` / `percent`, which already return strings\n * (`style.height: cpu|clamp(0,100)|toFixed(0)|unit(%)`). null / undefined pass through\n * (`nullishPassthrough`) rather than becoming \"undefinedpx\".\n */\nconst unit = (options: string[]): FilterFn => {\n const opt = options?.[0] ?? optionsRequired('unit');\n return (value: unknown): string => String(value) + opt;\n};\n\nlet seen: string | undefined;\nlet valid = \"en\";\n\n/**\n * The default locale (`config.locale`) as Intl takes it, checked when it changes (an identity\n * compare per apply): one it does not (`<html lang=\"en_US\">`) is \"en\" (as 3.x), with a warning.\n */\nfunction defaultLocale(): string {\n if (config.locale !== seen) {\n seen = config.locale;\n try {\n valid = Intl.getCanonicalLocales(seen)[0];\n } catch {\n console.warn(`[@wcstack/state] ${text(M.LocaleInvalid, [seen])}`);\n valid = \"en\";\n }\n }\n return valid;\n}\n\n/**\n * Locale-formatted number. The locale-dependent filters (`locale date time datetime`) fix an\n * **explicit** locale at construction but read the default `config.locale` **on every apply**: a\n * default baked into the closure at binding time would make an ordering accident (locale settled\n * after the bindings) permanent, since `config.locale` is not in the dependency graph. Read per\n * apply, a re-applied binding at least recovers.\n */\nconst locale = (options: string[]): FilterFn => {\n const explicit = options?.[0];\n return (value: unknown): string => {\n if (typeof value !== 'number') {valueMustBeNumber('locale', value);}\n return value.toLocaleString(explicit ?? defaultLocale());\n };\n};\n\n/**\n * A number as money: `currency(code[, locale])`, the code ISO 4217 (`price|currency(JPY)` → \"¥1,800\",\n * `currency(EUR,de-DE)` → \"1.800,00 €\"). A code Intl does not take fails when the bindings are planned.\n * (docs/seam-apps.md, router-admin: the page built an `Intl.NumberFormat` per currency in getters.)\n */\nconst currency = (options: string[]): FilterFn => {\n const code = options?.[0] ?? optionsRequired('currency');\n const explicit = options?.[1];\n const format = { style: \"currency\", currency: code } as const;\n try {\n new Intl.NumberFormat(\"en\", format);\n // (Intl takes any three letters: the list of the ones it knows, where there is one)\n const known = (Intl as { supportedValuesOf?: (key: string) => string[] }).supportedValuesOf?.(\"currency\");\n if (known && !known.includes(code.toUpperCase())) throw 0;\n } catch {\n currencyInvalid(code);\n }\n return (value: unknown): string => {\n if (typeof value !== 'number') {valueMustBeNumber('currency', value);}\n return value.toLocaleString(explicit ?? defaultLocale(), format);\n };\n};\n\nconst upper = (): FilterFn => (value: unknown): string => String(value).toUpperCase();\n\nconst lower = (): FilterFn => (value: unknown): string => String(value).toLowerCase();\n\nconst capitalize = (): FilterFn => (value: unknown): string => {\n const v = String(value);\n if (v.length === 0) {return v;}\n if (v.length === 1) {return v.toUpperCase();}\n return v.charAt(0).toUpperCase() + v.slice(1);\n};\n\nconst trim = (): FilterFn => (value: unknown): string => String(value).trim();\n\n/** `slice(start[, end])`. */\nconst slice = (options: string[]): FilterFn => {\n const numberedOpts: number[] = [requiredNumberOption(options, 0, 'slice')];\n const opt2 = options?.[1];\n if (typeof opt2 !== 'undefined') {\n numberedOpts.push(numberOption(opt2, 'slice'));\n }\n return (value: unknown): string => String(value).slice(...numberedOpts);\n};\n\n/** Pads the start to a length; the pad string defaults to '0' (JavaScript's default is a space). */\nconst padStart = (options: string[]): FilterFn => {\n const opt1 = requiredNumberOption(options, 0, 'padStart');\n const opt2 = options?.[1] ?? '0';\n return (value: unknown): string => String(value).padStart(opt1, opt2);\n};\n\n/** Pads the end to a length; the pad string defaults to ' ' (as in JavaScript). */\nconst padEnd = (options: string[]): FilterFn => {\n const opt1 = requiredNumberOption(options, 0, 'padEnd');\n const opt2 = options?.[1] ?? ' ';\n return (value: unknown): string => String(value).padEnd(opt1, opt2);\n};\n\nconst repeat = (options: string[]): FilterFn => {\n const opt = requiredNumberOption(options, 0, 'repeat');\n return (value: unknown): string => String(value).repeat(opt);\n};\n\nconst reverse = (): FilterFn => (value: unknown): string => String(value).split('').reverse().join('');\n\n/**\n * Shortens a string and appends a suffix (default '…', U+2026). The length counts **kept\n * characters**; a string at or below it is returned untouched (no suffix).\n */\nconst truncate = (options: string[]): FilterFn => {\n const maxLength = requiredNumberOption(options, 0, 'truncate');\n const suffix = options?.[1] ?? '…';\n return (value: unknown): string => {\n const v = String(value);\n if (v.length <= maxLength) {return v;}\n return v.slice(0, maxLength) + suffix;\n };\n};\n\n/**\n * Joins an array. The default separator is \", \" rather than \",\": a bare comma is what `String()`\n * already produces, so defaulting to it would make `|join` a no-op.\n */\nconst join = (options: string[]): FilterFn => {\n const opt = options?.[0] ?? ', ';\n return (value: unknown): string => {\n if (!Array.isArray(value)) {valueMustBeArray('join');}\n return value.join(opt);\n };\n};\n\nconst STYLES = [\"full\", \"long\", \"medium\", \"short\"];\n\n/**\n * The options of `date time datetime`: `(locale?, style?)`, the style Intl's `dateStyle` / `timeStyle`\n * (`date(en-US,medium)` → \"Oct 13, 2026\"). A style alone keeps the default locale (`date(long)`).\n * Without a style the format is the locale's numeric one, as before.\n */\nfunction dateOptions(options: string[], fn: string): [string | undefined, Intl.DateTimeFormatOptions[\"dateStyle\"]] {\n let [loc, style]: (string | undefined)[] = options ?? [];\n if (style === undefined && loc !== undefined && STYLES.includes(loc)) [loc, style] = [undefined, loc];\n if (style !== undefined && !STYLES.includes(style)) styleInvalid(fn, style);\n return [loc, style as Intl.DateTimeFormatOptions[\"dateStyle\"]];\n}\n\n/** Locale-formatted date (the default locale is read per apply — see `locale`). */\nconst date = (options: string[]): FilterFn => {\n const [explicit, style] = dateOptions(options, 'date');\n const format: Intl.DateTimeFormatOptions | undefined = style && { dateStyle: style };\n return (value: unknown): string => {\n if (!(value instanceof Date)) {valueMustBeDate('date', value);}\n return value.toLocaleDateString(explicit ?? defaultLocale(), format);\n };\n};\n\n/** Locale-formatted time (the default locale is read per apply — see `locale`). */\nconst time = (options: string[]): FilterFn => {\n const [explicit, style] = dateOptions(options, 'time');\n const format: Intl.DateTimeFormatOptions | undefined = style && { timeStyle: style };\n return (value: unknown): string => {\n if (!(value instanceof Date)) {valueMustBeDate('time', value);}\n return value.toLocaleTimeString(explicit ?? defaultLocale(), format);\n };\n};\n\n/** Locale-formatted date and time (the default locale is read per apply — see `locale`). */\nconst datetime = (options: string[]): FilterFn => {\n const [explicit, style] = dateOptions(options, 'datetime');\n const format: Intl.DateTimeFormatOptions | undefined = style && { dateStyle: style, timeStyle: style };\n return (value: unknown): string => {\n if (!(value instanceof Date)) {valueMustBeDate('datetime', value);}\n return value.toLocaleString(explicit ?? defaultLocale(), format);\n };\n};\n\n/** YYYY-MM-DD with a configurable separator (default '-'), locale-independent. */\nconst ymd = (options: string[]): FilterFn => {\n const opt = options?.[0] ?? '-';\n return (value: unknown): string => {\n if (!(value instanceof Date)) {valueMustBeDate('ymd', value);}\n const year = value.getFullYear().toString();\n const month = (value.getMonth() + 1).toString().padStart(2, '0');\n const day = value.getDate().toString().padStart(2, '0');\n return `${year}${opt}${month}${opt}${day}`;\n };\n};\n\n/** HH:MM:SS with a configurable separator (default ':'), zero-padded and locale-independent. */\nconst hms = (options: string[]): FilterFn => {\n const opt = options?.[0] ?? ':';\n return (value: unknown): string => {\n if (!(value instanceof Date)) {valueMustBeDate('hms', value);}\n const hours = value.getHours().toString().padStart(2, '0');\n const minutes = value.getMinutes().toString().padStart(2, '0');\n const seconds = value.getSeconds().toString().padStart(2, '0');\n return `${hours}${opt}${minutes}${opt}${seconds}`;\n };\n};\n\nconst abs = (): FilterFn => (value: unknown): number => {\n if (typeof value !== 'number') {valueMustBeNumber('abs', value);}\n return Math.abs(value);\n};\n\n/** Constrains a number to the inclusive range [min, max] (`style.width: ratio|clamp(0,1)|percent(0)`). */\nconst clamp = (options: string[]): FilterFn => {\n const min = requiredNumberOption(options, 0, 'clamp');\n const max = requiredNumberOption(options, 1, 'clamp');\n return (value: unknown): number => {\n if (typeof value !== 'number') {valueMustBeNumber('clamp', value);}\n return Math.min(Math.max(value, min), max);\n };\n};\n\n// The conversions convert — an absent value is converted too (`string` gives \"undefined\");\n// put `coalesce` in front when a missing value should not be converted.\nconst number = (): FilterFn => (value: unknown): number => Number(value);\n\nconst string = (): FilterFn => (value: unknown): string => String(value);\n\nconst int = (): FilterFn => (value: unknown): number => parseInt(String(value), 10);\n\nconst float = (): FilterFn => (value: unknown): number => parseFloat(String(value));\n\n/** Replaces a falsy value (JavaScript's truthiness) with the typed literal: defaults(0) gives 0, defaults('0') \"0\" (B9). */\nconst defaults = (options: string[], literals?: readonly unknown[]): FilterFn => {\n const opt = options?.[0] ?? optionsRequired('defaults');\n const fallback = firstLiteral(opt, literals);\n return (value: unknown): unknown => {\n if (!value) {return fallback;}\n return value;\n };\n};\n\n/** Replaces only null / undefined (`defaults` also replaces 0, false and \"\") — SQL's COALESCE. */\nconst coalesce = (options: string[], literals?: readonly unknown[]): FilterFn => {\n const opt = options?.[0] ?? optionsRequired('coalesce');\n const fallback = firstLiteral(opt, literals);\n return (value: unknown): unknown => value ?? fallback;\n};\n\n/** \"\" → null, anything else unchanged. */\nconst nullIfEmpty = (): FilterFn => (value: unknown): unknown => (value === \"\") ? null : value;\n\nconst { eq, ne, not, lt, le, gt, ge, falsy, truthy, boolean } = coreFilters;\n\n/**\n * What `installFormats()` registers: factory and [min, max] argument count (B3 — the same bounds\n * lint uses), in the order the registry keeps them. The did-you-mean suggestion gives a tie to the\n * first registered, so the order is the one the full build registered up to 4.0.0-rc.3, when this\n * add-on had the 23 display filters and the core 24: the display filters, then that core set, each\n * in the source's (lint's) relative order. The core's 10 are registered here too, in their place\n * (the core registers them again when it first plans a binding, and a name registered again keeps\n * its place).\n */\nconst registered: Readonly<Record<string, FilterDefinition>> = {\n toFixed: { factory: toFixed, arity: [0, 1] },\n locale: { factory: locale, arity: [0, 1] },\n\n // The `String(value)` family passes an absent value through (B8 — see nullishPassthrough)\n upper: { factory: nullishPassthrough(upper), arity: [0, 0] },\n lower: { factory: nullishPassthrough(lower), arity: [0, 0] },\n capitalize: { factory: nullishPassthrough(capitalize), arity: [0, 0] },\n trim: { factory: nullishPassthrough(trim), arity: [0, 0] },\n slice: { factory: nullishPassthrough(slice), arity: [1, 2] },\n // The length is required too (the implementation reads both)\n padStart: { factory: nullishPassthrough(padStart), arity: [1, 2] },\n padEnd: { factory: nullishPassthrough(padEnd), arity: [1, 2] },\n repeat: { factory: nullishPassthrough(repeat), arity: [1, 1] },\n reverse: { factory: nullishPassthrough(reverse), arity: [0, 0] },\n truncate: { factory: nullishPassthrough(truncate), arity: [1, 2] },\n join: { factory: join, arity: [0, 1] },\n\n round: { factory: round, arity: [0, 1] },\n floor: { factory: floor, arity: [0, 1] },\n ceil: { factory: ceil, arity: [0, 1] },\n percent: { factory: percent, arity: [0, 1] },\n unit: { factory: nullishPassthrough(unit), arity: [1, 1] },\n\n // The locale-dependent three take a locale like `locale` does (`date(ja-JP)`), and a style (`date(ja-JP,long)`)\n date: { factory: nullishPassthrough(date), arity: [0, 2] },\n time: { factory: nullishPassthrough(time), arity: [0, 2] },\n datetime: { factory: nullishPassthrough(datetime), arity: [0, 2] },\n ymd: { factory: nullishPassthrough(ymd), arity: [0, 1] },\n hms: { factory: nullishPassthrough(hms), arity: [0, 1] },\n\n // the core set of 4.0.0-rc.3 (the core's own: eq ne not lt le gt ge falsy truthy boolean)\n eq, ne, not, lt, le, gt, ge,\n add: numeric('add', (value, opt) => value + opt),\n sub: numeric('sub', (value, opt) => value - opt),\n mul: numeric('mul', (value, opt) => value * opt),\n div: numeric('div', (value, opt) => value / opt),\n mod: numeric('mod', (value, opt) => value % opt),\n abs: { factory: abs, arity: [0, 0] },\n clamp: { factory: clamp, arity: [2, 2] },\n int: { factory: int, arity: [0, 0] },\n float: { factory: float, arity: [0, 0] },\n falsy, truthy,\n defaults: { factory: defaults, arity: [1, 1] },\n coalesce: { factory: coalesce, arity: [1, 1] },\n boolean,\n number: { factory: number, arity: [0, 0] },\n string: { factory: string, arity: [0, 0] },\n nullIfEmpty: { factory: nullIfEmpty, arity: [0, 0] },\n // (added in 4.2: last, so the order of the others is unchanged)\n currency: { factory: currency, arity: [1, 2] },\n};\n\n/** The formats add-on's own filters (what `registered` holds beyond the core set), in that order. */\nexport const formatFilters: Readonly<Record<string, FilterDefinition>> = /*#__PURE__*/ Object.fromEntries(\n /*#__PURE__*/ Object.entries(registered).filter(([name]) => !(name in coreFilters)),\n);\n\nlet installed = false;\n\n/** Puts the formats add-on in the registry. Idempotent. */\nexport function installFormats(): void {\n if (installed) return;\n installed = true;\n registerFilters(registered);\n}\n","/**\n * The formats add-on (@wcstack/state/features/formats): the 38 filters that compute and show a value\n * (display, string shaping, dates — locale-aware —, arithmetic, conversions, missing values).\n */\nimport { hooks, type Feature } from \"../hooks\";\nimport { installFormats } from \"../filters/formats\";\n\nexport const formats: Feature = { name: \"formats\", hooks, install: installFormats };\nexport default formats;\n","/**\n * diagnostics/guidance.ts — self-fix guidance for error messages, ported verbatim from\n * `@wcstack/state` (`errorGuidance.ts`). Only the diagnostics add-on uses it: the core's\n * messages state the fact, and the add-on appends this.\n *\n * The did-you-mean criteria (edit distance 2, ties go to the first candidate, case folded) are the\n * same as lint's suggestion, so the console, lint and the IDE never propose different names.\n */\n\n/** Insert / delete / substitute edit distance. Returns max + 1 early when the lengths differ by more than max. */\nfunction editDistance(a: string, b: string, max: number): number {\n if (Math.abs(a.length - b.length) > max) {\n return max + 1;\n }\n const prev: number[] = new Array(b.length + 1);\n const curr: number[] = new Array(b.length + 1);\n for (let j = 0; j <= b.length; j++) {\n prev[j] = j;\n }\n for (let i = 1; i <= a.length; i++) {\n curr[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);\n }\n for (let j = 0; j <= b.length; j++) {\n prev[j] = curr[j];\n }\n }\n return prev[b.length];\n}\n\n/**\n * The nearest candidate within edit distance 2 as ` Did you mean \"<best>\"?`, or `\"\"` when there is\n * none. An empty input (a trailing `a|` pipe) gets no suggestion.\n */\nexport function didYouMean(input: string, candidates: Iterable<string>): string {\n if (input.length === 0) {\n return \"\";\n }\n const folded = input.toLowerCase();\n let best: string | null = null;\n let bestDistance = 3;\n for (const candidate of candidates) {\n const distance = editDistance(folded, candidate.toLowerCase(), 2);\n if (distance < bestDistance) {\n best = candidate;\n bestDistance = distance;\n }\n }\n return best !== null ? ` Did you mean \"${best}\"?` : \"\";\n}\n\n/**\n * The pointer to lint. Attach it **only where lint actually detects the case** — a hint that sends\n * the author to a lint run that comes back clean costs the loop its credibility.\n */\nexport const LINT_HINT = \" Validate statically: npx @wcstack/lint <file>.\";\n","/**\n * The sentences of the core's numbered messages (src/messages.ts), in the diagnostics add-on:\n * the core carries the number and the values, this renders what the core used to say. Each\n * sentence follows its `[wcs/<code>] ` (`codeOf`: the code the hundreds of the number name).\n * `Record<M, …>` makes a number without a sentence a type error.\n */\nimport { M } from \"../messages\";\nimport { MAX_DRAIN_PASSES, MAX_INDEX_PARAM, MAX_RENDER_CHAIN } from \"../engine\";\nimport { MAX_PATH_SEGMENTS, MODIFIER_SEPARATOR, RECURSION_WILDCARD } from \"../parser/define\";\n\ntype Sentence = (...a: any[]) => string;\n\n/**\n * The code of each hundred of message numbers (\"\" = none): the code lint and the VS Code extension\n * report for the same case. The core carried this up to 4.0.0-rc.3; without this add-on a message\n * now reads as its number and values alone.\n */\nexport const CODES = [\n \"\", \"binding-syntax\", \"template-syntax\", \"binding-path-missing\", \"binding-type-expectation\",\n \"filter-unknown\", \"filter-arity\", \"getter-cycle\", \"getter-depth-exceeded\", \"index-arity\",\n \"index-param-range\", \"recursion-unsupported\", \"token-misconfigured\", \"token-undeclared\",\n \"wildcard-rank\", \"spread-no-bindable\", \"declaration-alias\", \"name-alias\",\n];\n\n/** `[wcs/<code>] ` for a message number, or \"\" when it has none. */\nexport const codeOf = (id: M): string => {\n const c = CODES[(id / 100) | 0];\n return c ? `[wcs/${c}] ` : \"\";\n};\n\n/** The options 4.0 moved from `bootstrapState` to the state's `$behavior`. */\nconst MOVED = [\"enableMustache\", \"sameValueGuard\", \"enableDirectionalInitialSync\"];\n\n/** `<tag a=\"v\" …>` from the tag and its attributes' names and values. */\n/** What a value given to a filter was (`a string (\"2026-10-13T…\")`), for the type messages. */\nconst was = (v: unknown): string =>\n v == null ? String(v)\n : v instanceof Date ? \"a Date\"\n : Array.isArray(v) ? \"an array\"\n : typeof v === \"string\" ? `a string (${JSON.stringify(v.length > 32 ? v.slice(0, 32) + \"…\" : v)})`\n : typeof v === \"object\" ? \"an object\" : `a ${typeof v} (${String(v)})`;\n/** The namespace a binding of kind 2–4 (dom/view.ts: K_CLASS, K_ATTR, K_STYLE) names its member under. */\nconst NAMESPACES = [\"\", \"\", \"class.\", \"attr.\", \"style.\"];\n\nconst element = (tag: string, at: string[]): string => `<${tag}${at.map((a, i) => (i % 2 ? `=\"${a}\"` : ` ${a}`)).join(\"\")}>`;\n\nconst CSP_GUIDE = \"https://github.com/wcstack/wcstack/blob/main/docs/csp.md\";\n\nexport const SENTENCES: Record<M, Sentence> = {\n [M.ScanRemoved]: () => \"$scan was removed (use $watch or $on)\",\n [M.GetterWithoutSetter]: (p) => `\"${p}\" is a getter without a setter`,\n [M.NoRow]: (p) => `no row for \"${p}\"`,\n [M.ParentNotObject]: (p, parent) => `cannot write \"${p}\": its parent is ${parent}`,\n [M.NotAMethod]: (name) => `\"${name}\" is not a method`,\n [M.GetAllNoCommonLevel]: (p) => `$getAll(\"${p}\"): no loop level in common with the context`,\n [M.EqIndexNoRow]: (p) => `$eqIndex(\"${p}\") needs a list row scope.`,\n [M.Readonly]: () => \"This state is readonly.\",\n [M.SetAllNeedsIndexes]: (p) => `$setAll(\"${p}\") needs indexes ([] for every match)`,\n [M.SetAllSpreadLength]: (p, n) => `$setAll(\"${p}\", …, { spread: true }) needs an array of ${n} values`,\n [M.DrainNotSettled]: () => `updates did not settle after ${MAX_DRAIN_PASSES} passes`,\n [M.RenderChain]: () => `render chain depth limit exceeded (${MAX_RENDER_CHAIN} drains that rendering itself started); bindings for this batch were not applied.`,\n // (named as written — `textContent: iso`, `class.active: x` — when the binding has a member; else its type)\n [M.BindingFailed]: (type, p, name, kind) => `binding \"${name ? (NAMESPACES[kind] ?? \"\") + name : type}: ${p}\" failed to apply.`,\n [M.LoadFailed]: (src, status) => `failed to load \"${src}\": ${status}`,\n [M.ElementFailed]: () => \"this <wcs-state> failed to initialize; create a new one\",\n [M.NotInitialized]: () => \"state is not initialized\",\n [M.NoScript]: (id) => `no <script> with id \"${id}\"`,\n [M.InlineBlocked]: () => `The inline <script> of <wcs-state> was blocked by Content-Security-Policy. Inline state is evaluated through a blob: URL: give the page's nonce to the <script> that loads @wcstack/state, or allow blob: in script-src. Moving the state into an external file (src=\"./state.js\") needs neither. See ${CSP_GUIDE}`,\n [M.InlineFailed]: (detail) => `Failed to evaluate the inline <script> of <wcs-state>: ${detail}. If this page sets a Content-Security-Policy, see ${CSP_GUIDE}`,\n [M.TokenSubscriberThrew]: (name) => `a subscriber of token \"${name}\" threw.`,\n [M.TokenListNotArray]: (key) => `${key} must be an array of strings.`,\n [M.TokenEntryEmpty]: (key) => `${key} entries must be non-empty strings.`,\n [M.TokenEntryReserved]: (key, name, reserved) => `${key} entry \"${name}\" conflicts with the reserved namespace name \"${reserved}\".`,\n [M.TokenEntryDuplicated]: (key, name) => `${key} entry \"${name}\" is duplicated.`,\n [M.OnNotObject]: () => \"$on must be an object of handlers.\",\n [M.OnEntryUndeclared]: (name) => `$on entry \"${name}\" is not declared in $eventTokens.`,\n [M.OnEntryNotFunction]: (name) => `$on entry \"${name}\" must be a function.`,\n [M.NamingLimit]: (limit) => `view-transition naming-limit (${limit}) reached.`,\n [M.FilterOptionsRequired]: (fn) => `filter ${fn} requires at least one option`,\n [M.FilterOptionNotNumber]: (fn) => `filter ${fn} requires a number as option`,\n [M.FilterValueNotNumber]: (fn, v) => `filter ${fn} requires a number value, not ${was(v)}${typeof v === \"string\" ? ` — put |number before |${fn}, or convert it where it is read` : \"\"}`,\n [M.FilterValueNotDate]: (fn, v) => `filter ${fn} requires a date value (a Date), not ${was(v)}${typeof v === \"string\" || typeof v === \"number\" ? \" — make the Date where it is read: a getter returning new Date(…)\" : \"\"}${typeof v === \"string\" && /^\\d{4}-\\d\\d-\\d\\d$/.test(v) ? `. A date-only string is a day, not a moment: new Date(${JSON.stringify(v)}) is midnight UTC, the day before west of Greenwich — new Date(y, m - 1, d) is that day where the page is` : \"\"}`,\n [M.FilterStyleInvalid]: (fn, v) => `filter ${fn} takes a style of full, long, medium or short, not \"${v}\"`,\n [M.FilterCurrencyInvalid]: (v) => `filter currency takes an ISO 4217 currency code (JPY, USD, EUR), not \"${v}\"`,\n [M.FilterValueNotArray]: (fn) => `filter ${fn} requires an array value`,\n [M.DirectionalSyncDisabled]: () => \"init=/sync= modifiers require enableDirectionalInitialSync.\",\n [M.ModifierUnknown]: (key, modifier) => `Unknown binding modifier \"${key}\" in \"${modifier}\".`,\n [M.ModifierTwice]: (key) => `Binding modifier \"${key}\" may only be specified once.`,\n [M.ModifierValue]: (key, value) => `Invalid ${key} modifier value \"${value}\".`,\n [M.EventInitNone]: () => \"Event bindings only allow init=none.\",\n [M.InitUnsupported]: (type, init) => `Binding type \"${type}\" does not support init=${init}.`,\n [M.MemberUndeclared]: (name) => `Property \"${name}\" is not declared by wcBindable.`,\n [M.InitIncompatible]: (init, name) => `init=${init} is incompatible with wcBindable member \"${name}\".`,\n [M.SyncConnectNeedsOutput]: (name) => `sync=connect requires observable property \"${name}\".`,\n [M.OptionInvalid]: (where, key) => `${where}: \"${key}\" is not one of its options, or not of the option's type.${where === \"bootstrapState\" && MOVED.includes(key) ? \" 4.0 moved it to the state's $behavior.\" : \"\"}`,\n [M.BehaviorChanged]: () => \"a re-set state may not change $behavior: create the element again.\",\n [M.SecondRoot]: () => \"a second <wcs-state> on the same root: there is one state tree per root — graft a subtree with <wcs-state mount=\\\"path\\\"> (v1's name=\\\"…\\\" is gone: read the mounted state by its path).\",\n [M.LocaleInvalid]: (l) => `the locale \"${l}\" (<html lang> or bootstrapState's locale) is not a language tag Intl takes (en-US, not en_US): the locale filters use \"en\".`,\n [M.FeaturesNotArray]: () => '$features must be an array of add-on names ([\"temporal\", \"formats\"]).',\n [M.InitFailed]: (tag, ...at) => `${element(tag, at)} failed to initialize.`,\n [M.ConnectedFailed]: (tag, ...at) => `${element(tag, at)} $connectedCallback failed.`,\n [M.DisconnectedFailed]: (tag, ...at) => `${element(tag, at)} $disconnectedCallback failed.`,\n\n [M.BindTextNoColon]: (t) => `Invalid bindText: \"${t}\". Missing ':' separator between propPart and statePart.`,\n [M.StructuralTakesNoModifiers]: (t, keyword) => `\"${t}\": \"${keyword}\" takes no modifiers or filters on its left side — write \"${keyword}:\".`,\n [M.ElseTakesNoValue]: (t) => `\"${t}\": \"else\" takes no value — write \"else:\".`,\n [M.SpreadNoPath]: (t) => `Invalid spread binding \"${t}\": spread target path is required.`,\n [M.SpreadNoFilters]: (t) => `Invalid spread binding \"${t}\": filters are not allowed on spread targets.`,\n [M.LeadingDotNamespace]: (prop) => `\"${prop}\": a leading \".\" binds an element property by name — write a non-empty property that is not a namespace (class, attr, style, command, eventToken, state).`,\n [M.UnterminatedQuote]: (quote, args) => `unterminated ${quote} quote in the filter arguments \"(${args})\". Close the quote.`,\n [M.FilterUnclosed]: (f) => `Invalid filter format: missing closing parenthesis in \"${f}\".`,\n [M.FilterUnopened]: (f) => `Invalid filter format: missing opening parenthesis in \"${f}\".`,\n [M.FilterParenOrder]: (f) => `Invalid filter format: \")\" comes before \"(\" in \"${f}\".`,\n [M.FilterTrailing]: (f, trailing) => `\"${f}\": unexpected \"${trailing}\" after the filter's closing \")\" — separate filters with \"|\" (write \"${f.slice(0, f.lastIndexOf(\")\") + 1)}|${trailing}\").`,\n [M.FilterEmpty]: (source) => `an empty filter in \"${source}\" — remove the extra \"|\" or name the filter.`,\n [M.FilterNameHasModifiersInput]: (name, mods) => `\"${name}\" is not a filter name: a modifier list \"${MODIFIER_SEPARATOR}${mods}\" comes before the input filters, not inside one`,\n [M.FilterNameHasModifiersOutput]: (name) => `\"${name}\" is not a filter name: \"${MODIFIER_SEPARATOR}\" cannot appear in one.`,\n [M.OneModifierList]: (prop) => `\"${prop}\": a binding takes one modifier list after a single \"#\"`,\n [M.NoPropertyName]: (prop) => `\"${prop}\": the left side of a binding must name a property — write \"<property>: <path>\" (modifiers and input filters come after the name).`,\n [M.TooManySegments]: (p, n) => `\"${p}\" has ${n} path segments — the limit is ${MAX_PATH_SEGMENTS}.`,\n [M.SelectorRemoved]: (t) => `\"${t}\": the \"@name\" selector was removed in v2 — there is a single state tree. Mount the named state onto the tree (<wcs-state mount=\"...\">) and read it by its path prefix instead.`,\n [M.UnsafeSegment]: (p) => `\"${p}\": a state path cannot go through \"__proto__\" or \"prototype\" (it would reach every object's prototype).`,\n [M.ForNoFilters]: (t) => `\"${t}\": \"for:\" takes no filters — a row is \"<path>.<index>\", so the rows of a filtered list would name other elements. Declare a getter that returns the filtered list and loop over it (\"for: <getter>\").`,\n [M.NamespaceNeedsName]: (t, ns) => ns === \"class\"\n ? `\"${t}\": \"class:\" needs a class name — \"class.NAME:\" toggles one class (a bare \"class:\" would set an element property named \"class\", which does nothing). To set the whole class attribute, bind \"className:\".`\n : `\"${t}\": \"attr:\" needs an attribute name — \"attr.NAME:\" sets one attribute (a bare \"attr:\" would set an element property named \"attr\", which does nothing).`,\n [M.EmptySegment]: (t) => `\"${t}\": the right side of a binding must name a state path — write \"<property>: <path>\" (a path segment cannot be empty; \".\" alone and a leading \".\" are the loop-relative shorthand).`,\n\n [M.StructuralNotSingle]: (t) => `Invalid bindText: \"${t}\". 'if', 'elseif', 'else', and 'for' bindings must be single binding.`,\n [M.ElseWithoutIf]: (type) => `\"${type}:\" must follow an \"if:\" template`,\n [M.TemplateHandedOver]: (type) => `a \"${type}:\" template at the top of inserted content was not rendered, as it would render beside itself out of the inserter's reach: wrap it in an element.`,\n [M.OuterInTemplate]: (name) => `\"${name}:\" replaces its element, so it cannot be used inside a \"for\" / \"if\" template (a row or branch keeps its nodes by position): bind innerHTML: on a wrapper element instead.`,\n\n [M.PathMissing]: (p) => `Path \"${p}\" does not exist on the state tree.`,\n\n [M.ClassNeedsBoolean]: (name, type) => `class.${name} needs a boolean, got ${type}.`,\n\n [M.FilterUnknown]: (name) => `filter not found: ${name}.`,\n\n [M.FilterTooFewArgs]: (name, min, given) => `filter \"${name}\" requires at least ${min} argument(s) (${given} given).`,\n [M.FilterTooManyArgs]: (name, max, given) => `filter \"${name}\" accepts at most ${max} argument(s) (${given} given).`,\n\n [M.GetterCycle]: (p) => `\"${p}\" depends on itself`,\n\n [M.GetterDepth]: (p) => `\"${p}\"`,\n\n [M.IndexArityExact]: (api, p, depth, n) => `${api}(\"${p}\") takes ${depth} index(es), got ${n}.`,\n [M.IndexArityAtMost]: (api, p, depth, n) => `${api}(\"${p}\") takes at most ${depth} index(es), got ${n}.`,\n\n [M.IndexParamRange]: (key) => `\"${key}\": list index parameters run from $1 to $${MAX_INDEX_PARAM}.`,\n\n [M.RecursionUnsupported]: (p) => `\"${p}\" uses \"${RECURSION_WILDCARD}\", which is not accepted here.`,\n\n [M.CommandRightSide]: (prop, p) => `\"${prop}: ${p}\": the right-hand side must be $command.<name>`,\n // a native element's command (no hyphen: never a custom element) is the native-commands add-on's\n [M.NoBindable]: (tag, what) => `<${tag}> declares no static wcBindable (${what}).${\n !tag.includes(\"-\") && what.startsWith(\"command.\") ? \" A native element's command needs the add-on @wcstack/state/features/native-commands.\" : \"\"}`,\n [M.NoCommand]: (tag, method) => `<${tag}> declares no command \"${method}\".`,\n [M.NoProperty]: (tag, prop) => `<${tag}> declares no property \"${prop}\".`,\n [M.NativeNoCommand]: (tag, method, allowed) => `<${tag}> has no command \"${method}\" (a native <${tag}>'s commands: ${allowed}).`,\n\n [M.EventTokenUndeclared]: (name) => `eventToken \"${name}\" is not declared in $eventTokens.`,\n [M.CommandTokenUndeclared]: (name) => `\"$command.${name}\" is not declared in $commandTokens.`,\n\n [M.WildcardNoLoop]: (p, depth, n = 0) => `\"${p}\" needs ${depth} enclosing loop level(s); the scope provides ${n}.`,\n [M.WildcardRelative]: (p) => `\"${p}\" is relative: it needs an enclosing \"for\" template`,\n [M.WildcardOtherList]: (p, over, loop) => `\"${p}\" ranges over the rows of \"${over}\", but the enclosing \"for\" template at that level renders \"${loop}\".`,\n\n [M.SpreadNoBindable]: (tag, what) => `<${tag}> declares no static wcBindable (${what}).`,\n\n [M.DeclarationRemoved]: (old, name) => `${old} was removed: write ${name}.`,\n\n [M.ApiRemoved]: (old, name) => `${old} was removed: write ${name}.`,\n};\n","/**\n * The diagnostics add-on's sentences and guidance: a numbered core message rendered as its\n * sentence (src/diagnostics/messages.ts), then how to fix it, the nearest name and the lint\n * pointer. The add-on installs these; so does `@wcstack/state/parser`, a bundle of its own.\n */\nimport { didYouMean, LINT_HINT } from \"./guidance\";\nimport { FORMATS_FILTER_NAMES, hasFilter } from \"../filters/registry\";\nimport type { M } from \"../messages\";\nimport { codeOf, SENTENCES } from \"./messages\";\n\n/** A numbered core message as its sentence (the number and the values if it is not known here). */\nexport function render(id: number, args: readonly unknown[]): string {\n const sentence = SENTENCES[id as M];\n return sentence === undefined ? `${codeOf(id)}#${id} ${args.join(\" \")}` : codeOf(id) + sentence(...args);\n}\n\n/** Codes lint detects statically: only these point the author to a lint run. */\nconst LINT_CODES = new Set([\n \"binding-syntax\", \"template-syntax\", \"filter-unknown\", \"filter-arity\", \"index-arity\",\n \"wildcard-rank\", \"token-undeclared\", \"binding-path-missing\", \"index-param-range\",\n]);\n\n/** How to fix it, by what the message says. */\nconst GUIDES: [RegExp, string][] = [\n [/no loop level in common with the context/, \"; pass indexes ([] for all).\"],\n [/\"([^\"#]+)#([^\"]*)\" is not a filter name: a modifier list .* comes before the input filters/, ' — write \"<property>#$2|$1\".'],\n [/\\[wcs\\/recursion-unsupported\\]/, \" It is only meaningful in a $recursion declaration, in a recursive getter key, and in the path argument of $getAll / $setAll — and only when the state declares a $recursion anchor.\"],\n [/must be single binding/, ' Put the structural binding alone in its own data-wcs (e.g. <template data-wcs=\"for: items\">).'],\n [/\\[wcs\\/wildcard-rank\\] .* needs \\d+ enclosing/, ' Wrap it in that many \"for\" templates, or use $resolve(path, indexes) to name the row explicitly.'],\n [/\\[wcs\\/wildcard-rank\\] .* ranges over the rows of/, ' A \"*\" in a binding is the row of the loop around it: read a row of another list in a getter, with $resolve(path, indexes).'],\n [/\\[wcs\\/binding-type-expectation\\] class\\.([^ ]+)/, ' Write \"class.$1: path|truthy\" to toggle on truthiness.'],\n [/path segments — the limit/, \" Every prefix of a path is interned, so the cost grows with the square of the depth.\"],\n [/\\[wcs\\/index-arity\\] \\$resolve/, \" $resolve takes one index per \\\"*\\\"; $getAll / $setAll take at most that many (fewer expands the rest).\"],\n [/\"([^\"#]+)#[^\"]*\" is not a filter name: \"#\" cannot appear in one/, ' Modifiers belong on the left side of the binding, before the \":\" — write \"$1\" here.'],\n];\n\n/**\n * The filter names 3.2 renamed, which 3.x kept as aliases and 4.0 removed (3.x's `filterAliases`;\n * lint has the same table). Their message names the replacement, not the nearest name: for these\n * that is an unrelated filter (`dec` → `eq`, `fix` → `div`), and following it changes the meaning.\n */\nexport const RENAMED_FILTERS: Readonly<Record<string, string>> = {\n inc: \"add\", dec: \"sub\", fix: \"toFixed\", uc: \"upper\", lc: \"lower\", cap: \"capitalize\", rep: \"repeat\", rev: \"reverse\", pad: \"padStart\", null: \"nullIfEmpty\",\n};\n\n/** How to write a filter 4.0 removed, or null. */\nfunction removedFilter(name: string): string | null {\n // 4.0 folded substr(start, length) into slice(start, end): the second argument changes meaning\n if (name === \"substr\") return ' \"substr\" was removed in 4.0 — write slice(start, start + length): slice takes the end index, not a length.';\n const to = Object.hasOwn(RENAMED_FILTERS, name) ? RENAMED_FILTERS[name] : null;\n return to === null ? null : ` \"${name}\" was renamed \"${to}\" in 3.2 and removed in 4.0 — write \"${to}\".`;\n}\n\nexport function explain(message: string, subject?: string, candidates?: Iterable<string>): string {\n const removed = subject !== undefined && message.includes(\"[wcs/filter-unknown]\") ? removedFilter(subject) : null;\n let out = removed ?? (subject !== undefined && candidates !== undefined ? didYouMean(subject, candidates) : \"\");\n for (const [re, text] of GUIDES) {\n const m = re.exec(message);\n if (m !== null) out += text.replace(/\\$(\\d)/g, (_, i: string) => m[Number(i)]);\n }\n // \"value#ro#wo\": one modifier list — the fix joins them\n const mods = /\"([^\"#]+)#([^\"]+)\": a binding takes one modifier list/.exec(message);\n if (mods !== null) out += ` — write \"${mods[1]}#${mods[2].split(\"#\").join(\",\")}\".`;\n // a formatting filter on a page without the formats add-on (the core names installFeatures), or a\n // typo on a page with no formatting filters at all: the formats add-on may be what is missing\n if (message.includes(\"[wcs/filter-unknown]\")) {\n if (message.includes(\"formats add-on\")) out += ` On a split auto page: features=\"formats\" on the root, or \"$features\": [\"formats\"].`;\n else if (!FORMATS_FILTER_NAMES.some(hasFilter)) {\n out += ` No formatting filters are installed — add the formats add-on: installFeatures([formats]) from \"@wcstack/state/features/formats\" (a split auto page: features=\"formats\", or \"$features\").`;\n }\n }\n const code = /\\[wcs\\/([\\w-]+)\\]/.exec(message);\n // (not something lint reports: the path-length limit is a runtime cost, a template handed over at\n // the top of inserted content (#204) is the page's order of loading, not its markup, and lint's\n // manifest knows the formatting filters — one missing because the formats add-on is not installed\n // is the page's. A row of another list (#1403) and an `outerHTML:` in a template (#203) lint does\n // report, as of its 4.0 parser)\n if (code !== null && LINT_CODES.has(code[1]) && !/ path segments — the limit is |inserted content was not rendered|formats add-on/.test(message)) out += LINT_HINT;\n return out;\n}\n","/**\n * The diagnostics add-on (@wcstack/state/features/diagnostics): the sentences and the self-fix\n * guidance of error messages. The core states the message number and the values\n * (`#901 \"$resolve\" \"m.*.*\" 2 1`); with this installed, the message is the code shared with lint\n * and the sentence (`[wcs/index-arity] $resolve(\"m.*.*\") takes 2 index(es), got 1.`), followed by the\n * nearest name (did-you-mean, the same rule as lint), how to fix it, and a pointer to lint where\n * lint really detects the case. The full `auto` bundle installs it.\n */\nimport { chain, first, hooks, known, type Feature } from \"../hooks\";\nimport type { Engine } from \"../engine\";\nimport { parsePath, type Pattern } from \"../pattern\";\nimport { raiseError } from \"../parser/raiseError\";\nimport { config } from \"../config\";\nimport type { WcsState } from \"../element\";\nimport type { Binding } from \"../dom/view\";\nimport { getTrustedTypesPolicy, isHtmlSink } from \"../trustedTypes\";\nimport { didYouMean, LINT_HINT } from \"../diagnostics/guidance\";\nimport { explain, render } from \"../diagnostics/explain\";\nimport { raise, M } from \"../messages\";\nimport type { Token } from \"../token\";\n\n// ---------------------------------------------------------------- paths that do not resolve\n\n/** What named a path: a binding, a `$watch` key, a `$postUpdate` call, a getter's read. */\nconst BINDING = 0;\nconst WATCH = 1;\nconst POST = 2;\nconst READ = 3;\n/** Paths bindings, `$watch` keys and `$postUpdate` named, by engine: checked one macrotask later (and after a re-set). */\nconst named = new WeakMap<Engine, Map<Pattern, number>>();\nconst checked = new WeakMap<Engine, Set<Pattern>>();\nconst due = new WeakSet<Engine>();\n/** Volumes (`<wcs-state mount>`) whose loading settled: the paths under them are checked from then on. */\nconst settled = new WeakSet<Element>();\n\nfunction findDescriptor(o: object, key: string): PropertyDescriptor | undefined {\n for (let x: object | null = o; x !== null && x !== Object.prototype; x = Object.getPrototypeOf(x)) {\n const d = Object.getOwnPropertyDescriptor(x, key);\n if (d !== undefined) return d;\n }\n return undefined;\n}\n\nfunction keysOf(o: object): string[] {\n const out = new Set<string>();\n for (let x: object | null = o; x !== null && x !== Object.prototype; x = Object.getPrototypeOf(x)) {\n for (const k of Object.getOwnPropertyNames(x)) if (k[0] !== \"$\" && k !== \"constructor\") out.add(k);\n }\n return [...out];\n}\n\n/**\n * The pattern a path with an explicit index reads through: an index with no `*` after it\n * (`items.0.x`) has an accessor of its own (Engine.markupAccessor), so whether it reads a getter\n * is the question of the pattern it names (`items.*.x`). A `*` after the index (`groups.0.items.*.x`,\n * a row of `for: groups.0.items`) reads its row's own item: the pattern itself. So does a path the\n * author declared a getter under (`get \"groups.0.items\"()`): that getter is what it reads (#388).\n */\nfunction wildcardForm(engine: Engine, q: Pattern): Pattern | undefined {\n const segs = q.path.split(\".\");\n // (a leading numeric segment is a root key, not an index: parsePath)\n const i = segs.findIndex((s, j) => j > 0 && /^\\d/.test(s));\n return i < 0 || segs.indexOf(\"*\", i) >= 0 || findDescriptor(engine.target, q.path)?.get !== undefined\n ? q : engine.patterns.peek(parsePath(q.path).pattern);\n}\n\n/**\n * The segment of `p` that certainly does not exist, with the names that do at its level; null\n * when the path exists or it cannot be told without evaluating a getter (a getter on the way, a\n * null or primitive on the way, a list with no row to look into).\n */\nfunction missing(engine: Engine, p: Pattern): { seg: string; names: string[]; row: boolean } | null {\n const chain: Pattern[] = [];\n for (let q: Pattern | null = p; q !== null; q = q.parent) chain.unshift(q);\n const named = (q: Pattern | null): Pattern | null | undefined => (q === null ? null : wildcardForm(engine, q));\n // a getter anywhere on the path answers it — also one declared deeper than a segment the data\n // lacks (\\`get \"box.label\"()\\` with no \\`box\\` key: it renders and updates — docs/seam-apps.md)\n if (chain.some((q) => named(q)?.getter != null)) return null;\n return under(engine, chain, 0, engine.target, named);\n}\n\n/** `missing` from `chain[k]` on, in `v`. */\nfunction under(engine: Engine, chain: Pattern[], k: number, v: any, named: (q: Pattern | null) => Pattern | null | undefined): { seg: string; names: string[]; row: boolean } | null {\n for (; k < chain.length; k++) {\n const q = chain[k];\n if (v === null || typeof v !== \"object\") return null;\n if (q.last === \"*\") {\n if (!Array.isArray(v) || v.length === 0) return null;\n // a row field is declared when any row has it — an optional one (`pending` on the rows a page\n // added itself) is not missing because the first row lacks it (docs/seam-apps.md, ssr-news)\n // (missing in every row: the names any row has are the candidates)\n let first: { seg: string; names: string[]; row: boolean } | null = null;\n for (const row of v) {\n const m = under(engine, chain, k + 1, row, named);\n if (m === null) return null;\n if (first === null) first = m;\n else if (m.seg === first.seg) for (const n of m.names) if (!first.names.includes(n)) first.names.push(n);\n }\n return first;\n }\n if (Array.isArray(v) && /^\\d+$/.test(q.last)) {\n // an explicit index: only a row that is there can be looked into\n if (Number(q.last) >= v.length) return null;\n v = v[Number(q.last)];\n continue;\n }\n const d = findDescriptor(v, q.last);\n // a top-level key a re-set dropped is declared: it reads undefined, and a write fills it\n if (d === undefined && q.parent === null && engine.dropped.has(q.last)) return null;\n if (d === undefined) {\n const names = keysOf(v);\n // getters declared one level under the same parent (`items.*.subtotal`)\n const parent = named(q.parent);\n for (const g of engine.patterns.all()) if (g.parent === parent && g.getter !== null) names.push(g.last);\n return { seg: q.last, names, row: chain.slice(0, k).some((x) => x.last === \"*\") };\n }\n if (d.get !== undefined || d.set !== undefined) return null;\n v = d.value;\n }\n return null;\n}\n\nfunction check(engine: Engine): void {\n due.delete(engine);\n const map = named.get(engine);\n if (map === undefined) return;\n let done = checked.get(engine);\n if (done === undefined) checked.set(engine, (done = new Set()));\n // The paths named, and those a getter read (`this[\"items.*.pirce\"]`, `$getAll(\"items.*.pirce\")`): such a read\n // gets undefined, and what is computed from it is wrong without a word (an outside evaluation, a tax return\n // draft). A top-level key the state lacks already fails the read (the core's error); a named path is reported\n // as named; the engine's own accessor of an index path (`items.0.x`) reads for the binding that named it\n const todo = new Map(map);\n const readers = new Map<Pattern, Pattern>();\n for (const p of engine.patterns.all()) {\n const g = p.parent === null || done.has(p) || map.has(p) ? undefined : p.dependents.find((d) => !d.markup);\n if (g === undefined) continue;\n readers.set(p, g);\n todo.set(p, READ);\n }\n for (const [p, kind] of todo) {\n if (done.has(p)) continue;\n done.add(p);\n const m = missing(engine, p);\n if (m === null) continue;\n // under the mount path of a volume on the page still loading: checked again once it settles (3.x D22)\n const v = [...((engine.root as ParentNode | null)?.querySelectorAll(`${config.tagNames.state}[mount]`) ?? [])]\n .find((e) => !settled.has(e) && (p.path + \".\").startsWith(e.getAttribute(\"mount\") + \".\"));\n if (v !== undefined) {\n done.delete(p);\n void (v as WcsState).initializePromise.then(() => {\n settled.add(v);\n schedule(engine);\n });\n continue;\n }\n // a row of `for: groups.0.items` with a row getter declared on `groups.*.items.*` (#388)\n const w = engine.patterns.peek(parsePath(p.path).pattern);\n let rowGetter = \"\";\n if (w !== undefined && w !== p && w.getter !== null) {\n const loops = w.lists.slice(1).map((l, k) => `for: ${k === 0 ? l!.path : l!.path.slice(w.lists[k]!.path.length + 2)}`);\n rowGetter = ` The getter \"${w.path}\" is declared for the rows of ${loops.join(\" → \")}; a list named by an index has rows of its own.`;\n }\n const near = didYouMean(m.seg, m.names);\n // A row field no row has is not a sign of a mistake: rows are data, and an optional field (the\n // `pending` a page puts on its own rows) is absent from the server's (docs/seam-apps.md, ssr-news).\n // Reported only with a near name — a likely typo (`.nmae` beside `name`) — or a row getter of\n // another list form. So is a getter's read: `this[\"opts.flag\"] ?? false` reads an optional key on purpose\n if ((m.row || kind === READ) && near === \"\" && rowGetter === \"\") continue;\n const [code, subject, source] = kind === WATCH ? [\"watch-path-missing\", \"$watch path\", \"watch\"]\n : kind === POST ? [\"post-update-path-missing\", \"$postUpdate path\", \"postUpdate\"]\n : kind === READ ? [\"read-path-missing\", \"Path\", \"getter\"]\n : [\"binding-path-missing\", \"Bound path\", \"binding\"];\n hooks.noticed?.(engine, { \"type\": \"state:path-unresolved\", \"source\": source, \"path\": p.path, \"missingSegment\": m.seg });\n console.warn(`[@wcstack/state] [wcs/${code}] ${subject} \"${p.path}\"${kind === READ ? ` read by the getter \"${readers.get(p)!.path}\"` : \"\"} does not resolve on the state tree: \"${m.seg}\" is not declared.${near}${rowGetter} ${kind === POST ? \"The call updates nothing.\" : kind === READ ? \"The getter reads undefined.\" : \"Updates to this path will be silently dropped.\"}${LINT_HINT}`);\n }\n}\n\nfunction schedule(engine: Engine): void {\n if (due.has(engine)) return;\n due.add(engine);\n setTimeout(() => check(engine), 0);\n}\n\n/** The `declared` hook: a path a binding or a `$watch` key names. */\nfunction declared(engine: Engine, p: Pattern, watch = false): void {\n note(engine, p, watch ? WATCH : BINDING);\n}\n\nfunction note(engine: Engine, p: Pattern, kind: number): void {\n // a missing top-level key already fails the binding's read (the core's error)\n if (p.path[0] === \"$\" || p.path.includes(\"#\") || (kind === BINDING && p.parent === null)) return;\n let map = named.get(engine);\n if (map === undefined) named.set(engine, (map = new Map()));\n if (!map.has(p)) map.set(p, kind);\n schedule(engine);\n}\n\nconst wrapped = new WeakSet<Engine>();\n/** A `$postUpdate` is running: what it lands is not a write (see written). */\nlet posting = false;\n\n/**\n * `$postUpdate(path)` says what at a path changed in place; a path that does not resolve updates nothing,\n * and said nothing (`rows.${r}.cell.${c}.text` for `cells` — a 7GUIs evaluation's Cells). Its pattern is\n * checked as a binding's is, the top-level key too (no read fails for it).\n */\nfunction watchPostUpdate(engine: Engine): void {\n if (wrapped.has(engine)) return;\n wrapped.add(engine);\n const api = (engine as any).api as Record<string, (path: string) => void>;\n const post = api.$postUpdate;\n api.$postUpdate = (path: string) => {\n posting = true;\n try {\n post(path);\n } finally {\n posting = false;\n }\n const p = engine.patterns.peek(parsePath(path).pattern);\n if (p !== undefined) note(engine, p, POST);\n };\n}\n\n/** The top-level keys a state declared (its own and its prototypes'), and those written since, by engine. */\nconst declaredKeys = new WeakMap<Engine, Set<string>>();\n\n/**\n * A write of a top-level key the state did not declare, beside a near one it did (`this.selectedID` and\n * `selectedId`): 4.0 creates the key, and nothing bound to the declared one changes (a 7GUIs evaluation's\n * CRUD). Warned once per key; a key with no near name is one the state adds on purpose.\n */\nfunction written(engine: Engine, p: Pattern): void {\n const keys = declaredKeys.get(engine);\n const key = p.last;\n if (p.parent !== null || posting || keys === undefined || keys.has(key) || key[0] === \"$\" || engine.dropped.has(key)) return;\n const near = didYouMean(key, [...keys]);\n keys.add(key);\n // (a volume grafts its state at its mount path, and the keys on the way to it: those keys are the page's)\n if (near !== \"\" && ![...((engine.root as ParentNode | undefined)?.querySelectorAll(`${config.tagNames.state}[mount]`) ?? [])]\n .some((e) => `${e.getAttribute(\"mount\")}.`.startsWith(`${key}.`))) {\n console.warn(`[@wcstack/state] [wcs/write-path-missing] \"${key}\" is not declared: writing it creates a new key.${near}${LINT_HINT}`);\n }\n}\n\n// ---------------------------------------------------------------- commands that reach nothing\n\n/**\n * A command token emitted while nothing subscribes to it: the call is lost, and tokens keep nothing to replay.\n * Its `command.` binding may not be attached yet — the element is defined later (an autoloader, a slow CDN),\n * or it is in an `if:` branch the same update renders (emit from `$renderedCallback`) — or there is none.\n * Warned once per token (the author's decision, docs/v4-direction-2026-10.md §5.2 — a 7GUIs evaluation's Timer\n * and Cells). The engine's `commands` is watched from its first declaration on, so the tokens of a re-set\n * are wrapped too.\n */\nfunction watchCommands(engine: Engine): void {\n if (Object.getOwnPropertyDescriptor(engine, \"commands\")?.set !== undefined) return;\n let ns = engine.commands;\n Object.defineProperty(engine, \"commands\", {\n configurable: true,\n get: () => ns,\n set: (v: Readonly<Record<string, Token>>) => {\n ns = v;\n for (const t of Object.values(v)) loud(t);\n },\n });\n}\n\nconst wrappedTokens = new WeakSet<Token>();\n\nfunction loud(t: Token): void {\n if (wrappedTokens.has(t)) return;\n wrappedTokens.add(t);\n const emit = t.emit;\n let said = false;\n (t as any).emit = (...args: unknown[]): unknown[] => {\n if (t.size === 0 && !said) {\n said = true;\n console.warn(`[@wcstack/state] [wcs/command-token-unbound] \"$command.${t.name}\" was emitted with no subscriber and is lost: its element is not defined or rendered yet (emit from $renderedCallback), or no command. binding takes it.${LINT_HINT}`);\n }\n return emit.apply(t, args);\n };\n}\n\n/** The handlers whose failure was explained, by engine. */\nconst explained = new WeakMap<Engine, Set<string>>();\n\n/**\n * The handler of a delegated `on<type>:` threw, and it reads `event.currentTarget`: that is the root there,\n * not the element (`getBoundingClientRect` is not a function, a `.value` is undefined). Said once per handler,\n * after the error (the author's decision, docs/v4-direction-2026-10.md §5.2 — a 7GUIs evaluation).\n */\nfunction handlerThrew(engine: Engine, path: string, type: string): void {\n let v: any = engine.target;\n for (const seg of path.split(\".\")) v = v == null ? undefined : findDescriptor(v, seg)?.value;\n if (typeof v !== \"function\" || !String(v).includes(\"currentTarget\")) return;\n let said = explained.get(engine);\n if (said === undefined) explained.set(engine, (said = new Set()));\n if (said.has(path)) return;\n said.add(path);\n console.warn(`[@wcstack/state] [wcs/delegated-current-target] \"${path}\" reads event.currentTarget, the root for a delegated on${type}:. Write on${type}#direct:, or use event.target.closest(…).${LINT_HINT}`);\n}\n\n// ---------------------------------------------------------------- $on handlers that use this\n\n/** The `$on` handlers already told about: a re-set state does not say it again. */\nconst toldThis = new WeakSet<(...args: any[]) => unknown>();\n/** `this.x`, `this[\"x\"]`, `const state = this` — not the word in a string (`\"this is\"`). */\nconst USES_THIS = /\\bthis\\s*[.[]|=\\s*this\\b/;\n\n/**\n * A `$on` handler that uses `this`: it is called as `handler(state, event)`, so `this` is undefined and it\n * throws when the event arrives — a TypeError with no code, which never says why (docs/seam-apps.md,\n * family-ledger). Said once per handler when the state is declared, before any event, as lint's\n * `wcs/on-handler-this` says it.\n */\nfunction onHandlersThis(target: Record<string, any>): void {\n const on = findDescriptor(target, \"$on\")?.value;\n if (on === null || typeof on !== \"object\") return;\n for (const name of Object.keys(on)) {\n const fn = on[name];\n if (typeof fn !== \"function\" || toldThis.has(fn) || !USES_THIS.test(String(fn))) continue;\n toldThis.add(fn);\n console.warn(`[@wcstack/state] [wcs/on-handler-this] The $on handler \"${name}\" uses this. A $on handler is called as ${name}(state, event): this is undefined there, so it throws when the event arrives — write ${name}(state, event) { state.x = … }.${LINT_HINT}`);\n }\n}\n\n// ---------------------------------------------------------------- two root states\n\n/** The roots already told about. */\nconst toldRoots = new WeakSet<Node>();\n\nconst describeState = (e: Element): string => {\n for (const a of [\"src\", \"state\", \"json\"]) if (e.hasAttribute(a)) return `<${e.localName} ${a}${a === \"json\" ? \"\" : `=\"${e.getAttribute(a)}\"`}>`;\n return `<${e.localName}>`;\n};\n\n/**\n * A root `<wcs-state>` binds a root that has another one: there is one state tree per root, and the one whose\n * state was ready first takes it — a `json=` state, ready at once, before the page's `src=` or inline state that\n * comes first in the document, which is then refused (#47) and the page binds against the wrong state\n * (docs/seam-apps.md, family-ledger). Said once per root, naming both.\n */\nfunction secondRoot(engine: Engine, phase: string): void {\n const el = engine.element as Element | null;\n if (phase !== \"mounting\" || !el) return;\n const root = el.getRootNode() as Node & ParentNode;\n if (toldRoots.has(root)) return;\n const others = [...root.querySelectorAll(config.tagNames.state)].filter((e) => e !== el && !e.hasAttribute(\"mount\") && !e.hasAttribute(\"bind-component\"));\n if (others.length === 0) return;\n toldRoots.add(root);\n console.warn(`[@wcstack/state] [wcs/second-root] ${others.length + 1} root <wcs-state> elements share one root, and there is one state tree per root: ${describeState(el)} takes it — its state was ready first, whatever the order in the document — and ${others.map(describeState).join(\", \")} is refused (#47). Keep one, and graft the others with <wcs-state mount=\"path\">.${LINT_HINT}`);\n}\n\n/**\n * A drain made patterns (`loose`, before its sweep): a getter may have read a path for the first time — in a\n * row added since, or down a branch of its own code. Checked as the bindings' are; a drain that read no new\n * path schedules nothing.\n */\nfunction drained(engine: Engine): void {\n if (named.has(engine) && ((engine as any).loose as Pattern[]).length > 0) schedule(engine);\n}\n\n/** A re-set: every path is checked again against the new state. */\nfunction recheck(engine: Engine): void {\n checked.delete(engine);\n if (named.has(engine)) schedule(engine);\n}\n\n// ---------------------------------------------------------------- recursion's static checks\n\n/**\n * `$recursion` families that can never work (approved simplification: these checks moved out of\n * the core): a suffix naming the recursion structure itself, two families one of which is the\n * other a few repeats deeper, and a concrete key that one of the families expands to.\n */\nfunction checkRecursion(target: Record<string, any>): void {\n const decl = target.$recursion;\n if (decl === null || typeof decl !== \"object\") return;\n const entries = Object.entries(decl);\n if (entries.length !== 1 || typeof entries[0][1] !== \"string\") return;\n const [anchor, repeat] = entries[0] as [string, string];\n if (!anchor.endsWith(\".*\") || !repeat.endsWith(\".*\")) return;\n const list = anchor.slice(0, -2);\n const key = repeat.slice(0, -2);\n const step = `.${repeat}`;\n const head = `${list}.**`;\n const keys = keysOf(target);\n const families = keys.filter((k) => k.startsWith(head)).map((k) => k.slice(head.length));\n const bad = (why: string): never => raiseError(`[wcs/recursion-declaration-invalid] ${why}`);\n for (const s of families) {\n if (s === `.${key}` || s.startsWith(`.${key}.`)) {\n bad(`\"${head}${s}\" names the recursion structure itself (the \"${key}\" lists): recursive getters compute values over the nodes.`);\n }\n for (const t of families) {\n if (t.length > s.length && t.endsWith(s) && new RegExp(`^(?:${esc(step)})+$`).test(t.slice(0, t.length - s.length))) {\n bad(`\"${head}${s}\" and \"${head}${t}\" expand to the same concrete path at different depths (they differ by whole repetitions of \"${repeat}\"). Rename one of them.`);\n }\n }\n const re = new RegExp(`^${esc(anchor)}(?:${esc(step)})*${esc(s)}$`);\n for (const k of keys) {\n if (!k.includes(\"**\") && re.test(k)) bad(`\"${k}\" is already defined on the state, so the recursive getter \"${head}${s}\" cannot expand to it.`);\n }\n }\n}\n\nconst esc = (s: string): string => s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\nlet trustedTypesReported = false;\n\n/**\n * An HTML sink write Trusted Types blocked: the browser's message names no fix, so say once\n * per page what to install (the same report as @wcstack/state 3.3).\n */\nfunction failed(_engine: Engine, error: unknown, binding: Binding): void {\n const prop = binding.name === \"html\" ? \"innerHTML\" : binding.name;\n if (trustedTypesReported || !(error instanceof TypeError) || !isHtmlSink(prop) || !(\"trustedTypes\" in globalThis)) return;\n trustedTypesReported = true;\n const cause = typeof getTrustedTypesPolicy()?.createHTML === \"function\"\n ? \"The injected policy's createHTML() did not return a TrustedHTML.\"\n : \"No sanitizing policy is installed, and @wcstack/state deliberately does not pass state values through an identity policy — that would defeat the CSP.\";\n console.error(\n `[@wcstack/state] Writing to \"${prop}\" was blocked by Trusted Types (require-trusted-types-for 'script'). ${cause}\\n`\n + `Install a sanitizing policy before the first binding is applied:\\n`\n + ` globalThis[Symbol.for(\"wcstack.trustedTypes.policy\")] =\\n`\n + ` trustedTypes.createPolicy(\"my-app\", { createHTML: (s) => DOMPurify.sanitize(s) });\\n`\n + `Or bind the value as text instead of HTML. See docs/csp.md section 7.`,\n { element: binding.node, property: prop },\n );\n}\n\n// ---------------------------------------------------------------- the default getter\n\nconst warnedDetail = new WeakMap<Element, Set<string>>();\n\n/**\n * A wc-bindable property's event read with the default getter (`e.detail`): warns once per\n * element and property about the two shapes that cannot be what the element meant (README\n * \"What the element writes back\", as @wcstack/state 3.3). The write is applied as it is.\n * (a) no detail while the element's property has a value — a plain Event, or a forgotten detail;\n * (b) a detail object with a `<name>` key while the property is not an object — a wrapper.\n */\nfunction detail(el: Element, name: string, v: unknown): void {\n const prop = (el as any)[name];\n const reason = v === undefined\n ? prop === undefined ? null : `the event carried no detail (undefined) while element.${name} is ${typeof prop}`\n : v !== null && typeof v === \"object\" && Object.prototype.hasOwnProperty.call(v, name) && (prop === null || typeof prop !== \"object\")\n ? `the event's detail is an object with a \"${name}\" key while element.${name} is ${typeof prop}`\n : null;\n if (reason === null) return;\n let said = warnedDetail.get(el);\n if (said === undefined) warnedDetail.set(el, (said = new Set()));\n if (said.has(name)) return;\n said.add(name);\n console.warn(\n `[@wcstack/state] [wcs/default-getter-mismatch] <${el.localName}> \"${name}\": ${reason}. `\n + \"With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare \"\n + `getter (e.g. (e) => e.detail.${name}, or (e) => e.target.${name}) on that wcBindable property.`,\n );\n}\n\n// ---------------------------------------------------------------- 3.x names 4.0 removed\n\n/**\n * Declarations 3.2 renamed, whose old names 4.0 removed: a declaration under one would do nothing.\n * (The core detected these and the two APIs below up to 4.0.0-rc.3; without this add-on they are\n * ignored like any other unknown `$` key.)\n */\nconst REMOVED_DECLARATIONS: [string, string][] = [[\"$streams\", \"$stream\"], [\"$updatedCallback\", \"$renderedCallback\"]];\n/** APIs 3.2 renamed, whose old names 4.0 removed: reading one fails with the name to write. */\nconst REMOVED_APIS: Readonly<Record<string, string>> = { \"$trackDependency\": \"$dependOn\", \"$untrackDependency\": \"$untracked\" };\n\n/** A state that declares a 3.x name 4.0 removed (`$scan` has no successor: $watch or $on). */\nfunction removedDeclarations(target: Record<string, any>): void {\n if (target.$scan !== undefined) raise(M.ScanRemoved);\n for (const [old, name] of REMOVED_DECLARATIONS) if (target[old] !== undefined) raise(M.DeclarationRemoved, [old, name]);\n}\n\nexport const diagnostics: Feature = {\n name: \"diagnostics\",\n hooks,\n install(): void {\n hooks.explain = explain;\n hooks.render = render;\n hooks.declared = declared;\n hooks.detail = detail;\n hooks.failed = chain(hooks.failed, failed);\n // the removed names first, before what is installed (the core checked them before it took the\n // state in): a refused state never reaches the other add-ons' runtimes\n const prev = hooks.declare;\n hooks.declare = (engine, target) => {\n removedDeclarations(target);\n prev?.(engine, target);\n checkRecursion(target);\n onHandlersThis(target);\n recheck(engine);\n watchPostUpdate(engine);\n watchCommands(engine);\n declaredKeys.set(engine, new Set(keysOf(target)));\n };\n hooks.handlerThrew = handlerThrew;\n hooks.element = chain(hooks.element, secondRoot);\n hooks.written = chain(hooks.written, written);\n hooks.drained = chain(hooks.drained, drained);\n hooks.dollar = first(known, hooks.dollar, (_engine, key) => (Object.hasOwn(REMOVED_APIS, key) ? raise(M.ApiRemoved, [key, REMOVED_APIS[key]]) : undefined));\n },\n};\nexport default diagnostics;\n","/**\n * `$watch` — the headless subscription (README \"Watch\", docs/state-watch-hook-design.md).\n *\n * A handler fires at the end of a drain, once per location that landed in it: a write of its\n * path or of an object above it in the same row, a change that reached its getter, a row that\n * entered its list. `cur` is the value at the drain; `prev` the value before the batch's first\n * write when a primitive was written (for a getter: its previous evaluation). A change that reaches\n * a getter fires it, whether its value changed or not (3.x D4: a watch has no condition of its own).\n * A row's getter that no write of the batch changed — it read none of the written paths, directly or\n * through a getter it read — fires only if its value changed: a row a list kept when a write\n * re-synced or re-sorted the list (`items = [...items, x]`) is reached again through what it read\n * under the row, which did not change (#389). A write at the list (or above it) changes what a row\n * read there (`this.items.length`), not under its row.\n * Declaration order between handlers, ascending indexes between rows of one path.\n *\n * A handler's writes form the next batch. Each write carries a chain depth (as @wcstack/state\n * 3.4, #354): 0, or one more than the depth of what fired the handler making it — or restarted the\n * `$stream` making it (stream.ts: its run's values and end too, within the task the run started in).\n * For a data path that is the deepest write landing there in the batch; for a getter, the first write\n * since it was last evaluated (a reached getter is not reached again until it is read), and 0 when a\n * list re-synced in the drain reached it — loops through those are left to the render chain\n * (MAX_RENDER_CHAIN). A handler fired more than MAX_CHAIN deep does not\n * run (as 3.x: 33 links run): the chain is cut and reported once. Writes riding in the same batch (a\n * render's write-back) neither lengthen nor reset it.\n *\n * Differences from @wcstack/state 3.3 that rows make possible: a row watch needs neither a\n * `for` binding nor `$listKeys` (the watch keeps its lists synced itself), wildcard getters are\n * eager too, and a whole-array assignment fires only for the rows that entered the list (a row\n * kept by identity did not change).\n */\nimport type { Engine } from \"../engine\";\nimport type { Pattern } from \"../pattern\";\nimport type { StateList, StateRow } from \"../list\";\nimport { raiseError, report } from \"../parser/raiseError\";\nimport { hooks } from \"../hooks\";\n\ntype Handler = (this: unknown, cur: unknown, prev: unknown, ...indexes: number[]) => unknown;\n\ninterface Watch {\n readonly path: string;\n readonly p: Pattern;\n readonly handler: Handler;\n /** A getter (or under one): kept evaluated, `prev` is its previous evaluation. */\n getter: boolean;\n /** Previous evaluation by row (getter watches; the root's under ROOT): a removed row takes its entry with it. */\n last: WeakMap<object, unknown>;\n}\n\n/**\n * A landing of a batch: `prev` (the first write's), the deepest write's chain depth, and whether a\n * write landed there (not only a change that reached a getter).\n */\ntype Hit = [prev: unknown, depth: number, landed: boolean];\n\nexport const MAX_CHAIN = 32;\nconst ROOT = {};\n/**\n * An explicit index (`items.0.v`, read like a getter): a write to another row, a list change,\n * reaches it unchanged. A leading numeric segment is a root key (`2024.total`), not an index.\n */\nconst INDEX_PATH = /\\.\\d/;\nconst PROTOTYPE_NAMES = new Set(Object.getOwnPropertyNames(Object.prototype));\n\n/**\n * The current task's number, bumped in the next task after it is asked for: a MessageChannel message\n * (neither throttled in a background tab nor replaced by a faked timer), or a timer where there is none.\n */\nlet taskSeq = 0;\nlet pinged = false;\nlet ping: (() => void) | null = null;\nconst nextTask = (): void => {\n pinged = false;\n taskSeq++;\n};\nexport function thisTask(): number {\n if (ping === null) {\n if (typeof MessageChannel === \"function\") {\n const ch = new MessageChannel();\n ch.port1.onmessage = nextTask;\n // (Node: the port must not keep the process alive)\n (ch.port1 as { unref?: () => void }).unref?.();\n ping = () => ch.port2.postMessage(0);\n } else ping = () => setTimeout(nextTask, 0);\n }\n if (!pinged) {\n pinged = true;\n ping();\n }\n return taskSeq;\n}\n\n/** Whether a write at a path of `changed` changed what getter `g` read (directly, or through a getter it read). */\nfunction reads(g: Pattern, changed: Set<Pattern>): boolean {\n const seen = new Set<Pattern>();\n const stack = [g];\n while (stack.length > 0) {\n const h = stack.pop()!;\n if (seen.has(h)) continue;\n seen.add(h);\n for (const s of h.sources) {\n for (const p of changed) {\n // a write at the list a row is in (or above it) changes what was read there, not under the row\n if (s.isUnder(p) && (s.depth === p.depth || !(p.depth < h.depth && h.lists[p.depth + 1]!.isUnder(p)))) return true;\n }\n if (s.getter !== null) stack.push(s);\n }\n }\n return false;\n}\n\nexport function parseWatches(engine: Engine, decl: unknown): Watch[] {\n if (decl === undefined) return [];\n if (decl === null || typeof decl !== \"object\") raiseError(\"$watch must be an object mapping paths to handler functions.\");\n const out: Watch[] = [];\n for (const path of Object.keys(decl)) {\n const handler = (decl as Record<string, unknown>)[path];\n if (path === \"\" || path[0] === \"$\" || path.includes(\"@\") || PROTOTYPE_NAMES.has(path)) raiseError(`$watch path \"${path}\" is not a path of the state tree.`);\n if (typeof handler !== \"function\") raiseError(`$watch entry \"${path}\" must be a function.`);\n const p = engine.pattern(path);\n hooks.declared?.(engine, p, true);\n out.push({ path, p, handler: handler as Handler, getter: false, last: new WeakMap() });\n }\n return out;\n}\n\nexport class WatchRuntime {\n readonly engine: Engine;\n readonly watches: Watch[];\n active = false;\n /** Landings of the current batch: watch → row → hit. */\n private hits = new Map<Watch, Map<StateRow | null, Hit>>();\n /**\n * What elements wrote before the watches were active — the value an element already had when its\n * binding attached (an open `<wcs-sse>`, the router's first params, a `<wcs-storage>`'s saved value):\n * [path, row, the value before, the value the element wrote]. Whether that value is there before or\n * after the bindings attach depends on how fast the page loaded, so activate() fires, once, the\n * watches of the paths that still hold it, and the root getters that read them (`prev`: the value\n * before, none for a getter) — docs/seam-apps.md: state-collab-board, router-admin, router-auth.\n * A write from code before then (`$connectedCallback`) fires nothing, as before.\n */\n private early: [Pattern, StateRow | null, unknown, unknown][] = [];\n /** The chain depth of a write made now: 0, or one more than what fired the running handler (or restart). */\n depth = 0;\n /**\n * The paths a cut reported in task `cutTask`. A chain carries its depth only synchronously (and\n * through a `$stream`'s values within the task its run started in): a cut of the same paths later\n * in the task is the same chain's — what it left running reaching the limit again.\n */\n private cutTask = -1;\n private reported = new Set<string>();\n /** The paths written in the batch (what a change reaching a getter may have come from). */\n private changed: Set<Pattern> | null = null;\n\n constructor(engine: Engine, watches: Watch[]) {\n this.engine = engine;\n this.watches = watches;\n }\n\n /** After `$connectedCallback` (and on reconnect): watches see the writes from now on. */\n activate(): void {\n const engine = this.engine;\n this.hits.clear();\n const early = this.early;\n this.early = [];\n for (const w of this.watches) {\n w.getter = w.p.getter !== null || w.p.underGetter;\n w.last = new WeakMap();\n // (the list a row watch reads can be a getter that throws too)\n this.prime(w, () => {\n if (w.p.depth === 0) {\n if (w.getter) w.last.set(ROOT, engine.readUntracked(w.p, null));\n } else {\n // a row watch keeps its lists synced, rendered or not; a getter watch is eager per row\n this.eachRow(w.p, 1, null, (row) => {\n if (w.getter) this.prime(w, () => w.last.set(row, engine.readUntracked(w.p, row)));\n });\n }\n });\n }\n this.active = true;\n // what elements brought before now, still there: fired once, as the writes of a batch\n const held = new Set<Pattern>();\n for (const [p, row, before, value] of early) {\n if ((row === null || row.alive) && Object.is(engine.readUntracked(p, row), value)) {\n held.add(p);\n for (const w of this.watches) if (w.p === p) this.hit(w, row, before, true);\n }\n }\n // (a root getter's sources are known now: priming evaluated it)\n for (const w of this.watches) if (w.getter && w.p.depth === 0 && !this.hits.has(w) && reads(getterOf(w.p), held)) this.hit(w, null, undefined, true);\n if (this.hits.size > 0) engine.schedule();\n }\n\n /** What a watch reads before the writes (its `prev`): what throws is reported, the others go on. */\n private prime(w: Watch, read: () => void): void {\n try {\n read();\n } catch (error) {\n report(error, `[@wcstack/state] $watch initial evaluation of \"${w.path}\" threw.`);\n hooks.noticed?.(this.engine, { \"type\": \"state:watch-error\", \"phase\": \"prime\", \"path\": w.path, \"error\": error });\n }\n }\n\n deactivate(): void {\n this.active = false;\n this.hits.clear();\n this.early = [];\n }\n\n /** Calls fn for every row at p.depth, creating the lists on the way (they then stay synced). */\n private eachRow(p: Pattern, k: number, parent: StateRow | null, fn: (row: StateRow) => void): void {\n const engine = this.engine;\n const list = engine.childList(parent, p.lists[k]!);\n for (const row of list.rows) {\n if (k === p.depth) fn(row);\n else this.eachRow(p, k + 1, row, fn);\n }\n }\n\n /** Records a landing at the current depth: the first `prev` stays, the deepest write's depth wins. */\n private hit(w: Watch, row: StateRow | null, prev: unknown, landed: boolean): void {\n let rows = this.hits.get(w);\n if (rows === undefined) this.hits.set(w, (rows = new Map()));\n const h = rows.get(row);\n if (h === undefined) rows.set(row, [prev, this.depth, landed]);\n else {\n if (h[1] < this.depth) h[1] = this.depth;\n h[2] ||= landed;\n }\n }\n\n written(p: Pattern, row: StateRow | null, old: unknown, value: unknown, direct: boolean, element?: boolean): void {\n if (!this.active) {\n // an element's write before the watches are active (see `early`)\n if (element) this.early.push([p, row, old, value]);\n return;\n }\n (this.changed ??= new Set()).add(p);\n for (const w of this.watches) {\n const wp = w.p;\n // the watched path, or an object above it in the same row (a getter's row replaced included)\n if (wp.depth !== p.depth || !wp.isUnder(p)) continue;\n // `prev`: a getter's previous evaluation; for data, the old value the same-value guard reads\n // when a primitive was written there (none when it is off, or above it)\n this.hit(w, row, w.getter ? w.last.get(row ?? ROOT) : wp === p && direct && this.engine.guard && (value === null || (typeof value !== \"object\" && typeof value !== \"function\")) ? old : undefined, true);\n }\n }\n\n getterReached(g: Pattern, row: StateRow | null): void {\n if (!this.active) return;\n // a getter, or a path under it in the same row — also one that became so after the activation\n // (a mounted component's exported getter, a volume's accessor grafted later)\n for (const w of this.watches) {\n if ((w.getter ||= w.p.getter !== null || w.p.underGetter) && w.p.depth === g.depth && w.p.isUnder(g)) this.hit(w, row, w.last.get(row ?? ROOT), false);\n }\n }\n\n /** Rows that entered a list a row watch ranges over fire (and nested lists under them sync). */\n listSynced(list: StateList, old: StateRow[]): void {\n if (!this.active) return;\n let before: Set<StateRow> | null = null;\n for (const w of this.watches) {\n const wp = w.p;\n if (wp.depth < list.depth || wp.lists[list.depth] !== list.pattern) continue;\n before ??= new Set(old);\n for (const row of list.rows) {\n if (before.has(row)) continue;\n if (wp.depth === list.depth) this.hit(w, row, undefined, true);\n else this.eachRow(wp, list.depth + 1, row, (r) => this.hit(w, r, undefined, true));\n }\n }\n }\n\n drained(): void {\n const changed = this.changed;\n this.changed = null;\n if (!this.active || this.hits.size === 0) return;\n const batch = this.hits;\n this.hits = new Map();\n const engine = this.engine;\n const cut: string[] = [];\n for (const w of this.watches) {\n const rows = batch.get(w);\n if (rows === undefined) continue;\n const entries = [...rows].filter(([row]) => row === null || row.alive);\n if (entries.length > 1) entries.sort((a, b) => compareRows(a[0]!, b[0]!));\n // (whether a write of the batch changed what the watched getter read: asked once, for an unchanged row)\n let real: boolean | undefined;\n for (const [row, [prev, depth, landed]] of entries) {\n let cur: unknown;\n // (DevTools: the handler fired, or what threw — the value's evaluation or the handler)\n let phase = \"evaluate\";\n const saved = engine.ctx;\n this.depth = depth + 1;\n engine.feeding++;\n try {\n // (read past the limit too: a getter's cache is then current, and its next change reaches it)\n cur = engine.readUntracked(w.p, row);\n if (w.getter) {\n w.last.set(row ?? ROOT, cur);\n // unchanged: an explicit index, or a row no write of the batch changed (a row a list kept, #389)\n if (Object.is(cur, prev) && (INDEX_PATH.test(w.path) || (row !== null && !landed && !(real ??= changed !== null && reads(getterOf(w.p), changed))))) continue;\n }\n // fired more than MAX_CHAIN deep: the chain stops here (the batch's other handlers run)\n if (depth > MAX_CHAIN) {\n if (!cut.includes(w.path)) cut.push(w.path);\n continue;\n }\n engine.ctx = row;\n hooks.noticed?.(engine, { \"type\": \"state:watch-fired\", \"path\": w.path });\n phase = \"handler\";\n w.handler.call(engine.proxy, cur, prev, ...engine.indexesOf(row));\n } catch (error) {\n report(error, `[@wcstack/state] $watch \"${w.path}\" failed; the other watches still run.`);\n hooks.noticed?.(engine, { \"type\": \"state:watch-error\", \"phase\": phase, \"path\": w.path, \"error\": error });\n } finally {\n engine.ctx = saved;\n this.depth = 0;\n engine.feeding--;\n }\n }\n }\n if (cut.length > 0) this.chainCut(cut);\n }\n\n /** A chain of handlers / stream restarts went past MAX_CHAIN: reported once a task for its paths (nothing is rolled back). */\n chainCut(paths: string[]): void {\n const task = thisTask();\n if (task !== this.cutTask) {\n this.cutTask = task;\n this.reported.clear();\n }\n const fresh = paths.filter((path) => !this.reported.has(path));\n if (fresh.length === 0) return;\n for (const path of fresh) this.reported.add(path);\n report(`[@wcstack/state] $watch handlers / $stream restarts kept writing for ${MAX_CHAIN} batches; the chain is cut (nothing is rolled back).`);\n hooks.noticed?.(this.engine, { \"type\": \"state:watch-chain-limit\", \"maxDepth\": MAX_CHAIN, \"paths\": fresh });\n }\n}\n\n/** The getter a watched path is, or lies under (in the same row). */\nfunction getterOf(p: Pattern): Pattern {\n while (p.getter === null && p.parent !== null) p = p.parent;\n return p;\n}\n\n/** Ascending indexes, outermost first. */\nfunction compareRows(a: StateRow, b: StateRow): number {\n const ia: number[] = [];\n const ib: number[] = [];\n for (let r: StateRow | null = a; r !== null; r = r.list.parentRow) ia.unshift(r.index);\n for (let r: StateRow | null = b; r !== null; r = r.list.parentRow) ib.unshift(r.index);\n for (let i = 0; i < ia.length && i < ib.length; i++) if (ia[i] !== ib[i]) return ia[i] - ib[i];\n return ia.length - ib.length;\n}\n","/**\n * `$stream` — an async producer folded into one reactive property (README \"Streams\",\n * packages/state/docs/streams.md).\n *\n * `args` runs as a getter of its own (a pattern with no path in the state), so the paths it reads\n * are tracked like any getter's; a change that reaches it restarts the stream at the end of the\n * drain, once (switchMap: abort, reset to `initial`, re-run `args`, call `source`). Its\n * dependencies are captured afresh on every run. `$streamStatus.<name>` / `$streamError.<name>` are\n * read-only companions kept on the state.\n *\n * A restart's writes are reactions: they continue the render chain (MAX_RENDER_CHAIN), and the\n * `$watch` chain (watch.ts) one deeper than the write that reached `args` (#354). That depth is the\n * deepest such write's for a data path `args` reads, but the first one's since `args` was last\n * evaluated when the change came through a getter (a reached getter is not reached again until it\n * is read), and 0 when a list re-synced in the drain reached it: such loops are left to the render\n * chain. A restart more than MAX_CHAIN deep is not made (the chain is cut and reported); the next\n * change of its inputs restarts it.\n *\n * A run's own writes after its start — a value its source yields, the status `done` / `error` — made\n * within the task the run started in (synchronously or in its microtasks) are as deep as the run: the\n * `$watch` handlers they fire and the restarts they cause continue its chain, so a loop through a\n * source that yields at once (a `$watch` on the value moving what `args` reads, two streams reading\n * each other's values) is cut instead of running on microtasks alone. From a later task (a network\n * response, a message, a timer) they are new input, as a write from code: they start a chain afresh.\n */\nimport type { Engine } from \"../engine\";\nimport { FAILED, UNSET, type Pattern } from \"../pattern\";\nimport { raiseError } from \"../parser/raiseError\";\nimport { MAX_CHAIN, thisTask, type WatchRuntime } from \"./watch\";\n\ntype Status = \"idle\" | \"active\" | \"done\" | \"error\";\n\ninterface Entry {\n readonly name: string;\n readonly source: (args: unknown, signal: AbortSignal) => unknown;\n readonly fold: ((acc: unknown, chunk: unknown) => unknown) | undefined;\n readonly initial: unknown;\n /** The `args` getter (null without args: start once). */\n readonly g: Pattern | null;\n readonly args: (() => unknown) | null;\n controller: AbortController | null;\n restart: boolean;\n /** The `$watch` chain depth of what asked for the restart (meaningful while `restart`). */\n depth: number;\n}\n\nconst STATUS = \"$streamStatus\";\nconst ERROR = \"$streamError\";\nconst PROTOTYPE_NAMES = new Set(Object.getOwnPropertyNames(Object.prototype));\n\n/** A read-only companion path is being written by the runtime itself. */\nexport let internalWrite = false;\n\nfunction hasAccessorOrMethod(target: object, name: string): boolean {\n for (let o: object | null = target; o !== null && o !== Object.prototype; o = Object.getPrototypeOf(o)) {\n const d = Object.getOwnPropertyDescriptor(o, name);\n if (d !== undefined) return d.get !== undefined || d.set !== undefined || typeof d.value === \"function\";\n }\n return false;\n}\n\n/** Validates `$stream` and materializes the value property and the companions on `target`. */\nexport function parseStreams(engine: Engine, target: Record<string, any>): Entry[] {\n const decl = target.$stream;\n if (decl === undefined) return [];\n if (decl === null || typeof decl !== \"object\") raiseError(\"$stream must be an object mapping stream names to definitions.\");\n const entries: Entry[] = [];\n const status: Record<string, Status> = {};\n const errors: Record<string, unknown> = {};\n for (const name of Object.keys(decl)) {\n // the author's object: read by quoted keys (the build shortens internal property names)\n const def = decl[name];\n if (name === \"\" || name[0] === \"$\" || /[.*]/.test(name) || PROTOTYPE_NAMES.has(name)) raiseError(`$stream entry \"${name}\" must be a flat property name.`);\n if (def === null || typeof def !== \"object\") raiseError(`$stream entry \"${name}\" must be an object.`);\n const source = def[\"source\"];\n const fold = def[\"fold\"];\n const args = def[\"args\"];\n const initial = def[\"initial\"];\n if (typeof source !== \"function\") raiseError(`$stream entry \"${name}\" needs a source function.`);\n if (fold !== undefined && typeof fold !== \"function\") raiseError(`$stream entry \"${name}\": fold must be a function.`);\n if (fold !== undefined && !(\"initial\" in def)) raiseError(`$stream entry \"${name}\": fold needs an initial value.`);\n if (args !== undefined && typeof args !== \"function\") raiseError(`$stream entry \"${name}\": args must be a function.`);\n if (hasAccessorOrMethod(target, name)) raiseError(`$stream entry \"${name}\" collides with a getter, setter or method of the state.`);\n if (target[name] === undefined) target[name] = initial;\n status[name] = \"idle\";\n errors[name] = null;\n entries.push({\n name, source, fold, initial, controller: null, restart: false, depth: 0,\n g: args === undefined ? null : engine.pattern(`$streamArgs.${name}`),\n args: args === undefined ? null : function (this: unknown) { return args(this); },\n });\n }\n target[STATUS] = status;\n target[ERROR] = errors;\n return entries;\n}\n\nexport class StreamRuntime {\n readonly engine: Engine;\n readonly entries: Entry[];\n /** The engine's `$watch` runtime: it holds the depth of the write made now, and reports a cut. */\n readonly watch: WatchRuntime;\n\n constructor(engine: Engine, entries: Entry[], watch: WatchRuntime) {\n this.engine = engine;\n this.entries = entries;\n this.watch = watch;\n }\n\n private set(ns: string, name: string, value: unknown): void {\n internalWrite = true;\n try {\n this.engine.write(this.engine.pattern(`${ns}.${name}`), null, value);\n } finally {\n internalWrite = false;\n }\n }\n\n /** Eager start after `$connectedCallback`: an `args` failure is thrown as is. */\n startAll(): void {\n for (const e of this.entries) this.start(e, true);\n }\n\n /** A re-set replaced the state: the old runs stop without touching the new state. */\n abortAll(): void {\n for (const e of this.entries) {\n e.restart = false;\n e.controller?.abort();\n e.controller = null;\n }\n }\n\n stopAll(): void {\n for (const e of this.entries) {\n e.restart = false;\n if (e.controller !== null) {\n e.controller.abort();\n e.controller = null;\n }\n this.set(STATUS, e.name, \"idle\");\n }\n }\n\n getterReached(g: Pattern): void {\n const depth = this.watch.depth;\n for (const e of this.entries) {\n if (e.g !== g) continue;\n // (a restart a stop or a re-set dropped leaves its depth behind)\n e.depth = e.restart ? Math.max(e.depth, depth) : depth;\n e.restart = true;\n }\n }\n\n /** At the end of a drain (after the watches): each stream whose `args` inputs changed restarts once. */\n drained(): void {\n const engine = this.engine;\n const watch = this.watch;\n const cut: string[] = [];\n for (const e of this.entries) {\n if (!e.restart) continue;\n const depth = e.depth;\n e.restart = false;\n if (depth > MAX_CHAIN) {\n cut.push(e.name);\n // reached, not re-run: the next change of its inputs must reach it again\n e.g!.rootValue = FAILED;\n continue;\n }\n watch.depth = depth + 1;\n engine.feeding++;\n try {\n this.start(e, false);\n } finally {\n engine.feeding--;\n watch.depth = 0;\n }\n }\n if (cut.length > 0) watch.chainCut(cut);\n }\n\n private start(e: Entry, eager: boolean): void {\n const engine = this.engine;\n if (e.controller !== null) e.controller.abort();\n e.controller = null;\n let args: unknown;\n if (e.g !== null) {\n const g = e.g;\n // (re)attached on every start: a re-set forgets every accessor of the old state\n g.getter = e.args;\n const kept = g.sources.slice();\n untrack(g);\n try {\n args = engine.read(g, null);\n checkArgs(e.name, g, args);\n } catch (error) {\n // the dependencies of the last successful run stay: touching one retries\n untrack(g);\n for (const s of kept) s.addDependent(g);\n g.rootValue = FAILED;\n if (eager) throw error;\n this.set(ERROR, e.name, error);\n this.set(STATUS, e.name, \"error\");\n return;\n }\n }\n const ctrl = new AbortController();\n e.controller = ctrl;\n engine.write(engine.pattern(e.name), null, e.initial);\n this.set(ERROR, e.name, null);\n this.set(STATUS, e.name, \"active\");\n void this.consume(e, ctrl, args);\n }\n\n private async consume(e: Entry, ctrl: AbortController, args: unknown): Promise<void> {\n const engine = this.engine;\n const signal = ctrl.signal;\n const live = (): boolean => !signal.aborted && e.controller === ctrl;\n const p = engine.pattern(e.name);\n // the run's depth and task: what it writes in that task continues its chain\n const depth = this.watch.depth;\n const task = thisTask();\n const put = (fn: () => void): void => {\n if (thisTask() === task) this.watch.depth = depth;\n try {\n fn();\n } finally {\n this.watch.depth = 0;\n }\n };\n let acc = e.initial;\n try {\n const producer: any = await e.source(args, signal);\n if (!live()) return;\n const chunk = (v: unknown): void => {\n acc = e.fold !== undefined ? e.fold(acc, v) : v;\n put(() => engine.write(p, null, acc));\n };\n if (producer !== null && typeof producer?.getReader === \"function\") {\n // a ReadableStream: only reader.cancel() can unwind a parked read\n const reader = producer.getReader();\n signal.addEventListener(\"abort\", () => { reader.cancel().catch(() => {}); });\n for (;;) {\n const r = await reader.read();\n if (!live()) return;\n if (r.done) break;\n chunk(r.value);\n }\n } else if (producer !== null && typeof producer?.[Symbol.asyncIterator] === \"function\") {\n const it = producer[Symbol.asyncIterator]();\n signal.addEventListener(\"abort\", () => { void it.return?.(); });\n for (;;) {\n const r = await it.next();\n if (!live()) return;\n if (r.done) break;\n chunk(r.value);\n }\n } else {\n throw new TypeError(`$stream \"${e.name}\": source must return an async iterable or a ReadableStream`);\n }\n if (!live()) return;\n e.controller = null;\n put(() => this.set(STATUS, e.name, \"done\"));\n } catch (error) {\n if (!live()) return;\n e.controller = null;\n ctrl.abort();\n put(() => {\n this.set(ERROR, e.name, error);\n this.set(STATUS, e.name, \"error\");\n });\n }\n }\n}\n\n/** Forgets what a getter read (its dependencies are captured again by the next evaluation). */\nfunction untrack(g: Pattern): void {\n for (const s of g.sources) {\n const i = s.dependents.indexOf(g);\n if (i >= 0) s.dependents.splice(i, 1);\n (s as any).dependentSet.delete(g);\n }\n g.sources.length = 0;\n g.rootValue = UNSET;\n}\n\nfunction checkArgs(name: string, g: Pattern, args: unknown): void {\n if (args !== null && typeof (args as any)?.then === \"function\") raiseError(`$stream \"${name}\": args must be synchronous (it returned a Promise).`);\n for (const s of g.sources) {\n if (s.depth > 0) raiseError(`$stream \"${name}\": args must not read a wildcard path (\"${s.path}\").`);\n if (s.path === name || s.path === `${STATUS}.${name}` || s.path === `${ERROR}.${name}`) raiseError(`$stream \"${name}\": args must not read the stream itself (\"${s.path}\").`);\n }\n}\n","/**\n * The temporal add-on (@wcstack/state/features/temporal): `$watch` and `$stream`.\n * At the end of every drain, after its report (`$renderedCallback`): the watches, then the\n * stream restarts. Both start after `$connectedCallback` and stop on disconnect.\n */\nimport type { Engine } from \"../engine\";\nimport { chain, first, handled, hooks, known, type Feature } from \"../hooks\";\nimport { raiseError } from \"../parser/raiseError\";\nimport { parseWatches, WatchRuntime } from \"../temporal/watch\";\nimport { internalWrite, parseStreams, StreamRuntime } from \"../temporal/stream\";\n\ninterface Runtime {\n watch: WatchRuntime;\n stream: StreamRuntime;\n connected: boolean;\n /** The state it was made for: a re-set refused after it (list-keys, recursion) leaves the old one in place. */\n target: object;\n}\n\nconst runtimes = new WeakMap<Engine, Runtime>();\n/** The engine's runtime when it is its state's (not one a refused re-set left: that one never runs). */\nfunction live(engine: Engine): Runtime | undefined {\n const rt = runtimes.get(engine);\n return rt?.target === engine.target ? rt : undefined;\n}\n\nfunction declare(engine: Engine, target: Record<string, any>): void {\n const watch = new WatchRuntime(engine, parseWatches(engine, target.$watch));\n const stream = new StreamRuntime(engine, parseStreams(engine, target), watch);\n const old = runtimes.get(engine);\n if (old !== undefined) {\n old.watch.deactivate();\n old.stream.abortAll();\n }\n runtimes.set(engine, { watch, stream, connected: old?.connected ?? false, target });\n}\n\nfunction element(engine: Engine, phase: \"mounting\" | \"back\" | \"connected\" | \"disconnected\" | \"reset\"): void {\n const rt = runtimes.get(engine);\n // an engine made before the add-on was installed has no runtime (and declares nothing temporal);\n // a server render (@wcstack/server) keeps streams at their initial value and watches off\n if (rt === undefined || phase === \"mounting\" || document.documentElement?.hasAttribute(\"data-wcs-server\")) return;\n // (kept on a runtime a refused re-set left too: the next re-set takes it over. \"back\" comes after\n // \"disconnected\", before $connectedCallback runs again: not connected yet)\n if (phase !== \"reset\") rt.connected = phase === \"connected\";\n // a refused state's runtime never runs, nor stops (writes `$streamStatus`), on the state that stayed\n if (rt.target !== engine.target) return;\n if (phase === \"disconnected\") {\n rt.watch.deactivate();\n rt.stream.stopAll();\n return;\n }\n if (!rt.connected) return;\n rt.watch.activate();\n rt.stream.startAll();\n}\n\nconst NAMESPACES = [\"$streamStatus\", \"$streamError\"];\n\nexport const temporal: Feature = {\n name: \"temporal\",\n hooks,\n install(): void {\n hooks.declare = chain(hooks.declare, declare);\n hooks.element = chain(hooks.element, element);\n hooks.written = chain(hooks.written, (engine, p, row, old, value, direct, element) => live(engine)?.watch.written(p, row, old, value, direct, element));\n hooks.getterReached = chain(hooks.getterReached, (engine, g, row) => {\n const rt = live(engine);\n if (rt === undefined) return;\n rt.watch.getterReached(g, row);\n rt.stream.getterReached(g);\n });\n hooks.listSynced = chain(hooks.listSynced, (engine, list, old) => live(engine)?.watch.listSynced(list, old));\n hooks.drained = chain(hooks.drained, (engine) => {\n const rt = live(engine);\n if (rt === undefined) return;\n rt.watch.drained();\n rt.stream.drained();\n });\n // `this.$streamStatus` (the object, untracked) and `this[\"$streamStatus.x\"]` (tracked)\n hooks.dollar = first(known, hooks.dollar, (engine, key) => {\n const ns = key.split(\".\", 1)[0];\n if (!NAMESPACES.includes(ns)) return undefined;\n return ns === key ? engine.target[key] : engine.read(engine.pattern(key), null);\n });\n hooks.beforeWrite = first(handled, hooks.beforeWrite, (_engine, p) => {\n if (!internalWrite && p.path.charCodeAt(0) === 36 && NAMESPACES.includes(p.path.split(\".\", 1)[0])) {\n raiseError(`\"${p.path}\" is read-only (the stream runtime owns it).`);\n }\n return false;\n });\n },\n};\nexport default temporal;\n","/**\n * The list-keys add-on (@wcstack/state/features/list-keys): `$listKeys` — identity for refetched\n * rows (README \"$listKeys\"). Assigning an array to a declared list path keeps the row objects whose\n * key matches and writes into them only the fields that changed (a dropped field is cleared with\n * null); the stored array is rebuilt from the kept objects, so rows, their DOM and focus survive a\n * refresh, and a refresh that changes nothing does nothing.\n */\nimport type { Engine } from \"../engine\";\nimport type { Pattern } from \"../pattern\";\nimport type { StateRow } from \"../list\";\nimport { chain, first, handled, hooks, type Feature } from \"../hooks\";\nimport { raiseError } from \"../parser/raiseError\";\n\ntype KeyOf = (row: Record<string, unknown>) => unknown;\n\n/** By state object: a re-set refused after the declaration (recursion) leaves the old state's keys in force. */\nconst keysByTarget = new WeakMap<object, Map<Pattern, KeyOf>>();\n/** The merged array is being written: the write goes through as a plain one. */\nlet merging = false;\nconst PROTO = \"__proto__\";\n/** A field name that is one path segment (no `.` / `*`, not an index, not a `$` name, not `prototype`: a path refuses it). */\nconst SEGMENT = /^(?!prototype$)[^\\d.*$][^.*]*$/;\n\nfunction declare(engine: Engine, target: Record<string, any>): void {\n const decl = target.$listKeys;\n const keys = new Map<Pattern, KeyOf>();\n if (decl !== undefined) {\n if (decl === null || typeof decl !== \"object\") raiseError(\"$listKeys must be an object mapping list paths to a key field or function.\");\n for (const path of Object.keys(decl)) {\n const key = decl[path];\n if (typeof key === \"string\") keys.set(engine.pattern(path), (row) => row[key]);\n else if (typeof key === \"function\") keys.set(engine.pattern(path), key as KeyOf);\n else raiseError(`$listKeys \"${path}\" must be a field name or a function.`);\n }\n }\n keysByTarget.set(target, keys);\n}\n\nfunction isPlain(v: unknown): v is Record<string, unknown> {\n if (v === null || typeof v !== \"object\") return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\n\nfunction keyed(path: string, rows: readonly unknown[], keyOf: KeyOf): Map<unknown, Record<string, unknown>> {\n const out = new Map<unknown, Record<string, unknown>>();\n for (const r of rows) {\n if (!isPlain(r)) raiseError(`$listKeys \"${path}\": rows must be plain objects.`);\n const k = keyOf(r);\n if (k === undefined || k === null) raiseError(`$listKeys \"${path}\": a row has no key.`);\n if (out.has(k)) raiseError(`$listKeys \"${path}\": duplicate key ${JSON.stringify(k)}.`);\n out.set(k, r);\n }\n return out;\n}\n\nfunction beforeWrite(engine: Engine, p: Pattern, row: StateRow | null, value: unknown): boolean {\n if (merging || !Array.isArray(value)) return false;\n const keyOf = keysByTarget.get(engine.target)?.get(p);\n if (keyOf === undefined) return false;\n const old = engine.readData(p, row);\n if (!Array.isArray(old) || old === value) return false;\n const before = keyed(p.path, old, keyOf);\n keyed(p.path, value, keyOf);\n // the stored array: the kept objects where keys match, the new ones elsewhere\n const merged: unknown[] = [];\n const updates: [number, Record<string, unknown>, Record<string, unknown>][] = [];\n let same = old.length === value.length;\n for (let i = 0; i < value.length; i++) {\n const next = value[i] as Record<string, unknown>;\n const kept = before.get(keyOf(next));\n merged.push(kept ?? next);\n if (kept !== undefined) updates.push([i, kept, next]);\n if (merged[i] !== old[i]) same = false;\n }\n const changes: [number, string, unknown][] = [];\n for (const [i, kept, next] of updates) {\n for (const f of Object.keys(next)) if (!Object.is(kept[f], next[f])) changes.push([i, f, next[f]]);\n for (const f of Object.keys(kept)) if (!(f in next) && kept[f] !== null) changes.push([i, f, null]);\n }\n if (same && changes.length === 0) return true; // a no-op refresh does nothing\n if (!same) {\n merging = true;\n try {\n engine.write(p, row, merged);\n } finally {\n merging = false;\n }\n }\n if (changes.length > 0) {\n const list = engine.childList(p.depth === 0 ? null : row, p);\n for (const [i, f, v] of changes) {\n // a field name is the server's. `__proto__` (an own key from JSON) is not a field: copied, it\n // would replace the row's prototype. A name that is not one path segment (`@odata.etag`,\n // `2fa`) or is a row getter's goes into the row as it is, the row told as a whole.\n if (f === PROTO) continue;\n const r = list.rows[i];\n const fp = SEGMENT.test(f) ? engine.pattern(`${p.path}.*.${f}`) : null;\n if (fp?.getter === null) engine.write(fp, r, v);\n else {\n (r.item as Record<string, unknown>)[f] = v;\n engine.write(engine.pattern(`${p.path}.*`), r, r.item, true);\n }\n }\n }\n return true;\n}\n\nexport const listKeys: Feature = {\n name: \"list-keys\",\n hooks,\n install(): void {\n hooks.declare = chain(hooks.declare, declare);\n hooks.beforeWrite = first(handled, hooks.beforeWrite, beforeWrite);\n },\n};\nexport default listKeys;\n","/**\n * Volumes — `<wcs-state mount=\"p\">` (README \"Mounting Additional State\"). A volume is not a\n * root: its state is grafted onto the root tree at `p` by ordinary writes, its getters and\n * setters become root accessors at `p.<key>`, its methods live at `p.<method>`, and inside all\n * of them — and in its `$connectedCallback` / `$disconnectedCallback` — `this` is chrooted at\n * `p` (`this.x` is the tree's `p.x`). Load order does not matter: a volume that loads before its\n * root grafts when the root engine is created, before the page is bound; if the root fails to\n * initialize, its volumes report it and settle. A root hydrated from a server snapshot (SSR)\n * already holds the volume's data at `p`: the volume adopts it (3.x D14). A volume in a component\n * wired to its host (`data-wcs=\"state…\"`) is refused, whenever it loads (3.x left it pending).\n *\n * Not carried over from @wcstack/state 3.3 (approved simplifications, each an error rather than\n * a silent no-op): injections on the volume element (`data-wcs=\"state.k: …\"`), and a volume's\n * own `$watch` / `$listKeys` / `$renderedCallback` — declare them on the root.\n */\nimport type { Engine } from \"../engine\";\nimport type { Pattern } from \"../pattern\";\nimport type { Claimed } from \"../hooks\";\nimport type { WcsState } from \"../element\";\nimport { config } from \"../config\";\nimport { engines } from \"../dom/mount\";\nimport { raiseError, report } from \"../parser/raiseError\";\n\nexport interface Volume {\n readonly el: HTMLElement;\n readonly root: Node;\n readonly path: string;\n state: Record<string, any> | null;\n engine: Engine | null;\n chroot: object | null;\n /** Settles the element's connectedCallbackPromise. */\n settle: (() => void) | null;\n}\n\n/** Mount paths held on each root (reserved when a volume connects, kept once grafted). */\nconst slots = new WeakMap<Node, Map<string, Volume>>();\n/**\n * Loaded volumes waiting for their root's engine; an element: the root's `<wcs-state>` that failed\n * to initialize (what loads later fails with it while it is in the page: failed()).\n */\nconst waiting = new WeakMap<Node, Volume[] | Element>();\nconst ORPHAN = \"will not graft: the root state failed to initialize.\";\n/** The engines of components wired to their host: they read the host's tree, a volume has none to graft onto. */\nexport const wired = new WeakSet<Engine>();\n/** The volumes grafted onto each engine. */\nexport const grafted = new WeakMap<Engine, Volume[]>();\n\nconst REJECTED = [\"$stream\", \"$streams\", \"$scan\", \"$recursion\", \"$watch\", \"$listKeys\", \"$renderedCallback\", \"$updatedCallback\", \"$behavior\", \"$features\"];\nconst NOT_RUN = [\"$commandTokens\", \"$eventTokens\", \"$on\", \"$errorCallback\"];\nconst PREFIX = (path: string) => `[@wcstack/state] <${config.tagNames.state} mount=\"${path}\">`;\n\n/** `$` APIs that take a state path: inside a volume the path is relative to the mount. */\nconst PATH_APIS = new Set([\"$getAll\", \"$setAll\", \"$resolve\", \"$postUpdate\", \"$dependOn\", \"$eq\", \"$eqIndex\"]);\n\nfunction chrootOf(engine: Engine, prefix: string): object {\n const at = (key: string) => `${prefix}.${key}`;\n return new Proxy({}, {\n get(_t, key) {\n if (typeof key === \"symbol\") return undefined;\n if (key.charCodeAt(0) !== 36) return engine.proxy[at(key)];\n const v = engine.proxy[key];\n if (key === \"$eqPath\") return (path: string, keyPath: string) => v(at(path), at(keyPath));\n return PATH_APIS.has(key) && typeof v === \"function\" ? (path: string, ...rest: unknown[]) => v(at(path), ...rest) : v;\n },\n set(_t, key, value) {\n if (typeof key === \"symbol\") return false;\n engine.proxy[at(key as string)] = value;\n return true;\n },\n });\n}\n\nfunction validPath(path: string): boolean {\n return path !== \"\" && path.split(\".\").every((s) => s !== \"\" && !/[*$#@\\s]/.test(s));\n}\n\n/**\n * An engine whose `<wcs-state>` is in the page: nothing grafts onto one that is out (a root out of the\n * page lets go of its root node; a component whose `<wcs-state>` alone left stays registered).\n */\nconst live = (e: Engine | undefined): Engine | undefined => ((e?.element as Node | undefined)?.isConnected ? e : undefined);\n\n/** The root `<wcs-state>` on `root` failed to initialize, and is still in the page. */\nfunction failed(root: Node): boolean {\n const w = waiting.get(root);\n return w !== undefined && !Array.isArray(w) && w.isConnected;\n}\n\n/** The engine created on `root`: graft the volumes that were waiting for it (before its page is bound). */\nexport function rootEngineCreated(engine: Engine, root: Node): void {\n const list = waiting.get(root);\n waiting.delete(root);\n if (Array.isArray(list)) for (const v of list) graft(v, engine);\n}\n\nfunction release(v: Volume): void {\n const held = slots.get(v.root);\n if (held?.get(v.path) === v) held.delete(v.path);\n}\n\n/**\n * A root engine's `<wcs-state>` left the page (\"disconnected\"), or is back (\"back\"; a component's:\n * \"connected\"). Out, the mount paths its volumes hold let go of it (they are kept on the root node,\n * which outlives the content it bound). Back, and still its root's engine (the core holds the root\n * again unless another `<wcs-state>` bound it meanwhile), the volumes that connected meanwhile graft,\n * and its own hold their paths again — unless another volume took one meanwhile.\n */\nexport function rootMoved(engine: Engine, phase: string): void {\n const list = grafted.get(engine) ?? [];\n if (phase === \"disconnected\") for (const v of list) release(v);\n else if (phase !== \"reset\" && live(engines.get(engine.root!)) === engine) {\n rootEngineCreated(engine, engine.root!);\n for (const v of list) if (!slots.get(v.root)!.has(v.path)) slots.get(v.root)!.set(v.path, v);\n }\n}\n\n/** Reports a volume that will not graft, releases its slot and settles its promise. */\nfunction fail(v: Volume, message: string): void {\n report(`${PREFIX(v.path)} ${message}`);\n release(v);\n v.settle?.();\n v.settle = null;\n}\n\nfunction callLifecycle(v: Volume, name: \"$connectedCallback\" | \"$disconnectedCallback\"): void {\n const fn = v.state?.[name];\n if (typeof fn !== \"function\") return;\n try {\n const r = fn.call(v.chroot);\n if (r !== null && typeof r === \"object\" && typeof r.then === \"function\") r.then(undefined, report);\n } catch (e) {\n report(e);\n }\n}\n\nfunction graft(v: Volume, engine: Engine): void {\n if (wired.has(engine)) return fail(v, \"will not graft: its component is wired to its host.\");\n const state = v.state!;\n const target = engine.target;\n const segs = v.path.split(\".\");\n let at: any = target;\n for (const s of segs) at = at == null ? undefined : at[s];\n // a root hydrated from a server snapshot (ssr/ssr.ts) has the volume's data there already: adopted\n if (at !== undefined && (engine as any).hydrated !== true) return fail(v, `will not graft: the root state already has \"${v.path}\".`);\n const chroot = chrootOf(engine, v.path);\n v.chroot = chroot;\n // the data; accessors and methods (bound to the chroot) apart, as root accessors at `p.<key>`,\n // so that whatever replaces the data (the snapshot, a write of the mount path) keeps them\n const data: Record<string, unknown> = {};\n const defs: PropertyDescriptorMap = {};\n const seen = new Set<string>();\n for (let o: object | null = state; o !== null && o !== Object.prototype; o = Object.getPrototypeOf(o)) {\n for (const key of Object.getOwnPropertyNames(o)) {\n if (seen.has(key) || key === \"constructor\") continue;\n seen.add(key);\n const { get, set, value } = Object.getOwnPropertyDescriptor(o, key)!;\n if (get !== undefined || set !== undefined) {\n defs[`${v.path}.${key}`] = {\n get: get && function () { return get.call(chroot); },\n set: set && function (next: unknown) { set.call(chroot, next); },\n };\n } else if (key[0] === \"$\") continue;\n else if (typeof value === \"function\") {\n const fn = value.bind(chroot);\n defs[`${v.path}.${key}`] = { get: () => fn };\n } else data[key] = value;\n }\n }\n if (at === undefined) {\n // intermediate objects of a deep mount path, then the volume's own object\n for (let i = 1; i < segs.length; i++) {\n const p = engine.pattern(segs.slice(0, i).join(\".\"));\n if (engine.readData(p, null) == null) engine.write(p, null, {});\n }\n engine.write(engine.pattern(v.path), null, data);\n }\n // registered as the root's own are (a row-level getter gets its cache slot; the paths under\n // them read through them)\n (engine as any).registerAccessors(Object.defineProperties({}, defs));\n for (const path in defs) engine.changed(engine.pattern(path), null);\n v.engine = engine;\n let list = grafted.get(engine);\n if (list === undefined) grafted.set(engine, (list = []));\n list.push(v);\n if (v.el.isConnected) callLifecycle(v, \"$connectedCallback\");\n v.settle?.();\n v.settle = null;\n}\n\n/**\n * A root `<wcs-state>` (the one no claim took; asked by the last, claimComponent): if it fails to\n * initialize, the volumes waiting on `root` settle instead of waiting forever, and so do the ones\n * that load later — and the components waiting there for their wiring (onRootFailed).\n */\nexport function watchRoot(el: HTMLElement, root: Node): null {\n (el as WcsState).connectedCallbackPromise.catch(() => {\n // a root that bound the page (only its $connectedCallback failed), or a stray second one (#47)\n // beside the root that binds it: nothing failed for what waits there\n const live = engines.get(root)?.element as Element | undefined;\n if ((el as WcsState).bound || (live !== undefined && live !== el && live.isConnected)) return;\n orphan(root, el);\n for (const f of giveUp.get(root) ?? []) f();\n });\n return null;\n}\n\n/**\n * The state of `root` failed to initialize (`el`: the page's root, or a component's in its shadow\n * root): the volumes waiting there report it and settle, and so do those that load later while\n * `el` is in the page.\n */\nexport function orphan(root: Node, el: Element): void {\n const list = waiting.get(root);\n if (Array.isArray(list)) for (const v of list) fail(v, ORPHAN);\n waiting.set(root, el);\n}\n\n/** What else waits on a root node's `<wcs-state>` (a component, for the page's wiring). */\nconst giveUp = new WeakMap<Node, Set<() => void>>();\n\n/**\n * Calls `fn` when (or if) the root `<wcs-state>` on `root` fails to initialize; the function\n * returned stops waiting (what `fn` holds is not kept for as long as the page lives).\n */\nexport function onRootFailed(root: Node, fn: () => void): () => boolean {\n if (failed(root)) fn();\n const s = giveUp.get(root) ?? new Set();\n giveUp.set(root, s.add(fn));\n return () => s.delete(fn);\n}\n\n/** `<wcs-state mount=\"p\">`: claimed instead of becoming a root. */\nexport function claimVolume(el: HTMLElement, root: Node): Claimed | null {\n const path = el.getAttribute(\"mount\");\n if (path === null) return null;\n const v: Volume = { el, root, path, state: null, engine: null, chroot: null, settle: null };\n let problem: string | null = null;\n if (!validPath(path)) problem = `has an invalid mount path: it must be a static path (no \"*\", \"$\", \"#\", \"@\").`;\n else if (el.hasAttribute(config.bindAttributeName)) problem = `injections (data-wcs=\"state.<key>: …\") are not supported — read the root path in a root getter.`;\n else {\n let held = slots.get(root);\n if (held === undefined) slots.set(root, (held = new Map()));\n const other = held.get(path);\n // one grafted onto a root that left the page holds it no more, nor does one waiting for its root\n // out of the page (the page's content replaced): that one yields, and never grafts. (One out of\n // the page that no other volume asks for still grafts when its root comes.)\n if (other !== undefined && other !== v && (other.engine === null ? other.el.isConnected : live(other.engine))) {\n problem = `will not graft: another volume already holds \"${path}\".`;\n } else {\n if (other?.engine === null) {\n const list = waiting.get(root);\n if (Array.isArray(list)) waiting.set(root, list.filter((x) => x !== other));\n other.settle?.();\n other.settle = null;\n }\n held.set(path, v);\n }\n }\n return {\n // a volume that cannot load resolves its connectedCallbackPromise (3.x; it reports, as below)\n lenient: true,\n start(state): Promise<void> | void {\n if (problem !== null) return fail(v, problem);\n // (it yielded its slot while it loaded: see above)\n if (slots.get(root)!.get(path) !== v) return;\n for (const key of REJECTED) if (state[key] !== undefined) return fail(v, `${key} is not run in a volume — declare it on the root state.`);\n for (const key of NOT_RUN) if (state[key] !== undefined) console.warn(`${PREFIX(path)} ${key} is not run in a volume (it belongs to the root).`);\n v.state = state;\n return new Promise<void>((resolve) => {\n v.settle = resolve;\n const engine = live(engines.get(root));\n const list = waiting.get(root);\n if (engine !== undefined) graft(v, engine);\n else if (failed(root)) fail(v, ORPHAN);\n else waiting.set(root, [...(Array.isArray(list) ? list : []), v]);\n });\n },\n connected() {\n if (v.engine !== null) callLifecycle(v, \"$connectedCallback\");\n },\n disconnected() {\n // a grafted volume keeps its data and its slot (there is no unmount)\n if (v.engine !== null) callLifecycle(v, \"$disconnectedCallback\");\n },\n reset() {\n raiseError(`re-setting a volume is not supported: its data was copied into the root tree at \"${path}\" — write the paths under it on the root instead.`);\n },\n };\n}\n\n/** A root write that would replace an object a volume is grafted under. */\nexport function guardAncestorWrite(engine: Engine, p: Pattern): void {\n const list = grafted.get(engine);\n if (list === undefined || p.depth !== 0) return;\n for (const { path } of list) {\n if (path.startsWith(`${p.path}.`)) raiseError(`writing \"${p.path}\" would replace the volume grafted at \"${path}\"; write the paths under it instead.`);\n }\n}\n","/**\n * Declarative Custom Components (README \"DCC\"). The `<wcs-state>` inside the shadow root of a\n * `[data-wc-definition]` host is not a root: it defines the host's tag. Each instance gets a\n * copy of the definition's (untouched) shadow content, whose own `<wcs-state>` is an ordinary\n * root with a fresh state. The class's prototype reads and writes that state (writes before it\n * initializes wait for it; methods return Promises); `$bindables` / `$commands` become its\n * `static wcBindable`, and a write to a bindable (or under it, or a `$postUpdate`) dispatches\n * `<tag>:<prop>-changed` from the instance — a notification: `detail` carries the written value\n * only for a write of the member itself, and the declared getter reads the member off the element.\n *\n * The shadow is built on first use — an accessor or the connect, whichever comes first — not in\n * the constructor: a `for` row binds its elements before they are inserted, a parser-made\n * instance has no attributes in its constructor, and the definition host itself (upgraded by\n * define()) already has its shadow.\n */\nimport type { Engine } from \"../engine\";\nimport type { Pattern } from \"../pattern\";\nimport type { Claimed } from \"../hooks\";\nimport { config } from \"../config\";\nimport { raiseError } from \"../parser/raiseError\";\n\ninterface Definition {\n readonly tag: string;\n readonly bindables: readonly string[];\n}\n\n/** DCC instances by host element, and the definition of each instance's inner engine. */\nconst instances = new WeakMap<Element, Definition>();\nconst byEngine = new WeakMap<Engine, { host: Element; def: Definition }>();\n\nfunction names(state: Record<string, any>, key: string): string[] {\n const v = state[key];\n if (v === undefined) return [];\n if (!Array.isArray(v)) raiseError(`${key} must be an array of state member names.`);\n const seen = new Set<string>();\n for (const n of v) {\n if (typeof n !== \"string\" || n === \"\") raiseError(`${key} entries must be non-empty strings.`);\n if (n[0] === \"$\") raiseError(`${key} entry \"${n}\": internal ($) members are never exposed.`);\n if (seen.has(n)) raiseError(`${key} entry \"${n}\" is duplicated.`);\n seen.add(n);\n }\n return v;\n}\n\n/** Every member of the state (own and inherited), by descriptor. */\nfunction members(state: Record<string, any>): Map<string, PropertyDescriptor> {\n const out = new Map<string, PropertyDescriptor>();\n for (let o: object | null = state; o !== null && o !== Object.prototype; o = Object.getPrototypeOf(o)) {\n for (const key of Object.getOwnPropertyNames(o)) {\n if (key === \"constructor\" || key[0] === \"$\" || out.has(key)) continue;\n out.set(key, Object.getOwnPropertyDescriptor(o, key)!);\n }\n }\n const streams = state.$stream;\n if (streams !== null && typeof streams === \"object\") for (const n of Object.keys(streams)) if (!out.has(n)) out.set(n, { value: undefined });\n return out;\n}\n\nfunction define(tag: string, content: DocumentFragment, mode: ShadowRootMode, state: Record<string, any>): void {\n if (!tag.includes(\"-\")) raiseError(`DCC: <${tag} data-wc-definition> is not a valid custom element name.`);\n if (customElements.get(tag) !== undefined) raiseError(`DCC: <${tag}> is already defined.`);\n const all = members(state);\n const bindables = names(state, \"$bindables\");\n const commands = names(state, \"$commands\");\n for (const n of bindables) {\n const d = all.get(n);\n if (d === undefined) raiseError(`$bindables entry \"${n}\" does not exist on the state.`);\n if (typeof d.value === \"function\") raiseError(`$bindables entry \"${n}\" is a method: list it in $commands.`);\n }\n for (const n of commands) {\n const d = all.get(n);\n if (d === undefined) raiseError(`$commands entry \"${n}\" does not exist on the state.`);\n if (typeof d.value !== \"function\") raiseError(`$commands entry \"${n}\" is not a method: list it in $bindables.`);\n }\n const def: Definition = { tag, bindables };\n /** Each instance's inner `<wcs-state>` (null: a definition host, or content without one). */\n const states = new WeakMap<Element, any>();\n const pending = new WeakMap<Element, [string, unknown][]>();\n /** Builds the instance's shadow once; its inner `<wcs-state>`. */\n const ensure = (el: Element): any => {\n if (states.has(el)) return states.get(el);\n if (el.hasAttribute(\"data-wc-definition\")) return null;\n const shadow = el.attachShadow({ mode });\n shadow.appendChild(content.cloneNode(true));\n const state = shadow.querySelector(config.tagNames.state);\n states.set(el, state);\n instances.set(el, def);\n if (state === null && bindables.length > 0) {\n console.warn(`[@wcstack/state] DCC: <${tag}> declares $bindables but its content has no <${config.tagNames.state}>: no change events.`);\n }\n return state;\n };\n /** The instance's inner engine once its state initialized, else null. */\n const inner = (el: Element): any => ensure(el)?.engine ?? null;\n /** Resolves when the instance's state initialized, before its `$connectedCallback` (and lands the writes queued before). */\n const ready = (el: Element): Promise<void> => Promise.resolve(ensure(el)?.initializePromise).then(() => {\n const queued = pending.get(el);\n pending.delete(el);\n const engine = inner(el);\n if (queued !== undefined && engine !== null) for (const [k, v] of queued) engine.proxy[k] = v;\n });\n\n class Dcc extends HTMLElement {\n static wcBindable = bindables.length === 0 && commands.length === 0 ? null : {\n protocol: \"wc-bindable\", version: 1,\n properties: bindables.map((name) => ({ name, event: `${tag}:${name}-changed`, getter: (e: Event) => (e.target as any)[name] })),\n inputs: bindables.map((name) => ({ name })),\n ...(commands.length === 0 ? {} : { commands: commands.map((name) => ({ name, async: true })) }),\n };\n\n connectedCallback(): void {\n if (ensure(this) !== null) void ready(this);\n }\n\n /** The inner `<wcs-state>` (as in 3.3; builds the shadow if it is not built yet). */\n get stateElement(): HTMLElement | null {\n return ensure(this);\n }\n }\n for (const [name, d] of all) {\n if (typeof d.value === \"function\") {\n Object.defineProperty(Dcc.prototype, name, {\n configurable: true,\n value(this: Element, ...args: unknown[]) {\n return ready(this).then(() => {\n const engine = inner(this);\n return engine === null ? undefined : engine.proxy[name].apply(engine.proxy, args);\n });\n },\n });\n } else {\n Object.defineProperty(Dcc.prototype, name, {\n configurable: true,\n get(this: Element) { return inner(this)?.proxy[name]; },\n set(this: Element, value: unknown) {\n const engine = inner(this);\n if (engine !== null) engine.proxy[name] = value;\n else {\n let q = pending.get(this);\n if (q === undefined) pending.set(this, (q = []));\n q.push([name, value]);\n }\n },\n });\n }\n }\n customElements.define(tag, Dcc);\n}\n\n/** The `<wcs-state>` of a definition host: claimed to define the tag. */\nexport function claimDcc(el: HTMLElement, root: Node): Claimed | null {\n const host = (root as ShadowRoot).host;\n if (host === undefined || !host.hasAttribute(\"data-wc-definition\")) return null;\n // the definition's content, before anything touches it: every instance starts from this\n const content = document.createDocumentFragment();\n for (const n of [...root.childNodes]) content.appendChild(n.cloneNode(true));\n const mode = (root as ShadowRoot).mode;\n return {\n start(state) {\n if (el.hasAttribute(\"bind-component\")) raiseError(\"DCC: a <wcs-state bind-component> cannot define a component (use one mechanism).\");\n define(host.localName, content, mode, state);\n },\n connected() {},\n disconnected() {},\n reset() {\n raiseError(\"re-setting a DCC definition is not supported: each instance loads its own state.\");\n },\n };\n}\n\n/** A root engine was created: an instance's inner state gets its host's change events. */\nexport function dccEngineCreated(engine: Engine, root: Node): void {\n const host = (root as ShadowRoot).host;\n const def = host === undefined ? undefined : instances.get(host);\n if (def !== undefined) byEngine.set(engine, { host, def });\n}\n\n/**\n * A write at a bindable, under it, or its `$postUpdate`: `<tag>:<prop>-changed` from the\n * instance, with the written value as `detail` only for a data write of the member itself.\n */\nexport function dccWritten(engine: Engine, p: Pattern, value: unknown, direct: boolean): void {\n const info = byEngine.get(engine);\n if (info === undefined) return;\n const name = p.path.split(\".\", 1)[0];\n if (!info.def.bindables.includes(name)) return;\n const exact = direct && p.path === name;\n info.host.dispatchEvent(new CustomEvent(`${info.def.tag}:${name}-changed`, { detail: exact ? value : undefined, bubbles: true }));\n}\n","/**\n * Component mounts — `<wcs-state bind-component=\"prop\">` directly inside a custom element\n * (README \"Web Component Binding\"). Each component runs an engine of its own over its state\n * object (the host element's `prop`): its bindings, rows, `$1`, event indexes, getters and\n * private keys are the component's. The host wires it with ordinary property bindings on the\n * element (`state: user`, `state.x: path`, `state: .` in a row); those are taken over as\n * mount entries, and the component reads and writes the mounted keys through the host's\n * engine. Changes cross both ways through the `written` / `getterReached` hooks: the host's\n * reach the components mounted on them, and a component's writes under a mounted key reach\n * the host (and, from there, the other components mounted on the same data).\n *\n * Own keys stay private (rule R1): a key the component declares itself is its own, except a\n * one-segment partial entry, which wins over a data default. Unwired, a Shadow DOM component\n * owns an independent tree; a Light DOM one cannot (it shares the page) and fails loudly.\n *\n * `#ro` on an entry (`state#ro: user`) is honoured as in 3.3: a component's code writing through it\n * throws `[wcs/mount-readonly]`, an element's write-back inside the component is dropped.\n *\n * A whole mount's accessors are exported at the mount point (README \"Exported getters\"): the host\n * reads `user.display` (row by row for `state: .`) from the component mounted there, unless the\n * tree has the key.\n * A mounted component runs no temporal declaration and no `$renderedCallback`, and refuses `$recursion`.\n */\nimport { Engine, rowAt } from \"../engine\";\nimport { WILDCARD, type Pattern } from \"../pattern\";\nimport type { StateRow } from \"../list\";\nimport type { Binding } from \"../dom/view\";\nimport { hooks, loadFeatures, type Claimed } from \"../hooks\";\nimport { config } from \"../config\";\nimport { DirtyStrategy } from \"../strategy/dirty\";\nimport { engines, mount, mountSubtree } from \"../dom/mount\";\nimport { bind, drainBinds } from \"../dom/binder\";\nimport { registryOf } from \"../dom/wc\";\nimport { raiseError, report } from \"../parser/raiseError\";\nimport type { WcsState } from \"../element\";\nimport { onRootFailed, orphan, rootEngineCreated, watchRoot, wired } from \"./volume\";\n\ninterface Entry {\n /** The component-side path (\"\" = the whole state). */\n readonly inner: string;\n /** The host pattern and row (at the pattern's depth) it is mounted on. */\n readonly outer: Pattern;\n readonly row: StateRow | null;\n /** Mounted `#ro`: the component reads it and does not write it. */\n readonly ro: boolean;\n}\n\n/** What a host element keeps across the `<wcs-state>` elements its renders create. */\ninterface Host {\n readonly el: Element;\n readonly prop: string;\n /** The author's state object: the component's private data lives here. */\n readonly state: Record<string, any>;\n /** The host's engine (null: an unwired, independent component). */\n readonly engine: Engine | null;\n readonly entries: Entry[];\n current: Mount | null;\n}\n\ninterface Synth {\n readonly e: Entry;\n readonly p: Pattern;\n readonly row: StateRow | null;\n}\n\ninterface Mount {\n /** Its `<wcs-state>`: a new one that takes the scope over replaces it (resume). */\n el: HTMLElement;\n /** The nodes of the scope root once it was bound: still there, a new `<wcs-state>` takes the scope over. */\n nodes: ChildNode[];\n readonly component: Engine;\n readonly host: Host;\n readonly slots: { m: Mount; e: Entry }[];\n /** Component patterns that read and write the host. */\n readonly synth: Map<Pattern, Synth>;\n registered: boolean;\n /** A mounted key its setter just wrote through the host (its `written` is not forwarded again). */\n skip: Pattern | null;\n /** The entry a change of the component is crossing to the host through: its other entries still take it. */\n from: Entry | null;\n /** Exported accessors (a whole mount's): host pattern (`user.display`) → the component's accessor pattern. */\n exports: Map<Pattern, Pattern> | null;\n /**\n * It failed before its bindings were built (a markup error): what it bound before the error follows\n * the host while it is connected, as a root's does (#384), and no lifecycle hook runs — its\n * `$connectedCallback` never did.\n */\n broken?: boolean;\n}\n\ntype Slot = Mount[\"slots\"][number];\n\n/** Plain property bindings hosts made on custom elements: the candidates for wiring. */\nconst hostBindings = new WeakMap<Element, Binding[]>();\n/** Those of them written with `#ro`. */\nconst readonlyWiring = new WeakSet<Binding>();\n/** An element property's value before a host's first write to it (a mount takes the component's). */\nconst before = new WeakMap<Element, Map<string, unknown>>();\n/** Components waiting for their host to bind the wiring written in its markup. */\nconst waiting = new WeakMap<Element, () => void>();\n/**\n * SSR: a row is a clone of its plan, so the server's output carries no `data-wcs` on a row's\n * elements. A host binding made while rendering on the server writes the heads it binds here\n * instead, so a component whose class is defined before the client adopts the row still waits\n * for its wiring (as it does for `data-wcs`); the client's host binding removes it.\n */\nconst WIRED = \"data-wcs-wired\";\nconst onServer = (): boolean => document.documentElement?.hasAttribute(\"data-wcs-server\") === true;\nconst hosts = new WeakMap<Element, Host>();\nconst mounts = new WeakMap<Engine, Mount>();\n/** Mount entries by host engine, host pattern and host row. */\nconst index = new WeakMap<Engine, Map<Pattern, Map<StateRow | null, Set<Slot>>>>();\nlet registered = 0;\n/** Engines a change is crossing from: it does not come back to them. */\nconst active = new Set<Engine>();\n\nconst UNWIRED = {};\n/** Declarations a mounted component does not run (`$listKeys` runs: it keys the component's own lists). */\nconst INERT = [\"$watch\", \"$stream\", \"$renderedCallback\"];\n\nconst headOf = (path: string): string => path.split(\".\", 1)[0];\n\n/** `a.*.b.*` with [2, 5] → `a.2.b.5`. */\nfunction fill(path: string, idx: number[]): string {\n let i = 0;\n return path.split(\".\").map((s) => (s === WILDCARD ? String(idx[i++]) : s)).join(\".\");\n}\n\n/** The core's hook: a plain property binding on a custom element (before it applies). */\nexport function hostBinding(b: Binding, ro: boolean): boolean {\n const el = b.node as Element;\n const head = headOf(b.name);\n if (!onServer()) el.removeAttribute(WIRED);\n else if (!wiredInMarkup(el, head)) {\n const heads = el.getAttribute(WIRED)?.split(\" \") ?? [];\n if (!heads.includes(head)) el.setAttribute(WIRED, [...heads, head].join(\" \"));\n }\n // the component took its wiring when it loaded: a mount is not re-wired\n if (hosts.get(el)?.prop === head) {\n raiseError(`<${el.localName}>.${head} has loaded its state: the wiring \"${b.name}\" added afterwards cannot reach it — bind the host's wiring before the component loads.`);\n }\n let list = hostBindings.get(el);\n if (list === undefined) hostBindings.set(el, (list = []));\n list.push(b);\n if (ro) readonlyWiring.add(b);\n let values = before.get(el);\n if (values === undefined) before.set(el, (values = new Map()));\n if (!values.has(head)) values.set(head, (el as any)[head]);\n waiting.get(el)?.();\n return false;\n}\n\n/** The core's hook: a Light DOM component's content is bound by its own engine. */\nexport function componentScope(el: Element): boolean {\n return el.localName.includes(\"-\") && el.querySelector(`:scope > ${config.tagNames.state}[bind-component]`) !== null;\n}\n\nfunction wiredInMarkup(host: Element, prop: string): boolean {\n const text = host.getAttribute(config.bindAttributeName);\n return text !== null && new RegExp(`(^|;)\\\\s*${prop.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}\\\\s*[.#:]`).test(text);\n}\n\n/**\n * A host whose wiring is in its markup, and which the page did not bind: it was out of the page when\n * the page's state loaded, or was inserted since — by code, not by a `for:` / `if:` (which binds it\n * before inserting it) or the router (which hands it over). Its `<wcs-state>` hands it over as the\n * router does (src/dom/binder.ts): it is bound now, or once its root's state is in the page (it has not\n * loaded yet, or its `<wcs-state>` is out). In a Light DOM component, that component's engine binds it,\n * when it mounts (now, if it has). A host the page did bind is left alone (an element is walked once),\n * and so is one whose root failed before binding the page (onRootFailed refuses the component).\n */\nfunction wireLate(host: Element): void {\n let scope = host.parentElement;\n while (scope !== null && !componentScope(scope)) scope = scope.parentElement;\n const E = engines.get(scope ?? host.getRootNode());\n const el = E?.element as WcsState | undefined;\n // (the binder binds to the page's engine now, or keeps the host for when it is in the page)\n if (el?.isConnected ? el.bound : scope === null) {\n if (scope === null) bind(host);\n else mountSubtree(E!, host);\n }\n}\n\n/** The server's output says the host binds `prop` on this row element (see WIRED). */\nconst wiredOnServer = (host: Element, prop: string): boolean => host.getAttribute(WIRED)?.split(\" \").includes(prop) === true;\n\n/** A frozen author object is copied into a writable one (same prototype). */\nfunction melt(o: Record<string, any>): Record<string, any> {\n const ds = Object.getOwnPropertyDescriptors(o);\n let frozen = Object.isFrozen(o);\n for (const d of Object.values(ds)) if (\"value\" in d && d.writable === false) { d.writable = true; frozen = true; }\n return frozen ? Object.create(Object.getPrototypeOf(o), ds) : o;\n}\n\nasync function load(el: HTMLElement, prop: string, host: Element, light: boolean): Promise<Record<string, any>> {\n const tag = host.localName;\n if ([\"state\", \"src\", \"json\"].some((a) => el.hasAttribute(a)) || el.querySelector('script[type=\"module\"]') !== null) {\n raiseError(`<${config.tagNames.state} bind-component> takes its state from <${tag}>.${prop}: it cannot also load one (state / src / json / an inline script).`);\n }\n await registryOf(host).whenDefined(tag);\n let h = hosts.get(host);\n if (h !== undefined) {\n if (h.prop !== prop) raiseError(`<${tag}> already has a <${config.tagNames.state} bind-component=\"${h.prop}\">.`);\n return h.state;\n }\n const wiring = () => (hostBindings.get(host) ?? []).filter((b) => headOf(b.name) === prop);\n // the host binds its wiring when it renders the element (a row before inserting it; the page\n // when its state loads; a server-rendered row when the client adopts it), or when the\n // element's class is defined — or, written in its markup on a host the page did not bind, now\n const marked = wiredInMarkup(host, prop);\n if (marked && wiring().length === 0) wireLate(host);\n if (wiring().length === 0 && (marked || wiredOnServer(host, prop))) {\n // (if the page's state fails, its wiring never comes)\n let stop!: () => boolean;\n await new Promise<void>((r, j) => {\n waiting.set(host, r);\n stop = onRootFailed(host.getRootNode(), () => j(new Error(`[@wcstack/state] <${tag}>.${prop} will not mount: the root state failed to initialize.`)));\n }).finally(() => stop());\n }\n waiting.delete(host);\n const bs = wiring();\n const values = before.get(host);\n const original = values !== undefined && values.has(prop) ? values.get(prop) : (host as any)[prop];\n if (original === null || typeof original !== \"object\") {\n raiseError(`\"bind-component\": <${tag}>.${prop} must be an object (the component's state), got ${original === null ? \"null\" : typeof original}.`);\n }\n if (bs.length === 0 && light) {\n // reported as an uncaught error, after this element settles (as 3.3 does)\n const error = new Error(`[@wcstack/state] A plain (unwired) Light DOM \"bind-component\" is not supported. Attach a shadow root to <${tag}>, or mount it from the host (${config.bindAttributeName}=\"${prop}: path\").`);\n queueMicrotask(() => { throw error; });\n return UNWIRED;\n }\n const entries: Entry[] = [];\n for (const b of bs) {\n const inner = b.name === prop ? \"\" : b.name.slice(prop.length + 1);\n if (entries.some((e) => e.inner === inner)) raiseError(`<${tag}> maps \"${b.name}\" twice.`);\n const star = inner.split(\".\").indexOf(WILDCARD);\n if (star >= 0) {\n const list = inner.split(\".\").slice(0, star).join(\".\");\n raiseError(`<${tag}> maps \"${b.name}\": the component-side path of a mount cannot contain \"*\"${list === \"\" ? \"\" : ` — map the list itself (\"${prop}.${list}: <the host's list>\")`}.`);\n }\n entries.push({ inner, outer: b.pattern, row: b.row, ro: readonlyWiring.has(b) });\n // the component reads the host from now on: the binding no longer writes the element\n b.engine.unregister(b);\n if (inner !== \"\") delete (host as any)[b.name];\n }\n const state = bs.length === 0 ? melt(original as Record<string, any>) : original as Record<string, any>;\n hosts.set(host, (h = { el: host, prop, state, engine: bs.length === 0 ? null : bs[0].engine, entries, current: null }));\n return state;\n}\n\nconst warned = new Set<string>();\nfunction warnOnce(key: string, message: string): void {\n if (warned.has(key)) return;\n warned.add(key);\n console.warn(`[@wcstack/state] ${message}`);\n}\n\n/** Whether `key` is the component's own (a data default, an accessor or a method of its state). */\nconst own = (h: Host, key: string): boolean => key in h.state;\n\n/** The component's own surface for `key`: an accessor or a method (a data default is not). */\nfunction surface(h: Host, key: string): boolean {\n const d = findDescriptor(h.state, key);\n return d !== undefined && (d.get !== undefined || d.set !== undefined || typeof d.value === \"function\");\n}\n\n/**\n * The component's patterns that read and write the host: a partial entry's path, and under a\n * whole mount every top-level key the component does not declare itself.\n */\nfunction wire(m: Mount): void {\n const C = m.component;\n const h = m.host;\n const H = h.engine!;\n const tag = h.el.localName;\n const whole = h.entries.find((e) => e.inner === \"\") ?? null;\n for (const e of h.entries) {\n if (e.inner === \"\") continue;\n const head = headOf(e.inner);\n // a one-segment entry wins over a data default; the component's own surface (an accessor,\n // a method) and an own key above a deep entry win over the entry\n if (own(h, head) && (e.inner !== head || surface(h, head))) {\n warnOnce(`${tag}.${e.inner}`, `[wcs/mount-own-key-shadow] <${tag}>: \"${h.prop}.${e.inner}\" is hidden by the component's own \"${head}\"; rename one side.`);\n }\n }\n if (whole !== null) {\n const at = H.readUntracked(whole.outer, whole.row);\n if (at !== null && typeof at === \"object\") {\n for (const key of Object.keys(h.state)) {\n if (key[0] !== \"$\" && key in at && !h.entries.some((e) => e.inner === key)) {\n warnOnce(`${tag}.${key}`, `[wcs/mount-own-key-shadow] <${tag}>: its own \"${key}\" hides \"${whole.outer.path}.${key}\" — remove the default to read the tree, or rename it to keep it private.`);\n }\n }\n }\n }\n const declared = INERT.filter((k) => h.state[k] !== undefined);\n if (declared.length > 0) {\n warnOnce(`${tag}.${h.prop}$`, `[wcs/mount-dollar-declaration] <${tag}>: ${declared.join(\", \")} ${declared.length === 1 ? \"is\" : \"are\"} not run in a mounted component — declare it on the root state.`);\n }\n const base = (C as any).onPatternCreated;\n (C as any).onPatternCreated = (p: Pattern) => {\n mountKey(m, whole, p);\n base.call(C, p);\n };\n // patterns the engine made before (the parents of the component's own accessors): mounted\n // keys among them, then what now reads through them. A snapshot: both loops walk it (a pattern\n // made during the first goes through the wrapped onPatternCreated above).\n const made = [...C.patterns.all()];\n for (const p of made) mountKey(m, whole, p);\n for (const p of made) base.call(C, p);\n // a mount in a host row goes with the row (4.0 discards a removed row's element): it renders no\n // more — what it would read of the row throws (live), its own keys stay readable and writable.\n // So does a mount inside a component that went with its row: it reads the tree through that one.\n const drain = C.drain;\n C.drain = () => {\n if (inPlace(m)) drain.call(C);\n };\n}\n\n/** Every host row a mount reads through is still there: its own, and those of the components it is in. */\nfunction inPlace(m: Mount | undefined): boolean {\n for (; m !== undefined; m = mounts.get(m.host.engine!)) {\n if (m.host.entries.some((e) => e.row !== null && !e.row.alive)) return false;\n }\n return true;\n}\n\n/**\n * `element.state` is the component's proxy, handed out as an object: a function the state declares\n * (a method, or a function-valued key it starts with) read off it always runs on it, whatever `this`\n * it is called with — detached (`const { toggle } = element.state`), as a listener\n * (`button.addEventListener(\"click\", element.state.toggle)`), by a timer — as 3.x's `bind` did\n * (#331; an explicit `call(other)` is ignored, as with `bind`). It is wrapped once per function, in a\n * proxy that keeps the function's properties, statics, `new`, `name` and identity across reads; a\n * function a key comes to hold later, the tree's or its own, is returned as it is. Only reads through\n * the proxy itself are wrapped, not through a view of it (`createStateAsync(\"readonly\")`, whose\n * methods must run on the read-only view). A root's proxy is only lent to a callback, and a volume's\n * methods are bound to its chroot already.\n */\nfunction bindMethods(C: Engine, state: object): void {\n const methods = new Map<unknown, unknown>();\n for (let o: object | null = state; o !== null && o !== Object.prototype; o = Object.getPrototypeOf(o)) {\n for (const k of Object.getOwnPropertyNames(o)) {\n const v = Object.getOwnPropertyDescriptor(o, k)!.value;\n if (typeof v === \"function\" && k !== \"constructor\") methods.set(v, null);\n }\n }\n const apply = (f: (...a: unknown[]) => unknown, _self: unknown, args: unknown[]): unknown => Reflect.apply(f, C.proxy, args);\n C.bound = (fn) => {\n let b = methods.get(fn);\n if (b === null) methods.set(fn, (b = new Proxy(fn, { apply })));\n return b;\n };\n}\n\nfunction findDescriptor(o: object, key: string): PropertyDescriptor | undefined {\n for (let x: object | null = o; x !== null && x !== Object.prototype; x = Object.getPrototypeOf(x)) {\n const d = Object.getOwnPropertyDescriptor(x, key);\n if (d !== undefined) return d;\n }\n return undefined;\n}\n\nfunction mountKey(m: Mount, whole: Entry | null, p: Pattern): void {\n if (p.getter !== null) return;\n const h = m.host;\n const H = h.engine!;\n const head = headOf(p.path);\n let e = h.entries.find((x) => x.inner === p.path);\n if (e === undefined && p.parent !== null) return mountUnder(m, p);\n if (p.depth !== 0) return;\n let target: Pattern;\n if (e !== undefined) {\n if (e.inner !== head ? own(h, head) : surface(h, head)) return;\n target = e.outer;\n } else if (whole !== null && p.parent === null && head[0] !== \"$\" && !own(h, head)) {\n e = whole;\n target = H.pattern(`${whole.outer.path}.${head}`);\n } else {\n return;\n }\n const row = e.row;\n const through = e;\n p.getter = () => H.readUntracked(target, live(m, row));\n p.setter = (value: unknown) => {\n across(m, through, () => H.write(target, row, value));\n m.skip = p;\n };\n m.synth.set(p, { e, p: target, row });\n}\n\n/**\n * The host row an entry is mounted on, for reading or writing through it. A removed row is gone\n * for good (4.0 never puts a removed row's element in another row): nothing of it is the\n * component's any more, and the position it had may hold another row now (3.4 #367 / #368).\n */\nfunction live(m: Mount, row: StateRow | null): StateRow | null {\n if (row !== null && !row.alive) raiseError(`The host row of <${m.host.el.localName}> was removed.`);\n return row;\n}\n\n/** Runs a change of component `m` crossing to its host through entry `e`. */\nfunction across(m: Mount, e: Entry, fn: () => void): void {\n const was = active.has(m.component);\n active.add(m.component);\n m.from = e;\n try {\n fn();\n } finally {\n if (!was) active.delete(m.component);\n m.from = null;\n }\n}\n\n/** Whether a change crossing from the component's own entry `from` (or from its host) reaches `slot`. */\nconst reaches = (slot: Slot, reached: boolean): boolean =>\n reached || !active.has(slot.m.component) || (slot.m.from !== null && slot.m.from !== slot.e);\n\n/**\n * A path under a mounted key whose host counterpart is a getter (a host getter, a recursive\n * family): read — and written, if it has a setter — through the host, row by row.\n */\nfunction mountUnder(m: Mount, p: Pattern): void {\n let s: Pattern | null = p.parent;\n let info: Synth | undefined;\n while (s !== null && (info = m.synth.get(s)) === undefined) s = s.parent;\n if (s === null || info === undefined) return;\n const C = m.component;\n const H = m.host.engine!;\n const hp = H.pattern(info.p.path + p.path.slice(s.path.length));\n if (hp.getter === null) return;\n const from = info;\n /**\n * The host row of `hp`: the entry's own row (not the row now at its position), and under it the\n * component's rows (a component path with a `*` of its own).\n */\n const at = (): StateRow | null => {\n const r = live(m, from.row);\n if (p.depth === 0) return r;\n H.resolve(fill(hp.path, [...H.indexesOf(r), ...C.indexesOf(rowAt(C.ctx, p.depth))]), null);\n return (H as any).rr as StateRow | null;\n };\n p.getter = () => {\n const r = at();\n return hp.depth > 0 && r === null ? undefined : H.readUntracked(hp, r);\n };\n if (hp.setter !== null) {\n p.setter = (value: unknown) => {\n const r = at();\n across(m, from.e, () => H.write(hp, r, value));\n m.skip = p;\n };\n }\n if (p.depth > 0) p.slot = (C as any).slotCount++;\n m.synth.set(p, { e: from.e, p: hp, row: from.row });\n}\n\nfunction register(m: Mount, on: boolean): void {\n if (m.registered === on || m.host.engine === null) return;\n m.registered = on;\n registered += on ? 1 : -1;\n const H = m.host.engine;\n let byP = index.get(H);\n if (byP === undefined) index.set(H, (byP = new Map()));\n for (const slot of m.slots) {\n let byRow = byP.get(slot.e.outer);\n if (byRow === undefined) byP.set(slot.e.outer, (byRow = new Map()));\n let set = byRow.get(slot.e.row);\n if (set === undefined) byRow.set(slot.e.row, (set = new Set()));\n if (on) set.add(slot);\n else {\n set.delete(slot);\n if (set.size === 0) byRow.delete(slot.e.row);\n }\n }\n const whole = m.host.entries.find((e) => e.inner === \"\");\n if (whole === undefined) return;\n if (m.exports === null) exportAccessors(m, whole);\n // the host's readers of the exported paths: the component answers them now (a re-set of the\n // host while it was away forgot the answer), or no longer\n for (const hp of m.exports!.keys()) {\n if (on && hp.getter === null) answer(H, hp, whole.outer);\n H.strategy.invalidate(H, hp, whole.row);\n }\n if (m.exports!.size > 0) H.schedule();\n if (on) warnShadowed(m, whole);\n}\n\n// ---------------------------------------------------------------- exported accessors\n\n/** The getters `answer` gave host patterns (a re-set of the host forgets them with its accessors). */\nconst exporting = new WeakSet<object>();\n\n/**\n * README \"Exported getters\": a whole mount's accessors (getters and setters, not methods or\n * private data, no `*` in the name) are read at the mount point. The host's own accessor there\n * wins; a key the tree has wins (`wcs/mount-export-shadowed`).\n */\nfunction exportAccessors(m: Mount, whole: Entry): void {\n const h = m.host;\n const H = h.engine!;\n m.exports = new Map();\n const seen = new Set<string>();\n for (let o: object | null = h.state; o !== null && o !== Object.prototype; o = Object.getPrototypeOf(o)) {\n for (const k of Object.getOwnPropertyNames(o)) {\n if (seen.has(k)) continue;\n seen.add(k);\n const d = Object.getOwnPropertyDescriptor(o, k)!;\n if ((d.get === undefined && d.set === undefined) || k[0] === \"$\" || k.includes(WILDCARD)) continue;\n // a dotted accessor exports only from the component's own data (`form.label`), not the tree's\n const head = headOf(k);\n if (k !== head && !own(h, head)) continue;\n const hp = H.pattern(`${whole.outer.path}.${k}`);\n // the host's own accessor there wins\n if (hp.getter === null) answer(H, hp, whole.outer);\n else if (!exporting.has(hp.getter)) continue;\n m.exports.set(hp, m.component.pattern(k));\n }\n }\n}\n\n/** The mount that exports `hp` at host row `row` (the row at the mount point's depth). */\nfunction exporter(H: Engine, outer: Pattern, row: StateRow | null, hp: Pattern): Mount | null {\n const set = index.get(H)?.get(outer)?.get(row);\n if (set === undefined) return null;\n let found: Mount | null = null;\n for (const slot of set) {\n if (slot.e.inner !== \"\" || slot.m.exports?.has(hp) !== true || slot.m === found) continue;\n if (found !== null) {\n raiseError(`[wcs/mount-export-ambiguous] \"${hp.path}\" is exported by two mounted components on the same instance: <${found.host.el.localName}> and <${slot.m.host.el.localName}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`);\n }\n found = slot.m;\n }\n return found;\n}\n\n/** Makes host pattern `hp` read (and write) the accessor of the component mounted at `outer`, row by row. */\nfunction answer(H: Engine, hp: Pattern, outer: Pattern): void {\n const parent = hp.parent!;\n const last = hp.last;\n /** The tree's object that has the key, or null. */\n const tree = (): any => {\n const o = H.read(parent, H.ctx) as any;\n return o !== null && typeof o === \"object\" && last in o ? o : null;\n };\n hp.getter = () => {\n const o = tree();\n if (o !== null) return o[last];\n const m = exporter(H, outer, H.ctx, hp);\n return m === null ? undefined : m.component.read(m.exports!.get(hp)!, null);\n };\n exporting.add(hp.getter);\n hp.setter = (value: unknown) => {\n const o = tree();\n const m = o === null ? exporter(H, outer, H.ctx, hp) : null;\n if (m === null) {\n // no component answers it here: the tree's own key\n const at = H.read(parent, H.ctx) as any;\n if (at !== null && typeof at === \"object\") at[last] = value;\n return;\n }\n const cp = m.exports!.get(hp)!;\n if (findDescriptor(m.host.state, cp.path)?.set === undefined) {\n raiseError(`Cannot write to \"${cp.path}\" on mounted <${m.host.el.localName}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`);\n }\n m.component.write(cp, null, value);\n };\n if (hp.depth > 0) hp.slot = H.slotCount++;\n}\n\nfunction warnShadowed(m: Mount, whole: Entry): void {\n const H = m.host.engine!;\n for (const [hp, cp] of m.exports!) {\n const o = H.readUntracked(hp.parent!, whole.row) as any;\n if (o === null || typeof o !== \"object\" || !(hp.last in o)) continue;\n const tag = m.host.el.localName;\n warnOnce(`${tag}|${hp.path}`, `[wcs/mount-export-shadowed] <${tag}>.${m.host.prop}.${cp.path} is exported at \"${hp.path}\" but the tree already has that key, so readers outside the component get the tree value. Remove the tree key or rename the accessor. See docs/state-overlay-export-design.md X1.`);\n }\n}\n\n/** A component's exported accessor was reached (it may now differ): so are the host's readers of it. */\nfunction exportReached(m: Mount, g: Pattern): void {\n const whole = m.host.entries.find((e) => e.inner === \"\")!;\n const H = m.host.engine!;\n for (const [hp, cp] of m.exports!) {\n if (cp !== g) continue;\n H.strategy.invalidate(H, hp, whole.row);\n H.schedule();\n }\n}\n\n/**\n * The `beforeWrite` hook: a component's write through a `#ro` entry, or through an entry whose\n * host row is gone. Code (a method, `element.state`, `$setAll` / `$resolve`) is refused; an\n * element's write-back (a two-way input in the component) is dropped, as `#ro` on that binding\n * would (@wcstack/state 3.3).\n */\nexport function guardReadonlyMount(E: Engine, p: Pattern, element: boolean): boolean {\n const m = mounts.get(E);\n if (m === undefined) return false;\n let info: Synth | undefined;\n for (let s: Pattern | null = p; s !== null && info === undefined; s = s.parent) info = m.synth.get(s);\n if (info === undefined) return false;\n const e = info.e;\n // the host's row went away (an await outlived it): the write has nowhere to land (3.3.x)\n const gone = e.row !== null && !e.row.alive;\n if (!gone && !e.ro) return false;\n if (element) return true;\n live(m, e.row);\n raiseError(`[wcs/mount-readonly] <${m.host.el.localName}> cannot write \"${p.path}\": it is mounted read-only (\"${m.host.prop}${e.inner === \"\" ? \"\" : `.${e.inner}`}#ro: ${e.outer.path}\"). Write it on the host, or drop #ro from the mount.`);\n}\n\n/** A host engine that has components mounted on it: its state cannot be re-set. */\nexport function hasMounts(engine: Engine): boolean {\n const byP = index.get(engine);\n if (byP === undefined) return false;\n for (const byRow of byP.values()) if (byRow.size > 0) return true;\n return false;\n}\n\n/**\n * Applies a change another engine made to shared data: the lists under it re-sync (an\n * element's row takes the array's new element), hooks see it, dependents update.\n */\nfunction touch(E: Engine, p: Pattern, row: StateRow | null, old: unknown, value: unknown, direct: boolean): void {\n if (p.getter !== null) {\n E.strategy.invalidate(E, p, row);\n E.schedule();\n return;\n }\n if (p.last === WILDCARD) {\n if (row === null) return;\n row.item = (row.list.arr as unknown[])[row.index];\n E.strategy.resetRow(row);\n if (row.children !== null) for (const l of row.children.values()) E.sync(l);\n } else {\n (E as any).syncListsUnder(p, row);\n }\n hooks.written?.(E, p, row, old, value, direct);\n E.changed(p, row);\n}\n\n/** The value an entry is mounted on may have been replaced: every key read through it is stale. */\nfunction refresh(slot: Slot): void {\n const C = slot.m.component;\n for (const [p, s] of slot.m.synth) {\n if (s.e !== slot.e) continue;\n if (p.depth === 0) C.strategy.invalidate(C, p, null);\n else C.forAllRows(p.lists[p.depth]!, (r) => C.strategy.invalidate(C, p, r));\n }\n C.schedule();\n}\n\n/** A host change at or under an entry: the component's path under the mounted key. */\nfunction into(slot: Slot, q: Pattern, p: Pattern, row: StateRow | null, old: unknown, value: unknown, direct: boolean): void {\n const rest = p.path.slice(q.path.length);\n if (rest === \"\") return refresh(slot);\n const m = slot.m;\n const C = m.component;\n let cpath: string;\n if (slot.e.inner === \"\") {\n cpath = rest.slice(1);\n const head = headOf(cpath);\n // the component keeps it private, or a partial entry maps it elsewhere (the longest prefix wins)\n if (head[0] === \"$\" || own(m.host, head) || m.host.entries.some((x) => x.inner !== \"\" && (cpath === x.inner || cpath.startsWith(`${x.inner}.`)))) return;\n } else {\n cpath = slot.e.inner + rest;\n }\n const idx: number[] = [];\n for (let k = q.depth + 1; k <= p.depth; k++) idx.push(rowAt(row, k)!.index);\n C.resolve(fill(cpath, idx), null);\n const cp = (C as any).rp as Pattern;\n const crow = (C as any).rr as StateRow | null;\n if (cp.depth > 0 && crow === null) return;\n touch(C, cp, crow, old, value, direct);\n}\n\n/** A component's write under a mounted key: the host's path, with the host row's indexes first. */\nfunction up(m: Mount, p: Pattern, row: StateRow | null, old: unknown, value: unknown, direct: boolean): void {\n let s: Pattern | null = p;\n let info: Synth | undefined;\n while (s !== null && (info = m.synth.get(s)) === undefined) s = s.parent;\n if (s === null || info === undefined) return; // private data\n const H = m.host.engine!;\n if (s === p && m.skip === p) {\n m.skip = null; // its setter wrote through the host\n return;\n }\n // its host row went away (a write there is refused; `$postUpdate` is not a write): the position\n // it had may hold another row now\n if (info.row !== null && !info.row.alive) return;\n const idx = [...H.indexesOf(info.row), ...m.component.indexesOf(row)];\n H.resolve(fill(info.p.path + p.path.slice(s.path.length), idx), null);\n const hp = (H as any).rp as Pattern;\n const hr = (H as any).rr as StateRow | null;\n if (hp.depth > 0 && hr === null) return;\n across(m, info.e, () => touch(H, hp, hr, old, value, direct));\n}\n\n/**\n * The `written` / `getterReached` hook: a change in engine E crosses to the host it is mounted\n * on (a write, not a getter reached) and to the components mounted on it. A write does not come\n * back to the engines it is crossing from; a getter reached does — it only invalidates, and the\n * components a write started in read the host's getters too.\n */\nexport function crossed(E: Engine, p: Pattern, row: StateRow | null, old: unknown, value: unknown, direct: boolean, reached: boolean): void {\n if (registered === 0) return;\n const was = active.has(E);\n active.add(E);\n try {\n const m = mounts.get(E);\n if (!reached && m !== undefined && m.registered && !active.has(m.host.engine!)) up(m, p, row, old, value, direct);\n if (reached && m !== undefined && m.registered && m.exports !== null) exportReached(m, p);\n const byP = index.get(E);\n if (byP === undefined) return;\n for (const [q, byRow] of byP) {\n if (p.isUnder(q)) {\n const set = byRow.get(q.depth === 0 ? null : rowAt(row, q.depth));\n if (set !== undefined) for (const slot of [...set]) if (reaches(slot, reached)) into(slot, q, p, row, old, value, direct);\n } else if (q.isUnder(p)) {\n for (const [r, set] of [...byRow]) {\n if (p.depth !== 0 && rowAt(r, p.depth) !== row) continue;\n for (const slot of [...set]) if (reaches(slot, reached)) refresh(slot);\n }\n }\n }\n } finally {\n if (!was) active.delete(E);\n }\n}\n\nasync function start(el: HTMLElement, host: Element, root: Node, state: Record<string, any>, built: () => void): Promise<void> {\n if (state === UNWIRED) return;\n // the add-ons its `$features` names, before anything reads the host's current mount\n const loading = loadFeatures(state);\n if (loading) await loading;\n const h = hosts.get(host)!;\n // a mounted engine is never \"mounting\": its `$recursion` would run half set up — refused, as in a volume\n if (h.engine && state.$recursion) {\n raiseError(`[wcs/mount-dollar-declaration] <${host.localName}>: $recursion is not run in a mounted component — declare it on the root state.`);\n }\n const old = h.current;\n if (old !== null && old.el !== el && old.el.isConnected) {\n raiseError(`<${host.localName}> already has a connected <${config.tagNames.state} bind-component=\"${h.prop}\">.`);\n }\n if (old !== null) register(old, false);\n if (old !== null && takesOver(old, el, root)) return resume(old, el, root, built);\n const C = new Engine(state, new DirtyStrategy());\n C.element = el;\n (el as any).engine = C;\n bindMethods(C, state);\n const m: Mount = { el, nodes: [], component: C, host: h, slots: [], synth: new Map(), registered: false, skip: null, from: null, exports: null };\n for (const e of h.entries) m.slots.push({ m, e });\n h.current = m;\n mounts.set(C, m);\n const independent = h.engine === null;\n if (!independent) {\n wire(m);\n register(m, true);\n // the volumes in it are refused (graft), those that loaded first and those that load later\n wired.add(C);\n rootEngineCreated(C, root);\n } else {\n hooks.element?.(C, \"mounting\");\n }\n // a Light DOM component in a server-rendered page takes the server's nodes of its content (F33)\n const adopted = hooks.adoptScope?.(root, C);\n mount(C, root as ShadowRoot | Element);\n adopted?.();\n m.nodes = [...root.childNodes];\n drainBinds();\n if (independent) C.watchRendered();\n Object.defineProperty(host, h.prop, { configurable: true, enumerable: true, get: () => C.proxy });\n const ready = (host as any).$stateReadyCallback;\n if (typeof ready === \"function\") {\n try {\n const r = ready.call(host, h.prop);\n if (r !== null && typeof r === \"object\" && typeof r.then === \"function\") r.then(undefined, report);\n } catch (e) {\n report(e);\n }\n }\n // the bindings are built: what waits for them goes on, whatever $connectedCallback does (as a root)\n built();\n // taken out while it initialized: it hears the host, and runs `$connectedCallback`, when it is back\n if (!el.isConnected) {\n register(m, false);\n return;\n }\n await C.callHook(\"$connectedCallback\");\n if (independent && el.isConnected) hooks.element?.(C, \"connected\");\n}\n\n/**\n * Whether a new `<wcs-state bind-component>` takes the scope of the old mount `o` over (resume)\n * instead of binding its root afresh: when nodes the old engine bound or rendered are still in the\n * root (it swapped only its `<wcs-state>`). A kept `<style>`, whitespace or other nodes without\n * bindings do not count: content rendered again, its `<wcs-state>` included, is bound afresh. Nodes\n * with bindings added since next to kept bound ones (the old engine cannot take them, a new one\n * cannot take the kept ones) are reported.\n */\nfunction takesOver(o: Mount, el: Node, root: Node): boolean {\n // (a `<wcs-state>` in another root of the host finds none of the old nodes there)\n const C = o.component;\n const attr = `[${config.bindAttributeName}]`;\n const binds = (n: Node): boolean => n.nodeType === 1 && ((n as Element).matches(attr) || (n as Element).querySelector(attr) !== null);\n // the root's children the old engine binds or rendered\n const kept = new Set<Node>();\n const top = (n: Node | null): void => {\n while (n !== null && n.parentNode !== root) n = n.parentNode;\n if (n !== null) kept.add(n);\n };\n const range = (v: { headAt(n: Node): Node | null }, anchor: Node): void => {\n for (let n = v.headAt(anchor); n !== null && n !== anchor; n = n.nextSibling) top(n);\n top(anchor);\n };\n for (const bs of C.rootBindings.values()) {\n for (const b of bs) {\n if (b.chain === null) top(b.node);\n else for (const br of b.chain.branches) range(b.chain, br.anchor);\n }\n }\n for (const l of C.rootLists.values()) for (const v of [l.view, ...(l.extra ?? [])]) if (v !== null) range(v, v.anchor);\n for (const n of o.nodes) if (n.parentNode === root && binds(n)) kept.add(n);\n if (kept.size === 0) return false;\n const added = [...root.childNodes].filter((n) => n !== el && !kept.has(n) && !o.nodes.includes(n)\n && (binds(n) || (C.mustache && n.textContent!.includes(\"{{\"))));\n if (added.length > 0) {\n console.warn(`[@wcstack/state] <${o.host.el.localName}>: ${added.length} node(s) added beside the content taken over are not bound.`);\n }\n return true;\n}\n\n/**\n * A new `<wcs-state bind-component>` over the content the old one bound (a component that swapped only\n * its `<wcs-state>`): it takes the scope over, as a reconnection — the old engine's bindings, rows and\n * `{{ }}` anchors are on these nodes. Walking them again would bind nothing (an element walked once is\n * left alone) and read the text the bindings rendered as markup (3.x #417 / #419). Nodes with bindings\n * added since are not bound (takesOver reports them).\n */\nasync function resume(m: Mount, el: HTMLElement, root: Node, built: () => void): Promise<void> {\n // the old element lets go of the engine (its createState no longer reaches the scope)\n (m.el as any).engine = null;\n m.el = el;\n m.component.element = el;\n (el as any).engine = m.component;\n m.nodes = m.nodes.filter((n) => n.parentNode === root);\n // (taken out while it initialized: it hears the host when it is back, as a mount does)\n if (el.isConnected) await reconnect(m, built);\n else built();\n}\n\n/**\n * A mount connected again (or taken over, resume): it hears the host from now on, then\n * `$connectedCallback` — after `built`, for a take-over (getBindingsReady goes on as for a mount).\n */\nasync function reconnect(m: Mount, built?: () => void): Promise<void> {\n register(m, true);\n for (const slot of m.slots) refresh(slot);\n built?.();\n if (m.broken) return;\n // (async: a `$connectedCallback` that throws rejects, as one that rejects does)\n await m.component.callHook(\"$connectedCallback\");\n if (m.host.engine === null && m.el.isConnected) hooks.element?.(m.component, \"connected\");\n}\n\n/** `<wcs-state bind-component=\"prop\">`: claimed instead of becoming a root of its page. */\nexport function claimComponent(el: HTMLElement, root: Node): Claimed | null {\n const prop = el.getAttribute(\"bind-component\");\n // the last claim: a `<wcs-state>` neither a volume nor a DCC definition nor a component is a root\n if (prop === null) return watchRoot(el, root);\n const parent = el.parentNode;\n const shadow = parent instanceof ShadowRoot;\n const host = shadow ? (parent as ShadowRoot).host : parent instanceof Element ? parent : null;\n /** Its mount, from the moment it is made (`$connectedCallback` may still run, or have thrown); null once another `<wcs-state>` took it over. */\n const mine = (): Mount | null => {\n const m = host === null ? undefined : hosts.get(host)?.current;\n return m?.el === el ? m : null;\n };\n // a component that does not mount: the volumes in its shadow root have no tree to graft onto\n const failed = (e: unknown): never => {\n if (shadow) orphan(parent!, el);\n throw e;\n };\n /** Its bindings were built (it mounted, or took a scope over). */\n let bound = false;\n return {\n load() {\n return (host === null || !host.localName.includes(\"-\")\n ? Promise.reject(new Error(`[@wcstack/state] \"bind-component\" requires <${config.tagNames.state}> to be a direct child of a custom element.`))\n : load(el, prop, host, !shadow)).catch(failed);\n },\n async start(state, built) {\n await start(el, host!, shadow ? parent! : host!, state, () => {\n bound = true;\n built();\n }).catch((e) => {\n // (one whose `$connectedCallback` failed is an ordinary mount)\n const m = mine();\n if (!bound && m !== null) m.broken = true;\n return failed(e);\n });\n },\n connected() {\n // a failed `$connectedCallback` is reported as a root's on reconnect is\n const m = mine();\n if (m !== null) reconnect(m).catch(report);\n // a newer `<wcs-state>` took the scope over: put back where it was, this one takes the scope over\n // again, as a new one would — once the DOM operation that put it back is done (it may take the\n // newer one out), and refused while the newer one is still in\n else if (bound) {\n void Promise.resolve().then(() => {\n if (el.parentNode === parent) return start(el, host!, shadow ? parent! : host!, hosts.get(host!)!.state, () => {});\n }).catch(report);\n }\n // still waiting for its host's wiring: the host is back (wireLate)\n else if (waiting.has(host!)) wireLate(host!);\n },\n disconnected() {\n const m = mine();\n if (m === null) return;\n register(m, false);\n if (m.broken) return;\n m.component.callHook(\"$disconnectedCallback\");\n if (m.host.engine === null) hooks.element?.(m.component, \"disconnected\");\n },\n reset() {\n raiseError(`re-setting a component's state is not supported: write <${host?.localName}>.${prop} instead.`);\n },\n };\n}\n","/**\n * The scopes add-on (@wcstack/state/features/scopes): `<wcs-state>` elements that are not roots.\n * Volumes (`<wcs-state mount=\"p\">`, src/scopes/volume.ts), Declarative Custom Components\n * (`[data-wc-definition]`, src/scopes/dcc.ts) and component mounts (`<wcs-state\n * bind-component>`, src/scopes/component.ts).\n */\nimport { chain, first, handled, hooks, taken, type Feature } from \"../hooks\";\nimport { raiseError } from \"../parser/raiseError\";\nimport { claimVolume, grafted, guardAncestorWrite, rootEngineCreated, rootMoved } from \"../scopes/volume\";\nimport { claimDcc, dccEngineCreated, dccWritten } from \"../scopes/dcc\";\nimport { claimComponent, componentScope, crossed, guardReadonlyMount, hasMounts, hostBinding } from \"../scopes/component\";\n\nexport const scopes: Feature = {\n name: \"scopes\",\n hooks,\n install(): void {\n hooks.claim = first(taken, hooks.claim, claimVolume);\n hooks.claim = first(taken, hooks.claim, claimDcc);\n // last: what it does not take is a root, which it watches for the volumes (watchRoot)\n hooks.claim = first(taken, hooks.claim, claimComponent);\n hooks.hostBinding = hostBinding;\n hooks.componentScope = componentScope;\n hooks.element = chain(hooks.element, (engine, phase) => {\n if (phase !== \"mounting\") return rootMoved(engine, phase);\n const root = (engine.element as Node).getRootNode();\n rootEngineCreated(engine, root);\n dccEngineCreated(engine, root);\n });\n hooks.written = chain(hooks.written, (engine, p, row, old, value, direct) => {\n dccWritten(engine, p, value, direct);\n crossed(engine, p, row, old, value, direct, false);\n });\n hooks.getterReached = chain(hooks.getterReached, (engine, g, row) => crossed(engine, g, row, undefined, undefined, false, true));\n hooks.beforeWrite = first(handled, hooks.beforeWrite, (engine, p, _row, _value, element) => {\n guardAncestorWrite(engine, p);\n return guardReadonlyMount(engine, p, element);\n });\n // first, before what is installed (in any order) replaces its runtime for the new state:\n // a refused re-set leaves the old state, its watches, streams and keys as they were\n const declared = hooks.declare;\n hooks.declare = (engine, target) => {\n const list = grafted.get(engine);\n if (list !== undefined && list.length > 0) {\n raiseError(`re-setting a root state with grafted volumes (${list.map((v) => v.path).join(\", \")}) is not supported: their data is part of the tree.`);\n }\n if (hasMounts(engine)) raiseError(\"re-setting a root state with mounted components is not supported: they read its data.\");\n declared?.(engine, target);\n };\n },\n};\nexport default scopes;\n","/**\n * Recursive paths (README \"Recursive paths\"): one self-recursive anchor per state,\n * `$recursion: { \"nodes.*\": \"children.*\" }`, and `**` as a depth variable — `nodes.**.x` stands\n * for `nodes.*.x`, `nodes.*.children.*.x`, … The engine only ever sees the concrete depths:\n *\n * - a getter `get \"nodes.**.total\"()` is a family, materialized as an ordinary getter on each\n * concrete depth's pattern when that pattern is made (so `$1`, caching and dependencies are the\n * ordinary per-depth ones, and a deep change reaches every ancestor through ordinary edges);\n * - `**` in a path read or `$getAll(path)` without indexes is bound to the depth of the row the\n * evaluation runs in (a family getter's row, a row getter's, an event handler's);\n * - `$getAll(path, [])` collects every depth (depth first, pre-order), `$setAll(path, [], v)`\n * writes every node; the expansions of a family are read-only.\n *\n * The engines with a `$recursion` get their `onPatternCreated`, `resolve`, `getAll` and `setAll`\n * wrapped; an engine without one pays nothing. The static checks of 3.3 (colliding families,\n * structural suffixes on getters) are the diagnostics add-on's (approved simplification).\n */\nimport type { Engine } from \"../engine\";\nimport type { Pattern } from \"../pattern\";\nimport type { StateRow } from \"../list\";\nimport { raiseError } from \"../parser/raiseError\";\nimport { raise, M } from \"../messages\";\nimport { recursionUnsupported } from \"../parser/parseStatePart\";\n\nconst NAME = \"$recursion\";\nconst MAX_DEPTH = 128;\n\ninterface Spec {\n /** `nodes` (the anchor without its trailing `.*`). */\n readonly list: string;\n /** `.children.*` */\n readonly step: string;\n /** `children` */\n readonly key: string;\n /** Families by suffix (`.total`): the author's getter. */\n readonly families: Map<string, (this: unknown) => unknown>;\n readonly matchers: [RegExp, string][];\n /** Node list patterns: `nodes`, `nodes.*.children`, `nodes.*.children.*.children`, … */\n readonly nodeList: RegExp;\n /** The family key each materialized expansion belongs to. */\n readonly owners: Map<Pattern, string>;\n}\n\nconst specs = new WeakMap<Engine, Spec>();\nconst wrapped = new WeakSet<Engine>();\n/** Patterns created while the state's accessors are registered (the `**` keys among them are templates). */\nconst registering = new WeakSet<Engine>();\nlet engines = 0;\n\nconst esc = (s: string): string => s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\nconst code = (c: string) => `[wcs/recursion-${c}]`;\n\nfunction checkPath(kind: string, path: unknown): string {\n const bad = (why: string): never => raiseError(`${code(\"declaration-invalid\")} ${NAME} ${kind} \"${String(path)}\" ${why}`);\n if (typeof path !== \"string\" || path === \"\") raiseError(`${code(\"declaration-invalid\")} ${NAME} ${kind} must be a non-empty string.`);\n const segs = path.split(\".\");\n if (segs.length < 2 || segs[segs.length - 1] !== \"*\") bad('must end with \".*\" (a list element).');\n for (let i = 0; i < segs.length - 1; i++) {\n const s = segs[i];\n if (s === \"\") bad(\"must not contain empty path segments.\");\n if (s === \"*\" || s === \"**\" || /^\\d/.test(s)) bad('must have exactly one \"*\", at the end.');\n if (s.includes(\"#\")) bad('must not contain \"#\".');\n }\n if (path[0] === \"$\") bad('must not start with \"$\".');\n return path;\n}\n\n/** Reads and checks the declaration; null when the state has none. */\nfunction read(target: Record<string, any>): Spec | null {\n const decl = target[NAME];\n const keys: [string, PropertyDescriptor][] = [];\n const seen = new Set<string>();\n for (let o: object | null = target; o !== null && o !== Object.prototype; o = Object.getPrototypeOf(o)) {\n for (const k of Object.getOwnPropertyNames(o)) {\n if (!seen.has(k) && k.includes(\"**\")) keys.push([k, Object.getOwnPropertyDescriptor(o, k)!]);\n seen.add(k);\n }\n }\n if (decl === undefined) {\n if (keys.length > 0) recursionUnsupported(keys[0][0]);\n return null;\n }\n if (decl === null || typeof decl !== \"object\" || Array.isArray(decl)) {\n raiseError(`${code(\"declaration-invalid\")} ${NAME} must be an object mapping one anchor path to its repeating sub-path.`);\n }\n const entries = Object.entries(decl);\n if (entries.length !== 1) raiseError(`${code(\"declaration-invalid\")} ${NAME} must declare exactly one anchor (it declares ${entries.length}).`);\n const anchor = checkPath(\"anchor\", entries[0][0]);\n const repeat = checkPath(\"repeat\", entries[0][1]);\n const list = anchor.slice(0, -2);\n const key = repeat.slice(0, -2);\n const step = `.${repeat}`;\n const families = new Map<string, (this: unknown) => unknown>();\n const matchers: [RegExp, string][] = [];\n const head = `${list}.**`;\n for (const [k, d] of keys) {\n const suffix = k.slice(head.length);\n if (!k.startsWith(head) || (suffix !== \"\" && suffix[0] !== \".\") || suffix.includes(\"**\")) {\n raiseError(`[wcs/recursion-anchor] \"${k}\": a recursive key is \"${head}\" followed by a path (the anchor is \"${anchor}\").`);\n }\n if (suffix === \"\" || suffix.split(\".\").slice(1).some((s) => s === \"\")) raiseError(`[wcs/recursion-anchor] \"${k}\" needs a path after \"**\".`);\n if (d.get === undefined || d.set !== undefined) raiseError(`${code(\"declaration-invalid\")} \"${k}\": a recursive key is a getter without a setter.`);\n families.set(suffix, d.get);\n matchers.push([new RegExp(`^${esc(anchor)}((?:${esc(step)})*)${esc(suffix)}$`), suffix]);\n }\n return { list, step, key, families, matchers, owners: new Map(), nodeList: new RegExp(`^${esc(list)}((?:${esc(`.*.${key}`)})*)$`) };\n}\n\n/** `nodes.*` + `.children.*` × k */\nconst nodePath = (spec: Spec, k: number): string => `${spec.list}.*${spec.step.repeat(k)}`;\n\n/** The depth of the node row `row` is in or under (null: not under the anchor). */\nfunction depthOf(spec: Spec, row: StateRow | null): { k: number; row: StateRow } | null {\n for (let r = row; r !== null; r = r.list.parentRow) {\n const m = spec.nodeList.exec(r.list.pattern.path);\n if (m !== null) return { k: m[1].length / (spec.key.length + 3), row: r };\n }\n return null;\n}\n\n/** What follows `nodes.**` in a path (`.x`, or \"\" for the nodes themselves). */\nfunction suffixOf(spec: Spec, path: string): string {\n const head = `${spec.list}.**`;\n const rest = path.slice(head.length);\n if (!path.startsWith(head) || (rest !== \"\" && rest[0] !== \".\") || rest.includes(\"**\")) {\n raiseError(`[wcs/recursion-anchor] \"${path}\" does not start at the recursion anchor \"${spec.list}.*\".`);\n }\n return rest;\n}\n\n/** `nodes.**.x` → the concrete depth of the evaluation's row. */\nfunction bind(spec: Spec, path: string, ctx: StateRow | null): string {\n const rest = suffixOf(spec, path);\n const at = depthOf(spec, ctx);\n if (at === null) {\n raiseError(`[wcs/recursion-context] \"${path}\" uses \"**\", which is bound to the depth of the row it is evaluated in; there is none here — use $getAll(\"${path}\", []) for every depth.`);\n }\n return nodePath(spec, at.k) + rest;\n}\n\n/** Every node row, depth first and pre-order: (depth, row). Reads (and so tracks) each list. */\nfunction walk(engine: Engine, spec: Spec, visit: (k: number, row: StateRow) => void): void {\n const ancestors = new Set<unknown>();\n const seen = new Set<unknown>();\n const enter = (arr: unknown, listPath: string, k: number): boolean => {\n if (!Array.isArray(arr) || arr.length === 0) return false;\n if (ancestors.has(arr)) raiseError(`${code(\"cycle\")} \"${listPath}\" is reachable from itself: the data under \"${spec.list}\" must be a tree.`);\n if (seen.has(arr)) raiseError(`${code(\"shared-list\")} \"${listPath}\" is the same array instance as a list reached before: the data under \"${spec.list}\" must be a tree.`);\n if (k + 1 > MAX_DEPTH) raiseError(`${code(\"depth-exceeded\")} Recursion on \"${spec.list}.*\" reached depth ${k + 1} (the limit is ${MAX_DEPTH}).`);\n seen.add(arr);\n return true;\n };\n const down = (rows: StateRow[], k: number): void => {\n for (const row of rows) {\n visit(k, row);\n const listP = engine.pattern(`${nodePath(spec, k)}.${spec.key}`);\n const arr = engine.read(listP, row);\n if (!enter(arr, listP.path, k + 1)) continue;\n ancestors.add(arr);\n down(engine.childList(row, listP).rows, k + 1);\n ancestors.delete(arr);\n }\n };\n const rootP = engine.pattern(spec.list);\n const arr = engine.read(rootP, null);\n if (!enter(arr, spec.list, 0)) return;\n ancestors.add(arr);\n down(engine.childList(null, rootP).rows, 0);\n}\n\nfunction wrap(engine: Engine): void {\n wrapped.add(engine);\n const e = engine as any;\n const created = e.onPatternCreated;\n e.onPatternCreated = (p: Pattern) => {\n const spec = specs.get(engine);\n if (p.path.includes(\"**\")) {\n // a recursive key's own pattern while the accessors are registered: an inert template that\n // refuses to be read, and stays one when every pattern is looked at again (a volume grafting\n // its accessors, a re-set — one that drops `$recursion` forgets it: refused again); a new one\n // later is refused by the core (made patterns are interned after this runs)\n const known = engine.patterns.peek(p.path) === p;\n if (registering.has(engine) || (spec === undefined && known)) p.getter = () => recursionUnsupported(p.path);\n else if (!known) created.call(engine, p);\n return;\n }\n if (spec !== undefined && p.getter === null) {\n for (const [re, suffix] of spec.matchers) {\n if (!re.test(p.path)) continue;\n p.getter = spec.families.get(suffix)!;\n if (p.depth > 0) p.slot = e.slotCount++;\n spec.owners.set(p, spec.list + \".**\" + suffix);\n break;\n }\n }\n created.call(engine, p);\n };\n const resolve = e.resolve;\n e.resolve = (path: string, ctx: StateRow | null) => {\n const spec = specs.get(engine);\n return resolve.call(engine, spec !== undefined && path.includes(\"**\") ? bind(spec, path, ctx) : path, ctx);\n };\n const getAll = e.getAll;\n e.getAll = (path: string, indexes?: number[]) => {\n const spec = specs.get(engine);\n if (spec === undefined || !path.includes(\"**\")) return getAll.call(engine, path, indexes);\n if (indexes === undefined) return getAll.call(engine, bind(spec, path, e.ctx));\n if (!Array.isArray(indexes) || indexes.length > 0) {\n raiseError(`${code(\"getall-form\")} $getAll(\"${path}\", indexes) with \"**\" takes either no indexes (this depth) or [] (every depth).`);\n }\n const suffix = suffixOf(spec, path);\n const out: unknown[] = [];\n walk(engine, spec, (k, row) => {\n for (const v of getAll.call(engine, nodePath(spec, k) + suffix, engine.indexesOf(row))) out.push(v);\n });\n return out;\n };\n const setAll = e.setAll;\n e.setAll = (path: string, indexes: number[], value: unknown, options?: { spread?: boolean }) => {\n const spec = specs.get(engine);\n if (spec === undefined || !path.includes(\"**\")) return setAll.call(engine, path, indexes, value, options);\n // (the core's own messages where the core's $setAll has one)\n if (!Array.isArray(indexes)) raise(M.SetAllNeedsIndexes, [path]);\n if (indexes.length > 0) raiseError(`${code(\"setall-form\")} $setAll(\"${path}\", indexes, …) with \"**\" takes no partial prefix: pass [] to write every node.`);\n if (typeof value === \"function\" || options?.spread === true) raiseError(`${code(\"setall-form\")} $setAll(\"${path}\", [], value) with \"**\" takes a plain value (no mapper, no spread).`);\n if (e.readonlyDepth > 0) raise(M.Readonly);\n const suffix = suffixOf(spec, path);\n // the checks (3.x's): an index spelling is a `*` (`.children.0` is a child node), and a child\n // node's path is a node's (`.children.*.total` is the family `.total` one level down)\n let rest = suffix.replace(/\\.\\d+(?=\\.|$)/g, \".*\");\n while (rest.startsWith(spec.step)) rest = rest.slice(spec.step.length);\n // the structure: a node, the objects on the way to its child list and the list, the list's length\n const segs = spec.key.split(\".\");\n if (rest === \"\" || rest === `.${spec.key}.length` || segs.some((_, i) => rest === `.${segs.slice(0, i + 1).join(\".\")}`)) {\n raiseError(`${code(\"structural-write\")} \"${path}\" writes the recursion structure itself (a node, its \"${spec.key}\" list or that list's length, or an object on the way to it).`);\n }\n for (const s of spec.families.keys()) {\n // (a family under a child node, `.children.*.x`, is `.x` at every depth below the first: refused\n // before anything is written, not part-way through)\n let f = s;\n while (f.startsWith(spec.step)) f = f.slice(spec.step.length);\n if (rest === f || rest.startsWith(`${f}.`)) raiseError(`${code(\"readonly\")} \"${path}\" writes into the recursive getter \"${spec.list}.**${s}\".`);\n }\n // every node first: a tree that fails the walk writes nothing\n const nodes: [number, StateRow][] = [];\n walk(engine, spec, (k, row) => nodes.push([k, row]));\n let written = 0;\n for (const [k, row] of nodes) written += setAll.call(engine, nodePath(spec, k) + suffix, engine.indexesOf(row), value);\n return written;\n };\n}\n\n/** The `declare` hook: a state received (construction, or a re-set before it replaces the old one). */\nexport function declareRecursion(engine: Engine, target: Record<string, any>): void {\n const spec = read(target);\n const had = specs.has(engine);\n if (spec === null) {\n if (had) {\n specs.delete(engine);\n engines--;\n }\n return;\n }\n if (!had) engines++;\n specs.set(engine, spec);\n registering.add(engine);\n if (!wrapped.has(engine)) wrap(engine);\n}\n\n/** The `element` hook: the state's accessors are registered — a new `**` pattern is refused again. */\nexport function recursionSettled(engine: Engine): void {\n registering.delete(engine);\n}\n\n/** The `beforeWrite` hook: an expansion of a recursive getter is read-only. */\nexport function guardExpansion(engine: Engine, p: Pattern): boolean {\n if (engines === 0) return false;\n const spec = specs.get(engine);\n if (spec === undefined) return false;\n for (let q: Pattern | null = p; q !== null; q = q.parent) {\n const owner = spec.owners.get(q);\n if (owner !== undefined) raiseError(`${code(\"readonly\")} \"${p.path}\" writes into the recursive getter \"${owner}\".`);\n }\n return false;\n}\n","/**\n * The recursion add-on (@wcstack/state/features/recursion): `$recursion` and `**` — see\n * src/recursion/recursion.ts.\n */\nimport { chain, first, handled, hooks, type Feature } from \"../hooks\";\nimport { declareRecursion, guardExpansion, recursionSettled } from \"../recursion/recursion\";\n\nexport const recursion: Feature = {\n name: \"recursion\",\n hooks,\n install(): void {\n hooks.declare = chain(hooks.declare, declareRecursion);\n hooks.element = chain(hooks.element, (engine, phase) => {\n if (phase === \"mounting\" || phase === \"reset\") recursionSettled(engine);\n });\n hooks.beforeWrite = first(handled, hooks.beforeWrite, guardExpansion);\n },\n};\nexport default recursion;\n","import pkg from \"../package.json\" with { type: \"json\" };\n\n/** The package version: stamped into `<wcs-ssr>`, compared on hydration (major.minor), shown by DevTools. */\nexport const VERSION: string = pkg.version;\n","{\n \"name\": \"@wcstack/state\",\n \"version\": \"4.9.0\",\n \"description\": \"Reactive state management with declarative data binding for Web Components. Zero dependencies, buildless.\",\n \"type\": \"module\",\n \"main\": \"./dist/index.esm.js\",\n \"module\": \"./dist/index.esm.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.esm.js\"\n },\n \"./auto\": {\n \"types\": \"./dist/auto.d.ts\",\n \"import\": \"./dist/auto.min.js\"\n },\n \"./core\": {\n \"types\": \"./dist/split/core.d.ts\",\n \"import\": \"./dist/split/core.js\"\n },\n \"./features/*\": {\n \"types\": \"./dist/split/features/*.d.ts\",\n \"import\": \"./dist/split/features/*.js\"\n },\n \"./define\": {\n \"types\": \"./dist/define.d.ts\",\n \"import\": \"./dist/define.js\"\n },\n \"./manifest\": {\n \"types\": \"./dist/manifest.d.ts\",\n \"import\": \"./dist/manifest.esm.js\"\n },\n \"./parser\": {\n \"types\": \"./dist/parser.d.ts\",\n \"import\": \"./dist/parser.esm.js\"\n },\n \"./wcs-manifest.json\": \"./dist/wcs-manifest.json\"\n },\n \"files\": [\n \"dist\",\n \"!dist/core.min.js\"\n ],\n \"scripts\": {\n \"clean\": \"node -e \\\"require('node:fs').rmSync('dist', { recursive: true, force: true })\\\"\",\n \"build\": \"node build.mjs\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\",\n \"lint\": \"eslint src\",\n \"typecheck\": \"tsc --noEmit\",\n \"golden\": \"node scripts/golden.mjs\",\n \"version:patch\": \"npm version patch\",\n \"version:minor\": \"npm version minor\",\n \"version:major\": \"npm version major\",\n \"prepublishOnly\": \"npm run build && npm run test:coverage\"\n },\n \"keywords\": [\n \"web-components\",\n \"state-management\",\n \"reactive\",\n \"data-binding\",\n \"proxy\",\n \"custom-elements\",\n \"shadow-dom\",\n \"buildless\",\n \"zero-dependencies\",\n \"declarative\"\n ],\n \"author\": \"mogera551\",\n \"homepage\": \"https://wcstack.github.io\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/wcstack/wcstack.git\",\n \"directory\": \"packages/state\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/wcstack/wcstack/issues\"\n },\n \"license\": \"MIT\",\n \"devDependencies\": {\n \"@eslint/js\": \"^9.39.5\",\n \"@vitest/coverage-v8\": \"^4.1.11\",\n \"esbuild\": \"0.27.2\",\n \"eslint\": \"^9.39.5\",\n \"globals\": \"^16.5.0\",\n \"happy-dom\": \"^20.0.11\",\n \"rollup\": \"^4.63.5\",\n \"rollup-plugin-dts\": \"^6.5.1\",\n \"terser\": \"^5.51.2\",\n \"typescript\": \"^5.9.3\",\n \"typescript-eslint\": \"^8.70.1\",\n \"vitest\": \"^4.0.15\"\n }\n}\n","/**\n * `<wcs-ssr>` (`config.tagNames.ssr`): the server's snapshot before a `<wcs-state enable-ssr>` —\n * `version`, the state's data (a JSON `<script>`) and the page-level templates. The SSR add-on\n * defines the tag; this class only reads the snapshot (the add-on hydrates from it and removes it).\n */\nimport { config } from \"../config\";\nimport { VERSION } from \"../version\";\nimport { HTMLElementBase } from \"../element\";\n\nexport interface ISsrElement {\n /** The @wcstack/state version that rendered the page. */\n readonly version: string;\n /** The state's data the server rendered with. */\n readonly stateData: Record<string, any>;\n /** The page-level templates, by id. */\n readonly templates: Map<string, HTMLTemplateElement>;\n /** Always empty: every binding is applied when the client adopts the server's DOM (3.x kept a value table here). */\n readonly hydrateProps: Record<string, Record<string, unknown>>;\n getTemplate(id: string): HTMLTemplateElement | null;\n /** The snapshot is adoptable: the same major.minor as this build. */\n verifyVersion(): boolean;\n}\n\n/** `4.0.1` → `4.0`: a snapshot is adoptable by the same major.minor. */\nexport const majorMinor = (v: string): string => v.split(\".\").slice(0, 2).join(\".\");\n\nexport class Ssr extends HTMLElementBase implements ISsrElement {\n /** The first snapshot element under `root`, or null. */\n static find(root: Node): ISsrElement | null {\n return ((root as ParentNode).querySelector?.(config.tagNames.ssr) as Ssr | null) ?? null;\n }\n\n get version(): string {\n return this.getAttribute(\"version\") ?? \"\";\n }\n\n get stateData(): Record<string, any> {\n const script = this.querySelector('script[type=\"application/json\"]');\n return script === null ? {} : JSON.parse(script.textContent || \"{}\");\n }\n\n get templates(): Map<string, HTMLTemplateElement> {\n const map = new Map<string, HTMLTemplateElement>();\n // quoted: `children` is an internal name the bundles shorten (mangle.mjs)\n for (const t of Array.from(this[\"children\"])) if (t.localName === \"template\") map.set(t.id, t as HTMLTemplateElement);\n return map;\n }\n\n get hydrateProps(): Record<string, Record<string, unknown>> {\n return {};\n }\n\n getTemplate(id: string): HTMLTemplateElement | null {\n return this.templates.get(id) ?? null;\n }\n\n verifyVersion(): boolean {\n return majorMinor(this.version) === majorMinor(VERSION);\n }\n}\n\n/** Defines `<wcs-ssr>` in `registry` (once per registry). */\nexport function defineSsr(registry: CustomElementRegistry): void {\n const tag = config.tagNames.ssr;\n if (registry.get(tag) === undefined) registry.define(tag, class extends Ssr {});\n}\n","/**\n * Server-side rendering with @wcstack/server (README \"Server-Side Rendering\"), for\n * `<wcs-state enable-ssr>` roots.\n *\n * Server (`<html data-wcs-server>`): the page renders as usual; the snapshot builder\n * (`Symbol.for(\"wcstack.ssr.snapshotBuilder\")`, called by the server before it serializes)\n * then makes the DOM adoptable:\n * - every view's rows / branch move right after its anchor, between `<!--wcs-[-->` and\n * `<!--wcs-]-->`, each row opened by `<!--wcs-|-->` (a branch region carries its index,\n * `<!--wcs-[:i-->`, and follows the chain's last anchor so the chain's templates stay adjacent);\n * - a page-level anchor becomes `<!--wcs-p:ID-->`, its template kept in `<wcs-ssr>` as\n * `<template id=ID>`; a page-level text binding (a mustache, a comment binding) is wrapped in\n * `<!--wcs-t:EXPR-->…<!--wcs-/t-->` (the client puts a comment binding back);\n * - adjacent text nodes are separated (`<!--wcs-s-->`) and empty ones kept (`<!--wcs-e-->`), so\n * parsing the HTML gives back the rows' exact structure;\n * - `<wcs-ssr version>` before the element holds the state's data (JSON) and the templates.\n *\n * Client: before the page is bound, the texts and templates are restored and the regions read where\n * they are (their marks go; the page's walk passes their nodes by); each block the engine builds\n * takes its region's next row instead of a clone (a row's nested regions wait for its nested views\n * in turn). The server's nodes never leave the page — no custom element in a row or a branch is\n * disconnected — and get their bindings; a view's anchors move after its rows instead. A row that\n * does not fit its plan is built anew in its place, and the rows no view took go once the page is\n * bound. `$connectedCallback` does not run (the server ran it).\n *\n * A snapshot of another major.minor is discarded, and the page renders on the client as it would\n * without a server: the state comes from its own source, `$connectedCallback` runs, and the server's\n * rows and marks give way to the templates they came from — those of @wcstack/server 3.x's output\n * too (`legacy`). They give way only once the page was planned on a copy: markup this client cannot\n * plan fails its initialization with the server's HTML left as it was.\n *\n * Not carried over from @wcstack/state 3.3 (approved): the inline snapshot for servers without\n * the builder protocol, and the property value table (every binding is applied on adoption).\n */\nimport type { Engine } from \"../engine\";\nimport { ForView, type Block, type IfView, type RowPlan, type Spec } from \"../dom/view\";\nimport { config } from \"../config\";\nimport { hooks } from \"../hooks\";\n\nimport { VERSION } from \"../version\";\nimport { isOuter, setsContent, templateContent, textSpec, walkBindings, walked } from \"../dom/plan\";\nimport { majorMinor } from \"./element\";\nimport { parseBindTextsForElement } from \"../parser/parseBindTextsForElement\";\n/** The snapshot element's tag (`config.tagNames.ssr`, `wcs-ssr` by default). */\nconst tag = (): string => config.tagNames.ssr;\nconst BUILDER = Symbol.for(\"wcstack.ssr.snapshotBuilder\");\n\nexport const isServer = (): boolean => document.documentElement?.hasAttribute(\"data-wcs-server\") === true;\n\nconst mark = (data: string): Comment => document.createComment(data);\nconst isMark = (n: Node | null, data: string): boolean => n !== null && n.nodeType === 8 && (n as Comment).data === data;\nconst startsMark = (n: Node | null, prefix: string): boolean => n !== null && n.nodeType === 8 && (n as Comment).data.startsWith(prefix);\n\n// ---------------------------------------------------------------- server\n\n/** Page-level anchors (the walker's) and the template each replaced, by engine. */\nconst anchors = new WeakMap<Engine, Map<Node, Element>>();\n/** The engines that recorded anchors in a page (its root node): the page's, and its Light DOM components'. */\nconst enginesByRoot = new WeakMap<Node, Set<Engine>>();\n/**\n * The custom elements the page's walker bound, with the nodes in them then (and a text's data): the\n * walk is post-order, so its anchors, text marks and rows are there, and the element's own bindings\n * have not written yet. What an element renders from a value comes later: in the server's HTML the\n * client would walk it as the page's markup (a user's `{{ … }}`, a `data-wcs` in sanitized HTML),\n * so the snapshot leaves it — and a text with `{{` that it was not then (a value's, in a node of\n * its own or one the page wrote) — to the client.\n */\nconst kept = new WeakMap<Node, Map<Node, string>>();\n/** What the client does not walk: a region (rows it adopts), an element whose content a binding sets. */\nconst skip = new WeakSet<Node>();\n/**\n * Mustache texts: their expressions. In an element whose content is text (`<textarea>`, `<title>`),\n * a mark would be text to the browser, and the value the client's markup: the element takes its\n * template along instead (`data-wcs-raw`), and the client puts it back before binding the page.\n */\nconst rawTexts = new WeakMap<Node, string>();\n\n/** Nodes from `from` to `to`, siblings, inclusive. */\nfunction range(from: Node, to: Node): Node[] {\n const out: Node[] = [];\n for (let n: Node | null = from; n !== null; n = n.nextSibling) {\n out.push(n);\n if (n === to) break;\n }\n return out;\n}\n\n/** `to` with `from`'s attributes, and `content` (into a template's content when it has one). */\nfunction attrs<T extends Element>(from: Element, to: T, ...content: Node[]): T {\n for (const a of Array.from(from.attributes)) to.setAttribute(a.name, a.value);\n ((to as unknown as HTMLTemplateElement).content ?? to).append(...content);\n return to;\n}\n\nconst lastOf = (b: Block): Node => (b.nodes === null ? b.first : b.nodes[b.nodes.length - 1]);\n\n/**\n * The anchor `<wcs-link>` (@wcstack/router) renders right after itself, its children moved into it:\n * the server's is marked `data-wcs-ssr-link`, and is the link's `anchorElement` once the router took\n * it (dropping the mark). In a row it is the link's: the link's children are there.\n */\nconst beside = (n: Node): Node | null => {\n const a = n.nextSibling as Element | null;\n return n.nodeType === 1 && a?.localName === \"a\" && (a.hasAttribute(\"data-wcs-ssr-link\") || (n as any).anchorElement === a) ? a : null;\n};\n\n/**\n * Makes the blocks one region right after the anchors `from` … `to` (a view renders its blocks before\n * its anchor; a branch before its own, the chain's later anchors after it). The anchors move, not the\n * blocks: a custom element in a row is not disconnected, so what it rendered as it connected stays\n * (`<wcs-link>` renders its anchor a microtask later, and would not again before the server serializes).\n */\nfunction region(from: Node, to: Node, blocks: Block[], branch: number | null): void {\n const open = mark(branch === null ? \"wcs-[\" : `wcs-[:${branch}`);\n const close = mark(\"wcs-]\");\n if (blocks.length > 0) (blocks[0].head() as ChildNode).before(...range(from, to));\n (to as ChildNode).after(open);\n for (const b of blocks) if (branch === null) b.head().before(mark(\"wcs-|\"));\n const last = blocks.length > 0 ? lastOf(blocks[blocks.length - 1]) : open;\n ((beside(last) ?? last) as ChildNode).after(close);\n for (const n of range(open, close)) skip.add(n);\n}\n\nfunction visitView(v: ForView | IfView): void {\n if (v instanceof ForView) {\n region(v.anchor, v.anchor, v.rowViews, null);\n for (const b of v.rowViews) visitBlock(b);\n return;\n }\n const cur = v.current;\n if (cur === null) return;\n region(v.branches[v.index].anchor, v.branches[v.branches.length - 1].anchor, [cur], v.index);\n visitBlock(cur);\n}\n\nfunction visitBlock(b: Block): void {\n if (b.children !== null) for (const c of b.children) visitView(c);\n}\n\nconst RAW = new Set([\"script\", \"style\", \"template\", \"textarea\", \"title\"]);\nconst RAW_ATTR = \"data-wcs-raw\";\nconst raw = (el: Element): boolean => RAW.has(el.localName) || el.localName === tag();\n\n/** Keeps every text node a text node through HTML serialization and parsing. */\nfunction protectTexts(parent: Node): void {\n for (const n of Array.from(parent.childNodes)) {\n if (n.nodeType === 3) {\n if ((n as Text).data === \"\") n.replaceWith(mark(\"wcs-e\"));\n else if (n.nextSibling !== null && n.nextSibling.nodeType === 3) n.after(mark(\"wcs-s\"));\n } else if (n.nodeType === 1 && !raw(n as Element)) {\n protectTexts(n);\n }\n }\n}\n\nfunction json(value: unknown): string {\n return JSON.stringify(value).replace(/[<>&\\u2028\\u2029]/g, (c) => `\\\\u${c.charCodeAt(0).toString(16).padStart(4, \"0\")}`);\n}\n\n/** The state's own data (no `$` keys, no accessors, no functions). */\nfunction data(target: Record<string, any>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(target)) {\n if (key[0] === \"$\") continue;\n const d = Object.getOwnPropertyDescriptor(target, key)!;\n if (d.get !== undefined || d.set !== undefined || typeof d.value === \"function\") continue;\n out[key] = d.value;\n }\n return out;\n}\n\nlet ids = 0;\n\nfunction snapshot(el: Element, engine: Engine): void {\n const root = el.getRootNode() as Document | ShadowRoot;\n // the page's engine, and those of the Light DOM components in it: their walkers' anchors are in\n // the page too (a Shadow DOM component's are in its own shadow root)\n const engines = [engine];\n for (const E of enginesByRoot.get(root) ?? []) {\n if (E !== engine && (E.element as Element | null)?.hasAttribute(\"bind-component\") === true) engines.push(E);\n }\n const map = new Map<Node, Element>();\n for (const E of engines) {\n const own = anchors.get(E);\n if (own === undefined) continue;\n // the views the walker made, top down (a nested view's region stays inside its row's)\n const byAnchor = new Map<Node, ForView | IfView>();\n for (const l of E.rootLists.values()) {\n if (l.view !== null) byAnchor.set(l.view.anchor, l.view);\n if (l.extra !== null) for (const v of l.extra) byAnchor.set(v.anchor, v);\n }\n for (const bs of E.rootBindings.values()) {\n for (const b of bs) if (b.chain !== null) for (const br of b.chain.branches) byAnchor.set(br.anchor, b.chain);\n }\n const done = new Set<ForView | IfView>();\n for (const [anchor, template] of own) {\n map.set(anchor, template);\n const v = byAnchor.get(anchor);\n if (v !== undefined && !done.has(v) && anchor.isConnected) {\n done.add(v);\n visitView(v);\n }\n }\n }\n for (const h of Array.from(root.querySelectorAll(\"*\"))) {\n const own = kept.get(h);\n if (own !== undefined) {\n // what the client does not walk is left: what `skip` has, and — the page's — a Light DOM\n // component (bound later, by its own engine). A text without `{{` is no markup to the client,\n // whoever wrote it; one the page wrote is left as it was written, and a mustache's where the\n // client puts its expression back: right after its mark (the client replaces what follows it),\n // or in a text element (`data-wcs-raw`). Elsewhere it goes: an element may drop comments, or\n // move a text element's text out, and its value would be the client's markup\n const w = document.createTreeWalker(h, 133, {\n acceptNode: (n) => (skip.has(n) || (n.nodeType === 1 && own.has(n) && scoped(n as Element)) ? 2 : 1),\n });\n const out: ChildNode[] = [];\n for (let n = w.nextNode(); n !== null; n = w.nextNode()) {\n const p = n.previousSibling!;\n if (n.nodeType === 3\n ? (n as Text).data.includes(\"{{\")\n && !(raw(n.parentNode as Element) ? rawTexts.has(n) : own.has(p) && startsMark(p, \"wcs-t:\"))\n && (rawTexts.has(n) || own.get(n) !== (n as Text).data)\n : !own.has(n)) out.push(n as ChildNode);\n }\n for (const n of out) n.remove();\n }\n const cs = Array.from(h.childNodes);\n if (raw(h) && cs.some((c) => rawTexts.has(c))) {\n // (a comment there — a server's DOM may parse one in a <textarea> — is text to a browser)\n h.setAttribute(RAW_ATTR, cs.map((c) => (rawTexts.has(c) ? `{{ ${rawTexts.get(c)} }}` : c.nodeType === 8 ? `<!--${(c as Comment).data}-->` : c.textContent)).join(\"\"));\n }\n }\n protectTexts(root.nodeType === 9 ? (root as Document).body : root);\n const ssr = document.createElement(tag());\n ssr.setAttribute(\"version\", VERSION);\n const script = document.createElement(\"script\");\n script.type = \"application/json\";\n script.textContent = json(data(engine.target));\n ssr.append(script);\n for (const [anchor, template] of map) {\n if (!anchor.isConnected) continue;\n // the anchor's context, by name (a server's DOM may not know <foreignObject> leads back to HTML):\n // SVG under <svg> — its id says so (`wcs-s…`) — and HTML under <foreignObject>\n let e = anchor.parentNode as Element | null;\n while (e !== null && e.localName !== \"svg\" && e.localName !== \"foreignObject\") e = e.parentElement;\n const svg = e?.localName === \"svg\";\n const id = `wcs-${svg ? \"s\" : \"t\"}${ids++}`;\n (anchor as ChildNode).replaceWith(mark(`wcs-p:${id}`));\n let c: Node = document.importNode(templateContent(template as HTMLTemplateElement), true);\n // a template in it that is an SVG element goes as an HTML one, which a serializer reads (the\n // client's parser reads it back in its context)\n for (const x of Array.from((c as Element).querySelectorAll(\"template\"))) {\n // by namespace, not `instanceof SVGElement`: a server window (@wcstack/server) need not expose that global\n if (x.namespaceURI === \"http://www.w3.org/2000/svg\") x.replaceWith(attrs(x, document.createElement(\"template\"), ...x.childNodes));\n }\n // an SVG template's content goes in <svg>, so the client's parser reads it as SVG\n if (svg) {\n const w = document.createElementNS(e!.namespaceURI, \"svg\");\n w.append(c);\n c = w;\n }\n const t = document.createElement(\"template\");\n t.id = id;\n ssr.append(attrs(template, t, c));\n }\n el.before(ssr);\n}\n\n/**\n * The form controls' current state into their markup, as 3.x wrote it: an input's value (its\n * `value` attribute) and checkedness (`checked`), a textarea's value (its text), the options a\n * select has selected (`selected`) — whatever set them (a `value:` / `checked:` / `selectedIndex:`\n * binding, `radio:`, a row's), where it differs from what the markup gives back. The page then shows\n * the server's values before the client binds it, or without JS; the client's bindings find them\n * there, and write over them from then on. On a page with a `<wcs-state>` only (enable-ssr or not).\n * A password's value never goes into the HTML (3.x wrote it): the client's binding fills it in.\n */\nfunction forms(doc: Document): void {\n if (doc.querySelector(config.tagNames.state) === null) return;\n for (const n of Array.from(doc.querySelectorAll<any>(\"input,textarea,select\"))) {\n if (n.localName === \"select\") {\n const o: HTMLOptionElement[] = Array.from(n.options);\n // (a single select without a marked option, its first enabled one selected: what a parser selects)\n if (n.multiple || o.some((x) => x.hasAttribute(\"selected\")) || o[n.selectedIndex] !== o.find((x) => !x.disabled)) {\n for (const x of o) x.toggleAttribute(\"selected\", x.selected);\n }\n } else if (n.localName === \"textarea\") {\n // (a value with `{{` in it would be the client's markup there, a mustache; a mustache in it is\n // the client's to put back — see snapshot: both left to the client)\n if (n.value !== n.defaultValue && !n.value.includes(\"{{\") && !Array.from(n.childNodes).some((c) => rawTexts.has(c as Node))) n.textContent = n.value;\n } else if (n.type === \"checkbox\" || n.type === \"radio\") {\n n.toggleAttribute(\"checked\", n.checked);\n } else if (n.type !== \"password\" && n.value !== n.defaultValue) {\n n.setAttribute(\"value\", n.value);\n }\n }\n}\n\n/** The builder the server calls before it serializes (protocol wcs-ssr-snapshot v1). */\nfunction build(doc: Document): void {\n // first: moving the rows into their regions (snapshot) may change what a select has selected\n forms(doc);\n for (const el of Array.from(doc.querySelectorAll(`${config.tagNames.state}[enable-ssr]`))) {\n if (el.hasAttribute(\"mount\") || el.hasAttribute(\"bind-component\")) continue;\n if (el.previousElementSibling?.localName === tag()) continue;\n const engine = (el as any).engine as Engine | null;\n if (engine !== null && engine !== undefined) snapshot(el, engine);\n }\n}\n\n/** Where the builder finds this module: the latest evaluation (a server may load one per render). */\nconst IMPL = Symbol.for(\"wcstack.state.ssr.impl\");\n\nexport function installBuilder(): void {\n const g = globalThis as any;\n g[IMPL] = { build, reset() { ids = 0; } };\n // another engine's builder (the current @wcstack/state) is not replaced\n if (g[BUILDER] === undefined) {\n g[BUILDER] = { protocol: \"wcs-ssr-snapshot\", version: 1, build: (doc: Document) => g[IMPL].build(doc), reset: () => g[IMPL].reset() };\n }\n}\n\n// ---------------------------------------------------------------- client\n\ninterface Region {\n /** The branch the region renders (null: a list). */\n readonly branch: number | null;\n /** Each row's nodes, where the server put them (a region in the row included). */\n readonly rows: Node[][];\n /**\n * The region's end mark, after its rows: the server put a view's rows after its anchor, and the view\n * renders them before it — the anchor goes here when the view takes the first row (null after).\n */\n tail: ChildNode | null;\n}\n\n/** Regions waiting for their view, by the node right before them (a view's anchor). */\nconst held = new Map<Node, Region>();\n\n/**\n * The Light DOM components of a page being hydrated, by host: their content is bound by their own\n * engine, which starts later (once its host is wired, or its class defined), so it keeps the\n * server's nodes until then and is prepared when that engine binds it (adoptScope).\n */\nconst deferred = new WeakMap<Node, { ssr: Element; adopt: boolean }>();\nconst scoped = (el: Element): boolean => hooks.componentScope?.(el) === true;\n\n/** An element regions may be in: not a text element, nor a Light DOM component (its engine reads its own). */\nconst enters = (n: Node): boolean => n.nodeType === 1 && !raw(n as Element) && !scoped(n as Element);\n\n/** A region's nodes: its rows', and its end mark. */\nconst nodesOf = (r: Region): Node[] => r.rows.flat().concat(r.tail ?? []);\n\n/** Takes a region's nodes out of the page (rows no view took, or not the plan's). */\nconst drop = (r: Region): void => {\n for (const n of nodesOf(r)) (n as ChildNode).remove();\n};\n\n/**\n * Reads the region `start` opens where it is: its marks go but its end mark, and its nodes stay (no\n * custom element in them is disconnected). It is held by the node before it, its view's anchor (the\n * page's walk then passes its nodes by: its blocks bind them where they are), or dropped (`keep`\n * false, or no node before it). A region in it — in a row, after a view's anchor of the row, or in an\n * element of it — is read in turn. Its nodes go in `row` (the row it is in); returns the node after it.\n */\nfunction read(start: Comment, keep: boolean, row?: Node[]): Node | null {\n const m = /^wcs-\\[(?::(\\d+))?/.exec(start.data)!;\n const key = start.previousSibling;\n const parent = start.parentNode!;\n const rows: Node[][] = [];\n let n: Node | null = start.nextSibling;\n start.remove();\n while (n !== null && !isMark(n, \"wcs-]\")) {\n let next: Node | null = n.nextSibling;\n if (isMark(n, \"wcs-|\")) {\n rows.push([]);\n (n as ChildNode).remove();\n } else {\n // (a branch has no row marks; a list's node before its first one is a value's)\n if (rows.length === 0) rows.push([]);\n const own = rows[rows.length - 1];\n if (startsMark(n, \"wcs-[\")) next = read(n as Comment, keep, own);\n else {\n own.push(n);\n if (enters(n)) strip(n, keep);\n }\n }\n n = next;\n }\n // (cut short — a parser moved its end mark into an element (see mend): it ends with its parent)\n const r: Region = { branch: m[1] === undefined ? null : Number(m[1]), rows, tail: (n ?? parent.appendChild(mark(\"wcs-]\"))) as ChildNode };\n const nodes = nodesOf(r);\n n = r.tail!.nextSibling;\n // (not spread: a region may have more nodes than a call takes arguments)\n for (const x of nodes) {\n row?.push(x);\n if (keep) walked.add(x);\n }\n if (keep && key !== null) {\n held.set(key, r);\n } else {\n drop(r);\n }\n return n;\n}\n\n/** Reads every region under `parent` (see read). */\nfunction strip(parent: Node, keep: boolean): void {\n for (let n: Node | null = parent.firstChild; n !== null; ) {\n if (startsMark(n, \"wcs-[\")) {\n n = read(n as Comment, keep);\n } else {\n if (enters(n)) strip(n, keep);\n n = n.nextSibling;\n }\n }\n}\n\n/** Texts and templates back to what the page was written with; the regions read (see strip). */\nfunction prepare(container: Node, ssr: Element, adopt: boolean): void {\n const walk = (parent: Node): void => {\n for (const n of Array.from(parent.childNodes)) {\n // a text marker takes the nodes up to its end with it\n if (n.parentNode !== parent) continue;\n if (n.nodeType === 8) {\n const d = (n as Comment).data;\n // (a mark the server did not write — in a value — that does not parse is left as it is;\n // a string given to replaceWith goes in as a text node)\n try {\n if (d === \"wcs-s\") n.remove();\n else if (d === \"wcs-e\") n.replaceWith(\"\");\n else if (d.startsWith(\"wcs-t:\")) {\n // the value between the markers, back to a text binding: a comment binding, which binds\n // whether or not the page's mustaches are on (it was a mustache, or a comment binding)\n const text = mark(`@@:${decodeURIComponent(d.slice(6))}`);\n let e: ChildNode | null = n.nextSibling;\n while (e !== null && !isMark(e, \"wcs-/t\")) {\n const next = e.nextSibling;\n e.remove();\n e = next;\n }\n e?.remove();\n n.replaceWith(text);\n } else if (d.startsWith(\"wcs-p:\")) {\n const t = ssr.querySelector(`template[id=\"${d.slice(6)}\"]`) as HTMLTemplateElement | null;\n if (t !== null) {\n const p = n.parentNode as Element;\n // an SVG template (`wcs-s…`): its content came in <svg> (so parsed as SVG)\n const copy = d[10] === \"s\"\n ? attrs(t, document.createElementNS(p.namespaceURI, \"template\"), ...document.importNode(t.content.firstChild!, true).childNodes)\n : document.importNode(t, true);\n copy.removeAttribute(\"id\");\n p.replaceChild(copy, n);\n }\n }\n } catch { /* */ }\n } else if (n.nodeType === 1 && !raw(n as Element)) {\n if (scoped(n as Element)) deferred.set(n, { ssr, adopt });\n else walk(n);\n }\n }\n };\n walk(container);\n mend(container);\n strip(container, adopt);\n}\n\n/**\n * A region a parser cut: its start mark in a <table>, its rows and end mark in the <tbody> the parser\n * added at its first <tr> (the regions after it with them). The comments and templates right before\n * the <tbody> that the cut region starts with go into it — its anchor and marks: nothing in them\n * connects — and the rows stay where they are. A <tbody> written in the page (a row of a list of\n * them, a branch) holds no end mark of a region that starts before it, and is left alone.\n */\nfunction mend(container: Node): void {\n for (const body of Array.from((container as ParentNode).querySelectorAll(\"table > tbody\"))) {\n const run: Node[] = [];\n for (let p = body.previousSibling; p !== null && (p.nodeType === 8 || isBlank(p) || (p as Element).localName === \"template\"); p = p.previousSibling) run.unshift(p);\n // the regions the run leaves open (an end mark whose start is before the run — past an element —\n // closes a region that stays where it is, with what comes before the mark)\n let from = 0;\n let open = 0;\n run.forEach((n, i) => {\n if (startsMark(n, \"wcs-[\")) open++;\n else if (isMark(n, \"wcs-]\") && --open < 0) {\n open = 0;\n from = i + 1;\n }\n });\n if (open === 0) continue;\n // ... and the <tbody> ends one: the parser moved its rows in\n let depth = 0;\n for (let c = body.firstChild; c !== null; c = c.nextSibling) {\n if (startsMark(c, \"wcs-[\")) depth++;\n else if (isMark(c, \"wcs-]\") && depth-- === 0) {\n body.prepend(...run.slice(from));\n break;\n }\n }\n }\n}\n\n/**\n * The `adoptScope` hook: a Light DOM component's engine binds its host. Its content is prepared\n * now, and its blocks take the server's nodes while its walk runs (a walk adopts synchronously).\n * What it did not adopt is dropped after the walk: the regions held then are its own (a page's are\n * read and adopted in one go too, and dropped before anything else runs).\n */\nexport function adoptScope(host: Node, engine: Engine): (() => void) | null {\n const d = deferred.get(host);\n if (d === undefined) return null;\n deferred.delete(host);\n const undo = (c: Node): void => prepare(c, d.ssr, d.adopt);\n // (a snapshot discarded: planned on a copy first, as the page — see hydrate)\n if (!d.adopt) plan(engine, host, host, undo);\n undo(host);\n if (!d.adopt) return null;\n const prev = hooks.adopt;\n hooks.adopt = adopt;\n return () => {\n hooks.adopt = prev;\n release();\n };\n}\n\n/** Drops the held regions: rows no view took. */\nfunction release(): void {\n for (const r of held.values()) drop(r);\n held.clear();\n}\n\n/** The comments under `scope`, in document order. */\nfunction comments(scope: Node): Comment[] {\n const out: Comment[] = [];\n for (const w = document.createTreeWalker(scope, 128); w.nextNode(); ) out.push(w.currentNode as Comment);\n return out;\n}\n\n/**\n * A Light DOM component's wiring, one entry per mapping: [the page's path (null: not known — a key\n * private to the component around), its own path (\"\" for a whole mount, `state: user`), the path as\n * its host wrote it (null at the top: the page's)].\n */\ntype Wiring = (string | null)[][];\n\n/** `path` from column `from` of `wiring` to column `to`, by the longest it is or starts with; null: none. */\nfunction across(wiring: Wiring, path: string, from: number, to: number): string | null {\n let best: (string | null)[] | null = null;\n for (const w of wiring) {\n const k = w[from];\n if (k !== null && (k === \"\" || path === k || path.startsWith(`${k}.`)) && (best === null || k.length > best[from]!.length)) best = w;\n }\n const v = best?.[to];\n if (v == null) return null;\n const k = best![from]!;\n const rest = k === \"\" ? path : path.slice(k.length + 1);\n return v === \"\" ? rest : rest === \"\" ? v : `${v}.${rest}`;\n}\n\n/**\n * The output of @wcstack/server 3.x back to the page as written, as 3.x's own fallback did\n * (`Ssr.cleanupDom`): a row or a branch (`<!--@@wcs-for-start:…-->` up to its `-end` mark among its\n * siblings) goes, a text between its marks becomes a comment binding of what the mark holds (before\n * 3.5.3 the path alone, its filters lost: the warning says so; from 3.5.3, `fresh`, the binding's\n * expression as written: wcstack#373), a template's mark (`<!--@@wcs-for:ID-->`) becomes the template\n * `<wcs-ssr>` keeps under that id (whose content has the marks of the templates in it), and the\n * elements lose `data-wcs-ssr-id`.\n *\n * In a Light DOM component, 3.x wrote a template's own path as the page's (`state: user` makes `name`\n * `user.name`; a private key `user.#m1.name`, or `#m2.name` in a partial mount; in a component in a\n * component, through both), and so the marks' paths before 3.5.3: they go back to the component's own\n * through its host's wiring (the content of a template is the component's already). A mark from 3.5.3\n * is the component's own text, not mapped (it may name a key that is one of the page's wired paths\n * too: `state.x: v; state.v: w`). An expression a comment cannot hold (one with a `--`) falls back to\n * its path, unfiltered. From 3.5.4 (wcstack#427) that is the path the component wrote, read as written\n * like any other mark: the value shows, without its filters. 3.5.3 wrote the page's path there\n * instead, which is mapped back when it names a private key (`#mN.`: never in the component's own\n * text, so the mapping cannot misread a 3.5.4 mark); a wired one cannot be told from the component's\n * own text, and is read as it — a component key of that name shows its value, the right one only when\n * the wiring keeps the name, else the text stays empty (a limit of 3.5.3 output only: migration guide\n * §3.6).\n */\nfunction legacy(container: Node, ssr: Element, fresh: boolean): void {\n const wirings = new Map<Element, Wiring>();\n /** The wiring of the Light DOM component `n` is in (a nested one's composed with the one around), or null. */\n const wiringOf = (n: Node): Wiring | null => {\n let h = n.parentElement;\n while (h !== null && !scoped(h)) h = h.parentElement;\n if (h === null) return null;\n let wiring = wirings.get(h);\n if (wiring === undefined) {\n const up = wiringOf(h);\n const prop = h.querySelector(`:scope > ${config.tagNames.state}[bind-component]`)!.getAttribute(\"bind-component\");\n wirings.set(h, (wiring = []));\n for (const b of parseBindTextsForElement(h.getAttribute(config.bindAttributeName) ?? \"\")) {\n const at = b.statePathName;\n if (b.propSegments[0] === prop) wiring.push([up ? across(up, at, 1, 0) : at, b.propSegments.slice(1).join(\".\"), up && at]);\n }\n }\n return wiring;\n };\n /**\n * A path 3.x wrote at `n`, as the component's own there (`asIs`: a text mark from 3.5.3, left as it\n * is but for a private key's path, which 3.5.3's fallback writes).\n */\n const own = (n: Node, path: string, asIs?: boolean): string => {\n const wiring = wiringOf(n);\n if (wiring === null) return path;\n // (no `|`: a mark with filters, from 3.5.3, is the component's own text, a `#m1.` in it an argument's)\n const m = /^([^|]*)#m\\d+\\.([^|]*)$/.exec(path);\n if (m === null) return asIs ? path : across(wiring, path, 0, 1) ?? path;\n // after the last private key mark, a component's own path: this one's when what comes before the\n // mark is this one's mount path (`user.#m1.name`, `user.profile.#m3.name`, `#m2.box.#m4.name` with\n // `state: box`; nothing for a partial mount, `#m2.name`), else the one's around it, which this one\n // is mounted on (`#m2.box.k` with `state: box`)\n const at = m[1].replace(/#m\\d+\\./g, \"\").slice(0, -1);\n return wiring.some((w) => w[1] === \"\" && (w[0] === at || w[2] === at)) ? m[2] : across(wiring, m[2], 2, 1) ?? m[2];\n };\n // from the last: a row's own marks go before the row does\n for (const c of comments(container).reverse()) {\n const m = /^@@wcs-(\\w+)-start:([\\s\\S]*)/.exec(c.data);\n if (m === null) continue;\n // (no end among its siblings — an output cut short: left as it is)\n let e = c.nextSibling;\n while (e !== null && !isMark(e, `@@wcs-${m[1]}-end:${m[2]}`)) e = e.nextSibling;\n if (e === null) continue;\n while (c.nextSibling !== e) c.nextSibling!.remove();\n e.remove();\n c.replaceWith(...(m[1] === \"text\" ? [mark(`@@:${own(c, m[2], fresh)}`)] : []));\n }\n const restore = (scope: Node, at?: Node): void => {\n for (const c of comments(scope)) {\n const id = /^@@wcs-(?:for|if|elseif|else):(\\S+)$/.exec(c.data)?.[1];\n const t = Array.from(ssr.querySelectorAll(\"template\")).find((x) => x.id === id);\n if (t === undefined) continue;\n const copy = document.importNode(t, true);\n const a = config.bindAttributeName;\n copy.removeAttribute(\"id\");\n copy.setAttribute(a, copy.getAttribute(a)!.replace(/^(\\s*\\w+\\s*:\\s*)([^\\s|]+)/, (_, k: string, p: string) => k + own(at ?? c, p)));\n restore(copy.content, at ?? c);\n // 3.x made each `elseif` an `if` in an `else` of its own (whose content starts with it): back\n // to the chain of templates it was written as\n const f = copy.content.firstChild as Element | null;\n c.replaceWith(...(/^\\s*elseif\\s*:/.test(f?.getAttribute?.(a) ?? \"\") ? copy.content.childNodes : [copy]));\n }\n };\n restore(container);\n for (const e of Array.from((container as ParentNode).querySelectorAll(\"[data-wcs-ssr-id]\"))) e.removeAttribute(\"data-wcs-ssr-id\");\n}\n\n/**\n * What the reader typed before the client bound the page — the server's HTML is usable at once, the\n * bundles may take seconds: the form controls whose value is not the one their markup gives (a\n * browser restoring a form on reload counts too). Binding the page writes the state's values over\n * them, and the text was lost without a word (docs/seam-apps.md, ssr-news; the author's decision,\n * docs/v4-direction-2026-10.md §5.1). Returns what gives each its value back and sends it an\n * `input` and a `change`, as the reader's own edit would: a two-way binding writes it to the state.\n */\nfunction typed(container: Node): () => void {\n const edits: [HTMLElement, () => void][] = [];\n for (const n of Array.from((container as ParentNode).querySelectorAll<any>(\"input,textarea,select\"))) {\n if (n.localName === \"select\") {\n const o: HTMLOptionElement[] = Array.from(n.options);\n const sel = o.map((x) => x.selected);\n // a single select's markup selects its last marked option, or its first enabled one (the mark\n // is read as the attribute: a server's DOM need not have defaultSelected)\n const marked = o.map((x) => x.hasAttribute(\"selected\"));\n let at = marked.lastIndexOf(true);\n if (at < 0) at = o.findIndex((x) => !x.disabled);\n if (n.multiple ? o.some((x, i) => sel[i] !== marked[i]) : n.selectedIndex !== at) edits.push([n, () => o.forEach((x, i) => (x.selected = sel[i]))]);\n } else if (n.type === \"checkbox\" || n.type === \"radio\") {\n // (a radio: the one the reader chose; the group's others follow it)\n const c = n.checked;\n if (c !== n.defaultChecked && (c || n.type === \"checkbox\")) edits.push([n, () => (n.checked = c)]);\n } else if (n.type !== \"file\" && n.value !== n.defaultValue) {\n const v = n.value;\n edits.push([n, () => (n.value = v)]);\n }\n }\n return () => {\n for (const [n, put] of edits) {\n if (!n.isConnected) continue;\n put();\n n.dispatchEvent(new Event(\"input\", { bubbles: true }));\n n.dispatchEvent(new Event(\"change\", { bubbles: true }));\n }\n };\n}\n\n/**\n * Walks a copy of `container` — in a template's content, where no custom element is created — as the\n * mount of `root` walks it, once `undo` put it back as written: what this client cannot plan (a newer\n * minor's markup, a filter argument it does not know) fails its initialization while the server's\n * rows and branches are still in the page, not after they went (docs/seam-apps.md, ssr-news). (An\n * event binding puts its listener on the root at once: the mount's walk finds it there)\n */\nfunction plan(engine: Engine, root: Node, container: Node, undo: (c: Node) => void): void {\n const copy = document.createElement(\"template\").content;\n for (const n of container.childNodes) copy.appendChild(copy.ownerDocument.importNode(n, true));\n undo(copy);\n engine.root = root;\n const none = (): void => {};\n walkBindings(engine, [...copy.childNodes], null, true, none, none, none, (_, expr) => textSpec(engine, expr, null, 0));\n}\n\n/** The `element` hook, \"mounting\": a client root with a server snapshot adopts the server's DOM. */\nexport function hydrate(engine: Engine): void {\n const el = engine.element as Element;\n if (!el.hasAttribute(\"enable-ssr\") || isServer()) return;\n const ssr = el.previousElementSibling;\n const found = ssr?.localName === tag();\n const version = found ? ssr!.getAttribute(\"version\") : null;\n const same = version === null || majorMinor(version) === majorMinor(VERSION);\n if (same) {\n // the server ran $connectedCallback; the client does not\n const e = engine as any;\n const callHook = e.callHook;\n e.callHook = (name: string, args?: unknown[]) => (name === \"$connectedCallback\" ? undefined : callHook.call(engine, name, args));\n }\n if (!found) return;\n // @wcstack/server 3.x's output: marks of its own; from 3.5.3 on a text mark holds the binding's\n // expression (see legacy). A prerelease, or a version that does not parse, counts as older\n const old = !same && parseInt(version!) < 4;\n const v = /^3\\.(\\d+)\\.(\\d+)$/.exec(version!);\n const fresh = v !== null && (+v[1] - 5 || +v[2] - 3) >= 0;\n if (!same) {\n // (the filters' sentence: output before 3.5.3 only)\n console.warn(`[@wcstack/state] <${tag()} version=\"${version}\"> does not match ${VERSION}: its snapshot is discarded, and the page renders on the client from its own state.${old && !fresh\n ? \" 3.x output keeps only the path of a text binding outside a template, so such a binding loses its filters: deploy @wcstack/server 4.0 with this client.\"\n : \"\"}`);\n }\n const script = same ? ssr!.querySelector('script[type=\"application/json\"]') : null;\n if (script !== null) {\n const snap = JSON.parse(script.textContent || \"{}\") as Record<string, unknown>;\n const target = engine.target;\n for (const key of Object.keys(snap)) {\n const d = Object.getOwnPropertyDescriptor(target, key);\n if (d !== undefined && (d.get !== undefined || d.set !== undefined || typeof d.value === \"function\")) continue;\n target[key] = snap[key];\n }\n // the snapshot holds the server's volume data too: a volume adopts it (scopes/volume.ts)\n (engine as any).hydrated = true;\n }\n const root = el.getRootNode() as Document | ShadowRoot;\n for (const r of Array.from(root.querySelectorAll(`[${RAW_ATTR}]`))) {\n r.textContent = r.getAttribute(RAW_ATTR);\n r.removeAttribute(RAW_ATTR);\n }\n const container = root.nodeType === 9 ? (root as Document).body : root;\n // (its templates are not the page's markup: out before the page is walked)\n ssr!.remove();\n // back to the page as written (see prepare, legacy)\n const undo = (c: Node): void => (old ? legacy(c, ssr!, fresh) : prepare(c, ssr!, same));\n if (!same) plan(engine, root, container, undo);\n // (taken before the page is bound, which writes the state's values; given back right after)\n queueMicrotask(typed(container));\n undo(container);\n if (same) {\n // only while the page is adopted — its walk, which runs now: every other block is built with one\n // null check. What no view took then goes before anything else runs\n hooks.adopt = adopt;\n queueMicrotask(() => {\n release();\n hooks.adopt = null;\n });\n }\n}\n\n/**\n * The `ssrMark` hook: on the server, records (and leaves `outerHTML:` / `outerText:` to the client); on the client,\n * a held region follows its template's anchor.\n */\nexport function ssrMark(engine: Engine, node: Node, source: Element | string | Spec[]): void {\n if (isServer()) {\n if (source instanceof Array) {\n // `outerHTML:` / `outerText:` replace the element with the value: the client would find no\n // binding there, and walk the value as the page's markup. The server renders the element as\n // written; the client binds it and applies the value\n for (let i = source.length; i-- > 0; ) if (isOuter(source[i])) source.splice(i, 1);\n // a custom element (a Light DOM component binds its own) whose content no binding sets: what\n // is in it now is the page's (see kept)\n const el = node as Element;\n if (source.some(setsContent)) skip.add(el);\n else if (el.localName.includes(\"-\") && !scoped(el)) {\n const own = new Map<Node, string>();\n for (const w = document.createTreeWalker(el, 133); w.nextNode(); ) own.set(w.currentNode, (w.currentNode as Text).data);\n kept.set(el, own);\n }\n return;\n }\n if (typeof source === \"string\") {\n rawTexts.set(node, source);\n if (raw(node.parentNode as Element)) return;\n const open = mark(`wcs-t:${encodeURIComponent(source)}`);\n const close = mark(\"wcs-/t\");\n (node as Text).before(open);\n (node as Text).after(close);\n return;\n }\n let map = anchors.get(engine);\n if (map === undefined) anchors.set(engine, (map = new Map()));\n map.set(node, source);\n const root = node.getRootNode();\n let es = enginesByRoot.get(root);\n if (es === undefined) enginesByRoot.set(root, (es = new Set()));\n es.add(engine);\n return;\n }\n // (an element's specs are never a key: the templates the anchors replaced are)\n if (typeof source !== \"string\" && held.size > 0) {\n const r = held.get(source as Element);\n if (r !== undefined) {\n held.delete(source as Element);\n held.set(node, r);\n }\n }\n}\n\n/** An anchor of an `if` / `elseif` / `else` chain (the core names them by config). */\nconst isIfAnchor = (n: Node | null): boolean =>\n n !== null && n.nodeType === 8 && [config.commentIfPrefix, config.commentElseIfPrefix, config.commentElsePrefix].includes((n as Comment).data);\nconst isBlank = (n: Node): boolean => n.nodeType === 3 && (n as Text).data.trim() === \"\";\n\n/** The next of the plan's nodes after `n`: a held region after an anchor is the anchor's view's. */\nconst after = (n: Node): Node | null => {\n const x = held.get(n)?.tail ?? n;\n return (beside(x) ?? x).nextSibling;\n};\n\n/**\n * Whether a row's top-level nodes `own` have the plan's nodes where a binding lands — not so when a\n * Light DOM element added children before them, or a parser moved them (see mend); puts them\n * in `plan.scratch` for the block.\n */\nfunction fits(plan: RowPlan, own: Node[]): boolean {\n if (own.length !== plan.fragment.childNodes.length) return false;\n const paths = plan.nodePaths;\n for (let i = 0; i < paths.length; i++) {\n const path = paths[i];\n let a: Node = plan.fragment;\n let b: Node | null | undefined = own[path[0]];\n for (let j = 0; ; ) {\n a = a.childNodes[path[j]];\n if (b?.nodeName !== a.nodeName) return false;\n if (++j === path.length) break;\n b = (beside(b) ?? b).firstChild;\n for (let k = path[j]; k > 0 && b !== null; k--) b = after(b);\n }\n plan.scratch[i] = b;\n }\n return true;\n}\n\n/**\n * The `adopt` hook: the next server row (or branch) of the view anchored at `anchor` — its top-level\n * nodes, left where they are (the view inserts nothing, and no custom element in them is disconnected).\n */\nexport function adopt(plan: RowPlan, anchor: Node, isFor: boolean): ChildNode[] | null {\n if (held.size === 0) return null;\n let key = anchor;\n let branch = 0;\n if (!isFor) {\n // only this chain: an `if` anchor starts one (a chain right before or after is another). No\n // element is between its anchors: whitespace, comments (readChain) and the text a comment binding\n // there renders may be\n const head = config.commentIfPrefix;\n if (!isMark(anchor, head)) {\n for (let p = anchor.previousSibling; p !== null && p.nodeType !== 1; p = p.previousSibling) {\n if (isIfAnchor(p)) branch++;\n if (isMark(p, head)) break;\n }\n }\n // up to the anchor its region follows (the branch's nodes come right after it)\n for (let n = anchor.nextSibling; !held.has(key) && n !== null && !isMark(n, head) && n.nodeType !== 1; n = n.nextSibling) {\n if (isIfAnchor(n)) key = n;\n }\n }\n const r = held.get(key);\n if (r === undefined) return null;\n if (!isFor && r.branch !== branch) {\n // the server rendered another branch: it goes, this one is built\n held.delete(key);\n drop(r);\n return null;\n }\n const nodes = r.rows.shift();\n if (r.rows.length === 0) held.delete(key);\n // a view renders before its anchor (a branch before its own: the chain's anchors from it on), and\n // the server put its rows after: the anchors go where the rows end\n r.tail?.replaceWith(...range(anchor, key));\n r.tail = null;\n if (nodes === undefined) return null;\n // the row's own top-level nodes (a region in it is a nested view's, a link's anchor the link's)\n let own: Node[] = [];\n for (let i = 0; i < nodes.length; i++) {\n const inner = held.get(nodes[i]);\n own.push(nodes[i]);\n // (its nodes follow it, up to its end mark)\n if (inner !== undefined) while (i < nodes.length && nodes[i] !== inner.tail) i++;\n else if (beside(nodes[i]) === nodes[i + 1]) i++;\n }\n if (!fits(plan, own)) {\n // rendered anew, in its place (the rows around it stay; an empty one's place is before the next\n // row, or the anchor): its nodes found before it is in the page (a custom element in it may add\n // children as it connects)\n const fresh = (plan.single ? plan.root! : plan.fragment).cloneNode(true);\n own = plan.single ? [fresh] : [...fresh.childNodes];\n fits(plan, own);\n ((nodes[0] ?? r.rows.find((x) => x.length > 0)?.[0] ?? anchor) as ChildNode).before(fresh);\n for (const n of nodes) (n as ChildNode).remove();\n }\n return own as ChildNode[];\n}\n","/**\n * The SSR add-on (@wcstack/state/features/ssr): `<wcs-state enable-ssr>` with @wcstack/server —\n * see src/ssr/ssr.ts.\n */\nimport { chain, hooks, type Feature } from \"../hooks\";\nimport { adoptScope, hydrate, installBuilder, ssrMark } from \"../ssr/ssr\";\nimport { defineSsr } from \"../ssr/element\";\nimport { registries } from \"../element\";\n\nexport const ssr: Feature = {\n name: \"ssr\",\n hooks,\n install(): void {\n hooks.ssrMark = ssrMark;\n hooks.adoptScope = adoptScope;\n // the snapshot first, before what is installed (in any order) runs at \"mounting\": a volume\n // grafting there adopts it, and its $connectedCallback writes over it (3.x D14)\n const prev = hooks.element;\n hooks.element = (engine, phase) => {\n if (phase === \"mounting\") hydrate(engine);\n prev?.(engine, phase);\n };\n installBuilder();\n // `<wcs-ssr>` in every registry `<wcs-state>` is defined in, now and later\n hooks.tags = chain(hooks.tags, defineSsr);\n for (const r of registries()) defineSsr(r);\n },\n};\nexport default ssr;\n","/**\n * DevTools (`@wcstack/devtools`) — the DevTools Hook Protocol v2 (docs/devtools-hook-protocol.ja.md),\n * spoken by an add-on so the engine pays nothing while no DevTools is attached.\n *\n * The protocol's pulls (the roster, keys, read, write, keyed subscriptions) read the engines; its\n * events come from the add-on hooks (written, drained, failed, the element lifecycle) and from\n * the tokens, wrapped per engine. Addresses and bindings are small plain objects of the shape\n * DevTools reads (`absolutePathInfo.pathInfo.path`, `listIndex.indexes`, `propName`,\n * `statePathName`, `bindingType`, `node`), built only while a sink is set. Every key that\n * crosses to DevTools is quoted: the build shortens internal names, some of which (`kind`,\n * `path`, `node`, `propName`, …) are also the protocol's.\n *\n * The one part v2 builds from the engine's own bookkeeping — \"binding added / removed\" — the new\n * engine does not have (row bindings are lazy slots, made on their first change). While DevTools\n * is attached, the add-on takes the list of bindings after every drain (materialized ones and\n * slots alike) and reports the difference: DevTools sees the same live ledger, at a cost paid\n * only then.\n */\nimport type { Engine } from \"../engine\";\nimport type { Pattern } from \"../pattern\";\nimport type { StateRow } from \"../list\";\nimport type { Token } from \"../token\";\nimport { ForView, IfView, K_ATTR, K_CLASS, K_EVENT, K_STYLE, K_TEXT, type Binding, type Block, RowView, type Spec } from \"../dom/view\";\nimport { engines as byRoot } from \"../dom/mount\";\nimport { VERSION } from \"../version\";\nimport { hooks } from \"../hooks\";\n\nconst HOOK = \"__WCSTACK_DEVTOOLS_HOOK__\";\nconst PROTOCOL = 2;\n\ntype Sink = (event: Record<string, unknown>) => void;\ntype Source = Record<string, any>;\n\nlet sink: Sink | null = null;\n/** The attached DevTools' sink (analyzeContract forwards its events there). */\nexport const devtoolsSink = (): Sink | null => sink;\nconst live = new Set<Engine>();\n\n// ---------------------------------------------------------------- registry (first one wins)\n\nfunction createRegistry(): Record<string, unknown> {\n const sources = new Map<string, Source>();\n const listeners = new Set<Record<string, (...a: any[]) => void>>();\n const apply = (s: Source): void => {\n if (listeners.size === 0) s[\"_setSink\"](null);\n else s[\"_setSink\"]((event: unknown) => { for (const l of listeners) l[\"onEvent\"]?.(s[\"id\"], event); });\n };\n return {\n \"version\": PROTOCOL,\n \"sources\": sources,\n \"register\"(s: Source): void {\n if (sources.has(s[\"id\"])) return;\n sources.set(s[\"id\"], s);\n apply(s);\n for (const l of listeners) l[\"onSourceRegistered\"]?.(s);\n },\n \"unregister\"(id: string): void {\n const s = sources.get(id);\n if (s === undefined) return;\n s[\"_setSink\"](null);\n sources.delete(id);\n for (const l of listeners) l[\"onSourceUnregistered\"]?.(id);\n },\n \"addListener\"(l: Record<string, (...a: any[]) => void>): () => void {\n listeners.add(l);\n for (const s of sources.values()) {\n apply(s);\n l[\"onSourceRegistered\"]?.(s);\n }\n return () => {\n if (listeners.delete(l)) for (const s of sources.values()) apply(s);\n };\n },\n };\n}\n\n// ---------------------------------------------------------------- shapes DevTools reads\n\nconst address = (engine: Engine, p: Pattern, row: StateRow | null): Record<string, unknown> => ({\n \"absolutePathInfo\": { \"pathInfo\": { \"path\": p.path }, \"stateElement\": engine.element },\n \"listIndex\": row === null ? null : { \"indexes\": engine.indexesOf(row) },\n});\n\nfunction propName(kind: number, name: string): string {\n if (kind === K_TEXT) return \"textContent\";\n if (kind === K_CLASS) return `class.${name}`;\n if (kind === K_ATTR) return `attr.${name}`;\n if (kind === K_STYLE) return `style.${name}`;\n return name;\n}\n\n/** A binding as DevTools reads it: `{ binding, absoluteAddress }`. */\ntype Entry = Record<string, unknown>;\n\nconst nodeIds = new WeakMap<Node, number>();\nlet nodeSeq = 0;\nconst idOf = (n: Node): number => {\n let id = nodeIds.get(n);\n if (id === undefined) nodeIds.set(n, (id = ++nodeSeq));\n return id;\n};\n\n/** Every binding of the engine now — materialized ones and row slots alike — by identity. */\nfunction snapshot(engine: Engine, old: Map<string, Entry> | undefined): Map<string, Entry> {\n const out = new Map<string, Entry>();\n const seen = new Set<object>();\n const add = (kind: number, name: string, node: Node, p: Pattern, row: StateRow | null, type: string): void => {\n if (kind === K_EVENT) return;\n const prop = propName(kind, name);\n const r = p.depth === 0 ? null : row;\n const key = `${idOf(node)}|${prop}|${p.path}|${r === null ? \"\" : engine.indexesOf(r).join(\",\")}`;\n if (out.has(key)) return;\n const kept = old?.get(key);\n out.set(key, kept ?? {\n \"binding\": { \"propName\": prop, \"statePathName\": p.path, \"bindingType\": type, \"node\": node, \"replaceNode\": node },\n \"absoluteAddress\": address(engine, p, r),\n });\n };\n const binding = (b: Binding): void => add(b.kind, b.name, b.node, b.pattern, b.row, b.typeName());\n const block = (b: Block): void => {\n if (seen.has(b)) return;\n seen.add(b);\n if (b.bindings !== null) for (const x of b.bindings) binding(x);\n if (b instanceof RowView && b.slots !== null) {\n const lazy: Spec[] = b.plan.lazy;\n for (let k = 0; k < lazy.length; k++) {\n const made = b.bound?.[k];\n if (made !== undefined) binding(made);\n else add(lazy[k].kind, lazy[k].name, b.slots[2 * k] as Node, lazy[k].pattern!, b.row, lazy[k].kind === K_TEXT ? \"text\" : \"prop\");\n }\n }\n if (b.children !== null) for (const v of b.children) view(v);\n };\n const view = (v: ForView | IfView): void => {\n if (seen.has(v)) return;\n seen.add(v);\n if (v instanceof ForView) {\n // the list binding itself: v2 has one per `for`, on the anchor that replaced the template\n add(-1, \"for\", v.anchor, v.list.pattern, v.list.parentRow, \"for\");\n for (const rv of v.rowViews) block(rv);\n } else if (v.current !== null) block(v.current);\n };\n for (const bs of engine.rootBindings.values()) {\n for (const b of bs) {\n binding(b);\n if (b.chain !== null) view(b.chain);\n }\n }\n for (const l of engine.rootLists.values()) {\n if (l.view !== null) view(l.view);\n if (l.extra !== null) for (const v of l.extra) view(v);\n }\n return out;\n}\n\nlet ledgers = new WeakMap<Engine, Map<string, Entry>>();\n\n/** Reports the bindings added and removed since the last look. */\nfunction sync(engine: Engine): void {\n if (sink === null) return;\n const old = ledgers.get(engine);\n const now = live.has(engine) ? snapshot(engine, old) : new Map<string, Entry>();\n if (old !== undefined) for (const [k, e] of old) if (!now.has(k)) sink({ \"type\": \"state:binding-removed\", ...e });\n for (const [k, e] of now) if (old === undefined || !old.has(k)) sink({ \"type\": \"state:binding-added\", ...e });\n ledgers.set(engine, now);\n}\n\n// ---------------------------------------------------------------- the pulls\n\nfunction engineOf(root: Node): Engine {\n const e = byRoot.get(root);\n if (e === undefined) throw new Error(\"[@wcstack/state] devtools: no state tree on this root\");\n return e;\n}\n\nfunction summary(engine: Engine): Record<string, unknown> {\n const list = new Set<string>();\n const element = new Set<string>();\n const getter = new Set<string>();\n const setter = new Set<string>();\n for (const p of engine.patterns.all()) {\n for (let k = 1; k <= p.depth; k++) list.add(p.lists[k]!.path);\n if (p.last === \"*\") element.add(p.path);\n if (p.getter !== null) getter.add(p.path);\n if (p.setter !== null) setter.add(p.path);\n }\n const t = engine.target;\n return {\n \"rootNode\": engine.root,\n \"element\": engine.element,\n \"paths\": { \"list\": list, \"element\": element, \"getter\": getter, \"setter\": setter },\n \"commandTokenNames\": new Set(Object.keys(engine.commands)),\n \"eventTokenNames\": new Set(engine.events.keys()),\n \"staticDependency\": new Map(),\n \"dynamicDependency\": new Map(),\n \"watchPaths\": t.$watch !== null && typeof t.$watch === \"object\" ? new Set(Object.keys(t.$watch)) : null,\n \"keyedListPaths\": t.$listKeys !== null && typeof t.$listKeys === \"object\" ? new Set(Object.keys(t.$listKeys)) : null,\n };\n}\n\nfunction keyedSubscriptions(engine: Engine): Record<string, unknown>[] {\n const out: Record<string, unknown>[] = [];\n for (const p of engine.patterns.all()) {\n const subs = p.eqSubs;\n const lists = p.eqIndexWatchers?.length ?? 0;\n if ((subs === null || subs.size === 0) && lists === 0) continue;\n let rows = 0;\n if (subs !== null) for (const s of subs.values()) rows += s.size;\n let lastValue: unknown;\n try { lastValue = p.depth === 0 ? engine.readUntracked(p, null) : undefined; } catch { lastValue = undefined; }\n out.push({ \"path\": p.path, \"tracked\": false, \"rows\": rows, \"keys\": subs === null ? 0 : subs.size, \"lists\": lists, \"lastValue\": lastValue });\n }\n return out;\n}\n\nfunction createSource(): Source {\n return {\n \"id\": `state:${Math.random().toString(36).slice(2, 10)}`,\n \"kind\": \"state\",\n \"packageVersion\": VERSION,\n \"getStateElements\": () => [...live].map(summary),\n \"overlays\": () => [],\n \"keyedSubscriptions\": (root: Node) => keyedSubscriptions(engineOf(root)),\n \"keys\"(root: Node): string[] {\n const t = engineOf(root).target;\n return Object.keys(t).filter((k) => {\n if (k.includes(\"*\") || k[0] === \"$\") return false;\n const d = Object.getOwnPropertyDescriptor(t, k)!;\n return d.get !== undefined || typeof d.value !== \"function\";\n });\n },\n \"read\"(root: Node, path: string, indexes?: number[]): unknown {\n const el = engineOf(root).element as any;\n let v: unknown;\n el.createState(\"readonly\", (s: any) => { v = s.$resolve(path, indexes ?? []); });\n return v;\n },\n \"write\"(root: Node, path: string, value: unknown, indexes?: number[]): void {\n const el = engineOf(root).element as any;\n el.createState(\"writable\", (s: any) => { s.$resolve(path, indexes ?? [], value); });\n },\n \"_setSink\"(next: Sink | null): void {\n const attached = sink === null && next !== null;\n sink = next;\n // detached: the ledgers go — an attach after it is told every binding there, and none of\n // their nodes is held meanwhile\n if (next === null) ledgers = new WeakMap();\n // what the add-ons notice ($watch fired / threw / cut, a path that does not resolve), with the\n // tree it came from (`stateElement`): built only while a DevTools is attached\n hooks.noticed = next && ((engine, event) => sink?.({ ...event, \"stateElement\": engine.element }));\n // a DevTools that attaches late sees the bindings there already\n if (attached) queueMicrotask(() => { for (const e of live) sync(e); });\n },\n };\n}\n\n// ---------------------------------------------------------------- the hooks\n\nconst wrapped = new WeakSet<Token>();\n\nfunction wrapTokens(engine: Engine): void {\n const wrap = (t: Token, kind: \"command\" | \"event\"): void => {\n if (wrapped.has(t)) return;\n wrapped.add(t);\n const emit = t.emit;\n t.emit = (...args: unknown[]) => {\n if (sink !== null) sink({ \"type\": \"state:token-emit\", \"kind\": kind, \"tokenName\": t.name, \"args\": args, \"subscriberCount\": t.size, \"stateElement\": engine.element });\n return emit.apply(t, args);\n };\n };\n for (const t of Object.values(engine.commands)) wrap(t, \"command\");\n for (const t of engine.events.values()) wrap(t, \"event\");\n}\n\nconst batches = new WeakMap<Engine, Set<unknown>>();\n\nexport function devtoolsElement(engine: Engine, phase: string): void {\n if (phase === \"mounting\" || phase === \"reset\") wrapTokens(engine);\n if (phase === \"connected\") {\n if (live.has(engine)) return;\n live.add(engine);\n sink?.({ \"type\": \"state:element-registered\", \"rootNode\": engine.root, \"element\": engine.element });\n sync(engine);\n } else if (phase === \"disconnected\") {\n live.delete(engine);\n sync(engine);\n sink?.({ \"type\": \"state:element-unregistered\", \"rootNode\": engine.root, \"element\": engine.element });\n }\n}\n\nexport function devtoolsWritten(engine: Engine, p: Pattern, row: StateRow | null, old: unknown, value: unknown, direct: boolean): void {\n if (sink === null) return;\n const a = address(engine, p, p.depth === 0 ? null : row);\n let batch = batches.get(engine);\n if (batch === undefined) batches.set(engine, (batch = new Set()));\n batch.add(a);\n if (direct) sink({ \"type\": \"state:write\", \"absoluteAddress\": a, \"value\": value, \"oldValue\": old, \"hasOldValue\": true });\n}\n\nexport function devtoolsDrained(engine: Engine): void {\n if (sink === null) return;\n const batch = batches.get(engine);\n batches.delete(engine);\n if (batch !== undefined) sink({ \"type\": \"state:update-batch\", \"addresses\": batch });\n sync(engine);\n}\n\nexport function devtoolsFailed(_engine: Engine, error: unknown, b: Binding): void {\n sink?.({ \"type\": \"state:binding-apply-error\", \"path\": b.pattern.path, \"bindingType\": b.typeName(), \"error\": error });\n}\n\nexport function registerSource(): void {\n if (typeof document === \"undefined\" || document.documentElement?.hasAttribute(\"data-wcs-server\")) return;\n const g = globalThis as any;\n const registry = g[HOOK] ?? (g[HOOK] = createRegistry());\n if (registry[\"version\"] !== PROTOCOL) console.warn(`[@wcstack/state] devtools hook registry version ${registry[\"version\"]}, expected ${PROTOCOL}: keeping the existing one.`);\n registry[\"register\"](createSource());\n}\n","/**\n * The DevTools add-on (@wcstack/state/features/devtools): `@wcstack/devtools` over the hook\n * protocol v2 — see src/devtools/devtools.ts.\n */\nimport { chain, hooks, type Feature } from \"../hooks\";\nimport { devtoolsDrained, devtoolsElement, devtoolsFailed, devtoolsWritten, registerSource } from \"../devtools/devtools\";\n\nexport const devtools: Feature = {\n name: \"devtools\",\n hooks,\n install(): void {\n hooks.element = chain(hooks.element, devtoolsElement);\n hooks.written = chain(hooks.written, devtoolsWritten);\n hooks.drained = chain(hooks.drained, devtoolsDrained);\n hooks.failed = chain(hooks.failed, devtoolsFailed);\n registerSource();\n },\n};\nexport default devtools;\n","/**\n * Native element commands (the native-commands add-on): `command.<method>:` on an element with no\n * wc-bindable declaration — `<dialog data-wcs=\"command.showModal: $command.open\">` — so a state\n * opens a dialog, focuses an input or plays a video by emitting a token, never by reaching the\n * element (docs/state-engine-rewrite/native-commands.ja.md).\n */\nimport type { NativeCall } from \"../hooks\";\nimport { raise, M } from \"../messages\";\n\n/**\n * The methods a native element's `command.<method>:` may call, by tag (`*`: every element). None\n * writes HTML, an attribute or the tree, or changes a control's value without its `input` event\n * (the state would not see it). Decided by this table alone, not by what the element has: a\n * binding binds in every browser (and on the server) alike, and a method a browser lacks fails\n * when it is called. The tooling manifest publishes a copy as `nativeCommands`.\n */\nexport const NATIVE_COMMANDS: Readonly<Record<string, readonly string[]>> = {\n \"*\": [\"focus\", \"blur\", \"click\", \"scrollIntoView\", \"showPopover\", \"hidePopover\", \"togglePopover\"],\n \"dialog\": [\"show\", \"showModal\", \"close\", \"requestClose\"],\n \"form\": [\"requestSubmit\", \"checkValidity\", \"reportValidity\"],\n \"input\": [\"select\", \"setSelectionRange\", \"showPicker\", \"setCustomValidity\", \"checkValidity\", \"reportValidity\"],\n \"textarea\": [\"select\", \"setSelectionRange\", \"setCustomValidity\", \"checkValidity\", \"reportValidity\"],\n \"select\": [\"showPicker\", \"setCustomValidity\", \"checkValidity\", \"reportValidity\"],\n \"audio\": [\"play\", \"pause\", \"load\"],\n \"video\": [\"play\", \"pause\", \"load\"],\n};\n\n/** What a native `tag` may be commanded to run (its own row only: `<constructor>` reads no prototype). */\nexport const nativeCommandsOf = (tag: string): readonly string[] =>\n [...NATIVE_COMMANDS[\"*\"], ...(Object.hasOwn(NATIVE_COMMANDS, tag) ? NATIVE_COMMANDS[tag] : [])];\n\n/** `hooks.nativeCommand`: null for a custom element (it declares its commands); throws for a method outside the table. */\nexport function nativeCommand(el: Element, method: string): NativeCall | null {\n const tag = el.localName;\n if (tag.includes(\"-\")) return null;\n const allowed = nativeCommandsOf(tag);\n if (!allowed.includes(method)) raise(M.NativeNoCommand, [tag, method, allowed.join(\", \")], method, allowed);\n // an event's emit (`onclick: $command.x`: the event, then the list indexes) is no argument of a\n // native method — `close(event)` would set the dialog's returnValue to \"[object PointerEvent]\"\n return (target, args) => (target as any)[method](...(args[0] instanceof Event ? [] : args));\n}\n","import { define } from \"./element\";\nimport { installFeatures } from \"./hooks\";\nimport { ALL_FEATURES } from \"./features/all\";\n\n// the auto bundle is the full engine: the core and every add-on\ninstallFeatures(ALL_FEATURES);\ndefine();\n","/**\n * Every add-on: what `@wcstack/state` (`bootstrapState`) and the auto bundle install. A page\n * that installs only some imports `@wcstack/state/core` and `features/<name>` instead.\n */\nimport type { Feature } from \"../hooks\";\nimport { formats } from \"./formats\";\nimport { diagnostics } from \"./diagnostics\";\nimport { temporal } from \"./temporal\";\nimport { listKeys } from \"./list-keys\";\nimport { scopes } from \"./scopes\";\nimport { recursion } from \"./recursion\";\nimport { ssr } from \"./ssr\";\nimport { devtools } from \"./devtools\";\nimport { nativeCommands } from \"./native-commands\";\n\nexport const ALL_FEATURES: readonly Feature[] = [formats, diagnostics, temporal, listKeys, scopes, recursion, ssr, devtools, nativeCommands];\n","/**\n * The native-commands add-on (@wcstack/state/features/native-commands): `command.<method>:` on a\n * native element (README \"Native element commands\") — `showModal` / `close` on a `<dialog>`,\n * `focus` on an `<input>`, `play` / `pause` on a `<video>`, from the table in native/commands.ts.\n * Without it a native element's `command.` fails as before (`[wcs/token-misconfigured]`).\n */\nimport { hooks, type Feature } from \"../hooks\";\nimport { nativeCommand } from \"../native/commands\";\n\nexport const nativeCommands: Feature = {\n name: \"native-commands\",\n hooks,\n install(): void {\n hooks.nativeCommand = nativeCommand;\n },\n};\nexport default n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B,IAAc,CAAE7pB,SAAU,aAAcC,QAAS,EAAGgqB,SAC/F,EE8UEkpB,GACKpkB,KAAaprB,SAAS2mC,IAAWxb,GAAK92B,KAAK,IAAIgrB,QAAQsnB,IAC5D,IAAMtuB,EAAM/F,GAAOM,SAAS1Z,WACF,IAAtBytC,EAAS7wC,IAAIuiB,IAAoBsuB,EAAS9H,OAAOxmB,EAAK,cAAcuP,MACxEvvB,EAAMuzC,KAAOjF,EACf,CyB3XA9H","ignoreList":[]}
|
|
1
|
+
{"version":3,"names":["Pattern","constructor","path","last","parent","this","children","getter","setter","underGetter","dependents","sources","crossSources","slot","rootValue","UNSET","eqIndexWatchers","eqIndexKeys","indexWatchers","eqSubs","pinned","dead","markup","mark","dependentSet","Set","lists","slice","w","push","depth","length","tail","addDependent","has","add","dropDependent","delete","d","splice","indexOf","forget","clear","isUnder","ancestor","p","Symbol","DIRTY","FAILED","PatternTable","onCreate","byPath","Map","peek","get","i","lastIndexOf","set","all","values","drop","literalCache","parsePath","cached","literal","segs","split","indexes","s","c","charCodeAt","Number","pattern","join","parsed","size","StateRow","list","index","item","cache","view","bindings","alive","StateList","parentRow","arr","rows","extra","queued","stale","shared","EMPTY","hooks","chain","prev","fn","a","first","answered","r","handled","known","taken","installed","loadFeatures","state","names","$features","load","Array","isArray","missing","filter","n","requireFeature","feature","what","Error","raiseError","message","subject","candidates","explain","report","error","rest","reportError","console","cause","text","id","args","render","map","JSON","stringify","String","raise","Token","name","subscribers","subscribe","unsubscribe","emit","results","readNames","value","key","reserved","seen","TRANSITION_RUNNER_KEY","for","getTransitionRunner","source","candidate","globalThis","protocol","version","run","accepts","runTransition","mutate","types","runner","ELSE_KEYWORD","EVENT_TOKEN_NAMESPACE","CLASS_NAMESPACE","ATTR_NAMESPACE","INDEX_PARAM","NUMBER_LITERAL","parseFilterArgsWithLiterals","argsText","literals","current","inQuote","hasQuote","firstQuoteStart","lastQuoteEnd","flush","arg","startLimit","endLimit","trimStart","trimEnd","finalizeArg","quoted","test","toLiteral","char","trimFn","trim","outsideQuotes","found","quote","indexOfOutsideQuotes","splitOutsideQuotes","separator","parts","start","splitFilters","part","filterIOType","pos","filtersText","filters","filterTextList","sourceText","filterText","openParenIndex","closeParenIndex","pop","lastIndexOfOutsideQuotes","trailing","filterName","substring","includes","modifiers","parseFilters","cacheFilterInfos","recursionUnsupported","parseStatePart","statePart","stateAndPath","statePathName","isLoopRelative","startsWith","body","some","segment","segmentCount","checkPathLikeGetPathInfo","outFilters","DECLARATIONS","BEHAVIOR_KEYS","unbound","evals","upsert","m","k","make","v","newSet","newArray","twice","WeakMap","isThenable","then","sameValueZero","b","unsubEq","sub","dig","rowAt","row","ctxRow","ctx","Engine","target","strategy","slotCount","readonlyDepth","dropped","delegated","blockKey","element","errors","rendered","frames","depthNow","top","rootLists","rootBindings","queue","dirtyLists","staleLists","scheduled","draining","listsByArray","carried","held","inApply","unsettled","fedBack","codeWrote","feeding","unchainFn","renderedFn","rp","rr","drainFn","drain","deliverFn","handler","proxy","rootEqSubs","loose","api","$untracked","f","untracked","$eqIndex","level","watchIndex","read","g","watchers","listP","readUntracked","$eq","eq","$eqPath","keyPath","kp","$dependOn","resolve","track","$getAll","getAll","$setAll","options","setAll","$resolve","checkArity","rowOf","write","$postUpdate","resetRow","touched","mirror","rekeyEqUnder","landed","patterns","onPatternCreated","loadTarget","engine","getOwnPropertyDescriptor","_t","Reflect","configurable","receiver","t","dollar","bound","trap","Proxy","registerAccessors","o","Object","prototype","getPrototypeOf","getOwnPropertyNames","markupAccessor","findIndex","j","childList","l","sync","trySync","failAt","anchor","unfile","old","next","oe","ne","rowRemoved","end","byItem","indexChanged","reconcile","same","x","listSynced","schedule","keys","sel","before","after","invalidateUnder","onIndexChange","subs","e","was","idx","readData","readGetter","epoch","reads","Math","min","evalGetter","frame","outer","call","prune","unlink","sweep","parents","q","commands","subscribeEq","forSubtree","rekeyEqIndex","invalidate","occurrence","beforeWrite","callAt","guard","is","syncListsUnder","sharing","direct","suffix","dup","holdsTwice","land","mp","down","deps","up","forListsUnder","enqueueBound","ls","forAllLists","forRowsUnder","written","changed","onWrite","delegate","type","root","addEventListener","parentNode","cancelBubble","block","dispatch","reset","bs","enqueue","resetList","watchRendered","$behavior","mustache","directional","ns","$commandTokens","freeze","commandNamespace","events","deliver","tokens","$eventTokens","on","$on","entries","token","eventTokens","declare","indexesOf","out","unshift","fireEventToken","event","command","emitCommand","invoke","apply","slots","enqueueSlots","fv","rv","walkDependents","visit","visitGetter","forAllRows","getterReached","register","unregister","queueMicrotask","dropWork","cutLoop","max","paths","noticed","maxDepth","setTimeout","MAX_RENDER_CHAIN","pass","ran","update","owner","applyBinding","settled","pending","drained","fail","node","typeName","noteRendered","$renderedCallback","callHook","hook","$errorCallback","binding","failed","bindingType","kind","forMatches","walk","lp","targets","spread","exact","config","bindAttributeName","commentForPrefix","commentIfPrefix","commentElseIfPrefix","commentElsePrefix","tagNames","ssr","locale","document","documentElement","lang","enableContractAnalyzer","STRUCTURAL_BINDING_TYPE_SET","KEYWORDS_WITHOUT_MODIFIERS","EXPLICIT_PROPERTY_REJECTED_HEADS","parseBindTextsForElement","bindText","splitBindTexts","separatorIndex","propPart","keyword","stateResult","propName","propSegments","propModifiers","inFilters","propResult","propText","modifierParts","propModifiersText","parsePropPart","head","FORMATS_FILTER_NAMES","definitions","resolvedByKey","registerFilters","hasFilter","optionsRequired","fnName","optionMustBeNumber","valueMustBeNumber","valueMustBeDate","validateNumberString","isNaN","numberOption","requiredNumberOption","firstLiteral","opt","numeric","op","factory","arity","coreFilters","not","lt","le","gt","ge","falsy","truthy","boolean","pipe","fs","buildFilters","filterArgsKey","resolved","definition","unknownFilter","filterFn","resolveFilter","TRUSTED_TYPES_POLICY_SLOT","getTrustedTypesPolicy","isHtmlSink","prop","trustHtml","trustedTypes","isHTML","policy","create","createHTML","LEDGER_KEY","named","WeakSet","autoNaming","naming","namingLimit","bindableByClass","registryOf","el","customElementRegistry","customElements","whenDefined","attach","later","tag","localName","isConnected","cls","upgrade","decl","wcBindable","isInteger","properties","inputs","semantics","readBindable","cleanups","failSpec","attachProperty","spec","bd","input","init","outputOnly","Binding","K_CUSTOM","adopt","ro","detail","applying","authority","seed","snapshot","Promise","noBindable","BUBBLING","TYPE_NAMES","HOLD","initialOf","initial","checked","elementValue","applyTo","writeBack","cur","NaN","isContent","data","removeAttribute","SELECTED","innerHTML","classList","toggle","setAttribute","style","removeProperty","setProperty","reselect","Block","nodes","plan","lead","hits","nodePaths","nodeAt","contains","own","listener","headAt","insertBefore","ref","nextSibling","removeNodes","remove","removeContiguous","dispose","RowView","super","lazy","slotBinding","listFor","lastBlock","takeBlock","buildBlock","at","build","scratch","adopted","single","createDocumentFragment","fragment","cloneNode","childNodes","limit","nodeType","ledger","counter","assigned","warned","warn","nameBlock","specs","nested","ForView","iv","attachChain","branches","br","attachSpec","h","custom","bubbles","removeEventListener","attachEvent","method","nativeCommand","WeakRef","deref","attachCommand","prevent","preventDefault","stop","stopPropagation","attachEventToken","brow","exclude","attachSpread","hostBinding","attachCustomOrPlain","twoWay","IfView","rowViews","_n","viewOf","keep","firstChild","replaceChildren","views","src","Int32Array","anyKept","next0","Uint8Array","fill","tails","lo","hi","mid","lisKeep","frag","appendChild","bindAttr","blank","INITS","SYNCS","COMMAND_PREFIX","boundPattern","expandPath","loop","declared","isOuter","setsContent","notAfterIf","elementSpecs","mods","find","isInit","flags","handlerThrew","getAttribute","toLowerCase","isTwoWay","specFor","MUSTACHE","splitMustache","lastIndex","exec","ownerDocument","createTextNode","expr","textSpec","parseBindTextForEmbeddedNode","directive","chainAnchorText","readChain","walked","walkBindings","page","onFor","onIf","onElement","onText","anchorFor","createComment","replaceWith","ssrMark","child","hasAttribute","compilePlan","into","componentScope","COMMENT_BINDING","templateContent","createRange","selectNodeContents","content","cloneContents","template","asRow","importNode","stripInsignificantWhitespace","previousSibling","pathOf","used","shifts","isSlotKind","sort","NO_TEXT","strip","engines","mount","container","mountSubtree","subtree","range","BINDER_KEY","PENDING_KEY","TAKEN_KEY","early","bind","getRootNode","drainBinds","waiting","binder","getBinder","globals","pendingQueue","takenSet","flushPendingBinds","DirtyStrategy","loads","readyByRoot","enroll","getBindingsReady","els","any","initializePromise","connectedCallbackPromise","reject","HTMLElementBase","HTMLElement","WcsState","started","claimed","loaded","receiveInitial","resolveConnected","rejectConnected","catch","resolveInitialize","hasConnectedCallbackPromise","connectedCallback","connected","rerun","claim","lenient","ShadowRoot","loadState","built","disconnectedCallback","disconnected","setInitialState","receive","createState","mutability","callback","createStateAsync","querySelectorAll","script","parse","textContent","async","url","URL","baseURI","href","res","fetch","ok","status","json","default","loadSrc","querySelector","blocked","effectiveDirective","blob","createObjectURL","Blob","encodeURIComponent","revokeObjectURL","loadInnerScript","host","loading","other","flatMap","refs","registries","nullishPassthrough","valid","defaultLocale","Intl","getCanonicalLocales","STYLES","dateOptions","loc","zone","option","styleInvalid","DateTimeFormat","timeZone","two","padStart","registered","toFixed","explicit","toLocaleString","upper","toUpperCase","lower","capitalize","charAt","numberedOpts","opt2","opt1","padEnd","repeat","reverse","truncate","maxLength","round","optValue","pow","floor","ceil","percent","unit","date","format","dateStyle","Date","toLocaleDateString","time","timeStyle","toLocaleTimeString","datetime","ymd","getFullYear","getMonth","getDate","hms","getHours","getMinutes","getSeconds","mul","div","mod","abs","clamp","int","parseInt","float","parseFloat","defaults","fallback","coalesce","number","string","nullIfEmpty","currency","code","NumberFormat","supportedValuesOf","currencyInvalid","formats","install","editDistance","curr","cost","didYouMean","folded","best","bestDistance","distance","LINT_HINT","CODES","codeOf","MOVED","NAMESPACES","CSP_GUIDE","SENTENCES","modifier","where","given","allowed","over","sentence","LINT_CODES","GUIDES","RENAMED_FILTERS","inc","dec","fix","uc","lc","cap","rep","rev","pad","null","to","hasOwn","removedFilter","re","replace","_","due","findDescriptor","keysOf","wildcardForm","under","seg","done","todo","readers","wrote","byElement","rowGetter","loops","near","missingSegment","check","watch","note","wrapped","posting","declaredKeys","elementWrote","_row","_old","_value","_direct","wrappedTokens","loud","said","explained","toldThis","USES_THIS","toldRoots","describeState","secondRoot","phase","others","esc","trustedTypesReported","_engine","TypeError","property","warnedDetail","reason","hasOwnProperty","REMOVED_DECLARATIONS","REMOVED_APIS","$trackDependency","$untrackDependency","diagnostics","$scan","removedDeclarations","$recursion","endsWith","step","families","bad","why","RegExp","checkRecursion","onHandlersThis","recheck","post","watchPostUpdate","defineProperty","watchCommands","ROOT","INDEX_PATH","PROTOTYPE_NAMES","taskSeq","pinged","ping","nextTask","thisTask","MessageChannel","ch","port1","onmessage","unref","port2","postMessage","stack","WatchRuntime","watches","active","cutTask","reported","activate","prime","eachRow","hit","getterOf","deactivate","wp","batch","cut","real","compareRows","saved","chainCut","task","fresh","ia","ib","STATUS","ERROR","internalWrite","hasAccessorOrMethod","StreamRuntime","startAll","abortAll","restart","controller","abort","stopAll","eager","kept","untrack","checkArgs","ctrl","AbortController","consume","signal","live","aborted","put","acc","producer","chunk","fold","getReader","reader","cancel","asyncIterator","it","return","runtimes","rt","parseWatches","$watch","stream","$stream","def","parseStreams","temporal","keysByTarget","merging","SEGMENT","$listKeys","isPlain","proto","keyed","keyOf","merged","updates","changes","fp","listKeys","ORPHAN","wired","grafted","REJECTED","NOT_RUN","PREFIX","PATH_APIS","rootEngineCreated","graft","release","settle","callLifecycle","chroot","hydrated","prefix","chrootOf","defs","defineProperties","orphan","giveUp","claimVolume","problem","every","validPath","instances","byEngine","claimDcc","mode","streams","members","bindables","states","ensure","shadow","attachShadow","inner","ready","Dcc","stateElement","define","hostBindings","readonlyWiring","WIRED","hosts","mounts","UNWIRED","INERT","headOf","wiredInMarkup","heads","wireLate","scope","parentElement","E","warnOnce","surface","mountKey","whole","H","info","synth","C","component","hp","from","across","skip","mountUnder","through","reaches","reached","byP","byRow","exports","answer","exporting","exportAccessors","cp","warnShadowed","exporter","tree","touch","refresh","cpath","crow","crossed","hr","exportReached","attr","binds","matches","added","takesOver","reconnect","resume","methods","_self","bindMethods","independent","base","made","inPlace","wire","adoptScope","enumerable","$stateReadyCallback","broken","claimComponent","watchRoot","Element","mine","light","wiring","marked","wiredOnServer","onRootFailed","finally","original","star","ds","getOwnPropertyDescriptors","frozen","isFrozen","writable","melt","scopes","rootMoved","dccEngineCreated","dispatchEvent","CustomEvent","dccWritten","guardAncestorWrite","guardReadonlyMount","hasMounts","NAME","registering","checkPath","nodePath","suffixOf","nodeList","depthOf","ancestors","enter","listPath","rootP","declareRecursion","matchers","owners","had","created","wrap","guardExpansion","recursion","recursionSettled","VERSION","majorMinor","Ssr","stateData","templates","hydrateProps","getTemplate","verifyVersion","defineSsr","registry","BUILDER","isServer","isMark","startsMark","anchors","enginesByRoot","rawTexts","attrs","attributes","append","beside","anchorElement","region","blocks","branch","open","close","lastOf","visitView","visitBlock","RAW","RAW_ATTR","raw","protectTexts","ids","byAnchor","createTreeWalker","acceptNode","scoped","nextNode","cs","createElement","toString","svg","namespaceURI","createElementNS","doc","multiple","selectedIndex","disabled","toggleAttribute","selected","defaultValue","forms","previousElementSibling","IMPL","deferred","enters","nodesOf","flat","concat","prepare","decodeURIComponent","copy","replaceChild","isBlank","forEach","prepend","mend","undo","comments","currentNode","none","es","isIfAnchor","fits","nodeName","isFor","shift","snap","wirings","wiringOf","asIs","restore","legacy","edits","defaultChecked","Event","typed","hydrate","installBuilder","tags","HOOK","sink","address","absolutePathInfo","pathInfo","listIndex","nodeIds","nodeSeq","ledgers","now","idOf","replaceNode","absoluteAddress","engineOf","summary","rootNode","commandTokenNames","eventTokenNames","staticDependency","dynamicDependency","watchPaths","keyedListPaths","batches","devtoolsElement","tokenName","subscriberCount","wrapTokens","devtoolsWritten","oldValue","hasOldValue","devtoolsDrained","addresses","devtoolsFailed","NATIVE_COMMANDS","dialog","form","textarea","select","audio","video","nativeCommandsOf","features","installFeatures","listeners","_setSink","onEvent","onSourceRegistered","onSourceUnregistered","addListener","createRegistry","random","packageVersion","getStateElements","overlays","keyedSubscriptions","lastValue","tracked","attached","registerSource","installBinder"],"sources":["../src/pattern.ts","../src/list.ts","../src/hooks.ts","../src/parser/raiseError.ts","../src/messages.ts","../src/token.ts","../src/protocol/transitionRunner.ts","../src/parser/define.ts","../src/parser/parseFilterArgs.ts","../src/parser/utils.ts","../src/parser/parseFilters.ts","../src/parser/parseStatePart.ts","../src/engine.ts","../src/config.ts","../src/parser/parsePropPart.ts","../src/parser/types.ts","../src/parser/parseBindTextsForElement.ts","../src/filters/registry.ts","../src/filters/errorMessages.ts","../src/filters/options.ts","../src/filters/core.ts","../src/dom/filters.ts","../src/trustedTypes.ts","../src/dom/naming.ts","../src/dom/wc.ts","../src/dom/view.ts","../src/dom/plan.ts","../src/parser/parseBindTextForEmbeddedNode.ts","../src/dom/mount.ts","../src/protocol/binder.ts","../src/dom/binder.ts","../src/strategy/dirty.ts","../src/element.ts","../src/filters/formats.ts","../src/features/formats.ts","../src/diagnostics/guidance.ts","../src/diagnostics/messages.ts","../src/diagnostics/explain.ts","../src/features/diagnostics.ts","../src/temporal/watch.ts","../src/temporal/stream.ts","../src/features/temporal.ts","../src/features/list-keys.ts","../src/scopes/volume.ts","../src/scopes/dcc.ts","../src/scopes/component.ts","../src/features/scopes.ts","../src/recursion/recursion.ts","../src/features/recursion.ts","../src/version.ts","../package.json","../src/ssr/element.ts","../src/ssr/ssr.ts","../src/features/ssr.ts","../src/devtools/devtools.ts","../src/features/devtools.ts","../src/native/commands.ts","../src/auto.ts","../src/features/all.ts","../src/features/native-commands.ts"],"sourcesContent":["/**\n * Path patterns.\n *\n * A pattern is the authoring-level path with every list position written as `*`\n * (`data.*.label`). Each engine interns its patterns once; everything at run time\n * refers to the Pattern object, never to a path string. A concrete location is a\n * pattern plus the row that owns its last wildcard — there is no address object.\n */\n\nexport const WILDCARD = \"*\";\n\nexport class Pattern {\n readonly path: string;\n readonly parent: Pattern | null;\n readonly last: string;\n /** Number of `*` segments. 0 = a location on the root, n = a location inside a depth-n row. */\n readonly depth: number;\n /** Segments after the last `*` (all segments when depth is 0). Read from the row item / the root. */\n readonly tail: readonly string[];\n /** `lists[k]` is the list pattern whose rows the k-th wildcard (1-based) ranges over. */\n readonly lists: readonly (Pattern | null)[];\n children: Pattern[] = [];\n\n // --- filled in by the engine ---\n getter: (() => unknown) | null = null;\n setter: ((value: unknown) => void) | null = null;\n /** true when some proper ancestor is an accessor (read through it instead of walking data). */\n underGetter = false;\n /** Getter patterns whose evaluation read this pattern. */\n readonly dependents: Pattern[] = [];\n /** Patterns this getter read (union over its evaluations). */\n sources: Pattern[] = [];\n /** Sources read from a row other than the evaluating row's own chain (fan out on change). */\n crossSources: Set<Pattern> | null = null;\n /** Cache slot of a row-level getter on its rows. -1 when not a row-level getter. */\n slot = -1;\n /** Root-level getter cache (depth 0). */\n rootValue: unknown = UNSET;\n /** `$eqIndex(this path)` watchers: getters keyed on the index of their row at `level`. */\n eqIndexWatchers: { getter: Pattern; level: number }[] | null = null;\n /** On a list pattern: the `$eqIndex` registrations over its rows (re-keyed on reorder). */\n eqIndexKeys: { source: Pattern; getter: Pattern }[] | null = null;\n /** On a list pattern: getters that read the index (`$k`) of this list's rows. */\n indexWatchers: Pattern[] | null = null;\n /** `$eq(this path, key)` subscriptions: getter occurrences keyed by the value they wait for. */\n eqSubs: Map<unknown, Set<EqSub>> | null = null;\n /**\n * Something outside a path's read or write holds it (a binding, a list, an add-on: Engine.pattern):\n * never swept. A pattern only a path made (`this[\"users.\" + id]`) goes when it holds nothing (Engine.sweep).\n */\n pinned = false;\n /** Swept: out of the table (a later use of its path makes a new one). */\n dead = false;\n /** Its accessor is the engine's own for an index path (Engine.markupAccessor), not the author's or an add-on's. */\n markup = false;\n /** Scratch of Engine.prune: the evaluation that read it. */\n mark = 0;\n\n private readonly dependentSet = new Set<Pattern>();\n\n constructor(path: string, last: string, parent: Pattern | null) {\n this.path = path;\n this.parent = parent;\n this.last = last;\n // the parent's list table, plus our own when we are a wildcard segment\n const lists: (Pattern | null)[] = parent === null ? [null] : parent.lists.slice();\n const w = last === WILDCARD;\n if (w) lists.push(parent);\n this.depth = lists.length - 1;\n this.tail = w ? [] : parent === null ? [last] : [...parent.tail, last];\n this.lists = lists;\n }\n\n addDependent(getter: Pattern): void {\n if (this.dependentSet.has(getter)) return;\n this.dependentSet.add(getter);\n this.dependents.push(getter);\n getter.sources.push(this);\n }\n\n /** `getter` reads this no more (its side, `sources`, is the caller's). */\n dropDependent(getter: Pattern): void {\n this.dependentSet.delete(getter);\n const d = this.dependents;\n d.splice(d.indexOf(getter), 1);\n }\n\n /** A re-set replaced the state: forget its accessors and everything learned from them. */\n forget(): void {\n this.getter = null;\n this.setter = null;\n this.slot = -1;\n this.rootValue = UNSET;\n this.dependents.length = 0;\n this.dependentSet.clear();\n this.sources.length = 0;\n this.crossSources = null;\n this.eqIndexWatchers = null;\n this.eqIndexKeys = null;\n this.indexWatchers = null;\n this.eqSubs = null;\n }\n\n /** true when `this` is `ancestor` or lies under it. */\n isUnder(ancestor: Pattern): boolean {\n let p: Pattern | null = this;\n while (p !== null) {\n if (p === ancestor) return true;\n p = p.parent;\n }\n return false;\n }\n}\n\n/** One getter occurrence subscribed under a key of a `$eq` source. */\nexport interface EqSub {\n getter: Pattern;\n row: import(\"./list\").StateRow | null;\n}\n\n/** Sentinel for \"no cached value\". */\nexport const UNSET: unique symbol = Symbol(\"unset\") as never;\n/** Sentinel for \"cached value is stale\" (dirty strategy). */\nexport const DIRTY: unique symbol = Symbol(\"dirty\") as never;\n/**\n * Sentinel for \"evaluated, but it threw\" (or stale with its readers dropped by a cut drain):\n * someone read it, so a change of its sources must reach it.\n */\nexport const FAILED: unique symbol = Symbol(\"failed\") as never;\n\nexport class PatternTable {\n private readonly byPath = new Map<string, Pattern>();\n private readonly onCreate: ((p: Pattern) => void) | null;\n\n constructor(onCreate: ((p: Pattern) => void) | null = null) {\n this.onCreate = onCreate;\n }\n\n peek(path: string): Pattern | undefined {\n return this.byPath.get(path);\n }\n\n get(path: string): Pattern {\n let p = this.byPath.get(path);\n if (p !== undefined) return p;\n const i = path.lastIndexOf(\".\");\n const parent = i < 0 ? null : this.get(path.slice(0, i));\n p = new Pattern(path, path.slice(i + 1), parent);\n this.onCreate?.(p);\n this.byPath.set(path, p);\n if (parent) parent.children.push(p);\n return p;\n }\n\n all(): IterableIterator<Pattern> {\n return this.byPath.values();\n }\n\n drop(p: Pattern): void {\n this.byPath.delete(p.path);\n }\n}\n\n/**\n * A concrete path (`data.3.label`, `data.*.label`, `selectedIndex`) split into its\n * pattern and the explicit indexes it carries. `*` segments take their index from the\n * evaluation context, so they are returned as `-1`. A leading numeric segment is a key of\n * the root (`2024.total`), never an index: the root is not a list.\n */\nexport interface ParsedPath {\n pattern: string;\n indexes: number[] | null;\n}\n\nconst literalCache = new Map<string, ParsedPath>();\n\nexport function parsePath(path: string): ParsedPath {\n const cached = literalCache.get(path);\n if (cached !== undefined) return cached;\n let literal = true;\n const segs = path.split(\".\");\n const indexes: number[] = [];\n for (let i = 0; i < segs.length; i++) {\n const s = segs[i];\n const c = s.charCodeAt(0);\n if (i > 0 && c >= 48 && c <= 57) {\n literal = false;\n indexes.push(Number(s));\n segs[i] = WILDCARD;\n } else if (s === WILDCARD) indexes.push(-1);\n }\n if (!literal) return { pattern: segs.join(\".\"), indexes };\n const parsed: ParsedPath = { pattern: path, indexes: null };\n // literal paths (no explicit index) are few and reused: keep them — up to a bound, as a key built\n // from data (`this[\"users.\" + id]`) makes a new one each time\n if (literalCache.size > 4095) literalCache.clear();\n literalCache.set(path, parsed);\n return parsed;\n}\n","import type { Pattern } from \"./pattern\";\nimport type { Binding, ForView, RowView } from \"./dom/view\";\n\n/**\n * One element of a list, owned by its StateList. The row is the whole address of\n * everything under `list.*`: the value (`item`), the position (`index`), the getter\n * cache and the bindings that render it hang off this object — no ledger keyed by an\n * address. Dropping the row drops all of it.\n */\nexport class StateRow {\n readonly list: StateList;\n index: number;\n item: unknown;\n /** Getter cache by slot (row-level getters of this engine). */\n cache: unknown[] | null = null;\n /** The rendering of this row by its list's first for view (see StateList.extra for the others). */\n view: RowView | null = null;\n /**\n * Binding objects whose location is in this row (pattern depth = this row's depth), wherever\n * they render. Row views' slot bindings are not here: they are reached through the views.\n */\n bindings: Binding[] | null = null;\n /** `$eq` subscriptions of getters evaluated at this row (dropped with the row). */\n eqSubs: import(\"./engine\").EqEntry[] | null = null;\n /** Nested lists under this row, by list pattern. */\n children: Map<Pattern, StateList> | null = null;\n alive = true;\n\n constructor(list: StateList, index: number, item: unknown) {\n this.list = list;\n this.index = index;\n this.item = item;\n }\n}\n\nexport class StateList {\n readonly pattern: Pattern;\n readonly parentRow: StateRow | null;\n /** Depth of this list's rows (1 for a root list). */\n readonly depth: number;\n /** The array the rows were last reconciled against. */\n arr: unknown[] | null = null;\n rows: StateRow[] = [];\n /** The first for view that renders this list, if any (its row views are on row.view). */\n view: ForView | null = null;\n /** Further for views rendering the same list (each keeps its row views by row). */\n extra: ForView[] | null = null;\n /** Queued for a view update in the current drain. */\n queued = false;\n /** Its pattern reads through a getter that changed: re-synced at the next drain pass. */\n stale = false;\n /** Another list has the same array (a getter returning it, an index path): writes reach both. */\n shared = false;\n\n constructor(pattern: Pattern, parentRow: StateRow | null) {\n this.pattern = pattern;\n this.parentRow = parentRow;\n this.depth = pattern.depth + 1;\n }\n}\n\nexport interface ReconcileHooks {\n /** A kept row changed position. */\n indexChanged(row: StateRow): void;\n /** A row left the list (it marks it dead). */\n rowRemoved(row: StateRow): void;\n}\n\ntype Bucket = StateRow | StateRow[];\n\n/**\n * Brings `list.rows` in line with `next`, reusing rows by item identity.\n * Returns the previous rows (for $eqIndex re-keying) or null when nothing changed.\n * DOM is not touched here; the list's view catches up in the drain.\n */\nexport function reconcile(list: StateList, next: unknown, hooks: ReconcileHooks): StateRow[] | null {\n const arr = Array.isArray(next) ? next : EMPTY;\n if (arr === list.arr) return null;\n const old = list.rows;\n const n = arr.length;\n const o = old.length;\n const rows: StateRow[] = new Array(n);\n\n let start = 0;\n while (start < n && start < o && old[start].item === arr[start]) {\n rows[start] = old[start];\n start++;\n }\n let oe = o - 1;\n let ne = n - 1;\n while (oe >= start && ne >= start && old[oe].item === arr[ne]) {\n rows[ne] = old[oe];\n oe--;\n ne--;\n }\n\n if (start > oe) {\n for (let i = start; i <= ne; i++) rows[i] = new StateRow(list, i, arr[i]);\n } else if (start > ne) {\n for (let i = start; i <= oe; i++) hooks.rowRemoved(old[i]);\n } else {\n // a row whose item is where it was keeps its place: among equal items (a board of 0 / 1), handing\n // the rows out in order would move every one after the first change\n const end = oe < ne ? oe : ne;\n for (let i = start; i <= end; i++) if (old[i].item === arr[i]) rows[i] = old[i];\n const byItem = new Map<unknown, Bucket>();\n // filled from the end, so a bucket hands out its first row with pop(): shift() moves the whole\n // array, and over a long run of equal items the reconcile went quadratic\n for (let i = oe; i >= start; i--) {\n const row = old[i];\n if (i <= end && rows[i] === row) continue;\n const b = byItem.get(row.item);\n if (b === undefined) byItem.set(row.item, row);\n else if (Array.isArray(b)) b.push(row);\n else byItem.set(row.item, [b, row]);\n }\n for (let i = start; i <= ne; i++) {\n if (rows[i] !== undefined) continue;\n const item = arr[i];\n const b = byItem.get(item);\n let row: StateRow | undefined;\n if (b !== undefined) {\n if (Array.isArray(b)) {\n row = b.pop();\n if (b.length === 0) byItem.delete(item);\n } else {\n row = b;\n byItem.delete(item);\n }\n }\n rows[i] = row ?? new StateRow(list, i, item);\n }\n for (const b of byItem.values()) {\n if (Array.isArray(b)) for (const r of b) hooks.rowRemoved(r);\n else hooks.rowRemoved(b);\n }\n }\n\n // positions: only rows from `start` on can have moved\n for (let i = start; i < n; i++) {\n const row = rows[i];\n if (row.index !== i) {\n row.index = i;\n hooks.indexChanged(row);\n }\n }\n list.rows = rows;\n list.arr = arr;\n return old;\n}\n\n/** What a list whose value is not an array reconciles against (engine: an index there is a key). */\nexport const EMPTY: unknown[] = [];\n","/**\n * The places the core calls into add-ons (docs/state-engine-rewrite/addons-plan.ja.md §1.2).\n *\n * Add-ons ship as separate entries of the same build as the core (`features/*`): they reach\n * the core's internals directly, and the core only calls out through these slots. A slot is\n * empty until an installed feature fills it (the object starts with none: a list of null slots\n * would be the core's bytes), so a page without the feature pays one `?.` check. A feature\n * restoring a slot may set it to null.\n * Slots are added with the first feature that needs them; several features share one through\n * chain / first. The slots `element` and `detail` keep their names (a DevTools-facing field and a DOM\n * name share them); the others are shortened by the build. An empty slot is read through\n * Object.prototype: a page that polluted it (a value under `element`, say) breaks the core loudly\n * there, as it does wherever the core reads a plain object's keys (`$behavior`); not defended.\n */\nimport type { Engine } from \"./engine\";\nimport type { Pattern } from \"./pattern\";\nimport type { StateList, StateRow } from \"./list\";\nimport type { Binding, RowPlan, Spec } from \"./dom/view\";\n\nexport interface Hooks {\n /** Diagnostics: extra text for an error message (did-you-mean, lint pointer, how to fix). */\n explain?: ((message: string, subject?: string, candidates?: Iterable<string>) => string) | null;\n /** Diagnostics: the full sentence of a numbered core message (`src/messages.ts`). */\n render?: ((id: number, args: readonly unknown[]) => string) | null;\n /**\n * A write before it is applied (`element`: an element wrote it back, not code); true = the\n * add-on handled it ($listKeys, a read-only mount dropping an element's write).\n */\n beforeWrite?: ((engine: Engine, p: Pattern, row: StateRow | null, value: unknown, element: boolean) => boolean) | null;\n /** A write landed: `direct` for a data write (then `old` is the value before, `value` the new one). */\n /** `element`: an element wrote it (a binding's write-back or its initial value), not code. */\n written?: ((engine: Engine, p: Pattern, row: StateRow | null, old: unknown, value: unknown, direct: boolean, element?: boolean) => void) | null;\n /** A change reached a getter occurrence whose cached value was current (it may now differ). */\n getterReached?: ((engine: Engine, g: Pattern, row: StateRow | null) => void) | null;\n /** A list was reconciled with a new value; `old` are its rows before. */\n listSynced?: ((engine: Engine, list: StateList, old: StateRow[]) => void) | null;\n /** A drain ended (after its report and `$renderedCallback`). */\n drained?: ((engine: Engine) => void) | null;\n /** A state object was received (construction, or a re-set before it replaces the old one). */\n declare?: ((engine: Engine, target: Record<string, any>) => void) | null;\n /**\n * A root engine's lifecycle: \"mounting\" (created, its page not bound yet), \"back\" (its `<wcs-state>`\n * connected again, before `$connectedCallback` runs again: it holds its root again, unless another\n * one bound it meanwhile), \"connected\" (after `$connectedCallback`, and on reconnect), \"disconnected\",\n * \"reset\" (after a re-set).\n */\n element?: ((engine: Engine, phase: \"mounting\" | \"back\" | \"connected\" | \"disconnected\" | \"reset\") => void) | null;\n /**\n * A `<wcs-state>` an add-on takes over instead of it becoming a root (a volume, a DCC\n * definition): asked when it connects; the core then only loads its state.\n */\n claim?: ((el: HTMLElement, root: Node) => Claimed | null) | null;\n /** A `$` name the core does not know. */\n dollar?: ((engine: Engine, key: string) => unknown) | null;\n /** A binding failed to apply (reported after the drain, before `$errorCallback` / the console). */\n failed?: ((engine: Engine, error: unknown, binding: Binding) => void) | null;\n /**\n * A plain property binding on a custom element, made and not yet registered or applied (a\n * component mount's wiring, `state.x: path`); true = an add-on took it over.\n */\n hostBinding?: ((binding: Binding, ro: boolean) => boolean) | null;\n /** An element whose content an add-on binds (a Light DOM component): the walker leaves it. */\n componentScope?: ((el: Element) => boolean) | null;\n /**\n * The page walker replaced a structural template with its anchor (`source` is the template),\n * bound a mustache text node (`source` is its expression), or is about to bind an element\n * (`source` is its specs, which the hook may take some out of): SSR records the first two, and\n * on the server leaves `outerHTML:` to the client.\n */\n ssrMark?: ((engine: Engine, node: Node, source: Element | string | Spec[]) => void) | null;\n /**\n * A block is about to be cloned from `plan` for the view anchored at `anchor`: an add-on may\n * hand over existing nodes instead (SSR hydration) — the block's top-level nodes, already where\n * the block renders (the view inserts nothing), with the plan's nodes in them in `plan.scratch`.\n */\n adopt?: ((plan: RowPlan, anchor: Node, isFor: boolean) => ChildNode[] | null) | null;\n /**\n * A Light DOM component's engine is about to bind `root` (its host): SSR hands over the server's\n * nodes there too; the function returned is called when the walk is done.\n */\n adoptScope?: ((root: Node, engine: Engine) => (() => void) | null) | null;\n /** A path a binding (or, with `watch`, a `$watch` key) names: diagnostics checks it exists. */\n declared?: ((engine: Engine, p: Pattern, watch?: boolean) => void) | null;\n /** `<wcs-state>` was defined in `registry`: an add-on defines its own tags there (`<wcs-ssr>`). */\n tags?: ((registry: CustomElementRegistry) => void) | null;\n /** A wc-bindable property's event read with the default getter (`e.detail`): diagnostics checks its shape. */\n detail?: ((el: Element, name: string, detail: unknown) => void) | null;\n /** The handler `path` of a delegated `on<type>:` threw (reported already): diagnostics says when `currentTarget` is why. */\n handlerThrew?: ((engine: Engine, path: string, type: string) => void) | null;\n /**\n * `command.<method>:` on an element with no wc-bindable declaration: how a native element's\n * method is called (native-commands), or null for a custom element. The add-on throws for a\n * method a native element may not be commanded to run.\n */\n nativeCommand?: ((el: Element, method: string) => NativeCall | null) | null;\n /** The split auto entry: loads and installs add-ons of its build by name (a state's `$features`). */\n load?: ((names: string[]) => Promise<void>) | null;\n /**\n * An event an add-on (or the core) reports for the DevTools protocol (a `$watch` handler fired or\n * threw, a `$watch` chain or an update loop cut, a path that does not resolve): `event` is the\n * protocol's payload, its keys quoted (`{ \"type\": \"state:watch-fired\", \"path\": … }`). Called as\n * `hooks.noticed?.(engine, {…})`, the payload is built only while the slot is filled.\n */\n noticed?: ((engine: Engine, event: Record<string, unknown>) => void) | null;\n}\n\n/** Calls a native element's command method with what the token was emitted with. */\nexport type NativeCall = (target: Element, args: unknown[]) => unknown;\n\n/** What an add-on does with a `<wcs-state>` it claimed. */\nexport interface Claimed {\n /** Where the state comes from, when not from the element's own sources. */\n load?(): Promise<Record<string, any>>;\n /**\n * The loaded state; `connectedCallbackPromise` resolves when this is done, and `built` is called\n * once its bindings are built (before `$connectedCallback`: getBindingsReady resolves then, as for a\n * root). When it (or the load) throws, the core reports the failure and rejects the promise with\n * it — a DCC definition, a component mount: 3.x's README promises it for their configuration\n * errors, and 4.0 also rejects where 3.x did not (a component whose root failed: 3.x left it\n * unsettled; a second mount in one scope: 3.x resolved it) — or resolves it, for a lenient claim.\n */\n start(state: Record<string, any>, built: () => void): Promise<void> | void;\n /** A failure resolves `connectedCallbackPromise` instead (a volume settles without grafting, as 3.x). */\n lenient?: boolean;\n connected(): void;\n disconnected(): void;\n /** `setInitialState` after the start. */\n reset(state: Record<string, any>): void;\n}\n\nexport const hooks: Hooks = {};\n\ntype HookFn = (...args: any[]) => any;\n\n/*\n * A feature fills a slot by assigning it (`hooks.written = chain(hooks.written, fn)`), never by\n * its name as a string: the slot names are shortened by the build (mangle.mjs) like any internal\n * property.\n */\n\n/** A slot several features share: `fn` runs after whatever is there. */\nexport function chain<F extends HookFn>(prev: F | null | undefined, fn: F): F {\n return prev == null ? fn : ((...a: unknown[]) => { prev(...a); fn(...a); }) as F;\n}\n\n/** A slot whose first answer wins (`answered` tells one): `fn` is asked when what is there does not answer. */\nexport function first<F extends HookFn>(answered: (r: unknown) => boolean, prev: F | null | undefined, fn: F): F {\n return prev == null ? fn : ((...a: unknown[]) => { const r = prev(...a); return answered(r) ? r : fn(...a); }) as F;\n}\n\n/** `beforeWrite`: the first feature that handles the write. */\nexport const handled = (r: unknown): boolean => r === true;\n/** `dollar`: the first feature that knows the `$` name (a value, possibly null or false). */\nexport const known = (r: unknown): boolean => r !== undefined;\n/** `claim`: the first feature that takes the `<wcs-state>`. */\nexport const taken = (r: unknown): boolean => r != null;\n\n/** An add-on entry: `installFeatures([temporal, diagnostics])` before the state is defined. */\nexport interface Feature {\n readonly name: string;\n /** The slots of the build it comes from: it fills only those (the core checks they are its own). */\n readonly hooks: object;\n install(): void;\n}\n\nconst installed = new Set<string>();\n\nexport function installFeatures(features: readonly Feature[]): void {\n for (const f of features) {\n if (installed.has(f.name)) continue;\n // An add-on of another copy of the engine — another version (a vendor directory replaced in place),\n // or the same files under another URL (esm.run) — fills that copy's slots: its name would pass\n // requireFeature, and a `$watch` would never run, without a word (docs/seam-apps.md, prod-booking)\n if (f.hooks !== hooks) {\n throw new Error(`[@wcstack/state] [wcs/feature-foreign] The add-on \"${f.name}\" is from another copy of @wcstack/state (another version, or another URL): load the core and its add-ons from one build`);\n }\n installed.add(f.name);\n f.install();\n }\n}\n\n/**\n * A state's `$features` before its engine is made: the missing add-ons, loaded where an entry can\n * load them (`hooks.load`); undefined when there is nothing to wait for. The engine then checks\n * every name (a bundle or the full build only checks).\n */\nexport function loadFeatures(state: Record<string, any>): Promise<void> | undefined {\n const names = state.$features;\n if (hooks.load != null && Array.isArray(names)) {\n const missing = names.filter((n) => !installed.has(n));\n if (missing.length > 0) return hooks.load(missing);\n }\n}\n\n/** The barrier: a declaration that needs a feature the page did not install. */\nexport function requireFeature(feature: string, what: string): void {\n if (!installed.has(feature)) {\n throw new Error(`[@wcstack/state] [wcs/feature-not-installed] ${what} needs the add-on @wcstack/state/features/${feature}`);\n }\n}\n","import { hooks } from \"../hooks\";\n\n/**\n * Throws `[@wcstack/state] <message>`. The core's messages state the fact (a number and values); the\n * diagnostics add-on, when installed, appends the guidance (the nearest of `candidates` to\n * `subject`, how to fix it, the lint pointer).\n */\nexport function raiseError(message: string, subject?: string, candidates?: Iterable<string>): never {\n throw new Error(`[@wcstack/state] ${message}${hooks.explain?.(message, subject, candidates) ?? \"\"}`);\n}\n\n/**\n * Reports an error the engine caught or found — a getter, a filter, a handler or a callback of the\n * page that threw, a `<wcs-state>` that failed to initialize, an update loop cut — through the\n * platform's `reportError()`, so the page's error handlers (`window.onerror`, an `error` listener)\n * see it as an uncaught error, and the console shows it. A production error reporter heard none of\n * them when they went to `console.error` (docs/seam-apps.md, prod-booking). `message` says where\n * (the element, the binding): the reported Error carries both, with the original as its `cause`.\n * Where there is no `reportError()` (happy-dom, Node) it is `console.error` with the arguments as\n * before.\n */\nexport function report(error: unknown, message?: string, ...rest: unknown[]): void {\n if (typeof reportError !== \"function\") console.error(...(message === undefined ? [error] : [message, error]), ...rest);\n else reportError(message === undefined ? error : new Error(`${message} ${error}`, { cause: error }));\n}\n","/**\n * The core's messages, by number. The prose lives in the diagnostics add-on\n * (`src/diagnostics/messages.ts`); without it a message reads `[@wcstack/state] #108 \"a|b(\"` —\n * the message number and the values it would have shown. With it (the full `auto` bundle installs\n * it) the message is the code shared with lint and the VS Code extension and the full sentence\n * (`[wcs/binding-syntax] Invalid filter format: …`), followed by the guidance.\n *\n * The hundreds of a number name its code (the diagnostics add-on's `CODES`, in the core up to\n * 4.0.0-rc.3): 1xx binding-syntax, 2xx template-syntax, …; 1–99 carry no code. Numbers are only\n * ever added, so a number read on a page keeps its meaning across versions. `M` is a const enum:\n * the build inlines the numbers.\n *\n * Kept as full text in the core, not numbered: the barriers a page without add-ons meets on\n * purpose (`[wcs/feature-not-installed]`, a formatting filter without the formats add-on).\n */\nimport { hooks } from \"./hooks\";\nimport { raiseError } from \"./parser/raiseError\";\n\nexport const enum M {\n // no code\n ScanRemoved = 1,\n GetterWithoutSetter = 2,\n NoRow = 3,\n ParentNotObject = 4,\n NotAMethod = 5,\n GetAllNoCommonLevel = 6,\n EqIndexNoRow = 7,\n Readonly = 8,\n SetAllNeedsIndexes = 9,\n SetAllSpreadLength = 10,\n DrainNotSettled = 11,\n BindingFailed = 12,\n LoadFailed = 13,\n ElementFailed = 14,\n NotInitialized = 15,\n NoScript = 16,\n TokenSubscriberThrew = 17,\n TokenListNotArray = 18,\n TokenEntryEmpty = 19,\n TokenEntryReserved = 20,\n TokenEntryDuplicated = 21,\n OnNotObject = 22,\n OnEntryUndeclared = 23,\n OnEntryNotFunction = 24,\n NamingLimit = 25,\n FilterOptionsRequired = 26,\n FilterOptionNotNumber = 27,\n FilterValueNotNumber = 28,\n FilterValueNotDate = 29,\n FilterValueNotArray = 30,\n DirectionalSyncDisabled = 31,\n SelectorRemoved = 32,\n ModifierUnknown = 33,\n ModifierTwice = 34,\n ModifierValue = 35,\n EventInitNone = 36,\n InitUnsupported = 37,\n MemberUndeclared = 38,\n InitIncompatible = 39,\n SyncConnectNeedsOutput = 40,\n RenderChain = 41,\n InlineBlocked = 42,\n InlineFailed = 43,\n OptionInvalid = 44,\n BehaviorChanged = 45,\n FeaturesNotArray = 46,\n SecondRoot = 47,\n LocaleInvalid = 48,\n InitFailed = 49,\n ConnectedFailed = 50,\n DisconnectedFailed = 51,\n FilterStyleInvalid = 52,\n FilterCurrencyInvalid = 53,\n FilterTimeZoneInvalid = 54,\n // [wcs/binding-syntax]\n BindTextNoColon = 101,\n StructuralTakesNoModifiers = 102,\n ElseTakesNoValue = 103,\n SpreadNoPath = 104,\n SpreadNoFilters = 105,\n LeadingDotNamespace = 106,\n UnterminatedQuote = 107,\n FilterUnclosed = 108,\n FilterUnopened = 109,\n FilterParenOrder = 110,\n FilterTrailing = 111,\n FilterEmpty = 112,\n FilterNameHasModifiersInput = 113,\n FilterNameHasModifiersOutput = 114,\n OneModifierList = 115,\n NoPropertyName = 116,\n TooManySegments = 117,\n EmptySegment = 119,\n UnsafeSegment = 120,\n ForNoFilters = 121,\n NamespaceNeedsName = 122,\n // [wcs/template-syntax]\n StructuralNotSingle = 201,\n ElseWithoutIf = 202,\n OuterInTemplate = 203,\n TemplateHandedOver = 204,\n // [wcs/binding-path-missing]\n PathMissing = 301,\n // [wcs/binding-type-expectation]\n ClassNeedsBoolean = 401,\n // [wcs/filter-unknown]\n FilterUnknown = 501,\n // [wcs/filter-arity]\n FilterTooFewArgs = 601,\n FilterTooManyArgs = 602,\n // [wcs/getter-cycle]\n GetterCycle = 701,\n // [wcs/getter-depth-exceeded]\n GetterDepth = 801,\n // [wcs/index-arity]\n IndexArityExact = 901,\n IndexArityAtMost = 902,\n // [wcs/index-param-range]\n IndexParamRange = 1001,\n // [wcs/recursion-unsupported]\n RecursionUnsupported = 1101,\n // [wcs/token-misconfigured]\n CommandRightSide = 1201,\n NoBindable = 1202,\n NoCommand = 1203,\n NoProperty = 1204,\n NativeNoCommand = 1205,\n // [wcs/token-undeclared]\n EventTokenUndeclared = 1301,\n CommandTokenUndeclared = 1302,\n // [wcs/wildcard-rank]\n WildcardNoLoop = 1401,\n WildcardRelative = 1402,\n WildcardOtherList = 1403,\n // [wcs/spread-no-bindable]\n SpreadNoBindable = 1501,\n // [wcs/declaration-alias]\n DeclarationRemoved = 1601,\n // [wcs/name-alias]\n ApiRemoved = 1701,\n}\n\n/** A message without the `[@wcstack/state]` prefix: the code and the full sentence with diagnostics, else the number and the values. */\nexport function text(id: M, args: readonly unknown[] = []): string {\n return hooks.render?.(id, args) ?? `#${id}${args.map((a) => ` ${typeof a === \"string\" ? JSON.stringify(a) : String(a)}`).join(\"\")}`;\n}\n\n/** Throws message `id` (`subject` / `candidates` feed the diagnostics add-on's did-you-mean). */\nexport function raise(id: M, args?: readonly unknown[], subject?: string, candidates?: Iterable<string>): never {\n raiseError(text(id, args), subject, candidates);\n}\n","/**\n * The command-token / event-token pub/sub primitive (the same shape as @wcstack/state's\n * `Token`). A subscriber that throws is reported and the others still receive the call.\n */\nimport { raise, M, text } from \"./messages\";\nimport { report } from \"./parser/raiseError\";\n\nexport type TokenSubscriber = (...args: unknown[]) => unknown;\n\nexport class Token {\n readonly name: string;\n private readonly subscribers = new Set<TokenSubscriber>();\n\n constructor(name: string) {\n this.name = name;\n }\n\n get size(): number {\n return this.subscribers.size;\n }\n\n subscribe(fn: TokenSubscriber): () => void {\n this.subscribers.add(fn);\n return () => {\n this.subscribers.delete(fn);\n };\n }\n\n unsubscribe(fn: TokenSubscriber): boolean {\n return this.subscribers.delete(fn);\n }\n\n emit(...args: unknown[]): unknown[] {\n const results: unknown[] = [];\n for (const fn of this.subscribers) {\n try {\n results.push(fn(...args));\n } catch (error) {\n results.push(undefined);\n report(error, `[@wcstack/state] ${text(M.TokenSubscriberThrew, [this.name])}`);\n }\n }\n return results;\n }\n}\n\nfunction readNames(value: unknown, key: string, reserved?: string): string[] {\n if (value === undefined) return [];\n if (!Array.isArray(value)) raise(M.TokenListNotArray, [key]);\n const seen = new Set<string>();\n for (const name of value) {\n if (typeof name !== \"string\" || name === \"\") raise(M.TokenEntryEmpty, [key]);\n if (name === reserved) raise(M.TokenEntryReserved, [key, name, reserved]);\n if (seen.has(name)) raise(M.TokenEntryDuplicated, [key, name]);\n seen.add(name);\n }\n return value as string[];\n}\n\n/**\n * `$commandTokens` → the frozen `$command` namespace (name → Token). On a re-set, a name\n * the previous state declared keeps its token: elements subscribed to it keep receiving.\n */\nexport function commandNamespace(target: Record<string, any>, prev?: Readonly<Record<string, Token>>): Readonly<Record<string, Token>> {\n const ns: Record<string, Token> = {};\n for (const name of readNames(target.$commandTokens, \"$commandTokens\", \"$command\")) ns[name] = prev?.[name] ?? new Token(name);\n return Object.freeze(ns);\n}\n\n/**\n * `$eventTokens` + `$on` → name → Token, with each `$on` handler subscribed as\n * `(state, event, ...listIndexes)` through `deliver`.\n */\nexport function eventTokens(\n target: Record<string, any>,\n deliver: (handler: (...args: unknown[]) => unknown, args: unknown[]) => unknown,\n): Map<string, Token> {\n const tokens = new Map<string, Token>();\n for (const name of readNames(target.$eventTokens, \"$eventTokens\")) tokens.set(name, new Token(name));\n const on = target.$on;\n if (on === undefined) return tokens;\n if (on === null || typeof on !== \"object\") raise(M.OnNotObject);\n for (const [name, handler] of Object.entries(on)) {\n const token = tokens.get(name);\n if (token === undefined) raise(M.OnEntryUndeclared, [name]);\n if (typeof handler !== \"function\") raise(M.OnEntryNotFunction, [name]);\n token.subscribe((...args) => deliver(handler as (...a: unknown[]) => unknown, args));\n }\n return tokens;\n}\n","// ===========================================================================\n// AUTO-GENERATED FILE - DO NOT EDIT.\n// Generated from /protocol/transition-runner.ts by scripts/sync-protocol-types.mjs.\n// Run `node scripts/sync-protocol-types.mjs` after editing the source.\n// ===========================================================================\n\n// transition-runner protocol — how a package that mutates the DOM hands that\n// mutation to whoever is arbitrating view transitions on the page.\n//\n// @wcstack/state and @wcstack/router must not depend on @wcstack/view-transition\n// (zero runtime dependencies, independently publishable), so the arbiter installs\n// itself on a well-known global symbol and the participants look it up lazily.\n// No arbiter installed means the mutation is invoked directly, synchronously —\n// byte-for-byte the behavior these packages had before the protocol existed.\n//\n// docs/view-transition-design.md §4 is the normative description.\n//\n// SINGLE SOURCE OF TRUTH: edit only this file (/protocol/transition-runner.ts), then run\n// `node scripts/sync-protocol-types.mjs` to regenerate the per-package copies\n// (packages/<pkg>/src/protocol/transitionRunner.ts). Those copies are generated — do not edit them.\n\n/**\n * Global key the arbiter installs itself under. `Symbol.for` so independently\n * loaded copies of this file (two CDN bundles on one page) still agree.\n */\nexport const TRANSITION_RUNNER_KEY = Symbol.for(\"wcstack.transition-runner\");\n\n/** Who is asking. Backs the arbiter's `for=` participant gate. */\nexport type TransitionSource = \"router\" | \"state\";\n\n/** `view-transition-name` assignment policy the arbiter declares for participants. */\nexport type TransitionNaming = \"manual\" | \"auto\";\n\nexport interface IWcsTransitionRunOptions {\n /** Participant id, for the `for=` gate and for diagnostics. */\n readonly source?: string;\n /** Transition types, where the environment supports `startViewTransition({ types })`. */\n readonly types?: readonly string[];\n}\n\nexport interface IWcsTransitionRunner {\n readonly protocol: \"wcs-transition-runner\";\n /** Integer protocol version. All versions >= 1 are participant-compatible. */\n readonly version: number;\n /** `\"auto\"` licenses a participant to assign `view-transition-name` itself. */\n readonly naming: TransitionNaming;\n /** Upper bound on auto-assigned names; past it a participant stops naming. */\n readonly namingLimit: number;\n /** Whether this participant animates at all. */\n accepts(source: string): boolean;\n /**\n * Invoke `mutate` inside a view transition when one is possible.\n *\n * Contract (docs/view-transition-design.md §4):\n * - `mutate` is invoked exactly once, whatever happens to the transition.\n * - The promise resolves once `mutate` has run — never waits for the animation.\n * - When no transition is started, `mutate` runs synchronously inside `run()`.\n * - It rejects only if `mutate` threw.\n */\n run(mutate: () => void, options?: IWcsTransitionRunOptions): Promise<void>;\n}\n\n/**\n * The installed arbiter, or null when there is none, it speaks a version this\n * reader does not, or it does not accept this participant.\n *\n * Looked up on every call rather than cached: the tag can be added, removed, or\n * reconfigured at any point in a page's life, and a stale cache would either\n * animate what the author just switched off or miss what they switched on.\n */\nexport function getTransitionRunner(source: string): IWcsTransitionRunner | null {\n const candidate = (globalThis as Record<symbol, unknown>)[TRANSITION_RUNNER_KEY] as\n | IWcsTransitionRunner\n | undefined;\n if (candidate === undefined || candidate === null) return null;\n if (candidate.protocol !== \"wcs-transition-runner\") return null;\n if (typeof candidate.version !== \"number\" || candidate.version < 1) return null;\n if (typeof candidate.run !== \"function\") return null;\n if (typeof candidate.accepts !== \"function\" || !candidate.accepts(source)) return null;\n return candidate;\n}\n\n/**\n * Run `mutate` under the installed arbiter, or directly when there is none.\n *\n * Returns `undefined` in the no-arbiter case instead of a resolved promise: the\n * state drain calls this on every batch, and awaiting is a caller's choice, not\n * an allocation the common path should pay for. `await` accepts both.\n */\nexport function runTransition(\n source: string,\n mutate: () => void,\n types?: readonly string[],\n): Promise<void> | undefined {\n const runner = getTransitionRunner(source);\n if (runner === null) {\n mutate();\n return undefined;\n }\n return runner.run(mutate, { source, types });\n}\n","/**\n * Constants of the `data-wcs` binding grammar, copied from `@wcstack/state`\n * (`src/define.ts` / `src/errorGuidance.ts`). The values are the syntax contract\n * (`[prop][#mod]: [path][|filter...]`) and must stay identical to the current engine.\n */\n\n/** Path segment delimiter. */\nexport const DELIMITER = '.';\n/** Separator between the bindings of one attribute value. */\nexport const BINDING_SEPARATOR = ';';\n/** Separator between the left side (property) and the right side (path). */\nexport const PROP_VALUE_SEPARATOR = ':';\n/** Separator between the property and its modifier list. */\nexport const MODIFIER_SEPARATOR = '#';\n/** Separator of the filter pipeline. */\nexport const FILTER_SEPARATOR = '|';\n\nexport const ELSE_KEYWORD = 'else';\nexport const SPREAD_PROP = '...';\nexport const EVENT_PROP_PREFIX = 'on';\nexport const EVENT_TOKEN_NAMESPACE = 'eventToken';\n/** `<wcs-state mount>` left side `state.<key>: path` (volume injection). */\nexport const VOLUME_INJECTION_PROP = 'state';\nexport const COMMAND_NAMESPACE = 'command';\nexport const CLASS_NAMESPACE = 'class';\nexport const ATTR_NAMESPACE = 'attr';\nexport const STYLE_NAMESPACE = 'style';\n\n/**\n * Segment-count ceiling of one path. The current engine enforces it in `getPathInfo`\n * (first intern only) with a `[wcs/binding-syntax]` diagnostic; the parser port keeps the\n * same check inline on the string.\n */\nexport const MAX_PATH_SEGMENTS = 512;\n\n/** `$1` … `$128`, no leading zero: a loop index parameter (anything else after the `$` is not one). */\nexport const INDEX_PARAM = /^\\$[1-9]\\d{0,2}$/;\nexport const MAX_INDEX_PARAM = 128;\n\n/** Recursive wildcard — only meaningful in `$recursion` declarations, never in a binding path. */\nexport const RECURSION_WILDCARD = '**';\n","/**\n * フィルタ引数リストのパース。`filter(a, b)` の `a, b` 部分を受け取る。\n *\n * トリムの規則は「**クォートの外側だけ**」。`fix( 2 )` のような書き癖を吸収するために\n * 素の引数は前後をトリムするが、クォートは「ここは literal」という宣言なので中身の\n * 空白は残す。両方まとめてトリムしていたため `pad(5, ' ')` が空文字パディング\n * (=無変化)に化けており、空白区切りの `join(' / ')` も指定できなかった。\n *\n * Port of `@wcstack/state` `src/bindTextParser/parseFilterArgs.ts` (behaviour unchanged).\n */\nimport { raise, M } from \"../messages\";\n\n/** 引数 1 つを確定する。クォート由来の文字が入った範囲より外側だけをトリムする。 */\nfunction finalizeArg(text: string, firstQuoteStart: number, lastQuoteEnd: number): string {\n // 先頭側: 最初のクォート文字より前だけが削れる(クォートが無ければ全体が対象)\n const startLimit = firstQuoteStart === -1 ? text.length : firstQuoteStart;\n // 末尾側: 最後のクォート文字より後ろだけが削れる(クォートが無ければ全体が対象)\n const endLimit = lastQuoteEnd === -1 ? 0 : lastQuoteEnd;\n // (`trim` removes what `\\s` matches: WhiteSpace and LineTerminator)\n return text.slice(startLimit - text.slice(0, startLimit).trimStart().length, endLimit + text.slice(endLimit).trimEnd().length);\n}\n\n/** 引用符の無い引数の型(要件 B9): true / false / null / 数値は型付き、それ以外は文字列 */\nconst NUMBER_LITERAL = /^[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$/;\nfunction toLiteral(text: string, quoted: boolean): unknown {\n if (quoted) return text;\n if (text === \"true\") return true;\n if (text === \"false\") return false;\n if (text === \"null\") return null;\n return NUMBER_LITERAL.test(text) ? Number(text) : text;\n}\n\n/**\n * 引数の原文と、その型付きの値(要件 B9)を一緒に返す。原文は引用符を外したもの。\n *\n * 末尾の空引数だけが落ちる(`\"a,\"` → 1 個、`\",a\"` → 2 個、`\",\"` → 1 個)。`filter()` を\n * 「引数 0 個」と読むための規則で、先頭・中間の空引数は位置を保つために残す。\n */\nexport function parseFilterArgsWithLiterals(argsText: string): { args: string[]; literals: unknown[] } {\n const args: string[] = [];\n const literals: unknown[] = [];\n let current = '';\n let inQuote: string | null = null;\n let hasQuote = false;\n let firstQuoteStart = -1;\n let lastQuoteEnd = -1;\n\n /** Ends an argument; only the last one is dropped when empty (and not quoted). */\n const flush = (last?: boolean): void => {\n const arg = finalizeArg(current, firstQuoteStart, lastQuoteEnd);\n if (!last || arg || hasQuote) {\n args.push(arg);\n literals.push(toLiteral(arg, hasQuote));\n }\n current = '';\n hasQuote = false;\n firstQuoteStart = -1;\n lastQuoteEnd = -1;\n };\n\n for (let i = 0; i < argsText.length; i++) {\n const char = argsText[i];\n\n if (inQuote) {\n if (char === inQuote) {\n inQuote = null;\n } else {\n if (firstQuoteStart === -1) {\n firstQuoteStart = current.length;\n }\n current += char;\n lastQuoteEnd = current.length;\n }\n } else if (char === '\"' || char === \"'\") {\n inQuote = char;\n hasQuote = true;\n } else if (char === ',') {\n flush();\n } else {\n current += char;\n }\n }\n\n if (inQuote !== null) {\n // 閉じていない引用符は受理しない(要件 B2)。以前は黙って閉じたことにしていた\n raise(M.UnterminatedQuote, [inQuote, argsText]);\n }\n flush(true);\n\n return { args, literals };\n}\n","export const trimFn = (s: string): string => s.trim();\n\n/**\n * The positions of `char` in `text` that are outside quotes (`'` / `\"`), in order (要件 B1).\n * 閉じていない引用符はそのまま末尾まで続く扱い — 不正な引用符はフィルタ引数の段で名指しで落ちる。\n */\nfunction outsideQuotes(text: string, char: string): number[] {\n const found: number[] = [];\n let quote: string | null = null;\n for (let i = 0; i < text.length; i++) {\n const c = text[i];\n if (quote !== null) {\n if (c === quote) quote = null;\n } else if (c === \"'\" || c === '\"') {\n quote = c;\n } else if (c === char) {\n found.push(i);\n }\n }\n return found;\n}\n\n/** `text` の中で、引用符(`'` / `\"`)の外にある最初の `char` の位置。無ければ -1(要件 B1)。 */\nexport const indexOfOutsideQuotes = (text: string, char: string): number => outsideQuotes(text, char)[0] ?? -1;\n\n/**\n * `text` の中で、引用符の外にある**最後の** `char` の位置。無ければ -1(要件 B1)。\n * フィルタの閉じ括弧を探す用(`a|foo(')')` の引用符内の `)` を終端と誤認しないため)。\n */\nexport const lastIndexOfOutsideQuotes = (text: string, char: string): number => outsideQuotes(text, char).pop() ?? -1;\n\n/**\n * `separator` で区切る。ただし引用符の中は区切らない(要件 B1): `join(';')` や `join('|')` の\n * 区切り文字は引数であって、バインディングやフィルタの区切りではない。\n */\nexport function splitOutsideQuotes(text: string, separator: string): string[] {\n const parts: string[] = [];\n let start = 0;\n for (const i of outsideQuotes(text, separator)) {\n parts.push(text.slice(start, i));\n start = i + 1;\n }\n parts.push(text.slice(start));\n return parts;\n}\n","import { FILTER_SEPARATOR, MODIFIER_SEPARATOR } from \"./define\";\nimport { parseFilterArgsWithLiterals } from \"./parseFilterArgs\";\nimport { raise, M } from \"../messages\";\nimport { FilterIOType, ParsedFilter } from \"./types\";\nimport { indexOfOutsideQuotes, lastIndexOfOutsideQuotes, splitOutsideQuotes, trimFn } from \"./utils\";\n\n// format: filterName(arg1,arg2) or filterName\n\n/**\n * 文法の段(要件 D16): 名前と引数だけを読む。**実関数は引かない** — フィルタ名の解決\n * (別名も含む)はエンジン側の仕事。未知のフィルタもここでは落とさない。\n *\n * Port of `@wcstack/state` `src/bindTextParser/parseFilters.ts` (behaviour unchanged; the\n * tooling-only `clearFilterFnCacheForTooling` is dropped).\n *\n * @param filterTextList 個々のフィルタの原文(`|` で切った後)\n * @param filterIOType 入力(左辺)/ 出力(右辺)。実関数は引かないが、助言の出し分けに使う\n * @param sourceText 診断に埋める原文。呼び出し側は**その辺の全文**(`propPart` / `statePart`)を\n * 渡すこと。`|` より後ろだけを渡すと、`textContent: a|` のように末尾が空の形で\n * 空文字になり、つなぎ直し(`filterTextList.join(\"|\")`)と同じで文脈が消える。\n * 省略時のつなぎ直しは、原文を持たない直接の呼び出し用のフォールバック\n */\nexport function parseFilters(filterTextList: string[], filterIOType: FilterIOType, sourceText?: string): ParsedFilter[] {\n const source = sourceText ?? filterTextList.join(\"|\");\n return filterTextList.map((filterText) => {\n // 括弧も引用符の外だけで探す(要件 B1)。素の `indexOf` / `lastIndexOf` だと\n // `foo(')')` の引用符内の `)` を終端に取り、「閉じ括弧が無い」ではなく\n // 「引用符が閉じていない」という見当違いの診断になっていた\n const openParenIndex = indexOfOutsideQuotes(filterText, '(');\n let closeParenIndex = lastIndexOfOutsideQuotes(filterText, ')');\n if (closeParenIndex === -1) {\n // 引用符の外に閉じ括弧が無い = 引用符が閉じていない形(`join('x)`)か、本当に無いか。\n // 前者で「閉じ括弧が無い」と言うのは見当違いなので素の探索へ落とし、引数の段の\n // `[wcs/binding-syntax] unterminated ' quote` に診断させる\n closeParenIndex = filterText.lastIndexOf(')');\n }\n // check parentheses\n if (openParenIndex !== -1 && closeParenIndex === -1) {\n raise(M.FilterUnclosed, [filterText]);\n }\n if (closeParenIndex !== -1 && openParenIndex === -1) {\n raise(M.FilterUnopened, [filterText]);\n }\n if (closeParenIndex !== -1 && closeParenIndex < openParenIndex) {\n // `foo)1(` — 以前は `substring` が start > end で引数を入れ替えるため、フィルタ名\n // `foo)1` として受理されていた\n raise(M.FilterParenOrder, [filterText]);\n }\n if (closeParenIndex !== -1 && filterText.slice(closeParenIndex + 1).trim().length > 0) {\n // 閉じ括弧の後ろの残余を**黙って捨てていた**。`n|fix(2)uc` は `uc` が消えて診断ゼロで\n // 通っていた。実害は「`|` の打ち忘れでフィルタが 1 本消えても無診断」\n const trailing = filterText.slice(closeParenIndex + 1).trim();\n raise(M.FilterTrailing, [filterText, trailing]);\n }\n const filterName = (openParenIndex === -1 ? filterText : filterText.substring(0, openParenIndex)).trim();\n if (filterName.length === 0) {\n // 空のフィルタ(`x|`・`x||y`・`x|(1)`)は文法の誤り。解析の段で名指しで落とす — 未知の\n // フィルタとは別物で、実関数の解決まで持ち越すと tooling の解析が素通りする\n raise(M.FilterEmpty, [source]);\n }\n if (filterName.includes(MODIFIER_SEPARATOR)) {\n // フィルタ名に `#` が飲まれた形。`[wcs/filter-unknown] filter not found: trim#ro` だと\n // 診断が指す先が実際の誤りと違う(要件 B4 の並び)。\n // 助言は辺で分ける — **修飾子は左辺にしか存在しない**ので、右辺で「修飾子をフィルタより\n // 前に書け」と言うと成立しない直し方(`textContent#ro|trim: x`)を勧めることになる\n const [, modifiers] = filterName.split(MODIFIER_SEPARATOR);\n raise(filterIOType === \"input\" ? M.FilterNameHasModifiersInput : M.FilterNameHasModifiersOutput, [filterName, modifiers]);\n }\n if (openParenIndex === -1) {\n // no arguments\n return { filterName, args: [], literals: [] };\n }\n const argsText = filterText.substring(openParenIndex + 1, closeParenIndex);\n return { filterName, ...parseFilterArgsWithLiterals(argsText) };\n });\n}\n\n/**\n * One side of a binding split at its first `|` outside quotes: the text before it (trimmed) and its\n * parsed filters. `cache` is keyed by the text after the `|`: the same text gives **the same array**\n * (callers must not change it); a failed parse is not cached. The diagnostics quote the whole side\n * (`part`): the text after the `|` alone is empty for `a|`.\n */\nexport function splitFilters(part: string, filterIOType: FilterIOType, cache: Map<string, ParsedFilter[]>): [string, ParsedFilter[]] {\n // 引用符の中の `|` はフィルタの区切りではない(要件 B1 — `join('|')`)\n const pos = indexOfOutsideQuotes(part, FILTER_SEPARATOR);\n if (pos === -1) return [part.trim(), []];\n const filtersText = part.slice(pos + 1).trim();\n let filters = cache.get(filtersText);\n if (filters === undefined) {\n filters = parseFilters(splitOutsideQuotes(filtersText, FILTER_SEPARATOR).map(trimFn), filterIOType, part);\n cache.set(filtersText, filters);\n }\n return [part.slice(0, pos).trim(), filters];\n}\n","import { DELIMITER, MAX_PATH_SEGMENTS, RECURSION_WILDCARD } from \"./define\";\nimport { splitFilters } from \"./parseFilters\";\nimport { raise, M } from \"../messages\";\nimport { ParsedBinding, ParsedFilter } from \"./types\";\n\n// 解析の段の形(フィルタは名前と引数だけ — 実関数はエンジンが引く。要件 D16)。\n// `@wcstack/state` はここで `statePathInfo`(`getPathInfo` の intern 結果)も返していたが、\n// 新エンジンはパスを自分で解決するので文字列だけを返す。\nexport type StatePartParseResult = Pick<ParsedBinding, 'statePathName' | 'outFilters'>;\n\n/**\n * 出力フィルタ列の解析結果のキャッシュ(鍵は `|` より後ろの原文)。同じ原文は**同じ配列**を返す —\n * 消費側は返された `outFilters` を変更しないこと。落ちた解析は載らない。\n * (`@wcstack/state` の tooling 専用の解放口 `clearStatePartCacheForTooling` は移植しない)\n */\nconst cacheFilterInfos = new Map<string, ParsedFilter[]>();\n/** Tooling (`clearParserCaches`): a long-running process drops what it parsed. */\nexport const clearStatePartCache = (): void => cacheFilterInfos.clear();\n\n/**\n * `getPathInfo` が初回 intern で行っていた文字列だけで決まる検査の移植(順序も同じ:\n * `**` → セグメント数)。`getPathInfo` は `**` のパスを intern しないので毎回落ち、\n * 上限超えのパスも intern されないので毎回落ちる — 状態を持たない検査と同値。\n */\nfunction checkPathLikeGetPathInfo(path: string): void {\n if (path.includes(RECURSION_WILDCARD)) {\n recursionUnsupported(path);\n }\n const segmentCount = path.split(DELIMITER).length;\n if (segmentCount > MAX_PATH_SEGMENTS) {\n raise(M.TooManySegments, [path, segmentCount]);\n }\n}\n\n// format: statePath|filter|filter\n// statePath-format: path.to.property (e.g., user.name.first, users.*.name, users.0.name, not include @)\n// filters-format: filterName or filterName(arg1,arg2)\n\n/** Port of `@wcstack/state` `src/bindTextParser/parseStatePart.ts` (no `statePathInfo`). */\n/** `**` outside the places a `$recursion` declaration gives it meaning. */\nexport function recursionUnsupported(path: string): never {\n raise(M.RecursionUnsupported, [path]);\n}\n\nexport function parseStatePart(statePart: string): StatePartParseResult {\n const [stateAndPath, filters] = splitFilters(statePart, \"output\", cacheFilterInfos);\n if (stateAndPath.includes(\"@\")) {\n // 名前次元は v2 で撤去(docs/state-mount-design.md D16 / §9)。パスは 1 本のツリー。\n raise(M.SelectorRemoved, [stateAndPath]);\n }\n const statePathName = stateAndPath;\n // 右辺も左辺(`parsePropPart`)と同じ規準で空セグメントを弾く(要件 B1)。\n //\n // **判定の前にループ相対の短縮形を正規化する。** `.` で始まる右辺は `for` 行の相対パスで\n // (展開はエンジンの仕事 — パーサは展開前の原文をそのまま返す)、先頭の空セグメント 1 つは正当。\n // とくに **`.` 単独は「行そのもの」を指す正規の書き方**(`state: .`)— 「先頭は許すが末尾は拒否」と\n // 素朴に書くと `\".\"` は `[\"\", \"\"]` = 先頭かつ末尾なので落ちる。取り除いた残りが空でも通すこと\n const isLoopRelative = statePathName.startsWith(DELIMITER);\n const body = isLoopRelative ? statePathName.slice(DELIMITER.length) : statePathName;\n const hasEmptySegment = body.length > 0 && body.split(DELIMITER).some((segment) => segment.length === 0);\n if (hasEmptySegment || (!isLoopRelative && body.length === 0)) {\n raise(M.EmptySegment, [statePart]);\n }\n checkPathLikeGetPathInfo(statePathName);\n return {\n statePathName,\n outFilters: filters,\n };\n}\n","import { DIRTY, Pattern, PatternTable, parsePath, WILDCARD, type EqSub } from \"./pattern\";\nimport { StateList, StateRow, reconcile, EMPTY, type ReconcileHooks } from \"./list\";\nimport type { Strategy } from \"./strategy/types\";\nimport type { Binding } from \"./dom/view\";\nimport { commandNamespace, eventTokens, type Token } from \"./token\";\nimport { runTransition } from \"./protocol/transitionRunner\";\nimport { raise, M, text } from \"./messages\";\nimport { recursionUnsupported } from \"./parser/parseStatePart\";\nimport { hooks, requireFeature } from \"./hooks\";\nimport { INDEX_PARAM, MAX_INDEX_PARAM } from \"./parser/define\";\nimport { report } from \"./parser/raiseError\";\n\n/** Declarations an add-on serves: without it installed they fail instead of doing nothing. */\nconst DECLARATIONS: [string, string][] = [[\"$watch\", \"temporal\"], [\"$stream\", \"temporal\"], [\"$listKeys\", \"list-keys\"], [\"$recursion\", \"recursion\"]];\n\n/**\n * The options of `$behavior` (each true by default): what an engine reads them as is `mustache` / `guard` / `directional`.\n * The tooling manifest publishes the same list (`behaviorOptions`, public/manifest.ts — public-surface.test.ts pins\n * them equal; the manifest does not import the engine).\n */\nexport const BEHAVIOR_KEYS: readonly string[] = [\"enableMustache\", \"sameValueGuard\", \"enableDirectionalInitialSync\"];\n\n/** `**` binds a depth only where a path is read: an assignment, $resolve, $postUpdate and $dependOn refuse it. */\nfunction unbound(path: string): string {\n if (path.includes(\"**\")) recursionUnsupported(path);\n return path;\n}\n\n/** `$1` … `$128`, no leading zero (parser/define.ts — the tooling manifest reads them there too). */\nexport { INDEX_PARAM, MAX_INDEX_PARAM };\n\ninterface Frame {\n getter: Pattern;\n row: StateRow | null;\n untracked: number;\n /** The evaluation this frame runs (`$eq` tells its keys from an earlier evaluation's). */\n epoch: number;\n /** What a root getter's evaluation read (Engine.prune). */\n reads: Pattern[];\n}\n\n/** Getter evaluations so far (each frame takes the next: an evaluation's identity). */\nlet evals = 0;\n\n/** A `$eq` subscription of a getter occurrence, kept on its row (or the engine, at the root). */\nexport interface EqEntry {\n source: Pattern;\n key: unknown;\n sub: EqSub;\n epoch: number;\n}\n\n/** A drain that keeps producing work this many times in a row is an update loop. */\nexport const MAX_DRAIN_PASSES = 32;\n/**\n * Drains in a row that rendering itself started (an element's write-back, a write in\n * `$renderedCallback`) beyond this many are an update loop (as @wcstack/state 3.3.x).\n */\nexport const MAX_RENDER_CHAIN = 100;\n/** Nested getter evaluations deeper than this are a runaway chain. */\nconst MAX_GETTER_DEPTH = 128;\n\nexport type Visit = (getter: Pattern, row: StateRow | null) => boolean;\n\n/** The value of `k` in `m`, made and set first when there is none (`make`: a shared factory, not a closure per call). */\nfunction upsert<K, V>(m: { get(k: K): V | undefined; set(k: K, v: V): unknown }, k: K, make: () => V): V {\n let v = m.get(k);\n if (v === undefined) m.set(k, (v = make()));\n return v;\n}\nconst newSet = <T>(): Set<T> => new Set<T>();\nconst newArray = <T>(): T[] => [];\n\n/**\n * Whether an array holds one object at two positions (F26, `items: [o, o]`), found when a write into a\n * row's object first needs it: once per array, so the writes after it stay O(1). An element written in\n * place drops the answer.\n */\nconst twice = new WeakMap<unknown[], boolean>();\nfunction holdsTwice(arr: unknown[]): boolean {\n let v = twice.get(arr);\n if (v === undefined) {\n const seen = new Set<unknown>();\n twice.set(arr, v = arr.some((x) => Object(x) === x && (seen.has(x) || !seen.add(x))));\n }\n return v;\n}\n\n/** A promise, or anything with a then(). */\nexport function isThenable(r: any): r is PromiseLike<unknown> {\n return r !== null && typeof r === \"object\" && typeof r.then === \"function\";\n}\n\n/** Map-key equality: Object.is, except +0 and -0 are equal (keys of a Map). */\nfunction sameValueZero(a: unknown, b: unknown): boolean {\n return a === b || (a !== a && b !== b);\n}\n\n/** Drops a `$eq` subscription; a key nobody waits for any more leaves the map (it may be a row's item). */\nfunction unsubEq(source: Pattern, key: unknown, sub: EqSub): void {\n const set = source.eqSubs?.get(key);\n if (set !== undefined && set.delete(sub) && set.size === 0) source.eqSubs!.delete(key);\n}\n\nfunction dig(v: any, segs: readonly string[]): unknown {\n for (let i = 0; i < segs.length; i++) {\n if (v == null) return undefined;\n v = v[segs[i]];\n }\n return v;\n}\n\n/** The row at `depth` on the chain of `row` (itself or an ancestor), or null. */\nexport function rowAt(row: StateRow | null, depth: number): StateRow | null {\n while (row !== null && row.list.depth > depth) row = row.list.parentRow;\n return row !== null && row.list.depth === depth ? row : null;\n}\n\n/** The context row of `p`'s list at depth `k` — null when the context is a row of another list. */\nfunction ctxRow(ctx: StateRow | null, p: Pattern, k: number): StateRow | null {\n const r = rowAt(ctx, k);\n return r !== null && r.list.pattern === p.lists[k] ? r : null;\n}\n\n/**\n * One engine per <wcs-state>. It owns everything reachable from its state: the\n * patterns, the lists and their rows, the bindings, the update queue. Nothing is keyed\n * by the state element, because nothing is shared between engines.\n */\nexport class Engine implements ReconcileHooks {\n target!: Record<string, any>;\n /** `$behavior` (fixed at construction): `{{ }}` text, the same-value guard, direction-aware initial sync. */\n mustache!: boolean;\n guard!: boolean;\n directional!: boolean;\n readonly patterns: PatternTable;\n readonly strategy: Strategy;\n readonly proxy: Record<string, any>;\n /** Number of row-level getter slots. */\n slotCount = 0;\n /** Evaluation context: the row a getter / method / setter runs for. */\n ctx: StateRow | null = null;\n /** Writes throw while > 0: a readonly createState callback, or a getter being evaluated. */\n readonlyDepth = 0;\n /**\n * Top-level keys a re-set dropped (the old state had them, the new one lacks them): they read as\n * undefined, not as keys never declared (read; the diagnostics add-on reads it too). Kept here — the\n * author's state object is not written to (it may be frozen, or a Proxy that refuses).\n */\n readonly dropped = new Set<string>();\n /** The node the bindings were mounted on (delegated listeners live here); none before the mount. */\n root?: Node;\n /** Delegated event types → the property (per engine) their element handlers are stored under. */\n private readonly delegated = new Map<string, symbol>();\n /** Property (per engine) on a block's top node(s) holding the block, for delegated events. */\n readonly blockKey = Symbol(\"wcs.block\");\n /** The <wcs-state> element (`this.$stateElement`). */\n element: unknown = null;\n /**\n * A mounted component's (scopes add-on): a function read off the proxy itself, made to run on it\n * when called detached — the proxy is `element.state`, and `const { toggle } = element.state`\n * works (3.x #331). Undefined (or no answer): as it is.\n */\n declare bound?: (fn: (...args: any[]) => unknown) => unknown;\n /** `$command`: the command tokens declared in `$commandTokens`. */\n commands!: Readonly<Record<string, Token>>;\n /** The event tokens declared in `$eventTokens`, with the `$on` handlers subscribed. */\n events!: Map<string, Token>;\n /** Binding failures of the current drain, reported after it (`$errorCallback` or console). */\n private errors: [unknown, Binding][] = [];\n /** Paths applied in the current drain, for `$renderedCallback` (collected only when declared). */\n rendered: Map<string, number[][]> | null = null;\n private frames: Frame[] = [];\n private depthNow = 0;\n private top: Frame | null = null;\n readonly rootLists = new Map<Pattern, StateList>();\n readonly rootBindings = new Map<Pattern, Set<Binding>>();\n private queue: Binding[] = [];\n private dirtyLists: StateList[] = [];\n /** Lists over a changed getter, re-synced at the start of the next drain pass. */\n private staleLists: StateList[] = [];\n private scheduled = false;\n private draining = false;\n /** The lists over each array (only while more than one list has it do writes mirror). */\n private readonly listsByArray = new WeakMap<unknown[], StateList[]>();\n /** Drains in a row that rendering started (MAX_RENDER_CHAIN); a pause between tasks ends it. */\n private chain = 0;\n /**\n * For the drain the write-backs of an apply an arbiter deferred start: its place in that apply's\n * chain (0: none). The pause before the apply ends the task's chain, not this one. Only what the\n * apply writes synchronously is carried: an async `$renderedCallback` writing after an `await`\n * starts a task chain again, so such a loop runs one lap per arbiter task and is never cut.\n */\n private carried = 0;\n /**\n * Applies an arbiter is holding for its transition: until the last has run, what follows a drain\n * (`$watch`, the diagnostics) waits, so it sees the page the update produced, as without one — a\n * `$watch` that navigated ran before `<wcs-storage>` saved (docs/seam-apps.md, city-library).\n */\n private held = 0;\n /** Draining inside such an apply: its passes are applied at once, in the arbiter's transition. */\n private inApply = 0;\n /** This chain was reported as not settling within a drain (#11): reported once a chain. */\n private unsettled = false;\n /** Since the last drain started: a write rendering fed back / a write from code (which ends a chain). */\n private fedBack = false;\n private codeWrote = false;\n /**\n * Inside `$renderedCallback` (until an async one settles) or a `$watch` handler: its writes are\n * reactions, fed back like an element's (MAX_RENDER_CHAIN).\n */\n feeding = 0;\n private readonly unchainFn = () => {\n this.chain = 0;\n this.unsettled = false;\n };\n private readonly renderedFn = () => {\n this.feeding--;\n };\n // out-parameters of resolve()\n private rp: Pattern | null = null;\n private rr: StateRow | null = null;\n\n private readonly drainFn = () => {\n // (drained already, inside an arbiter's apply)\n if (this.scheduled) this.drain();\n };\n private readonly deliverFn = (handler: (...a: unknown[]) => unknown, args: unknown[]) => handler(this.proxy, ...args);\n /** `$eq` subscriptions of root-level getters. */\n private readonly rootEqSubs: EqEntry[] = [];\n /** Patterns made, or no longer read by a root getter, since the last sweep: what it looks at. */\n private loose: Pattern[] = [];\n /** The `$` functions of the state (`this.$eq`, …), by name. */\n private readonly api: Record<string, unknown> = {\n $untracked: (fn: () => unknown) => {\n const f = this.top;\n if (f === null) return fn();\n f.untracked++;\n try {\n return fn();\n } finally {\n f.untracked--;\n }\n },\n $eqIndex: (path: string, level = 1) => {\n const row = rowAt(this.ctx, level);\n if (row === null) raise(M.EqIndexNoRow, [path]);\n const source = this.pattern(path);\n // a getter (or a path under one) changes without a write: an ordinary tracked read, and the\n // row's index is read as `$1` reads it (a moved row compares again)\n if (source.getter !== null || source.underGetter) {\n this.watchIndex(level);\n return row.index === this.read(source, null);\n }\n const f = this.top;\n if (f !== null) {\n const g = f.getter;\n const watchers = source.eqIndexWatchers ?? (source.eqIndexWatchers = []);\n if (!watchers.some((w) => w.getter === g && w.level === level)) {\n watchers.push({ getter: g, level });\n const listP = g.lists[level]!;\n (listP.eqIndexKeys ?? (listP.eqIndexKeys = [])).push({ source, getter: g });\n }\n }\n return row.index === this.readUntracked(source, null);\n },\n $eq: (path: string, key: unknown) => this.eq(path, key),\n $eqPath: (path: string, keyPath: string) => {\n const kp = this.pattern(keyPath);\n return this.eq(path, this.readUntracked(kp, rowAt(this.ctx, kp.depth)));\n },\n $dependOn: (path: string) => {\n this.resolve(unbound(path), this.ctx);\n if (this.top !== null && this.top.untracked === 0) this.track(this.rp!, this.rr, this.top);\n },\n $getAll: (path: string, indexes?: number[]) => this.getAll(path, indexes),\n $setAll: (path: string, indexes: number[], value: unknown, options?: { spread?: boolean }) =>\n this.setAll(path, indexes, value, options),\n // $resolve(path, indexes) reads; $resolve(path, indexes, value) writes (the argument count decides)\n $resolve: (...args: unknown[]) => {\n const path = unbound(args[0] as string);\n const indexes = (args[1] ?? []) as number[];\n const p = this.pattern(path, true);\n this.checkArity(\"$resolve\", path, p, indexes, true);\n const row = this.rowOf(p, indexes, null);\n if (args.length < 3) return this.read(p, row);\n this.write(p, row, args[2]);\n },\n $postUpdate: (path: string) => {\n this.resolve(unbound(path), this.ctx);\n const p = this.rp!;\n const row = this.rr;\n // changed in place: an element is what its array holds now\n if (p.last === WILDCARD && row !== null) {\n row.item = row.list.arr![row.index];\n twice.delete(row.list.arr!);\n this.strategy.resetRow(row);\n }\n this.touched(p, row);\n if (row !== null) this.mirror(row, p, undefined, row.item, false);\n // the value before is not known: the `$eq` / `$eqIndex` occurrences under every key change\n if (p.depth === 0) this.rekeyEqUnder(p, undefined, undefined, true);\n this.landed(p, row, undefined, undefined, false);\n },\n };\n\n constructor(target: Record<string, any>, strategy: Strategy) {\n this.strategy = strategy;\n this.patterns = new PatternTable((p) => {\n this.loose.push(p);\n this.onPatternCreated(p);\n });\n this.loadTarget(target);\n const engine = this;\n // the handler reads engine.target, not the proxy's target (a stand-in): a re-set swaps the state.\n // So do `in`, `delete`, `Object.keys(this)`, `instanceof` (the forwarded traps below); a descriptor\n // is reported configurable, as the stand-in has none (a frozen state's would break the invariants)\n const handler: ProxyHandler<object> = {\n getOwnPropertyDescriptor(_t, key) {\n const d = Reflect.getOwnPropertyDescriptor(engine.target, key);\n if (d) d.configurable = true;\n return d;\n },\n get(_t, key, receiver) {\n const t = engine.target;\n if (typeof key === \"symbol\") return Reflect.get(t, key);\n if (key.charCodeAt(0) === 36 /* $ */) return engine.dollar(key);\n if (key.indexOf(\".\") < 0) {\n const p = engine.patterns.peek(key);\n if (p === undefined || p.getter === null) {\n const v = t[key];\n // (a view of the proxy — the readonly createStateAsync's — gets it as it is)\n if (typeof v === \"function\") return (receiver === engine.proxy && engine.bound?.(v)) || v;\n }\n // a known top-level key: no path to parse\n if (p !== undefined && p.depth === 0) return engine.read(p, null);\n }\n engine.resolve(key, engine.ctx);\n return engine.read(engine.rp!, engine.rr);\n },\n set(_t, key, value) {\n if (typeof key === \"symbol\") return Reflect.set(engine.target, key, value);\n engine.resolve(unbound(key), engine.ctx);\n engine.write(engine.rp!, engine.rr, value);\n return true;\n },\n };\n for (const trap of [\"has\", \"ownKeys\", \"deleteProperty\", \"defineProperty\", \"getPrototypeOf\"]) {\n (handler as any)[trap] = (_t: object, ...a: unknown[]) => (Reflect as any)[trap](engine.target, ...a);\n }\n this.proxy = new Proxy({}, handler);\n }\n\n // ---------------------------------------------------------------- patterns\n\n /**\n * The pattern of `path`, pinned: whoever asks keeps it (a binding, a list, an add-on). `loose`: a\n * path read or written (the proxy, `$resolve`, `$getAll`), swept once it holds nothing.\n */\n pattern(path: string, loose?: boolean): Pattern {\n const p = this.patterns.get(path);\n if (!loose) p.pinned = true;\n return p;\n }\n\n private registerAccessors(target: object): void {\n const seen = new Set<string>();\n for (let o: object | null = target; o !== null && o !== Object.prototype; o = Object.getPrototypeOf(o)) {\n for (const key of Object.getOwnPropertyNames(o)) {\n if (seen.has(key)) continue;\n seen.add(key);\n const d = Object.getOwnPropertyDescriptor(o, key)!;\n if (d.get === undefined && d.set === undefined) continue;\n const p = this.pattern(key);\n p.getter = d.get ?? null;\n p.setter = d.set ?? null;\n if (p.getter !== null && p.depth > 0) p.slot = this.slotCount++;\n }\n }\n // accessors registered after their descendants were created: recompute\n for (const p of this.patterns.all()) this.onPatternCreated(p);\n }\n\n private onPatternCreated(p: Pattern): void {\n // (the recursion add-on makes its `**` templates without this, while the state registers)\n if (p.path.includes(\"**\")) recursionUnsupported(p.path);\n // a path through an object's prototype would read and write every object's (once per path)\n if (p.last === \"__proto__\" || p.last === \"prototype\") raise(M.UnsafeSegment, [p.path]);\n const parent = p.parent;\n p.underGetter = parent !== null && p.last !== WILDCARD && parent.depth === p.depth &&\n (parent.getter !== null || parent.underGetter);\n if (p.getter === null) this.markupAccessor(p);\n }\n\n /**\n * Markup names two things the tree does not hold, as `this[...]` reads them: an explicit index\n * (`items.0.v`, the row at that index now) and a loop index (`items.*.$1`, `$1` in a row).\n * Their patterns (only markup makes them: the proxy parses an index into a row) read — and an\n * index path writes — as the proxy resolves them, so the reads are tracked like a getter's.\n * Where a number is a key of an object (`sales.2024.total`), the path resolves to the pattern\n * itself (rowOf): it is read and written through its parent.\n */\n private markupAccessor(p: Pattern): void {\n const path = p.path;\n const last = p.last;\n if (INDEX_PARAM.test(last)) {\n p.getter = function (this: any) {\n return this[last];\n };\n } else {\n const segs = path.split(\".\");\n // (a leading numeric segment is a root key, not an index: parsePath)\n const i = segs.findIndex((s, j) => j > 0 && s.charCodeAt(0) >= 48 && s.charCodeAt(0) <= 57);\n // none, or a `*` after it: a row of a list over the index path (`for: groups.0.items`) reads its\n // own item, and a write through the index reaches it as a list with the same array (mirror)\n if (i < 0 || segs.indexOf(WILDCARD, i) >= 0) return;\n // (the parent read from the context row: the occurrence's, the setter's — at p.depth)\n p.getter = () => {\n this.resolve(path, this.ctx);\n if (this.rp !== p) return this.read(this.rp!, this.rr);\n return (this.read(p.parent!, this.ctx) as any)?.[last];\n };\n p.setter = (v: unknown) => {\n this.resolve(path, this.ctx);\n if (this.rp !== p) return this.write(this.rp!, this.rr, v);\n const o = this.read(p.parent!, this.ctx) as any;\n if (o == null) raise(M.ParentNotObject, [path, o]);\n o[last] = v;\n };\n }\n p.markup = true;\n if (p.depth > 0) p.slot = this.slotCount++;\n }\n\n // ---------------------------------------------------------------- lists\n\n /** The list of list pattern `p` in `row` (null: a root list), made on first use, synced. */\n childList(row: StateRow | null, p: Pattern): StateList {\n const m = row === null ? this.rootLists : (row.children ??= new Map());\n let l = m.get(p);\n if (l === undefined) m.set(p, (l = new StateList(p, row)));\n // (the list holds it: a path's read made it loose, `users.3.name` through `users`)\n p.pinned = true;\n this.sync(l);\n return l;\n }\n\n /** Syncs `l`; a failure (a missing key, a getter that throws) is its for binding's, and it keeps its rows. */\n private trySync(l: StateList): void {\n try {\n this.sync(l);\n } catch (error) {\n this.failAt(error, l.pattern.path, l.view?.anchor ?? null, \"for\");\n }\n }\n\n /** Reconciles a list's rows with the current value of its pattern. */\n sync(l: StateList): void {\n const value = this.readUntracked(l.pattern, l.parentRow);\n const before = l.arr;\n if (value === before) return;\n // out of the lists over its array before (filed again under the new one below)\n this.unfile(l);\n const old = reconcile(l, value, this);\n if (old === null) return;\n // filed under its array: lists that share an array mirror writes\n // (a value that is not an array reconciles against a stand-in: nothing to share)\n if (l.arr === value) {\n const same = upsert(this.listsByArray, value as unknown[], newArray<StateList>);\n same.push(l);\n // (the rows it kept are up to date: a write into an object reached every list showing it, F26)\n if (same.length > 1) for (const x of same) x.shared = true;\n }\n hooks.listSynced?.(this, l, old);\n if ((l.view !== null || l.extra !== null) && !l.queued) {\n l.queued = true;\n this.dirtyLists.push(l);\n this.schedule();\n }\n const keys = l.pattern.eqIndexKeys;\n if (keys !== null) {\n for (const { source, getter } of keys) {\n const sel = this.readUntracked(source, null) as number;\n const before = old[sel];\n const after = l.rows[sel];\n if (before === after) continue;\n if (before !== undefined && before.alive) this.invalidateUnder(getter, before);\n if (after !== undefined) this.invalidateUnder(getter, after);\n }\n }\n }\n\n indexChanged(row: StateRow): void {\n this.strategy.onIndexChange(this, row);\n }\n\n rowRemoved(row: StateRow): void {\n row.alive = false;\n const subs = row.eqSubs;\n if (subs !== null) {\n for (const e of subs) unsubEq(e.source, e.key, e.sub);\n row.eqSubs = null;\n }\n // the rows of its nested lists go with it, and the lists leave the ledger of their arrays\n if (row.children !== null) {\n for (const l of row.children.values()) {\n this.unfile(l);\n for (const r of l.rows) this.rowRemoved(r);\n }\n }\n }\n\n /** Takes `l` out of the lists over its array; one left alone with it no longer mirrors. */\n private unfile(l: StateList): void {\n const was = this.listsByArray.get(l.arr!);\n if (was === undefined) return;\n was.splice(was.indexOf(l) >>> 0, 1);\n l.shared = false;\n if (was.length === 1) was[0].shared = false;\n }\n\n // ---------------------------------------------------------------- resolve / read\n\n /** Splits a concrete path into (pattern, row) — written to this.rp / this.rr. */\n resolve(path: string, ctx: StateRow | null): void {\n const parsed = parsePath(path);\n const p = (this.rp = this.pattern(parsed.pattern, true));\n const idx = parsed.indexes;\n this.rr = p.depth === 0 ? null : idx === null ? ctxRow(ctx, p, p.depth) : this.rowOf(p, idx, ctx, path);\n }\n\n /**\n * The row at p.depth addressed by `idx` (one index per `*`; -1 takes the one of `ctx`). The pattern\n * it is at goes to this.rp — set last: finding the row can sync a list over a getter, whose\n * evaluation resolves paths too. An index of `path` (the proxy's) into an object that is not an\n * array (`sales.2024.total`) is a key: the pattern keeps it as written (into null or a string, it\n * has no row).\n */\n private rowOf(p: Pattern, idx: readonly number[], ctx: StateRow | null, path?: string): StateRow | null {\n let row: StateRow | null = null;\n for (let k = 1, j = 0, v; k <= p.depth; k++) {\n const listP = p.lists[k]!;\n const list = this.childList(row, listP);\n let i = idx[j++];\n if (i < 0) i = ctxRow(ctx, p, k)?.index ?? -1;\n else if (path && list.arr === EMPTY && Object((v = this.readUntracked(listP, row))) === v) {\n const segs = p.path.split(\".\");\n const n = listP.path.split(\".\").length;\n segs[n] = path.split(\".\")[n];\n p = this.pattern(segs.join(\".\"), true);\n k--;\n continue;\n }\n row = list.rows[i] ?? null;\n if (row === null) break;\n }\n this.rp = p;\n return row;\n }\n\n /** Raw data read (no getter, no tracking). `row` is the row at p.depth. */\n readData(p: Pattern, row: StateRow | null): unknown {\n return p.depth === 0 ? dig(this.target, p.tail) : row === null ? undefined : dig(row.item, p.tail);\n }\n\n /** Tracked read. `row` is the row at p.depth (null at the root). */\n read(p: Pattern, row: StateRow | null): unknown {\n const f = this.top;\n if (f !== null && f.untracked === 0) this.track(p, row, f);\n if (p.getter !== null) return this.strategy.readGetter(this, p, row);\n if (p.underGetter) {\n const parent = this.read(p.parent!, row) as any;\n return parent == null ? undefined : parent[p.last];\n }\n // (`then` / `toJSON` are probes — await, JSON.stringify — not reads of the state: undefined)\n if (p.parent === null && !(p.last in this.target) && !this.dropped.has(p.last) && p.last !== \"then\" && p.last !== \"toJSON\") {\n raise(M.PathMissing, [p.path], p.last, Object.keys(this.target));\n }\n return this.readData(p, row);\n }\n\n readUntracked(p: Pattern, row: StateRow | null): unknown {\n const f = this.top;\n if (f === null) return this.read(p, row);\n f.untracked++;\n try {\n return this.read(p, row);\n } finally {\n f.untracked--;\n }\n }\n\n private track(p: Pattern, row: StateRow | null, f: Frame): void {\n const g = f.getter;\n p.addDependent(g);\n // a root getter's reads (once each, but around a nested one): what it no longer reads goes (prune)\n if (g.depth === 0) {\n if (p.mark !== f.epoch) {\n p.mark = f.epoch;\n f.reads.push(p);\n }\n } else if (p.depth > 0 && rowAt(row, Math.min(p.depth, g.depth)) !== rowAt(f.row, Math.min(p.depth, g.depth))) {\n (g.crossSources ?? (g.crossSources = new Set())).add(p);\n }\n }\n\n /** Evaluates a getter occurrence with dependency tracking. Caching is the strategy's. */\n evalGetter(g: Pattern, row: StateRow | null): unknown {\n // frames are reused by depth: an evaluation allocates nothing of its own\n for (let i = 0; i < this.depthNow; i++) {\n const f = this.frames[i];\n if (f.getter === g && f.row === row) raise(M.GetterCycle, [g.path]);\n }\n if (this.depthNow >= MAX_GETTER_DEPTH) raise(M.GetterDepth, [g.path]);\n const depth = this.depthNow++;\n this.readonlyDepth++;\n const frame = (this.frames[depth] ??= { getter: g, row, untracked: 0, epoch: 0, reads: [] });\n frame.getter = g;\n frame.row = row;\n frame.untracked = 0;\n frame.epoch = ++evals;\n frame.reads.length = 0;\n const outer = this.top;\n this.top = frame;\n const prev = this.ctx;\n this.ctx = row;\n try {\n const v = g.getter!.call(this.proxy);\n if (g.depth === 0) this.prune(g, frame);\n return v;\n } finally {\n this.readonlyDepth--;\n this.depthNow--;\n this.top = outer;\n this.ctx = prev;\n frame.row = null;\n }\n }\n\n /**\n * A root getter evaluated (without throwing): the top-level sources it did not read this time are no\n * longer its sources. Its one occurrence is the whole getter, so what it reads is what it depends on\n * (a row getter's sources stay the union over its rows). A key built from data it read before\n * (`this[\"users.\" + this.selectedId]`) then holds nothing, and is swept. One holding an array stays:\n * a write into an object that array shares with the one the getter returns reaches the rows of the\n * list over the getter through it (mirror — F26, 3.x #362).\n */\n private prune(g: Pattern, f: Frame): void {\n const e = f.epoch;\n for (const s of f.reads) s.mark = e;\n g.sources = g.sources.filter((s) => s.mark === e || s.depth > 0 ||\n (!s.underGetter && Array.isArray(s.getter !== null ? s.rootValue : this.readData(s, null))) || this.unlink(s, g));\n }\n\n /** `getter` reads `s` no more (its side is the caller's): `s` may hold nothing now. False (filtered out). */\n private unlink(s: Pattern, getter: Pattern): false {\n s.dropDependent(getter);\n this.loose.push(s);\n return false;\n }\n\n /**\n * After a drain: the patterns only a path made that hold nothing now leave the table, so it grows\n * with the state's shape, not with every key a path was ever built with. A pattern stays while it\n * is pinned (Engine.pattern: `$eqIndex`'s source among them), at the top level (the state's own\n * keys), has children, is read by a getter, is `$eq`'s source, or has an accessor that is not the\n * engine's own for an index path at the top level (one in a row has a cache slot).\n */\n private sweep(): void {\n for (let c = this.loose; c.length > 0; c = this.loose) {\n this.loose = [];\n const parents = new Set<Pattern>();\n for (const p of c) {\n if (p.pinned || p.dead || p.parent === null || p.children.length > 0 || p.dependents.length > 0 ||\n (p.getter !== null && !(p.markup && p.slot < 0)) || p.eqSubs !== null) continue;\n p.dead = true;\n this.patterns.drop(p);\n parents.add(p.parent);\n // an index path's accessor read its parent\n for (const s of p.sources) this.unlink(s, p);\n }\n for (const q of parents) if (!(q.children = q.children.filter((x) => !x.dead)).length) this.loose.push(q);\n }\n }\n\n /** The getter evaluating now reads the index of its row at level `n`: a move of that row re-evaluates it. */\n private watchIndex(n: number): void {\n const f = this.top;\n if (f !== null && f.untracked === 0) {\n const g = f.getter;\n const listP = g.lists[n];\n if (listP) {\n const w = listP.indexWatchers ?? (listP.indexWatchers = []);\n if (!w.includes(g)) w.push(g);\n }\n }\n }\n\n private dollar(key: string): unknown {\n const c = key.charCodeAt(1);\n if (c >= 48 && c <= 57) {\n const n = key.length === 2 ? c - 48 : INDEX_PARAM.test(key) ? +key.slice(1) : 0;\n if (n < 1 || n > MAX_INDEX_PARAM) {\n raise(M.IndexParamRange, [key]);\n }\n this.watchIndex(n);\n return rowAt(this.ctx, n)?.index;\n }\n const fn = this.api[key];\n if (fn !== undefined) return fn;\n // (the 3.x names 4.0 removed, $trackDependency and $untrackDependency, are the diagnostics add-on's)\n switch (key) {\n case \"$stateElement\":\n return this.element;\n case \"$command\":\n return this.commands;\n }\n return hooks.dollar?.(this, key);\n }\n\n /**\n * `$eq(path, key)`: is the value of `path` equal to `key`? Inside a getter the occurrence\n * subscribes under `key` instead of depending on `path`: a write to `path` re-evaluates\n * only the occurrences keyed under its old and its new value. A `path` that is a getter\n * (or under one) changes without a write, so it falls back to an ordinary tracked read.\n */\n private eq(path: string, key: unknown): boolean {\n this.resolve(path, this.ctx);\n const source = this.rp!;\n const row = this.rr;\n if (source.getter !== null || source.underGetter || source.depth > 0) return sameValueZero(this.read(source, row), key);\n const f = this.top;\n if (f !== null && f.untracked === 0) this.subscribeEq(source, key, f);\n return sameValueZero(this.readUntracked(source, null), key);\n }\n\n /**\n * Subscribes the occurrence evaluating in `f` under `key`. A key it subscribed in an earlier\n * evaluation and not in this one moved; one of this evaluation stays (`$eq(p, a) || $eq(p, b)`).\n */\n private subscribeEq(source: Pattern, key: unknown, f: Frame): void {\n const getter = f.getter;\n const row = f.row;\n const list = row === null ? this.rootEqSubs : (row.eqSubs ?? (row.eqSubs = []));\n for (let i = 0; i < list.length; i++) {\n const e = list[i];\n if (e.sub.getter !== getter || e.source !== source) continue;\n if (sameValueZero(e.key, key)) {\n e.epoch = f.epoch;\n return;\n }\n if (e.epoch !== f.epoch) {\n unsubEq(source, e.key, e.sub);\n list.splice(i--, 1);\n }\n }\n const sub: EqSub = { getter, row };\n upsert((source.eqSubs ??= new Map()), key, newSet<EqSub>).add(sub);\n list.push({ source, key, sub, epoch: f.epoch });\n }\n\n /**\n * A root write to `p` (or an object above a `$eq` / `$eqIndex` source): re-key every source at or\n * under it. `all` (`$postUpdate`, which knows no value before): every key.\n */\n private rekeyEqUnder(p: Pattern, before: unknown, after: unknown, all?: boolean): void {\n this.forSubtree(p, (q) => {\n const map = q.eqSubs;\n if (map === null && q.eqIndexWatchers === null) return;\n const rest = q === p ? [] : q.path.slice(p.path.length + 1).split(\".\");\n const b = dig(before, rest);\n const a = dig(after, rest);\n if (q.eqIndexWatchers !== null) this.rekeyEqIndex(q, b, a, all);\n // the occurrences keyed under the value before and the value after\n if (map !== null) for (const k of all ? map.keys() : [b, a]) {\n const set = map.get(k);\n if (set === undefined) continue;\n for (const sub of set) {\n if (sub.row !== null && !sub.row.alive) {\n unsubEq(q, k, sub);\n continue;\n }\n this.strategy.invalidate(this, sub.getter, sub.row);\n }\n }\n });\n }\n\n // ---------------------------------------------------------------- write\n\n /**\n * `occurrence`: an event-semantics write, applied even when equal to the current value.\n * `element`: an element wrote it back (a two-way input, a wc-bindable event), not code.\n */\n write(p: Pattern, row: StateRow | null, value: unknown, occurrence = false, element = false): void {\n if (this.readonlyDepth > 0) raise(M.Readonly);\n if (element || this.feeding > 0) this.fedBack = true;\n else this.codeWrote = true;\n if (hooks.beforeWrite?.(this, p, row, value, element)) return;\n // a setter's write is not a data write: the add-ons hear of it without old and new values\n if (p.setter !== null) {\n // a setter that throws after it wrote: what it wrote still lands (3.x #361), and the error\n // propagates. One that throws before writing anything lands as well, as one that returns\n // without writing does (3.x notifies in `finally` too): `$watch` hears of it, a getter recomputes\n try {\n this.callAt(p.setter, row, [value]);\n } finally {\n this.landed(p, row, undefined, undefined, false, element);\n }\n return;\n }\n if (p.getter !== null) raise(M.GetterWithoutSetter, [p.path]);\n if (p.depth > 0 && row === null) raise(M.NoRow, [p.path]);\n // under a getter, the value before is read through it (the data has no such path)\n const old = p.underGetter ? this.readUntracked(p, row) : this.readData(p, row);\n if (!occurrence && this.guard && Object.is(old, value) && Object(value) !== value) return;\n if (p.last === WILDCARD) {\n // element write: the position keeps its row, the row takes the new value\n const r = row!;\n (r.list.arr as unknown[])[r.index] = value;\n twice.delete(r.list.arr!);\n r.item = value;\n this.strategy.resetRow(r);\n } else {\n const parent = (p.tail.length === 1\n ? (p.depth === 0 ? this.target : row!.item)\n : this.readUntracked(p.parent!, row)) as any;\n if (parent == null) raise(M.ParentNotObject, [p.path, parent]);\n parent[p.last] = value;\n }\n this.syncListsUnder(p, row);\n if (row !== null) this.mirror(row, p, old, value);\n if (p.depth === 0) this.rekeyEqUnder(p, old, value);\n this.landed(p, row, old, value, true, element);\n }\n\n /** The lists over `l`'s array now (`l` among them), none of a removed row. */\n private sharing(l: StateList): StateList[] {\n return (this.listsByArray.get(l.arr!) ?? []).filter((m) => m.arr === l.arr && (m.parentRow === null || m.parentRow.alive));\n }\n\n /**\n * A write into row `row` of a list whose array another list has too (`for: shown` over a getter\n * returning `todos`, `for: groups.0.items`): the other list's row at the same position shows it.\n *\n * A write into the row's object (not the element) reaches it wherever else it is (F26, `get\n * shown()` filtering `todos`). From the array holding it (the list's own, or one its getter read\n * at a data path), the write goes to the getters that read that array and returned one holding the\n * object (a filter, a sort, a slice: evaluated again), on down their dependents, and to the rows\n * holding the object in the lists over those arrays. A getter whose array does not hold the object\n * is not reached: it read the array, not the object (the dependency boundary).\n */\n private mirror(row: StateRow, p: Pattern, old: unknown, value: unknown, direct = true): void {\n const l = row.list;\n const suffix = p.path.slice(l.pattern.path.length + 2);\n // a write into the row's object, which its array holds at another position too (F26): those rows show it\n const dup = suffix !== \"\" && holdsTwice(l.arr!);\n // another list has its array, or it is over a getter or a getter reads it: its object may be in\n // another array too. A plain list pays these checks only\n if (!dup && !l.shared && l.pattern.getter === null && !l.pattern.dependents.length) return;\n const o = row.item;\n const land = (m: StateList, r: StateRow | undefined): void => {\n if (r === undefined || r === row) return;\n const mp = this.pattern(`${m.pattern.path}.*${suffix}`, true);\n if (suffix === \"\") {\n r.item = value;\n this.strategy.resetRow(r);\n }\n if (direct) this.syncListsUnder(mp, r);\n else this.touched(mp, r);\n this.landed(mp, r, old, value, direct);\n };\n for (const m of this.sharing(l)) {\n land(m, m.rows[row.index]);\n if (dup) for (const r of m.rows) if (r.item === o && r.index !== row.index) land(m, r);\n }\n if (suffix === \"\") return;\n // (a leaf write: the row's item is an object. The lists over its own array were reached above)\n const seen = new Set<unknown>([l.arr]);\n const has = (a: unknown): a is unknown[] => Array.isArray(a) && a.includes(o);\n const down = (arr: unknown, deps: Pattern[]): void => {\n if (!seen.has(arr) && seen.add(arr)) for (const m of this.listsByArray.get(arr as unknown[]) ?? []) for (const r of m.rows) if (r.item === o) land(m, r);\n // each getter once (a cycle across evaluations ends). One passing the array on (`get shown()\n // { return this.todos }`) is not evaluated again: the lists over it were reached already. One\n // reached before (earlier in the batch, or just now through a getter it reads) is evaluated again\n // in the drain, its list synced then: the rows it keeps are those its list shows now\n for (const g of deps) {\n let v = g.rootValue;\n const stale = v === DIRTY;\n if (stale) v = this.rootLists.get(g)?.arr;\n if ((stale || has(v)) && !seen.has(g.dependents) && seen.add(g.dependents)) {\n if (!stale && v !== arr) this.strategy.invalidate(this, g, null);\n down(v, g.dependents);\n }\n }\n };\n const up = (g: Pattern): void => {\n for (const s of g.sources) {\n if (seen.has(s) || !seen.add(s)) continue;\n if (s.getter !== null) up(s);\n else if (!s.underGetter) {\n const a = this.readData(s, null);\n if (has(a)) down(a, s.dependents);\n }\n }\n };\n if (l.pattern.getter !== null) up(l.pattern);\n else down(l.arr!, l.pattern.dependents);\n }\n\n /**\n * `$postUpdate`: what is at `p` changed in place. Its lists are synced as a write syncs them, and\n * their rows (and the rows of the lists over the same arrays) show it again: a write reaches a\n * row's bindings through the row it replaced, an in-place change through none.\n */\n private touched(p: Pattern, row: StateRow | null): void {\n this.forListsUnder(p, row, (l) => {\n this.sync(l);\n for (const m of l.shared ? this.sharing(l) : [l]) {\n const e = this.pattern(`${m.pattern.path}.*`);\n for (const r of m.rows) {\n this.enqueueBound(e, r);\n this.touched(e, r);\n }\n }\n });\n }\n\n private syncListsUnder(p: Pattern, row: StateRow | null): void {\n const ls = row === null ? this.rootLists : row.children;\n if (ls !== null) for (const l of ls.values()) if (l.pattern.isUnder(p)) this.sync(l);\n }\n\n /** The lists of `row` (the root lists at null) whose pattern is `p` or under it. */\n private forListsUnder(p: Pattern, row: StateRow | null, fn: (l: StateList) => void): void {\n const ls = row === null ? this.rootLists : row.children;\n if (ls !== null) for (const l of ls.values()) if (l.pattern.isUnder(p)) fn(l);\n }\n\n /**\n * `$eqIndex(source, level)` compares the index of the row at `level`: when `source` changes, the\n * getter's occurrences under the rows at that level with the old or the new index change (`all`:\n * under every row).\n */\n private rekeyEqIndex(source: Pattern, before: unknown, after: unknown, all?: boolean): void {\n for (const { getter, level } of source.eqIndexWatchers!) {\n this.forAllLists(getter.lists[level]!, (l) => {\n for (const k of all ? l.rows.keys() : [before, after]) {\n const r = typeof k === \"number\" ? l.rows[k] : undefined;\n if (r !== undefined) this.invalidateUnder(getter, r);\n }\n });\n }\n }\n\n /** Invalidates getter `g`'s occurrences at or under `row` (row.depth <= g.depth). */\n private invalidateUnder(g: Pattern, row: StateRow): void {\n if (row.list.depth === g.depth) this.strategy.invalidate(this, g, row);\n else this.forRowsUnder(row, g, (r) => this.strategy.invalidate(this, g, r));\n }\n\n /** A write landed at (p, row): the add-ons hear of it, then its dependents. */\n private landed(p: Pattern, row: StateRow | null, old: unknown, value: unknown, direct: boolean, element?: boolean): void {\n hooks.written?.(this, p, row, old, value, direct, element);\n this.changed(p, row);\n }\n\n changed(p: Pattern, row: StateRow | null): void {\n this.strategy.onWrite(this, p, row);\n this.schedule();\n }\n\n /**\n * One listener per event type on the root, dispatching to the delegated element handlers.\n * Returns the property the element's handler is stored under (one symbol per engine and\n * type, so two engines never run each other's handlers).\n */\n delegate(type: string): symbol {\n const known = this.delegated.get(type);\n if (known !== undefined) return known;\n const key = Symbol(`wcs.on${type}`);\n this.delegated.set(type, key);\n const root = this.root!;\n const blockKey = this.blockKey;\n root.addEventListener(type, (e) => {\n for (let n = e.target as any; n !== null && n !== root; n = n.parentNode) {\n // a handler stored on the element (a root-level one, or one a block pinned)\n const fn = n[key];\n if (fn !== undefined) {\n fn(e);\n if (e.cancelBubble) return;\n }\n // a block's top node: the handlers of the block's elements the event passed\n const block = n[blockKey];\n if (block !== undefined && block.alive && block.dispatch(type, e)) return;\n }\n });\n return key;\n }\n\n // ---------------------------------------------------------------- re-set\n\n /**\n * `setInitialState` on an initialized element: the state is replaced whole and every\n * binding is re-applied to it before this returns. Not a write: no `$renderedCallback`.\n * Everything learned from the old state goes (accessors, dependencies, caches, `$eq`\n * keys); rows are kept where their list's array is the same instance.\n */\n reset(target: Record<string, any>): void {\n const old = this.target;\n // a key the old state had (or an earlier re-set dropped) and this one lacks is empty (B8), as a\n // missing path under a key is — not a key never declared, which fails on read: its bindings, lists\n // and getters read undefined, until it is written. Its accessors too: those on a class state's\n // prototype, which for…in does not list, are the top-level patterns with a getter\n const dropped = this.dropped;\n for (const p of this.patterns.all()) if (p.parent === null && p.getter !== null) dropped.add(p.last);\n this.loadTarget(target);\n for (const k in old) if (k[0] !== \"$\") dropped.add(k);\n for (const k of dropped) if (k in target) dropped.delete(k);\n for (const bs of this.rootBindings.values()) for (const b of bs) this.enqueue(b);\n for (const l of this.rootLists.values()) this.resetList(l);\n this.rendered = null;\n try {\n this.drain();\n } finally {\n this.watchRendered();\n }\n hooks.element?.(this, \"reset\");\n }\n\n /** Takes in a state object: at construction, and on a re-set (everything learned from the old one goes). */\n private loadTarget(target: Record<string, any>): void {\n for (const [key, feature] of DECLARATIONS) if (target[key] !== undefined) requireFeature(feature, key);\n // (the 3.x declarations 4.0 removed — $scan, $streams, $updatedCallback — are the diagnostics add-on's)\n const f = target.$features;\n if (f !== undefined) {\n if (!Array.isArray(f)) raise(M.FeaturesNotArray);\n for (const name of f) requireFeature(name, \"$features\");\n }\n // an options object: null and an array are not one (as for bootstrapState's options)\n const c = target.$behavior === undefined ? {} : target.$behavior;\n if (typeof c !== \"object\" || !c || Array.isArray(c)) raise(M.OptionInvalid, [\"state\", \"$behavior\"]);\n for (const key in c) if (!BEHAVIOR_KEYS.includes(key) || typeof c[key] !== \"boolean\") raise(M.OptionInvalid, [\"$behavior\", key]);\n const [mustache, guard, directional] = BEHAVIOR_KEYS.map((key) => c[key] ?? true);\n // a re-set keeps the engine, and what was built by the old options\n if (this.target !== undefined && (mustache !== this.mustache || guard !== this.guard || directional !== this.directional)) raise(M.BehaviorChanged);\n // (read before anything is taken in: a malformed declaration leaves a re-set's old state in place)\n const commands = commandNamespace(target, this.commands);\n const events = eventTokens(target, this.deliverFn);\n this.mustache = mustache;\n this.guard = guard;\n this.directional = directional;\n hooks.declare?.(this, target);\n this.target = target;\n this.slotCount = 0;\n for (const p of this.patterns.all()) p.forget();\n this.rootEqSubs.length = 0;\n this.registerAccessors(target);\n this.commands = commands;\n this.events = events;\n }\n\n private resetList(l: StateList): void {\n // a list that cannot be read (its getter throws) fails alone: the re-set goes on (and ends with its hook)\n this.trySync(l);\n const element = this.pattern(`${l.pattern.path}.*`);\n for (const row of l.rows) {\n row.cache = null;\n row.eqSubs = null;\n this.enqueueBound(element, row);\n if (row.children !== null) for (const c of row.children.values()) this.resetList(c);\n }\n }\n\n // ---------------------------------------------------------------- tokens\n\n /** The loop indexes of `row`, outermost first (`$1`, `$2`, …). */\n indexesOf(row: StateRow | null): number[] {\n const out: number[] = [];\n for (let r = row; r !== null; r = r.list.parentRow) out.unshift(r.index);\n return out;\n }\n\n /** An element event wired with `eventToken.<prop>: <name>` — the token is resolved at fire time. */\n fireEventToken(name: string, event: Event, row: StateRow | null): void {\n const token = this.events.get(name);\n if (token === undefined) raise(M.EventTokenUndeclared, [name], name, this.events.keys());\n token.emit(event, ...this.indexesOf(row));\n }\n\n /** The `$command.<name>` token (declared in `$commandTokens`). */\n command(name: string): Token {\n const token = this.commands[name];\n if (token === undefined) raise(M.CommandTokenUndeclared, [name], name, Object.keys(this.commands));\n return token;\n }\n\n /** `onclick: $command.<name>` — emits the token with (event, ...listIndexes). */\n emitCommand(name: string, event: Event, row: StateRow | null): void {\n this.command(name).emit(event, ...this.indexesOf(row));\n }\n\n // ---------------------------------------------------------------- methods\n\n invoke(name: string, event: Event, row: StateRow | null): unknown {\n // a dotted name is a path (a volume method lives under its mount path)\n const fn = name.includes(\".\") ? this.readUntracked(this.pattern(name), null) : this.target[name];\n if (typeof fn !== \"function\") raise(M.NotAMethod, [name]);\n return this.callAt(fn, row, [event, ...this.indexesOf(row)]);\n }\n\n /** Calls `fn` on the proxy with the evaluation context at `row`. */\n private callAt(fn: (...args: any[]) => unknown, row: StateRow | null, args: unknown[]): unknown {\n const prev = this.ctx;\n this.ctx = row;\n try {\n return fn.apply(this.proxy, args);\n } finally {\n this.ctx = prev;\n }\n }\n\n // ---------------------------------------------------------------- change walk\n\n /** Queues the bindings on `p` (and patterns under it) in the scope of `row`. */\n enqueueBound(p: Pattern, row: StateRow | null): void {\n // a list over a getter (or under one) is re-synced in the drain: a data write syncs its\n // lists right away, but a getter's value is only known when it is read again\n if (p.getter !== null) {\n const ls = row === null ? this.rootLists : row.children;\n if (ls !== null) {\n for (const l of ls.values()) {\n if (!l.stale && l.pattern.isUnder(p)) {\n l.stale = true;\n this.staleLists.push(l);\n }\n }\n }\n }\n if (row === null) {\n this.forSubtree(p, (q) => {\n const bs = this.rootBindings.get(q);\n if (bs !== undefined) for (const b of bs) this.enqueue(b);\n });\n return;\n }\n const bs = row.bindings;\n if (bs !== null) for (let i = 0; i < bs.length; i++) if (bs[i].pattern.isUnder(p)) this.enqueue(bs[i]);\n // slot bindings of the row's renderings\n const view = row.view;\n if (view !== null && view.slots !== null) view.enqueueSlots(this, p);\n const extra = row.list.extra;\n if (extra !== null) {\n for (const fv of extra) {\n const rv = fv.map!.get(row);\n if (rv !== undefined && rv.slots !== null) rv.enqueueSlots(this, p);\n }\n }\n }\n\n /** Reaches every getter occurrence that read `p` (or a pattern under it) at `row`. */\n walkDependents(p: Pattern, row: StateRow | null, visit: Visit): void {\n this.forSubtree(p, (q) => {\n const deps = q.dependents;\n for (let i = 0; i < deps.length; i++) {\n const g = deps[i];\n if (g.depth === 0) this.visitGetter(g, null, visit);\n else if (row === null || q.depth === 0 || g.lists[1] !== q.lists[1] || (g.crossSources !== null && g.crossSources.has(q))) {\n this.forAllRows(g.lists[g.depth]!, (r) => this.visitGetter(g, r, visit));\n } else if (g.depth <= q.depth) {\n const r = rowAt(row, g.depth);\n if (r !== null) this.visitGetter(g, r, visit);\n } else this.forRowsUnder(row, g, (r) => this.visitGetter(g, r, visit));\n }\n });\n }\n\n visitGetter(g: Pattern, row: StateRow | null, visit: Visit): void {\n if (!visit(g, row)) return;\n hooks.getterReached?.(this, g, row);\n this.enqueueBound(g, row);\n this.walkDependents(g, row, visit);\n }\n\n forSubtree(p: Pattern, fn: (q: Pattern) => void): void {\n fn(p);\n const c = p.children;\n for (let i = 0; i < c.length; i++) this.forSubtree(c[i], fn);\n }\n\n /** Every row of every list instance of list pattern `listP`. */\n forAllRows(listP: Pattern, fn: (row: StateRow) => void): void {\n this.forAllLists(listP, (l) => {\n for (const r of l.rows) fn(r);\n });\n }\n\n /** Every list instance of list pattern `listP`. */\n private forAllLists(listP: Pattern, fn: (l: StateList) => void): void {\n if (listP.depth === 0) {\n const l = this.rootLists.get(listP);\n if (l !== undefined) fn(l);\n return;\n }\n this.forAllRows(listP.lists[listP.depth]!, (parent) => {\n const l = parent.children?.get(listP);\n if (l !== undefined) fn(l);\n });\n }\n\n /** Rows at g.depth at or under `row` (row.depth <= g.depth). */\n forRowsUnder(row: StateRow, g: Pattern, fn: (row: StateRow) => void): void {\n if (row.list.depth === g.depth) return fn(row);\n const l = row.children?.get(g.lists[row.list.depth + 1]!);\n if (l !== undefined) for (const r of l.rows) this.forRowsUnder(r, g, fn);\n }\n\n // ---------------------------------------------------------------- bindings & drain\n\n /** Registers a binding where a change of its location finds it: its row, or the root table. */\n register(b: Binding): void {\n const row = b.row;\n if (row !== null) {\n (row.bindings ?? (row.bindings = [])).push(b);\n return;\n }\n upsert(this.rootBindings, b.pattern, newSet<Binding>).add(b);\n }\n\n unregister(b: Binding): void {\n const row = b.row;\n if (row === null) {\n this.rootBindings.get(b.pattern)?.delete(b);\n return;\n }\n // a row that left its list takes its registrations with it\n const bs = row.bindings;\n if (row.alive && bs !== null) bs.splice(bs.indexOf(b) >>> 0, 1);\n }\n\n enqueue(b: Binding): void {\n if (b.queued) return;\n b.queued = true;\n this.queue.push(b);\n this.schedule();\n }\n\n schedule(): void {\n if (this.scheduled) return;\n this.scheduled = true;\n queueMicrotask(this.drainFn);\n }\n\n /** Drops the queued work of a cut update loop: what it would have shown waits for the next change. */\n private dropWork(): void {\n for (const b of this.queue) b.queued = false;\n for (const l of this.dirtyLists) l.queued = false;\n for (const l of this.staleLists) l.stale = false;\n this.queue = [];\n this.dirtyLists = [];\n this.staleLists = [];\n this.strategy.dropped(this);\n }\n\n /**\n * Cuts an update loop past `max` (`id`: its message): reported with the paths its queued work\n * would have rendered (the console, and DevTools as `state:render-chain-limit`), then dropped.\n */\n private cutLoop(id: M, max: number): void {\n const paths = [...new Set([...this.queue, ...this.dirtyLists, ...this.staleLists].map((x) => x.pattern.path))];\n report(paths, `[@wcstack/state] ${text(id)}`);\n hooks.noticed?.(this, { \"type\": \"state:render-chain-limit\", \"maxDepth\": max, \"paths\": paths });\n this.dropWork();\n }\n\n drain(): void {\n this.scheduled = false;\n // a drain only rendering fed (no write from code since the last) continues a chain: the carried\n // one of a deferred apply, or the task's\n const carried = this.carried;\n this.carried = 0;\n let chain = 0;\n if (!this.fedBack || this.codeWrote) this.unchainFn();\n else if (carried > 0) chain = carried;\n else if ((chain = ++this.chain) === 1) setTimeout(this.unchainFn, 0);\n this.fedBack = this.codeWrote = false;\n if (chain > MAX_RENDER_CHAIN) {\n if (chain === MAX_RENDER_CHAIN + 1) this.cutLoop(M.RenderChain, MAX_RENDER_CHAIN);\n else this.dropWork();\n return;\n }\n this.draining = true;\n try {\n for (let pass = 0; this.queue.length > 0 || this.dirtyLists.length > 0 || this.staleLists.length > 0; pass++) {\n if (pass >= MAX_DRAIN_PASSES) {\n // (once a chain: a reaction that starts the same loop again in each drain is not reported again)\n if (this.unsettled) this.dropWork();\n else this.cutLoop(M.DrainNotSettled, MAX_DRAIN_PASSES);\n this.unsettled = true;\n break;\n }\n const stale = this.staleLists;\n if (stale.length > 0) {\n this.staleLists = [];\n for (const l of stale) {\n l.stale = false;\n this.trySync(l);\n }\n }\n const lists = this.dirtyLists;\n const q = this.queue;\n this.dirtyLists = [];\n this.queue = [];\n // a pass that changes structure — a list's rows, an `if` branch — goes to the page's\n // view-transition arbiter, if any (transition-runner protocol); one that only updates\n // values is applied right here, as with no arbiter (a value change is CSS transitions'\n // job, and a transition per keystroke left the page unclickable — docs/seam-apps.md,\n // router-admin). Queued entries stay marked until applied, so a write meanwhile folds\n // into them\n let ran = false;\n const apply = (): void => {\n ran = true;\n // list views first (they build rows), then bindings\n for (const l of lists) {\n l.queued = false;\n for (const v of [l.view, ...(l.extra ?? [])]) {\n if (v === null || !v.alive) continue;\n // a row that fails to build (a binding refused as it is attached) fails this view\n // alone: the rest of the pass is still applied (nothing stays queued)\n try {\n v.update();\n } catch (error) {\n this.failAt(error, l.pattern.path, v.anchor, \"for\");\n }\n }\n }\n // `if` / `elseif` conditions first: a branch one closes takes its bindings with it, so\n // they are not applied with the value that closes it (a condition over a getter is\n // queued after the bindings on the path it reads — docs/seam-apps.md, router-auth)\n for (let k = 0; k < 2; k++) {\n for (let i = 0; i < q.length; i++) {\n const b = q[i];\n // applied since it was queued (a row slot, when its row was built)\n if (!b.queued || (b.chain === null) === (k === 0)) continue;\n b.queued = false;\n if (b.owner === null || b.owner.alive) this.applyBinding(b);\n }\n }\n // applied later by the arbiter, outside any drain: report its failures now. What that\n // apply and the `$watch` after it write (a write-back, `$renderedCallback`, a copied list)\n // is drained here, the next of this drain's chain, and applied in the same transition — a\n // frame of its own showed the loading line gone over the old rows (router-admin)\n if (!this.draining) {\n this.report();\n if (--this.held === 0) this.settled();\n if (this.scheduled) {\n this.carried = chain + 1;\n this.inApply++;\n try {\n while (this.scheduled) this.drain();\n } finally {\n this.inApply--;\n }\n }\n }\n };\n const pending = (lists.length > 0 || q.some((b) => b.chain !== null)) && this.inApply === 0 ? runTransition(\"state\", apply) : apply();\n if (!ran) this.held++;\n if (pending !== undefined) pending.then(undefined, report);\n }\n } finally {\n this.draining = false;\n }\n // (writes made while applying are this drain's own passes)\n this.fedBack = this.codeWrote = false;\n this.report();\n if (this.held === 0) this.settled();\n // (as is the one a carried drain's reactions start)\n if (carried > 0 && this.scheduled) this.carried = chain + 1;\n }\n\n /** What follows a drain once its page is applied (`held`): `$watch`, the diagnostics, the sweep. */\n private settled(): void {\n hooks.drained?.(this);\n this.sweep();\n }\n\n // ---------------------------------------------------------------- apply, hooks, reports\n\n /** A binding that failed to apply: reported after the drain. */\n fail(error: unknown, b: Binding): void {\n this.errors.push([error, b]);\n }\n\n /**\n * A failure of what has no Binding object, reported like a binding's: a list that failed to sync\n * or render (its `for`), a binding refused as it was attached in a row.\n */\n failAt(error: unknown, path: string, node: Node | null, type: string): void {\n this.fail(error, { pattern: { path }, node, typeName: () => type } as unknown as Binding);\n }\n\n applyBinding(b: Binding): void {\n try {\n b.apply();\n } catch (error) {\n this.errors.push([error, b]);\n return;\n }\n if (this.rendered !== null) this.noteRendered(b.pattern, b.row);\n }\n\n /** Records an applied binding for `$renderedCallback`. */\n noteRendered(p: Pattern, row: StateRow | null): void {\n const list = upsert(this.rendered!, p.path, newArray<number[]>);\n if (row !== null) list.push(this.indexesOf(row));\n }\n\n /** Starts collecting applied paths when the state declares `$renderedCallback`. */\n watchRendered(): void {\n this.rendered = typeof this.target.$renderedCallback === \"function\" ? new Map() : null;\n }\n\n /** `$renderedCallback` for the paths applied since the last report, then binding failures. */\n report(): void {\n const rendered = this.rendered;\n if (rendered !== null && rendered.size > 0) {\n this.rendered = new Map();\n const paths = [...rendered.keys()];\n const indexes: Record<string, number[][]> = {};\n for (const [p, l] of rendered) if (l.length > 0) indexes[p] = l;\n this.feeding++;\n let r: any;\n try {\n r = this.callHook(\"$renderedCallback\", [paths, indexes]);\n } catch (e) {\n report(e);\n }\n if (isThenable(r)) {\n r.then(this.renderedFn, (e: unknown) => {\n this.renderedFn();\n report(e);\n });\n } else {\n this.feeding--;\n }\n }\n if (this.errors.length === 0) return;\n const errors = this.errors;\n this.errors = [];\n const hook = this.target.$errorCallback;\n for (const [error, binding] of errors) {\n hooks.failed?.(this, error, binding);\n const path = binding.pattern.path;\n const type = binding.typeName();\n if (typeof hook === \"function\") {\n // quoted keys: the author reads them (mangle.mjs shortens the unquoted ones)\n try {\n const r = this.callHook(\"$errorCallback\", [error, { \"path\": path, \"bindingType\": type, \"node\": binding.node }]) as any;\n if (isThenable(r)) r.then(undefined, report);\n } catch (e) {\n report(e);\n }\n } else {\n // (the binding's member and kind name it as written; the node points at it)\n report(error, `[@wcstack/state] ${text(M.BindingFailed, binding.name ? [type, path, binding.name, binding.kind] : [type, path])}`, binding.node);\n }\n }\n }\n\n /** Runs a lifecycle hook with the writable proxy; returns its result (awaited by the caller or not). */\n callHook(name: string, args: unknown[] = []): unknown {\n const fn = this.target[name];\n return typeof fn === \"function\" ? this.callAt(fn, null, args) : undefined;\n }\n\n // ---------------------------------------------------------------- $getAll / $setAll / $resolve\n\n /** Calls fn for every row at p.depth that matches `indexes` (a prefix over p's wildcards). */\n private forMatches(p: Pattern, indexes: readonly number[], fn: (row: StateRow | null, idx: number[]) => void): void {\n if (p.depth === 0) {\n fn(null, []);\n return;\n }\n const idx: number[] = [];\n const walk = (k: number, parent: StateRow | null): void => {\n const lp = p.lists[k]!;\n // the list itself is read too: a getter over $getAll sees the first row of an empty list\n this.read(lp, parent);\n const list = this.childList(parent, lp);\n const visit = (r: StateRow): void => {\n idx.push(r.index);\n if (k === p.depth) fn(r, idx);\n else walk(k + 1, r);\n idx.pop();\n };\n for (const r of k - 1 < indexes.length ? [list.rows[indexes[k - 1]]] : list.rows) if (r !== undefined) visit(r);\n };\n walk(1, null);\n }\n\n private getAll(path: string, indexes?: number[]): unknown[] {\n const p = this.pattern(path, true);\n if (indexes !== undefined) this.checkArity(\"$getAll\", path, p, indexes, false);\n // by default the loop context, on the wildcard levels the path shares with it\n let idx = indexes;\n if (idx === undefined) {\n idx = [];\n const ctx = this.ctx;\n if (ctx !== null && p.depth > 0) {\n for (let k = 1; k <= p.depth; k++) {\n const r = ctxRow(ctx, p, k);\n if (r === null) break;\n idx.push(r.index);\n }\n if (idx.length === 0) raise(M.GetAllNoCommonLevel, [path]);\n }\n }\n const out: unknown[] = [];\n this.forMatches(p, idx, (row) => out.push(this.read(p, row)));\n return out;\n }\n\n private setAll(path: string, indexes: number[], value: unknown, options?: { spread?: boolean }): number {\n if (!Array.isArray(indexes)) raise(M.SetAllNeedsIndexes, [path]);\n if (this.readonlyDepth > 0) raise(M.Readonly);\n const p = this.pattern(path, true);\n this.checkArity(\"$setAll\", path, p, indexes, false);\n const targets: [StateRow | null, number[]][] = [];\n this.forMatches(p, indexes, (row, idx) => targets.push([row, idx.slice()]));\n const spread = options?.spread === true;\n if (spread && (!Array.isArray(value) || value.length !== targets.length)) {\n raise(M.SetAllSpreadLength, [path, targets.length]);\n }\n let written = 0;\n for (let i = 0; i < targets.length; i++) {\n const [row, idx] = targets[i];\n const v = typeof value === \"function\"\n ? (value as (cur: unknown, ...i: number[]) => unknown)(this.readUntracked(p, row), ...idx)\n : spread ? (value as unknown[])[i] : value;\n if (v === undefined) continue;\n this.write(p, row, v);\n written++;\n }\n return written;\n }\n\n /** `$resolve` takes exactly one index per `*`; `$getAll` / `$setAll` at most one (fewer expands the rest). */\n private checkArity(api: string, path: string, p: Pattern, indexes: readonly number[], exact: boolean): void {\n const n = indexes.length;\n if (n > p.depth || (exact && n < p.depth)) {\n raise(exact ? M.IndexArityExact : M.IndexArityAtMost, [api, path, p.depth, n]);\n }\n }\n}\n","import { raise, M } from \"./messages\";\n\n/**\n * Page-wide configuration (`bootstrapState(config)`): how this page spells wcstack markup (the tag\n * names, the binding attribute, the anchor comments — fixed before the first definition, the same\n * on the server) and the locale default. How a state tree behaves is its own `$behavior` (engine.ts).\n */\nexport interface Config {\n bindAttributeName: string;\n /** The text of a `for` template's anchor comment. */\n commentForPrefix: string;\n /** The texts of an `if` / `elseif` / `else` chain's anchor comments. */\n commentIfPrefix: string;\n commentElseIfPrefix: string;\n commentElsePrefix: string;\n tagNames: { state: string; ssr: string };\n locale: string;\n /** Opt-in `analyzeContract()` (dev time); off, it returns at once. */\n enableContractAnalyzer: boolean;\n}\n\nexport const config: Config = {\n bindAttributeName: \"data-wcs\",\n commentForPrefix: \"wcs-for\",\n commentIfPrefix: \"wcs-if\",\n commentElseIfPrefix: \"wcs-elseif\",\n commentElsePrefix: \"wcs-else\",\n tagNames: { state: \"wcs-state\", ssr: \"wcs-ssr\" },\n locale: typeof document !== \"undefined\" ? document.documentElement?.lang || \"en\" : \"en\",\n enableContractAnalyzer: false,\n};\n\nexport type PartialConfig = Partial<Omit<Config, \"tagNames\">> & { tagNames?: Partial<Config[\"tagNames\"]> };\n\n/**\n * Applies the options given; an undefined value is left out. An option `bootstrapState` does not\n * have (a key 4.0 moved to the state's `$behavior` or removed included), a value of another type\n * than its default (null, or an array for an object, included) or a tag name it does not define\n * throws, and then nothing is applied — the same rule as every package's bootstrap.\n */\nexport function setConfig(partial: PartialConfig): void {\n const options = config as unknown as Record<string, unknown>;\n const tags = config.tagNames as Record<string, string>;\n const given = Object.entries(partial).filter(([, value]) => value !== undefined);\n const givenTags = Object.entries(partial.tagNames ?? {}).filter(([, tag]) => tag !== undefined);\n for (const [key, value] of given) {\n const current = options[key];\n if (!Object.hasOwn(options, key) || value === null || typeof value !== typeof current || Array.isArray(value) !== Array.isArray(current)) {\n raise(M.OptionInvalid, [\"bootstrapState\", key]);\n }\n }\n for (const [name, tag] of givenTags) {\n if (!Object.hasOwn(tags, name) || typeof tag !== \"string\") raise(M.OptionInvalid, [\"bootstrapState\", `tagNames.${name}`]);\n }\n for (const [key, value] of given) {\n if (key !== \"tagNames\") {\n options[key] = value;\n }\n }\n for (const [name, tag] of givenTags) tags[name] = tag as string;\n}\n\n/** The current configuration (read-only view). */\nexport const getConfig = (): Readonly<Config> => config;\n","import { DELIMITER, MODIFIER_SEPARATOR } from \"./define\";\nimport { splitFilters } from \"./parseFilters\";\nimport { raise, M } from \"../messages\";\nimport { ParsedBinding, ParsedFilter } from \"./types\";\nimport { trimFn } from \"./utils\";\n\n// 解析の段の形(フィルタは名前と引数だけ — 実関数はエンジンが引く。要件 D16)\nexport type PropPartParseResult = Pick<ParsedBinding, 'propName' | 'propSegments' | 'propModifiers' | 'inFilters'>;\n\n/**\n * 入力フィルタ列の解析結果のキャッシュ(鍵は `|` より後ろの原文)。同じ原文は**同じ配列**を返す —\n * 消費側は返された `inFilters` を変更しないこと。落ちた解析は載らない。\n * (`@wcstack/state` の tooling 専用の解放口 `clearPropPartCacheForTooling` は移植しない)\n */\nconst cacheFilterInfos = new Map<string, ParsedFilter[]>();\n/** Tooling (`clearParserCaches`): a long-running process drops what it parsed. */\nexport const clearPropPartCache = (): void => cacheFilterInfos.clear();\n\n// format: propName#moodifier1,modifier2\n// propName-format: path.to.property (e.g., textContent, style.color, not include :)\n// special path:\n// 'attr.attributeName' for attributes (e.g., attr.href, attr.data-id)\n// 'style.propertyName' for style properties (e.g., style.backgroundColor, style.fontSize)\n// 'class.className' for class names (e.g., class.active, class.hidden)\n// 'onclick', 'onchange' etc. for event listeners\n\n/** Port of `@wcstack/state` `src/bindTextParser/parsePropPart.ts` (behaviour unchanged). */\nexport function parsePropPart(propPart: string): PropPartParseResult {\n const [propText, filters] = splitFilters(propPart, \"input\", cacheFilterInfos);\n\n // **不変条件**: ここから下の `split` は素で走らせてよい。`propText` は「引用符外の最初の `|`\n // より前」のスライスであり、引用符を含みうるのは入力フィルタの引数(`|` の後ろ)だけなので、\n // `#` も `,` も `.` も引用符の中に現れない。**修飾子の値に引用符を許す拡張(例\n // `value#fmt('a,b'): x`)を入れるなら、この 3 つも `splitOutsideQuotes` に替えること**。\n const modifierParts = propText.split(MODIFIER_SEPARATOR).map(trimFn);\n if (modifierParts.length > 2) {\n // 修飾子の並びは 1 つだけ(要件 B2)。`value#ro#wo` は以前 `ro` だけを残して黙って捨てていた\n raise(M.OneModifierList, [propText]);\n }\n const [propName, propModifiersText] = modifierParts;\n const propSegments = propName.split(DELIMITER).map(trimFn);\n // 明示のプロパティ形(`.name:` — 要件 B5 / D34)だけは先頭の空セグメントが正しい形。\n // それ以外で空のセグメントが残るのは書き間違い: 左辺が空(`\": x\"` / `\"#ro: x\"` / `\"|trim: x\"`)だと\n // `element[\"\"] = value` の expando ができて完全に沈黙し、末尾が空(`\"foo.: x\"`)だと適用の段で\n // 素の TypeError になる。どちらも解析の段で名指しで落とす(`.: x` 等は D34 の検査が受け持つ)\n const isExplicitProperty = propSegments.length > 1 && propSegments[0] === '';\n if (!isExplicitProperty && (propName.length === 0 || propSegments.some((segment) => segment.length === 0))) {\n raise(M.NoPropertyName, [propPart]);\n }\n const propModifiers = propModifiersText\n ? propModifiersText.split(',').map(trimFn)\n : [];\n return {\n propName,\n propSegments,\n propModifiers,\n inFilters: filters,\n };\n}\n","export type BindingType = 'text' | 'prop' | 'event' | 'for' | 'if' | 'elseif' | 'else' | 'radio' | 'checkbox' | 'spread';\n\n/** Left side (input) or right side (output) of a binding — only used to pick the diagnostic wording. */\nexport type FilterIOType = 'input' | 'output';\n\n/**\n * A filter as the grammar reads it: name and arguments only. The filter function is resolved\n * later by the engine (the parser never looks names up, so unknown names pass here).\n *\n * Field names are the ones of `@wcstack/state`'s `IParsedFilter`:\n * - `filterName` — the name as written (no alias resolution).\n * - `args` — the raw argument texts, quotes removed (format filters read these).\n * - `literals` — the typed value of each argument (requirement B9): unquoted `true` / `false` /\n * `null` / numbers are typed, everything else (and every quoted argument) is the string.\n * Always the same length and order as `args`.\n */\nexport interface ParsedFilter {\n filterName: string;\n args: string[];\n literals: unknown[];\n}\n\n/** Parse result of one binding (DOM independent). */\nexport interface ParsedBinding {\n propName: string;\n propSegments: string[];\n propModifiers: string[];\n statePathName: string;\n inFilters: ParsedFilter[];\n outFilters: ParsedFilter[];\n bindingType: BindingType;\n}\n\n/** Bindings that must be the only binding of their attribute value. */\nexport const STRUCTURAL_BINDING_TYPE_SET: ReadonlySet<BindingType> = new Set<BindingType>([\n 'if',\n 'elseif',\n 'else',\n 'for',\n]);\n","import {\n ATTR_NAMESPACE,\n BINDING_SEPARATOR,\n CLASS_NAMESPACE,\n COMMAND_NAMESPACE,\n DELIMITER,\n ELSE_KEYWORD,\n EVENT_PROP_PREFIX,\n EVENT_TOKEN_NAMESPACE,\n FILTER_SEPARATOR,\n MODIFIER_SEPARATOR,\n PROP_VALUE_SEPARATOR,\n SPREAD_PROP,\n STYLE_NAMESPACE,\n VOLUME_INJECTION_PROP,\n} from \"./define\";\nimport { parsePropPart } from \"./parsePropPart\";\nimport { parseStatePart, type StatePartParseResult } from \"./parseStatePart\";\nimport { raise, M } from \"../messages\";\nimport { ParsedBinding, STRUCTURAL_BINDING_TYPE_SET } from \"./types\";\nimport { indexOfOutsideQuotes, splitOutsideQuotes, trimFn } from \"./utils\";\n\n// format: propPart:statePart; propPart:statePart; ...\n// special-propPart:\n// if: statePart (single binding for conditional rendering)\n// else: (single binding for conditional rendering, and statePart is ignored)\n// elseif: statePart only (single binding for conditional rendering)\n// for: statePart only (single binding for loop rendering)\n// onclick: statePart, onchange: statePart etc. (event listeners)\n// ...: statePart (spread — the engine expands it into the target's wcBindable properties)\n\n/** 左辺に修飾子も入力フィルタも取らない束縛(構造ディレクティブと spread)— 付いていれば拒否する(要件 B4) */\nconst KEYWORDS_WITHOUT_MODIFIERS = new Set<string>([ELSE_KEYWORD, 'if', 'elseif', 'for', SPREAD_PROP]);\n\n/**\n * 明示のプロパティ形(`.name:`)の先頭に置けない語 — 名前空間として読まれる語(要件 B5)。\n * `state`(`VOLUME_INJECTION_PROP`)も含む: `<wcs-state mount>` 上の左辺 `state.<key>:` は\n * 注入の宣言(要件 B14③)なので、`.state.taxRate:` はプロパティか注入か曖昧になる。\n */\nconst EXPLICIT_PROPERTY_REJECTED_HEADS = new Set<string>([\n CLASS_NAMESPACE, ATTR_NAMESPACE, STYLE_NAMESPACE, COMMAND_NAMESPACE, EVENT_TOKEN_NAMESPACE,\n VOLUME_INJECTION_PROP,\n]);\n\n/**\n * `data-wcs` の値をバインディングごとに区切る(前後の空白は残す — tooling が位置を数えられるように)。\n * 引用符の中の `;` は区切りではない(要件 B1 — `join(';')`)。\n */\nexport function splitBindTexts(bindText: string): string[] {\n return splitOutsideQuotes(bindText, BINDING_SEPARATOR);\n}\n\n/**\n * `data-wcs` 属性値 1 つを解析する。Port of `@wcstack/state`\n * `src/bindTextParser/parseBindTextsForElement.ts` — same signature (text only: no decision\n * here needs the element), same results minus `statePathInfo`, same diagnostics.\n *\n * The parser does NOT: expand the loop-relative shorthand (`.name` / `.`), expand `...:`\n * spread into the target's properties, resolve filter names/functions, or check the\n * `if`/`elseif`/`else` sibling order — the engine does those.\n */\nexport function parseBindTextsForElement(bindText: string): ParsedBinding[] {\n const bindTexts = splitBindTexts(bindText).map(trimFn).filter(s => s.length > 0);\n const results = bindTexts.map((bindText): ParsedBinding => {\n // 左辺と右辺の区切りも引用符の外だけで探す(要件 B1)。`value|defaults(':'): path` の\n // 引数の中の `:` を区切りとして拾っていた\n const separatorIndex = indexOfOutsideQuotes(bindText, PROP_VALUE_SEPARATOR);\n if (separatorIndex === -1) {\n raise(M.BindTextNoColon, [bindText]);\n }\n const propPart = bindText.slice(0, separatorIndex).trim();\n const statePart = bindText.slice(separatorIndex + 1).trim();\n // 種別は修飾子・入力フィルタより前の名前で決める(要件 B4)。以前は左辺全体との完全一致で\n // 判定していたので、`radio#ro:` が汎用プロパティに落ちていた。\n // **不変条件**: ここは素の `split` でよい — 取り出すのは最初の区切りより前の**先頭**片で、\n // 引用符を含みうるのは入力フィルタの引数(引用符外の最初の `|` より後ろ)だけなので、\n // `#` も `|` も引用符の中では出会わない。**修飾子の値に引用符を許す拡張を入れるなら\n // `indexOfOutsideQuotes` に替えること**(`parsePropPart.ts` の同じ注記と対)。\n const keyword = propPart.split(MODIFIER_SEPARATOR)[0].split(FILTER_SEPARATOR)[0].trim();\n if (KEYWORDS_WITHOUT_MODIFIERS.has(keyword)) {\n if (keyword !== propPart) {\n raise(M.StructuralTakesNoModifiers, [bindText, keyword]);\n }\n let stateResult: StatePartParseResult;\n if (keyword === ELSE_KEYWORD) {\n if (statePart.length > 0) {\n // else は値を取らない(要件 B2)。以前は右辺を黙って捨てていた\n raise(M.ElseTakesNoValue, [bindText]);\n }\n stateResult = { statePathName: '#else', outFilters: [] };\n } else if (keyword === SPREAD_PROP) {\n // 空の右辺は spread 専用の語彙で先に落とす。`parseStatePart` の一般の空パス診断\n // (「the right side of a binding must name a state path」)より、ここでは\n // 「spread target path is required」のほうが直し方を指している\n if (statePart.length === 0) {\n raise(M.SpreadNoPath, [bindText]);\n }\n stateResult = parseStatePart(statePart);\n if (stateResult.outFilters.length > 0) {\n raise(M.SpreadNoFilters, [bindText]);\n }\n } else {\n stateResult = parseStatePart(statePart);\n // a row of `for: p` is `p.<index>`: the rows of a filtered list would name other elements (#370)\n if (keyword === 'for' && stateResult.outFilters.length > 0) {\n raise(M.ForNoFilters, [bindText]);\n }\n }\n return {\n propName: keyword,\n propSegments: [keyword],\n propModifiers: [],\n inFilters: [],\n ...stateResult,\n bindingType: keyword === SPREAD_PROP ? 'spread' : keyword as ParsedBinding['bindingType'],\n };\n }\n // `class` / `attr` は名前を伴ってはじめて束縛になる(`class.done:` / `attr.href:`)。名前の無い\n // `class:` / `attr:` は要素の(存在しない)`class` / `attr` プロパティへの書き込みになり、何も起きず\n // 何も報告されなかった(`.class:` は B5 で拒否済み)。`style:` は `el.style = \"…\"` が cssText に\n // 届くので受ける\n if (keyword === CLASS_NAMESPACE || keyword === ATTR_NAMESPACE) {\n raise(M.NamespaceNeedsName, [bindText, keyword]);\n }\n const stateResult = parseStatePart(statePart);\n const propResult = parsePropPart(propPart);\n const [head] = propResult.propSegments;\n // 左辺の先頭ドット(`.online:`)は明示のプロパティ形(要件 B5・3.x 計画 D34)。ドットの無い形と\n // 同じ束縛だが、`on` で始まってもイベントにはならない(`online:` は \"line\" イベントを待つ)。\n // 名前空間の語(`.class.x` / `.command.x` …)はプロパティか名前空間か曖昧なので受けない\n if (head === '' && propResult.propSegments.length > 1) {\n const propSegments = propResult.propSegments.slice(1);\n if (propSegments.includes('') || EXPLICIT_PROPERTY_REJECTED_HEADS.has(propSegments[0])) {\n raise(M.LeadingDotNamespace, [propPart]);\n }\n return {\n ...propResult,\n propName: propSegments.join(DELIMITER),\n propSegments,\n ...stateResult,\n bindingType: 'prop',\n };\n }\n return {\n ...propResult,\n ...stateResult,\n // 修飾子(`#ro`・`#onchange` …)と入力フィルタは radio / checkbox のハンドラが読む(要件 B4)。\n // eventToken.<prop>: <name> は要素 dispatch を state へ流す pub/sub 配線。\n // 値適用ではないため bindingType 'event' として listener attach 経路に乗せる。\n bindingType: keyword === 'radio' || keyword === 'checkbox' ? keyword\n : head === EVENT_TOKEN_NAMESPACE || head.startsWith(EVENT_PROP_PREFIX) ? 'event' : 'prop',\n };\n });\n // check for sigle binding for 'if', 'elseif', 'else', 'for'\n if (results.length > 1) {\n const isIncludeSingleBinding = results.some(r => STRUCTURAL_BINDING_TYPE_SET.has(r.bindingType));\n if (isIncludeSingleBinding) {\n // lint 側の単独バインディング検査(bindingValidator の structuralMustBeSingle)が\n // 同じケースを検出するため誘導を付ける(三面同語彙)。\n raise(M.StructuralNotSingle, [bindText]);\n }\n }\n return results;\n}\n","/**\n * filters/registry.ts — the filter registry, ported from `@wcstack/state` (`core/filterRegistry.ts`).\n *\n * The grammar (`path|filter(args)`) only produces names and arguments; the functions are looked up\n * here when the bindings are planned. The core set (`./core`) and the formats add-on (`./formats`)\n * each put their filters in with an install call; this module knows neither implementation, so a\n * page that skips the add-on does not carry its code.\n *\n * Differences from the source, all decided:\n * - one registry, not an input / output pair (the source registered the same table in both);\n * - no aliases (`inc dec fix uc lc cap pad rep rev null` are not carried over);\n * - every registered filter has arity bounds (the source allowed them to be absent);\n * - the core set is registered like any other (the source hard-wired `not` into the registry).\n */\nimport { raiseError } from \"../parser/raiseError\";\nimport { raise, M } from \"../messages\";\n\nexport type FilterFn = (value: unknown) => unknown;\n\n/**\n * Builds the function for one use of a filter. `options` are the argument texts (unquoted),\n * `literals` their typed values (requirement B9 — only filters that compare or return an argument\n * read them).\n */\nexport type FilterFactory = (options: string[], literals: readonly unknown[]) => FilterFn;\n\n/** A filter as an install call hands it to the registry: the factory and its [min, max] argument count (B3). */\nexport interface FilterDefinition {\n factory: FilterFactory;\n arity: readonly [number, number];\n}\n\n/**\n * The formats add-on's filters (37: up to 4.0.0-rc.3 the 23 display ones, then the core's\n * arithmetic, conversion and missing-value 14). Only the names live here (not the code), so that a\n * page without the add-on can still say where one of them comes from instead of calling it a typo.\n * A test keeps this list equal to the add-on's table.\n */\nexport const FORMATS_FILTER_NAMES: readonly string[] = [\n \"toFixed\", \"locale\",\n \"upper\", \"lower\", \"capitalize\", \"trim\", \"slice\", \"padStart\", \"padEnd\", \"repeat\", \"reverse\", \"truncate\", \"join\",\n \"round\", \"floor\", \"ceil\", \"percent\", \"unit\",\n \"date\", \"time\", \"datetime\", \"ymd\", \"hms\",\n \"add\", \"sub\", \"mul\", \"div\", \"mod\", \"abs\", \"clamp\", \"int\", \"float\", \"defaults\", \"coalesce\", \"number\", \"string\", \"nullIfEmpty\",\n \"currency\",\n];\n\n/**\n * A `Map`, not a plain object: bracket access on an object lets the `Object.prototype` members\n * through as filters (`|toString` / `|constructor` / `|valueOf`), which then fail with a\n * meaningless TypeError instead of `[wcs/filter-unknown]`.\n */\nconst definitions = new Map<string, FilterDefinition>();\n\n/** Name + arguments → the function already built for them (each is built once). */\nconst resolvedByKey = new Map<string, FilterFn>();\n\n/**\n * The key of one argument list: **both the raw texts and the typed values** (B3 / B9).\n * - Raw texts alone would make `defaults(0)` and `defaults('0')` the same `[\"0\"]`, sharing one\n * function between two filters of different types.\n * - Typed values alone would fold `1` / `1.0` / `01` / `+1` into the same number, although the\n * factories that read the raw text (`truncate` / `unit` / `join` / `ymd` / `padStart` …) answer\n * them differently.\n * - A structural key, never `args.join(\",\")`: `['a,b']` and `['a', 'b']` are different arguments.\n */\nexport function filterArgsKey(args: readonly string[], literals: readonly unknown[]): string {\n return `${JSON.stringify(args)}${JSON.stringify(literals)}`;\n}\n\n/** Called by the install functions. Idempotent — a name registered again replaces the previous one. */\nexport function registerFilters(map: Record<string, FilterDefinition>): void {\n for (const name of Object.keys(map)) {\n // a copy: the registry keeps what was registered\n definitions.set(name, { ...map[name] });\n }\n // A new registration can change the answers already built (a page installs once; tests and\n // tooling swap registrations)\n resolvedByKey.clear();\n}\n\nexport function hasFilter(name: string): boolean {\n return definitions.has(name);\n}\n\n/** The registered names, which the did-you-mean suggestion reads. */\nexport function knownFilterNames(): string[] {\n return [...definitions.keys()];\n}\n\n/** Drops the functions already built (tooling that clears its parser caches). */\nexport function clearFilterResolutionCache(): void {\n resolvedByKey.clear();\n}\n\n/**\n * `[wcs/filter-unknown]`. A formatting filter on a page without the formats add-on is not a typo:\n * that barrier is kept as full text, since it is met on pages without add-ons (the diagnostics\n * add-on adds the nearest name to either).\n */\nfunction unknownFilter(name: string, known: Iterable<string>): never {\n if (FORMATS_FILTER_NAMES.includes(name)) {\n raiseError(`[wcs/filter-unknown] filter not found: ${name}. \"${name}\" is in the formats add-on — install it with installFeatures([formats]) from \"@wcstack/state/features/formats\".`, name, known);\n }\n raise(M.FilterUnknown, [name], name, known);\n}\n\n/**\n * The function for one use of a filter (binding planning). An unknown name or a wrong argument count\n * fails here, by name — the parser never rejects a filter.\n */\nexport function resolveFilter(name: string, options: string[], literals: readonly unknown[]): FilterFn {\n const key = `${name}${filterArgsKey(options, literals)}`;\n const resolved = resolvedByKey.get(key);\n if (typeof resolved !== \"undefined\") {\n return resolved;\n }\n const definition = definitions.get(name);\n if (definition === undefined) {\n unknownFilter(name, definitions.keys());\n }\n // Same vocabulary as lint's wcs/filter-arity\n const [min, max] = definition.arity;\n if (options.length < min) raise(M.FilterTooFewArgs, [name, min, options.length]);\n if (options.length > max) raise(M.FilterTooManyArgs, [name, max, options.length]);\n const filterFn = definition.factory(options, literals);\n resolvedByKey.set(key, filterFn);\n return filterFn;\n}\n","/**\n * filters/errorMessages.ts — the filters' error messages, ported from `@wcstack/state`\n * (`formats/errorMessages.ts`). Numbered core messages (src/messages.ts): the sentences, the same\n * as the source's, are the diagnostics add-on's.\n */\n\nimport { raise, M } from \"../messages\";\n\n/** The filter requires an option but none was given (the factory-side guard; arity usually fires first). */\nexport function optionsRequired(fnName: string): never {\n raise(M.FilterOptionsRequired, [fnName]);\n}\n\n/** A numeric option is not a number. */\nexport function optionMustBeNumber(fnName: string): never {\n raise(M.FilterOptionNotNumber, [fnName]);\n}\n\n/** A date filter's style is not one of full / long / medium / short. */\nexport function styleInvalid(fnName: string, value: string): never {\n raise(M.FilterStyleInvalid, [fnName, value]);\n}\n\n/** `currency`'s code is not a currency Intl knows. */\nexport function currencyInvalid(value: string): never {\n raise(M.FilterCurrencyInvalid, [value]);\n}\n\n/** The value given to a numeric filter is not a number (the message says what it was). */\nexport function valueMustBeNumber(fnName: string, value: unknown): never {\n raise(M.FilterValueNotNumber, [fnName, value]);\n}\n\n/** The value given to a date filter is not a Date (the message says what it was). */\nexport function valueMustBeDate(fnName: string, value: unknown): never {\n raise(M.FilterValueNotDate, [fnName, value]);\n}\n\n/** The value given to an array filter is not an array. */\nexport function valueMustBeArray(fnName: string): never {\n raise(M.FilterValueNotArray, [fnName]);\n}\n","/**\n * filters/options.ts — option parsing shared by the core set and the formats add-on, ported\n * verbatim from `@wcstack/state` (`formats/builtinFilters.ts`).\n *\n * Numeric options are read **once, when the filter is built**: the checks stay in one place and the\n * `Number()` conversion stays off the apply path.\n */\nimport { optionMustBeNumber, optionsRequired } from \"./errorMessages\";\n\n/** `\"\"` and anything `Number()` cannot read are rejected (so `lt('')` is an error, not `lt(0)`). */\nexport function validateNumberString(value: string): boolean {\n if (!value || isNaN(Number(value))) {\n return false;\n }\n return true;\n}\n\n/** One numeric option, converted: non-numeric → `optionMustBeNumber`. */\nexport function numberOption(value: string, fnName: string): number {\n if (!validateNumberString(value)) {optionMustBeNumber(fnName);}\n return Number(value);\n}\n\n/** A required numeric option: missing → `optionsRequired`, non-numeric → `optionMustBeNumber`. */\nexport function requiredNumberOption(options: readonly string[] | undefined, index: number, fnName: string): number {\n return numberOption(options?.[index] ?? optionsRequired(fnName), fnName);\n}\n\n/**\n * The typed literal of the first argument (requirement B9): an unquoted `true` / `false` / `null` /\n * number arrives typed, a quoted argument as a string. Without literals (tooling calling a factory\n * directly) the raw option text stands in.\n */\nexport function firstLiteral(opt: string, literals: readonly unknown[] | undefined): unknown {\n return literals !== undefined && literals.length > 0 ? literals[0] : opt;\n}\n","/**\n * filters/core.ts — the core filter set (10): the conditions a binding tests, as opposed to the\n * values the formats add-on (`./formats`) computes and shows. Ported from `@wcstack/state`\n * (`formats/builtinFilters.ts`) with the semantics unchanged.\n *\n * - conditions: `eq ne not lt le gt ge truthy falsy boolean`\n *\n * The arithmetic (`add sub mul div mod abs clamp`), conversion (`number string int float`) and\n * missing-value (`defaults coalesce nullIfEmpty`) filters were here up to 4.0.0-rc.3; they are the\n * formats add-on's since, for the core's size target.\n *\n * `installCoreFilters()` puts them in the registry; the engine calls it before it plans bindings\n * (`else:` is built with an injected `not`, so the core set is never optional).\n */\nimport { optionMustBeNumber, optionsRequired, valueMustBeNumber } from \"./errorMessages\";\nimport { firstLiteral, requiredNumberOption, validateNumberString } from \"./options\";\nimport { registerFilters, type FilterDefinition, type FilterFn } from \"./registry\";\n\n/** Equality — compares with the option (a typed literal compares as itself, B9). */\nconst eq = (options: string[], literals?: readonly unknown[]): FilterFn => {\n const opt = options?.[0] ?? optionsRequired('eq');\n const literal = firstLiteral(opt, literals);\n return (value: unknown): boolean => {\n if (typeof value === 'number') {\n // A typed literal that is not a string compares as itself (B9): a number is never equal to\n // `true` / `false` / `null`, so `selectedId|eq(null)` is false once the id is a number instead\n // of throwing on every apply. Only an unquoted non-number (`eq(abc)`) still reports the type\n // mismatch, and it has to stay here: `eq` accepts values of any type (`status|eq(active)` is\n // valid), so it cannot be rejected at construction the way `lt` / `add` can.\n if (typeof literal !== 'string') {return value === literal;}\n if (!validateNumberString(opt)) {optionMustBeNumber('eq');}\n return value === Number(opt);\n }\n if (typeof value === 'string') {\n return value === opt;\n }\n // Booleans, null and the rest compare with the typed literal: eq(true) matches true (B9)\n return value === literal;\n };\n};\n\n/** Inequality — the negation of `eq`, with the same typing rules (B9). */\nconst ne = (options: string[], literals?: readonly unknown[]): FilterFn => {\n const opt = options?.[0] ?? optionsRequired('ne');\n const literal = firstLiteral(opt, literals);\n return (value: unknown): boolean => {\n if (typeof value === 'number') {\n if (typeof literal !== 'string') {return value !== literal;}\n if (!validateNumberString(opt)) {optionMustBeNumber('ne');}\n return value !== Number(opt);\n }\n if (typeof value === 'string') {\n return value !== opt;\n }\n return value !== literal;\n };\n};\n\n/**\n * Inverts truthiness (lenient `!value`). `else:` is built as the `if` condition plus an injected\n * `not`, and `if:` coerces with `Boolean()`; a strict `not` made `else:` throw — rendering neither\n * branch — whenever the condition was a falsy non-boolean (`0` / `\"\"` / `undefined` / `null`).\n */\nconst not = (): FilterFn => (value: unknown): boolean => !value;\n\n/**\n * A comparison or arithmetic filter: one numeric option, a number value (`lt` … `ge` here, `add` …\n * `mod` in the formats add-on).\n */\nexport const numeric = (name: string, op: (value: number, opt: number) => unknown): FilterDefinition => ({\n factory: (options: string[]): FilterFn => {\n const opt = requiredNumberOption(options, 0, name);\n return (value: unknown): unknown => {\n if (typeof value !== 'number') {valueMustBeNumber(name, value);}\n return op(value, opt);\n };\n },\n arity: [1, 1],\n});\n\n/** JavaScript's truthiness, the same as `boolean` (B10). */\nconst truthy = (): FilterFn => (value: unknown): boolean => !!value;\n\n/** JavaScript's falsiness (`!value`: false, null, undefined, 0, -0, 0n, '' and NaN — B10). */\nconst falsy = (): FilterFn => (value: unknown): boolean => !value;\n\nconst boolean = (): FilterFn => (value: unknown): boolean => Boolean(value);\n\n/**\n * The core set: factory and [min, max] argument count (B3 — the same bounds lint uses).\n *\n * The key order is the source's (`builtinFilterMeta`, which lint reads): the did-you-mean\n * suggestion breaks ties by registration order (see `installFormats` for the order the full\n * build registers).\n */\nexport const coreFilters: Readonly<Record<string, FilterDefinition>> = {\n eq: { factory: eq, arity: [1, 1] },\n ne: { factory: ne, arity: [1, 1] },\n not: { factory: not, arity: [0, 0] },\n lt: numeric('lt', (value, opt) => value < opt),\n le: numeric('le', (value, opt) => value <= opt),\n gt: numeric('gt', (value, opt) => value > opt),\n ge: numeric('ge', (value, opt) => value >= opt),\n falsy: { factory: falsy, arity: [0, 0] },\n truthy: { factory: truthy, arity: [0, 0] },\n boolean: { factory: boolean, arity: [0, 0] },\n};\n\nlet installed = false;\n\n/** Puts the core set in the registry. Idempotent; the engine calls it before planning any binding. */\nexport function installCoreFilters(): void {\n if (installed) return;\n installed = true;\n registerFilters(coreFilters);\n}\n","import type { ParsedFilter } from \"../parser/index\";\nimport { resolveFilter, type FilterFn } from \"../filters/registry\";\nimport { installCoreFilters } from \"../filters/core\";\n\nexport type { FilterFn };\n\n/** `v` through the filters `fs` (none when null). */\nexport function pipe(fs: FilterFn[] | null, v: unknown): unknown {\n if (fs !== null) for (let i = 0; i < fs.length; i++) v = fs[i](v);\n return v;\n}\n\n/**\n * Resolves a binding's parsed filters to functions (at plan time, once per binding spec).\n * The core filters (the conditions) are always available; the others come with the formats add-on\n * (`installFeatures([formats])`; the full build installs it).\n */\nexport function buildFilters(parsed: readonly ParsedFilter[]): FilterFn[] | null {\n if (parsed.length === 0) return null;\n installCoreFilters(); // idempotent\n return parsed.map((f) => resolveFilter(f.filterName, f.args, f.literals));\n}\n","/**\n * Trusted Types for the HTML sinks (`html:`, `innerHTML:`, `outerHTML:`, `srcdoc:`).\n * The policy lives on the same global slot as @wcstack/state, so a page that installed\n * one for the current engine keeps working:\n * globalThis[Symbol.for(\"wcstack.trustedTypes.policy\")] = trustedTypes.createPolicy(…)\n * No identity policy is ever created here — that would defeat the CSP.\n */\nexport interface TrustedTypesPolicy {\n createHTML?(input: string): unknown;\n}\n\nexport const TRUSTED_TYPES_POLICY_SLOT = Symbol.for(\"wcstack.trustedTypes.policy\");\n\ntype Slot = { [key: symbol]: unknown };\n\nexport function getTrustedTypesPolicy(): TrustedTypesPolicy | null {\n const value = (globalThis as Slot)[TRUSTED_TYPES_POLICY_SLOT];\n return value !== null && typeof value === \"object\" ? (value as TrustedTypesPolicy) : null;\n}\n\nexport function setTrustedTypesPolicy(policy: TrustedTypesPolicy | null): void {\n (globalThis as Slot)[TRUSTED_TYPES_POLICY_SLOT] = policy;\n}\n\nexport function isHtmlSink(prop: string): boolean {\n return prop === \"innerHTML\" || prop === \"outerHTML\" || prop === \"srcdoc\";\n}\n\n/**\n * A value for an HTML sink: a TrustedHTML (the page made it with its own policy) as it is, anything\n * else — an array or another object too, which the sink would turn into markup — as a string\n * (null / undefined: empty) passed through the installed policy (if any).\n */\nexport function trustHtml(value: unknown): unknown {\n if ((globalThis as any).trustedTypes?.isHTML(value)) return value;\n const s = value == null ? \"\" : String(value);\n const policy = getTrustedTypesPolicy();\n const create = policy?.createHTML;\n return typeof create === \"function\" ? create.call(policy, s) : s;\n}\n","import { getTransitionRunner } from \"../protocol/transitionRunner\";\nimport { M, text } from \"../messages\";\n\n/**\n * Automatic `view-transition-name` (docs/view-transition-design.md §6), as @wcstack/state\n * does it: when the page's arbiter declares `naming=\"auto\"`, the first element of every\n * row and `if` branch built gets a unique name. A name must be on the element before the\n * browser snapshots the old state, so it is given when the block is built, never renamed,\n * and capped (each named element is a snapshot group of its own).\n *\n * The ledger is per document (a `Symbol.for` slot shared with @wcstack/state), so two\n * bundles on one page never mint the same name.\n */\ninterface Ledger {\n counter: number;\n assigned: number;\n warned: boolean;\n}\n\nconst LEDGER_KEY = Symbol.for(\"wcstack.state.view-transition-naming\");\nconst named = new WeakSet<Element>();\n\n/** The naming cap when the arbiter names automatically, or -1 (the author names). */\nexport function autoNaming(): number {\n const runner = getTransitionRunner(\"state\");\n return runner !== null && runner.naming === \"auto\" ? runner.namingLimit : -1;\n}\n\n/** Names the first element of `nodes` (`wcs-row-3`, `wcs-branch-7`), within the cap. */\nexport function nameBlock(first: ChildNode, nodes: ChildNode[] | null, kind: \"row\" | \"branch\", limit: number): void {\n let el: Element | null = null;\n if (nodes === null) el = first.nodeType === 1 ? (first as Element) : null;\n else for (let i = 0; i < nodes.length && el === null; i++) if (nodes[i].nodeType === 1) el = nodes[i] as Element;\n const style = (el as HTMLElement | null)?.style;\n if (el === null || style === undefined || named.has(el)) return;\n const ledger = ((globalThis as any)[LEDGER_KEY] ??= { counter: 0, assigned: 0, warned: false }) as Ledger;\n if (ledger.assigned >= limit) {\n if (!ledger.warned) {\n ledger.warned = true;\n console.warn(`[@wcstack/state] ${text(M.NamingLimit, [limit])}`);\n }\n return;\n }\n named.add(el);\n ledger.assigned++;\n style.setProperty(\"view-transition-name\", `wcs-${kind}-${++ledger.counter}`);\n style.setProperty(\"view-transition-class\", `wcs-${kind}`);\n}\n","/**\n * Wiring to custom elements that declare the wc-bindable protocol:\n * static wcBindable = { protocol: \"wc-bindable\", version: 1,\n * properties: [{ name, event, getter?, semantics? }], // element → state\n * inputs: [{ name, attribute? }], // state → element\n * commands: [{ name, async? }] } // state invokes\n * Property bindings take their direction and initial authority from the declaration;\n * `command.<m>:` subscribes a method to a command token; `eventToken.<p>:` fires an event\n * token when the element dispatches that property's event; `...:` spreads a state object\n * over every declared property and input.\n */\nimport type { Engine } from \"../engine\";\nimport { raise, M } from \"../messages\";\nimport { hooks } from \"../hooks\";\nimport type { StateRow } from \"../list\";\nimport { adopt, Binding, failSpec, K_CUSTOM, type Block, type Spec } from \"./view\";\nimport { pipe } from \"./filters\";\nimport { report } from \"../parser/raiseError\";\n// (view.ts imports this module too: the cycle is fine, everything here is used at call time)\n\ninterface PropertyDecl {\n event: string;\n getter: ((e: Event) => unknown) | null;\n /** `semantics: \"event\"`: an occurrence, written even when equal to the current value. */\n occurrence: boolean;\n}\n\nexport interface Bindable {\n properties: Map<string, PropertyDecl>;\n /** The settable members. Their `attribute` hint is not used: the element reflects its own attributes. */\n inputs: Set<string>;\n commands: Set<string>;\n}\n\nconst bindableByClass = new WeakMap<CustomElementConstructor, Bindable | null>();\n\n/** The element's wc-bindable declaration (null when it has none), cached per class. */\nexport function readBindable(cls: CustomElementConstructor): Bindable | null {\n if (bindableByClass.has(cls)) return bindableByClass.get(cls)!;\n const decl = (cls as any).wcBindable;\n let out: Bindable | null = null;\n if (decl !== null && typeof decl === \"object\" && decl.protocol === \"wc-bindable\" && Number.isInteger(decl.version) && decl.version >= 1) {\n out = { properties: new Map(), inputs: new Set(), commands: new Set() };\n for (const p of decl.properties ?? []) {\n out.properties.set(p.name, { event: p.event, getter: typeof p.getter === \"function\" ? p.getter : null, occurrence: p.semantics === \"event\" });\n }\n for (const i of decl.inputs ?? []) out.inputs.add(i.name);\n for (const c of decl.commands ?? []) if (c !== null && typeof c === \"object\" && typeof c.name === \"string\") out.commands.add(c.name);\n }\n bindableByClass.set(cls, out);\n return out;\n}\n\n/** The registry that defines `el`: a scoped one (`attachShadow({ customElementRegistry })`) or the global one. */\nexport const registryOf = (el: Element): CustomElementRegistry =>\n ((el as any).customElementRegistry as CustomElementRegistry | null | undefined) ?? customElements;\n\n/**\n * Runs `attach` (for spec `s`) once the element's class is defined (at once when it already is) and\n * upgraded, unless its block went away in the meantime (`pending`). A native element has no definition to wait\n * for: it is attached at once (and refused there, as a custom element with no declaration is).\n */\nexport function whenDefined(engine: Engine, s: Spec, el: Element, owner: Block | null, attach: (bindable: Bindable | null) => void, later = false): void {\n const tag = el.localName;\n if (!tag.includes(\"-\")) return attach(null);\n const r = registryOf(el);\n // a row built in a fragment takes the registry of the shadow root it goes into (a scoped one)\n // when it is placed, in this drain: wait for that before waiting for a definition\n if (!later && !el.isConnected && r.get(tag) === undefined && \"customElementRegistry\" in el) {\n queueMicrotask(() => whenDefined(engine, s, el, owner, attach, true));\n return;\n }\n const run = (): void => {\n const cls = r.get(tag);\n r.upgrade(el);\n attach(cls ? readBindable(cls) : null);\n };\n if (!later && r.get(tag) !== undefined) return run();\n // a row gone while it waited for its registry waits for nothing (its block's cleanups have run)\n if (owner !== null && !owner.alive) return;\n // later, outside any drain: a failure is the binding's; it and what was applied are reported by\n // a drain (one for every element the definition upgrades: one `$renderedCallback`)\n pending(r.whenDefined(tag), owner, () => {\n try {\n run();\n } catch (error) {\n failSpec(engine, error, s, el);\n }\n engine.schedule();\n });\n}\n\n/**\n * Runs `fn` once `p` settles, unless `owner` went away first. Its own scope: the reaction holds\n * only `f`, so a removed row of a tag never defined keeps nothing alive.\n */\nfunction pending(p: Promise<unknown>, owner: Block | null, fn: () => void): void {\n let f: (() => void) | null = fn;\n if (owner !== null) (owner.cleanups ??= []).push(() => {\n f = null;\n });\n void p.then(() => f?.());\n}\n\n/** A property binding on a member of a custom element's wc-bindable declaration. */\nexport function attachProperty(engine: Engine, spec: Spec, el: Element, name: string, pattern = spec.pattern!,\n row: StateRow | null, owner: Block | null, bd: Bindable): Binding {\n const out = bd.properties.get(name) ?? null;\n const input = bd.inputs.has(name);\n // enableDirectionalInitialSync off (3.x opt-out): no member checks (and no init= / sync=, see\n // plan.ts); state wins every initial sync, output-only included\n const directional = engine.directional;\n if (directional && out === null && !input) raise(M.MemberUndeclared, [name]);\n // what the member's shape allows: output-only takes element / none, input-only state / none, two-way any\n const init = spec.init;\n const refused = out === null ? init === \"element\" || init === \"auto\" : !input && (init === \"state\" || init === \"auto\");\n if (refused) raise(M.InitIncompatible, [init, name]);\n if (spec.sync === \"connect\" && out === null) raise(M.SyncConnectNeedsOutput, [name]);\n const outputOnly = directional && out !== null && !input;\n const b = new Binding(engine, K_CUSTOM, el, name, pattern, row, owner, spec.filters, undefined);\n b.inFilters = spec.inFilters;\n // state → element (every member but an output-only one)\n adopt(engine, b, !outputOnly);\n // element → state (a declared property)\n if (out !== null && !spec.ro) {\n el.addEventListener(out.event, (e) => {\n let v: unknown;\n if (out.getter !== null) v = out.getter(e);\n else {\n v = (e as CustomEvent).detail;\n // the protocol's default getter: diagnostics tells the two shapes it can see are wrong\n if (!out.occurrence) hooks.detail?.(el, name, v);\n }\n if (b.applying && Object.is(v, b.value)) return; // our own write echoing back\n v = pipe(b.inFilters, v);\n // the element already shows this value: the apply this write causes must not echo it\n // back to the element it came from\n if (b.filters === null) b.value = v;\n engine.write(b.pattern, b.row, v, out.occurrence, true);\n });\n }\n // initial authority: output-only members seed state from the element, others the other way\n const authority = init ?? (outputOnly ? \"element\" : \"state\");\n if (authority === \"state\") {\n if (!outputOnly) engine.applyBinding(b);\n } else if (authority === \"element\" || authority === \"auto\") {\n const seed = (): void => {\n if (owner !== null && !owner.alive) return;\n if (authority === \"auto\" && engine.readUntracked(b.pattern, b.row) !== undefined) {\n if (!outputOnly) engine.applyBinding(b);\n return;\n }\n const snapshot = (el as any)[name];\n if (b.filters === null) b.value = snapshot; // seeded from the element: nothing to write back\n engine.write(b.pattern, b.row, snapshot, false, true);\n };\n if (spec.sync === \"connect\" && !el.isConnected) void Promise.resolve().then(seed);\n else seed();\n }\n return b;\n}\n\nfunction noBindable(id: M, el: Element, what: string): never {\n raise(id, [el.localName, what]);\n}\n\n/**\n * `command.<method>: $command.<token>` — the element's method subscribes to the token. A native\n * element (no declaration) is called the way the native-commands add-on says, when installed.\n */\nexport function attachCommand(engine: Engine, spec: Spec, el: Element, owner: Block | null, bd: Bindable | null): void {\n const method = spec.name;\n // (the path, \"$command.<token>\")\n const token = engine.command(spec.token!.slice(9));\n const call = bd === null ? hooks.nativeCommand?.(el, method) : null;\n if (!call) {\n if (bd === null) noBindable(M.NoBindable, el, `command.${method}`);\n if (!bd.commands.has(method)) raise(M.NoCommand, [el.localName, method]);\n }\n const ref = new WeakRef(el);\n const fn = (...args: unknown[]): unknown => {\n const target = ref.deref() as any;\n if (target === undefined) {\n unsubscribe();\n return undefined;\n }\n // detached for now (a route hidden with its nodes kept): not called, still subscribed\n return target.isConnected ? (call ? call(target, args) : target[method](...args)) : undefined;\n };\n const unsubscribe = token.subscribe(fn);\n if (owner !== null) (owner.cleanups ??= []).push(unsubscribe);\n}\n\n/** `eventToken.<property>: <token>` — the property's event fires the event token. */\nexport function attachEventToken(engine: Engine, spec: Spec, el: Element, row: StateRow | null, bd: Bindable | null): void {\n const prop = spec.name;\n if (bd === null) noBindable(M.NoBindable, el, `eventToken.${prop}`);\n const decl = bd.properties.get(prop);\n if (decl === undefined) raise(M.NoProperty, [el.localName, prop]);\n const name = spec.token!;\n el.addEventListener(decl.event, (e) => {\n if (spec.prevent) e.preventDefault();\n if (spec.stop) e.stopPropagation();\n try {\n engine.fireEventToken(name, e, row);\n } catch (error) {\n report(error);\n }\n });\n}\n\n/** `...: path` — one property binding per declared property and input (explicit bindings win). */\nexport function attachSpread(engine: Engine, spec: Spec, el: Element, row: StateRow | null, owner: Block | null, bd: Bindable | null): void {\n if (bd === null) noBindable(M.SpreadNoBindable, el, `\"...: ${spec.pattern!.path}\"`);\n const names = new Set([...bd.properties.keys(), ...bd.inputs]);\n for (const name of names) {\n if (spec.exclude?.includes(name)) continue;\n const p = engine.pattern(`${spec.pattern!.path}.${name}`);\n const r = p.depth === 0 ? null : row;\n attachProperty(engine, { ...spec, init: null, sync: null }, el, name, p, r, owner, bd);\n }\n}\n","import { rowAt, type Engine } from \"../engine\";\nimport type { Pattern } from \"../pattern\";\nimport type { StateList, StateRow } from \"../list\";\nimport { pipe, type FilterFn } from \"./filters\";\nimport { isHtmlSink, trustHtml } from \"../trustedTypes\";\nimport { autoNaming, nameBlock } from \"./naming\";\nimport { raise, M } from \"../messages\";\nimport { hooks } from \"../hooks\";\n\n/**\n * `on*:` bindings of bubbling events are delegated: one listener per event type on the root\n * (so `event.currentTarget` is the root — decided 2026-09-25), which runs the handlers of the\n * elements the event passed, innermost first. Inside a block the handler is not attached to the\n * element at all: the block's top node carries the block, which finds its handlers from its plan\n * when an event passes (Block.dispatch). Outside any block (a root-level element), where a\n * block's content can shift before the element (see compilePlan), and on a custom element, the\n * handler is stored on the element. A custom element may dispatch such an event without bubbling\n * (the root never hears it): that one is heard on the element. A non-bubbling event type gets a\n * listener on the element itself.\n *\n * `on*#direct:` is not delegated: a listener on the element itself, as 3.x (`currentTarget` is the\n * element) — `#stop` stops the page's own listeners on its ancestors, an ancestor's\n * `stopPropagation()` does not keep it from running, and an element moved under another root still\n * runs it. In a block (a row, a branch) it is attached with the block and removed when the block\n * goes. It runs where the DOM puts it: an outer `#direct` runs before the delegated handlers inside\n * it (they run at the root), so an inner `#stop` stops it only if the inner one is `#direct` too.\n */\nexport function attachEvent(engine: Engine, node: Node, s: Spec, row: StateRow | null, block: Block | null): void {\n const fn = s.listener!;\n const h = (e: Event): void => fn(e, row);\n if (s.delegated) {\n const key = engine.delegate(s.name);\n const prev = (node as any)[key];\n // two of one type on one element (`onclick: a; onclick: b`): both run\n (node as any)[key] = prev === undefined ? h : (e: Event): void => {\n prev(e);\n h(e);\n };\n if (s.custom) node.addEventListener(s.name, (e) => e.bubbles || h(e));\n } else {\n node.addEventListener(s.name, h);\n if (s.direct && block !== null) (block.cleanups ??= []).push(() => node.removeEventListener(s.name, h));\n }\n}\n\n/** Events that bubble: the only ones a delegated listener can see. */\nexport const BUBBLING = new Set([\"click\", \"dblclick\", \"input\", \"change\", \"submit\", \"keydown\", \"keyup\", \"mousedown\", \"mouseup\", \"pointerdown\", \"pointerup\"]);\n\nimport { attachCommand, attachEventToken, attachProperty, attachSpread, whenDefined, type Bindable } from \"./wc\";\n\nexport const K_TEXT = 0;\nexport const K_PROP = 1;\nexport const K_CLASS = 2;\nexport const K_ATTR = 3;\nexport const K_STYLE = 4;\nexport const K_EVENT = 5;\nexport const K_FOR = 6;\nexport const K_IF = 7;\nexport const K_HTML = 8;\nexport const K_RADIO = 9;\nexport const K_CHECKBOX = 10;\n/** A property of a custom element (direction and authority from its wc-bindable declaration). */\nexport const K_CUSTOM = 11;\nexport const K_COMMAND = 12;\nexport const K_EVTTOKEN = 13;\nexport const K_SPREAD = 14;\n\n\nexport interface BranchSpec {\n /** Index into the plan's node paths: the anchor this branch renders before. */\n node: number;\n plan: RowPlan;\n /** null for `else:`. */\n pattern: Pattern | null;\n filters: FilterFn[] | null;\n}\n\nexport interface Spec {\n /** Index into the plan's node paths (unused at the root). */\n node: number;\n kind: number;\n /** Property / class / attribute / style name, or the event type. */\n name: string;\n pattern: Pattern | null;\n filters: FilterFn[] | null;\n /** What the DOM already shows, so the first apply can skip a no-op write. */\n initial: unknown;\n /** Event handler, run for the row of the block the element is in (null outside rows). */\n listener: ((e: Event, row: StateRow | null) => void) | null;\n /** An event binding whose type bubbles: dispatched from the root listener. */\n delegated: boolean;\n /** `on*#direct:`: a listener on the element itself (see attachEvent). */\n direct: boolean;\n /** The row plan of a nested `for`. */\n plan: RowPlan | null;\n /** The branches of an `if` / `elseif` / `else` chain. */\n branches: BranchSpec[] | null;\n /** Input filters (left side), applied to what the element writes back. */\n inFilters: FilterFn[] | null;\n /** The event that writes the element's value back to state (two-way, radio, checkbox), or null. */\n twoWay: string | null;\n /** On a custom element: the binding is resolved when the element's class is defined. */\n custom: boolean;\n /** `#init=` / `#sync=` (binding authority on wc-bindable members). */\n init: string | null;\n sync: string | null;\n /** `#ro`: the element never writes back. */\n ro: boolean;\n prevent: boolean;\n stop: boolean;\n /** The path a command / event token binding names: `$command.<token>` / the event token's name. */\n token: string | null;\n /** Spread: members bound explicitly after it on the same element (last wins). */\n exclude: string[] | null;\n /**\n * In a row plan: the index of this binding among the row's slots (-1 = a Binding object is\n * built with the row). A slot binding reads its own row and needs nothing from the element,\n * so the row keeps only its node and value until a change reaches it.\n */\n slot: number;\n}\n\nexport interface RowPlan {\n fragment: DocumentFragment;\n /** The single top-level node (when `single`), cloned directly instead of the fragment. */\n root: Node | null;\n /** Reused per block creation (nodes are handed to bindings before the next block). */\n scratch: Node[];\n /** The child-index path of every bound node (from the fragment). */\n nodePaths: number[][];\n /** The node paths a block resolves when it is built (the others serve only delegated events). */\n build: number[];\n /** The delegated event specs found through the block (by their node paths) when an event passes. */\n events: Spec[];\n /** The specs bound as a block is built (all but `events`). */\n specs: Spec[];\n /** The block renders exactly one top-level node. */\n single: boolean;\n /** Some spec builds a nested view (for / if): the scratch nodes must be copied first. */\n nested: boolean;\n /** The slot specs of a row plan, by slot index (empty for a branch plan). */\n lazy: Spec[];\n}\n\n/**\n * A binding's type as the parser classifies it (@wcstack/state 3.x reports the same in\n * `$errorCallback`'s info, the console and DevTools): `class.` / `attr.` / `style.` / `command.`\n * and HTML are properties, `eventToken.` is an event.\n */\nconst TYPE_NAMES = [\"text\", \"prop\", \"prop\", \"prop\", \"prop\", \"event\", \"for\", \"if\", \"prop\", \"radio\", \"checkbox\", \"prop\", \"prop\", \"event\", \"spread\"];\n\n/** A binding refused as it is attached fails alone (reported as its own failure). */\nexport const failSpec = (engine: Engine, error: unknown, s: Spec, node: Node): void =>\n engine.failAt(error, s.pattern?.path ?? s.token!, node, TYPE_NAMES[s.kind]);\n\n/** A binding's first value when #init= leaves the element as it is: its first apply only records the value. */\nconst HOLD: unique symbol = Symbol() as never;\n\n/**\n * The first value of a binding on an element with no wc-bindable declaration. `#init=none` and\n * `element`, and `auto` over an undefined state value, leave the element as it is (3.3): the\n * value is still read (a getter must be, for a change to reach it) and applied from the next change.\n */\nexport function initialOf(engine: Engine, s: Spec, row: StateRow | null): unknown {\n const init = s.init;\n return init === null || init === \"state\" || (init === \"auto\" && engine.readUntracked(s.pattern!, row) !== undefined) ? s.initial : HOLD;\n}\n\nexport class Binding {\n queued = false;\n declare readonly engine: Engine;\n declare readonly kind: number;\n declare readonly node: Node;\n declare readonly name: string;\n declare readonly pattern: Pattern;\n /** Row at pattern.depth (null for a root-level pattern). */\n declare readonly row: StateRow | null;\n /** The block that renders this binding (null at the root). */\n declare readonly owner: Block | null;\n declare readonly filters: FilterFn[] | null;\n /** Input filters for the value the element writes back. */\n inFilters: FilterFn[] | null = null;\n /** The `if` chain an `if`/`elseif` condition drives. */\n declare readonly chain: IfView | null;\n declare value: unknown;\n /** Set while state writes the element (an event it fires synchronously is our own echo). */\n applying = false;\n\n constructor(engine: Engine, kind: number, node: Node, name: string, pattern: Pattern,\n row: StateRow | null, owner: Block | null, filters: FilterFn[] | null, initial: unknown, chain: IfView | null = null) {\n this.engine = engine;\n this.kind = kind;\n this.node = node;\n this.name = name;\n this.pattern = pattern;\n this.row = row;\n this.owner = owner;\n this.filters = filters;\n this.value = initial;\n this.chain = chain;\n }\n\n typeName(): string {\n return TYPE_NAMES[this.kind];\n }\n\n apply(): void {\n if (this.chain !== null) {\n this.chain.update();\n return;\n }\n const v = pipe(this.filters, this.engine.read(this.pattern, this.row));\n // the same object may have changed in place ($postUpdate, an array assigned again): shown\n // again — but an element input keeps the object it already has, and an HTML sink the markup it\n // parsed (a TrustedHTML does not change: parsing it again would rebuild the nodes). A radio is\n // set again: checking another one of its group unchecked it.\n if (v === this.value && this.kind !== K_RADIO && (typeof v !== \"object\" || v === null || this.kind === K_CUSTOM || this.kind === K_HTML || isHtmlSink(this.name))) return;\n if (this.value === HOLD) {\n this.value = v;\n return;\n }\n const n = this.node as any;\n if (this.kind === K_CUSTOM) {\n if (v === undefined) {\n // an element input keeps its own value when state has no opinion (B8)\n this.value = v;\n return;\n }\n this.value = v;\n this.applying = true;\n try {\n if (n[this.name] !== v) n[this.name] = v;\n } finally {\n this.applying = false;\n }\n return;\n }\n if (this.kind === K_RADIO) n.checked = v !== undefined && this.elementValue() === v;\n else if (this.kind === K_CHECKBOX) n.checked = Array.isArray(v) && v.includes(this.elementValue());\n else applyTo(this.kind, n, this.name, v);\n this.value = v;\n }\n\n /** The element's own value (radio / checkbox), through the input filters. */\n elementValue(): unknown {\n return pipe(this.inFilters, (this.node as any).value);\n }\n\n /** Writes the element's value back to state (two-way, radio, checkbox). */\n writeBack(): void {\n const n = this.node as any;\n const engine = this.engine;\n let v: unknown;\n if (this.kind === K_RADIO) {\n if (!n.checked) return;\n v = this.elementValue();\n } else if (this.kind === K_CHECKBOX) {\n const e = this.elementValue();\n const cur = engine.readUntracked(this.pattern, this.row);\n const arr = Array.isArray(cur) ? cur : [];\n const has = arr.includes(e);\n // checked and listed, or neither: nothing to write\n if (n.checked ? has : !has) return;\n v = has ? arr.filter((x) => x !== e) : [...arr, e];\n } else {\n v = pipe(this.inFilters, n[this.name]);\n // the element shows its own value now, not the last applied one: the next apply runs (NaN\n // equals nothing) — a write in the same drain may put that value back (a reset, a validation)\n this.value = NaN;\n }\n engine.write(this.pattern, this.row, v, false, true);\n }\n}\n\n/** A property that is the element's content (its children are a value). */\nexport const isContent = (name: string): boolean => name === \"textContent\" || name === \"innerText\" || name === \"innerHTML\";\n\n/**\n * Writes `v` to the element: the kinds that need nothing but the node and the name (the\n * ones a row slot can hold).\n */\nexport function applyTo(kind: number, n: any, name: string, v: unknown): void {\n switch (kind) {\n case K_TEXT:\n n.data = v == null ? \"\" : String(v);\n return;\n case K_PROP:\n // display surfaces: undefined and null both mean \"no value\" (B8); other properties are element inputs\n if (isContent(name)) {\n // a string, as a browser's setter makes it (happy-dom — the server's DOM — writes 0 as \"\", and\n // throws on a number for innerText); innerHTML keeps a TrustedHTML as it is\n n[name] = name === \"innerHTML\" ? trustHtml(v) : v == null ? \"\" : String(v);\n } else if (isHtmlSink(name)) {\n // srcdoc without a value: the attribute goes (the frame shows its src again, as attr.srcdoc:\n // did); outerHTML: undefined writes nothing (\"\" would take the element itself out)\n if (v == null && name === \"srcdoc\") n.removeAttribute(name);\n else if (v !== undefined) n[name] = trustHtml(v);\n } else if (v !== undefined) {\n // undefined: an element input keeps its own value when state has no opinion (B8);\n // never re-write what the element already shows (keeps the caret while typing)\n if (n[name] !== v && !(name === \"value\" && n.value === String(v))) n[name] = v;\n // a select's value may name an option not rendered yet: kept for reselect\n if ((name === \"value\" || name === \"selectedIndex\") && n.localName === \"select\") n[SELECTED] = [name, v];\n }\n return;\n case K_HTML:\n n.innerHTML = trustHtml(v);\n return;\n case K_CLASS:\n if (v != null && typeof v !== \"boolean\") {\n raise(M.ClassNeedsBoolean, [name, typeof v]);\n }\n n.classList.toggle(name, v === true);\n return;\n case K_ATTR:\n if (v == null) n.removeAttribute(name);\n else n.setAttribute(name, String(v));\n return;\n case K_STYLE:\n // the property as CSS writes it (background-color, --gap), or as the DOM does\n // (backgroundColor, which setProperty ignores; 3.x wrote style[name])\n if (!name.includes(\"-\")) n.style[name] = v == null ? \"\" : String(v);\n else if (v == null) n.style.removeProperty(name);\n else n.style.setProperty(name, String(v));\n return;\n }\n}\n\n/** A select's last bound `value` / `selectedIndex`: [name, value]. */\nconst SELECTED: unique symbol = Symbol() as never;\n\n/**\n * A view rendered options into `parent`: the select's bound value is applied again. A block binds\n * its plan in document order, so a select's value there comes before the options a `for` inside\n * it renders, and names none of them; so does a value applied before a later change renders more\n * options (3.3 applies it after the options). (On the page a select's children are bound first.)\n */\nfunction reselect(parent: Node): void {\n const sel: any = (parent as Element).localName === \"optgroup\" ? parent.parentNode : parent;\n const r = sel?.[SELECTED];\n if (r !== undefined) sel[r[0]] = r[1];\n}\n\n/**\n * One rendering of a plan: a list row (RowView) or the content of an `if` branch.\n * It owns its nodes, its bindings and the structural views nested in it.\n */\nexport class Block {\n alive = true;\n /** The row this block renders in (its own row for a RowView; the enclosing row, or null, for an if branch). */\n declare readonly row: StateRow | null;\n declare readonly first: ChildNode;\n /** All top-level nodes when the plan renders more than one. */\n declare readonly nodes: ChildNode[] | null;\n /** The Binding objects built with this block, unregistered when it goes (allocated on first use). */\n bindings: Binding[] | null = null;\n children: (ForView | IfView)[] | null = null;\n /** Run when the block goes away (token unsubscriptions); allocated on first use. */\n cleanups: (() => void)[] | null = null;\n /** The view anchored at the block's first top-level node: it renders before the block's first node. */\n lead: ForView | IfView | null = null;\n declare readonly plan: RowPlan;\n\n constructor(row: StateRow | null, first: ChildNode, nodes: ChildNode[] | null, plan: RowPlan) {\n this.row = row;\n this.first = first;\n this.nodes = nodes;\n this.plan = plan;\n }\n\n /**\n * An event of `type` reached this block's top node: runs the handlers of the block's\n * elements it passed, innermost first. Returns true when one of them stopped it.\n */\n dispatch(type: string, e: Event): boolean {\n const target = e.target as Node;\n const plan = this.plan;\n // the specs are in document order (an element's own together): the elements the event passed\n // are met outermost first, so each one's handlers go in front — innermost first\n const hits: Spec[][] = [];\n let last: Node | null = null;\n for (const s of plan.events) {\n if (s.name !== type) continue;\n const path = plan.nodePaths[s.node];\n const n = nodeAt(this.nodes === null ? this.first : this.nodes[path[0]], path, 1);\n if (!n.contains(target)) continue;\n if (n !== last) hits.unshift([]);\n hits[0].push(s);\n last = n;\n }\n // stopPropagation stops the elements further out, not the rest of the same element's (as the DOM)\n for (const own of hits) {\n for (const s of own) s.listener!(e, this.row);\n if (e.cancelBubble) return true;\n }\n return false;\n }\n\n get last(): ChildNode {\n return this.nodes === null ? this.first : this.nodes[this.nodes.length - 1];\n }\n\n /**\n * The block's first node. A view nested at the block's top level renders before its anchor, so\n * the block spans from here to its last top-level node, the rows and branches of those views\n * included.\n */\n head(): ChildNode {\n const v = this.lead;\n return (v === null ? null : v.headAt(this.first)) ?? this.first;\n }\n\n insertBefore(parent: Node, ref: Node | null): void {\n const last = this.last;\n for (let n = this.head(); ; ) {\n const next = n.nextSibling!;\n parent.insertBefore(n, ref);\n if (n === last) return;\n n = next;\n }\n }\n\n removeNodes(): void {\n if (this.nodes === null) this.first.remove();\n else removeContiguous(this.head(), this.last);\n }\n\n /** Stops the block: runs its cleanups, unregisters its bindings, disposes the views nested in it. */\n dispose(engine: Engine): void {\n this.alive = false;\n if (this.cleanups !== null) for (const c of this.cleanups) c();\n const bs = this.bindings;\n if (bs !== null) for (let i = 0; i < bs.length; i++) engine.unregister(bs[i]);\n if (this.children !== null) for (const c of this.children) c.dispose();\n }\n}\n\n/**\n * The rendering of one row by one for view. Its slot bindings (plan.lazy) are kept as\n * node / value pairs and become Binding objects only when a change first reaches them:\n * creating a row allocates no Binding for them and registers nothing — a change of the\n * row finds them through the row's views (Engine.enqueueBound).\n */\nexport class RowView extends Block {\n /** Position in the view's previous order (set during an update). */\n pos = 0;\n /** [node0, value0, node1, value1, …] by slot; the value is the last one applied. */\n declare readonly slots: unknown[] | null;\n /** The Binding objects the slots became (sparse, allocated on first use). */\n bound: (Binding | undefined)[] | null = null;\n\n constructor(row: StateRow, first: ChildNode, nodes: ChildNode[] | null, plan: RowPlan) {\n super(row, first, nodes, plan);\n this.slots = plan.lazy.length === 0 ? null : new Array(plan.lazy.length * 2);\n }\n\n /** The Binding object of slot k (built on first use; from then on it holds the value). */\n slotBinding(engine: Engine, k: number): Binding {\n const bound = (this.bound ??= new Array(this.plan.lazy.length));\n let b = bound[k];\n if (b === undefined) {\n const s = this.plan.lazy[k];\n const slots = this.slots!;\n b = bound[k] = new Binding(engine, s.kind, slots[2 * k] as Node, s.name, s.pattern!, this.row, this, s.filters, slots[2 * k + 1]);\n }\n return b;\n }\n\n /** Queues the slot bindings on `p` or under it. */\n enqueueSlots(engine: Engine, p: Pattern): void {\n const lazy = this.plan.lazy;\n for (let k = 0; k < lazy.length; k++) if (lazy[k].pattern!.isUnder(p)) engine.enqueue(this.slotBinding(engine, k));\n }\n\n override dispose(engine: Engine): void {\n const row = this.row!;\n if (row.view === this) row.view = null;\n super.dispose(engine);\n }\n}\n\n/**\n * The list whose rows `p` ranges over, in the context of `row`. A path that fails to read\n * (a missing top-level key) is reported as the `for` binding's failure and the list starts\n * empty: it was created before the read, so a later write of the path fills it.\n */\nexport function listFor(engine: Engine, p: Pattern, row: StateRow | null, anchor: Node): StateList {\n const parent = rowAt(row, p.depth);\n try {\n return engine.childList(parent, p);\n } catch (error) {\n engine.failAt(error, p.path, anchor, \"for\");\n return parent === null ? engine.rootLists.get(p)! : parent.children!.get(p)!;\n }\n}\n\n/**\n * Records `b` in its block (unregistered when the block goes) and, unless it only carries\n * element → state, registers it where a change of its location finds it.\n */\nexport function adopt(engine: Engine, b: Binding, register: boolean): void {\n if (register) engine.register(b);\n const owner = b.owner;\n if (owner !== null) (owner.bindings ??= []).push(b);\n}\n\n/** The block built by the last buildBlock call (taken right after it; saves an allocation per row). */\nlet lastBlock: Block | null = null;\n\n/** The block the last buildBlock call built; released here so a removed tree is not kept alive. */\nfunction takeBlock(): Block {\n const b = lastBlock!;\n lastBlock = null;\n return b;\n}\n\n/** The auto-naming cap for the blocks being built (-1: none), read once per view update. */\nlet naming = -1;\n\n/**\n * Clones the plan in the context of `row`, binds it and applies the initial values\n * (off-document). `fv`: the for view the block is a row of (null for an if branch).\n * Returns the node to insert: the block's element, or a fragment of its nodes.\n */\nexport function buildBlock(engine: Engine, plan: RowPlan, row: StateRow | null, fv: ForView | null, at: Node | null = null): Node {\n const paths = plan.nodePaths;\n const build = plan.build;\n const nodes = plan.scratch;\n let first: ChildNode;\n let all: ChildNode[] | null = null;\n // SSR hydration: the server's nodes, where they are (the add-on put the plan's nodes in them in\n // `nodes`); the view then inserts an empty fragment\n const adopted = hooks.adopt?.(plan, fv === null ? at! : fv.anchor, fv !== null);\n const single = !adopted && plan.single;\n // a single plan clones the block's element itself; paths start at the fragment, so skip their first step\n const top = adopted ? document.createDocumentFragment() : (single ? plan.root! : plan.fragment).cloneNode(true);\n if (!adopted) for (let b = 0; b < build.length; b++) {\n const i = build[b];\n nodes[i] = nodeAt(top, paths[i], single ? 1 : 0);\n }\n if (single) {\n first = top as ChildNode;\n } else {\n all = adopted || [...top.childNodes] as ChildNode[];\n first = all[0];\n }\n let block: Block;\n let rv: RowView | null = null;\n if (fv !== null) {\n block = rv = new RowView(row!, first, all, plan);\n if (fv.map === null) row!.view = rv;\n else fv.map.set(row!, rv);\n } else {\n block = new Block(row, first, all, plan);\n }\n if (naming >= 0) nameBlock(first, all, fv !== null ? \"row\" : \"branch\", naming);\n if (plan.events.length > 0) {\n // delegated events find the block through its top node(s)\n const key = engine.blockKey;\n if (all === null) (first as any)[key] = block;\n else for (const n of all) if (n.nodeType === 1) (n as any)[key] = block;\n }\n const specs = plan.specs;\n const rendered = engine.rendered;\n // the scratch array is ours until a nested view builds a block of another plan: take\n // every node we need before that can happen\n const own = plan.nested ? nodes.slice(0, paths.length) : nodes;\n const slots = rv === null ? null : rv.slots;\n if (slots !== null) {\n // every slot has its node before anything runs: an element bound earlier in the row can\n // write state (wc-bindable seeding) and so reach a slot further on\n const lazy = plan.lazy;\n for (let k = 0; k < lazy.length; k++) {\n slots[2 * k] = own[lazy[k].node];\n slots[2 * k + 1] = lazy[k].initial;\n }\n }\n for (let i = 0; i < specs.length; i++) {\n const s = specs[i];\n const node = own[s.node];\n const k = s.slot;\n if (k >= 0 && slots !== null) {\n // a slot: the node and the value are all the row keeps\n const b = rv!.bound?.[k];\n if (b !== undefined) {\n // already reached by a change during this build: it is a Binding now, applied here (and\n // so no longer queued: the drain skips it)\n b.queued = false;\n engine.applyBinding(b);\n continue;\n }\n try {\n const v = pipe(s.filters, engine.read(s.pattern!, row));\n if (v !== s.initial) {\n applyTo(s.kind, node, s.name, v);\n slots[2 * k + 1] = v;\n }\n if (rendered !== null) engine.noteRendered(s.pattern!, row);\n } catch (error) {\n engine.fail(error, rv!.slotBinding(engine, k));\n }\n continue;\n }\n switch (s.kind) {\n case K_FOR: {\n const view = new ForView(engine, s.plan!, listFor(engine, s.pattern!, row, node), node as Comment);\n (block.children ??= []).push(view);\n if (node === first) block.lead = view;\n view.update();\n break;\n }\n case K_IF: {\n const iv = attachChain(engine, s.branches!.map((br) => ({ plan: br.plan, pattern: br.pattern, filters: br.filters, anchor: own[br.node] })), row, block);\n (block.children ??= []).push(iv);\n if (node === first) block.lead = iv;\n break;\n }\n default:\n // (the delegated events found through the block are not among the specs: nothing per row)\n // A binding refused as it is attached (an undeclared token or member, a failing `#init=auto`\n // read) fails alone: the row is still built whole, so its view's records stay right\n try {\n attachSpec(engine, s, node, row, block);\n } catch (error) {\n failSpec(engine, error, s, node);\n }\n }\n }\n lastBlock = block;\n return top;\n}\n\n/**\n * Binds a spec that builds no view to `node`, in `block` (null: a root-level element). A\n * delegated event that reaches here is stored on the element (attachEvent).\n */\nexport function attachSpec(engine: Engine, s: Spec, node: Node, row: StateRow | null, block: Block | null): void {\n const el = node as Element;\n switch (s.kind) {\n case K_EVENT:\n attachEvent(engine, node, s, row, block);\n return;\n case K_COMMAND:\n whenDefined(engine, s, el, block, (bd) => attachCommand(engine, s, el, block, bd));\n return;\n case K_EVTTOKEN:\n whenDefined(engine, s, el, block, (bd) => attachEventToken(engine, s, el, row, bd));\n return;\n }\n const p = s.pattern!;\n const brow = rowAt(row, p.depth);\n if (s.kind === K_SPREAD) {\n whenDefined(engine, s, el, block, (bd) => attachSpread(engine, s, el, brow, block, bd));\n return;\n }\n if (s.custom && s.kind === K_PROP) {\n whenDefined(engine, s, el, block, (bd) => attachCustomOrPlain(engine, s, el, brow, block, bd));\n return;\n }\n const b = new Binding(engine, s.kind, node, s.name, p, brow, block, s.filters, initialOf(engine, s, brow));\n b.inFilters = s.inFilters;\n adopt(engine, b, true);\n engine.applyBinding(b);\n if (s.twoWay !== null) node.addEventListener(s.twoWay, () => b.writeBack());\n}\n\n/** A property binding on a custom element: wc-bindable members get direction and authority, others are plain. */\nexport function attachCustomOrPlain(engine: Engine, s: Spec, el: Element, row: StateRow | null, owner: Block | null, bd: Bindable | null): void {\n if (bd !== null) {\n attachProperty(engine, s, el, s.name, s.pattern!, row, owner, bd);\n return;\n }\n const b = new Binding(engine, K_PROP, el, s.name, s.pattern!, row, owner, s.filters, initialOf(engine, s, row));\n b.inFilters = s.inFilters;\n if (hooks.hostBinding?.(b, s.ro)) return;\n adopt(engine, b, true);\n engine.applyBinding(b);\n}\n\nexport interface Branch {\n plan: RowPlan;\n pattern: Pattern | null;\n filters: FilterFn[] | null;\n anchor: Node;\n}\n\n/**\n * Builds an `if` chain: one condition binding per `if`/`elseif` (each drives the whole\n * chain) and the initial render. `owner` is the enclosing block (null at the root).\n */\nexport function attachChain(engine: Engine, branches: Branch[], row: StateRow | null, owner: Block | null): IfView {\n const iv = new IfView(engine, branches, row);\n let first: Binding | null = null;\n for (const br of branches) {\n if (br.pattern === null) continue;\n const p = br.pattern;\n const b = new Binding(engine, K_IF, br.anchor, \"if\", p, rowAt(row, p.depth), owner, null, undefined, iv);\n adopt(engine, b, true);\n if (owner === null) iv.rootBindings.push(b);\n first ??= b;\n }\n // the first branch is the `if:`: it always has a condition\n engine.applyBinding(first!);\n return iv;\n}\n\nexport class IfView {\n alive = true;\n current: Block | null = null;\n index = -1;\n /** Condition bindings of a root-level chain (a nested chain's belong to its block). */\n readonly rootBindings: Binding[] = [];\n declare readonly engine: Engine;\n declare readonly branches: Branch[];\n declare readonly row: StateRow | null;\n\n constructor(engine: Engine, branches: Branch[], row: StateRow | null) {\n this.engine = engine;\n this.branches = branches;\n this.row = row;\n }\n\n /** The first node this chain renders before anchor `n` (the shown branch's, if `n` is its anchor). */\n headAt(n: Node): ChildNode | null {\n return this.current !== null && this.branches[this.index].anchor === n ? this.current.head() : null;\n }\n\n /** Renders the first branch whose condition holds (JavaScript truthiness), or nothing. */\n update(): void {\n const engine = this.engine;\n let index = -1;\n for (let i = 0; i < this.branches.length; i++) {\n const br = this.branches[i];\n // `else:` (no condition) always holds\n if (br.pattern === null || pipe(br.filters, engine.read(br.pattern, rowAt(this.row, br.pattern.depth)))) {\n index = i;\n break;\n }\n }\n if (index === this.index) return;\n naming = autoNaming();\n if (this.current !== null) {\n this.current.removeNodes();\n this.current.dispose(engine);\n this.current = null;\n }\n this.index = index;\n if (index >= 0) {\n const br = this.branches[index];\n const top = buildBlock(engine, br.plan, this.row, null, br.anchor);\n this.current = takeBlock();\n const parent = br.anchor.parentNode!;\n parent.insertBefore(top, br.anchor);\n reselect(parent);\n }\n }\n\n dispose(): void {\n this.alive = false;\n for (const b of this.rootBindings) this.engine.unregister(b);\n if (this.current !== null) this.current.dispose(this.engine);\n }\n}\n\nexport class ForView {\n alive = true;\n rowViews: RowView[] = [];\n declare readonly engine: Engine;\n declare readonly plan: RowPlan;\n declare readonly list: StateList;\n declare readonly anchor: Comment;\n /**\n * The row views by row when another for view already renders this list (the list's first\n * view keeps them on row.view instead).\n */\n declare readonly map: Map<StateRow, RowView> | null;\n\n constructor(engine: Engine, plan: RowPlan, list: StateList, anchor: Comment) {\n this.engine = engine;\n this.plan = plan;\n this.list = list;\n this.anchor = anchor;\n if (list.view === null) {\n list.view = this;\n this.map = null;\n } else {\n (list.extra ??= []).push(this);\n this.map = new Map();\n }\n }\n\n /** The first node this view renders (before its anchor), or null with no rows. */\n headAt(_n: Node): ChildNode | null {\n return this.rowViews.length === 0 ? null : this.rowViews[0].head();\n }\n\n /** This view's rendering of `row`, or null. */\n viewOf(row: StateRow): RowView | null {\n return this.map === null ? row.view : this.map.get(row) ?? null;\n }\n\n private drop(rv: RowView): void {\n const map = this.map;\n if (map !== null && map.get(rv.row!) === rv) map.delete(rv.row!);\n rv.dispose(this.engine);\n }\n\n /** Brings the DOM in line with list.rows, moving kept rows as little as possible. */\n update(): void {\n const engine = this.engine;\n const rows = this.list.rows;\n const old = this.rowViews;\n naming = autoNaming();\n const n = rows.length;\n const o = old.length;\n const anchor = this.anchor;\n const parent = anchor.parentNode!;\n\n if (n === 0) {\n if (o > 0) {\n const first = old[0].head();\n const last = old[o - 1].last;\n // the rows are all the parent holds but the anchor and text (a <tbody> of rows, its whitespace):\n // one call empties it and puts those back — faster than a Range in Chromium (10,000 rows: 14 %; node\n // by node is 5 % slower than one) and linear in happy-dom. An element beside them would be put back\n // too (a custom element reconnected, an iframe reloaded): then node by node\n let keep: Node[] | null = [];\n for (let x = parent.firstChild; x !== null; x = x === first ? last.nextSibling : x.nextSibling) {\n if (x === first) continue;\n if (x !== anchor && x.nodeType !== 3) {\n keep = null;\n break;\n }\n keep.push(x);\n }\n if (keep !== null) parent.replaceChildren(...keep);\n else removeContiguous(first, last);\n for (let i = 0; i < o; i++) this.drop(old[i]);\n }\n this.rowViews = [];\n return;\n }\n\n const views: RowView[] = new Array(n);\n let s = 0;\n while (s < n && s < o && this.viewOf(rows[s]) === old[s]) {\n views[s] = old[s];\n s++;\n }\n let oe = o - 1;\n let ne = n - 1;\n while (oe >= s && ne >= s && this.viewOf(rows[ne]) === old[oe]) {\n views[ne] = old[oe];\n oe--;\n ne--;\n }\n for (let i = s; i <= oe; i++) {\n const rv = old[i];\n const row = rv.row!;\n if (!row.alive || this.viewOf(row) !== rv) {\n rv.removeNodes();\n this.drop(rv);\n } else {\n rv.pos = i;\n }\n }\n if (s <= ne) {\n const m = ne - s + 1;\n const src = new Int32Array(m);\n let anyKept = false;\n // no rows before: none kept (the first render builds every row)\n if (o > 0) for (let i = 0; i < m; i++) {\n const rv = this.viewOf(rows[s + i]);\n if (rv !== null && rv.alive) {\n src[i] = rv.pos;\n anyKept = true;\n } else {\n src[i] = -1;\n }\n }\n const next0: Node = ne + 1 < n ? views[ne + 1].head() : anchor;\n if (!anyKept) {\n const frag = document.createDocumentFragment();\n for (let i = s; i <= ne; i++) {\n frag.appendChild(buildBlock(engine, this.plan, rows[i], this));\n views[i] = takeBlock() as RowView;\n }\n parent.insertBefore(frag, next0);\n } else {\n const keep = lisKeep(src);\n let next: Node = next0;\n for (let i = m - 1; i >= 0; i--) {\n const row = rows[s + i];\n let rv = this.viewOf(row);\n if (rv === null || !rv.alive) {\n parent.insertBefore(buildBlock(engine, this.plan, row, this), next);\n rv = takeBlock() as RowView;\n } else if (keep[i] === 0) {\n rv.insertBefore(parent, next);\n }\n views[s + i] = rv;\n next = rv.head();\n }\n }\n }\n this.rowViews = views;\n reselect(parent);\n }\n\n dispose(): void {\n this.alive = false;\n const list = this.list;\n if (list.view === this) {\n list.view = null;\n } else if (list.extra !== null) {\n const i = list.extra.indexOf(this);\n if (i >= 0) list.extra.splice(i, 1);\n if (list.extra.length === 0) list.extra = null;\n }\n for (const rv of this.rowViews) rv.dispose(this.engine);\n this.map?.clear();\n }\n}\n\n/** The node `path` leads to from `n`, following its steps from `j` on. */\nfunction nodeAt(n: Node, path: number[], j: number): Node {\n for (; j < path.length; j++) {\n n = n.firstChild!;\n for (let k = path[j]; k > 0; k--) n = n.nextSibling!;\n }\n return n;\n}\n\nfunction removeContiguous(first: ChildNode, last: ChildNode): void {\n // node by node, not a Range's deleteContents(): happy-dom's (the DOM of @wcstack/testing and of SSR)\n // is quadratic — a list of 1,000 rows took 13 s to empty\n for (let n = first, next; n !== last; n = next) {\n next = n.nextSibling!;\n n.remove();\n }\n last.remove();\n}\n\n/** Marks the entries (>= 0) that form a longest increasing subsequence of `src`. */\nexport function lisKeep(src: Int32Array): Uint8Array {\n const n = src.length;\n const keep = new Uint8Array(n);\n const prev = new Int32Array(n).fill(-1);\n const tails: number[] = [];\n for (let i = 0; i < n; i++) {\n const v = src[i];\n if (v < 0) continue;\n let lo = 0;\n let hi = tails.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (src[tails[mid]] < v) lo = mid + 1;\n else hi = mid;\n }\n if (lo > 0) prev[i] = tails[lo - 1];\n tails[lo] = i;\n }\n let k = tails.length > 0 ? tails[tails.length - 1] : -1;\n while (k >= 0) {\n keep[k] = 1;\n k = prev[k];\n }\n return keep;\n}\n","import { INDEX_PARAM, isThenable, type Engine } from \"../engine\";\nimport type { StateRow } from \"../list\";\nimport { UNSET, type Pattern } from \"../pattern\";\nimport { config } from \"../config\";\nimport { parseBindTextForEmbeddedNode, parseBindTextsForElement, type ParsedBinding } from \"../parser/index\";\nimport { buildFilters, type FilterFn } from \"./filters\";\nimport { raise, M } from \"../messages\";\nimport { hooks } from \"../hooks\";\nimport { isHtmlSink } from \"../trustedTypes\";\nimport {\n K_ATTR, K_CHECKBOX, K_CLASS, K_COMMAND, K_EVENT, K_EVTTOKEN, K_FOR, K_HTML, K_IF, K_PROP, K_RADIO, K_SPREAD, K_STYLE, K_TEXT, BUBBLING,\n isContent, type Branch, type BranchSpec, type RowPlan, type Spec,\n} from \"./view\";\nimport { report } from \"../parser/raiseError\";\n\n/** The binding attribute (`bindAttributeName`, default data-wcs). */\nexport const bindAttr = (): string => config.bindAttributeName;\n\n/** `.label` / `.` inside a `for: data` template → `data.*.label` / `data.*`. */\nexport function expandPath(path: string, list: Pattern | null): string {\n if (path.charCodeAt(0) !== 46 /* . */) return path;\n if (list === null) raise(M.WildcardRelative, [path]);\n return path === \".\" ? `${list.path}.*` : `${list.path}.*${path}`;\n}\n\nfunction blank(): Spec {\n return {\n node: 0, kind: K_PROP, name: \"\", pattern: null, filters: null, initial: UNSET, listener: null, plan: null, branches: null,\n inFilters: null, twoWay: null, custom: false, init: null, sync: null, ro: false, prevent: false, stop: false, token: null, exclude: null,\n slot: -1, delegated: false, direct: false,\n };\n}\n\n/** Native elements whose property flows back to state (custom elements come with wc-bindable). */\nfunction isTwoWay(el: Element, prop: string): boolean {\n const tag = el.localName;\n if (tag === \"input\") {\n const type = (el.getAttribute(\"type\") || \"text\").toLowerCase();\n if (type === \"button\") return false;\n if ((type === \"radio\" || type === \"checkbox\") && prop === \"checked\") return true;\n return prop === \"value\" || prop === \"valueAsNumber\" || prop === \"valueAsDate\";\n }\n return (tag === \"select\" || tag === \"textarea\") && prop === \"value\";\n}\n\ninterface Flags {\n ro: boolean;\n prevent: boolean;\n stop: boolean;\n /** `#onchange` → \"change\": the event that writes back instead of the default. */\n event: string | null;\n init: string | null;\n sync: string | null;\n}\n\nconst INITS = [\"state\", \"element\", \"auto\", \"none\"];\nconst SYNCS = [\"call\", \"connect\"];\n\n/** `#ro`, `#prevent`, `#stop`, `#onchange`, `#init=…`, `#sync=…` (`#direct`: specFor). */\nfunction flags(engine: Engine, mods: string[]): Flags {\n const on = mods.find((m) => m.startsWith(\"on\"));\n // (the keys are compared, never used as property names: the build renames `init` / `sync`)\n let init: string | null = null;\n let sync: string | null = null;\n for (const m of mods) {\n const i = m.indexOf(\"=\");\n if (i < 0) continue;\n if (!engine.directional) raise(M.DirectionalSyncDisabled);\n const key = m.slice(0, i).trim();\n const value = m.slice(i + 1).trim();\n const isInit = key === \"init\";\n if (!isInit && key !== \"sync\") raise(M.ModifierUnknown, [key, m]);\n if ((isInit ? init : sync) !== null) raise(M.ModifierTwice, [key]);\n if (!(isInit ? INITS : SYNCS).includes(value)) raise(M.ModifierValue, [key, value]);\n if (isInit) init = value;\n else sync = value;\n }\n return {\n ro: mods.includes(\"ro\"), prevent: mods.includes(\"prevent\"), stop: mods.includes(\"stop\"),\n event: on ? on.slice(2) : null, init, sync,\n };\n}\n\nconst COMMAND_PREFIX = \"$command.\";\n\n/** The pattern of a path a binding names (shown to the diagnostics add-on). */\nexport function boundPattern(engine: Engine, path: string, list: Pattern | null): Pattern {\n // `$1` is the loop index: a row pattern of the innermost loop answers it (Engine.markupAccessor)\n if (INDEX_PARAM.test(path)) {\n if (list === null) raise(M.WildcardNoLoop, [path, Number(path.slice(1))]);\n path = `${list.path}.*.${path}`;\n }\n const p = engine.pattern(expandPath(path, list));\n // each \"*\" is the row of the enclosing loop at its level, never a row of another list (F32)\n const d = list === null ? 0 : list.depth + 1;\n if (p.depth > d) raise(M.WildcardNoLoop, [p.path, p.depth, d]);\n for (let k = 1; k <= p.depth; k++) {\n const loop = k === d ? list! : list!.lists[k]!;\n if (p.lists[k] !== loop) raise(M.WildcardOtherList, [p.path, p.lists[k]!.path, loop.path]);\n }\n hooks.declared?.(engine, p);\n return p;\n}\n\n/**\n * A binding that replaces its element with the value (`outerHTML:` / `outerText:`, the properties —\n * not `class.outerHTML:`, `attr.outerText:` or an `on…:` event of that name).\n */\nexport const isOuter = (s: Spec): boolean => s.kind === K_PROP && (s.name === \"outerHTML\" || s.name === \"outerText\");\n\n/**\n * A binding after which the element's children are not markup to bind: it sets the element's content\n * (they are a value), or replaces the element (they are out of the page).\n */\nexport const setsContent = (s: Spec): boolean =>\n s.kind === K_HTML || isOuter(s) || (s.kind === K_PROP && isContent(s.name));\n\n/** An `elseif:` / `else:` template with no `if:` before it. */\nexport function notAfterIf(type: string): never {\n raise(M.ElseWithoutIf, [type]);\n}\n\nexport function specFor(engine: Engine, b: ParsedBinding, list: Pattern | null, el: Element, node: number): Spec {\n const f = flags(engine, b.propModifiers);\n const custom = el.localName.includes(\"-\");\n const segs = b.propSegments;\n const path = b.statePathName;\n\n if (b.bindingType === \"event\") {\n if (f.init !== null && f.init !== \"none\") raise(M.EventInitNone);\n if (segs[0] === \"eventToken\") {\n return { ...blank(), node, kind: K_EVTTOKEN, name: segs.slice(1).join(\".\"), token: path, custom, prevent: f.prevent, stop: f.stop };\n }\n // `onclick: $command.x` emits a command token; `onclick: method` calls a state method\n const command = path.startsWith(COMMAND_PREFIX) ? path.slice(COMMAND_PREFIX.length) : null;\n const { prevent, stop } = f;\n const type = b.propName.slice(2);\n // `#direct`: a listener on the element itself, as 3.x (see attachEvent). (A custom element's\n // `change` / `click` may be dispatched without bubbling: see attachEvent too)\n const direct = b.propModifiers.includes(\"direct\");\n const delegated = !direct && BUBBLING.has(type);\n if (delegated) engine.delegate(type);\n // (a delegated handler's failure: the diagnostics add-on says when event.currentTarget, the root there, is why)\n const fail = (error: unknown): void => {\n report(error);\n if (delegated) hooks.handlerThrew?.(engine, path, type);\n };\n return {\n ...blank(), node, kind: K_EVENT, name: type, delegated, custom, direct,\n listener(e: Event, row: StateRow | null) {\n if (prevent) e.preventDefault();\n if (stop) e.stopPropagation();\n try {\n if (command !== null) engine.emitCommand(command, e, row);\n else {\n // an async handler's failure is reported like a sync one's (not left unhandled)\n const r = engine.invoke(path, e, row) as any;\n if (isThenable(r)) r.then(undefined, fail);\n }\n } catch (error) {\n fail(error);\n }\n },\n };\n }\n if (b.bindingType === \"spread\") {\n return { ...blank(), node, kind: K_SPREAD, pattern: boundPattern(engine, path, list), custom };\n }\n if (segs[0] === \"command\" && segs.length > 1) {\n if (!path.startsWith(COMMAND_PREFIX)) raise(M.CommandRightSide, [b.propName, path]);\n return { ...blank(), node, kind: K_COMMAND, name: segs.slice(1).join(\".\"), token: path, custom };\n }\n\n const pattern = boundPattern(engine, path, list);\n const spec: Spec = {\n ...blank(), node, kind: K_PROP, name: b.propName, pattern,\n filters: buildFilters(b.outFilters), inFilters: buildFilters(b.inFilters), ro: f.ro, init: f.init, sync: f.sync,\n };\n if (b.bindingType === \"radio\" || b.bindingType === \"checkbox\") {\n if (f.init === \"element\" || f.init === \"auto\") raise(M.InitUnsupported, [b.bindingType, f.init]);\n spec.kind = b.bindingType === \"radio\" ? K_RADIO : K_CHECKBOX;\n if (!f.ro) spec.twoWay = f.event ?? \"input\";\n return spec;\n }\n if (segs.length > 1) {\n const name = segs.slice(1).join(\".\");\n const head = segs[0];\n if (head === \"class\" || head === \"attr\" || head === \"style\") {\n // a namespace takes no initial authority: #init= is ignored (as in 3.3)\n spec.init = null;\n spec.name = name;\n if (head === \"class\") {\n spec.kind = K_CLASS;\n spec.initial = el.classList.contains(name);\n } else {\n // (an iframe's srcdoc attribute is an HTML sink: written as the property, through the policy)\n spec.kind = head === \"attr\" ? (name === \"srcdoc\" && el.localName === \"iframe\" ? K_PROP : K_ATTR) : K_STYLE;\n }\n return spec;\n }\n }\n if (b.propName === \"html\") {\n spec.kind = K_HTML;\n return spec;\n }\n spec.name = b.propName === \"text\" ? \"textContent\" : b.propName;\n // an HTML sink is never a wc-bindable member: written at once, through the policy\n spec.custom = custom && !isHtmlSink(spec.name);\n if (!custom && !f.ro && isTwoWay(el, spec.name)) spec.twoWay = f.event ?? (el.localName === \"select\" ? \"change\" : \"input\");\n return spec;\n}\n\n/**\n * The specs of one element's data-wcs, in order. A spread is told which members are bound\n * explicitly after it (last wins).\n */\nexport function elementSpecs(engine: Engine, text: string, list: Pattern | null, el: Element, node: number): Spec[] {\n const specs = parseBindTextsForElement(text).map((b) => specFor(engine, b, list, el, node));\n for (let i = 0; i < specs.length; i++) {\n if (specs[i].kind !== K_SPREAD) continue;\n specs[i].exclude = specs.slice(i + 1).filter((s) => s.kind === K_PROP).map((s) => s.name);\n }\n return specs;\n}\n\nconst MUSTACHE = /\\{\\{([\\s\\S]+?)\\}\\}/g;\n\n/** Replaces a text node holding `{{ … }}` with static text nodes and empty bound ones. */\nexport function splitMustache(t: Text): { node: Text; expr: string }[] {\n const s = t.data;\n const out: { node: Text; expr: string }[] = [];\n let last = 0;\n MUSTACHE.lastIndex = 0;\n for (let m = MUSTACHE.exec(s); m !== null; m = MUSTACHE.exec(s)) {\n // where the match starts (not `m.index`: `index` is a name the build shortens)\n const at = MUSTACHE.lastIndex - m[0].length;\n // (a string is inserted as a text node of t's document)\n if (at > last) t.before(s.slice(last, at));\n const bound = t.ownerDocument.createTextNode(\"\");\n t.before(bound);\n out.push({ node: bound, expr: m[1].trim() });\n last = MUSTACHE.lastIndex;\n }\n if (out.length === 0) return out;\n if (last < s.length) t.before(s.slice(last));\n t.remove();\n return out;\n}\n\nexport function textSpec(engine: Engine, expr: string, list: Pattern | null, node: number): Spec {\n const b = parseBindTextForEmbeddedNode(expr);\n return { ...blank(), node, kind: K_TEXT, pattern: boundPattern(engine, b.statePathName, list), filters: buildFilters(b.outFilters), initial: \"\" };\n}\n\n/** The structural directive on a template (`for` / `if` / `elseif` / `else`), or null. */\nexport function directive(el: Element): ParsedBinding | null {\n const text = el.getAttribute(bindAttr());\n if (text === null) return null;\n const b = parseBindTextsForElement(text)[0];\n return b !== undefined && (b.bindingType === \"for\" || b.bindingType === \"if\" || b.bindingType === \"elseif\" || b.bindingType === \"else\") ? b : null;\n}\n\nexport interface ChainPart {\n el: HTMLTemplateElement;\n pattern: Pattern | null;\n filters: FilterFn[] | null;\n}\n\n/** The anchor text of a chain's `k`-th template: `if`, then `elseif`, and `else` (no path). */\nexport const chainAnchorText = (k: number, part: ChainPart): string =>\n k === 0 ? config.commentIfPrefix : part.pattern === null ? config.commentElsePrefix : config.commentElseIfPrefix;\n\n/**\n * Reads an `if` chain starting at `first` (an `if:` template): the `elseif:` / `else:` templates\n * that follow it in the tree, across whitespace and comments. The walker skips the ones taken (each\n * is out of the tree, its anchor in its place).\n */\nexport function readChain(engine: Engine, first: Element, list: Pattern | null): ChainPart[] {\n const part = (el: Element, b: ParsedBinding): ChainPart => ({\n el: el as HTMLTemplateElement,\n pattern: b.bindingType === \"else\" ? null : boundPattern(engine, b.statePathName, list),\n filters: b.bindingType === \"else\" ? null : buildFilters(b.outFilters),\n });\n const parts = [part(first, directive(first)!)];\n for (let c = first.nextSibling; c !== null; c = c.nextSibling) {\n if ((c.nodeType === 3 && (c as Text).data.trim() === \"\") || c.nodeType === 8) continue;\n if (c.nodeType !== 1 || (c as Element).localName !== \"template\") break;\n const b = directive(c as Element);\n if (b === null || (b.bindingType !== \"elseif\" && b.bindingType !== \"else\")) break;\n parts.push(part(c as Element, b));\n if (b.bindingType === \"else\") break;\n }\n return parts;\n}\n\n/**\n * The elements a page walk has visited: each is bound once, however often it is handed over. SSR\n * hydration adds the top-level nodes of the server's rows and branches (a text's too): their blocks\n * bind them where they are, and the walk passes them by.\n */\nexport const walked = new WeakSet<Node>();\n\n/**\n * Walks `children` and what they contain for bindings, by the same markup rules for the page\n * (`page`: the mount — it skips script / style, enters `<wcs-state>`, and marks anchors for SSR)\n * and for a template's content (a plan). Structural templates are compiled and replaced by\n * their anchors; the rest is handed to the callbacks.\n */\nexport function walkBindings(engine: Engine, children: ChildNode[], list: Pattern | null, page: boolean,\n onFor: (anchor: Comment, p: Pattern, plan: RowPlan) => void,\n onIf: (branches: Branch[]) => void,\n onElement: (el: Element, specs: Spec[]) => void,\n onText: (node: Text, expr: string) => void): void {\n // a structural template leaves the tree: its anchor takes its place\n const anchorFor = (el: Element, type: string): Comment => {\n const anchor = document.createComment(type);\n el.replaceWith(anchor);\n if (page) hooks.ssrMark?.(engine, anchor, el);\n return anchor;\n };\n const walk = (children: ChildNode[]): void => {\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n // (out of the tree: an `elseif:` / `else:` template its chain's anchor replaced)\n if (child.parentNode === null) continue;\n if (child.nodeType === 1) {\n const el = child as Element;\n const tag = el.localName;\n // `data-wcs-ignore` (the bind attribute + \"-ignore\"): neither the element nor anything in it is read\n // as bindings — markup the page did not write (user content a server template put there; README,\n // \"Markup you did not write\")\n if (el.hasAttribute(bindAttr() + \"-ignore\")) continue;\n if (page) {\n // walked before (a subtree handed over again): left alone — its text and rows show\n // values now, which are not markup\n if (tag === \"script\" || tag === \"style\" || walked.has(el)) continue;\n walked.add(el);\n // markup written inside a <wcs-state> is part of the page (its own attributes are not bindings)\n if (tag === config.tagNames.state) {\n walk([...el.childNodes]);\n continue;\n }\n }\n // a template with no structural directive binds like any element (its content stays inert)\n const d = tag === \"template\" ? directive(el) : null;\n if (d !== null) {\n if (d.bindingType === \"for\") {\n const p = boundPattern(engine, d.statePathName, list);\n const plan = compilePlan(engine, el as HTMLTemplateElement, p, true);\n onFor(anchorFor(el, config.commentForPrefix), p, plan);\n } else if (d.bindingType === \"if\") {\n onIf(readChain(engine, el, list).map((part, k) => {\n const plan = compilePlan(engine, part.el, list, false);\n return { plan, pattern: part.pattern, filters: part.filters, anchor: anchorFor(part.el, chainAnchorText(k, part)) };\n }));\n } else {\n notAfterIf(d.bindingType);\n }\n continue;\n }\n const text = el.getAttribute(bindAttr());\n const specs = text === null ? null : elementSpecs(engine, text, list, el, 0);\n // What a binding puts in an element is a value, not markup. An element whose content a\n // binding sets (`textContent:` / `innerHTML:` / `html:`) is not walked at all — whenever the\n // value lands (a custom element's waits for its definition), and if it fails — nor one a\n // binding replaces (`outerHTML:` / `outerText:`: its children leave the page). Nor is the\n // content of a <noscript> or an <iframe>: raw text to a page that runs scripts (a server may\n // have rendered a value there). A Light DOM component's content is bound by its own engine\n const into = tag !== \"noscript\" && tag !== \"iframe\" && !specs?.some(setsContent) && !hooks.componentScope?.(el);\n // On the page an element's children are bound before it: what its bindings then put anywhere\n // in it (a custom element rendering a value into a child of its own) is never walked — nor\n // after an error in them, which leaves the walk with the element bound (it is before the\n // error in document order). A plan keeps document order (Block.dispatch relies on it): its\n // bindings change nothing in it\n try {\n if (page && into) walk([...el.childNodes]);\n } finally {\n if (specs !== null) onElement(el, specs);\n }\n if (!page && into) walk([...el.childNodes]);\n } else if (child.nodeType === 3 && engine.mustache && (child as Text).data.includes(\"{{\") && !walked.has(child)) {\n for (const { node, expr } of splitMustache(child as Text)) onText(node, expr);\n } else if (child.nodeType === 8) {\n // a comment binding, as 3.x (`$behavior.enableMustache` aside): a text binding in its place —\n // not in a <textarea> / <title>, where a browser's parser makes it text (a server's DOM may not)\n const m = COMMENT_BINDING.exec((child as Comment).data);\n const p = m && (child.parentNode as Element).localName;\n if (p !== null && p !== \"textarea\" && p !== \"title\") {\n const t = document.createTextNode(\"\");\n child.replaceWith(t);\n onText(t, m![1]);\n }\n }\n }\n };\n walk(children);\n}\n\n/**\n * `<!--@@: expr-->` / `<!--@@wcs-text: expr-->` (3.x's comment binding: a text binding that renders\n * nothing before it is bound — no FOUC, no element added); no other keyword (a router's `@@route:`,\n * 3.x's SSR marks). `expr` is a `{{ }}` expression (across lines, as a mustache's: SSR restores both\n * as this).\n */\nconst COMMENT_BINDING = /^\\s*@@\\s*(?:wcs-text)?\\s*:\\s*([\\s\\S]+?)\\s*$/;\n\n/**\n * A template's content. A `<template>` inside `<svg>` is an SVG element (the HTML parser makes it\n * so) and has no `.content`: its children are its content (a copy of them: the template keeps them).\n */\nexport const templateContent = (t: HTMLTemplateElement): DocumentFragment => {\n const r = document.createRange();\n r.selectNodeContents(t);\n return t.content ?? r.cloneContents();\n};\n\n/**\n * Compiles a template into a plan: the fragment to clone, the child-index path of every\n * bound node, and one spec per binding. Paths are resolved to patterns here, once —\n * blocks never parse or resolve anything. `list` is the enclosing `for` (for `.` paths).\n */\nexport function compilePlan(engine: Engine, template: HTMLTemplateElement, list: Pattern | null, asRow: boolean): RowPlan {\n const frag = document.importNode(templateContent(template), true);\n const targets: Node[] = [];\n const specs: Spec[] = [];\n const target = (node: Node): number => targets.push(node) - 1;\n\n walkBindings(engine, [...frag.childNodes], list, false,\n (anchor, p, plan) => {\n specs.push({ ...blank(), node: target(anchor), kind: K_FOR, pattern: p, plan });\n },\n (chain) => {\n const branches: BranchSpec[] = chain.map((br) => ({ node: target(br.anchor), plan: br.plan, pattern: br.pattern, filters: br.filters }));\n specs.push({ ...blank(), node: branches[0].node, kind: K_IF, branches });\n },\n (el, own) => {\n const n = target(el);\n for (const s of own) {\n // a row or a branch keeps its nodes by position: a binding that replaces its element (once —\n // the element is out of the page after) has no place in one\n if (isOuter(s)) raise(M.OuterInTemplate, [s.name]);\n s.node = n;\n }\n specs.push(...own);\n // the plan holds the bindings: blocks cloned from it carry nothing left to bind\n el.removeAttribute(bindAttr());\n },\n (node, expr) => {\n specs.push(textSpec(engine, expr, list, target(node)));\n });\n\n // Whitespace that never renders is not part of a block: at the top level, and inside\n // elements whose content model has no text (table parts, select). Bound text nodes start\n // empty: keep them.\n stripInsignificantWhitespace(frag, new Set(targets), true);\n\n const nodePaths = targets.map((t) => pathOf(frag, t));\n // one node cloned alone — not a structural anchor, whose view inserts before it (it needs a parent)\n const single = frag.childNodes.length === 1 && frag.firstChild!.nodeType !== 8;\n const nested = specs.some((s) => s.kind === K_FOR || s.kind === K_IF);\n const lazy: Spec[] = [];\n const used = new Set<number>();\n const events: Spec[] = [];\n // what a block binds as it is built (the delegated events it finds by path are not among them)\n const own: Spec[] = [];\n // in a row plan, the row's own locations bound by kinds that need only the node are slots (see RowView)\n const d = asRow ? list!.depth + 1 : -1;\n for (const s of specs) {\n // a node used only by delegated events is never resolved when a block is built (a custom\n // element's are attached: it may dispatch them without bubbling)\n if (s.kind === K_EVENT && s.delegated && !s.custom && !shifts(targets[s.node], frag)) {\n events.push(s);\n continue;\n }\n own.push(s);\n const p = s.pattern;\n if (p !== null && p.depth === d && p.lists[d] === list && isSlotKind(s)) s.slot = lazy.push(s) - 1;\n if (s.kind === K_IF) for (const br of s.branches!) used.add(br.node);\n else used.add(s.node);\n }\n const build = [...used].sort((a, b) => a - b);\n return { fragment: frag, root: single ? frag.firstChild : null, nodePaths, build, events, specs: own, single, nested, scratch: [], lazy };\n}\n\n/**\n * Whether the path to `n` from its block's top node can change once the block renders: a\n * structural anchor before it on the way (its view renders before the anchor) or a custom element\n * above it (a Light DOM component may add children). Such an element's delegated events are not\n * found by path: they are stored on the element as its block is built.\n */\nfunction shifts(n: Node, top: Node): boolean {\n for (; n.parentNode !== top; n = n.parentNode!) {\n if ((n.parentNode as Element).localName.includes(\"-\")) return true;\n for (let s = n.previousSibling; s; s = s.previousSibling) if (s.nodeType === 8) return true;\n }\n return false;\n}\n\nfunction isSlotKind(s: Spec): boolean {\n // a slot applies its first value as it is built: #init= needs a Binding (HOLD)\n if (s.init !== null) return false;\n switch (s.kind) {\n case K_TEXT:\n case K_CLASS:\n case K_ATTR:\n case K_STYLE:\n case K_HTML:\n return true;\n case K_PROP:\n return !s.custom && s.twoWay === null;\n default:\n return false;\n }\n}\n\n/** Elements whose children never render as text: whitespace between their children is noise. */\nconst NO_TEXT = new Set([\"table\", \"thead\", \"tbody\", \"tfoot\", \"tr\", \"colgroup\", \"select\", \"optgroup\", \"datalist\"]);\n\nfunction stripInsignificantWhitespace(parent: Node, keep: Set<Node>, strip: boolean): void {\n for (let n = parent.firstChild; n !== null;) {\n const next = n.nextSibling;\n if (n.nodeType === 3) {\n if (strip && !keep.has(n) && (n as Text).data.trim() === \"\") n.remove();\n } else if (n.nodeType === 1) {\n stripInsignificantWhitespace(n, keep, NO_TEXT.has((n as Element).localName));\n }\n n = next;\n }\n}\n\nfunction pathOf(root: Node, node: Node): number[] {\n const path: number[] = [];\n for (let n: Node = node; n !== root; n = n.parentNode!) {\n let i = 0;\n for (let s = n.previousSibling; s !== null; s = s.previousSibling) i++;\n path.unshift(i);\n }\n return path;\n}\n","import { parseStatePart } from \"./parseStatePart\";\nimport { ParsedBinding } from \"./types\";\n\n/**\n * テキストバインディング(mustache `{{ expr }}` / コメント `<!--@@: expr-->`・`<!--@@wcs-text: expr-->`)の式を解析する。\n * 式全体が `path[|filters]` — `;` は**分割しない**(属性経路との規定差)。\n * Port of `@wcstack/state` `src/bindTextParser/parseBindTextForEmbeddedNode.ts`.\n */\nexport function parseBindTextForEmbeddedNode(bindText: string): ParsedBinding {\n const stateResult = parseStatePart(bindText);\n return {\n propName: 'textContent',\n propSegments: ['textContent'],\n propModifiers: [],\n inFilters: [],\n ...stateResult,\n bindingType: 'text',\n };\n}\n","import type { Engine } from \"../engine\";\nimport { hooks } from \"../hooks\";\nimport { directive, textSpec, walkBindings } from \"./plan\";\nimport { raise, M } from \"../messages\";\nimport { attachChain, attachSpec, ForView, listFor } from \"./view\";\nimport { report } from \"../parser/raiseError\";\n\n/**\n * The engine mounted on each root (document, shadow root): the binder's lookup. A root's while its\n * `<wcs-state>` is in the page (src/element.ts): the root node outlives the content it bound.\n */\nexport const engines = new WeakMap<Node, Engine>();\n\n/**\n * Binds everything under `root` to `engine` and renders it. An element walked once is left\n * alone after (walkBindings): the binder protocol hands route content over on every insertion.\n */\nexport function mount(engine: Engine, root: Document | ShadowRoot | Element): void {\n const container: Node = root.nodeType === 9 ? (root as Document).body : root;\n engine.root = root;\n engines.set(root, engine);\n walk(engine, [...container.childNodes]);\n engine.report();\n}\n\n/**\n * Binds a subtree that entered the document after the mount (the binder protocol). It never throws\n * for markup reasons (the protocol): an error in the markup is reported, and what is before it in\n * document order (the elements it is in too) stays bound. A structural template handed over itself (a\n * route's top-level node) is rendered only when the caller carries its range (`range`: the router\n * takes everything up to its end mark along, the rows rendered beside the template included);\n * otherwise it is refused (#204): what it renders would sit beside it, where whoever inserted it\n * does not reach (an older router removes only its own nodes, `<wcs-head>` its one element). An\n * `if:` template handed over reads its `elseif:` / `else:` siblings into one chain (readChain), and\n * those, handed over next, are out of the document by then (their anchors took their place).\n */\nexport function mountSubtree(engine: Engine, subtree: Element, range?: boolean): void {\n try {\n const d = subtree.localName === \"template\" ? directive(subtree) : null;\n if (d !== null && !range) raise(M.TemplateHandedOver, [d.bindingType]);\n walk(engine, [subtree]);\n } catch (e) {\n report(e);\n }\n engine.report();\n}\n\nfunction walk(engine: Engine, children: ChildNode[]): void {\n walkBindings(engine, children, null, true,\n (anchor, p, plan) => {\n new ForView(engine, plan, listFor(engine, p, null, anchor), anchor).update();\n },\n (branches) => {\n attachChain(engine, branches, null, null);\n },\n (el, specs) => {\n hooks.ssrMark?.(engine, el, specs);\n for (const spec of specs) attachSpec(engine, spec, el, null, null);\n },\n (node, expr) => {\n hooks.ssrMark?.(engine, node, expr);\n attachSpec(engine, textSpec(engine, expr, null, 0), node, null, null);\n });\n}\n","// ===========================================================================\n// AUTO-GENERATED FILE - DO NOT EDIT.\n// Generated from /protocol/binder.ts by scripts/sync-protocol-types.mjs.\n// Run `node scripts/sync-protocol-types.mjs` after editing the source.\n// ===========================================================================\n\n// binder protocol — how a package that inserts DOM hands those nodes to whoever\n// owns data bindings on the page.\n//\n// The dual of transition-runner: that one hands a *mutation* to whoever animates\n// it, this one hands *new nodes* to whoever binds them.\n//\n// A `data-wcs` binding exists only for nodes @wcstack/state walked when it built\n// its bindings. Nodes that arrive later — the content of a route that was not\n// active at that moment, a <wcs-head> child reflected into <head> — were never\n// walked, so their bindings silently do nothing, however often they are inserted.\n// @wcstack/router must not depend on @wcstack/state (zero runtime dependencies,\n// independently publishable), so state installs a binder on a well-known global\n// symbol and inserters look it up lazily.\n//\n// No binder installed means nothing happens — byte-for-byte the behavior these\n// packages had before the protocol existed.\n//\n// docs/binder-protocol-design.md is the normative description.\n//\n// SINGLE SOURCE OF TRUTH: edit only this file (/protocol/binder.ts), then run\n// `node scripts/sync-protocol-types.mjs` to regenerate the per-package copies\n// (packages/<pkg>/src/protocol/binder.ts). Those copies are generated — do not edit them.\n\n/**\n * Global key the binder installs itself under. `Symbol.for` so independently\n * loaded copies of this file (two CDN bundles on one page) still agree.\n */\nexport const BINDER_KEY = Symbol.for(\"wcstack.binder\");\n\n/**\n * What the caller declares about a subtree it hands over (the second argument of `bind`; additive\n * since version 1 — a binder that predates it ignores it, and leaving it out keeps the old contract).\n */\nexport interface IWcsBindOptions {\n /**\n * The caller carries the range the subtree sits in: on removal it takes everything from its own\n * start mark up to its end mark along — what the binder rendered beside the subtree included, as\n * the rows a structural template handed over at the top of the content renders before its anchor —\n * and puts it all back on reinsertion. Only with this may a binder render such a template: without\n * it, what the binder rendered beside the subtree would be left behind, so @wcstack/state 4.0\n * refuses one (#204). @wcstack/state 3.x ignores the option and renders no structural template\n * handed over itself, with or without it (docs/binder-protocol-design.md §2, §9-5, §9-6).\n */\n readonly range?: boolean;\n}\n\nexport interface IWcsBinder {\n readonly protocol: \"wcs-binder\";\n /** Integer protocol version. All versions >= 1 are participant-compatible. */\n readonly version: number;\n /**\n * Take a subtree that has just entered the document and bind whatever\n * declarations it carries.\n *\n * Contract (docs/binder-protocol-design.md §2):\n * - Synchronous. Initial values are applied before this returns, so the\n * caller never shows one frame of unbound markup.\n * - Idempotent. A subtree that is already bound is left alone, so a caller\n * may hand over the same nodes on every insertion without tracking which\n * ones are new.\n * - Binding survives later relocation, so this need not be called again when\n * the same nodes are moved (measured: design doc §8-3).\n * - Never throws for markup reasons; a subtree with no declarations is a\n * no-op.\n * - `options` (optional) is what the caller declares about the subtree\n * ({@link IWcsBindOptions}).\n */\n bind(subtree: Node, options?: IWcsBindOptions): void;\n}\n\n/**\n * The installed binder, or null when there is none or it speaks a version this\n * reader does not.\n *\n * Looked up on every call rather than cached, for the same reason\n * transition-runner does: the page's composition can change at any point, and a\n * stale cache would keep calling into a binder that is no longer there.\n */\nexport function getBinder(): IWcsBinder | null {\n const candidate = (globalThis as Record<symbol, unknown>)[BINDER_KEY] as IWcsBinder | undefined;\n if (candidate === undefined || candidate === null) return null;\n if (candidate.protocol !== \"wcs-binder\") return null;\n if (typeof candidate.version !== \"number\" || candidate.version < 1) return null;\n if (typeof candidate.bind !== \"function\") return null;\n return candidate;\n}\n\n/**\n * Subtrees offered before a binder existed, and the set of everything a binder\n * has taken. Both live on global symbols so that independently loaded copies of\n * this file — the router's and state's — share one queue.\n *\n * The queue is needed because of load order: the router's auto bundle runs\n * before state's, so `<wcs-head>` reflects its children into `<head>` while\n * there is still nothing to bind them. Offering them to a binder that arrives\n * later is the difference between working and silently blank.\n */\nconst PENDING_KEY = Symbol.for(\"wcstack.binder.pending\");\nconst TAKEN_KEY = Symbol.for(\"wcstack.binder.taken\");\n\nfunction pendingQueue(): Node[] {\n const globals = globalThis as Record<symbol, unknown>;\n let queue = globals[PENDING_KEY] as Node[] | undefined;\n if (queue === undefined) {\n queue = [];\n globals[PENDING_KEY] = queue;\n }\n return queue;\n}\n\nfunction takenSet(): WeakSet<Node> {\n const globals = globalThis as Record<symbol, unknown>;\n let taken = globals[TAKEN_KEY] as WeakSet<Node> | undefined;\n if (taken === undefined) {\n taken = new WeakSet<Node>();\n globals[TAKEN_KEY] = taken;\n }\n return taken;\n}\n\n/**\n * Hand `subtree` to the installed binder, or hold it for one that arrives later.\n *\n * Returns whether a binder took it *now*. A `false` does not yet mean the markup\n * is doomed — check {@link wasBoundBy} once module scripts have run.\n *\n * `options` goes to the binder with the subtree. A subtree held for a later binder\n * is handed over without it: that binder's first walk of the page binds what is\n * still in place there.\n */\nexport function bindSubtree(subtree: Node, options?: IWcsBindOptions): boolean {\n const binder = getBinder();\n if (binder === null) {\n pendingQueue().push(subtree);\n return false;\n }\n takenSet().add(subtree);\n binder.bind(subtree, options);\n return true;\n}\n\n/** Whether any binder has taken this subtree. */\nexport function wasBoundBy(subtree: Node): boolean {\n return takenSet().has(subtree);\n}\n\n/**\n * Bind everything offered before this binder existed. Called by the binder right\n * after it installs itself.\n */\nexport function flushPendingBinds(): void {\n const binder = getBinder();\n if (binder === null) return;\n const queue = pendingQueue();\n if (queue.length === 0) return;\n const pending = queue.splice(0, queue.length);\n const taken = takenSet();\n for (const subtree of pending) {\n taken.add(subtree);\n binder.bind(subtree);\n }\n}\n","import { BINDER_KEY, flushPendingBinds, type IWcsBinder, type IWcsBindOptions } from \"../protocol/binder\";\nimport { engines, mountSubtree } from \"./mount\";\n\n/**\n * The binder protocol's provider (docs/binder-protocol-design.md): a package that inserts\n * DOM after the mount — the router's route content, `<wcs-head>`'s clones in <head> —\n * hands the subtree over, and it is bound to the engine of its root, synchronously.\n * Only what is handed over is bound (no scan of every insertion), and binding twice is a\n * no-op, so the router may hand the same nodes over on every insertion.\n */\n\n/**\n * Subtrees handed over before their root's engine finished its first mount, or while it was out of the\n * page, with what the caller declared (a range: a route's top-level template is rendered then).\n */\nconst early = new Map<Element, IWcsBindOptions | undefined>();\n\nexport function bind(subtree: Node, options?: IWcsBindOptions): void {\n // not in a document (it left, or was replaced, as a chain's `else:` template by its anchor): nothing to bind\n if (subtree.nodeType !== 1 || !subtree.isConnected) return;\n // (a root taken out of the page lets go of its root node: it binds what waited here when it is back.\n // A component's, whose <wcs-state> alone left, is still registered: not one to bind to either)\n const engine = engines.get(subtree.getRootNode());\n // (once each: the router hands the same nodes over on every insertion. One handed over early is\n // walked by the first mount where it is: the declaration is not needed then)\n if (engine === undefined || (engine.element as Node | null)?.isConnected === false) early.set(subtree as Element, options);\n else mountSubtree(engine, subtree as Element, options?.range);\n}\n\n/**\n * After an engine's first mount, and when a root is back in the page: binds what was handed over\n * too early — to this binder before the mount or while the root was out, or (queued by the\n * protocol) before any binder existed.\n */\nexport function drainBinds(): void {\n // (one that left the document meanwhile is dropped: handed over again if it comes back)\n const waiting = [...early];\n early.clear();\n for (const [subtree, options] of waiting) bind(subtree, options);\n flushPendingBinds();\n}\n\n/** Installs the binder on the protocol's global slot, unless another copy already has it. */\nexport function installBinder(): void {\n const slot = globalThis as Record<symbol, unknown>;\n if (slot[BINDER_KEY] === undefined) slot[BINDER_KEY] = { protocol: \"wcs-binder\", version: 1, bind } satisfies IWcsBinder;\n}\n","import type { Engine } from \"../engine\";\nimport { DIRTY, FAILED, UNSET, type Pattern } from \"../pattern\";\nimport type { StateRow } from \"../list\";\nimport type { Strategy } from \"./types\";\nimport { hooks } from \"../hooks\";\n\n/**\n * Push invalidation: a write walks its dependents immediately, marks their caches\n * DIRTY and queues their bindings. A cache already DIRTY (or never computed) stops the\n * walk — whatever depends on it was reached when it was marked.\n */\nexport class DirtyStrategy implements Strategy {\n readonly name = \"dirty\";\n\n private readonly mark = (g: Pattern, row: StateRow | null): boolean => {\n // UNSET: nobody read it; DIRTY: already reached. FAILED was read (and threw): reach it.\n if (g.depth === 0) {\n const v = g.rootValue;\n if (v === UNSET || v === DIRTY) return false;\n g.rootValue = DIRTY;\n return true;\n }\n const c = row === null ? null : row.cache;\n if (c === null) return false;\n const v = c[g.slot];\n if (v === UNSET || v === DIRTY) return false;\n c[g.slot] = DIRTY;\n return true;\n };\n\n onWrite(engine: Engine, p: Pattern, row: StateRow | null): void {\n // a write through a getter's setter: the written occurrence itself is stale\n if (p.getter !== null) this.mark(p, row);\n engine.enqueueBound(p, row);\n engine.walkDependents(p, row, this.mark);\n }\n\n onIndexChange(engine: Engine, row: StateRow): void {\n const watchers = row.list.pattern.indexWatchers;\n if (watchers === null) return;\n for (const g of watchers) {\n // the row itself (a row getter reading its own index): no closure per moved row\n if (g.depth === row.list.depth) engine.visitGetter(g, row, this.mark);\n else engine.forRowsUnder(row, g, (r) => engine.visitGetter(g, r, this.mark));\n }\n }\n\n invalidate(engine: Engine, g: Pattern, row: StateRow | null): void {\n this.mark(g, row);\n hooks.getterReached?.(engine, g, row);\n engine.enqueueBound(g, row);\n engine.walkDependents(g, row, this.mark);\n }\n\n readGetter(engine: Engine, g: Pattern, row: StateRow | null): unknown {\n const root = g.depth === 0;\n if (!root && row === null) return undefined;\n const c = root ? null : (row!.cache ??= new Array(engine.slotCount).fill(UNSET));\n let v = c === null ? g.rootValue : c[g.slot];\n // a getter made after the row's cache (a recursive family, a mounted key, a binder's subtree) has\n // no entry yet — nor one whose slot lies before a later getter's written past the end (a hole)\n if (v !== UNSET && v !== DIRTY && v !== FAILED && (c === null || g.slot in c)) return v;\n v = FAILED;\n try {\n return (v = engine.evalGetter(g, c === null ? null : row));\n } finally {\n if (c === null) g.rootValue = v;\n else c[g.slot] = v;\n }\n }\n\n resetRow(row: StateRow): void {\n row.cache = null;\n }\n\n dropped(engine: Engine): void {\n // DIRTY says \"its readers were reached\", and they were dropped: FAILED is reached again\n for (const g of engine.patterns.all()) {\n if (g.getter === null) continue;\n if (g.depth === 0) {\n if (g.rootValue === DIRTY) g.rootValue = FAILED;\n } else {\n engine.forAllRows(g.lists[g.depth]!, (r) => {\n const c = r.cache;\n if (c !== null && c[g.slot] === DIRTY) c[g.slot] = FAILED;\n });\n }\n }\n }\n}\n","import type { IWritableConfig } from \"./public/types\";\nimport { Engine } from \"./engine\";\nimport { engines, mount } from \"./dom/mount\";\nimport { drainBinds, installBinder } from \"./dom/binder\";\nimport { DirtyStrategy } from \"./strategy/dirty\";\nimport { config, setConfig } from \"./config\";\nimport type { Strategy } from \"./strategy/types\";\nimport { raise, M, text } from \"./messages\";\nimport { hooks, loadFeatures, requireFeature, type Claimed } from \"./hooks\";\nimport { report } from \"./parser/raiseError\";\n\nlet makeStrategy: () => Strategy = () => new DirtyStrategy();\n\n/** Chooses the invalidation strategy of every engine created from now on. */\nexport function configure(factory: () => Strategy): void {\n makeStrategy = factory;\n}\n\nlet loads = 0;\n\nasync function loadInnerScript(script: HTMLScriptElement): Promise<Record<string, any>> {\n // an import a Content-Security-Policy blocked rejects without saying why: the violation event\n // is the only witness (docs/csp.md §9)\n let blocked = false;\n const seen = (e: SecurityPolicyViolationEvent): void => {\n if (e.effectiveDirective.startsWith(\"script-src\")) blocked = true;\n };\n document.addEventListener(\"securitypolicyviolation\", seen);\n // a server (@wcstack/server) removes createObjectURL: a data: URL, unique so no load is cached\n const blob = typeof URL.createObjectURL === \"function\";\n const url = blob\n ? URL.createObjectURL(new Blob([script.text], { type: \"application/javascript\" }))\n : \"data:text/javascript;charset=utf-8,\" + encodeURIComponent(`${script.text}\\n//${++loads}`);\n try {\n const mod = await import(/* @vite-ignore */ url);\n return (mod.default ?? {}) as Record<string, any>;\n } catch (e) {\n // Firefox fires the violation a task after the rejection (Chromium and WebKit before it)\n await new Promise((r) => setTimeout(r));\n throw new Error(`[@wcstack/state] ${blocked ? text(M.InlineBlocked) : text(M.InlineFailed, [e instanceof Error ? e.message : String(e)])}`, { cause: e });\n } finally {\n document.removeEventListener(\"securitypolicyviolation\", seen);\n if (blob) URL.revokeObjectURL(url);\n }\n}\n\nasync function loadSrc(src: string): Promise<Record<string, any>> {\n const url = new URL(src, document.baseURI).href;\n if (/\\.json(?:[?#]|$)/.test(url)) {\n const res = await fetch(url);\n if (!res.ok) raise(M.LoadFailed, [src, res.status]);\n return (await res.json()) as Record<string, any>;\n }\n // on the server, the renderer's local module for the URL (protocol/ssr-snapshot.ts, resolveModule):\n // Node's loader reads no http: URL\n const mod = await import(/* @vite-ignore */ (globalThis as any)[Symbol.for(\"wcstack.ssr.resolveModule\")]?.(url) ?? url);\n return (mod.default ?? {}) as Record<string, any>;\n}\n\n/**\n * The root `<wcs-state>` elements of each root node (and the one a component mount or a DCC definition\n * has in its shadow root): a new list whenever one connects, without the ones no longer in the page.\n */\nconst readyByRoot = new WeakMap<Node, WcsState[]>();\n\n/**\n * Puts `el` among the `<wcs-state>` elements of `root` (a new list, without the ones that left) — or,\n * taken out of it, takes it off: the list holds nothing of a page that went.\n */\nfunction enroll(el: WcsState, root: Node = el.getRootNode()): void {\n readyByRoot.set(root, [...(readyByRoot.get(root) ?? []), el].filter((e, i, a) => e.isConnected && a.lastIndexOf(e) === i));\n}\n\n/**\n * Resolves when the bindings of `root` are built — by any `<wcs-state>` in it now, whatever its\n * `$connectedCallback` does then, as 3.x — and rejects, with the first failure, only when every one\n * failed before building them. A stray one (a second root, #47; one that fails to load) changes\n * nothing while another binds the root; one taken out of the page (or moved to another root) counts\n * no more (a root replaced: the new one decides). With none in it — none ever, or only ones that left —\n * it resolves at once: there is nothing to wait for (a page without state).\n */\nexport function getBindingsReady(root: Node): Promise<void> {\n const list = readyByRoot.get(root) ?? [];\n const els = list.filter((e) => e.getRootNode() === root);\n return Promise.any(els.map((el) => el.initializePromise.then((): unknown => el.bound || el.connectedCallbackPromise))).then(\n () => {},\n // none, or every one failed: one connected since (the list is a new one) may still bind the root\n // (quoted: `errors` is a name the build shortens, an AggregateError's is not)\n (e: AggregateError) => (els.length ? readyByRoot.get(root) !== list ? getBindingsReady(root) : Promise.reject(e[\"errors\"][0]) : undefined),\n );\n}\n\n/**\n * The base of the package's elements: HTMLElement, or — where there is none (Node without a DOM)\n * — an inert class, so the entries can be imported headless (a tool reading the manifest, a\n * server framework importing at the top level), as 3.x. Making an element stays a browser's.\n */\nexport const HTMLElementBase = (typeof HTMLElement === \"undefined\" ? class {} : HTMLElement) as typeof HTMLElement;\n\n/**\n * `<wcs-state>` — one engine per element, bound to the element's root node.\n * State resolution order: `state` (id of a JSON script) → `src` → `json` → inner\n * `<script type=\"module\">` → wait for `setInitialState()`.\n */\nexport class WcsState extends HTMLElementBase {\n static getBindingsReady = getBindingsReady;\n /** Servers (@wcstack/server) wait on connectedCallbackPromise when this is set. */\n static hasConnectedCallbackPromise = true;\n\n engine: Engine | null = null;\n readonly connectedCallbackPromise: Promise<void>;\n /**\n * Resolves once the state is loaded and bound (before `$connectedCallback`) — and also when\n * initialization fails: the failure is delivered on connectedCallbackPromise.\n */\n readonly initializePromise: Promise<void>;\n private resolveInitialize!: () => void;\n private resolveConnected!: () => void;\n private rejectConnected!: (e: unknown) => void;\n private started = false;\n /** Initialization failed before the page was bound: `setInitialState` refuses (#14). */\n private failed = false;\n private initial: Record<string, any> | null = null;\n /** Taken over by an add-on (a volume, a DCC definition): it never becomes a root. */\n private claimed: Claimed | null = null;\n /** A claimed element's state is loaded: `setInitialState` from now on is the add-on's re-set. */\n private loaded = false;\n /** The root's bindings are built (getBindingsReady resolves, whatever `$connectedCallback` does). */\n bound?: boolean;\n private receiveInitial: ((state: Record<string, any>) => void) | null = null;\n\n constructor() {\n super();\n this.connectedCallbackPromise = new Promise<void>((resolve, reject) => {\n this.resolveConnected = resolve;\n this.rejectConnected = reject;\n });\n this.connectedCallbackPromise.catch(() => {});\n this.initializePromise = new Promise<void>((resolve) => {\n this.resolveInitialize = resolve;\n });\n }\n\n connectedCallback(): void {\n if (this.started) {\n if (this.claimed !== null) {\n this.claimed.connected();\n return;\n }\n enroll(this);\n const engine = this.engine;\n if (engine !== null) {\n // back in the page: it holds its root again (unless another <wcs-state> bound it meanwhile),\n // binds what was handed over while it was out, and the add-ons hear of it (the volumes that\n // connected meanwhile graft) — then $connectedCallback runs again\n const root = engine.root;\n if (root === this.getRootNode() && !engines.has(root)) engines.set(root, engine);\n drainBinds();\n hooks.element?.(engine, \"back\");\n this.rerun(\"$connectedCallback\", M.ConnectedFailed, () => {\n if (this.isConnected) hooks.element?.(engine, \"connected\");\n });\n }\n return;\n }\n this.started = true;\n const root = this.getRootNode();\n const claimed = hooks.claim?.(this, root);\n if (claimed) {\n this.claimed = claimed;\n // the `<wcs-state>` of the shadow root it binds (a component's, a DCC definition's) is that\n // root's, as 3.x: getBindingsReady there waits for it — until its bindings are built, as a\n // root's — and fails with it (a volume never fails)\n if (!claimed.lenient && this.parentNode instanceof ShadowRoot) enroll(this);\n void (claimed.load === undefined ? this.loadState() : claimed.load()).then((state) => {\n this.loaded = true;\n return claimed.start(state, () => this.built());\n }).then(() => {\n this.resolveInitialize();\n this.resolveConnected();\n }, (e) => this.fail(e, claimed.lenient));\n return;\n }\n void this.start(root);\n enroll(this);\n }\n\n disconnectedCallback(): void {\n if (this.claimed !== null) {\n this.claimed.disconnected();\n return;\n }\n const engine = this.engine;\n if (engine === null) return;\n // out of the page, it lets go of its root (it holds it again when it is back): what outlives the\n // page's content — its root node, the document — does not keep its state and the DOM it bound\n // (a root that failed before its mount has none: enroll takes the root it is in now)\n const root = engine.root;\n if (engines.get(root!) === engine) engines.delete(root!);\n enroll(this, root);\n this.rerun(\"$disconnectedCallback\", M.DisconnectedFailed);\n hooks.element?.(engine, \"disconnected\");\n }\n\n /**\n * Supplies the initial state; on an initialized element, replaces the whole state and\n * re-applies every binding to it before returning (not a write: no `$renderedCallback`).\n */\n setInitialState(state: Record<string, any>): void {\n if (this.failed) raise(M.ElementFailed);\n // (until a claimed element's state is loaded, this supplies it like a root's)\n if (this.loaded) {\n this.claimed!.reset(state);\n return;\n }\n if (this.engine !== null) {\n this.engine.reset(state);\n return;\n }\n if (this.receiveInitial !== null) {\n const receive = this.receiveInitial;\n this.receiveInitial = null;\n receive(state);\n } else {\n this.initial = state;\n }\n }\n\n /** Runs `callback` with a state proxy; its writes are applied in the next drain. */\n createState(mutability: \"readonly\" | \"writable\", callback: (state: Record<string, any>) => void): void {\n const engine = this.engine;\n if (engine === null) raise(M.NotInitialized);\n if (mutability === \"readonly\") engine.readonlyDepth++;\n try {\n callback(engine.proxy);\n } finally {\n if (mutability === \"readonly\") engine.readonlyDepth--;\n }\n }\n\n /** `createState` whose callback may await; a readonly proxy stays readonly across its awaits. */\n async createStateAsync(mutability: \"readonly\" | \"writable\", callback: (state: Record<string, any>) => Promise<void>): Promise<void> {\n const engine = this.engine;\n if (engine === null) raise(M.NotInitialized);\n await callback(mutability === \"writable\" ? engine.proxy : new Proxy(engine.proxy, {\n // as in createState(\"readonly\"), the writes of $setAll and $resolve (path, indexes, value) refuse;\n // read with this view as the receiver, a method comes as it is and runs on this view\n get(t, k, receiver) {\n const v = Reflect.get(t, k, receiver);\n return k === \"$setAll\" || k === \"$resolve\" ? (...a: unknown[]) => (a.length > 2 && raise(M.Readonly), v(...a)) : v;\n },\n set() {\n raise(M.Readonly);\n },\n }));\n }\n\n private async loadState(): Promise<Record<string, any>> {\n // a parser that inserts the element before its children (a server render) has added them by now\n await 0;\n const id = this.getAttribute(\"state\");\n if (id !== null) {\n // a JSON script of that id (an element of user content with the same id, earlier, is not it)\n const find = (r: Node): HTMLScriptElement | undefined =>\n [...(r as Document).querySelectorAll<HTMLScriptElement>('script[type=\"application/json\"]')].find((x) => x.id === id);\n const script = find(this.getRootNode()) ?? find(document);\n if (script === undefined) return Promise.reject(new Error(`[@wcstack/state] ${text(M.NoScript, [id])}`));\n return Promise.resolve(JSON.parse(script.textContent || \"{}\"));\n }\n const src = this.getAttribute(\"src\");\n if (src !== null) return loadSrc(src);\n const json = this.getAttribute(\"json\");\n if (json !== null) return Promise.resolve(JSON.parse(json));\n const script = this.querySelector('script[type=\"module\"]') as HTMLScriptElement | null;\n if (script !== null) return loadInnerScript(script);\n if (this.initial !== null) return Promise.resolve(this.initial);\n return new Promise((resolve) => {\n this.receiveInitial = resolve;\n });\n }\n\n private async start(root: Node): Promise<void> {\n try {\n // what an add-on serves: a volume, a component mount, a DCC definition, server rendering\n const host = (root as ShadowRoot).host;\n if (this.hasAttribute(\"mount\") || this.hasAttribute(\"bind-component\") || host?.hasAttribute(\"data-wc-definition\")) {\n requireFeature(\"scopes\", \"<wcs-state>\");\n }\n const state = await this.loadState();\n const loading = loadFeatures(state);\n if (loading) await loading;\n // taken out of its root while it loaded (the page's content replaced, or moved to another root):\n // nothing is mounted on the root it left. It starts again where it is now, or when it connects\n // again. A state given by setInitialState() is kept for that; a state= / src= / json= / inline\n // script source is read again (a fetch runs again, an inline module is evaluated again)\n if (this.getRootNode() !== root) {\n this.initial = state;\n this.started = false;\n if (this.isConnected) this.connectedCallback();\n return;\n }\n if (this.hasAttribute(\"enable-ssr\")) requireFeature(\"ssr\", \"enable-ssr\");\n // one state tree per root: another <wcs-state> already bound this root (and still does —\n // whatever its $connectedCallback did then), or a component's took it\n const other = engines.get(root)?.element as WcsState | undefined;\n if (other?.isConnected && (other.bound || other.claimed)) raise(M.SecondRoot);\n const engine = new Engine(state, makeStrategy());\n engine.element = this;\n this.engine = engine;\n hooks.element?.(engine, \"mounting\");\n mount(engine, root as Document | ShadowRoot);\n drainBinds();\n engine.watchRendered();\n this.built();\n await engine.callHook(\"$connectedCallback\");\n if (this.isConnected) hooks.element?.(engine, \"connected\");\n this.resolveConnected();\n } catch (e) {\n // (a root that bound its page and whose $connectedCallback then failed has not: re-set stays open)\n this.failed = !this.bound;\n this.fail(e);\n }\n }\n\n /** The bindings are built (before `$connectedCallback`): getBindingsReady resolves, initializePromise too. */\n private built(): void {\n this.bound = true;\n this.resolveInitialize();\n }\n\n /**\n * Initialization failed: reported once, the element (and where its state comes from) before what\n * was thrown, as 3.5 — `<wcs-state src=\"./state.js\"> failed to initialize.`, or, once its\n * bindings were built, `… $connectedCallback failed.` — and connectedCallbackPromise rejects with\n * it, or resolves for a claim that is `lenient` (a volume).\n */\n private fail(e: unknown, lenient?: boolean): void {\n this.report(this.bound ? M.ConnectedFailed : M.InitFailed, e);\n this.resolveInitialize();\n if (lenient) this.resolveConnected();\n else this.rejectConnected(e);\n }\n\n /** Reports a failure once: the element (and where its state comes from), then what was thrown. */\n private report(id: M, e: unknown): void {\n const at = [\"mount\", \"bind-component\", \"state\", \"src\"].flatMap((n) => (this.hasAttribute(n) ? [n, this.getAttribute(n)] : []));\n report(e, `[@wcstack/state] ${text(id, [this.localName, ...at])}`);\n }\n\n /**\n * Runs a lifecycle callback of a root that connected before (on reconnect, on disconnect) at once: a\n * failure — thrown or rejected — is reported as a first connection's is, never thrown out of the\n * element's callback.\n */\n private rerun(name: string, id: M, then?: () => void): void {\n void (async () => this.engine!.callHook(name))().then(then, (e) => this.report(id, e));\n }\n}\n\n/**\n * The registries `<wcs-state>` was defined in: an add-on installed later defines its tags there\n * too. Weak: a server creates a registry per render, and holding them would keep every render's\n * registry (and every constructor defined in it) alive.\n */\nlet refs: WeakRef<CustomElementRegistry>[] = [];\n\n/**\n * The registries still alive (dead references are dropped). A registry deref() returned stays\n * alive until the end of this job, so the second deref() of each kept reference finds it.\n */\nexport function registries(): CustomElementRegistry[] {\n refs = refs.filter((r) => r.deref());\n return refs.map((r) => r.deref()!);\n}\n\n/**\n * Registers `<wcs-state>` (and the installed add-ons' tags) in `registry` — a scoped registry\n * does not inherit the global one, so a tree using one needs its own definitions.\n */\nexport function define(registry: CustomElementRegistry = customElements): void {\n installBinder();\n if (!registries().includes(registry)) refs.push(new WeakRef(registry));\n const tag = config.tagNames.state;\n if (registry.get(tag) === undefined) registry.define(tag, class extends WcsState {});\n hooks.tags?.(registry);\n}\n\n/** Applies `config` and registers `<wcs-state>`. The core only: install the add-ons first. */\nexport function bootstrapState(partial?: IWritableConfig, registry?: CustomElementRegistry): void {\n if (partial) setConfig(partial);\n define(registry);\n}\n\n/**\n * Waits for the bindings under `root` (3.x built them here; the new engine builds them when the\n * root's `<wcs-state>` loads its state, so this only waits — the same as getBindingsReady).\n */\nexport const buildBindings = (root: Document | ShadowRoot): Promise<void> => getBindingsReady(root);\n","/**\n * filters/formats.ts — the formats add-on (38 filters): the values a binding computes and shows, as\n * opposed to the conditions the core set (`./core`) tests. Ported from `@wcstack/state`\n * (`formats/builtinFilters.ts`) with the semantics unchanged.\n *\n * - number display: `toFixed round floor ceil percent unit locale currency`\n * - string shaping: `upper lower capitalize trim slice padStart padEnd repeat reverse truncate join`\n * (`substr` was removed in 4.0: `slice(start, start + length)`)\n * - date and time: `date time datetime ymd hms`\n * - arithmetic: `add sub mul div mod abs clamp`\n * - conversions: `number string int float`\n * - missing values: `defaults coalesce nullIfEmpty`\n *\n * (The last three groups were the core's up to 4.0.0-rc.3.)\n *\n * `installFormats()` puts them in the registry. Without it, one of these filters fails when the\n * bindings are planned with `[wcs/filter-unknown]` naming this add-on (never passes silently).\n * The locale-dependent five (`locale currency date time datetime`) read `config.locale` as their default.\n */\nimport { config } from \"../config\";\nimport { currencyInvalid, optionsRequired, styleInvalid, valueMustBeArray, valueMustBeDate, valueMustBeNumber } from \"./errorMessages\";\nimport { firstLiteral, numberOption, requiredNumberOption } from \"./options\";\nimport { registerFilters, type FilterDefinition, type FilterFactory, type FilterFn } from \"./registry\";\nimport { coreFilters, numeric } from \"./core\";\nimport { M, raise, text } from \"../messages\";\n\n/**\n * Extends the display-side empty-value contract (requirement B8) to the filters that build their\n * result with `String(value)`: those turn `undefined` / `null` into the *characters* \"undefined\" /\n * \"null\", so `attr.title: x|trim` wrote `title=\"undefined\"` where `attr.title: x` removes the\n * attribute. This family passes an absent value straight through and leaves the decision to the\n * apply side (attribute removed, class cleared, style cleared, text emptied).\n *\n * Deliberately **not** wrapped: the filters that reject a value of the wrong type (the number and\n * array families) — their throw is confined to the one binding and reported, a different quality of\n * failure from painting the word \"undefined\" into the page. The date family is wrapped (since 4.7):\n * a date usually arrives later (a fetch, a route) and is absent until then, and no value put in\n * front (`coalesce`) could stand for a missing date — every load reported a failure\n * (docs/seam-apps.md, prod-booking). A value of another type still throws.\n */\nconst nullishPassthrough = (factory: (options: string[]) => FilterFn): FilterFactory =>\n (options: string[]): FilterFn => {\n const filterFn = factory(options);\n // `== null` matches both null and undefined (deliberately loose)\n return (value: unknown): unknown => (value == null ? value : filterFn(value));\n };\n\n/** Fixed decimals (default 0). */\nconst toFixed = (options: string[]): FilterFn => {\n const opt = numberOption(options?.[0] ?? \"0\", 'toFixed');\n return (value: unknown): string => {\n if (typeof value !== 'number') {valueMustBeNumber('toFixed', value);}\n return value.toFixed(opt);\n };\n};\n\n/** Rounds to the given decimals (default 0). */\nconst round = (options: string[]): FilterFn => {\n const optValue = Math.pow(10, numberOption(options?.[0] ?? '0', 'round'));\n return (value: unknown): number => {\n if (typeof value !== 'number') {valueMustBeNumber('round', value);}\n return Math.round(value * optValue) / optValue;\n };\n};\n\n/** Rounds down to the given decimals (default 0). */\nconst floor = (options: string[]): FilterFn => {\n const optValue = Math.pow(10, numberOption(options?.[0] ?? '0', 'floor'));\n return (value: unknown): number => {\n if (typeof value !== 'number') {valueMustBeNumber('floor', value);}\n return Math.floor(value * optValue) / optValue;\n };\n};\n\n/** Rounds up to the given decimals (default 0). */\nconst ceil = (options: string[]): FilterFn => {\n const optValue = Math.pow(10, numberOption(options?.[0] ?? '0', 'ceil'));\n return (value: unknown): number => {\n if (typeof value !== 'number') {valueMustBeNumber('ceil', value);}\n return Math.ceil(value * optValue) / optValue;\n };\n};\n\n/** `0.123` → `\"12%\"` with the given decimals (default 0). */\nconst percent = (options: string[]): FilterFn => {\n const opt = numberOption(options?.[0] ?? '0', 'percent');\n return (value: unknown): string => {\n if (typeof value !== 'number') {valueMustBeNumber('percent', value);}\n return `${(value * 100).toFixed(opt)}%`;\n };\n};\n\n/**\n * Appends a CSS unit (or any suffix). Accepts strings as well as numbers **on purpose**: the useful\n * chains run through `toFixed` / `percent`, which already return strings\n * (`style.height: cpu|clamp(0,100)|toFixed(0)|unit(%)`). null / undefined pass through\n * (`nullishPassthrough`) rather than becoming \"undefinedpx\".\n */\nconst unit = (options: string[]): FilterFn => {\n const opt = options?.[0] ?? optionsRequired('unit');\n return (value: unknown): string => String(value) + opt;\n};\n\nlet seen: string | undefined;\nlet valid = \"en\";\n\n/**\n * The default locale (`config.locale`) as Intl takes it, checked when it changes (an identity\n * compare per apply): one it does not (`<html lang=\"en_US\">`) is \"en\" (as 3.x), with a warning.\n */\nfunction defaultLocale(): string {\n if (config.locale !== seen) {\n seen = config.locale;\n try {\n valid = Intl.getCanonicalLocales(seen)[0];\n } catch {\n console.warn(`[@wcstack/state] ${text(M.LocaleInvalid, [seen])}`);\n valid = \"en\";\n }\n }\n return valid;\n}\n\n/**\n * Locale-formatted number. The locale-dependent filters (`locale date time datetime`) fix an\n * **explicit** locale at construction but read the default `config.locale` **on every apply**: a\n * default baked into the closure at binding time would make an ordering accident (locale settled\n * after the bindings) permanent, since `config.locale` is not in the dependency graph. Read per\n * apply, a re-applied binding at least recovers.\n */\nconst locale = (options: string[]): FilterFn => {\n const explicit = options?.[0];\n return (value: unknown): string => {\n if (typeof value !== 'number') {valueMustBeNumber('locale', value);}\n return value.toLocaleString(explicit ?? defaultLocale());\n };\n};\n\n/**\n * A number as money: `currency(code[, locale])`, the code ISO 4217 (`price|currency(JPY)` → \"¥1,800\",\n * `currency(EUR,de-DE)` → \"1.800,00 €\"). A code Intl does not take fails when the bindings are planned.\n * (docs/seam-apps.md, router-admin: the page built an `Intl.NumberFormat` per currency in getters.)\n */\nconst currency = (options: string[]): FilterFn => {\n const code = options?.[0] ?? optionsRequired('currency');\n const explicit = options?.[1];\n const format = { style: \"currency\", currency: code } as const;\n try {\n new Intl.NumberFormat(\"en\", format);\n // (Intl takes any three letters: the list of the ones it knows, where there is one)\n const known = (Intl as { supportedValuesOf?: (key: string) => string[] }).supportedValuesOf?.(\"currency\");\n if (known && !known.includes(code.toUpperCase())) throw 0;\n } catch {\n currencyInvalid(code);\n }\n return (value: unknown): string => {\n if (typeof value !== 'number') {valueMustBeNumber('currency', value);}\n return value.toLocaleString(explicit ?? defaultLocale(), format);\n };\n};\n\nconst upper = (): FilterFn => (value: unknown): string => String(value).toUpperCase();\n\nconst lower = (): FilterFn => (value: unknown): string => String(value).toLowerCase();\n\n/** The first character upper-cased (`charAt(0)` of \"\" is \"\", so an empty string stays empty). */\nconst capitalize = (): FilterFn => (value: unknown): string => {\n const v = String(value);\n return v.charAt(0).toUpperCase() + v.slice(1);\n};\n\nconst trim = (): FilterFn => (value: unknown): string => String(value).trim();\n\n/** `slice(start[, end])`. */\nconst slice = (options: string[]): FilterFn => {\n const numberedOpts: number[] = [requiredNumberOption(options, 0, 'slice')];\n const opt2 = options?.[1];\n if (typeof opt2 !== 'undefined') {\n numberedOpts.push(numberOption(opt2, 'slice'));\n }\n return (value: unknown): string => String(value).slice(...numberedOpts);\n};\n\n/** Pads the start to a length; the pad string defaults to '0' (JavaScript's default is a space). */\nconst padStart = (options: string[]): FilterFn => {\n const opt1 = requiredNumberOption(options, 0, 'padStart');\n const opt2 = options?.[1] ?? '0';\n return (value: unknown): string => String(value).padStart(opt1, opt2);\n};\n\n/** Pads the end to a length; the pad string defaults to ' ' (as in JavaScript). */\nconst padEnd = (options: string[]): FilterFn => {\n const opt1 = requiredNumberOption(options, 0, 'padEnd');\n const opt2 = options?.[1] ?? ' ';\n return (value: unknown): string => String(value).padEnd(opt1, opt2);\n};\n\nconst repeat = (options: string[]): FilterFn => {\n const opt = requiredNumberOption(options, 0, 'repeat');\n return (value: unknown): string => String(value).repeat(opt);\n};\n\nconst reverse = (): FilterFn => (value: unknown): string => String(value).split('').reverse().join('');\n\n/**\n * Shortens a string and appends a suffix (default '…', U+2026). The length counts **kept\n * characters**; a string at or below it is returned untouched (no suffix).\n */\nconst truncate = (options: string[]): FilterFn => {\n const maxLength = requiredNumberOption(options, 0, 'truncate');\n const suffix = options?.[1] ?? '…';\n return (value: unknown): string => {\n const v = String(value);\n if (v.length <= maxLength) {return v;}\n return v.slice(0, maxLength) + suffix;\n };\n};\n\n/**\n * Joins an array. The default separator is \", \" rather than \",\": a bare comma is what `String()`\n * already produces, so defaulting to it would make `|join` a no-op.\n */\nconst join = (options: string[]): FilterFn => {\n const opt = options?.[0] ?? ', ';\n return (value: unknown): string => {\n if (!Array.isArray(value)) {valueMustBeArray('join');}\n return value.join(opt);\n };\n};\n\nconst STYLES = [\"full\", \"long\", \"medium\", \"short\"];\n\ntype DateStyle = Intl.DateTimeFormatOptions[\"dateStyle\"];\n\n/**\n * The options of `date time datetime`: `(locale?, style?, zone?)`. The style is Intl's `dateStyle` /\n * `timeStyle` (`date(en-US,medium)` → \"Oct 13, 2026\"); without one the format is the locale's\n * numeric one. The zone (4.10) is an IANA time zone, Intl's `timeZone` (`time(ja-JP,short,Asia/Tokyo)`);\n * without one the filters format in the runtime's zone — the reader's, or the server's under SSR\n * (docs/seam-apps.md, city-library: a Tokyo library's hours read 17:00 from Los Angeles).\n *\n * An empty argument keeps its default (`date(,,Asia/Tokyo)`, `date(ja-JP,,Asia/Tokyo)`; up to 4.9 an\n * empty locale or style threw inside Intl on every apply). A style in the locale's place keeps the\n * default locale (`date(long)`, `date(long,,Asia/Tokyo)`), and so does a zone alone when it has a \"/\"\n * or is `UTC` — no language tag has a \"/\", and `UTC` as a locale was Intl's silent fallback\n * (`date(Asia/Tokyo)`, `date(UTC)`; another zone without a \"/\" goes third: `date(,,GMT)`). A style or\n * a zone Intl does not take fails when the bindings are planned (a zone in the style's place is told\n * where it goes).\n */\nfunction dateOptions(options: string[], fn: string): [string | undefined, DateStyle, string | undefined] {\n let [loc, style, zone] = (options ?? []).map((option) => option || undefined);\n if (!style && STYLES.includes(loc!)) [loc, style] = [undefined, loc];\n // (`test(undefined)` reads \"undefined\": no match)\n else if (!style && !zone && /\\/|^UTC$/.test(loc!)) [loc, zone] = [undefined, loc];\n if (style && !STYLES.includes(style)) styleInvalid(fn, style);\n try {\n if (zone) new Intl.DateTimeFormat(undefined, { timeZone: zone });\n } catch {\n // (raised here: ./errorMessages is in the chunk the split core loads, and only this add-on needs it)\n raise(M.FilterTimeZoneInvalid, [fn, zone]);\n }\n return [loc, style as DateStyle, zone];\n}\n\n// (Without a style or a zone the options stay `undefined`, as before. A style and a zone are never \"\" here:\n// dateOptions makes an empty argument `undefined`.)\n\n/** Locale-formatted date (the default locale is read per apply — see `locale`). */\nconst date = (options: string[]): FilterFn => {\n const [explicit, style, timeZone] = dateOptions(options, 'date');\n const format = ((style || timeZone) && { dateStyle: style, timeZone }) as Intl.DateTimeFormatOptions | undefined;\n return (value: unknown): string => {\n if (!(value instanceof Date)) {valueMustBeDate('date', value);}\n return value.toLocaleDateString(explicit ?? defaultLocale(), format);\n };\n};\n\n/** Locale-formatted time (the default locale is read per apply — see `locale`). */\nconst time = (options: string[]): FilterFn => {\n const [explicit, style, timeZone] = dateOptions(options, 'time');\n const format = ((style || timeZone) && { timeStyle: style, timeZone }) as Intl.DateTimeFormatOptions | undefined;\n return (value: unknown): string => {\n if (!(value instanceof Date)) {valueMustBeDate('time', value);}\n return value.toLocaleTimeString(explicit ?? defaultLocale(), format);\n };\n};\n\n/** Locale-formatted date and time (the default locale is read per apply — see `locale`). */\nconst datetime = (options: string[]): FilterFn => {\n const [explicit, style, timeZone] = dateOptions(options, 'datetime');\n const format = ((style || timeZone) && { dateStyle: style, timeStyle: style, timeZone }) as Intl.DateTimeFormatOptions | undefined;\n return (value: unknown): string => {\n if (!(value instanceof Date)) {valueMustBeDate('datetime', value);}\n return value.toLocaleString(explicit ?? defaultLocale(), format);\n };\n};\n\n/** Two digits, zero-padded (`ymd` / `hms`). */\nconst two = (n: number): string => String(n).padStart(2, '0');\n\n/** YYYY-MM-DD with a configurable separator (default '-'), locale-independent, in the runtime's time zone. */\nconst ymd = (options: string[]): FilterFn => {\n const opt = options?.[0] ?? '-';\n return (value: unknown): string => {\n if (!(value instanceof Date)) {valueMustBeDate('ymd', value);}\n return `${value.getFullYear()}${opt}${two(value.getMonth() + 1)}${opt}${two(value.getDate())}`;\n };\n};\n\n/** HH:MM:SS with a configurable separator (default ':'), zero-padded and locale-independent, in the runtime's time zone. */\nconst hms = (options: string[]): FilterFn => {\n const opt = options?.[0] ?? ':';\n return (value: unknown): string => {\n if (!(value instanceof Date)) {valueMustBeDate('hms', value);}\n return `${two(value.getHours())}${opt}${two(value.getMinutes())}${opt}${two(value.getSeconds())}`;\n };\n};\n\nconst abs = (): FilterFn => (value: unknown): number => {\n if (typeof value !== 'number') {valueMustBeNumber('abs', value);}\n return Math.abs(value);\n};\n\n/** Constrains a number to the inclusive range [min, max] (`style.width: ratio|clamp(0,1)|percent(0)`). */\nconst clamp = (options: string[]): FilterFn => {\n const min = requiredNumberOption(options, 0, 'clamp');\n const max = requiredNumberOption(options, 1, 'clamp');\n return (value: unknown): number => {\n if (typeof value !== 'number') {valueMustBeNumber('clamp', value);}\n return Math.min(Math.max(value, min), max);\n };\n};\n\n// The conversions convert — an absent value is converted too (`string` gives \"undefined\");\n// put `coalesce` in front when a missing value should not be converted.\nconst number = (): FilterFn => (value: unknown): number => Number(value);\n\nconst string = (): FilterFn => (value: unknown): string => String(value);\n\nconst int = (): FilterFn => (value: unknown): number => parseInt(String(value), 10);\n\nconst float = (): FilterFn => (value: unknown): number => parseFloat(String(value));\n\n/** Replaces a falsy value (JavaScript's truthiness) with the typed literal: defaults(0) gives 0, defaults('0') \"0\" (B9). */\nconst defaults = (options: string[], literals?: readonly unknown[]): FilterFn => {\n const opt = options?.[0] ?? optionsRequired('defaults');\n const fallback = firstLiteral(opt, literals);\n return (value: unknown): unknown => {\n if (!value) {return fallback;}\n return value;\n };\n};\n\n/** Replaces only null / undefined (`defaults` also replaces 0, false and \"\") — SQL's COALESCE. */\nconst coalesce = (options: string[], literals?: readonly unknown[]): FilterFn => {\n const opt = options?.[0] ?? optionsRequired('coalesce');\n const fallback = firstLiteral(opt, literals);\n return (value: unknown): unknown => value ?? fallback;\n};\n\n/** \"\" → null, anything else unchanged. */\nconst nullIfEmpty = (): FilterFn => (value: unknown): unknown => (value === \"\") ? null : value;\n\nconst { eq, ne, not, lt, le, gt, ge, falsy, truthy, boolean } = coreFilters;\n\n/**\n * What `installFormats()` registers: factory and [min, max] argument count (B3 — the same bounds\n * lint uses), in the order the registry keeps them. The did-you-mean suggestion gives a tie to the\n * first registered, so the order is the one the full build registered up to 4.0.0-rc.3, when this\n * add-on had the 23 display filters and the core 24: the display filters, then that core set, each\n * in the source's (lint's) relative order. The core's 10 are registered here too, in their place\n * (the core registers them again when it first plans a binding, and a name registered again keeps\n * its place).\n */\nconst registered: Readonly<Record<string, FilterDefinition>> = {\n toFixed: { factory: toFixed, arity: [0, 1] },\n locale: { factory: locale, arity: [0, 1] },\n\n // The `String(value)` family passes an absent value through (B8 — see nullishPassthrough)\n upper: { factory: nullishPassthrough(upper), arity: [0, 0] },\n lower: { factory: nullishPassthrough(lower), arity: [0, 0] },\n capitalize: { factory: nullishPassthrough(capitalize), arity: [0, 0] },\n trim: { factory: nullishPassthrough(trim), arity: [0, 0] },\n slice: { factory: nullishPassthrough(slice), arity: [1, 2] },\n // The length is required too (the implementation reads both)\n padStart: { factory: nullishPassthrough(padStart), arity: [1, 2] },\n padEnd: { factory: nullishPassthrough(padEnd), arity: [1, 2] },\n repeat: { factory: nullishPassthrough(repeat), arity: [1, 1] },\n reverse: { factory: nullishPassthrough(reverse), arity: [0, 0] },\n truncate: { factory: nullishPassthrough(truncate), arity: [1, 2] },\n join: { factory: join, arity: [0, 1] },\n\n round: { factory: round, arity: [0, 1] },\n floor: { factory: floor, arity: [0, 1] },\n ceil: { factory: ceil, arity: [0, 1] },\n percent: { factory: percent, arity: [0, 1] },\n unit: { factory: nullishPassthrough(unit), arity: [1, 1] },\n\n // The locale-dependent three take a locale like `locale` does (`date(ja-JP)`), a style (`date(ja-JP,long)`)\n // and, since 4.10, a time zone (`date(ja-JP,long,Asia/Tokyo)`)\n date: { factory: nullishPassthrough(date), arity: [0, 3] },\n time: { factory: nullishPassthrough(time), arity: [0, 3] },\n datetime: { factory: nullishPassthrough(datetime), arity: [0, 3] },\n ymd: { factory: nullishPassthrough(ymd), arity: [0, 1] },\n hms: { factory: nullishPassthrough(hms), arity: [0, 1] },\n\n // the core set of 4.0.0-rc.3 (the core's own: eq ne not lt le gt ge falsy truthy boolean)\n eq, ne, not, lt, le, gt, ge,\n add: numeric('add', (value, opt) => value + opt),\n sub: numeric('sub', (value, opt) => value - opt),\n mul: numeric('mul', (value, opt) => value * opt),\n div: numeric('div', (value, opt) => value / opt),\n mod: numeric('mod', (value, opt) => value % opt),\n abs: { factory: abs, arity: [0, 0] },\n clamp: { factory: clamp, arity: [2, 2] },\n int: { factory: int, arity: [0, 0] },\n float: { factory: float, arity: [0, 0] },\n falsy, truthy,\n defaults: { factory: defaults, arity: [1, 1] },\n coalesce: { factory: coalesce, arity: [1, 1] },\n boolean,\n number: { factory: number, arity: [0, 0] },\n string: { factory: string, arity: [0, 0] },\n nullIfEmpty: { factory: nullIfEmpty, arity: [0, 0] },\n // (added in 4.2: last, so the order of the others is unchanged)\n currency: { factory: currency, arity: [1, 2] },\n};\n\n/** The formats add-on's own filters (what `registered` holds beyond the core set), in that order. */\nexport const formatFilters: Readonly<Record<string, FilterDefinition>> = /*#__PURE__*/ Object.fromEntries(\n /*#__PURE__*/ Object.entries(registered).filter(([name]) => !(name in coreFilters)),\n);\n\nlet installed = false;\n\n/** Puts the formats add-on in the registry. Idempotent. */\nexport function installFormats(): void {\n if (installed) return;\n installed = true;\n registerFilters(registered);\n}\n","/**\n * The formats add-on (@wcstack/state/features/formats): the 38 filters that compute and show a value\n * (display, string shaping, dates — locale-aware —, arithmetic, conversions, missing values).\n */\nimport { hooks, type Feature } from \"../hooks\";\nimport { installFormats } from \"../filters/formats\";\n\nexport const formats: Feature = { name: \"formats\", hooks, install: installFormats };\nexport default formats;\n","/**\n * diagnostics/guidance.ts — self-fix guidance for error messages, ported verbatim from\n * `@wcstack/state` (`errorGuidance.ts`). Only the diagnostics add-on uses it: the core's\n * messages state the fact, and the add-on appends this.\n *\n * The did-you-mean criteria (edit distance 2, ties go to the first candidate, case folded) are the\n * same as lint's suggestion, so the console, lint and the IDE never propose different names.\n */\n\n/** Insert / delete / substitute edit distance. Returns max + 1 early when the lengths differ by more than max. */\nfunction editDistance(a: string, b: string, max: number): number {\n if (Math.abs(a.length - b.length) > max) {\n return max + 1;\n }\n const prev: number[] = new Array(b.length + 1);\n const curr: number[] = new Array(b.length + 1);\n for (let j = 0; j <= b.length; j++) {\n prev[j] = j;\n }\n for (let i = 1; i <= a.length; i++) {\n curr[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);\n }\n for (let j = 0; j <= b.length; j++) {\n prev[j] = curr[j];\n }\n }\n return prev[b.length];\n}\n\n/**\n * The nearest candidate within edit distance 2 as ` Did you mean \"<best>\"?`, or `\"\"` when there is\n * none. An empty input (a trailing `a|` pipe) gets no suggestion.\n */\nexport function didYouMean(input: string, candidates: Iterable<string>): string {\n if (input.length === 0) {\n return \"\";\n }\n const folded = input.toLowerCase();\n let best: string | null = null;\n let bestDistance = 3;\n for (const candidate of candidates) {\n const distance = editDistance(folded, candidate.toLowerCase(), 2);\n if (distance < bestDistance) {\n best = candidate;\n bestDistance = distance;\n }\n }\n return best !== null ? ` Did you mean \"${best}\"?` : \"\";\n}\n\n/**\n * The pointer to lint. Attach it **only where lint actually detects the case** — a hint that sends\n * the author to a lint run that comes back clean costs the loop its credibility.\n */\nexport const LINT_HINT = \" Validate statically: npx @wcstack/lint <file>.\";\n","/**\n * The sentences of the core's numbered messages (src/messages.ts), in the diagnostics add-on:\n * the core carries the number and the values, this renders what the core used to say. Each\n * sentence follows its `[wcs/<code>] ` (`codeOf`: the code the hundreds of the number name).\n * `Record<M, …>` makes a number without a sentence a type error.\n */\nimport { M } from \"../messages\";\nimport { MAX_DRAIN_PASSES, MAX_INDEX_PARAM, MAX_RENDER_CHAIN } from \"../engine\";\nimport { MAX_PATH_SEGMENTS, MODIFIER_SEPARATOR, RECURSION_WILDCARD } from \"../parser/define\";\n\ntype Sentence = (...a: any[]) => string;\n\n/**\n * The code of each hundred of message numbers (\"\" = none): the code lint and the VS Code extension\n * report for the same case. The core carried this up to 4.0.0-rc.3; without this add-on a message\n * now reads as its number and values alone.\n */\nexport const CODES = [\n \"\", \"binding-syntax\", \"template-syntax\", \"binding-path-missing\", \"binding-type-expectation\",\n \"filter-unknown\", \"filter-arity\", \"getter-cycle\", \"getter-depth-exceeded\", \"index-arity\",\n \"index-param-range\", \"recursion-unsupported\", \"token-misconfigured\", \"token-undeclared\",\n \"wildcard-rank\", \"spread-no-bindable\", \"declaration-alias\", \"name-alias\",\n];\n\n/** `[wcs/<code>] ` for a message number, or \"\" when it has none. */\nexport const codeOf = (id: M): string => {\n const c = CODES[(id / 100) | 0];\n return c ? `[wcs/${c}] ` : \"\";\n};\n\n/** The options 4.0 moved from `bootstrapState` to the state's `$behavior`. */\nconst MOVED = [\"enableMustache\", \"sameValueGuard\", \"enableDirectionalInitialSync\"];\n\n/** `<tag a=\"v\" …>` from the tag and its attributes' names and values. */\n/** What a value given to a filter was (`a string (\"2026-10-13T…\")`), for the type messages. */\nconst was = (v: unknown): string =>\n v == null ? String(v)\n : v instanceof Date ? \"a Date\"\n : Array.isArray(v) ? \"an array\"\n : typeof v === \"string\" ? `a string (${JSON.stringify(v.length > 32 ? v.slice(0, 32) + \"…\" : v)})`\n : typeof v === \"object\" ? \"an object\" : `a ${typeof v} (${String(v)})`;\n/** The namespace a binding of kind 2–4 (dom/view.ts: K_CLASS, K_ATTR, K_STYLE) names its member under. */\nconst NAMESPACES = [\"\", \"\", \"class.\", \"attr.\", \"style.\"];\n\nconst element = (tag: string, at: string[]): string => `<${tag}${at.map((a, i) => (i % 2 ? `=\"${a}\"` : ` ${a}`)).join(\"\")}>`;\n\nconst CSP_GUIDE = \"https://github.com/wcstack/wcstack/blob/main/docs/csp.md\";\n\nexport const SENTENCES: Record<M, Sentence> = {\n [M.ScanRemoved]: () => \"$scan was removed (use $watch or $on)\",\n [M.GetterWithoutSetter]: (p) => `\"${p}\" is a getter without a setter`,\n [M.NoRow]: (p) => `no row for \"${p}\"`,\n [M.ParentNotObject]: (p, parent) => `cannot write \"${p}\": its parent is ${parent}`,\n [M.NotAMethod]: (name) => `\"${name}\" is not a method`,\n [M.GetAllNoCommonLevel]: (p) => `$getAll(\"${p}\"): no loop level in common with the context`,\n [M.EqIndexNoRow]: (p) => `$eqIndex(\"${p}\") needs a list row scope.`,\n [M.Readonly]: () => \"This state is readonly.\",\n [M.SetAllNeedsIndexes]: (p) => `$setAll(\"${p}\") needs indexes ([] for every match)`,\n [M.SetAllSpreadLength]: (p, n) => `$setAll(\"${p}\", …, { spread: true }) needs an array of ${n} values`,\n [M.DrainNotSettled]: () => `updates did not settle after ${MAX_DRAIN_PASSES} passes`,\n [M.RenderChain]: () => `render chain depth limit exceeded (${MAX_RENDER_CHAIN} drains that rendering itself started); bindings for this batch were not applied.`,\n // (named as written — `textContent: iso`, `class.active: x` — when the binding has a member; else its type)\n [M.BindingFailed]: (type, p, name, kind) => `binding \"${name ? (NAMESPACES[kind] ?? \"\") + name : type}: ${p}\" failed to apply.`,\n [M.LoadFailed]: (src, status) => `failed to load \"${src}\": ${status}`,\n [M.ElementFailed]: () => \"this <wcs-state> failed to initialize; create a new one\",\n [M.NotInitialized]: () => \"state is not initialized\",\n [M.NoScript]: (id) => `no <script> with id \"${id}\"`,\n [M.InlineBlocked]: () => `The inline <script> of <wcs-state> was blocked by Content-Security-Policy. Inline state is evaluated through a blob: URL: give the page's nonce to the <script> that loads @wcstack/state, or allow blob: in script-src. Moving the state into an external file (src=\"./state.js\") needs neither. See ${CSP_GUIDE}`,\n [M.InlineFailed]: (detail) => `Failed to evaluate the inline <script> of <wcs-state>: ${detail}. If this page sets a Content-Security-Policy, see ${CSP_GUIDE}`,\n [M.TokenSubscriberThrew]: (name) => `a subscriber of token \"${name}\" threw.`,\n [M.TokenListNotArray]: (key) => `${key} must be an array of strings.`,\n [M.TokenEntryEmpty]: (key) => `${key} entries must be non-empty strings.`,\n [M.TokenEntryReserved]: (key, name, reserved) => `${key} entry \"${name}\" conflicts with the reserved namespace name \"${reserved}\".`,\n [M.TokenEntryDuplicated]: (key, name) => `${key} entry \"${name}\" is duplicated.`,\n [M.OnNotObject]: () => \"$on must be an object of handlers.\",\n [M.OnEntryUndeclared]: (name) => `$on entry \"${name}\" is not declared in $eventTokens.`,\n [M.OnEntryNotFunction]: (name) => `$on entry \"${name}\" must be a function.`,\n [M.NamingLimit]: (limit) => `view-transition naming-limit (${limit}) reached.`,\n [M.FilterOptionsRequired]: (fn) => `filter ${fn} requires at least one option`,\n [M.FilterOptionNotNumber]: (fn) => `filter ${fn} requires a number as option`,\n [M.FilterValueNotNumber]: (fn, v) => `filter ${fn} requires a number value, not ${was(v)}${typeof v === \"string\" ? ` — put |number before |${fn}, or convert it where it is read` : \"\"}`,\n [M.FilterValueNotDate]: (fn, v) => `filter ${fn} requires a date value (a Date), not ${was(v)}${typeof v === \"string\" || typeof v === \"number\" ? \" — make the Date where it is read: a getter returning new Date(…)\" : \"\"}${typeof v === \"string\" && /^\\d{4}-\\d\\d-\\d\\d$/.test(v) ? `. A date-only string is a day, not a moment: new Date(${JSON.stringify(v)}) is midnight UTC, the day before west of Greenwich — new Date(y, m - 1, d) is that day where the page is` : \"\"}`,\n // (a time zone in the style's place — `date(ja-JP,Asia/Tokyo)`, `date(ja-JP,UTC)`, the shapes a lone\n // zone is read by in filters/formats.ts — is told where it goes)\n [M.FilterStyleInvalid]: (fn, v) => `filter ${fn} takes a style of full, long, medium or short, not \"${v}\"${/\\/|^UTC$/.test(v) ? ` — a time zone is the third argument, after the locale and the style, and an empty argument keeps its default: ${fn}(,,${v}), ${fn}(en-US,long,${v})` : \"\"}`,\n [M.FilterCurrencyInvalid]: (v) => `filter currency takes an ISO 4217 currency code (JPY, USD, EUR), not \"${v}\"`,\n [M.FilterTimeZoneInvalid]: (fn, v) => `filter ${fn} takes an IANA time zone (Asia/Tokyo, America/New_York, UTC), not \"${v}\"`,\n [M.FilterValueNotArray]: (fn) => `filter ${fn} requires an array value`,\n [M.DirectionalSyncDisabled]: () => \"init=/sync= modifiers require enableDirectionalInitialSync.\",\n [M.ModifierUnknown]: (key, modifier) => `Unknown binding modifier \"${key}\" in \"${modifier}\".`,\n [M.ModifierTwice]: (key) => `Binding modifier \"${key}\" may only be specified once.`,\n [M.ModifierValue]: (key, value) => `Invalid ${key} modifier value \"${value}\".`,\n [M.EventInitNone]: () => \"Event bindings only allow init=none.\",\n [M.InitUnsupported]: (type, init) => `Binding type \"${type}\" does not support init=${init}.`,\n [M.MemberUndeclared]: (name) => `Property \"${name}\" is not declared by wcBindable.`,\n [M.InitIncompatible]: (init, name) => `init=${init} is incompatible with wcBindable member \"${name}\".`,\n [M.SyncConnectNeedsOutput]: (name) => `sync=connect requires observable property \"${name}\".`,\n [M.OptionInvalid]: (where, key) => `${where}: \"${key}\" is not one of its options, or not of the option's type.${where === \"bootstrapState\" && MOVED.includes(key) ? \" 4.0 moved it to the state's $behavior.\" : \"\"}`,\n [M.BehaviorChanged]: () => \"a re-set state may not change $behavior: create the element again.\",\n [M.SecondRoot]: () => \"a second <wcs-state> on the same root: there is one state tree per root — graft a subtree with <wcs-state mount=\\\"path\\\"> (v1's name=\\\"…\\\" is gone: read the mounted state by its path).\",\n [M.LocaleInvalid]: (l) => `the locale \"${l}\" (<html lang> or bootstrapState's locale) is not a language tag Intl takes (en-US, not en_US): the locale filters use \"en\".`,\n [M.FeaturesNotArray]: () => '$features must be an array of add-on names ([\"temporal\", \"formats\"]).',\n [M.InitFailed]: (tag, ...at) => `${element(tag, at)} failed to initialize.`,\n [M.ConnectedFailed]: (tag, ...at) => `${element(tag, at)} $connectedCallback failed.`,\n [M.DisconnectedFailed]: (tag, ...at) => `${element(tag, at)} $disconnectedCallback failed.`,\n\n [M.BindTextNoColon]: (t) => `Invalid bindText: \"${t}\". Missing ':' separator between propPart and statePart.`,\n [M.StructuralTakesNoModifiers]: (t, keyword) => `\"${t}\": \"${keyword}\" takes no modifiers or filters on its left side — write \"${keyword}:\".`,\n [M.ElseTakesNoValue]: (t) => `\"${t}\": \"else\" takes no value — write \"else:\".`,\n [M.SpreadNoPath]: (t) => `Invalid spread binding \"${t}\": spread target path is required.`,\n [M.SpreadNoFilters]: (t) => `Invalid spread binding \"${t}\": filters are not allowed on spread targets.`,\n [M.LeadingDotNamespace]: (prop) => `\"${prop}\": a leading \".\" binds an element property by name — write a non-empty property that is not a namespace (class, attr, style, command, eventToken, state).`,\n [M.UnterminatedQuote]: (quote, args) => `unterminated ${quote} quote in the filter arguments \"(${args})\". Close the quote.`,\n [M.FilterUnclosed]: (f) => `Invalid filter format: missing closing parenthesis in \"${f}\".`,\n [M.FilterUnopened]: (f) => `Invalid filter format: missing opening parenthesis in \"${f}\".`,\n [M.FilterParenOrder]: (f) => `Invalid filter format: \")\" comes before \"(\" in \"${f}\".`,\n [M.FilterTrailing]: (f, trailing) => `\"${f}\": unexpected \"${trailing}\" after the filter's closing \")\" — separate filters with \"|\" (write \"${f.slice(0, f.lastIndexOf(\")\") + 1)}|${trailing}\").`,\n [M.FilterEmpty]: (source) => `an empty filter in \"${source}\" — remove the extra \"|\" or name the filter.`,\n [M.FilterNameHasModifiersInput]: (name, mods) => `\"${name}\" is not a filter name: a modifier list \"${MODIFIER_SEPARATOR}${mods}\" comes before the input filters, not inside one`,\n [M.FilterNameHasModifiersOutput]: (name) => `\"${name}\" is not a filter name: \"${MODIFIER_SEPARATOR}\" cannot appear in one.`,\n [M.OneModifierList]: (prop) => `\"${prop}\": a binding takes one modifier list after a single \"#\"`,\n [M.NoPropertyName]: (prop) => `\"${prop}\": the left side of a binding must name a property — write \"<property>: <path>\" (modifiers and input filters come after the name).`,\n [M.TooManySegments]: (p, n) => `\"${p}\" has ${n} path segments — the limit is ${MAX_PATH_SEGMENTS}.`,\n [M.SelectorRemoved]: (t) => `\"${t}\": the \"@name\" selector was removed in v2 — there is a single state tree. Mount the named state onto the tree (<wcs-state mount=\"...\">) and read it by its path prefix instead.`,\n [M.UnsafeSegment]: (p) => `\"${p}\": a state path cannot go through \"__proto__\" or \"prototype\" (it would reach every object's prototype).`,\n [M.ForNoFilters]: (t) => `\"${t}\": \"for:\" takes no filters — a row is \"<path>.<index>\", so the rows of a filtered list would name other elements. Declare a getter that returns the filtered list and loop over it (\"for: <getter>\").`,\n [M.NamespaceNeedsName]: (t, ns) => ns === \"class\"\n ? `\"${t}\": \"class:\" needs a class name — \"class.NAME:\" toggles one class (a bare \"class:\" would set an element property named \"class\", which does nothing). To set the whole class attribute, bind \"className:\".`\n : `\"${t}\": \"attr:\" needs an attribute name — \"attr.NAME:\" sets one attribute (a bare \"attr:\" would set an element property named \"attr\", which does nothing).`,\n [M.EmptySegment]: (t) => `\"${t}\": the right side of a binding must name a state path — write \"<property>: <path>\" (a path segment cannot be empty; \".\" alone and a leading \".\" are the loop-relative shorthand).`,\n\n [M.StructuralNotSingle]: (t) => `Invalid bindText: \"${t}\". 'if', 'elseif', 'else', and 'for' bindings must be single binding.`,\n [M.ElseWithoutIf]: (type) => `\"${type}:\" must follow an \"if:\" template`,\n [M.TemplateHandedOver]: (type) => `a \"${type}:\" template at the top of inserted content was not rendered, as it would render beside itself out of the inserter's reach: wrap it in an element.`,\n [M.OuterInTemplate]: (name) => `\"${name}:\" replaces its element, so it cannot be used inside a \"for\" / \"if\" template (a row or branch keeps its nodes by position): bind innerHTML: on a wrapper element instead.`,\n\n [M.PathMissing]: (p) => `Path \"${p}\" does not exist on the state tree.`,\n\n [M.ClassNeedsBoolean]: (name, type) => `class.${name} needs a boolean, got ${type}.`,\n\n [M.FilterUnknown]: (name) => `filter not found: ${name}.`,\n\n [M.FilterTooFewArgs]: (name, min, given) => `filter \"${name}\" requires at least ${min} argument(s) (${given} given).`,\n [M.FilterTooManyArgs]: (name, max, given) => `filter \"${name}\" accepts at most ${max} argument(s) (${given} given).`,\n\n [M.GetterCycle]: (p) => `\"${p}\" depends on itself`,\n\n [M.GetterDepth]: (p) => `\"${p}\"`,\n\n [M.IndexArityExact]: (api, p, depth, n) => `${api}(\"${p}\") takes ${depth} index(es), got ${n}.`,\n [M.IndexArityAtMost]: (api, p, depth, n) => `${api}(\"${p}\") takes at most ${depth} index(es), got ${n}.`,\n\n [M.IndexParamRange]: (key) => `\"${key}\": list index parameters run from $1 to $${MAX_INDEX_PARAM}.`,\n\n [M.RecursionUnsupported]: (p) => `\"${p}\" uses \"${RECURSION_WILDCARD}\", which is not accepted here.`,\n\n [M.CommandRightSide]: (prop, p) => `\"${prop}: ${p}\": the right-hand side must be $command.<name>`,\n // a native element's command (no hyphen: never a custom element) is the native-commands add-on's\n [M.NoBindable]: (tag, what) => `<${tag}> declares no static wcBindable (${what}).${\n !tag.includes(\"-\") && what.startsWith(\"command.\") ? \" A native element's command needs the add-on @wcstack/state/features/native-commands.\" : \"\"}`,\n [M.NoCommand]: (tag, method) => `<${tag}> declares no command \"${method}\".`,\n [M.NoProperty]: (tag, prop) => `<${tag}> declares no property \"${prop}\".`,\n [M.NativeNoCommand]: (tag, method, allowed) => `<${tag}> has no command \"${method}\" (a native <${tag}>'s commands: ${allowed}).`,\n\n [M.EventTokenUndeclared]: (name) => `eventToken \"${name}\" is not declared in $eventTokens.`,\n [M.CommandTokenUndeclared]: (name) => `\"$command.${name}\" is not declared in $commandTokens.`,\n\n [M.WildcardNoLoop]: (p, depth, n = 0) => `\"${p}\" needs ${depth} enclosing loop level(s); the scope provides ${n}.`,\n [M.WildcardRelative]: (p) => `\"${p}\" is relative: it needs an enclosing \"for\" template`,\n [M.WildcardOtherList]: (p, over, loop) => `\"${p}\" ranges over the rows of \"${over}\", but the enclosing \"for\" template at that level renders \"${loop}\".`,\n\n [M.SpreadNoBindable]: (tag, what) => `<${tag}> declares no static wcBindable (${what}).`,\n\n [M.DeclarationRemoved]: (old, name) => `${old} was removed: write ${name}.`,\n\n [M.ApiRemoved]: (old, name) => `${old} was removed: write ${name}.`,\n};\n","/**\n * The diagnostics add-on's sentences and guidance: a numbered core message rendered as its\n * sentence (src/diagnostics/messages.ts), then how to fix it, the nearest name and the lint\n * pointer. The add-on installs these; so does `@wcstack/state/parser`, a bundle of its own.\n */\nimport { didYouMean, LINT_HINT } from \"./guidance\";\nimport { FORMATS_FILTER_NAMES, hasFilter } from \"../filters/registry\";\nimport type { M } from \"../messages\";\nimport { codeOf, SENTENCES } from \"./messages\";\n\n/** A numbered core message as its sentence (the number and the values if it is not known here). */\nexport function render(id: number, args: readonly unknown[]): string {\n const sentence = SENTENCES[id as M];\n return sentence === undefined ? `${codeOf(id)}#${id} ${args.join(\" \")}` : codeOf(id) + sentence(...args);\n}\n\n/** Codes lint detects statically: only these point the author to a lint run. */\nconst LINT_CODES = new Set([\n \"binding-syntax\", \"template-syntax\", \"filter-unknown\", \"filter-arity\", \"index-arity\",\n \"wildcard-rank\", \"token-undeclared\", \"binding-path-missing\", \"index-param-range\",\n]);\n\n/** How to fix it, by what the message says. */\nconst GUIDES: [RegExp, string][] = [\n [/no loop level in common with the context/, \"; pass indexes ([] for all).\"],\n [/\"([^\"#]+)#([^\"]*)\" is not a filter name: a modifier list .* comes before the input filters/, ' — write \"<property>#$2|$1\".'],\n [/\\[wcs\\/recursion-unsupported\\]/, \" It is only meaningful in a $recursion declaration, in a recursive getter key, and in the path argument of $getAll / $setAll — and only when the state declares a $recursion anchor.\"],\n [/must be single binding/, ' Put the structural binding alone in its own data-wcs (e.g. <template data-wcs=\"for: items\">).'],\n [/\\[wcs\\/wildcard-rank\\] .* needs \\d+ enclosing/, ' Wrap it in that many \"for\" templates, or use $resolve(path, indexes) to name the row explicitly.'],\n [/\\[wcs\\/wildcard-rank\\] .* ranges over the rows of/, ' A \"*\" in a binding is the row of the loop around it: read a row of another list in a getter, with $resolve(path, indexes).'],\n [/\\[wcs\\/binding-type-expectation\\] class\\.([^ ]+)/, ' Write \"class.$1: path|truthy\" to toggle on truthiness.'],\n [/path segments — the limit/, \" Every prefix of a path is interned, so the cost grows with the square of the depth.\"],\n [/\\[wcs\\/index-arity\\] \\$resolve/, \" $resolve takes one index per \\\"*\\\"; $getAll / $setAll take at most that many (fewer expands the rest).\"],\n [/\"([^\"#]+)#[^\"]*\" is not a filter name: \"#\" cannot appear in one/, ' Modifiers belong on the left side of the binding, before the \":\" — write \"$1\" here.'],\n];\n\n/**\n * The filter names 3.2 renamed, which 3.x kept as aliases and 4.0 removed (3.x's `filterAliases`;\n * lint has the same table). Their message names the replacement, not the nearest name: for these\n * that is an unrelated filter (`dec` → `eq`, `fix` → `div`), and following it changes the meaning.\n */\nexport const RENAMED_FILTERS: Readonly<Record<string, string>> = {\n inc: \"add\", dec: \"sub\", fix: \"toFixed\", uc: \"upper\", lc: \"lower\", cap: \"capitalize\", rep: \"repeat\", rev: \"reverse\", pad: \"padStart\", null: \"nullIfEmpty\",\n};\n\n/** How to write a filter 4.0 removed, or null. */\nfunction removedFilter(name: string): string | null {\n // 4.0 folded substr(start, length) into slice(start, end): the second argument changes meaning\n if (name === \"substr\") return ' \"substr\" was removed in 4.0 — write slice(start, start + length): slice takes the end index, not a length.';\n const to = Object.hasOwn(RENAMED_FILTERS, name) ? RENAMED_FILTERS[name] : null;\n return to === null ? null : ` \"${name}\" was renamed \"${to}\" in 3.2 and removed in 4.0 — write \"${to}\".`;\n}\n\nexport function explain(message: string, subject?: string, candidates?: Iterable<string>): string {\n const removed = subject !== undefined && message.includes(\"[wcs/filter-unknown]\") ? removedFilter(subject) : null;\n let out = removed ?? (subject !== undefined && candidates !== undefined ? didYouMean(subject, candidates) : \"\");\n for (const [re, text] of GUIDES) {\n const m = re.exec(message);\n if (m !== null) out += text.replace(/\\$(\\d)/g, (_, i: string) => m[Number(i)]);\n }\n // \"value#ro#wo\": one modifier list — the fix joins them\n const mods = /\"([^\"#]+)#([^\"]+)\": a binding takes one modifier list/.exec(message);\n if (mods !== null) out += ` — write \"${mods[1]}#${mods[2].split(\"#\").join(\",\")}\".`;\n // a formatting filter on a page without the formats add-on (the core names installFeatures), or a\n // typo on a page with no formatting filters at all: the formats add-on may be what is missing\n if (message.includes(\"[wcs/filter-unknown]\")) {\n if (message.includes(\"formats add-on\")) out += ` On a split auto page: features=\"formats\" on the root, or \"$features\": [\"formats\"].`;\n else if (!FORMATS_FILTER_NAMES.some(hasFilter)) {\n out += ` No formatting filters are installed — add the formats add-on: installFeatures([formats]) from \"@wcstack/state/features/formats\" (a split auto page: features=\"formats\", or \"$features\").`;\n }\n }\n const code = /\\[wcs\\/([\\w-]+)\\]/.exec(message);\n // (not something lint reports: the path-length limit is a runtime cost, a template handed over at\n // the top of inserted content (#204) is the page's order of loading, not its markup, and lint's\n // manifest knows the formatting filters — one missing because the formats add-on is not installed\n // is the page's. A row of another list (#1403) and an `outerHTML:` in a template (#203) lint does\n // report, as of its 4.0 parser)\n if (code !== null && LINT_CODES.has(code[1]) && !/ path segments — the limit is |inserted content was not rendered|formats add-on/.test(message)) out += LINT_HINT;\n return out;\n}\n","/**\n * The diagnostics add-on (@wcstack/state/features/diagnostics): the sentences and the self-fix\n * guidance of error messages. The core states the message number and the values\n * (`#901 \"$resolve\" \"m.*.*\" 2 1`); with this installed, the message is the code shared with lint\n * and the sentence (`[wcs/index-arity] $resolve(\"m.*.*\") takes 2 index(es), got 1.`), followed by the\n * nearest name (did-you-mean, the same rule as lint), how to fix it, and a pointer to lint where\n * lint really detects the case. The full `auto` bundle installs it.\n */\nimport { chain, first, hooks, known, type Feature } from \"../hooks\";\nimport type { Engine } from \"../engine\";\nimport { parsePath, type Pattern } from \"../pattern\";\nimport { raiseError } from \"../parser/raiseError\";\nimport { config } from \"../config\";\nimport type { WcsState } from \"../element\";\nimport type { Binding } from \"../dom/view\";\nimport { getTrustedTypesPolicy, isHtmlSink } from \"../trustedTypes\";\nimport { didYouMean, LINT_HINT } from \"../diagnostics/guidance\";\nimport { explain, render } from \"../diagnostics/explain\";\nimport { raise, M } from \"../messages\";\nimport type { Token } from \"../token\";\n\n// ---------------------------------------------------------------- paths that do not resolve\n\n/** What named a path: a binding, a `$watch` key, a `$postUpdate` call, a getter's read. */\nconst BINDING = 0;\nconst WATCH = 1;\nconst POST = 2;\nconst READ = 3;\n/** Paths bindings, `$watch` keys and `$postUpdate` named, by engine: checked one macrotask later (and after a re-set). */\nconst named = new WeakMap<Engine, Map<Pattern, number>>();\nconst checked = new WeakMap<Engine, Set<Pattern>>();\nconst due = new WeakSet<Engine>();\n/** Volumes (`<wcs-state mount>`) whose loading settled: the paths under them are checked from then on. */\nconst settled = new WeakSet<Element>();\n\nfunction findDescriptor(o: object, key: string): PropertyDescriptor | undefined {\n for (let x: object | null = o; x !== null && x !== Object.prototype; x = Object.getPrototypeOf(x)) {\n const d = Object.getOwnPropertyDescriptor(x, key);\n if (d !== undefined) return d;\n }\n return undefined;\n}\n\nfunction keysOf(o: object): string[] {\n const out = new Set<string>();\n for (let x: object | null = o; x !== null && x !== Object.prototype; x = Object.getPrototypeOf(x)) {\n for (const k of Object.getOwnPropertyNames(x)) if (k[0] !== \"$\" && k !== \"constructor\") out.add(k);\n }\n return [...out];\n}\n\n/**\n * The pattern a path with an explicit index reads through: an index with no `*` after it\n * (`items.0.x`) has an accessor of its own (Engine.markupAccessor), so whether it reads a getter\n * is the question of the pattern it names (`items.*.x`). A `*` after the index (`groups.0.items.*.x`,\n * a row of `for: groups.0.items`) reads its row's own item: the pattern itself. So does a path the\n * author declared a getter under (`get \"groups.0.items\"()`): that getter is what it reads (#388).\n */\nfunction wildcardForm(engine: Engine, q: Pattern): Pattern | undefined {\n const segs = q.path.split(\".\");\n // (a leading numeric segment is a root key, not an index: parsePath)\n const i = segs.findIndex((s, j) => j > 0 && /^\\d/.test(s));\n return i < 0 || segs.indexOf(\"*\", i) >= 0 || findDescriptor(engine.target, q.path)?.get !== undefined\n ? q : engine.patterns.peek(parsePath(q.path).pattern);\n}\n\n/**\n * The segment of `p` that certainly does not exist, with the names that do at its level; null\n * when the path exists or it cannot be told without evaluating a getter (a getter on the way, a\n * null or primitive on the way, a list with no row to look into).\n */\nfunction missing(engine: Engine, p: Pattern): { seg: string; names: string[]; row: boolean } | null {\n const chain: Pattern[] = [];\n for (let q: Pattern | null = p; q !== null; q = q.parent) chain.unshift(q);\n const named = (q: Pattern | null): Pattern | null | undefined => (q === null ? null : wildcardForm(engine, q));\n // a getter anywhere on the path answers it — also one declared deeper than a segment the data\n // lacks (\\`get \"box.label\"()\\` with no \\`box\\` key: it renders and updates — docs/seam-apps.md)\n if (chain.some((q) => named(q)?.getter != null)) return null;\n return under(engine, chain, 0, engine.target, named);\n}\n\n/** `missing` from `chain[k]` on, in `v`. */\nfunction under(engine: Engine, chain: Pattern[], k: number, v: any, named: (q: Pattern | null) => Pattern | null | undefined): { seg: string; names: string[]; row: boolean } | null {\n for (; k < chain.length; k++) {\n const q = chain[k];\n if (v === null || typeof v !== \"object\") return null;\n if (q.last === \"*\") {\n if (!Array.isArray(v) || v.length === 0) return null;\n // a row field is declared when any row has it — an optional one (`pending` on the rows a page\n // added itself) is not missing because the first row lacks it (docs/seam-apps.md, ssr-news)\n // (missing in every row: the names any row has are the candidates)\n let first: { seg: string; names: string[]; row: boolean } | null = null;\n for (const row of v) {\n const m = under(engine, chain, k + 1, row, named);\n if (m === null) return null;\n if (first === null) first = m;\n else if (m.seg === first.seg) for (const n of m.names) if (!first.names.includes(n)) first.names.push(n);\n }\n return first;\n }\n if (Array.isArray(v) && /^\\d+$/.test(q.last)) {\n // an explicit index: only a row that is there can be looked into\n if (Number(q.last) >= v.length) return null;\n v = v[Number(q.last)];\n continue;\n }\n const d = findDescriptor(v, q.last);\n // a top-level key a re-set dropped is declared: it reads undefined, and a write fills it\n if (d === undefined && q.parent === null && engine.dropped.has(q.last)) return null;\n if (d === undefined) {\n const names = keysOf(v);\n // getters declared one level under the same parent (`items.*.subtotal`)\n const parent = named(q.parent);\n for (const g of engine.patterns.all()) if (g.parent === parent && g.getter !== null) names.push(g.last);\n // an empty object under a key is a seed the page fills later (`fieldErrors: {}`, then\n // `this.fieldErrors = { date: \"…\" }`), as a `null` one is: nothing in it to be wrong about, and\n // the lint reads the assignments since 4.9 (docs/seam-apps.md, family-ledger)\n if (k > 0 && names.length === 0) return null;\n return { seg: q.last, names, row: chain.slice(0, k).some((x) => x.last === \"*\") };\n }\n if (d.get !== undefined || d.set !== undefined) return null;\n v = d.value;\n }\n return null;\n}\n\nfunction check(engine: Engine): void {\n due.delete(engine);\n const map = named.get(engine);\n if (map === undefined) return;\n let done = checked.get(engine);\n if (done === undefined) checked.set(engine, (done = new Set()));\n // The paths named, and those a getter read (`this[\"items.*.pirce\"]`, `$getAll(\"items.*.pirce\")`): such a read\n // gets undefined, and what is computed from it is wrong without a word (an outside evaluation, a tax return\n // draft). A top-level key the state lacks already fails the read (the core's error); a named path is reported\n // as named; the engine's own accessor of an index path (`items.0.x`) reads for the binding that named it\n const todo = new Map(map);\n const readers = new Map<Pattern, Pattern>();\n for (const p of engine.patterns.all()) {\n const g = p.parent === null || done.has(p) || map.has(p) ? undefined : p.dependents.find((d) => !d.markup);\n if (g === undefined) continue;\n readers.set(p, g);\n todo.set(p, READ);\n }\n for (const [p, kind] of todo) {\n if (done.has(p)) continue;\n done.add(p);\n const m = missing(engine, p);\n if (m === null) continue;\n // under an object an element wrote (`searchParams: query` — the router's query has the URL's keys): its\n // shape is the element's, and a key it lacks now may come with the next write (docs/seam-apps.md, city-library)\n const wrote = byElement.get(engine);\n let up = p.parent;\n while (up !== null && !wrote?.has(up)) up = up.parent;\n if (up !== null) continue;\n // under the mount path of a volume on the page still loading: checked again once it settles (3.x D22)\n const v = [...((engine.root as ParentNode | null)?.querySelectorAll(`${config.tagNames.state}[mount]`) ?? [])]\n .find((e) => !settled.has(e) && (p.path + \".\").startsWith(e.getAttribute(\"mount\") + \".\"));\n if (v !== undefined) {\n done.delete(p);\n void (v as WcsState).initializePromise.then(() => {\n settled.add(v);\n schedule(engine);\n });\n continue;\n }\n // a row of `for: groups.0.items` with a row getter declared on `groups.*.items.*` (#388)\n const w = engine.patterns.peek(parsePath(p.path).pattern);\n let rowGetter = \"\";\n if (w !== undefined && w !== p && w.getter !== null) {\n const loops = w.lists.slice(1).map((l, k) => `for: ${k === 0 ? l!.path : l!.path.slice(w.lists[k]!.path.length + 2)}`);\n rowGetter = ` The getter \"${w.path}\" is declared for the rows of ${loops.join(\" → \")}; a list named by an index has rows of its own.`;\n }\n const near = didYouMean(m.seg, m.names);\n // A row field no row has is not a sign of a mistake: rows are data, and an optional field (the\n // `pending` a page puts on its own rows) is absent from the server's (docs/seam-apps.md, ssr-news).\n // Reported only with a near name — a likely typo (`.nmae` beside `name`) — or a row getter of\n // another list form. So is a getter's read: `this[\"opts.flag\"] ?? false` reads an optional key on purpose\n if ((m.row || kind === READ) && near === \"\" && rowGetter === \"\") continue;\n const [code, subject, source] = kind === WATCH ? [\"watch-path-missing\", \"$watch path\", \"watch\"]\n : kind === POST ? [\"post-update-path-missing\", \"$postUpdate path\", \"postUpdate\"]\n : kind === READ ? [\"read-path-missing\", \"Path\", \"getter\"]\n : [\"binding-path-missing\", \"Bound path\", \"binding\"];\n hooks.noticed?.(engine, { \"type\": \"state:path-unresolved\", \"source\": source, \"path\": p.path, \"missingSegment\": m.seg });\n console.warn(`[@wcstack/state] [wcs/${code}] ${subject} \"${p.path}\"${kind === READ ? ` read by the getter \"${readers.get(p)!.path}\"` : \"\"} does not resolve on the state tree: \"${m.seg}\" is not declared.${near}${rowGetter} ${kind === POST ? \"The call updates nothing.\" : kind === READ ? \"The getter reads undefined.\" : \"Updates to this path will be silently dropped.\"}${LINT_HINT}`);\n }\n}\n\nfunction schedule(engine: Engine): void {\n if (due.has(engine)) return;\n due.add(engine);\n setTimeout(() => check(engine), 0);\n}\n\n/** The `declared` hook: a path a binding or a `$watch` key names. */\nfunction declared(engine: Engine, p: Pattern, watch = false): void {\n note(engine, p, watch ? WATCH : BINDING);\n}\n\nfunction note(engine: Engine, p: Pattern, kind: number): void {\n // a missing top-level key already fails the binding's read (the core's error)\n if (p.path[0] === \"$\" || p.path.includes(\"#\") || (kind === BINDING && p.parent === null)) return;\n let map = named.get(engine);\n if (map === undefined) named.set(engine, (map = new Map()));\n if (!map.has(p)) map.set(p, kind);\n schedule(engine);\n}\n\nconst wrapped = new WeakSet<Engine>();\n/** A `$postUpdate` is running: what it lands is not a write (see written). */\nlet posting = false;\n\n/**\n * `$postUpdate(path)` says what at a path changed in place; a path that does not resolve updates nothing,\n * and said nothing (`rows.${r}.cell.${c}.text` for `cells` — a 7GUIs evaluation's Cells). Its pattern is\n * checked as a binding's is, the top-level key too (no read fails for it).\n */\nfunction watchPostUpdate(engine: Engine): void {\n if (wrapped.has(engine)) return;\n wrapped.add(engine);\n const api = (engine as any).api as Record<string, (path: string) => void>;\n const post = api.$postUpdate;\n api.$postUpdate = (path: string) => {\n posting = true;\n try {\n post(path);\n } finally {\n posting = false;\n }\n const p = engine.patterns.peek(parsePath(path).pattern);\n if (p !== undefined) note(engine, p, POST);\n };\n}\n\n/** The top-level keys a state declared (its own and its prototypes'), and those written since, by engine. */\nconst declaredKeys = new WeakMap<Engine, Set<string>>();\n\n/** The paths an element wrote (an output binding): what is under them is the element's to shape. */\nconst byElement = new WeakMap<Engine, Set<Pattern>>();\n\nfunction elementWrote(engine: Engine, p: Pattern, _row: unknown, _old: unknown, _value: unknown, _direct: boolean, element?: boolean): void {\n if (!element) return;\n let set = byElement.get(engine);\n if (set === undefined) byElement.set(engine, (set = new Set()));\n set.add(p);\n}\n\n/**\n * A write of a top-level key the state did not declare, beside a near one it did (`this.selectedID` and\n * `selectedId`): 4.0 creates the key, and nothing bound to the declared one changes (a 7GUIs evaluation's\n * CRUD). Warned once per key; a key with no near name is one the state adds on purpose.\n */\nfunction written(engine: Engine, p: Pattern): void {\n const keys = declaredKeys.get(engine);\n const key = p.last;\n if (p.parent !== null || posting || keys === undefined || keys.has(key) || key[0] === \"$\" || engine.dropped.has(key)) return;\n const near = didYouMean(key, [...keys]);\n keys.add(key);\n // (a volume grafts its state at its mount path, and the keys on the way to it: those keys are the page's)\n if (near !== \"\" && ![...((engine.root as ParentNode | undefined)?.querySelectorAll(`${config.tagNames.state}[mount]`) ?? [])]\n .some((e) => `${e.getAttribute(\"mount\")}.`.startsWith(`${key}.`))) {\n console.warn(`[@wcstack/state] [wcs/write-path-missing] \"${key}\" is not declared: writing it creates a new key.${near}${LINT_HINT}`);\n }\n}\n\n// ---------------------------------------------------------------- commands that reach nothing\n\n/**\n * A command token emitted while nothing subscribes to it: the call is lost, and tokens keep nothing to replay.\n * Its `command.` binding may not be attached yet — the element is defined later (an autoloader, a slow CDN),\n * or it is in an `if:` branch the same update renders (emit from `$renderedCallback`) — or there is none.\n * Warned once per token (the author's decision, docs/v4-direction-2026-10.md §5.2 — a 7GUIs evaluation's Timer\n * and Cells). The engine's `commands` is watched from its first declaration on, so the tokens of a re-set\n * are wrapped too.\n */\nfunction watchCommands(engine: Engine): void {\n if (Object.getOwnPropertyDescriptor(engine, \"commands\")?.set !== undefined) return;\n let ns = engine.commands;\n Object.defineProperty(engine, \"commands\", {\n configurable: true,\n get: () => ns,\n set: (v: Readonly<Record<string, Token>>) => {\n ns = v;\n for (const t of Object.values(v)) loud(t);\n },\n });\n}\n\nconst wrappedTokens = new WeakSet<Token>();\n\nfunction loud(t: Token): void {\n if (wrappedTokens.has(t)) return;\n wrappedTokens.add(t);\n const emit = t.emit;\n let said = false;\n (t as any).emit = (...args: unknown[]): unknown[] => {\n if (t.size === 0 && !said) {\n said = true;\n console.warn(`[@wcstack/state] [wcs/command-token-unbound] \"$command.${t.name}\" was emitted with no subscriber and is lost: its element is not defined or rendered yet (emit from $renderedCallback), or no command. binding takes it.${LINT_HINT}`);\n }\n return emit.apply(t, args);\n };\n}\n\n/** The handlers whose failure was explained, by engine. */\nconst explained = new WeakMap<Engine, Set<string>>();\n\n/**\n * The handler of a delegated `on<type>:` threw, and it reads `event.currentTarget`: that is the root there,\n * not the element (`getBoundingClientRect` is not a function, a `.value` is undefined). Said once per handler,\n * after the error (the author's decision, docs/v4-direction-2026-10.md §5.2 — a 7GUIs evaluation).\n */\nfunction handlerThrew(engine: Engine, path: string, type: string): void {\n let v: any = engine.target;\n for (const seg of path.split(\".\")) v = v == null ? undefined : findDescriptor(v, seg)?.value;\n if (typeof v !== \"function\" || !String(v).includes(\"currentTarget\")) return;\n let said = explained.get(engine);\n if (said === undefined) explained.set(engine, (said = new Set()));\n if (said.has(path)) return;\n said.add(path);\n console.warn(`[@wcstack/state] [wcs/delegated-current-target] \"${path}\" reads event.currentTarget, the root for a delegated on${type}:. Write on${type}#direct:, or use event.target.closest(…).${LINT_HINT}`);\n}\n\n// ---------------------------------------------------------------- $on handlers that use this\n\n/** The `$on` handlers already told about: a re-set state does not say it again. */\nconst toldThis = new WeakSet<(...args: any[]) => unknown>();\n/** `this.x`, `this[\"x\"]`, `const state = this` — not the word in a string (`\"this is\"`). */\nconst USES_THIS = /\\bthis\\s*[.[]|=\\s*this\\b/;\n\n/**\n * A `$on` handler that uses `this`: it is called as `handler(state, event)`, so `this` is undefined and it\n * throws when the event arrives — a TypeError with no code, which never says why (docs/seam-apps.md,\n * family-ledger). Said once per handler when the state is declared, before any event, as lint's\n * `wcs/on-handler-this` says it.\n */\nfunction onHandlersThis(target: Record<string, any>): void {\n const on = findDescriptor(target, \"$on\")?.value;\n if (on === null || typeof on !== \"object\") return;\n for (const name of Object.keys(on)) {\n const fn = on[name];\n if (typeof fn !== \"function\" || toldThis.has(fn) || !USES_THIS.test(String(fn))) continue;\n toldThis.add(fn);\n console.warn(`[@wcstack/state] [wcs/on-handler-this] The $on handler \"${name}\" uses this. A $on handler is called as ${name}(state, event): this is undefined there, so it throws when the event arrives — write ${name}(state, event) { state.x = … }.${LINT_HINT}`);\n }\n}\n\n// ---------------------------------------------------------------- two root states\n\n/** The roots already told about. */\nconst toldRoots = new WeakSet<Node>();\n\nconst describeState = (e: Element): string => {\n for (const a of [\"src\", \"state\", \"json\"]) if (e.hasAttribute(a)) return `<${e.localName} ${a}${a === \"json\" ? \"\" : `=\"${e.getAttribute(a)}\"`}>`;\n return `<${e.localName}>`;\n};\n\n/**\n * A root `<wcs-state>` binds a root that has another one: there is one state tree per root, and the one whose\n * state was ready first takes it — a `json=` state, ready at once, before the page's `src=` or inline state that\n * comes first in the document, which is then refused (#47) and the page binds against the wrong state\n * (docs/seam-apps.md, family-ledger). Said once per root, naming both.\n */\nfunction secondRoot(engine: Engine, phase: string): void {\n const el = engine.element as Element | null;\n if (phase !== \"mounting\" || !el) return;\n const root = el.getRootNode() as Node & ParentNode;\n if (toldRoots.has(root)) return;\n const others = [...root.querySelectorAll(config.tagNames.state)].filter((e) => e !== el && !e.hasAttribute(\"mount\") && !e.hasAttribute(\"bind-component\"));\n if (others.length === 0) return;\n toldRoots.add(root);\n console.warn(`[@wcstack/state] [wcs/second-root] ${others.length + 1} root <wcs-state> elements share one root, and there is one state tree per root: ${describeState(el)} takes it — its state was ready first, whatever the order in the document — and ${others.map(describeState).join(\", \")} is refused (#47). Keep one, and graft the others with <wcs-state mount=\"path\">.${LINT_HINT}`);\n}\n\n/**\n * A drain made patterns (`loose`, before its sweep): a getter may have read a path for the first time — in a\n * row added since, or down a branch of its own code. Checked as the bindings' are; a drain that read no new\n * path schedules nothing.\n */\nfunction drained(engine: Engine): void {\n if (named.has(engine) && ((engine as any).loose as Pattern[]).length > 0) schedule(engine);\n}\n\n/** A re-set: every path is checked again against the new state. */\nfunction recheck(engine: Engine): void {\n checked.delete(engine);\n if (named.has(engine)) schedule(engine);\n}\n\n// ---------------------------------------------------------------- recursion's static checks\n\n/**\n * `$recursion` families that can never work (approved simplification: these checks moved out of\n * the core): a suffix naming the recursion structure itself, two families one of which is the\n * other a few repeats deeper, and a concrete key that one of the families expands to.\n */\nfunction checkRecursion(target: Record<string, any>): void {\n const decl = target.$recursion;\n if (decl === null || typeof decl !== \"object\") return;\n const entries = Object.entries(decl);\n if (entries.length !== 1 || typeof entries[0][1] !== \"string\") return;\n const [anchor, repeat] = entries[0] as [string, string];\n if (!anchor.endsWith(\".*\") || !repeat.endsWith(\".*\")) return;\n const list = anchor.slice(0, -2);\n const key = repeat.slice(0, -2);\n const step = `.${repeat}`;\n const head = `${list}.**`;\n const keys = keysOf(target);\n const families = keys.filter((k) => k.startsWith(head)).map((k) => k.slice(head.length));\n const bad = (why: string): never => raiseError(`[wcs/recursion-declaration-invalid] ${why}`);\n for (const s of families) {\n if (s === `.${key}` || s.startsWith(`.${key}.`)) {\n bad(`\"${head}${s}\" names the recursion structure itself (the \"${key}\" lists): recursive getters compute values over the nodes.`);\n }\n for (const t of families) {\n if (t.length > s.length && t.endsWith(s) && new RegExp(`^(?:${esc(step)})+$`).test(t.slice(0, t.length - s.length))) {\n bad(`\"${head}${s}\" and \"${head}${t}\" expand to the same concrete path at different depths (they differ by whole repetitions of \"${repeat}\"). Rename one of them.`);\n }\n }\n const re = new RegExp(`^${esc(anchor)}(?:${esc(step)})*${esc(s)}$`);\n for (const k of keys) {\n if (!k.includes(\"**\") && re.test(k)) bad(`\"${k}\" is already defined on the state, so the recursive getter \"${head}${s}\" cannot expand to it.`);\n }\n }\n}\n\nconst esc = (s: string): string => s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\nlet trustedTypesReported = false;\n\n/**\n * An HTML sink write Trusted Types blocked: the browser's message names no fix, so say once\n * per page what to install (the same report as @wcstack/state 3.3).\n */\nfunction failed(_engine: Engine, error: unknown, binding: Binding): void {\n const prop = binding.name === \"html\" ? \"innerHTML\" : binding.name;\n if (trustedTypesReported || !(error instanceof TypeError) || !isHtmlSink(prop) || !(\"trustedTypes\" in globalThis)) return;\n trustedTypesReported = true;\n const cause = typeof getTrustedTypesPolicy()?.createHTML === \"function\"\n ? \"The injected policy's createHTML() did not return a TrustedHTML.\"\n : \"No sanitizing policy is installed, and @wcstack/state deliberately does not pass state values through an identity policy — that would defeat the CSP.\";\n console.error(\n `[@wcstack/state] Writing to \"${prop}\" was blocked by Trusted Types (require-trusted-types-for 'script'). ${cause}\\n`\n + `Install a sanitizing policy before the first binding is applied:\\n`\n + ` globalThis[Symbol.for(\"wcstack.trustedTypes.policy\")] =\\n`\n + ` trustedTypes.createPolicy(\"my-app\", { createHTML: (s) => DOMPurify.sanitize(s) });\\n`\n + `Or bind the value as text instead of HTML. See docs/csp.md section 7.`,\n { element: binding.node, property: prop },\n );\n}\n\n// ---------------------------------------------------------------- the default getter\n\nconst warnedDetail = new WeakMap<Element, Set<string>>();\n\n/**\n * A wc-bindable property's event read with the default getter (`e.detail`): warns once per\n * element and property about the two shapes that cannot be what the element meant (README\n * \"What the element writes back\", as @wcstack/state 3.3). The write is applied as it is.\n * (a) no detail while the element's property has a value — a plain Event, or a forgotten detail;\n * (b) a detail object with a `<name>` key while the property is not an object — a wrapper.\n */\nfunction detail(el: Element, name: string, v: unknown): void {\n const prop = (el as any)[name];\n const reason = v === undefined\n ? prop === undefined ? null : `the event carried no detail (undefined) while element.${name} is ${typeof prop}`\n : v !== null && typeof v === \"object\" && Object.prototype.hasOwnProperty.call(v, name) && (prop === null || typeof prop !== \"object\")\n ? `the event's detail is an object with a \"${name}\" key while element.${name} is ${typeof prop}`\n : null;\n if (reason === null) return;\n let said = warnedDetail.get(el);\n if (said === undefined) warnedDetail.set(el, (said = new Set()));\n if (said.has(name)) return;\n said.add(name);\n console.warn(\n `[@wcstack/state] [wcs/default-getter-mismatch] <${el.localName}> \"${name}\": ${reason}. `\n + \"With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare \"\n + `getter (e.g. (e) => e.detail.${name}, or (e) => e.target.${name}) on that wcBindable property.`,\n );\n}\n\n// ---------------------------------------------------------------- 3.x names 4.0 removed\n\n/**\n * Declarations 3.2 renamed, whose old names 4.0 removed: a declaration under one would do nothing.\n * (The core detected these and the two APIs below up to 4.0.0-rc.3; without this add-on they are\n * ignored like any other unknown `$` key.)\n */\nconst REMOVED_DECLARATIONS: [string, string][] = [[\"$streams\", \"$stream\"], [\"$updatedCallback\", \"$renderedCallback\"]];\n/** APIs 3.2 renamed, whose old names 4.0 removed: reading one fails with the name to write. */\nconst REMOVED_APIS: Readonly<Record<string, string>> = { \"$trackDependency\": \"$dependOn\", \"$untrackDependency\": \"$untracked\" };\n\n/** A state that declares a 3.x name 4.0 removed (`$scan` has no successor: $watch or $on). */\nfunction removedDeclarations(target: Record<string, any>): void {\n if (target.$scan !== undefined) raise(M.ScanRemoved);\n for (const [old, name] of REMOVED_DECLARATIONS) if (target[old] !== undefined) raise(M.DeclarationRemoved, [old, name]);\n}\n\nexport const diagnostics: Feature = {\n name: \"diagnostics\",\n hooks,\n install(): void {\n hooks.explain = explain;\n hooks.render = render;\n hooks.declared = declared;\n hooks.detail = detail;\n hooks.failed = chain(hooks.failed, failed);\n // the removed names first, before what is installed (the core checked them before it took the\n // state in): a refused state never reaches the other add-ons' runtimes\n const prev = hooks.declare;\n hooks.declare = (engine, target) => {\n removedDeclarations(target);\n prev?.(engine, target);\n checkRecursion(target);\n onHandlersThis(target);\n recheck(engine);\n watchPostUpdate(engine);\n watchCommands(engine);\n declaredKeys.set(engine, new Set(keysOf(target)));\n };\n hooks.handlerThrew = handlerThrew;\n hooks.element = chain(hooks.element, secondRoot);\n hooks.written = chain(chain(hooks.written, written), elementWrote);\n hooks.drained = chain(hooks.drained, drained);\n hooks.dollar = first(known, hooks.dollar, (_engine, key) => (Object.hasOwn(REMOVED_APIS, key) ? raise(M.ApiRemoved, [key, REMOVED_APIS[key]]) : undefined));\n },\n};\nexport default diagnostics;\n","/**\n * `$watch` — the headless subscription (README \"Watch\", docs/state-watch-hook-design.md).\n *\n * A handler fires at the end of a drain, once per location that landed in it: a write of its\n * path or of an object above it in the same row, a change that reached its getter, a row that\n * entered its list. `cur` is the value at the drain; `prev` the value before the batch's first\n * write when a primitive was written (for a getter: its previous evaluation). A change that reaches\n * a getter fires it, whether its value changed or not (3.x D4: a watch has no condition of its own).\n * A row's getter that no write of the batch changed — it read none of the written paths, directly or\n * through a getter it read — fires only if its value changed: a row a list kept when a write\n * re-synced or re-sorted the list (`items = [...items, x]`) is reached again through what it read\n * under the row, which did not change (#389). A write at the list (or above it) changes what a row\n * read there (`this.items.length`), not under its row.\n * Declaration order between handlers, ascending indexes between rows of one path.\n *\n * A handler's writes form the next batch. Each write carries a chain depth (as @wcstack/state\n * 3.4, #354): 0, or one more than the depth of what fired the handler making it — or restarted the\n * `$stream` making it (stream.ts: its run's values and end too, within the task the run started in).\n * For a data path that is the deepest write landing there in the batch; for a getter, the first write\n * since it was last evaluated (a reached getter is not reached again until it is read), and 0 when a\n * list re-synced in the drain reached it — loops through those are left to the render chain\n * (MAX_RENDER_CHAIN). A handler fired more than MAX_CHAIN deep does not\n * run (as 3.x: 33 links run): the chain is cut and reported once. Writes riding in the same batch (a\n * render's write-back) neither lengthen nor reset it.\n *\n * Differences from @wcstack/state 3.3 that rows make possible: a row watch needs neither a\n * `for` binding nor `$listKeys` (the watch keeps its lists synced itself), wildcard getters are\n * eager too, and a whole-array assignment fires only for the rows that entered the list (a row\n * kept by identity did not change).\n */\nimport type { Engine } from \"../engine\";\nimport type { Pattern } from \"../pattern\";\nimport type { StateList, StateRow } from \"../list\";\nimport { raiseError, report } from \"../parser/raiseError\";\nimport { hooks } from \"../hooks\";\n\ntype Handler = (this: unknown, cur: unknown, prev: unknown, ...indexes: number[]) => unknown;\n\ninterface Watch {\n readonly path: string;\n readonly p: Pattern;\n readonly handler: Handler;\n /** A getter (or under one): kept evaluated, `prev` is its previous evaluation. */\n getter: boolean;\n /** Previous evaluation by row (getter watches; the root's under ROOT): a removed row takes its entry with it. */\n last: WeakMap<object, unknown>;\n}\n\n/**\n * A landing of a batch: `prev` (the first write's), the deepest write's chain depth, and whether a\n * write landed there (not only a change that reached a getter).\n */\ntype Hit = [prev: unknown, depth: number, landed: boolean];\n\nexport const MAX_CHAIN = 32;\nconst ROOT = {};\n/**\n * An explicit index (`items.0.v`, read like a getter): a write to another row, a list change,\n * reaches it unchanged. A leading numeric segment is a root key (`2024.total`), not an index.\n */\nconst INDEX_PATH = /\\.\\d/;\nconst PROTOTYPE_NAMES = new Set(Object.getOwnPropertyNames(Object.prototype));\n\n/**\n * The current task's number, bumped in the next task after it is asked for: a MessageChannel message\n * (neither throttled in a background tab nor replaced by a faked timer), or a timer where there is none.\n */\nlet taskSeq = 0;\nlet pinged = false;\nlet ping: (() => void) | null = null;\nconst nextTask = (): void => {\n pinged = false;\n taskSeq++;\n};\nexport function thisTask(): number {\n if (ping === null) {\n if (typeof MessageChannel === \"function\") {\n const ch = new MessageChannel();\n ch.port1.onmessage = nextTask;\n // (Node: the port must not keep the process alive)\n (ch.port1 as { unref?: () => void }).unref?.();\n ping = () => ch.port2.postMessage(0);\n } else ping = () => setTimeout(nextTask, 0);\n }\n if (!pinged) {\n pinged = true;\n ping();\n }\n return taskSeq;\n}\n\n/** Whether a write at a path of `changed` changed what getter `g` read (directly, or through a getter it read). */\nfunction reads(g: Pattern, changed: Set<Pattern>): boolean {\n const seen = new Set<Pattern>();\n const stack = [g];\n while (stack.length > 0) {\n const h = stack.pop()!;\n if (seen.has(h)) continue;\n seen.add(h);\n for (const s of h.sources) {\n for (const p of changed) {\n // a write at the list a row is in (or above it) changes what was read there, not under the row\n if (s.isUnder(p) && (s.depth === p.depth || !(p.depth < h.depth && h.lists[p.depth + 1]!.isUnder(p)))) return true;\n }\n if (s.getter !== null) stack.push(s);\n }\n }\n return false;\n}\n\nexport function parseWatches(engine: Engine, decl: unknown): Watch[] {\n if (decl === undefined) return [];\n if (decl === null || typeof decl !== \"object\") raiseError(\"$watch must be an object mapping paths to handler functions.\");\n const out: Watch[] = [];\n for (const path of Object.keys(decl)) {\n const handler = (decl as Record<string, unknown>)[path];\n if (path === \"\" || path[0] === \"$\" || path.includes(\"@\") || PROTOTYPE_NAMES.has(path)) raiseError(`$watch path \"${path}\" is not a path of the state tree.`);\n if (typeof handler !== \"function\") raiseError(`$watch entry \"${path}\" must be a function.`);\n const p = engine.pattern(path);\n hooks.declared?.(engine, p, true);\n out.push({ path, p, handler: handler as Handler, getter: false, last: new WeakMap() });\n }\n return out;\n}\n\nexport class WatchRuntime {\n readonly engine: Engine;\n readonly watches: Watch[];\n active = false;\n /** Landings of the current batch: watch → row → hit. */\n private hits = new Map<Watch, Map<StateRow | null, Hit>>();\n /**\n * What elements wrote before the watches were active — the value an element already had when its\n * binding attached (an open `<wcs-sse>`, the router's first params, a `<wcs-storage>`'s saved value):\n * [path, row, the value before, the value the element wrote]. Whether that value is there before or\n * after the bindings attach depends on how fast the page loaded, so activate() fires, once, the\n * watches of the paths that still hold it, and the root getters that read them (`prev`: the value\n * before, none for a getter) — docs/seam-apps.md: state-collab-board, router-admin, router-auth.\n * A write from code before then (`$connectedCallback`) fires nothing, as before.\n */\n private early: [Pattern, StateRow | null, unknown, unknown][] = [];\n /** The chain depth of a write made now: 0, or one more than what fired the running handler (or restart). */\n depth = 0;\n /**\n * The paths a cut reported in task `cutTask`. A chain carries its depth only synchronously (and\n * through a `$stream`'s values within the task its run started in): a cut of the same paths later\n * in the task is the same chain's — what it left running reaching the limit again.\n */\n private cutTask = -1;\n private reported = new Set<string>();\n /** The paths written in the batch (what a change reaching a getter may have come from). */\n private changed: Set<Pattern> | null = null;\n\n constructor(engine: Engine, watches: Watch[]) {\n this.engine = engine;\n this.watches = watches;\n }\n\n /** After `$connectedCallback` (and on reconnect): watches see the writes from now on. */\n activate(): void {\n const engine = this.engine;\n this.hits.clear();\n const early = this.early;\n this.early = [];\n for (const w of this.watches) {\n w.getter = w.p.getter !== null || w.p.underGetter;\n w.last = new WeakMap();\n // (the list a row watch reads can be a getter that throws too)\n this.prime(w, () => {\n if (w.p.depth === 0) {\n if (w.getter) w.last.set(ROOT, engine.readUntracked(w.p, null));\n } else {\n // a row watch keeps its lists synced, rendered or not; a getter watch is eager per row\n this.eachRow(w.p, 1, null, (row) => {\n if (w.getter) this.prime(w, () => w.last.set(row, engine.readUntracked(w.p, row)));\n });\n }\n });\n }\n this.active = true;\n // what elements brought before now, still there: fired once, as the writes of a batch\n const held = new Set<Pattern>();\n for (const [p, row, before, value] of early) {\n if ((row === null || row.alive) && Object.is(engine.readUntracked(p, row), value)) {\n held.add(p);\n for (const w of this.watches) if (w.p === p) this.hit(w, row, before, true);\n }\n }\n // (a root getter's sources are known now: priming evaluated it)\n for (const w of this.watches) if (w.getter && w.p.depth === 0 && !this.hits.has(w) && reads(getterOf(w.p), held)) this.hit(w, null, undefined, true);\n if (this.hits.size > 0) engine.schedule();\n }\n\n /** What a watch reads before the writes (its `prev`): what throws is reported, the others go on. */\n private prime(w: Watch, read: () => void): void {\n try {\n read();\n } catch (error) {\n report(error, `[@wcstack/state] $watch initial evaluation of \"${w.path}\" threw.`);\n hooks.noticed?.(this.engine, { \"type\": \"state:watch-error\", \"phase\": \"prime\", \"path\": w.path, \"error\": error });\n }\n }\n\n deactivate(): void {\n this.active = false;\n this.hits.clear();\n this.early = [];\n }\n\n /** Calls fn for every row at p.depth, creating the lists on the way (they then stay synced). */\n private eachRow(p: Pattern, k: number, parent: StateRow | null, fn: (row: StateRow) => void): void {\n const engine = this.engine;\n const list = engine.childList(parent, p.lists[k]!);\n for (const row of list.rows) {\n if (k === p.depth) fn(row);\n else this.eachRow(p, k + 1, row, fn);\n }\n }\n\n /** Records a landing at the current depth: the first `prev` stays, the deepest write's depth wins. */\n private hit(w: Watch, row: StateRow | null, prev: unknown, landed: boolean): void {\n let rows = this.hits.get(w);\n if (rows === undefined) this.hits.set(w, (rows = new Map()));\n const h = rows.get(row);\n if (h === undefined) rows.set(row, [prev, this.depth, landed]);\n else {\n if (h[1] < this.depth) h[1] = this.depth;\n h[2] ||= landed;\n }\n }\n\n written(p: Pattern, row: StateRow | null, old: unknown, value: unknown, direct: boolean, element?: boolean): void {\n if (!this.active) {\n // an element's write before the watches are active (see `early`)\n if (element) this.early.push([p, row, old, value]);\n return;\n }\n (this.changed ??= new Set()).add(p);\n for (const w of this.watches) {\n const wp = w.p;\n // the watched path, or an object above it in the same row (a getter's row replaced included)\n if (wp.depth !== p.depth || !wp.isUnder(p)) continue;\n // `prev`: a getter's previous evaluation; for data, the old value the same-value guard reads\n // when a primitive was written there (none when it is off, or above it)\n this.hit(w, row, w.getter ? w.last.get(row ?? ROOT) : wp === p && direct && this.engine.guard && (value === null || (typeof value !== \"object\" && typeof value !== \"function\")) ? old : undefined, true);\n }\n }\n\n getterReached(g: Pattern, row: StateRow | null): void {\n if (!this.active) return;\n // a getter, or a path under it in the same row — also one that became so after the activation\n // (a mounted component's exported getter, a volume's accessor grafted later)\n for (const w of this.watches) {\n if ((w.getter ||= w.p.getter !== null || w.p.underGetter) && w.p.depth === g.depth && w.p.isUnder(g)) this.hit(w, row, w.last.get(row ?? ROOT), false);\n }\n }\n\n /** Rows that entered a list a row watch ranges over fire (and nested lists under them sync). */\n listSynced(list: StateList, old: StateRow[]): void {\n if (!this.active) return;\n let before: Set<StateRow> | null = null;\n for (const w of this.watches) {\n const wp = w.p;\n if (wp.depth < list.depth || wp.lists[list.depth] !== list.pattern) continue;\n before ??= new Set(old);\n for (const row of list.rows) {\n if (before.has(row)) continue;\n if (wp.depth === list.depth) this.hit(w, row, undefined, true);\n else this.eachRow(wp, list.depth + 1, row, (r) => this.hit(w, r, undefined, true));\n }\n }\n }\n\n drained(): void {\n const changed = this.changed;\n this.changed = null;\n if (!this.active || this.hits.size === 0) return;\n const batch = this.hits;\n this.hits = new Map();\n const engine = this.engine;\n const cut: string[] = [];\n for (const w of this.watches) {\n const rows = batch.get(w);\n if (rows === undefined) continue;\n const entries = [...rows].filter(([row]) => row === null || row.alive);\n if (entries.length > 1) entries.sort((a, b) => compareRows(a[0]!, b[0]!));\n // (whether a write of the batch changed what the watched getter read: asked once, for an unchanged row)\n let real: boolean | undefined;\n for (const [row, [prev, depth, landed]] of entries) {\n let cur: unknown;\n // (DevTools: the handler fired, or what threw — the value's evaluation or the handler)\n let phase = \"evaluate\";\n const saved = engine.ctx;\n this.depth = depth + 1;\n engine.feeding++;\n try {\n // (read past the limit too: a getter's cache is then current, and its next change reaches it)\n cur = engine.readUntracked(w.p, row);\n if (w.getter) {\n w.last.set(row ?? ROOT, cur);\n // unchanged: an explicit index, or a row no write of the batch changed (a row a list kept, #389)\n if (Object.is(cur, prev) && (INDEX_PATH.test(w.path) || (row !== null && !landed && !(real ??= changed !== null && reads(getterOf(w.p), changed))))) continue;\n }\n // fired more than MAX_CHAIN deep: the chain stops here (the batch's other handlers run)\n if (depth > MAX_CHAIN) {\n if (!cut.includes(w.path)) cut.push(w.path);\n continue;\n }\n engine.ctx = row;\n hooks.noticed?.(engine, { \"type\": \"state:watch-fired\", \"path\": w.path });\n phase = \"handler\";\n w.handler.call(engine.proxy, cur, prev, ...engine.indexesOf(row));\n } catch (error) {\n report(error, `[@wcstack/state] $watch \"${w.path}\" failed; the other watches still run.`);\n hooks.noticed?.(engine, { \"type\": \"state:watch-error\", \"phase\": phase, \"path\": w.path, \"error\": error });\n } finally {\n engine.ctx = saved;\n this.depth = 0;\n engine.feeding--;\n }\n }\n }\n if (cut.length > 0) this.chainCut(cut);\n }\n\n /** A chain of handlers / stream restarts went past MAX_CHAIN: reported once a task for its paths (nothing is rolled back). */\n chainCut(paths: string[]): void {\n const task = thisTask();\n if (task !== this.cutTask) {\n this.cutTask = task;\n this.reported.clear();\n }\n const fresh = paths.filter((path) => !this.reported.has(path));\n if (fresh.length === 0) return;\n for (const path of fresh) this.reported.add(path);\n report(`[@wcstack/state] $watch handlers / $stream restarts kept writing for ${MAX_CHAIN} batches; the chain is cut (nothing is rolled back).`);\n hooks.noticed?.(this.engine, { \"type\": \"state:watch-chain-limit\", \"maxDepth\": MAX_CHAIN, \"paths\": fresh });\n }\n}\n\n/** The getter a watched path is, or lies under (in the same row). */\nfunction getterOf(p: Pattern): Pattern {\n while (p.getter === null && p.parent !== null) p = p.parent;\n return p;\n}\n\n/** Ascending indexes, outermost first. */\nfunction compareRows(a: StateRow, b: StateRow): number {\n const ia: number[] = [];\n const ib: number[] = [];\n for (let r: StateRow | null = a; r !== null; r = r.list.parentRow) ia.unshift(r.index);\n for (let r: StateRow | null = b; r !== null; r = r.list.parentRow) ib.unshift(r.index);\n for (let i = 0; i < ia.length && i < ib.length; i++) if (ia[i] !== ib[i]) return ia[i] - ib[i];\n return ia.length - ib.length;\n}\n","/**\n * `$stream` — an async producer folded into one reactive property (README \"Streams\",\n * packages/state/docs/streams.md).\n *\n * `args` runs as a getter of its own (a pattern with no path in the state), so the paths it reads\n * are tracked like any getter's; a change that reaches it restarts the stream at the end of the\n * drain, once (switchMap: abort, reset to `initial`, re-run `args`, call `source`). Its\n * dependencies are captured afresh on every run. `$streamStatus.<name>` / `$streamError.<name>` are\n * read-only companions kept on the state.\n *\n * A restart's writes are reactions: they continue the render chain (MAX_RENDER_CHAIN), and the\n * `$watch` chain (watch.ts) one deeper than the write that reached `args` (#354). That depth is the\n * deepest such write's for a data path `args` reads, but the first one's since `args` was last\n * evaluated when the change came through a getter (a reached getter is not reached again until it\n * is read), and 0 when a list re-synced in the drain reached it: such loops are left to the render\n * chain. A restart more than MAX_CHAIN deep is not made (the chain is cut and reported); the next\n * change of its inputs restarts it.\n *\n * A run's own writes after its start — a value its source yields, the status `done` / `error` — made\n * within the task the run started in (synchronously or in its microtasks) are as deep as the run: the\n * `$watch` handlers they fire and the restarts they cause continue its chain, so a loop through a\n * source that yields at once (a `$watch` on the value moving what `args` reads, two streams reading\n * each other's values) is cut instead of running on microtasks alone. From a later task (a network\n * response, a message, a timer) they are new input, as a write from code: they start a chain afresh.\n */\nimport type { Engine } from \"../engine\";\nimport { FAILED, UNSET, type Pattern } from \"../pattern\";\nimport { raiseError } from \"../parser/raiseError\";\nimport { MAX_CHAIN, thisTask, type WatchRuntime } from \"./watch\";\n\ntype Status = \"idle\" | \"active\" | \"done\" | \"error\";\n\ninterface Entry {\n readonly name: string;\n readonly source: (args: unknown, signal: AbortSignal) => unknown;\n readonly fold: ((acc: unknown, chunk: unknown) => unknown) | undefined;\n readonly initial: unknown;\n /** The `args` getter (null without args: start once). */\n readonly g: Pattern | null;\n readonly args: (() => unknown) | null;\n controller: AbortController | null;\n restart: boolean;\n /** The `$watch` chain depth of what asked for the restart (meaningful while `restart`). */\n depth: number;\n}\n\nconst STATUS = \"$streamStatus\";\nconst ERROR = \"$streamError\";\nconst PROTOTYPE_NAMES = new Set(Object.getOwnPropertyNames(Object.prototype));\n\n/** A read-only companion path is being written by the runtime itself. */\nexport let internalWrite = false;\n\nfunction hasAccessorOrMethod(target: object, name: string): boolean {\n for (let o: object | null = target; o !== null && o !== Object.prototype; o = Object.getPrototypeOf(o)) {\n const d = Object.getOwnPropertyDescriptor(o, name);\n if (d !== undefined) return d.get !== undefined || d.set !== undefined || typeof d.value === \"function\";\n }\n return false;\n}\n\n/** Validates `$stream` and materializes the value property and the companions on `target`. */\nexport function parseStreams(engine: Engine, target: Record<string, any>): Entry[] {\n const decl = target.$stream;\n if (decl === undefined) return [];\n if (decl === null || typeof decl !== \"object\") raiseError(\"$stream must be an object mapping stream names to definitions.\");\n const entries: Entry[] = [];\n const status: Record<string, Status> = {};\n const errors: Record<string, unknown> = {};\n for (const name of Object.keys(decl)) {\n // the author's object: read by quoted keys (the build shortens internal property names)\n const def = decl[name];\n if (name === \"\" || name[0] === \"$\" || /[.*]/.test(name) || PROTOTYPE_NAMES.has(name)) raiseError(`$stream entry \"${name}\" must be a flat property name.`);\n if (def === null || typeof def !== \"object\") raiseError(`$stream entry \"${name}\" must be an object.`);\n const source = def[\"source\"];\n const fold = def[\"fold\"];\n const args = def[\"args\"];\n const initial = def[\"initial\"];\n if (typeof source !== \"function\") raiseError(`$stream entry \"${name}\" needs a source function.`);\n if (fold !== undefined && typeof fold !== \"function\") raiseError(`$stream entry \"${name}\": fold must be a function.`);\n if (fold !== undefined && !(\"initial\" in def)) raiseError(`$stream entry \"${name}\": fold needs an initial value.`);\n if (args !== undefined && typeof args !== \"function\") raiseError(`$stream entry \"${name}\": args must be a function.`);\n if (hasAccessorOrMethod(target, name)) raiseError(`$stream entry \"${name}\" collides with a getter, setter or method of the state.`);\n if (target[name] === undefined) target[name] = initial;\n status[name] = \"idle\";\n errors[name] = null;\n entries.push({\n name, source, fold, initial, controller: null, restart: false, depth: 0,\n g: args === undefined ? null : engine.pattern(`$streamArgs.${name}`),\n args: args === undefined ? null : function (this: unknown) { return args(this); },\n });\n }\n target[STATUS] = status;\n target[ERROR] = errors;\n return entries;\n}\n\nexport class StreamRuntime {\n readonly engine: Engine;\n readonly entries: Entry[];\n /** The engine's `$watch` runtime: it holds the depth of the write made now, and reports a cut. */\n readonly watch: WatchRuntime;\n\n constructor(engine: Engine, entries: Entry[], watch: WatchRuntime) {\n this.engine = engine;\n this.entries = entries;\n this.watch = watch;\n }\n\n private set(ns: string, name: string, value: unknown): void {\n internalWrite = true;\n try {\n this.engine.write(this.engine.pattern(`${ns}.${name}`), null, value);\n } finally {\n internalWrite = false;\n }\n }\n\n /** Eager start after `$connectedCallback`: an `args` failure is thrown as is. */\n startAll(): void {\n for (const e of this.entries) this.start(e, true);\n }\n\n /** A re-set replaced the state: the old runs stop without touching the new state. */\n abortAll(): void {\n for (const e of this.entries) {\n e.restart = false;\n e.controller?.abort();\n e.controller = null;\n }\n }\n\n stopAll(): void {\n for (const e of this.entries) {\n e.restart = false;\n if (e.controller !== null) {\n e.controller.abort();\n e.controller = null;\n }\n this.set(STATUS, e.name, \"idle\");\n }\n }\n\n getterReached(g: Pattern): void {\n const depth = this.watch.depth;\n for (const e of this.entries) {\n if (e.g !== g) continue;\n // (a restart a stop or a re-set dropped leaves its depth behind)\n e.depth = e.restart ? Math.max(e.depth, depth) : depth;\n e.restart = true;\n }\n }\n\n /** At the end of a drain (after the watches): each stream whose `args` inputs changed restarts once. */\n drained(): void {\n const engine = this.engine;\n const watch = this.watch;\n const cut: string[] = [];\n for (const e of this.entries) {\n if (!e.restart) continue;\n const depth = e.depth;\n e.restart = false;\n if (depth > MAX_CHAIN) {\n cut.push(e.name);\n // reached, not re-run: the next change of its inputs must reach it again\n e.g!.rootValue = FAILED;\n continue;\n }\n watch.depth = depth + 1;\n engine.feeding++;\n try {\n this.start(e, false);\n } finally {\n engine.feeding--;\n watch.depth = 0;\n }\n }\n if (cut.length > 0) watch.chainCut(cut);\n }\n\n private start(e: Entry, eager: boolean): void {\n const engine = this.engine;\n if (e.controller !== null) e.controller.abort();\n e.controller = null;\n let args: unknown;\n if (e.g !== null) {\n const g = e.g;\n // (re)attached on every start: a re-set forgets every accessor of the old state\n g.getter = e.args;\n const kept = g.sources.slice();\n untrack(g);\n try {\n args = engine.read(g, null);\n checkArgs(e.name, g, args);\n } catch (error) {\n // the dependencies of the last successful run stay: touching one retries\n untrack(g);\n for (const s of kept) s.addDependent(g);\n g.rootValue = FAILED;\n if (eager) throw error;\n this.set(ERROR, e.name, error);\n this.set(STATUS, e.name, \"error\");\n return;\n }\n }\n const ctrl = new AbortController();\n e.controller = ctrl;\n engine.write(engine.pattern(e.name), null, e.initial);\n this.set(ERROR, e.name, null);\n this.set(STATUS, e.name, \"active\");\n void this.consume(e, ctrl, args);\n }\n\n private async consume(e: Entry, ctrl: AbortController, args: unknown): Promise<void> {\n const engine = this.engine;\n const signal = ctrl.signal;\n const live = (): boolean => !signal.aborted && e.controller === ctrl;\n const p = engine.pattern(e.name);\n // the run's depth and task: what it writes in that task continues its chain\n const depth = this.watch.depth;\n const task = thisTask();\n const put = (fn: () => void): void => {\n if (thisTask() === task) this.watch.depth = depth;\n try {\n fn();\n } finally {\n this.watch.depth = 0;\n }\n };\n let acc = e.initial;\n try {\n const producer: any = await e.source(args, signal);\n if (!live()) return;\n const chunk = (v: unknown): void => {\n acc = e.fold !== undefined ? e.fold(acc, v) : v;\n put(() => engine.write(p, null, acc));\n };\n if (producer !== null && typeof producer?.getReader === \"function\") {\n // a ReadableStream: only reader.cancel() can unwind a parked read\n const reader = producer.getReader();\n signal.addEventListener(\"abort\", () => { reader.cancel().catch(() => {}); });\n for (;;) {\n const r = await reader.read();\n if (!live()) return;\n if (r.done) break;\n chunk(r.value);\n }\n } else if (producer !== null && typeof producer?.[Symbol.asyncIterator] === \"function\") {\n const it = producer[Symbol.asyncIterator]();\n signal.addEventListener(\"abort\", () => { void it.return?.(); });\n for (;;) {\n const r = await it.next();\n if (!live()) return;\n if (r.done) break;\n chunk(r.value);\n }\n } else {\n throw new TypeError(`$stream \"${e.name}\": source must return an async iterable or a ReadableStream`);\n }\n if (!live()) return;\n e.controller = null;\n put(() => this.set(STATUS, e.name, \"done\"));\n } catch (error) {\n if (!live()) return;\n e.controller = null;\n ctrl.abort();\n put(() => {\n this.set(ERROR, e.name, error);\n this.set(STATUS, e.name, \"error\");\n });\n }\n }\n}\n\n/** Forgets what a getter read (its dependencies are captured again by the next evaluation). */\nfunction untrack(g: Pattern): void {\n for (const s of g.sources) {\n const i = s.dependents.indexOf(g);\n if (i >= 0) s.dependents.splice(i, 1);\n (s as any).dependentSet.delete(g);\n }\n g.sources.length = 0;\n g.rootValue = UNSET;\n}\n\nfunction checkArgs(name: string, g: Pattern, args: unknown): void {\n if (args !== null && typeof (args as any)?.then === \"function\") raiseError(`$stream \"${name}\": args must be synchronous (it returned a Promise).`);\n for (const s of g.sources) {\n if (s.depth > 0) raiseError(`$stream \"${name}\": args must not read a wildcard path (\"${s.path}\").`);\n if (s.path === name || s.path === `${STATUS}.${name}` || s.path === `${ERROR}.${name}`) raiseError(`$stream \"${name}\": args must not read the stream itself (\"${s.path}\").`);\n }\n}\n","/**\n * The temporal add-on (@wcstack/state/features/temporal): `$watch` and `$stream`.\n * At the end of every drain, after its report (`$renderedCallback`): the watches, then the\n * stream restarts. Both start after `$connectedCallback` and stop on disconnect.\n */\nimport type { Engine } from \"../engine\";\nimport { chain, first, handled, hooks, known, type Feature } from \"../hooks\";\nimport { raiseError } from \"../parser/raiseError\";\nimport { parseWatches, WatchRuntime } from \"../temporal/watch\";\nimport { internalWrite, parseStreams, StreamRuntime } from \"../temporal/stream\";\n\ninterface Runtime {\n watch: WatchRuntime;\n stream: StreamRuntime;\n connected: boolean;\n /** The state it was made for: a re-set refused after it (list-keys, recursion) leaves the old one in place. */\n target: object;\n}\n\nconst runtimes = new WeakMap<Engine, Runtime>();\n/** The engine's runtime when it is its state's (not one a refused re-set left: that one never runs). */\nfunction live(engine: Engine): Runtime | undefined {\n const rt = runtimes.get(engine);\n return rt?.target === engine.target ? rt : undefined;\n}\n\nfunction declare(engine: Engine, target: Record<string, any>): void {\n const watch = new WatchRuntime(engine, parseWatches(engine, target.$watch));\n const stream = new StreamRuntime(engine, parseStreams(engine, target), watch);\n const old = runtimes.get(engine);\n if (old !== undefined) {\n old.watch.deactivate();\n old.stream.abortAll();\n }\n runtimes.set(engine, { watch, stream, connected: old?.connected ?? false, target });\n}\n\nfunction element(engine: Engine, phase: \"mounting\" | \"back\" | \"connected\" | \"disconnected\" | \"reset\"): void {\n const rt = runtimes.get(engine);\n // an engine made before the add-on was installed has no runtime (and declares nothing temporal);\n // a server render (@wcstack/server) keeps streams at their initial value and watches off\n if (rt === undefined || phase === \"mounting\" || document.documentElement?.hasAttribute(\"data-wcs-server\")) return;\n // (kept on a runtime a refused re-set left too: the next re-set takes it over. \"back\" comes after\n // \"disconnected\", before $connectedCallback runs again: not connected yet)\n if (phase !== \"reset\") rt.connected = phase === \"connected\";\n // a refused state's runtime never runs, nor stops (writes `$streamStatus`), on the state that stayed\n if (rt.target !== engine.target) return;\n if (phase === \"disconnected\") {\n rt.watch.deactivate();\n rt.stream.stopAll();\n return;\n }\n if (!rt.connected) return;\n rt.watch.activate();\n rt.stream.startAll();\n}\n\nconst NAMESPACES = [\"$streamStatus\", \"$streamError\"];\n\nexport const temporal: Feature = {\n name: \"temporal\",\n hooks,\n install(): void {\n hooks.declare = chain(hooks.declare, declare);\n hooks.element = chain(hooks.element, element);\n hooks.written = chain(hooks.written, (engine, p, row, old, value, direct, element) => live(engine)?.watch.written(p, row, old, value, direct, element));\n hooks.getterReached = chain(hooks.getterReached, (engine, g, row) => {\n const rt = live(engine);\n if (rt === undefined) return;\n rt.watch.getterReached(g, row);\n rt.stream.getterReached(g);\n });\n hooks.listSynced = chain(hooks.listSynced, (engine, list, old) => live(engine)?.watch.listSynced(list, old));\n hooks.drained = chain(hooks.drained, (engine) => {\n const rt = live(engine);\n if (rt === undefined) return;\n rt.watch.drained();\n rt.stream.drained();\n });\n // `this.$streamStatus` (the object, untracked) and `this[\"$streamStatus.x\"]` (tracked)\n hooks.dollar = first(known, hooks.dollar, (engine, key) => {\n const ns = key.split(\".\", 1)[0];\n if (!NAMESPACES.includes(ns)) return undefined;\n return ns === key ? engine.target[key] : engine.read(engine.pattern(key), null);\n });\n hooks.beforeWrite = first(handled, hooks.beforeWrite, (_engine, p) => {\n if (!internalWrite && p.path.charCodeAt(0) === 36 && NAMESPACES.includes(p.path.split(\".\", 1)[0])) {\n raiseError(`\"${p.path}\" is read-only (the stream runtime owns it).`);\n }\n return false;\n });\n },\n};\nexport default temporal;\n","/**\n * The list-keys add-on (@wcstack/state/features/list-keys): `$listKeys` — identity for refetched\n * rows (README \"$listKeys\"). Assigning an array to a declared list path keeps the row objects whose\n * key matches and writes into them only the fields that changed (a dropped field is cleared with\n * null); the stored array is rebuilt from the kept objects, so rows, their DOM and focus survive a\n * refresh, and a refresh that changes nothing does nothing.\n */\nimport type { Engine } from \"../engine\";\nimport type { Pattern } from \"../pattern\";\nimport type { StateRow } from \"../list\";\nimport { chain, first, handled, hooks, type Feature } from \"../hooks\";\nimport { raiseError } from \"../parser/raiseError\";\n\ntype KeyOf = (row: Record<string, unknown>) => unknown;\n\n/** By state object: a re-set refused after the declaration (recursion) leaves the old state's keys in force. */\nconst keysByTarget = new WeakMap<object, Map<Pattern, KeyOf>>();\n/** The merged array is being written: the write goes through as a plain one. */\nlet merging = false;\nconst PROTO = \"__proto__\";\n/** A field name that is one path segment (no `.` / `*`, not an index, not a `$` name, not `prototype`: a path refuses it). */\nconst SEGMENT = /^(?!prototype$)[^\\d.*$][^.*]*$/;\n\nfunction declare(engine: Engine, target: Record<string, any>): void {\n const decl = target.$listKeys;\n const keys = new Map<Pattern, KeyOf>();\n if (decl !== undefined) {\n if (decl === null || typeof decl !== \"object\") raiseError(\"$listKeys must be an object mapping list paths to a key field or function.\");\n for (const path of Object.keys(decl)) {\n const key = decl[path];\n if (typeof key === \"string\") keys.set(engine.pattern(path), (row) => row[key]);\n else if (typeof key === \"function\") keys.set(engine.pattern(path), key as KeyOf);\n else raiseError(`$listKeys \"${path}\" must be a field name or a function.`);\n }\n }\n keysByTarget.set(target, keys);\n}\n\nfunction isPlain(v: unknown): v is Record<string, unknown> {\n if (v === null || typeof v !== \"object\") return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\n\nfunction keyed(path: string, rows: readonly unknown[], keyOf: KeyOf): Map<unknown, Record<string, unknown>> {\n const out = new Map<unknown, Record<string, unknown>>();\n for (const r of rows) {\n if (!isPlain(r)) raiseError(`$listKeys \"${path}\": rows must be plain objects.`);\n const k = keyOf(r);\n if (k === undefined || k === null) raiseError(`$listKeys \"${path}\": a row has no key.`);\n if (out.has(k)) raiseError(`$listKeys \"${path}\": duplicate key ${JSON.stringify(k)}.`);\n out.set(k, r);\n }\n return out;\n}\n\nfunction beforeWrite(engine: Engine, p: Pattern, row: StateRow | null, value: unknown): boolean {\n if (merging || !Array.isArray(value)) return false;\n const keyOf = keysByTarget.get(engine.target)?.get(p);\n if (keyOf === undefined) return false;\n const old = engine.readData(p, row);\n if (!Array.isArray(old) || old === value) return false;\n const before = keyed(p.path, old, keyOf);\n keyed(p.path, value, keyOf);\n // the stored array: the kept objects where keys match, the new ones elsewhere\n const merged: unknown[] = [];\n const updates: [number, Record<string, unknown>, Record<string, unknown>][] = [];\n let same = old.length === value.length;\n for (let i = 0; i < value.length; i++) {\n const next = value[i] as Record<string, unknown>;\n const kept = before.get(keyOf(next));\n merged.push(kept ?? next);\n if (kept !== undefined) updates.push([i, kept, next]);\n if (merged[i] !== old[i]) same = false;\n }\n const changes: [number, string, unknown][] = [];\n for (const [i, kept, next] of updates) {\n for (const f of Object.keys(next)) if (!Object.is(kept[f], next[f])) changes.push([i, f, next[f]]);\n for (const f of Object.keys(kept)) if (!(f in next) && kept[f] !== null) changes.push([i, f, null]);\n }\n if (same && changes.length === 0) return true; // a no-op refresh does nothing\n if (!same) {\n merging = true;\n try {\n engine.write(p, row, merged);\n } finally {\n merging = false;\n }\n }\n if (changes.length > 0) {\n const list = engine.childList(p.depth === 0 ? null : row, p);\n for (const [i, f, v] of changes) {\n // a field name is the server's. `__proto__` (an own key from JSON) is not a field: copied, it\n // would replace the row's prototype. A name that is not one path segment (`@odata.etag`,\n // `2fa`) or is a row getter's goes into the row as it is, the row told as a whole.\n if (f === PROTO) continue;\n const r = list.rows[i];\n const fp = SEGMENT.test(f) ? engine.pattern(`${p.path}.*.${f}`) : null;\n if (fp?.getter === null) engine.write(fp, r, v);\n else {\n (r.item as Record<string, unknown>)[f] = v;\n engine.write(engine.pattern(`${p.path}.*`), r, r.item, true);\n }\n }\n }\n return true;\n}\n\nexport const listKeys: Feature = {\n name: \"list-keys\",\n hooks,\n install(): void {\n hooks.declare = chain(hooks.declare, declare);\n hooks.beforeWrite = first(handled, hooks.beforeWrite, beforeWrite);\n },\n};\nexport default listKeys;\n","/**\n * Volumes — `<wcs-state mount=\"p\">` (README \"Mounting Additional State\"). A volume is not a\n * root: its state is grafted onto the root tree at `p` by ordinary writes, its getters and\n * setters become root accessors at `p.<key>`, its methods live at `p.<method>`, and inside all\n * of them — and in its `$connectedCallback` / `$disconnectedCallback` — `this` is chrooted at\n * `p` (`this.x` is the tree's `p.x`). Load order does not matter: a volume that loads before its\n * root grafts when the root engine is created, before the page is bound; if the root fails to\n * initialize, its volumes report it and settle. A root hydrated from a server snapshot (SSR)\n * already holds the volume's data at `p`: the volume adopts it (3.x D14). A volume in a component\n * wired to its host (`data-wcs=\"state…\"`) is refused, whenever it loads (3.x left it pending).\n *\n * Not carried over from @wcstack/state 3.3 (approved simplifications, each an error rather than\n * a silent no-op): injections on the volume element (`data-wcs=\"state.k: …\"`), and a volume's\n * own `$watch` / `$listKeys` / `$renderedCallback` — declare them on the root.\n */\nimport type { Engine } from \"../engine\";\nimport type { Pattern } from \"../pattern\";\nimport type { Claimed } from \"../hooks\";\nimport type { WcsState } from \"../element\";\nimport { config } from \"../config\";\nimport { engines } from \"../dom/mount\";\nimport { raiseError, report } from \"../parser/raiseError\";\n\nexport interface Volume {\n readonly el: HTMLElement;\n readonly root: Node;\n readonly path: string;\n state: Record<string, any> | null;\n engine: Engine | null;\n chroot: object | null;\n /** Settles the element's connectedCallbackPromise. */\n settle: (() => void) | null;\n}\n\n/** Mount paths held on each root (reserved when a volume connects, kept once grafted). */\nconst slots = new WeakMap<Node, Map<string, Volume>>();\n/**\n * Loaded volumes waiting for their root's engine; an element: the root's `<wcs-state>` that failed\n * to initialize (what loads later fails with it while it is in the page: failed()).\n */\nconst waiting = new WeakMap<Node, Volume[] | Element>();\nconst ORPHAN = \"will not graft: the root state failed to initialize.\";\n/** The engines of components wired to their host: they read the host's tree, a volume has none to graft onto. */\nexport const wired = new WeakSet<Engine>();\n/** The volumes grafted onto each engine. */\nexport const grafted = new WeakMap<Engine, Volume[]>();\n\nconst REJECTED = [\"$stream\", \"$streams\", \"$scan\", \"$recursion\", \"$watch\", \"$listKeys\", \"$renderedCallback\", \"$updatedCallback\", \"$behavior\", \"$features\"];\nconst NOT_RUN = [\"$commandTokens\", \"$eventTokens\", \"$on\", \"$errorCallback\"];\nconst PREFIX = (path: string) => `[@wcstack/state] <${config.tagNames.state} mount=\"${path}\">`;\n\n/** `$` APIs that take a state path: inside a volume the path is relative to the mount. */\nconst PATH_APIS = new Set([\"$getAll\", \"$setAll\", \"$resolve\", \"$postUpdate\", \"$dependOn\", \"$eq\", \"$eqIndex\"]);\n\nfunction chrootOf(engine: Engine, prefix: string): object {\n const at = (key: string) => `${prefix}.${key}`;\n return new Proxy({}, {\n get(_t, key) {\n if (typeof key === \"symbol\") return undefined;\n if (key.charCodeAt(0) !== 36) return engine.proxy[at(key)];\n const v = engine.proxy[key];\n if (key === \"$eqPath\") return (path: string, keyPath: string) => v(at(path), at(keyPath));\n return PATH_APIS.has(key) && typeof v === \"function\" ? (path: string, ...rest: unknown[]) => v(at(path), ...rest) : v;\n },\n set(_t, key, value) {\n if (typeof key === \"symbol\") return false;\n engine.proxy[at(key as string)] = value;\n return true;\n },\n });\n}\n\nfunction validPath(path: string): boolean {\n return path !== \"\" && path.split(\".\").every((s) => s !== \"\" && !/[*$#@\\s]/.test(s));\n}\n\n/**\n * An engine whose `<wcs-state>` is in the page: nothing grafts onto one that is out (a root out of the\n * page lets go of its root node; a component whose `<wcs-state>` alone left stays registered).\n */\nconst live = (e: Engine | undefined): Engine | undefined => ((e?.element as Node | undefined)?.isConnected ? e : undefined);\n\n/** The root `<wcs-state>` on `root` failed to initialize, and is still in the page. */\nfunction failed(root: Node): boolean {\n const w = waiting.get(root);\n return w !== undefined && !Array.isArray(w) && w.isConnected;\n}\n\n/** The engine created on `root`: graft the volumes that were waiting for it (before its page is bound). */\nexport function rootEngineCreated(engine: Engine, root: Node): void {\n const list = waiting.get(root);\n waiting.delete(root);\n if (Array.isArray(list)) for (const v of list) graft(v, engine);\n}\n\nfunction release(v: Volume): void {\n const held = slots.get(v.root);\n if (held?.get(v.path) === v) held.delete(v.path);\n}\n\n/**\n * A root engine's `<wcs-state>` left the page (\"disconnected\"), or is back (\"back\"; a component's:\n * \"connected\"). Out, the mount paths its volumes hold let go of it (they are kept on the root node,\n * which outlives the content it bound). Back, and still its root's engine (the core holds the root\n * again unless another `<wcs-state>` bound it meanwhile), the volumes that connected meanwhile graft,\n * and its own hold their paths again — unless another volume took one meanwhile.\n */\nexport function rootMoved(engine: Engine, phase: string): void {\n const list = grafted.get(engine) ?? [];\n if (phase === \"disconnected\") for (const v of list) release(v);\n else if (phase !== \"reset\" && live(engines.get(engine.root!)) === engine) {\n rootEngineCreated(engine, engine.root!);\n for (const v of list) if (!slots.get(v.root)!.has(v.path)) slots.get(v.root)!.set(v.path, v);\n }\n}\n\n/** Reports a volume that will not graft, releases its slot and settles its promise. */\nfunction fail(v: Volume, message: string): void {\n report(`${PREFIX(v.path)} ${message}`);\n release(v);\n v.settle?.();\n v.settle = null;\n}\n\nfunction callLifecycle(v: Volume, name: \"$connectedCallback\" | \"$disconnectedCallback\"): void {\n const fn = v.state?.[name];\n if (typeof fn !== \"function\") return;\n try {\n const r = fn.call(v.chroot);\n if (r !== null && typeof r === \"object\" && typeof r.then === \"function\") r.then(undefined, report);\n } catch (e) {\n report(e);\n }\n}\n\nfunction graft(v: Volume, engine: Engine): void {\n if (wired.has(engine)) return fail(v, \"will not graft: its component is wired to its host.\");\n const state = v.state!;\n const target = engine.target;\n const segs = v.path.split(\".\");\n let at: any = target;\n for (const s of segs) at = at == null ? undefined : at[s];\n // a root hydrated from a server snapshot (ssr/ssr.ts) has the volume's data there already: adopted\n if (at !== undefined && (engine as any).hydrated !== true) return fail(v, `will not graft: the root state already has \"${v.path}\".`);\n const chroot = chrootOf(engine, v.path);\n v.chroot = chroot;\n // the data; accessors and methods (bound to the chroot) apart, as root accessors at `p.<key>`,\n // so that whatever replaces the data (the snapshot, a write of the mount path) keeps them\n const data: Record<string, unknown> = {};\n const defs: PropertyDescriptorMap = {};\n const seen = new Set<string>();\n for (let o: object | null = state; o !== null && o !== Object.prototype; o = Object.getPrototypeOf(o)) {\n for (const key of Object.getOwnPropertyNames(o)) {\n if (seen.has(key) || key === \"constructor\") continue;\n seen.add(key);\n const { get, set, value } = Object.getOwnPropertyDescriptor(o, key)!;\n if (get !== undefined || set !== undefined) {\n defs[`${v.path}.${key}`] = {\n get: get && function () { return get.call(chroot); },\n set: set && function (next: unknown) { set.call(chroot, next); },\n };\n } else if (key[0] === \"$\") continue;\n else if (typeof value === \"function\") {\n const fn = value.bind(chroot);\n defs[`${v.path}.${key}`] = { get: () => fn };\n } else data[key] = value;\n }\n }\n if (at === undefined) {\n // intermediate objects of a deep mount path, then the volume's own object\n for (let i = 1; i < segs.length; i++) {\n const p = engine.pattern(segs.slice(0, i).join(\".\"));\n if (engine.readData(p, null) == null) engine.write(p, null, {});\n }\n engine.write(engine.pattern(v.path), null, data);\n }\n // registered as the root's own are (a row-level getter gets its cache slot; the paths under\n // them read through them)\n (engine as any).registerAccessors(Object.defineProperties({}, defs));\n for (const path in defs) engine.changed(engine.pattern(path), null);\n v.engine = engine;\n let list = grafted.get(engine);\n if (list === undefined) grafted.set(engine, (list = []));\n list.push(v);\n if (v.el.isConnected) callLifecycle(v, \"$connectedCallback\");\n v.settle?.();\n v.settle = null;\n}\n\n/**\n * A root `<wcs-state>` (the one no claim took; asked by the last, claimComponent): if it fails to\n * initialize, the volumes waiting on `root` settle instead of waiting forever, and so do the ones\n * that load later — and the components waiting there for their wiring (onRootFailed).\n */\nexport function watchRoot(el: HTMLElement, root: Node): null {\n (el as WcsState).connectedCallbackPromise.catch(() => {\n // a root that bound the page (only its $connectedCallback failed), or a stray second one (#47)\n // beside the root that binds it: nothing failed for what waits there\n const live = engines.get(root)?.element as Element | undefined;\n if ((el as WcsState).bound || (live !== undefined && live !== el && live.isConnected)) return;\n orphan(root, el);\n for (const f of giveUp.get(root) ?? []) f();\n });\n return null;\n}\n\n/**\n * The state of `root` failed to initialize (`el`: the page's root, or a component's in its shadow\n * root): the volumes waiting there report it and settle, and so do those that load later while\n * `el` is in the page.\n */\nexport function orphan(root: Node, el: Element): void {\n const list = waiting.get(root);\n if (Array.isArray(list)) for (const v of list) fail(v, ORPHAN);\n waiting.set(root, el);\n}\n\n/** What else waits on a root node's `<wcs-state>` (a component, for the page's wiring). */\nconst giveUp = new WeakMap<Node, Set<() => void>>();\n\n/**\n * Calls `fn` when (or if) the root `<wcs-state>` on `root` fails to initialize; the function\n * returned stops waiting (what `fn` holds is not kept for as long as the page lives).\n */\nexport function onRootFailed(root: Node, fn: () => void): () => boolean {\n if (failed(root)) fn();\n const s = giveUp.get(root) ?? new Set();\n giveUp.set(root, s.add(fn));\n return () => s.delete(fn);\n}\n\n/** `<wcs-state mount=\"p\">`: claimed instead of becoming a root. */\nexport function claimVolume(el: HTMLElement, root: Node): Claimed | null {\n const path = el.getAttribute(\"mount\");\n if (path === null) return null;\n const v: Volume = { el, root, path, state: null, engine: null, chroot: null, settle: null };\n let problem: string | null = null;\n if (!validPath(path)) problem = `has an invalid mount path: it must be a static path (no \"*\", \"$\", \"#\", \"@\").`;\n else if (el.hasAttribute(config.bindAttributeName)) problem = `injections (data-wcs=\"state.<key>: …\") are not supported — read the root path in a root getter.`;\n else {\n let held = slots.get(root);\n if (held === undefined) slots.set(root, (held = new Map()));\n const other = held.get(path);\n // one grafted onto a root that left the page holds it no more, nor does one waiting for its root\n // out of the page (the page's content replaced): that one yields, and never grafts. (One out of\n // the page that no other volume asks for still grafts when its root comes.)\n if (other !== undefined && other !== v && (other.engine === null ? other.el.isConnected : live(other.engine))) {\n problem = `will not graft: another volume already holds \"${path}\".`;\n } else {\n if (other?.engine === null) {\n const list = waiting.get(root);\n if (Array.isArray(list)) waiting.set(root, list.filter((x) => x !== other));\n other.settle?.();\n other.settle = null;\n }\n held.set(path, v);\n }\n }\n return {\n // a volume that cannot load resolves its connectedCallbackPromise (3.x; it reports, as below)\n lenient: true,\n start(state): Promise<void> | void {\n if (problem !== null) return fail(v, problem);\n // (it yielded its slot while it loaded: see above)\n if (slots.get(root)!.get(path) !== v) return;\n for (const key of REJECTED) if (state[key] !== undefined) return fail(v, `${key} is not run in a volume — declare it on the root state.`);\n for (const key of NOT_RUN) if (state[key] !== undefined) console.warn(`${PREFIX(path)} ${key} is not run in a volume (it belongs to the root).`);\n v.state = state;\n return new Promise<void>((resolve) => {\n v.settle = resolve;\n const engine = live(engines.get(root));\n const list = waiting.get(root);\n if (engine !== undefined) graft(v, engine);\n else if (failed(root)) fail(v, ORPHAN);\n else waiting.set(root, [...(Array.isArray(list) ? list : []), v]);\n });\n },\n connected() {\n if (v.engine !== null) callLifecycle(v, \"$connectedCallback\");\n },\n disconnected() {\n // a grafted volume keeps its data and its slot (there is no unmount)\n if (v.engine !== null) callLifecycle(v, \"$disconnectedCallback\");\n },\n reset() {\n raiseError(`re-setting a volume is not supported: its data was copied into the root tree at \"${path}\" — write the paths under it on the root instead.`);\n },\n };\n}\n\n/** A root write that would replace an object a volume is grafted under. */\nexport function guardAncestorWrite(engine: Engine, p: Pattern): void {\n const list = grafted.get(engine);\n if (list === undefined || p.depth !== 0) return;\n for (const { path } of list) {\n if (path.startsWith(`${p.path}.`)) raiseError(`writing \"${p.path}\" would replace the volume grafted at \"${path}\"; write the paths under it instead.`);\n }\n}\n","/**\n * Declarative Custom Components (README \"DCC\"). The `<wcs-state>` inside the shadow root of a\n * `[data-wc-definition]` host is not a root: it defines the host's tag. Each instance gets a\n * copy of the definition's (untouched) shadow content, whose own `<wcs-state>` is an ordinary\n * root with a fresh state. The class's prototype reads and writes that state (writes before it\n * initializes wait for it; methods return Promises); `$bindables` / `$commands` become its\n * `static wcBindable`, and a write to a bindable (or under it, or a `$postUpdate`) dispatches\n * `<tag>:<prop>-changed` from the instance — a notification: `detail` carries the written value\n * only for a write of the member itself, and the declared getter reads the member off the element.\n *\n * The shadow is built on first use — an accessor or the connect, whichever comes first — not in\n * the constructor: a `for` row binds its elements before they are inserted, a parser-made\n * instance has no attributes in its constructor, and the definition host itself (upgraded by\n * define()) already has its shadow.\n */\nimport type { Engine } from \"../engine\";\nimport type { Pattern } from \"../pattern\";\nimport type { Claimed } from \"../hooks\";\nimport { config } from \"../config\";\nimport { raiseError } from \"../parser/raiseError\";\n\ninterface Definition {\n readonly tag: string;\n readonly bindables: readonly string[];\n}\n\n/** DCC instances by host element, and the definition of each instance's inner engine. */\nconst instances = new WeakMap<Element, Definition>();\nconst byEngine = new WeakMap<Engine, { host: Element; def: Definition }>();\n\nfunction names(state: Record<string, any>, key: string): string[] {\n const v = state[key];\n if (v === undefined) return [];\n if (!Array.isArray(v)) raiseError(`${key} must be an array of state member names.`);\n const seen = new Set<string>();\n for (const n of v) {\n if (typeof n !== \"string\" || n === \"\") raiseError(`${key} entries must be non-empty strings.`);\n if (n[0] === \"$\") raiseError(`${key} entry \"${n}\": internal ($) members are never exposed.`);\n if (seen.has(n)) raiseError(`${key} entry \"${n}\" is duplicated.`);\n seen.add(n);\n }\n return v;\n}\n\n/** Every member of the state (own and inherited), by descriptor. */\nfunction members(state: Record<string, any>): Map<string, PropertyDescriptor> {\n const out = new Map<string, PropertyDescriptor>();\n for (let o: object | null = state; o !== null && o !== Object.prototype; o = Object.getPrototypeOf(o)) {\n for (const key of Object.getOwnPropertyNames(o)) {\n if (key === \"constructor\" || key[0] === \"$\" || out.has(key)) continue;\n out.set(key, Object.getOwnPropertyDescriptor(o, key)!);\n }\n }\n const streams = state.$stream;\n if (streams !== null && typeof streams === \"object\") for (const n of Object.keys(streams)) if (!out.has(n)) out.set(n, { value: undefined });\n return out;\n}\n\nfunction define(tag: string, content: DocumentFragment, mode: ShadowRootMode, state: Record<string, any>): void {\n if (!tag.includes(\"-\")) raiseError(`DCC: <${tag} data-wc-definition> is not a valid custom element name.`);\n if (customElements.get(tag) !== undefined) raiseError(`DCC: <${tag}> is already defined.`);\n const all = members(state);\n const bindables = names(state, \"$bindables\");\n const commands = names(state, \"$commands\");\n for (const n of bindables) {\n const d = all.get(n);\n if (d === undefined) raiseError(`$bindables entry \"${n}\" does not exist on the state.`);\n if (typeof d.value === \"function\") raiseError(`$bindables entry \"${n}\" is a method: list it in $commands.`);\n }\n for (const n of commands) {\n const d = all.get(n);\n if (d === undefined) raiseError(`$commands entry \"${n}\" does not exist on the state.`);\n if (typeof d.value !== \"function\") raiseError(`$commands entry \"${n}\" is not a method: list it in $bindables.`);\n }\n const def: Definition = { tag, bindables };\n /** Each instance's inner `<wcs-state>` (null: a definition host, or content without one). */\n const states = new WeakMap<Element, any>();\n const pending = new WeakMap<Element, [string, unknown][]>();\n /** Builds the instance's shadow once; its inner `<wcs-state>`. */\n const ensure = (el: Element): any => {\n if (states.has(el)) return states.get(el);\n if (el.hasAttribute(\"data-wc-definition\")) return null;\n const shadow = el.attachShadow({ mode });\n shadow.appendChild(content.cloneNode(true));\n const state = shadow.querySelector(config.tagNames.state);\n states.set(el, state);\n instances.set(el, def);\n if (state === null && bindables.length > 0) {\n console.warn(`[@wcstack/state] DCC: <${tag}> declares $bindables but its content has no <${config.tagNames.state}>: no change events.`);\n }\n return state;\n };\n /** The instance's inner engine once its state initialized, else null. */\n const inner = (el: Element): any => ensure(el)?.engine ?? null;\n /** Resolves when the instance's state initialized, before its `$connectedCallback` (and lands the writes queued before). */\n const ready = (el: Element): Promise<void> => Promise.resolve(ensure(el)?.initializePromise).then(() => {\n const queued = pending.get(el);\n pending.delete(el);\n const engine = inner(el);\n if (queued !== undefined && engine !== null) for (const [k, v] of queued) engine.proxy[k] = v;\n });\n\n class Dcc extends HTMLElement {\n static wcBindable = bindables.length === 0 && commands.length === 0 ? null : {\n protocol: \"wc-bindable\", version: 1,\n properties: bindables.map((name) => ({ name, event: `${tag}:${name}-changed`, getter: (e: Event) => (e.target as any)[name] })),\n inputs: bindables.map((name) => ({ name })),\n ...(commands.length === 0 ? {} : { commands: commands.map((name) => ({ name, async: true })) }),\n };\n\n connectedCallback(): void {\n if (ensure(this) !== null) void ready(this);\n }\n\n /** The inner `<wcs-state>` (as in 3.3; builds the shadow if it is not built yet). */\n get stateElement(): HTMLElement | null {\n return ensure(this);\n }\n }\n for (const [name, d] of all) {\n if (typeof d.value === \"function\") {\n Object.defineProperty(Dcc.prototype, name, {\n configurable: true,\n value(this: Element, ...args: unknown[]) {\n return ready(this).then(() => {\n const engine = inner(this);\n return engine === null ? undefined : engine.proxy[name].apply(engine.proxy, args);\n });\n },\n });\n } else {\n Object.defineProperty(Dcc.prototype, name, {\n configurable: true,\n get(this: Element) { return inner(this)?.proxy[name]; },\n set(this: Element, value: unknown) {\n const engine = inner(this);\n if (engine !== null) engine.proxy[name] = value;\n else {\n let q = pending.get(this);\n if (q === undefined) pending.set(this, (q = []));\n q.push([name, value]);\n }\n },\n });\n }\n }\n customElements.define(tag, Dcc);\n}\n\n/** The `<wcs-state>` of a definition host: claimed to define the tag. */\nexport function claimDcc(el: HTMLElement, root: Node): Claimed | null {\n const host = (root as ShadowRoot).host;\n if (host === undefined || !host.hasAttribute(\"data-wc-definition\")) return null;\n // the definition's content, before anything touches it: every instance starts from this\n const content = document.createDocumentFragment();\n for (const n of [...root.childNodes]) content.appendChild(n.cloneNode(true));\n const mode = (root as ShadowRoot).mode;\n return {\n start(state) {\n if (el.hasAttribute(\"bind-component\")) raiseError(\"DCC: a <wcs-state bind-component> cannot define a component (use one mechanism).\");\n define(host.localName, content, mode, state);\n },\n connected() {},\n disconnected() {},\n reset() {\n raiseError(\"re-setting a DCC definition is not supported: each instance loads its own state.\");\n },\n };\n}\n\n/** A root engine was created: an instance's inner state gets its host's change events. */\nexport function dccEngineCreated(engine: Engine, root: Node): void {\n const host = (root as ShadowRoot).host;\n const def = host === undefined ? undefined : instances.get(host);\n if (def !== undefined) byEngine.set(engine, { host, def });\n}\n\n/**\n * A write at a bindable, under it, or its `$postUpdate`: `<tag>:<prop>-changed` from the\n * instance, with the written value as `detail` only for a data write of the member itself.\n */\nexport function dccWritten(engine: Engine, p: Pattern, value: unknown, direct: boolean): void {\n const info = byEngine.get(engine);\n if (info === undefined) return;\n const name = p.path.split(\".\", 1)[0];\n if (!info.def.bindables.includes(name)) return;\n const exact = direct && p.path === name;\n info.host.dispatchEvent(new CustomEvent(`${info.def.tag}:${name}-changed`, { detail: exact ? value : undefined, bubbles: true }));\n}\n","/**\n * Component mounts — `<wcs-state bind-component=\"prop\">` directly inside a custom element\n * (README \"Web Component Binding\"). Each component runs an engine of its own over its state\n * object (the host element's `prop`): its bindings, rows, `$1`, event indexes, getters and\n * private keys are the component's. The host wires it with ordinary property bindings on the\n * element (`state: user`, `state.x: path`, `state: .` in a row); those are taken over as\n * mount entries, and the component reads and writes the mounted keys through the host's\n * engine. Changes cross both ways through the `written` / `getterReached` hooks: the host's\n * reach the components mounted on them, and a component's writes under a mounted key reach\n * the host (and, from there, the other components mounted on the same data).\n *\n * Own keys stay private (rule R1): a key the component declares itself is its own, except a\n * one-segment partial entry, which wins over a data default. Unwired, a Shadow DOM component\n * owns an independent tree; a Light DOM one cannot (it shares the page) and fails loudly.\n *\n * `#ro` on an entry (`state#ro: user`) is honoured as in 3.3: a component's code writing through it\n * throws `[wcs/mount-readonly]`, an element's write-back inside the component is dropped.\n *\n * A whole mount's accessors are exported at the mount point (README \"Exported getters\"): the host\n * reads `user.display` (row by row for `state: .`) from the component mounted there, unless the\n * tree has the key.\n * A mounted component runs no temporal declaration and no `$renderedCallback`, and refuses `$recursion`.\n */\nimport { Engine, rowAt } from \"../engine\";\nimport { WILDCARD, type Pattern } from \"../pattern\";\nimport type { StateRow } from \"../list\";\nimport type { Binding } from \"../dom/view\";\nimport { hooks, loadFeatures, type Claimed } from \"../hooks\";\nimport { config } from \"../config\";\nimport { DirtyStrategy } from \"../strategy/dirty\";\nimport { engines, mount, mountSubtree } from \"../dom/mount\";\nimport { bind, drainBinds } from \"../dom/binder\";\nimport { registryOf } from \"../dom/wc\";\nimport { raiseError, report } from \"../parser/raiseError\";\nimport type { WcsState } from \"../element\";\nimport { onRootFailed, orphan, rootEngineCreated, watchRoot, wired } from \"./volume\";\n\ninterface Entry {\n /** The component-side path (\"\" = the whole state). */\n readonly inner: string;\n /** The host pattern and row (at the pattern's depth) it is mounted on. */\n readonly outer: Pattern;\n readonly row: StateRow | null;\n /** Mounted `#ro`: the component reads it and does not write it. */\n readonly ro: boolean;\n}\n\n/** What a host element keeps across the `<wcs-state>` elements its renders create. */\ninterface Host {\n readonly el: Element;\n readonly prop: string;\n /** The author's state object: the component's private data lives here. */\n readonly state: Record<string, any>;\n /** The host's engine (null: an unwired, independent component). */\n readonly engine: Engine | null;\n readonly entries: Entry[];\n current: Mount | null;\n}\n\ninterface Synth {\n readonly e: Entry;\n readonly p: Pattern;\n readonly row: StateRow | null;\n}\n\ninterface Mount {\n /** Its `<wcs-state>`: a new one that takes the scope over replaces it (resume). */\n el: HTMLElement;\n /** The nodes of the scope root once it was bound: still there, a new `<wcs-state>` takes the scope over. */\n nodes: ChildNode[];\n readonly component: Engine;\n readonly host: Host;\n readonly slots: { m: Mount; e: Entry }[];\n /** Component patterns that read and write the host. */\n readonly synth: Map<Pattern, Synth>;\n registered: boolean;\n /** A mounted key its setter just wrote through the host (its `written` is not forwarded again). */\n skip: Pattern | null;\n /** The entry a change of the component is crossing to the host through: its other entries still take it. */\n from: Entry | null;\n /** Exported accessors (a whole mount's): host pattern (`user.display`) → the component's accessor pattern. */\n exports: Map<Pattern, Pattern> | null;\n /**\n * It failed before its bindings were built (a markup error): what it bound before the error follows\n * the host while it is connected, as a root's does (#384), and no lifecycle hook runs — its\n * `$connectedCallback` never did.\n */\n broken?: boolean;\n}\n\ntype Slot = Mount[\"slots\"][number];\n\n/** Plain property bindings hosts made on custom elements: the candidates for wiring. */\nconst hostBindings = new WeakMap<Element, Binding[]>();\n/** Those of them written with `#ro`. */\nconst readonlyWiring = new WeakSet<Binding>();\n/** An element property's value before a host's first write to it (a mount takes the component's). */\nconst before = new WeakMap<Element, Map<string, unknown>>();\n/** Components waiting for their host to bind the wiring written in its markup. */\nconst waiting = new WeakMap<Element, () => void>();\n/**\n * SSR: a row is a clone of its plan, so the server's output carries no `data-wcs` on a row's\n * elements. A host binding made while rendering on the server writes the heads it binds here\n * instead, so a component whose class is defined before the client adopts the row still waits\n * for its wiring (as it does for `data-wcs`); the client's host binding removes it.\n */\nconst WIRED = \"data-wcs-wired\";\nconst onServer = (): boolean => document.documentElement?.hasAttribute(\"data-wcs-server\") === true;\nconst hosts = new WeakMap<Element, Host>();\nconst mounts = new WeakMap<Engine, Mount>();\n/** Mount entries by host engine, host pattern and host row. */\nconst index = new WeakMap<Engine, Map<Pattern, Map<StateRow | null, Set<Slot>>>>();\nlet registered = 0;\n/** Engines a change is crossing from: it does not come back to them. */\nconst active = new Set<Engine>();\n\nconst UNWIRED = {};\n/** Declarations a mounted component does not run (`$listKeys` runs: it keys the component's own lists). */\nconst INERT = [\"$watch\", \"$stream\", \"$renderedCallback\"];\n\nconst headOf = (path: string): string => path.split(\".\", 1)[0];\n\n/** `a.*.b.*` with [2, 5] → `a.2.b.5`. */\nfunction fill(path: string, idx: number[]): string {\n let i = 0;\n return path.split(\".\").map((s) => (s === WILDCARD ? String(idx[i++]) : s)).join(\".\");\n}\n\n/** The core's hook: a plain property binding on a custom element (before it applies). */\nexport function hostBinding(b: Binding, ro: boolean): boolean {\n const el = b.node as Element;\n const head = headOf(b.name);\n if (!onServer()) el.removeAttribute(WIRED);\n else if (!wiredInMarkup(el, head)) {\n const heads = el.getAttribute(WIRED)?.split(\" \") ?? [];\n if (!heads.includes(head)) el.setAttribute(WIRED, [...heads, head].join(\" \"));\n }\n // the component took its wiring when it loaded: a mount is not re-wired\n if (hosts.get(el)?.prop === head) {\n raiseError(`<${el.localName}>.${head} has loaded its state: the wiring \"${b.name}\" added afterwards cannot reach it — bind the host's wiring before the component loads.`);\n }\n let list = hostBindings.get(el);\n if (list === undefined) hostBindings.set(el, (list = []));\n list.push(b);\n if (ro) readonlyWiring.add(b);\n let values = before.get(el);\n if (values === undefined) before.set(el, (values = new Map()));\n if (!values.has(head)) values.set(head, (el as any)[head]);\n waiting.get(el)?.();\n return false;\n}\n\n/** The core's hook: a Light DOM component's content is bound by its own engine. */\nexport function componentScope(el: Element): boolean {\n return el.localName.includes(\"-\") && el.querySelector(`:scope > ${config.tagNames.state}[bind-component]`) !== null;\n}\n\nfunction wiredInMarkup(host: Element, prop: string): boolean {\n const text = host.getAttribute(config.bindAttributeName);\n return text !== null && new RegExp(`(^|;)\\\\s*${prop.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}\\\\s*[.#:]`).test(text);\n}\n\n/**\n * A host whose wiring is in its markup, and which the page did not bind: it was out of the page when\n * the page's state loaded, or was inserted since — by code, not by a `for:` / `if:` (which binds it\n * before inserting it) or the router (which hands it over). Its `<wcs-state>` hands it over as the\n * router does (src/dom/binder.ts): it is bound now, or once its root's state is in the page (it has not\n * loaded yet, or its `<wcs-state>` is out). In a Light DOM component, that component's engine binds it,\n * when it mounts (now, if it has). A host the page did bind is left alone (an element is walked once),\n * and so is one whose root failed before binding the page (onRootFailed refuses the component).\n */\nfunction wireLate(host: Element): void {\n let scope = host.parentElement;\n while (scope !== null && !componentScope(scope)) scope = scope.parentElement;\n const E = engines.get(scope ?? host.getRootNode());\n const el = E?.element as WcsState | undefined;\n // (the binder binds to the page's engine now, or keeps the host for when it is in the page)\n if (el?.isConnected ? el.bound : scope === null) {\n if (scope === null) bind(host);\n else mountSubtree(E!, host);\n }\n}\n\n/** The server's output says the host binds `prop` on this row element (see WIRED). */\nconst wiredOnServer = (host: Element, prop: string): boolean => host.getAttribute(WIRED)?.split(\" \").includes(prop) === true;\n\n/** A frozen author object is copied into a writable one (same prototype). */\nfunction melt(o: Record<string, any>): Record<string, any> {\n const ds = Object.getOwnPropertyDescriptors(o);\n let frozen = Object.isFrozen(o);\n for (const d of Object.values(ds)) if (\"value\" in d && d.writable === false) { d.writable = true; frozen = true; }\n return frozen ? Object.create(Object.getPrototypeOf(o), ds) : o;\n}\n\nasync function load(el: HTMLElement, prop: string, host: Element, light: boolean): Promise<Record<string, any>> {\n const tag = host.localName;\n if ([\"state\", \"src\", \"json\"].some((a) => el.hasAttribute(a)) || el.querySelector('script[type=\"module\"]') !== null) {\n raiseError(`<${config.tagNames.state} bind-component> takes its state from <${tag}>.${prop}: it cannot also load one (state / src / json / an inline script).`);\n }\n await registryOf(host).whenDefined(tag);\n let h = hosts.get(host);\n if (h !== undefined) {\n if (h.prop !== prop) raiseError(`<${tag}> already has a <${config.tagNames.state} bind-component=\"${h.prop}\">.`);\n return h.state;\n }\n const wiring = () => (hostBindings.get(host) ?? []).filter((b) => headOf(b.name) === prop);\n // the host binds its wiring when it renders the element (a row before inserting it; the page\n // when its state loads; a server-rendered row when the client adopts it), or when the\n // element's class is defined — or, written in its markup on a host the page did not bind, now\n const marked = wiredInMarkup(host, prop);\n if (marked && wiring().length === 0) wireLate(host);\n if (wiring().length === 0 && (marked || wiredOnServer(host, prop))) {\n // (if the page's state fails, its wiring never comes)\n let stop!: () => boolean;\n await new Promise<void>((r, j) => {\n waiting.set(host, r);\n stop = onRootFailed(host.getRootNode(), () => j(new Error(`[@wcstack/state] <${tag}>.${prop} will not mount: the root state failed to initialize.`)));\n }).finally(() => stop());\n }\n waiting.delete(host);\n const bs = wiring();\n const values = before.get(host);\n const original = values !== undefined && values.has(prop) ? values.get(prop) : (host as any)[prop];\n if (original === null || typeof original !== \"object\") {\n raiseError(`\"bind-component\": <${tag}>.${prop} must be an object (the component's state), got ${original === null ? \"null\" : typeof original}.`);\n }\n if (bs.length === 0 && light) {\n // reported as an uncaught error, after this element settles (as 3.3 does)\n const error = new Error(`[@wcstack/state] A plain (unwired) Light DOM \"bind-component\" is not supported. Attach a shadow root to <${tag}>, or mount it from the host (${config.bindAttributeName}=\"${prop}: path\").`);\n queueMicrotask(() => { throw error; });\n return UNWIRED;\n }\n const entries: Entry[] = [];\n for (const b of bs) {\n const inner = b.name === prop ? \"\" : b.name.slice(prop.length + 1);\n if (entries.some((e) => e.inner === inner)) raiseError(`<${tag}> maps \"${b.name}\" twice.`);\n const star = inner.split(\".\").indexOf(WILDCARD);\n if (star >= 0) {\n const list = inner.split(\".\").slice(0, star).join(\".\");\n raiseError(`<${tag}> maps \"${b.name}\": the component-side path of a mount cannot contain \"*\"${list === \"\" ? \"\" : ` — map the list itself (\"${prop}.${list}: <the host's list>\")`}.`);\n }\n entries.push({ inner, outer: b.pattern, row: b.row, ro: readonlyWiring.has(b) });\n // the component reads the host from now on: the binding no longer writes the element\n b.engine.unregister(b);\n if (inner !== \"\") delete (host as any)[b.name];\n }\n const state = bs.length === 0 ? melt(original as Record<string, any>) : original as Record<string, any>;\n hosts.set(host, (h = { el: host, prop, state, engine: bs.length === 0 ? null : bs[0].engine, entries, current: null }));\n return state;\n}\n\nconst warned = new Set<string>();\nfunction warnOnce(key: string, message: string): void {\n if (warned.has(key)) return;\n warned.add(key);\n console.warn(`[@wcstack/state] ${message}`);\n}\n\n/** Whether `key` is the component's own (a data default, an accessor or a method of its state). */\nconst own = (h: Host, key: string): boolean => key in h.state;\n\n/** The component's own surface for `key`: an accessor or a method (a data default is not). */\nfunction surface(h: Host, key: string): boolean {\n const d = findDescriptor(h.state, key);\n return d !== undefined && (d.get !== undefined || d.set !== undefined || typeof d.value === \"function\");\n}\n\n/**\n * The component's patterns that read and write the host: a partial entry's path, and under a\n * whole mount every top-level key the component does not declare itself.\n */\nfunction wire(m: Mount): void {\n const C = m.component;\n const h = m.host;\n const H = h.engine!;\n const tag = h.el.localName;\n const whole = h.entries.find((e) => e.inner === \"\") ?? null;\n for (const e of h.entries) {\n if (e.inner === \"\") continue;\n const head = headOf(e.inner);\n // a one-segment entry wins over a data default; the component's own surface (an accessor,\n // a method) and an own key above a deep entry win over the entry\n if (own(h, head) && (e.inner !== head || surface(h, head))) {\n warnOnce(`${tag}.${e.inner}`, `[wcs/mount-own-key-shadow] <${tag}>: \"${h.prop}.${e.inner}\" is hidden by the component's own \"${head}\"; rename one side.`);\n }\n }\n if (whole !== null) {\n const at = H.readUntracked(whole.outer, whole.row);\n if (at !== null && typeof at === \"object\") {\n for (const key of Object.keys(h.state)) {\n if (key[0] !== \"$\" && key in at && !h.entries.some((e) => e.inner === key)) {\n warnOnce(`${tag}.${key}`, `[wcs/mount-own-key-shadow] <${tag}>: its own \"${key}\" hides \"${whole.outer.path}.${key}\" — remove the default to read the tree, or rename it to keep it private.`);\n }\n }\n }\n }\n const declared = INERT.filter((k) => h.state[k] !== undefined);\n if (declared.length > 0) {\n warnOnce(`${tag}.${h.prop}$`, `[wcs/mount-dollar-declaration] <${tag}>: ${declared.join(\", \")} ${declared.length === 1 ? \"is\" : \"are\"} not run in a mounted component — declare it on the root state.`);\n }\n const base = (C as any).onPatternCreated;\n (C as any).onPatternCreated = (p: Pattern) => {\n mountKey(m, whole, p);\n base.call(C, p);\n };\n // patterns the engine made before (the parents of the component's own accessors): mounted\n // keys among them, then what now reads through them. A snapshot: both loops walk it (a pattern\n // made during the first goes through the wrapped onPatternCreated above).\n const made = [...C.patterns.all()];\n for (const p of made) mountKey(m, whole, p);\n for (const p of made) base.call(C, p);\n // a mount in a host row goes with the row (4.0 discards a removed row's element): it renders no\n // more — what it would read of the row throws (live), its own keys stay readable and writable.\n // So does a mount inside a component that went with its row: it reads the tree through that one.\n const drain = C.drain;\n C.drain = () => {\n if (inPlace(m)) drain.call(C);\n };\n}\n\n/** Every host row a mount reads through is still there: its own, and those of the components it is in. */\nfunction inPlace(m: Mount | undefined): boolean {\n for (; m !== undefined; m = mounts.get(m.host.engine!)) {\n if (m.host.entries.some((e) => e.row !== null && !e.row.alive)) return false;\n }\n return true;\n}\n\n/**\n * `element.state` is the component's proxy, handed out as an object: a function the state declares\n * (a method, or a function-valued key it starts with) read off it always runs on it, whatever `this`\n * it is called with — detached (`const { toggle } = element.state`), as a listener\n * (`button.addEventListener(\"click\", element.state.toggle)`), by a timer — as 3.x's `bind` did\n * (#331; an explicit `call(other)` is ignored, as with `bind`). It is wrapped once per function, in a\n * proxy that keeps the function's properties, statics, `new`, `name` and identity across reads; a\n * function a key comes to hold later, the tree's or its own, is returned as it is. Only reads through\n * the proxy itself are wrapped, not through a view of it (`createStateAsync(\"readonly\")`, whose\n * methods must run on the read-only view). A root's proxy is only lent to a callback, and a volume's\n * methods are bound to its chroot already.\n */\nfunction bindMethods(C: Engine, state: object): void {\n const methods = new Map<unknown, unknown>();\n for (let o: object | null = state; o !== null && o !== Object.prototype; o = Object.getPrototypeOf(o)) {\n for (const k of Object.getOwnPropertyNames(o)) {\n const v = Object.getOwnPropertyDescriptor(o, k)!.value;\n if (typeof v === \"function\" && k !== \"constructor\") methods.set(v, null);\n }\n }\n const apply = (f: (...a: unknown[]) => unknown, _self: unknown, args: unknown[]): unknown => Reflect.apply(f, C.proxy, args);\n C.bound = (fn) => {\n let b = methods.get(fn);\n if (b === null) methods.set(fn, (b = new Proxy(fn, { apply })));\n return b;\n };\n}\n\nfunction findDescriptor(o: object, key: string): PropertyDescriptor | undefined {\n for (let x: object | null = o; x !== null && x !== Object.prototype; x = Object.getPrototypeOf(x)) {\n const d = Object.getOwnPropertyDescriptor(x, key);\n if (d !== undefined) return d;\n }\n return undefined;\n}\n\nfunction mountKey(m: Mount, whole: Entry | null, p: Pattern): void {\n if (p.getter !== null) return;\n const h = m.host;\n const H = h.engine!;\n const head = headOf(p.path);\n let e = h.entries.find((x) => x.inner === p.path);\n if (e === undefined && p.parent !== null) return mountUnder(m, p);\n if (p.depth !== 0) return;\n let target: Pattern;\n if (e !== undefined) {\n if (e.inner !== head ? own(h, head) : surface(h, head)) return;\n target = e.outer;\n } else if (whole !== null && p.parent === null && head[0] !== \"$\" && !own(h, head)) {\n e = whole;\n target = H.pattern(`${whole.outer.path}.${head}`);\n } else {\n return;\n }\n const row = e.row;\n const through = e;\n p.getter = () => H.readUntracked(target, live(m, row));\n p.setter = (value: unknown) => {\n across(m, through, () => H.write(target, row, value));\n m.skip = p;\n };\n m.synth.set(p, { e, p: target, row });\n}\n\n/**\n * The host row an entry is mounted on, for reading or writing through it. A removed row is gone\n * for good (4.0 never puts a removed row's element in another row): nothing of it is the\n * component's any more, and the position it had may hold another row now (3.4 #367 / #368).\n */\nfunction live(m: Mount, row: StateRow | null): StateRow | null {\n if (row !== null && !row.alive) raiseError(`The host row of <${m.host.el.localName}> was removed.`);\n return row;\n}\n\n/** Runs a change of component `m` crossing to its host through entry `e`. */\nfunction across(m: Mount, e: Entry, fn: () => void): void {\n const was = active.has(m.component);\n active.add(m.component);\n m.from = e;\n try {\n fn();\n } finally {\n if (!was) active.delete(m.component);\n m.from = null;\n }\n}\n\n/** Whether a change crossing from the component's own entry `from` (or from its host) reaches `slot`. */\nconst reaches = (slot: Slot, reached: boolean): boolean =>\n reached || !active.has(slot.m.component) || (slot.m.from !== null && slot.m.from !== slot.e);\n\n/**\n * A path under a mounted key whose host counterpart is a getter (a host getter, a recursive\n * family): read — and written, if it has a setter — through the host, row by row.\n */\nfunction mountUnder(m: Mount, p: Pattern): void {\n let s: Pattern | null = p.parent;\n let info: Synth | undefined;\n while (s !== null && (info = m.synth.get(s)) === undefined) s = s.parent;\n if (s === null || info === undefined) return;\n const C = m.component;\n const H = m.host.engine!;\n const hp = H.pattern(info.p.path + p.path.slice(s.path.length));\n if (hp.getter === null) return;\n const from = info;\n /**\n * The host row of `hp`: the entry's own row (not the row now at its position), and under it the\n * component's rows (a component path with a `*` of its own).\n */\n const at = (): StateRow | null => {\n const r = live(m, from.row);\n if (p.depth === 0) return r;\n H.resolve(fill(hp.path, [...H.indexesOf(r), ...C.indexesOf(rowAt(C.ctx, p.depth))]), null);\n return (H as any).rr as StateRow | null;\n };\n p.getter = () => {\n const r = at();\n return hp.depth > 0 && r === null ? undefined : H.readUntracked(hp, r);\n };\n if (hp.setter !== null) {\n p.setter = (value: unknown) => {\n const r = at();\n across(m, from.e, () => H.write(hp, r, value));\n m.skip = p;\n };\n }\n if (p.depth > 0) p.slot = (C as any).slotCount++;\n m.synth.set(p, { e: from.e, p: hp, row: from.row });\n}\n\nfunction register(m: Mount, on: boolean): void {\n if (m.registered === on || m.host.engine === null) return;\n m.registered = on;\n registered += on ? 1 : -1;\n const H = m.host.engine;\n let byP = index.get(H);\n if (byP === undefined) index.set(H, (byP = new Map()));\n for (const slot of m.slots) {\n let byRow = byP.get(slot.e.outer);\n if (byRow === undefined) byP.set(slot.e.outer, (byRow = new Map()));\n let set = byRow.get(slot.e.row);\n if (set === undefined) byRow.set(slot.e.row, (set = new Set()));\n if (on) set.add(slot);\n else {\n set.delete(slot);\n if (set.size === 0) byRow.delete(slot.e.row);\n }\n }\n const whole = m.host.entries.find((e) => e.inner === \"\");\n if (whole === undefined) return;\n if (m.exports === null) exportAccessors(m, whole);\n // the host's readers of the exported paths: the component answers them now (a re-set of the\n // host while it was away forgot the answer), or no longer\n for (const hp of m.exports!.keys()) {\n if (on && hp.getter === null) answer(H, hp, whole.outer);\n H.strategy.invalidate(H, hp, whole.row);\n }\n if (m.exports!.size > 0) H.schedule();\n if (on) warnShadowed(m, whole);\n}\n\n// ---------------------------------------------------------------- exported accessors\n\n/** The getters `answer` gave host patterns (a re-set of the host forgets them with its accessors). */\nconst exporting = new WeakSet<object>();\n\n/**\n * README \"Exported getters\": a whole mount's accessors (getters and setters, not methods or\n * private data, no `*` in the name) are read at the mount point. The host's own accessor there\n * wins; a key the tree has wins (`wcs/mount-export-shadowed`).\n */\nfunction exportAccessors(m: Mount, whole: Entry): void {\n const h = m.host;\n const H = h.engine!;\n m.exports = new Map();\n const seen = new Set<string>();\n for (let o: object | null = h.state; o !== null && o !== Object.prototype; o = Object.getPrototypeOf(o)) {\n for (const k of Object.getOwnPropertyNames(o)) {\n if (seen.has(k)) continue;\n seen.add(k);\n const d = Object.getOwnPropertyDescriptor(o, k)!;\n if ((d.get === undefined && d.set === undefined) || k[0] === \"$\" || k.includes(WILDCARD)) continue;\n // a dotted accessor exports only from the component's own data (`form.label`), not the tree's\n const head = headOf(k);\n if (k !== head && !own(h, head)) continue;\n const hp = H.pattern(`${whole.outer.path}.${k}`);\n // the host's own accessor there wins\n if (hp.getter === null) answer(H, hp, whole.outer);\n else if (!exporting.has(hp.getter)) continue;\n m.exports.set(hp, m.component.pattern(k));\n }\n }\n}\n\n/** The mount that exports `hp` at host row `row` (the row at the mount point's depth). */\nfunction exporter(H: Engine, outer: Pattern, row: StateRow | null, hp: Pattern): Mount | null {\n const set = index.get(H)?.get(outer)?.get(row);\n if (set === undefined) return null;\n let found: Mount | null = null;\n for (const slot of set) {\n if (slot.e.inner !== \"\" || slot.m.exports?.has(hp) !== true || slot.m === found) continue;\n if (found !== null) {\n raiseError(`[wcs/mount-export-ambiguous] \"${hp.path}\" is exported by two mounted components on the same instance: <${found.host.el.localName}> and <${slot.m.host.el.localName}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`);\n }\n found = slot.m;\n }\n return found;\n}\n\n/** Makes host pattern `hp` read (and write) the accessor of the component mounted at `outer`, row by row. */\nfunction answer(H: Engine, hp: Pattern, outer: Pattern): void {\n const parent = hp.parent!;\n const last = hp.last;\n /** The tree's object that has the key, or null. */\n const tree = (): any => {\n const o = H.read(parent, H.ctx) as any;\n return o !== null && typeof o === \"object\" && last in o ? o : null;\n };\n hp.getter = () => {\n const o = tree();\n if (o !== null) return o[last];\n const m = exporter(H, outer, H.ctx, hp);\n return m === null ? undefined : m.component.read(m.exports!.get(hp)!, null);\n };\n exporting.add(hp.getter);\n hp.setter = (value: unknown) => {\n const o = tree();\n const m = o === null ? exporter(H, outer, H.ctx, hp) : null;\n if (m === null) {\n // no component answers it here: the tree's own key\n const at = H.read(parent, H.ctx) as any;\n if (at !== null && typeof at === \"object\") at[last] = value;\n return;\n }\n const cp = m.exports!.get(hp)!;\n if (findDescriptor(m.host.state, cp.path)?.set === undefined) {\n raiseError(`Cannot write to \"${cp.path}\" on mounted <${m.host.el.localName}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`);\n }\n m.component.write(cp, null, value);\n };\n if (hp.depth > 0) hp.slot = H.slotCount++;\n}\n\nfunction warnShadowed(m: Mount, whole: Entry): void {\n const H = m.host.engine!;\n for (const [hp, cp] of m.exports!) {\n const o = H.readUntracked(hp.parent!, whole.row) as any;\n if (o === null || typeof o !== \"object\" || !(hp.last in o)) continue;\n const tag = m.host.el.localName;\n warnOnce(`${tag}|${hp.path}`, `[wcs/mount-export-shadowed] <${tag}>.${m.host.prop}.${cp.path} is exported at \"${hp.path}\" but the tree already has that key, so readers outside the component get the tree value. Remove the tree key or rename the accessor. See docs/state-overlay-export-design.md X1.`);\n }\n}\n\n/** A component's exported accessor was reached (it may now differ): so are the host's readers of it. */\nfunction exportReached(m: Mount, g: Pattern): void {\n const whole = m.host.entries.find((e) => e.inner === \"\")!;\n const H = m.host.engine!;\n for (const [hp, cp] of m.exports!) {\n if (cp !== g) continue;\n H.strategy.invalidate(H, hp, whole.row);\n H.schedule();\n }\n}\n\n/**\n * The `beforeWrite` hook: a component's write through a `#ro` entry, or through an entry whose\n * host row is gone. Code (a method, `element.state`, `$setAll` / `$resolve`) is refused; an\n * element's write-back (a two-way input in the component) is dropped, as `#ro` on that binding\n * would (@wcstack/state 3.3).\n */\nexport function guardReadonlyMount(E: Engine, p: Pattern, element: boolean): boolean {\n const m = mounts.get(E);\n if (m === undefined) return false;\n let info: Synth | undefined;\n for (let s: Pattern | null = p; s !== null && info === undefined; s = s.parent) info = m.synth.get(s);\n if (info === undefined) return false;\n const e = info.e;\n // the host's row went away (an await outlived it): the write has nowhere to land (3.3.x)\n const gone = e.row !== null && !e.row.alive;\n if (!gone && !e.ro) return false;\n if (element) return true;\n live(m, e.row);\n raiseError(`[wcs/mount-readonly] <${m.host.el.localName}> cannot write \"${p.path}\": it is mounted read-only (\"${m.host.prop}${e.inner === \"\" ? \"\" : `.${e.inner}`}#ro: ${e.outer.path}\"). Write it on the host, or drop #ro from the mount.`);\n}\n\n/** A host engine that has components mounted on it: its state cannot be re-set. */\nexport function hasMounts(engine: Engine): boolean {\n const byP = index.get(engine);\n if (byP === undefined) return false;\n for (const byRow of byP.values()) if (byRow.size > 0) return true;\n return false;\n}\n\n/**\n * Applies a change another engine made to shared data: the lists under it re-sync (an\n * element's row takes the array's new element), hooks see it, dependents update.\n */\nfunction touch(E: Engine, p: Pattern, row: StateRow | null, old: unknown, value: unknown, direct: boolean): void {\n if (p.getter !== null) {\n E.strategy.invalidate(E, p, row);\n E.schedule();\n return;\n }\n if (p.last === WILDCARD) {\n if (row === null) return;\n row.item = (row.list.arr as unknown[])[row.index];\n E.strategy.resetRow(row);\n if (row.children !== null) for (const l of row.children.values()) E.sync(l);\n } else {\n (E as any).syncListsUnder(p, row);\n }\n hooks.written?.(E, p, row, old, value, direct);\n E.changed(p, row);\n}\n\n/** The value an entry is mounted on may have been replaced: every key read through it is stale. */\nfunction refresh(slot: Slot): void {\n const C = slot.m.component;\n for (const [p, s] of slot.m.synth) {\n if (s.e !== slot.e) continue;\n if (p.depth === 0) C.strategy.invalidate(C, p, null);\n else C.forAllRows(p.lists[p.depth]!, (r) => C.strategy.invalidate(C, p, r));\n }\n C.schedule();\n}\n\n/** A host change at or under an entry: the component's path under the mounted key. */\nfunction into(slot: Slot, q: Pattern, p: Pattern, row: StateRow | null, old: unknown, value: unknown, direct: boolean): void {\n const rest = p.path.slice(q.path.length);\n if (rest === \"\") return refresh(slot);\n const m = slot.m;\n const C = m.component;\n let cpath: string;\n if (slot.e.inner === \"\") {\n cpath = rest.slice(1);\n const head = headOf(cpath);\n // the component keeps it private, or a partial entry maps it elsewhere (the longest prefix wins)\n if (head[0] === \"$\" || own(m.host, head) || m.host.entries.some((x) => x.inner !== \"\" && (cpath === x.inner || cpath.startsWith(`${x.inner}.`)))) return;\n } else {\n cpath = slot.e.inner + rest;\n }\n const idx: number[] = [];\n for (let k = q.depth + 1; k <= p.depth; k++) idx.push(rowAt(row, k)!.index);\n C.resolve(fill(cpath, idx), null);\n const cp = (C as any).rp as Pattern;\n const crow = (C as any).rr as StateRow | null;\n if (cp.depth > 0 && crow === null) return;\n touch(C, cp, crow, old, value, direct);\n}\n\n/** A component's write under a mounted key: the host's path, with the host row's indexes first. */\nfunction up(m: Mount, p: Pattern, row: StateRow | null, old: unknown, value: unknown, direct: boolean): void {\n let s: Pattern | null = p;\n let info: Synth | undefined;\n while (s !== null && (info = m.synth.get(s)) === undefined) s = s.parent;\n if (s === null || info === undefined) return; // private data\n const H = m.host.engine!;\n if (s === p && m.skip === p) {\n m.skip = null; // its setter wrote through the host\n return;\n }\n // its host row went away (a write there is refused; `$postUpdate` is not a write): the position\n // it had may hold another row now\n if (info.row !== null && !info.row.alive) return;\n const idx = [...H.indexesOf(info.row), ...m.component.indexesOf(row)];\n H.resolve(fill(info.p.path + p.path.slice(s.path.length), idx), null);\n const hp = (H as any).rp as Pattern;\n const hr = (H as any).rr as StateRow | null;\n if (hp.depth > 0 && hr === null) return;\n across(m, info.e, () => touch(H, hp, hr, old, value, direct));\n}\n\n/**\n * The `written` / `getterReached` hook: a change in engine E crosses to the host it is mounted\n * on (a write, not a getter reached) and to the components mounted on it. A write does not come\n * back to the engines it is crossing from; a getter reached does — it only invalidates, and the\n * components a write started in read the host's getters too.\n */\nexport function crossed(E: Engine, p: Pattern, row: StateRow | null, old: unknown, value: unknown, direct: boolean, reached: boolean): void {\n if (registered === 0) return;\n const was = active.has(E);\n active.add(E);\n try {\n const m = mounts.get(E);\n if (!reached && m !== undefined && m.registered && !active.has(m.host.engine!)) up(m, p, row, old, value, direct);\n if (reached && m !== undefined && m.registered && m.exports !== null) exportReached(m, p);\n const byP = index.get(E);\n if (byP === undefined) return;\n for (const [q, byRow] of byP) {\n if (p.isUnder(q)) {\n const set = byRow.get(q.depth === 0 ? null : rowAt(row, q.depth));\n if (set !== undefined) for (const slot of [...set]) if (reaches(slot, reached)) into(slot, q, p, row, old, value, direct);\n } else if (q.isUnder(p)) {\n for (const [r, set] of [...byRow]) {\n if (p.depth !== 0 && rowAt(r, p.depth) !== row) continue;\n for (const slot of [...set]) if (reaches(slot, reached)) refresh(slot);\n }\n }\n }\n } finally {\n if (!was) active.delete(E);\n }\n}\n\nasync function start(el: HTMLElement, host: Element, root: Node, state: Record<string, any>, built: () => void): Promise<void> {\n if (state === UNWIRED) return;\n // the add-ons its `$features` names, before anything reads the host's current mount\n const loading = loadFeatures(state);\n if (loading) await loading;\n const h = hosts.get(host)!;\n // a mounted engine is never \"mounting\": its `$recursion` would run half set up — refused, as in a volume\n if (h.engine && state.$recursion) {\n raiseError(`[wcs/mount-dollar-declaration] <${host.localName}>: $recursion is not run in a mounted component — declare it on the root state.`);\n }\n const old = h.current;\n if (old !== null && old.el !== el && old.el.isConnected) {\n raiseError(`<${host.localName}> already has a connected <${config.tagNames.state} bind-component=\"${h.prop}\">.`);\n }\n if (old !== null) register(old, false);\n if (old !== null && takesOver(old, el, root)) return resume(old, el, root, built);\n const C = new Engine(state, new DirtyStrategy());\n C.element = el;\n (el as any).engine = C;\n bindMethods(C, state);\n const m: Mount = { el, nodes: [], component: C, host: h, slots: [], synth: new Map(), registered: false, skip: null, from: null, exports: null };\n for (const e of h.entries) m.slots.push({ m, e });\n h.current = m;\n mounts.set(C, m);\n const independent = h.engine === null;\n if (!independent) {\n wire(m);\n register(m, true);\n // the volumes in it are refused (graft), those that loaded first and those that load later\n wired.add(C);\n rootEngineCreated(C, root);\n } else {\n hooks.element?.(C, \"mounting\");\n }\n // a Light DOM component in a server-rendered page takes the server's nodes of its content (F33)\n const adopted = hooks.adoptScope?.(root, C);\n mount(C, root as ShadowRoot | Element);\n adopted?.();\n m.nodes = [...root.childNodes];\n drainBinds();\n if (independent) C.watchRendered();\n Object.defineProperty(host, h.prop, { configurable: true, enumerable: true, get: () => C.proxy });\n const ready = (host as any).$stateReadyCallback;\n if (typeof ready === \"function\") {\n try {\n const r = ready.call(host, h.prop);\n if (r !== null && typeof r === \"object\" && typeof r.then === \"function\") r.then(undefined, report);\n } catch (e) {\n report(e);\n }\n }\n // the bindings are built: what waits for them goes on, whatever $connectedCallback does (as a root)\n built();\n // taken out while it initialized: it hears the host, and runs `$connectedCallback`, when it is back\n if (!el.isConnected) {\n register(m, false);\n return;\n }\n await C.callHook(\"$connectedCallback\");\n if (independent && el.isConnected) hooks.element?.(C, \"connected\");\n}\n\n/**\n * Whether a new `<wcs-state bind-component>` takes the scope of the old mount `o` over (resume)\n * instead of binding its root afresh: when nodes the old engine bound or rendered are still in the\n * root (it swapped only its `<wcs-state>`). A kept `<style>`, whitespace or other nodes without\n * bindings do not count: content rendered again, its `<wcs-state>` included, is bound afresh. Nodes\n * with bindings added since next to kept bound ones (the old engine cannot take them, a new one\n * cannot take the kept ones) are reported.\n */\nfunction takesOver(o: Mount, el: Node, root: Node): boolean {\n // (a `<wcs-state>` in another root of the host finds none of the old nodes there)\n const C = o.component;\n const attr = `[${config.bindAttributeName}]`;\n const binds = (n: Node): boolean => n.nodeType === 1 && ((n as Element).matches(attr) || (n as Element).querySelector(attr) !== null);\n // the root's children the old engine binds or rendered\n const kept = new Set<Node>();\n const top = (n: Node | null): void => {\n while (n !== null && n.parentNode !== root) n = n.parentNode;\n if (n !== null) kept.add(n);\n };\n const range = (v: { headAt(n: Node): Node | null }, anchor: Node): void => {\n for (let n = v.headAt(anchor); n !== null && n !== anchor; n = n.nextSibling) top(n);\n top(anchor);\n };\n for (const bs of C.rootBindings.values()) {\n for (const b of bs) {\n if (b.chain === null) top(b.node);\n else for (const br of b.chain.branches) range(b.chain, br.anchor);\n }\n }\n for (const l of C.rootLists.values()) for (const v of [l.view, ...(l.extra ?? [])]) if (v !== null) range(v, v.anchor);\n for (const n of o.nodes) if (n.parentNode === root && binds(n)) kept.add(n);\n if (kept.size === 0) return false;\n const added = [...root.childNodes].filter((n) => n !== el && !kept.has(n) && !o.nodes.includes(n)\n && (binds(n) || (C.mustache && n.textContent!.includes(\"{{\"))));\n if (added.length > 0) {\n console.warn(`[@wcstack/state] <${o.host.el.localName}>: ${added.length} node(s) added beside the content taken over are not bound.`);\n }\n return true;\n}\n\n/**\n * A new `<wcs-state bind-component>` over the content the old one bound (a component that swapped only\n * its `<wcs-state>`): it takes the scope over, as a reconnection — the old engine's bindings, rows and\n * `{{ }}` anchors are on these nodes. Walking them again would bind nothing (an element walked once is\n * left alone) and read the text the bindings rendered as markup (3.x #417 / #419). Nodes with bindings\n * added since are not bound (takesOver reports them).\n */\nasync function resume(m: Mount, el: HTMLElement, root: Node, built: () => void): Promise<void> {\n // the old element lets go of the engine (its createState no longer reaches the scope)\n (m.el as any).engine = null;\n m.el = el;\n m.component.element = el;\n (el as any).engine = m.component;\n m.nodes = m.nodes.filter((n) => n.parentNode === root);\n // (taken out while it initialized: it hears the host when it is back, as a mount does)\n if (el.isConnected) await reconnect(m, built);\n else built();\n}\n\n/**\n * A mount connected again (or taken over, resume): it hears the host from now on, then\n * `$connectedCallback` — after `built`, for a take-over (getBindingsReady goes on as for a mount).\n */\nasync function reconnect(m: Mount, built?: () => void): Promise<void> {\n register(m, true);\n for (const slot of m.slots) refresh(slot);\n built?.();\n if (m.broken) return;\n // (async: a `$connectedCallback` that throws rejects, as one that rejects does)\n await m.component.callHook(\"$connectedCallback\");\n if (m.host.engine === null && m.el.isConnected) hooks.element?.(m.component, \"connected\");\n}\n\n/** `<wcs-state bind-component=\"prop\">`: claimed instead of becoming a root of its page. */\nexport function claimComponent(el: HTMLElement, root: Node): Claimed | null {\n const prop = el.getAttribute(\"bind-component\");\n // the last claim: a `<wcs-state>` neither a volume nor a DCC definition nor a component is a root\n if (prop === null) return watchRoot(el, root);\n const parent = el.parentNode;\n const shadow = parent instanceof ShadowRoot;\n const host = shadow ? (parent as ShadowRoot).host : parent instanceof Element ? parent : null;\n /** Its mount, from the moment it is made (`$connectedCallback` may still run, or have thrown); null once another `<wcs-state>` took it over. */\n const mine = (): Mount | null => {\n const m = host === null ? undefined : hosts.get(host)?.current;\n return m?.el === el ? m : null;\n };\n // a component that does not mount: the volumes in its shadow root have no tree to graft onto\n const failed = (e: unknown): never => {\n if (shadow) orphan(parent!, el);\n throw e;\n };\n /** Its bindings were built (it mounted, or took a scope over). */\n let bound = false;\n return {\n load() {\n return (host === null || !host.localName.includes(\"-\")\n ? Promise.reject(new Error(`[@wcstack/state] \"bind-component\" requires <${config.tagNames.state}> to be a direct child of a custom element.`))\n : load(el, prop, host, !shadow)).catch(failed);\n },\n async start(state, built) {\n await start(el, host!, shadow ? parent! : host!, state, () => {\n bound = true;\n built();\n }).catch((e) => {\n // (one whose `$connectedCallback` failed is an ordinary mount)\n const m = mine();\n if (!bound && m !== null) m.broken = true;\n return failed(e);\n });\n },\n connected() {\n // a failed `$connectedCallback` is reported as a root's on reconnect is\n const m = mine();\n if (m !== null) reconnect(m).catch(report);\n // a newer `<wcs-state>` took the scope over: put back where it was, this one takes the scope over\n // again, as a new one would — once the DOM operation that put it back is done (it may take the\n // newer one out), and refused while the newer one is still in\n else if (bound) {\n void Promise.resolve().then(() => {\n if (el.parentNode === parent) return start(el, host!, shadow ? parent! : host!, hosts.get(host!)!.state, () => {});\n }).catch(report);\n }\n // still waiting for its host's wiring: the host is back (wireLate)\n else if (waiting.has(host!)) wireLate(host!);\n },\n disconnected() {\n const m = mine();\n if (m === null) return;\n register(m, false);\n if (m.broken) return;\n m.component.callHook(\"$disconnectedCallback\");\n if (m.host.engine === null) hooks.element?.(m.component, \"disconnected\");\n },\n reset() {\n raiseError(`re-setting a component's state is not supported: write <${host?.localName}>.${prop} instead.`);\n },\n };\n}\n","/**\n * The scopes add-on (@wcstack/state/features/scopes): `<wcs-state>` elements that are not roots.\n * Volumes (`<wcs-state mount=\"p\">`, src/scopes/volume.ts), Declarative Custom Components\n * (`[data-wc-definition]`, src/scopes/dcc.ts) and component mounts (`<wcs-state\n * bind-component>`, src/scopes/component.ts).\n */\nimport { chain, first, handled, hooks, taken, type Feature } from \"../hooks\";\nimport { raiseError } from \"../parser/raiseError\";\nimport { claimVolume, grafted, guardAncestorWrite, rootEngineCreated, rootMoved } from \"../scopes/volume\";\nimport { claimDcc, dccEngineCreated, dccWritten } from \"../scopes/dcc\";\nimport { claimComponent, componentScope, crossed, guardReadonlyMount, hasMounts, hostBinding } from \"../scopes/component\";\n\nexport const scopes: Feature = {\n name: \"scopes\",\n hooks,\n install(): void {\n hooks.claim = first(taken, hooks.claim, claimVolume);\n hooks.claim = first(taken, hooks.claim, claimDcc);\n // last: what it does not take is a root, which it watches for the volumes (watchRoot)\n hooks.claim = first(taken, hooks.claim, claimComponent);\n hooks.hostBinding = hostBinding;\n hooks.componentScope = componentScope;\n hooks.element = chain(hooks.element, (engine, phase) => {\n if (phase !== \"mounting\") return rootMoved(engine, phase);\n const root = (engine.element as Node).getRootNode();\n rootEngineCreated(engine, root);\n dccEngineCreated(engine, root);\n });\n hooks.written = chain(hooks.written, (engine, p, row, old, value, direct) => {\n dccWritten(engine, p, value, direct);\n crossed(engine, p, row, old, value, direct, false);\n });\n hooks.getterReached = chain(hooks.getterReached, (engine, g, row) => crossed(engine, g, row, undefined, undefined, false, true));\n hooks.beforeWrite = first(handled, hooks.beforeWrite, (engine, p, _row, _value, element) => {\n guardAncestorWrite(engine, p);\n return guardReadonlyMount(engine, p, element);\n });\n // first, before what is installed (in any order) replaces its runtime for the new state:\n // a refused re-set leaves the old state, its watches, streams and keys as they were\n const declared = hooks.declare;\n hooks.declare = (engine, target) => {\n const list = grafted.get(engine);\n if (list !== undefined && list.length > 0) {\n raiseError(`re-setting a root state with grafted volumes (${list.map((v) => v.path).join(\", \")}) is not supported: their data is part of the tree.`);\n }\n if (hasMounts(engine)) raiseError(\"re-setting a root state with mounted components is not supported: they read its data.\");\n declared?.(engine, target);\n };\n },\n};\nexport default scopes;\n","/**\n * Recursive paths (README \"Recursive paths\"): one self-recursive anchor per state,\n * `$recursion: { \"nodes.*\": \"children.*\" }`, and `**` as a depth variable — `nodes.**.x` stands\n * for `nodes.*.x`, `nodes.*.children.*.x`, … The engine only ever sees the concrete depths:\n *\n * - a getter `get \"nodes.**.total\"()` is a family, materialized as an ordinary getter on each\n * concrete depth's pattern when that pattern is made (so `$1`, caching and dependencies are the\n * ordinary per-depth ones, and a deep change reaches every ancestor through ordinary edges);\n * - `**` in a path read or `$getAll(path)` without indexes is bound to the depth of the row the\n * evaluation runs in (a family getter's row, a row getter's, an event handler's);\n * - `$getAll(path, [])` collects every depth (depth first, pre-order), `$setAll(path, [], v)`\n * writes every node; the expansions of a family are read-only.\n *\n * The engines with a `$recursion` get their `onPatternCreated`, `resolve`, `getAll` and `setAll`\n * wrapped; an engine without one pays nothing. The static checks of 3.3 (colliding families,\n * structural suffixes on getters) are the diagnostics add-on's (approved simplification).\n */\nimport type { Engine } from \"../engine\";\nimport type { Pattern } from \"../pattern\";\nimport type { StateRow } from \"../list\";\nimport { raiseError } from \"../parser/raiseError\";\nimport { raise, M } from \"../messages\";\nimport { recursionUnsupported } from \"../parser/parseStatePart\";\n\nconst NAME = \"$recursion\";\nconst MAX_DEPTH = 128;\n\ninterface Spec {\n /** `nodes` (the anchor without its trailing `.*`). */\n readonly list: string;\n /** `.children.*` */\n readonly step: string;\n /** `children` */\n readonly key: string;\n /** Families by suffix (`.total`): the author's getter. */\n readonly families: Map<string, (this: unknown) => unknown>;\n readonly matchers: [RegExp, string][];\n /** Node list patterns: `nodes`, `nodes.*.children`, `nodes.*.children.*.children`, … */\n readonly nodeList: RegExp;\n /** The family key each materialized expansion belongs to. */\n readonly owners: Map<Pattern, string>;\n}\n\nconst specs = new WeakMap<Engine, Spec>();\nconst wrapped = new WeakSet<Engine>();\n/** Patterns created while the state's accessors are registered (the `**` keys among them are templates). */\nconst registering = new WeakSet<Engine>();\nlet engines = 0;\n\nconst esc = (s: string): string => s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\nconst code = (c: string) => `[wcs/recursion-${c}]`;\n\nfunction checkPath(kind: string, path: unknown): string {\n const bad = (why: string): never => raiseError(`${code(\"declaration-invalid\")} ${NAME} ${kind} \"${String(path)}\" ${why}`);\n if (typeof path !== \"string\" || path === \"\") raiseError(`${code(\"declaration-invalid\")} ${NAME} ${kind} must be a non-empty string.`);\n const segs = path.split(\".\");\n if (segs.length < 2 || segs[segs.length - 1] !== \"*\") bad('must end with \".*\" (a list element).');\n for (let i = 0; i < segs.length - 1; i++) {\n const s = segs[i];\n if (s === \"\") bad(\"must not contain empty path segments.\");\n if (s === \"*\" || s === \"**\" || /^\\d/.test(s)) bad('must have exactly one \"*\", at the end.');\n if (s.includes(\"#\")) bad('must not contain \"#\".');\n }\n if (path[0] === \"$\") bad('must not start with \"$\".');\n return path;\n}\n\n/** Reads and checks the declaration; null when the state has none. */\nfunction read(target: Record<string, any>): Spec | null {\n const decl = target[NAME];\n const keys: [string, PropertyDescriptor][] = [];\n const seen = new Set<string>();\n for (let o: object | null = target; o !== null && o !== Object.prototype; o = Object.getPrototypeOf(o)) {\n for (const k of Object.getOwnPropertyNames(o)) {\n if (!seen.has(k) && k.includes(\"**\")) keys.push([k, Object.getOwnPropertyDescriptor(o, k)!]);\n seen.add(k);\n }\n }\n if (decl === undefined) {\n if (keys.length > 0) recursionUnsupported(keys[0][0]);\n return null;\n }\n if (decl === null || typeof decl !== \"object\" || Array.isArray(decl)) {\n raiseError(`${code(\"declaration-invalid\")} ${NAME} must be an object mapping one anchor path to its repeating sub-path.`);\n }\n const entries = Object.entries(decl);\n if (entries.length !== 1) raiseError(`${code(\"declaration-invalid\")} ${NAME} must declare exactly one anchor (it declares ${entries.length}).`);\n const anchor = checkPath(\"anchor\", entries[0][0]);\n const repeat = checkPath(\"repeat\", entries[0][1]);\n const list = anchor.slice(0, -2);\n const key = repeat.slice(0, -2);\n const step = `.${repeat}`;\n const families = new Map<string, (this: unknown) => unknown>();\n const matchers: [RegExp, string][] = [];\n const head = `${list}.**`;\n for (const [k, d] of keys) {\n const suffix = k.slice(head.length);\n if (!k.startsWith(head) || (suffix !== \"\" && suffix[0] !== \".\") || suffix.includes(\"**\")) {\n raiseError(`[wcs/recursion-anchor] \"${k}\": a recursive key is \"${head}\" followed by a path (the anchor is \"${anchor}\").`);\n }\n if (suffix === \"\" || suffix.split(\".\").slice(1).some((s) => s === \"\")) raiseError(`[wcs/recursion-anchor] \"${k}\" needs a path after \"**\".`);\n if (d.get === undefined || d.set !== undefined) raiseError(`${code(\"declaration-invalid\")} \"${k}\": a recursive key is a getter without a setter.`);\n families.set(suffix, d.get);\n matchers.push([new RegExp(`^${esc(anchor)}((?:${esc(step)})*)${esc(suffix)}$`), suffix]);\n }\n return { list, step, key, families, matchers, owners: new Map(), nodeList: new RegExp(`^${esc(list)}((?:${esc(`.*.${key}`)})*)$`) };\n}\n\n/** `nodes.*` + `.children.*` × k */\nconst nodePath = (spec: Spec, k: number): string => `${spec.list}.*${spec.step.repeat(k)}`;\n\n/** The depth of the node row `row` is in or under (null: not under the anchor). */\nfunction depthOf(spec: Spec, row: StateRow | null): { k: number; row: StateRow } | null {\n for (let r = row; r !== null; r = r.list.parentRow) {\n const m = spec.nodeList.exec(r.list.pattern.path);\n if (m !== null) return { k: m[1].length / (spec.key.length + 3), row: r };\n }\n return null;\n}\n\n/** What follows `nodes.**` in a path (`.x`, or \"\" for the nodes themselves). */\nfunction suffixOf(spec: Spec, path: string): string {\n const head = `${spec.list}.**`;\n const rest = path.slice(head.length);\n if (!path.startsWith(head) || (rest !== \"\" && rest[0] !== \".\") || rest.includes(\"**\")) {\n raiseError(`[wcs/recursion-anchor] \"${path}\" does not start at the recursion anchor \"${spec.list}.*\".`);\n }\n return rest;\n}\n\n/** `nodes.**.x` → the concrete depth of the evaluation's row. */\nfunction bind(spec: Spec, path: string, ctx: StateRow | null): string {\n const rest = suffixOf(spec, path);\n const at = depthOf(spec, ctx);\n if (at === null) {\n raiseError(`[wcs/recursion-context] \"${path}\" uses \"**\", which is bound to the depth of the row it is evaluated in; there is none here — use $getAll(\"${path}\", []) for every depth.`);\n }\n return nodePath(spec, at.k) + rest;\n}\n\n/** Every node row, depth first and pre-order: (depth, row). Reads (and so tracks) each list. */\nfunction walk(engine: Engine, spec: Spec, visit: (k: number, row: StateRow) => void): void {\n const ancestors = new Set<unknown>();\n const seen = new Set<unknown>();\n const enter = (arr: unknown, listPath: string, k: number): boolean => {\n if (!Array.isArray(arr) || arr.length === 0) return false;\n if (ancestors.has(arr)) raiseError(`${code(\"cycle\")} \"${listPath}\" is reachable from itself: the data under \"${spec.list}\" must be a tree.`);\n if (seen.has(arr)) raiseError(`${code(\"shared-list\")} \"${listPath}\" is the same array instance as a list reached before: the data under \"${spec.list}\" must be a tree.`);\n if (k + 1 > MAX_DEPTH) raiseError(`${code(\"depth-exceeded\")} Recursion on \"${spec.list}.*\" reached depth ${k + 1} (the limit is ${MAX_DEPTH}).`);\n seen.add(arr);\n return true;\n };\n const down = (rows: StateRow[], k: number): void => {\n for (const row of rows) {\n visit(k, row);\n const listP = engine.pattern(`${nodePath(spec, k)}.${spec.key}`);\n const arr = engine.read(listP, row);\n if (!enter(arr, listP.path, k + 1)) continue;\n ancestors.add(arr);\n down(engine.childList(row, listP).rows, k + 1);\n ancestors.delete(arr);\n }\n };\n const rootP = engine.pattern(spec.list);\n const arr = engine.read(rootP, null);\n if (!enter(arr, spec.list, 0)) return;\n ancestors.add(arr);\n down(engine.childList(null, rootP).rows, 0);\n}\n\nfunction wrap(engine: Engine): void {\n wrapped.add(engine);\n const e = engine as any;\n const created = e.onPatternCreated;\n e.onPatternCreated = (p: Pattern) => {\n const spec = specs.get(engine);\n if (p.path.includes(\"**\")) {\n // a recursive key's own pattern while the accessors are registered: an inert template that\n // refuses to be read, and stays one when every pattern is looked at again (a volume grafting\n // its accessors, a re-set — one that drops `$recursion` forgets it: refused again); a new one\n // later is refused by the core (made patterns are interned after this runs)\n const known = engine.patterns.peek(p.path) === p;\n if (registering.has(engine) || (spec === undefined && known)) p.getter = () => recursionUnsupported(p.path);\n else if (!known) created.call(engine, p);\n return;\n }\n if (spec !== undefined && p.getter === null) {\n for (const [re, suffix] of spec.matchers) {\n if (!re.test(p.path)) continue;\n p.getter = spec.families.get(suffix)!;\n if (p.depth > 0) p.slot = e.slotCount++;\n spec.owners.set(p, spec.list + \".**\" + suffix);\n break;\n }\n }\n created.call(engine, p);\n };\n const resolve = e.resolve;\n e.resolve = (path: string, ctx: StateRow | null) => {\n const spec = specs.get(engine);\n return resolve.call(engine, spec !== undefined && path.includes(\"**\") ? bind(spec, path, ctx) : path, ctx);\n };\n const getAll = e.getAll;\n e.getAll = (path: string, indexes?: number[]) => {\n const spec = specs.get(engine);\n if (spec === undefined || !path.includes(\"**\")) return getAll.call(engine, path, indexes);\n if (indexes === undefined) return getAll.call(engine, bind(spec, path, e.ctx));\n if (!Array.isArray(indexes) || indexes.length > 0) {\n raiseError(`${code(\"getall-form\")} $getAll(\"${path}\", indexes) with \"**\" takes either no indexes (this depth) or [] (every depth).`);\n }\n const suffix = suffixOf(spec, path);\n const out: unknown[] = [];\n walk(engine, spec, (k, row) => {\n for (const v of getAll.call(engine, nodePath(spec, k) + suffix, engine.indexesOf(row))) out.push(v);\n });\n return out;\n };\n const setAll = e.setAll;\n e.setAll = (path: string, indexes: number[], value: unknown, options?: { spread?: boolean }) => {\n const spec = specs.get(engine);\n if (spec === undefined || !path.includes(\"**\")) return setAll.call(engine, path, indexes, value, options);\n // (the core's own messages where the core's $setAll has one)\n if (!Array.isArray(indexes)) raise(M.SetAllNeedsIndexes, [path]);\n if (indexes.length > 0) raiseError(`${code(\"setall-form\")} $setAll(\"${path}\", indexes, …) with \"**\" takes no partial prefix: pass [] to write every node.`);\n if (typeof value === \"function\" || options?.spread === true) raiseError(`${code(\"setall-form\")} $setAll(\"${path}\", [], value) with \"**\" takes a plain value (no mapper, no spread).`);\n if (e.readonlyDepth > 0) raise(M.Readonly);\n const suffix = suffixOf(spec, path);\n // the checks (3.x's): an index spelling is a `*` (`.children.0` is a child node), and a child\n // node's path is a node's (`.children.*.total` is the family `.total` one level down)\n let rest = suffix.replace(/\\.\\d+(?=\\.|$)/g, \".*\");\n while (rest.startsWith(spec.step)) rest = rest.slice(spec.step.length);\n // the structure: a node, the objects on the way to its child list and the list, the list's length\n const segs = spec.key.split(\".\");\n if (rest === \"\" || rest === `.${spec.key}.length` || segs.some((_, i) => rest === `.${segs.slice(0, i + 1).join(\".\")}`)) {\n raiseError(`${code(\"structural-write\")} \"${path}\" writes the recursion structure itself (a node, its \"${spec.key}\" list or that list's length, or an object on the way to it).`);\n }\n for (const s of spec.families.keys()) {\n // (a family under a child node, `.children.*.x`, is `.x` at every depth below the first: refused\n // before anything is written, not part-way through)\n let f = s;\n while (f.startsWith(spec.step)) f = f.slice(spec.step.length);\n if (rest === f || rest.startsWith(`${f}.`)) raiseError(`${code(\"readonly\")} \"${path}\" writes into the recursive getter \"${spec.list}.**${s}\".`);\n }\n // every node first: a tree that fails the walk writes nothing\n const nodes: [number, StateRow][] = [];\n walk(engine, spec, (k, row) => nodes.push([k, row]));\n let written = 0;\n for (const [k, row] of nodes) written += setAll.call(engine, nodePath(spec, k) + suffix, engine.indexesOf(row), value);\n return written;\n };\n}\n\n/** The `declare` hook: a state received (construction, or a re-set before it replaces the old one). */\nexport function declareRecursion(engine: Engine, target: Record<string, any>): void {\n const spec = read(target);\n const had = specs.has(engine);\n if (spec === null) {\n if (had) {\n specs.delete(engine);\n engines--;\n }\n return;\n }\n if (!had) engines++;\n specs.set(engine, spec);\n registering.add(engine);\n if (!wrapped.has(engine)) wrap(engine);\n}\n\n/** The `element` hook: the state's accessors are registered — a new `**` pattern is refused again. */\nexport function recursionSettled(engine: Engine): void {\n registering.delete(engine);\n}\n\n/** The `beforeWrite` hook: an expansion of a recursive getter is read-only. */\nexport function guardExpansion(engine: Engine, p: Pattern): boolean {\n if (engines === 0) return false;\n const spec = specs.get(engine);\n if (spec === undefined) return false;\n for (let q: Pattern | null = p; q !== null; q = q.parent) {\n const owner = spec.owners.get(q);\n if (owner !== undefined) raiseError(`${code(\"readonly\")} \"${p.path}\" writes into the recursive getter \"${owner}\".`);\n }\n return false;\n}\n","/**\n * The recursion add-on (@wcstack/state/features/recursion): `$recursion` and `**` — see\n * src/recursion/recursion.ts.\n */\nimport { chain, first, handled, hooks, type Feature } from \"../hooks\";\nimport { declareRecursion, guardExpansion, recursionSettled } from \"../recursion/recursion\";\n\nexport const recursion: Feature = {\n name: \"recursion\",\n hooks,\n install(): void {\n hooks.declare = chain(hooks.declare, declareRecursion);\n hooks.element = chain(hooks.element, (engine, phase) => {\n if (phase === \"mounting\" || phase === \"reset\") recursionSettled(engine);\n });\n hooks.beforeWrite = first(handled, hooks.beforeWrite, guardExpansion);\n },\n};\nexport default recursion;\n","import pkg from \"../package.json\" with { type: \"json\" };\n\n/** The package version: stamped into `<wcs-ssr>`, compared on hydration (major.minor), shown by DevTools. */\nexport const VERSION: string = pkg.version;\n","{\n \"name\": \"@wcstack/state\",\n \"version\": \"4.10.0\",\n \"description\": \"Reactive state management with declarative data binding for Web Components. Zero dependencies, buildless.\",\n \"type\": \"module\",\n \"main\": \"./dist/index.esm.js\",\n \"module\": \"./dist/index.esm.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.esm.js\"\n },\n \"./auto\": {\n \"types\": \"./dist/auto.d.ts\",\n \"import\": \"./dist/auto.min.js\"\n },\n \"./core\": {\n \"types\": \"./dist/split/core.d.ts\",\n \"import\": \"./dist/split/core.js\"\n },\n \"./features/*\": {\n \"types\": \"./dist/split/features/*.d.ts\",\n \"import\": \"./dist/split/features/*.js\"\n },\n \"./define\": {\n \"types\": \"./dist/define.d.ts\",\n \"import\": \"./dist/define.js\"\n },\n \"./manifest\": {\n \"types\": \"./dist/manifest.d.ts\",\n \"import\": \"./dist/manifest.esm.js\"\n },\n \"./parser\": {\n \"types\": \"./dist/parser.d.ts\",\n \"import\": \"./dist/parser.esm.js\"\n },\n \"./wcs-manifest.json\": \"./dist/wcs-manifest.json\"\n },\n \"files\": [\n \"dist\",\n \"!dist/core.min.js\"\n ],\n \"scripts\": {\n \"clean\": \"node -e \\\"require('node:fs').rmSync('dist', { recursive: true, force: true })\\\"\",\n \"build\": \"node build.mjs\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\",\n \"lint\": \"eslint src\",\n \"typecheck\": \"tsc --noEmit\",\n \"golden\": \"node scripts/golden.mjs\",\n \"version:patch\": \"npm version patch\",\n \"version:minor\": \"npm version minor\",\n \"version:major\": \"npm version major\",\n \"prepublishOnly\": \"npm run build && npm run test:coverage\"\n },\n \"keywords\": [\n \"web-components\",\n \"state-management\",\n \"reactive\",\n \"data-binding\",\n \"proxy\",\n \"custom-elements\",\n \"shadow-dom\",\n \"buildless\",\n \"zero-dependencies\",\n \"declarative\"\n ],\n \"author\": \"mogera551\",\n \"homepage\": \"https://wcstack.github.io\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/wcstack/wcstack.git\",\n \"directory\": \"packages/state\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/wcstack/wcstack/issues\"\n },\n \"license\": \"MIT\",\n \"devDependencies\": {\n \"@eslint/js\": \"^9.39.5\",\n \"@vitest/coverage-v8\": \"^4.1.11\",\n \"esbuild\": \"0.27.2\",\n \"eslint\": \"^9.39.5\",\n \"globals\": \"^16.5.0\",\n \"happy-dom\": \"^20.0.11\",\n \"rollup\": \"^4.63.5\",\n \"rollup-plugin-dts\": \"^6.5.1\",\n \"terser\": \"^5.51.2\",\n \"typescript\": \"^5.9.3\",\n \"typescript-eslint\": \"^8.70.1\",\n \"vitest\": \"^4.0.15\"\n }\n}\n","/**\n * `<wcs-ssr>` (`config.tagNames.ssr`): the server's snapshot before a `<wcs-state enable-ssr>` —\n * `version`, the state's data (a JSON `<script>`) and the page-level templates. The SSR add-on\n * defines the tag; this class only reads the snapshot (the add-on hydrates from it and removes it).\n */\nimport { config } from \"../config\";\nimport { VERSION } from \"../version\";\nimport { HTMLElementBase } from \"../element\";\n\nexport interface ISsrElement {\n /** The @wcstack/state version that rendered the page. */\n readonly version: string;\n /** The state's data the server rendered with. */\n readonly stateData: Record<string, any>;\n /** The page-level templates, by id. */\n readonly templates: Map<string, HTMLTemplateElement>;\n /** Always empty: every binding is applied when the client adopts the server's DOM (3.x kept a value table here). */\n readonly hydrateProps: Record<string, Record<string, unknown>>;\n getTemplate(id: string): HTMLTemplateElement | null;\n /** The snapshot is adoptable: the same major.minor as this build. */\n verifyVersion(): boolean;\n}\n\n/** `4.0.1` → `4.0`: a snapshot is adoptable by the same major.minor. */\nexport const majorMinor = (v: string): string => v.split(\".\").slice(0, 2).join(\".\");\n\nexport class Ssr extends HTMLElementBase implements ISsrElement {\n /** The first snapshot element under `root`, or null. */\n static find(root: Node): ISsrElement | null {\n return ((root as ParentNode).querySelector?.(config.tagNames.ssr) as Ssr | null) ?? null;\n }\n\n get version(): string {\n return this.getAttribute(\"version\") ?? \"\";\n }\n\n get stateData(): Record<string, any> {\n const script = this.querySelector('script[type=\"application/json\"]');\n return script === null ? {} : JSON.parse(script.textContent || \"{}\");\n }\n\n get templates(): Map<string, HTMLTemplateElement> {\n const map = new Map<string, HTMLTemplateElement>();\n // quoted: `children` is an internal name the bundles shorten (mangle.mjs)\n for (const t of Array.from(this[\"children\"])) if (t.localName === \"template\") map.set(t.id, t as HTMLTemplateElement);\n return map;\n }\n\n get hydrateProps(): Record<string, Record<string, unknown>> {\n return {};\n }\n\n getTemplate(id: string): HTMLTemplateElement | null {\n return this.templates.get(id) ?? null;\n }\n\n verifyVersion(): boolean {\n return majorMinor(this.version) === majorMinor(VERSION);\n }\n}\n\n/** Defines `<wcs-ssr>` in `registry` (once per registry). */\nexport function defineSsr(registry: CustomElementRegistry): void {\n const tag = config.tagNames.ssr;\n if (registry.get(tag) === undefined) registry.define(tag, class extends Ssr {});\n}\n","/**\n * Server-side rendering with @wcstack/server (README \"Server-Side Rendering\"), for\n * `<wcs-state enable-ssr>` roots.\n *\n * Server (`<html data-wcs-server>`): the page renders as usual; the snapshot builder\n * (`Symbol.for(\"wcstack.ssr.snapshotBuilder\")`, called by the server before it serializes)\n * then makes the DOM adoptable:\n * - every view's rows / branch move right after its anchor, between `<!--wcs-[-->` and\n * `<!--wcs-]-->`, each row opened by `<!--wcs-|-->` (a branch region carries its index,\n * `<!--wcs-[:i-->`, and follows the chain's last anchor so the chain's templates stay adjacent);\n * - a page-level anchor becomes `<!--wcs-p:ID-->`, its template kept in `<wcs-ssr>` as\n * `<template id=ID>`; a page-level text binding (a mustache, a comment binding) is wrapped in\n * `<!--wcs-t:EXPR-->…<!--wcs-/t-->` (the client puts a comment binding back);\n * - adjacent text nodes are separated (`<!--wcs-s-->`) and empty ones kept (`<!--wcs-e-->`), so\n * parsing the HTML gives back the rows' exact structure;\n * - `<wcs-ssr version>` before the element holds the state's data (JSON) and the templates.\n *\n * Client: before the page is bound, the texts and templates are restored and the regions read where\n * they are (their marks go; the page's walk passes their nodes by); each block the engine builds\n * takes its region's next row instead of a clone (a row's nested regions wait for its nested views\n * in turn). The server's nodes never leave the page — no custom element in a row or a branch is\n * disconnected — and get their bindings; a view's anchors move after its rows instead. A row that\n * does not fit its plan is built anew in its place, and the rows no view took go once the page is\n * bound. `$connectedCallback` does not run (the server ran it).\n *\n * A snapshot of another major.minor is discarded, and the page renders on the client as it would\n * without a server: the state comes from its own source, `$connectedCallback` runs, and the server's\n * rows and marks give way to the templates they came from — those of @wcstack/server 3.x's output\n * too (`legacy`). They give way only once the page was planned on a copy: markup this client cannot\n * plan fails its initialization with the server's HTML left as it was.\n *\n * Not carried over from @wcstack/state 3.3 (approved): the inline snapshot for servers without\n * the builder protocol, and the property value table (every binding is applied on adoption).\n */\nimport type { Engine } from \"../engine\";\nimport { ForView, type Block, type IfView, type RowPlan, type Spec } from \"../dom/view\";\nimport { config } from \"../config\";\nimport { hooks } from \"../hooks\";\n\nimport { VERSION } from \"../version\";\nimport { isOuter, setsContent, templateContent, textSpec, walkBindings, walked } from \"../dom/plan\";\nimport { majorMinor } from \"./element\";\nimport { parseBindTextsForElement } from \"../parser/parseBindTextsForElement\";\n/** The snapshot element's tag (`config.tagNames.ssr`, `wcs-ssr` by default). */\nconst tag = (): string => config.tagNames.ssr;\nconst BUILDER = Symbol.for(\"wcstack.ssr.snapshotBuilder\");\n\nexport const isServer = (): boolean => document.documentElement?.hasAttribute(\"data-wcs-server\") === true;\n\nconst mark = (data: string): Comment => document.createComment(data);\nconst isMark = (n: Node | null, data: string): boolean => n !== null && n.nodeType === 8 && (n as Comment).data === data;\nconst startsMark = (n: Node | null, prefix: string): boolean => n !== null && n.nodeType === 8 && (n as Comment).data.startsWith(prefix);\n\n// ---------------------------------------------------------------- server\n\n/** Page-level anchors (the walker's) and the template each replaced, by engine. */\nconst anchors = new WeakMap<Engine, Map<Node, Element>>();\n/** The engines that recorded anchors in a page (its root node): the page's, and its Light DOM components'. */\nconst enginesByRoot = new WeakMap<Node, Set<Engine>>();\n/**\n * The custom elements the page's walker bound, with the nodes in them then (and a text's data): the\n * walk is post-order, so its anchors, text marks and rows are there, and the element's own bindings\n * have not written yet. What an element renders from a value comes later: in the server's HTML the\n * client would walk it as the page's markup (a user's `{{ … }}`, a `data-wcs` in sanitized HTML),\n * so the snapshot leaves it — and a text with `{{` that it was not then (a value's, in a node of\n * its own or one the page wrote) — to the client.\n */\nconst kept = new WeakMap<Node, Map<Node, string>>();\n/** What the client does not walk: a region (rows it adopts), an element whose content a binding sets. */\nconst skip = new WeakSet<Node>();\n/**\n * Mustache texts: their expressions. In an element whose content is text (`<textarea>`, `<title>`),\n * a mark would be text to the browser, and the value the client's markup: the element takes its\n * template along instead (`data-wcs-raw`), and the client puts it back before binding the page.\n */\nconst rawTexts = new WeakMap<Node, string>();\n\n/** Nodes from `from` to `to`, siblings, inclusive. */\nfunction range(from: Node, to: Node): Node[] {\n const out: Node[] = [];\n for (let n: Node | null = from; n !== null; n = n.nextSibling) {\n out.push(n);\n if (n === to) break;\n }\n return out;\n}\n\n/** `to` with `from`'s attributes, and `content` (into a template's content when it has one). */\nfunction attrs<T extends Element>(from: Element, to: T, ...content: Node[]): T {\n for (const a of Array.from(from.attributes)) to.setAttribute(a.name, a.value);\n ((to as unknown as HTMLTemplateElement).content ?? to).append(...content);\n return to;\n}\n\nconst lastOf = (b: Block): Node => (b.nodes === null ? b.first : b.nodes[b.nodes.length - 1]);\n\n/**\n * The anchor `<wcs-link>` (@wcstack/router) renders right after itself, its children moved into it:\n * the server's is marked `data-wcs-ssr-link`, and is the link's `anchorElement` once the router took\n * it (dropping the mark). In a row it is the link's: the link's children are there.\n */\nconst beside = (n: Node): Node | null => {\n const a = n.nextSibling as Element | null;\n return n.nodeType === 1 && a?.localName === \"a\" && (a.hasAttribute(\"data-wcs-ssr-link\") || (n as any).anchorElement === a) ? a : null;\n};\n\n/**\n * Makes the blocks one region right after the anchors `from` … `to` (a view renders its blocks before\n * its anchor; a branch before its own, the chain's later anchors after it). The anchors move, not the\n * blocks: a custom element in a row is not disconnected, so what it rendered as it connected stays\n * (`<wcs-link>` renders its anchor a microtask later, and would not again before the server serializes).\n */\nfunction region(from: Node, to: Node, blocks: Block[], branch: number | null): void {\n const open = mark(branch === null ? \"wcs-[\" : `wcs-[:${branch}`);\n const close = mark(\"wcs-]\");\n if (blocks.length > 0) (blocks[0].head() as ChildNode).before(...range(from, to));\n (to as ChildNode).after(open);\n for (const b of blocks) if (branch === null) b.head().before(mark(\"wcs-|\"));\n const last = blocks.length > 0 ? lastOf(blocks[blocks.length - 1]) : open;\n ((beside(last) ?? last) as ChildNode).after(close);\n for (const n of range(open, close)) skip.add(n);\n}\n\nfunction visitView(v: ForView | IfView): void {\n if (v instanceof ForView) {\n region(v.anchor, v.anchor, v.rowViews, null);\n for (const b of v.rowViews) visitBlock(b);\n return;\n }\n const cur = v.current;\n if (cur === null) return;\n region(v.branches[v.index].anchor, v.branches[v.branches.length - 1].anchor, [cur], v.index);\n visitBlock(cur);\n}\n\nfunction visitBlock(b: Block): void {\n if (b.children !== null) for (const c of b.children) visitView(c);\n}\n\nconst RAW = new Set([\"script\", \"style\", \"template\", \"textarea\", \"title\"]);\nconst RAW_ATTR = \"data-wcs-raw\";\nconst raw = (el: Element): boolean => RAW.has(el.localName) || el.localName === tag();\n\n/** Keeps every text node a text node through HTML serialization and parsing. */\nfunction protectTexts(parent: Node): void {\n for (const n of Array.from(parent.childNodes)) {\n if (n.nodeType === 3) {\n if ((n as Text).data === \"\") n.replaceWith(mark(\"wcs-e\"));\n else if (n.nextSibling !== null && n.nextSibling.nodeType === 3) n.after(mark(\"wcs-s\"));\n } else if (n.nodeType === 1 && !raw(n as Element)) {\n protectTexts(n);\n }\n }\n}\n\nfunction json(value: unknown): string {\n return JSON.stringify(value).replace(/[<>&\\u2028\\u2029]/g, (c) => `\\\\u${c.charCodeAt(0).toString(16).padStart(4, \"0\")}`);\n}\n\n/** The state's own data (no `$` keys, no accessors, no functions). */\nfunction data(target: Record<string, any>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(target)) {\n if (key[0] === \"$\") continue;\n const d = Object.getOwnPropertyDescriptor(target, key)!;\n if (d.get !== undefined || d.set !== undefined || typeof d.value === \"function\") continue;\n out[key] = d.value;\n }\n return out;\n}\n\nlet ids = 0;\n\nfunction snapshot(el: Element, engine: Engine): void {\n const root = el.getRootNode() as Document | ShadowRoot;\n // the page's engine, and those of the Light DOM components in it: their walkers' anchors are in\n // the page too (a Shadow DOM component's are in its own shadow root)\n const engines = [engine];\n for (const E of enginesByRoot.get(root) ?? []) {\n if (E !== engine && (E.element as Element | null)?.hasAttribute(\"bind-component\") === true) engines.push(E);\n }\n const map = new Map<Node, Element>();\n for (const E of engines) {\n const own = anchors.get(E);\n if (own === undefined) continue;\n // the views the walker made, top down (a nested view's region stays inside its row's)\n const byAnchor = new Map<Node, ForView | IfView>();\n for (const l of E.rootLists.values()) {\n if (l.view !== null) byAnchor.set(l.view.anchor, l.view);\n if (l.extra !== null) for (const v of l.extra) byAnchor.set(v.anchor, v);\n }\n for (const bs of E.rootBindings.values()) {\n for (const b of bs) if (b.chain !== null) for (const br of b.chain.branches) byAnchor.set(br.anchor, b.chain);\n }\n const done = new Set<ForView | IfView>();\n for (const [anchor, template] of own) {\n map.set(anchor, template);\n const v = byAnchor.get(anchor);\n if (v !== undefined && !done.has(v) && anchor.isConnected) {\n done.add(v);\n visitView(v);\n }\n }\n }\n for (const h of Array.from(root.querySelectorAll(\"*\"))) {\n const own = kept.get(h);\n if (own !== undefined) {\n // what the client does not walk is left: what `skip` has, and — the page's — a Light DOM\n // component (bound later, by its own engine). A text without `{{` is no markup to the client,\n // whoever wrote it; one the page wrote is left as it was written, and a mustache's where the\n // client puts its expression back: right after its mark (the client replaces what follows it),\n // or in a text element (`data-wcs-raw`). Elsewhere it goes: an element may drop comments, or\n // move a text element's text out, and its value would be the client's markup\n const w = document.createTreeWalker(h, 133, {\n acceptNode: (n) => (skip.has(n) || (n.nodeType === 1 && own.has(n) && scoped(n as Element)) ? 2 : 1),\n });\n const out: ChildNode[] = [];\n for (let n = w.nextNode(); n !== null; n = w.nextNode()) {\n const p = n.previousSibling!;\n if (n.nodeType === 3\n ? (n as Text).data.includes(\"{{\")\n && !(raw(n.parentNode as Element) ? rawTexts.has(n) : own.has(p) && startsMark(p, \"wcs-t:\"))\n && (rawTexts.has(n) || own.get(n) !== (n as Text).data)\n : !own.has(n)) out.push(n as ChildNode);\n }\n for (const n of out) n.remove();\n }\n const cs = Array.from(h.childNodes);\n if (raw(h) && cs.some((c) => rawTexts.has(c))) {\n // (a comment there — a server's DOM may parse one in a <textarea> — is text to a browser)\n h.setAttribute(RAW_ATTR, cs.map((c) => (rawTexts.has(c) ? `{{ ${rawTexts.get(c)} }}` : c.nodeType === 8 ? `<!--${(c as Comment).data}-->` : c.textContent)).join(\"\"));\n }\n }\n protectTexts(root.nodeType === 9 ? (root as Document).body : root);\n const ssr = document.createElement(tag());\n ssr.setAttribute(\"version\", VERSION);\n const script = document.createElement(\"script\");\n script.type = \"application/json\";\n script.textContent = json(data(engine.target));\n ssr.append(script);\n for (const [anchor, template] of map) {\n if (!anchor.isConnected) continue;\n // the anchor's context, by name (a server's DOM may not know <foreignObject> leads back to HTML):\n // SVG under <svg> — its id says so (`wcs-s…`) — and HTML under <foreignObject>\n let e = anchor.parentNode as Element | null;\n while (e !== null && e.localName !== \"svg\" && e.localName !== \"foreignObject\") e = e.parentElement;\n const svg = e?.localName === \"svg\";\n const id = `wcs-${svg ? \"s\" : \"t\"}${ids++}`;\n (anchor as ChildNode).replaceWith(mark(`wcs-p:${id}`));\n let c: Node = document.importNode(templateContent(template as HTMLTemplateElement), true);\n // a template in it that is an SVG element goes as an HTML one, which a serializer reads (the\n // client's parser reads it back in its context)\n for (const x of Array.from((c as Element).querySelectorAll(\"template\"))) {\n // by namespace, not `instanceof SVGElement`: a server window (@wcstack/server) need not expose that global\n if (x.namespaceURI === \"http://www.w3.org/2000/svg\") x.replaceWith(attrs(x, document.createElement(\"template\"), ...x.childNodes));\n }\n // an SVG template's content goes in <svg>, so the client's parser reads it as SVG\n if (svg) {\n const w = document.createElementNS(e!.namespaceURI, \"svg\");\n w.append(c);\n c = w;\n }\n const t = document.createElement(\"template\");\n t.id = id;\n ssr.append(attrs(template, t, c));\n }\n el.before(ssr);\n}\n\n/**\n * The form controls' current state into their markup, as 3.x wrote it: an input's value (its\n * `value` attribute) and checkedness (`checked`), a textarea's value (its text), the options a\n * select has selected (`selected`) — whatever set them (a `value:` / `checked:` / `selectedIndex:`\n * binding, `radio:`, a row's), where it differs from what the markup gives back. The page then shows\n * the server's values before the client binds it, or without JS; the client's bindings find them\n * there, and write over them from then on. On a page with a `<wcs-state>` only (enable-ssr or not).\n * A password's value never goes into the HTML (3.x wrote it): the client's binding fills it in.\n */\nfunction forms(doc: Document): void {\n if (doc.querySelector(config.tagNames.state) === null) return;\n for (const n of Array.from(doc.querySelectorAll<any>(\"input,textarea,select\"))) {\n if (n.localName === \"select\") {\n const o: HTMLOptionElement[] = Array.from(n.options);\n // (a single select without a marked option, its first enabled one selected: what a parser selects)\n if (n.multiple || o.some((x) => x.hasAttribute(\"selected\")) || o[n.selectedIndex] !== o.find((x) => !x.disabled)) {\n for (const x of o) x.toggleAttribute(\"selected\", x.selected);\n }\n } else if (n.localName === \"textarea\") {\n // (a value with `{{` in it would be the client's markup there, a mustache; a mustache in it is\n // the client's to put back — see snapshot: both left to the client)\n if (n.value !== n.defaultValue && !n.value.includes(\"{{\") && !Array.from(n.childNodes).some((c) => rawTexts.has(c as Node))) n.textContent = n.value;\n } else if (n.type === \"checkbox\" || n.type === \"radio\") {\n n.toggleAttribute(\"checked\", n.checked);\n } else if (n.type !== \"password\" && n.value !== n.defaultValue) {\n n.setAttribute(\"value\", n.value);\n }\n }\n}\n\n/** The builder the server calls before it serializes (protocol wcs-ssr-snapshot v1). */\nfunction build(doc: Document): void {\n // first: moving the rows into their regions (snapshot) may change what a select has selected\n forms(doc);\n for (const el of Array.from(doc.querySelectorAll(`${config.tagNames.state}[enable-ssr]`))) {\n if (el.hasAttribute(\"mount\") || el.hasAttribute(\"bind-component\")) continue;\n if (el.previousElementSibling?.localName === tag()) continue;\n const engine = (el as any).engine as Engine | null;\n if (engine !== null && engine !== undefined) snapshot(el, engine);\n }\n}\n\n/** Where the builder finds this module: the latest evaluation (a server may load one per render). */\nconst IMPL = Symbol.for(\"wcstack.state.ssr.impl\");\n\nexport function installBuilder(): void {\n const g = globalThis as any;\n g[IMPL] = { build, reset() { ids = 0; } };\n // another engine's builder (the current @wcstack/state) is not replaced\n if (g[BUILDER] === undefined) {\n g[BUILDER] = { protocol: \"wcs-ssr-snapshot\", version: 1, build: (doc: Document) => g[IMPL].build(doc), reset: () => g[IMPL].reset() };\n }\n}\n\n// ---------------------------------------------------------------- client\n\ninterface Region {\n /** The branch the region renders (null: a list). */\n readonly branch: number | null;\n /** Each row's nodes, where the server put them (a region in the row included). */\n readonly rows: Node[][];\n /**\n * The region's end mark, after its rows: the server put a view's rows after its anchor, and the view\n * renders them before it — the anchor goes here when the view takes the first row (null after).\n */\n tail: ChildNode | null;\n}\n\n/** Regions waiting for their view, by the node right before them (a view's anchor). */\nconst held = new Map<Node, Region>();\n\n/**\n * The Light DOM components of a page being hydrated, by host: their content is bound by their own\n * engine, which starts later (once its host is wired, or its class defined), so it keeps the\n * server's nodes until then and is prepared when that engine binds it (adoptScope).\n */\nconst deferred = new WeakMap<Node, { ssr: Element; adopt: boolean }>();\nconst scoped = (el: Element): boolean => hooks.componentScope?.(el) === true;\n\n/** An element regions may be in: not a text element, nor a Light DOM component (its engine reads its own). */\nconst enters = (n: Node): boolean => n.nodeType === 1 && !raw(n as Element) && !scoped(n as Element);\n\n/** A region's nodes: its rows', and its end mark. */\nconst nodesOf = (r: Region): Node[] => r.rows.flat().concat(r.tail ?? []);\n\n/** Takes a region's nodes out of the page (rows no view took, or not the plan's). */\nconst drop = (r: Region): void => {\n for (const n of nodesOf(r)) (n as ChildNode).remove();\n};\n\n/**\n * Reads the region `start` opens where it is: its marks go but its end mark, and its nodes stay (no\n * custom element in them is disconnected). It is held by the node before it, its view's anchor (the\n * page's walk then passes its nodes by: its blocks bind them where they are), or dropped (`keep`\n * false, or no node before it). A region in it — in a row, after a view's anchor of the row, or in an\n * element of it — is read in turn. Its nodes go in `row` (the row it is in); returns the node after it.\n */\nfunction read(start: Comment, keep: boolean, row?: Node[]): Node | null {\n const m = /^wcs-\\[(?::(\\d+))?/.exec(start.data)!;\n const key = start.previousSibling;\n const parent = start.parentNode!;\n const rows: Node[][] = [];\n let n: Node | null = start.nextSibling;\n start.remove();\n while (n !== null && !isMark(n, \"wcs-]\")) {\n let next: Node | null = n.nextSibling;\n if (isMark(n, \"wcs-|\")) {\n rows.push([]);\n (n as ChildNode).remove();\n } else {\n // (a branch has no row marks; a list's node before its first one is a value's)\n if (rows.length === 0) rows.push([]);\n const own = rows[rows.length - 1];\n if (startsMark(n, \"wcs-[\")) next = read(n as Comment, keep, own);\n else {\n own.push(n);\n if (enters(n)) strip(n, keep);\n }\n }\n n = next;\n }\n // (cut short — a parser moved its end mark into an element (see mend): it ends with its parent)\n const r: Region = { branch: m[1] === undefined ? null : Number(m[1]), rows, tail: (n ?? parent.appendChild(mark(\"wcs-]\"))) as ChildNode };\n const nodes = nodesOf(r);\n n = r.tail!.nextSibling;\n // (not spread: a region may have more nodes than a call takes arguments)\n for (const x of nodes) {\n row?.push(x);\n if (keep) walked.add(x);\n }\n if (keep && key !== null) {\n held.set(key, r);\n } else {\n drop(r);\n }\n return n;\n}\n\n/** Reads every region under `parent` (see read). */\nfunction strip(parent: Node, keep: boolean): void {\n for (let n: Node | null = parent.firstChild; n !== null; ) {\n if (startsMark(n, \"wcs-[\")) {\n n = read(n as Comment, keep);\n } else {\n if (enters(n)) strip(n, keep);\n n = n.nextSibling;\n }\n }\n}\n\n/** Texts and templates back to what the page was written with; the regions read (see strip). */\nfunction prepare(container: Node, ssr: Element, adopt: boolean): void {\n const walk = (parent: Node): void => {\n for (const n of Array.from(parent.childNodes)) {\n // a text marker takes the nodes up to its end with it\n if (n.parentNode !== parent) continue;\n if (n.nodeType === 8) {\n const d = (n as Comment).data;\n // (a mark the server did not write — in a value — that does not parse is left as it is;\n // a string given to replaceWith goes in as a text node)\n try {\n if (d === \"wcs-s\") n.remove();\n else if (d === \"wcs-e\") n.replaceWith(\"\");\n else if (d.startsWith(\"wcs-t:\")) {\n // the value between the markers, back to a text binding: a comment binding, which binds\n // whether or not the page's mustaches are on (it was a mustache, or a comment binding)\n const text = mark(`@@:${decodeURIComponent(d.slice(6))}`);\n let e: ChildNode | null = n.nextSibling;\n while (e !== null && !isMark(e, \"wcs-/t\")) {\n const next = e.nextSibling;\n e.remove();\n e = next;\n }\n e?.remove();\n n.replaceWith(text);\n } else if (d.startsWith(\"wcs-p:\")) {\n const t = ssr.querySelector(`template[id=\"${d.slice(6)}\"]`) as HTMLTemplateElement | null;\n if (t !== null) {\n const p = n.parentNode as Element;\n // an SVG template (`wcs-s…`): its content came in <svg> (so parsed as SVG)\n const copy = d[10] === \"s\"\n ? attrs(t, document.createElementNS(p.namespaceURI, \"template\"), ...document.importNode(t.content.firstChild!, true).childNodes)\n : document.importNode(t, true);\n copy.removeAttribute(\"id\");\n p.replaceChild(copy, n);\n }\n }\n } catch { /* */ }\n } else if (n.nodeType === 1 && !raw(n as Element)) {\n if (scoped(n as Element)) deferred.set(n, { ssr, adopt });\n else walk(n);\n }\n }\n };\n walk(container);\n mend(container);\n strip(container, adopt);\n}\n\n/**\n * A region a parser cut: its start mark in a <table>, its rows and end mark in the <tbody> the parser\n * added at its first <tr> (the regions after it with them). The comments and templates right before\n * the <tbody> that the cut region starts with go into it — its anchor and marks: nothing in them\n * connects — and the rows stay where they are. A <tbody> written in the page (a row of a list of\n * them, a branch) holds no end mark of a region that starts before it, and is left alone.\n */\nfunction mend(container: Node): void {\n for (const body of Array.from((container as ParentNode).querySelectorAll(\"table > tbody\"))) {\n const run: Node[] = [];\n for (let p = body.previousSibling; p !== null && (p.nodeType === 8 || isBlank(p) || (p as Element).localName === \"template\"); p = p.previousSibling) run.unshift(p);\n // the regions the run leaves open (an end mark whose start is before the run — past an element —\n // closes a region that stays where it is, with what comes before the mark)\n let from = 0;\n let open = 0;\n run.forEach((n, i) => {\n if (startsMark(n, \"wcs-[\")) open++;\n else if (isMark(n, \"wcs-]\") && --open < 0) {\n open = 0;\n from = i + 1;\n }\n });\n if (open === 0) continue;\n // ... and the <tbody> ends one: the parser moved its rows in\n let depth = 0;\n for (let c = body.firstChild; c !== null; c = c.nextSibling) {\n if (startsMark(c, \"wcs-[\")) depth++;\n else if (isMark(c, \"wcs-]\") && depth-- === 0) {\n body.prepend(...run.slice(from));\n break;\n }\n }\n }\n}\n\n/**\n * The `adoptScope` hook: a Light DOM component's engine binds its host. Its content is prepared\n * now, and its blocks take the server's nodes while its walk runs (a walk adopts synchronously).\n * What it did not adopt is dropped after the walk: the regions held then are its own (a page's are\n * read and adopted in one go too, and dropped before anything else runs).\n */\nexport function adoptScope(host: Node, engine: Engine): (() => void) | null {\n const d = deferred.get(host);\n if (d === undefined) return null;\n deferred.delete(host);\n const undo = (c: Node): void => prepare(c, d.ssr, d.adopt);\n // (a snapshot discarded: planned on a copy first, as the page — see hydrate)\n if (!d.adopt) plan(engine, host, host, undo);\n undo(host);\n if (!d.adopt) return null;\n const prev = hooks.adopt;\n hooks.adopt = adopt;\n return () => {\n hooks.adopt = prev;\n release();\n };\n}\n\n/** Drops the held regions: rows no view took. */\nfunction release(): void {\n for (const r of held.values()) drop(r);\n held.clear();\n}\n\n/** The comments under `scope`, in document order. */\nfunction comments(scope: Node): Comment[] {\n const out: Comment[] = [];\n for (const w = document.createTreeWalker(scope, 128); w.nextNode(); ) out.push(w.currentNode as Comment);\n return out;\n}\n\n/**\n * A Light DOM component's wiring, one entry per mapping: [the page's path (null: not known — a key\n * private to the component around), its own path (\"\" for a whole mount, `state: user`), the path as\n * its host wrote it (null at the top: the page's)].\n */\ntype Wiring = (string | null)[][];\n\n/** `path` from column `from` of `wiring` to column `to`, by the longest it is or starts with; null: none. */\nfunction across(wiring: Wiring, path: string, from: number, to: number): string | null {\n let best: (string | null)[] | null = null;\n for (const w of wiring) {\n const k = w[from];\n if (k !== null && (k === \"\" || path === k || path.startsWith(`${k}.`)) && (best === null || k.length > best[from]!.length)) best = w;\n }\n const v = best?.[to];\n if (v == null) return null;\n const k = best![from]!;\n const rest = k === \"\" ? path : path.slice(k.length + 1);\n return v === \"\" ? rest : rest === \"\" ? v : `${v}.${rest}`;\n}\n\n/**\n * The output of @wcstack/server 3.x back to the page as written, as 3.x's own fallback did\n * (`Ssr.cleanupDom`): a row or a branch (`<!--@@wcs-for-start:…-->` up to its `-end` mark among its\n * siblings) goes, a text between its marks becomes a comment binding of what the mark holds (before\n * 3.5.3 the path alone, its filters lost: the warning says so; from 3.5.3, `fresh`, the binding's\n * expression as written: wcstack#373), a template's mark (`<!--@@wcs-for:ID-->`) becomes the template\n * `<wcs-ssr>` keeps under that id (whose content has the marks of the templates in it), and the\n * elements lose `data-wcs-ssr-id`.\n *\n * In a Light DOM component, 3.x wrote a template's own path as the page's (`state: user` makes `name`\n * `user.name`; a private key `user.#m1.name`, or `#m2.name` in a partial mount; in a component in a\n * component, through both), and so the marks' paths before 3.5.3: they go back to the component's own\n * through its host's wiring (the content of a template is the component's already). A mark from 3.5.3\n * is the component's own text, not mapped (it may name a key that is one of the page's wired paths\n * too: `state.x: v; state.v: w`). An expression a comment cannot hold (one with a `--`) falls back to\n * its path, unfiltered. From 3.5.4 (wcstack#427) that is the path the component wrote, read as written\n * like any other mark: the value shows, without its filters. 3.5.3 wrote the page's path there\n * instead, which is mapped back when it names a private key (`#mN.`: never in the component's own\n * text, so the mapping cannot misread a 3.5.4 mark); a wired one cannot be told from the component's\n * own text, and is read as it — a component key of that name shows its value, the right one only when\n * the wiring keeps the name, else the text stays empty (a limit of 3.5.3 output only: migration guide\n * §3.6).\n */\nfunction legacy(container: Node, ssr: Element, fresh: boolean): void {\n const wirings = new Map<Element, Wiring>();\n /** The wiring of the Light DOM component `n` is in (a nested one's composed with the one around), or null. */\n const wiringOf = (n: Node): Wiring | null => {\n let h = n.parentElement;\n while (h !== null && !scoped(h)) h = h.parentElement;\n if (h === null) return null;\n let wiring = wirings.get(h);\n if (wiring === undefined) {\n const up = wiringOf(h);\n const prop = h.querySelector(`:scope > ${config.tagNames.state}[bind-component]`)!.getAttribute(\"bind-component\");\n wirings.set(h, (wiring = []));\n for (const b of parseBindTextsForElement(h.getAttribute(config.bindAttributeName) ?? \"\")) {\n const at = b.statePathName;\n if (b.propSegments[0] === prop) wiring.push([up ? across(up, at, 1, 0) : at, b.propSegments.slice(1).join(\".\"), up && at]);\n }\n }\n return wiring;\n };\n /**\n * A path 3.x wrote at `n`, as the component's own there (`asIs`: a text mark from 3.5.3, left as it\n * is but for a private key's path, which 3.5.3's fallback writes).\n */\n const own = (n: Node, path: string, asIs?: boolean): string => {\n const wiring = wiringOf(n);\n if (wiring === null) return path;\n // (no `|`: a mark with filters, from 3.5.3, is the component's own text, a `#m1.` in it an argument's)\n const m = /^([^|]*)#m\\d+\\.([^|]*)$/.exec(path);\n if (m === null) return asIs ? path : across(wiring, path, 0, 1) ?? path;\n // after the last private key mark, a component's own path: this one's when what comes before the\n // mark is this one's mount path (`user.#m1.name`, `user.profile.#m3.name`, `#m2.box.#m4.name` with\n // `state: box`; nothing for a partial mount, `#m2.name`), else the one's around it, which this one\n // is mounted on (`#m2.box.k` with `state: box`)\n const at = m[1].replace(/#m\\d+\\./g, \"\").slice(0, -1);\n return wiring.some((w) => w[1] === \"\" && (w[0] === at || w[2] === at)) ? m[2] : across(wiring, m[2], 2, 1) ?? m[2];\n };\n // from the last: a row's own marks go before the row does\n for (const c of comments(container).reverse()) {\n const m = /^@@wcs-(\\w+)-start:([\\s\\S]*)/.exec(c.data);\n if (m === null) continue;\n // (no end among its siblings — an output cut short: left as it is)\n let e = c.nextSibling;\n while (e !== null && !isMark(e, `@@wcs-${m[1]}-end:${m[2]}`)) e = e.nextSibling;\n if (e === null) continue;\n while (c.nextSibling !== e) c.nextSibling!.remove();\n e.remove();\n c.replaceWith(...(m[1] === \"text\" ? [mark(`@@:${own(c, m[2], fresh)}`)] : []));\n }\n const restore = (scope: Node, at?: Node): void => {\n for (const c of comments(scope)) {\n const id = /^@@wcs-(?:for|if|elseif|else):(\\S+)$/.exec(c.data)?.[1];\n const t = Array.from(ssr.querySelectorAll(\"template\")).find((x) => x.id === id);\n if (t === undefined) continue;\n const copy = document.importNode(t, true);\n const a = config.bindAttributeName;\n copy.removeAttribute(\"id\");\n copy.setAttribute(a, copy.getAttribute(a)!.replace(/^(\\s*\\w+\\s*:\\s*)([^\\s|]+)/, (_, k: string, p: string) => k + own(at ?? c, p)));\n restore(copy.content, at ?? c);\n // 3.x made each `elseif` an `if` in an `else` of its own (whose content starts with it): back\n // to the chain of templates it was written as\n const f = copy.content.firstChild as Element | null;\n c.replaceWith(...(/^\\s*elseif\\s*:/.test(f?.getAttribute?.(a) ?? \"\") ? copy.content.childNodes : [copy]));\n }\n };\n restore(container);\n for (const e of Array.from((container as ParentNode).querySelectorAll(\"[data-wcs-ssr-id]\"))) e.removeAttribute(\"data-wcs-ssr-id\");\n}\n\n/**\n * What the reader typed before the client bound the page — the server's HTML is usable at once, the\n * bundles may take seconds: the form controls whose value is not the one their markup gives (a\n * browser restoring a form on reload counts too). Binding the page writes the state's values over\n * them, and the text was lost without a word (docs/seam-apps.md, ssr-news; the author's decision,\n * docs/v4-direction-2026-10.md §5.1). Returns what gives each its value back and sends it an\n * `input` and a `change`, as the reader's own edit would: a two-way binding writes it to the state.\n */\nfunction typed(container: Node): () => void {\n const edits: [HTMLElement, () => void][] = [];\n for (const n of Array.from((container as ParentNode).querySelectorAll<any>(\"input,textarea,select\"))) {\n if (n.localName === \"select\") {\n const o: HTMLOptionElement[] = Array.from(n.options);\n const sel = o.map((x) => x.selected);\n // a single select's markup selects its last marked option, or its first enabled one (the mark\n // is read as the attribute: a server's DOM need not have defaultSelected)\n const marked = o.map((x) => x.hasAttribute(\"selected\"));\n let at = marked.lastIndexOf(true);\n if (at < 0) at = o.findIndex((x) => !x.disabled);\n if (n.multiple ? o.some((x, i) => sel[i] !== marked[i]) : n.selectedIndex !== at) edits.push([n, () => o.forEach((x, i) => (x.selected = sel[i]))]);\n } else if (n.type === \"checkbox\" || n.type === \"radio\") {\n // (a radio: the one the reader chose; the group's others follow it)\n const c = n.checked;\n if (c !== n.defaultChecked && (c || n.type === \"checkbox\")) edits.push([n, () => (n.checked = c)]);\n } else if (n.type !== \"file\" && n.value !== n.defaultValue) {\n const v = n.value;\n edits.push([n, () => (n.value = v)]);\n }\n }\n return () => {\n for (const [n, put] of edits) {\n if (!n.isConnected) continue;\n put();\n n.dispatchEvent(new Event(\"input\", { bubbles: true }));\n n.dispatchEvent(new Event(\"change\", { bubbles: true }));\n }\n };\n}\n\n/**\n * Walks a copy of `container` — in a template's content, where no custom element is created — as the\n * mount of `root` walks it, once `undo` put it back as written: what this client cannot plan (a newer\n * minor's markup, a filter argument it does not know) fails its initialization while the server's\n * rows and branches are still in the page, not after they went (docs/seam-apps.md, ssr-news). (An\n * event binding puts its listener on the root at once: the mount's walk finds it there)\n */\nfunction plan(engine: Engine, root: Node, container: Node, undo: (c: Node) => void): void {\n const copy = document.createElement(\"template\").content;\n for (const n of container.childNodes) copy.appendChild(copy.ownerDocument.importNode(n, true));\n undo(copy);\n engine.root = root;\n const none = (): void => {};\n walkBindings(engine, [...copy.childNodes], null, true, none, none, none, (_, expr) => textSpec(engine, expr, null, 0));\n}\n\n/** The `element` hook, \"mounting\": a client root with a server snapshot adopts the server's DOM. */\nexport function hydrate(engine: Engine): void {\n const el = engine.element as Element;\n if (!el.hasAttribute(\"enable-ssr\") || isServer()) return;\n const ssr = el.previousElementSibling;\n const found = ssr?.localName === tag();\n const version = found ? ssr!.getAttribute(\"version\") : null;\n const same = version === null || majorMinor(version) === majorMinor(VERSION);\n if (same) {\n // the server ran $connectedCallback; the client does not\n const e = engine as any;\n const callHook = e.callHook;\n e.callHook = (name: string, args?: unknown[]) => (name === \"$connectedCallback\" ? undefined : callHook.call(engine, name, args));\n }\n if (!found) return;\n // @wcstack/server 3.x's output: marks of its own; from 3.5.3 on a text mark holds the binding's\n // expression (see legacy). A prerelease, or a version that does not parse, counts as older\n const old = !same && parseInt(version!) < 4;\n const v = /^3\\.(\\d+)\\.(\\d+)$/.exec(version!);\n const fresh = v !== null && (+v[1] - 5 || +v[2] - 3) >= 0;\n if (!same) {\n // (the filters' sentence: output before 3.5.3 only)\n console.warn(`[@wcstack/state] <${tag()} version=\"${version}\"> does not match ${VERSION}: its snapshot is discarded, and the page renders on the client from its own state.${old && !fresh\n ? \" 3.x output keeps only the path of a text binding outside a template, so such a binding loses its filters: deploy @wcstack/server 4.0 with this client.\"\n : \"\"}`);\n }\n const script = same ? ssr!.querySelector('script[type=\"application/json\"]') : null;\n if (script !== null) {\n const snap = JSON.parse(script.textContent || \"{}\") as Record<string, unknown>;\n const target = engine.target;\n for (const key of Object.keys(snap)) {\n const d = Object.getOwnPropertyDescriptor(target, key);\n if (d !== undefined && (d.get !== undefined || d.set !== undefined || typeof d.value === \"function\")) continue;\n target[key] = snap[key];\n }\n // the snapshot holds the server's volume data too: a volume adopts it (scopes/volume.ts)\n (engine as any).hydrated = true;\n }\n const root = el.getRootNode() as Document | ShadowRoot;\n for (const r of Array.from(root.querySelectorAll(`[${RAW_ATTR}]`))) {\n r.textContent = r.getAttribute(RAW_ATTR);\n r.removeAttribute(RAW_ATTR);\n }\n const container = root.nodeType === 9 ? (root as Document).body : root;\n // (its templates are not the page's markup: out before the page is walked)\n ssr!.remove();\n // back to the page as written (see prepare, legacy)\n const undo = (c: Node): void => (old ? legacy(c, ssr!, fresh) : prepare(c, ssr!, same));\n if (!same) plan(engine, root, container, undo);\n // (taken before the page is bound, which writes the state's values; given back right after)\n queueMicrotask(typed(container));\n undo(container);\n if (same) {\n // only while the page is adopted — its walk, which runs now: every other block is built with one\n // null check. What no view took then goes before anything else runs\n hooks.adopt = adopt;\n queueMicrotask(() => {\n release();\n hooks.adopt = null;\n });\n }\n}\n\n/**\n * The `ssrMark` hook: on the server, records (and leaves `outerHTML:` / `outerText:` to the client); on the client,\n * a held region follows its template's anchor.\n */\nexport function ssrMark(engine: Engine, node: Node, source: Element | string | Spec[]): void {\n if (isServer()) {\n if (source instanceof Array) {\n // `outerHTML:` / `outerText:` replace the element with the value: the client would find no\n // binding there, and walk the value as the page's markup. The server renders the element as\n // written; the client binds it and applies the value\n for (let i = source.length; i-- > 0; ) if (isOuter(source[i])) source.splice(i, 1);\n // a custom element (a Light DOM component binds its own) whose content no binding sets: what\n // is in it now is the page's (see kept)\n const el = node as Element;\n if (source.some(setsContent)) skip.add(el);\n else if (el.localName.includes(\"-\") && !scoped(el)) {\n const own = new Map<Node, string>();\n for (const w = document.createTreeWalker(el, 133); w.nextNode(); ) own.set(w.currentNode, (w.currentNode as Text).data);\n kept.set(el, own);\n }\n return;\n }\n if (typeof source === \"string\") {\n rawTexts.set(node, source);\n if (raw(node.parentNode as Element)) return;\n const open = mark(`wcs-t:${encodeURIComponent(source)}`);\n const close = mark(\"wcs-/t\");\n (node as Text).before(open);\n (node as Text).after(close);\n return;\n }\n let map = anchors.get(engine);\n if (map === undefined) anchors.set(engine, (map = new Map()));\n map.set(node, source);\n const root = node.getRootNode();\n let es = enginesByRoot.get(root);\n if (es === undefined) enginesByRoot.set(root, (es = new Set()));\n es.add(engine);\n return;\n }\n // (an element's specs are never a key: the templates the anchors replaced are)\n if (typeof source !== \"string\" && held.size > 0) {\n const r = held.get(source as Element);\n if (r !== undefined) {\n held.delete(source as Element);\n held.set(node, r);\n }\n }\n}\n\n/** An anchor of an `if` / `elseif` / `else` chain (the core names them by config). */\nconst isIfAnchor = (n: Node | null): boolean =>\n n !== null && n.nodeType === 8 && [config.commentIfPrefix, config.commentElseIfPrefix, config.commentElsePrefix].includes((n as Comment).data);\nconst isBlank = (n: Node): boolean => n.nodeType === 3 && (n as Text).data.trim() === \"\";\n\n/** The next of the plan's nodes after `n`: a held region after an anchor is the anchor's view's. */\nconst after = (n: Node): Node | null => {\n const x = held.get(n)?.tail ?? n;\n return (beside(x) ?? x).nextSibling;\n};\n\n/**\n * Whether a row's top-level nodes `own` have the plan's nodes where a binding lands — not so when a\n * Light DOM element added children before them, or a parser moved them (see mend); puts them\n * in `plan.scratch` for the block.\n */\nfunction fits(plan: RowPlan, own: Node[]): boolean {\n if (own.length !== plan.fragment.childNodes.length) return false;\n const paths = plan.nodePaths;\n for (let i = 0; i < paths.length; i++) {\n const path = paths[i];\n let a: Node = plan.fragment;\n let b: Node | null | undefined = own[path[0]];\n for (let j = 0; ; ) {\n a = a.childNodes[path[j]];\n if (b?.nodeName !== a.nodeName) return false;\n if (++j === path.length) break;\n b = (beside(b) ?? b).firstChild;\n for (let k = path[j]; k > 0 && b !== null; k--) b = after(b);\n }\n plan.scratch[i] = b;\n }\n return true;\n}\n\n/**\n * The `adopt` hook: the next server row (or branch) of the view anchored at `anchor` — its top-level\n * nodes, left where they are (the view inserts nothing, and no custom element in them is disconnected).\n */\nexport function adopt(plan: RowPlan, anchor: Node, isFor: boolean): ChildNode[] | null {\n if (held.size === 0) return null;\n let key = anchor;\n let branch = 0;\n if (!isFor) {\n // only this chain: an `if` anchor starts one (a chain right before or after is another). No\n // element is between its anchors: whitespace, comments (readChain) and the text a comment binding\n // there renders may be\n const head = config.commentIfPrefix;\n if (!isMark(anchor, head)) {\n for (let p = anchor.previousSibling; p !== null && p.nodeType !== 1; p = p.previousSibling) {\n if (isIfAnchor(p)) branch++;\n if (isMark(p, head)) break;\n }\n }\n // up to the anchor its region follows (the branch's nodes come right after it)\n for (let n = anchor.nextSibling; !held.has(key) && n !== null && !isMark(n, head) && n.nodeType !== 1; n = n.nextSibling) {\n if (isIfAnchor(n)) key = n;\n }\n }\n const r = held.get(key);\n if (r === undefined) return null;\n if (!isFor && r.branch !== branch) {\n // the server rendered another branch: it goes, this one is built\n held.delete(key);\n drop(r);\n return null;\n }\n const nodes = r.rows.shift();\n if (r.rows.length === 0) held.delete(key);\n // a view renders before its anchor (a branch before its own: the chain's anchors from it on), and\n // the server put its rows after: the anchors go where the rows end\n r.tail?.replaceWith(...range(anchor, key));\n r.tail = null;\n if (nodes === undefined) return null;\n // the row's own top-level nodes (a region in it is a nested view's, a link's anchor the link's)\n let own: Node[] = [];\n for (let i = 0; i < nodes.length; i++) {\n const inner = held.get(nodes[i]);\n own.push(nodes[i]);\n // (its nodes follow it, up to its end mark)\n if (inner !== undefined) while (i < nodes.length && nodes[i] !== inner.tail) i++;\n else if (beside(nodes[i]) === nodes[i + 1]) i++;\n }\n if (!fits(plan, own)) {\n // rendered anew, in its place (the rows around it stay; an empty one's place is before the next\n // row, or the anchor): its nodes found before it is in the page (a custom element in it may add\n // children as it connects)\n const fresh = (plan.single ? plan.root! : plan.fragment).cloneNode(true);\n own = plan.single ? [fresh] : [...fresh.childNodes];\n fits(plan, own);\n ((nodes[0] ?? r.rows.find((x) => x.length > 0)?.[0] ?? anchor) as ChildNode).before(fresh);\n for (const n of nodes) (n as ChildNode).remove();\n }\n return own as ChildNode[];\n}\n","/**\n * The SSR add-on (@wcstack/state/features/ssr): `<wcs-state enable-ssr>` with @wcstack/server —\n * see src/ssr/ssr.ts.\n */\nimport { chain, hooks, type Feature } from \"../hooks\";\nimport { adoptScope, hydrate, installBuilder, ssrMark } from \"../ssr/ssr\";\nimport { defineSsr } from \"../ssr/element\";\nimport { registries } from \"../element\";\n\nexport const ssr: Feature = {\n name: \"ssr\",\n hooks,\n install(): void {\n hooks.ssrMark = ssrMark;\n hooks.adoptScope = adoptScope;\n // the snapshot first, before what is installed (in any order) runs at \"mounting\": a volume\n // grafting there adopts it, and its $connectedCallback writes over it (3.x D14)\n const prev = hooks.element;\n hooks.element = (engine, phase) => {\n if (phase === \"mounting\") hydrate(engine);\n prev?.(engine, phase);\n };\n installBuilder();\n // `<wcs-ssr>` in every registry `<wcs-state>` is defined in, now and later\n hooks.tags = chain(hooks.tags, defineSsr);\n for (const r of registries()) defineSsr(r);\n },\n};\nexport default ssr;\n","/**\n * DevTools (`@wcstack/devtools`) — the DevTools Hook Protocol v2 (docs/devtools-hook-protocol.ja.md),\n * spoken by an add-on so the engine pays nothing while no DevTools is attached.\n *\n * The protocol's pulls (the roster, keys, read, write, keyed subscriptions) read the engines; its\n * events come from the add-on hooks (written, drained, failed, the element lifecycle) and from\n * the tokens, wrapped per engine. Addresses and bindings are small plain objects of the shape\n * DevTools reads (`absolutePathInfo.pathInfo.path`, `listIndex.indexes`, `propName`,\n * `statePathName`, `bindingType`, `node`), built only while a sink is set. Every key that\n * crosses to DevTools is quoted: the build shortens internal names, some of which (`kind`,\n * `path`, `node`, `propName`, …) are also the protocol's.\n *\n * The one part v2 builds from the engine's own bookkeeping — \"binding added / removed\" — the new\n * engine does not have (row bindings are lazy slots, made on their first change). While DevTools\n * is attached, the add-on takes the list of bindings after every drain (materialized ones and\n * slots alike) and reports the difference: DevTools sees the same live ledger, at a cost paid\n * only then.\n */\nimport type { Engine } from \"../engine\";\nimport type { Pattern } from \"../pattern\";\nimport type { StateRow } from \"../list\";\nimport type { Token } from \"../token\";\nimport { ForView, IfView, K_ATTR, K_CLASS, K_EVENT, K_STYLE, K_TEXT, type Binding, type Block, RowView, type Spec } from \"../dom/view\";\nimport { engines as byRoot } from \"../dom/mount\";\nimport { VERSION } from \"../version\";\nimport { hooks } from \"../hooks\";\n\nconst HOOK = \"__WCSTACK_DEVTOOLS_HOOK__\";\nconst PROTOCOL = 2;\n\ntype Sink = (event: Record<string, unknown>) => void;\ntype Source = Record<string, any>;\n\nlet sink: Sink | null = null;\n/** The attached DevTools' sink (analyzeContract forwards its events there). */\nexport const devtoolsSink = (): Sink | null => sink;\nconst live = new Set<Engine>();\n\n// ---------------------------------------------------------------- registry (first one wins)\n\nfunction createRegistry(): Record<string, unknown> {\n const sources = new Map<string, Source>();\n const listeners = new Set<Record<string, (...a: any[]) => void>>();\n const apply = (s: Source): void => {\n if (listeners.size === 0) s[\"_setSink\"](null);\n else s[\"_setSink\"]((event: unknown) => { for (const l of listeners) l[\"onEvent\"]?.(s[\"id\"], event); });\n };\n return {\n \"version\": PROTOCOL,\n \"sources\": sources,\n \"register\"(s: Source): void {\n if (sources.has(s[\"id\"])) return;\n sources.set(s[\"id\"], s);\n apply(s);\n for (const l of listeners) l[\"onSourceRegistered\"]?.(s);\n },\n \"unregister\"(id: string): void {\n const s = sources.get(id);\n if (s === undefined) return;\n s[\"_setSink\"](null);\n sources.delete(id);\n for (const l of listeners) l[\"onSourceUnregistered\"]?.(id);\n },\n \"addListener\"(l: Record<string, (...a: any[]) => void>): () => void {\n listeners.add(l);\n for (const s of sources.values()) {\n apply(s);\n l[\"onSourceRegistered\"]?.(s);\n }\n return () => {\n if (listeners.delete(l)) for (const s of sources.values()) apply(s);\n };\n },\n };\n}\n\n// ---------------------------------------------------------------- shapes DevTools reads\n\nconst address = (engine: Engine, p: Pattern, row: StateRow | null): Record<string, unknown> => ({\n \"absolutePathInfo\": { \"pathInfo\": { \"path\": p.path }, \"stateElement\": engine.element },\n \"listIndex\": row === null ? null : { \"indexes\": engine.indexesOf(row) },\n});\n\nfunction propName(kind: number, name: string): string {\n if (kind === K_TEXT) return \"textContent\";\n if (kind === K_CLASS) return `class.${name}`;\n if (kind === K_ATTR) return `attr.${name}`;\n if (kind === K_STYLE) return `style.${name}`;\n return name;\n}\n\n/** A binding as DevTools reads it: `{ binding, absoluteAddress }`. */\ntype Entry = Record<string, unknown>;\n\nconst nodeIds = new WeakMap<Node, number>();\nlet nodeSeq = 0;\nconst idOf = (n: Node): number => {\n let id = nodeIds.get(n);\n if (id === undefined) nodeIds.set(n, (id = ++nodeSeq));\n return id;\n};\n\n/** Every binding of the engine now — materialized ones and row slots alike — by identity. */\nfunction snapshot(engine: Engine, old: Map<string, Entry> | undefined): Map<string, Entry> {\n const out = new Map<string, Entry>();\n const seen = new Set<object>();\n const add = (kind: number, name: string, node: Node, p: Pattern, row: StateRow | null, type: string): void => {\n if (kind === K_EVENT) return;\n const prop = propName(kind, name);\n const r = p.depth === 0 ? null : row;\n const key = `${idOf(node)}|${prop}|${p.path}|${r === null ? \"\" : engine.indexesOf(r).join(\",\")}`;\n if (out.has(key)) return;\n const kept = old?.get(key);\n out.set(key, kept ?? {\n \"binding\": { \"propName\": prop, \"statePathName\": p.path, \"bindingType\": type, \"node\": node, \"replaceNode\": node },\n \"absoluteAddress\": address(engine, p, r),\n });\n };\n const binding = (b: Binding): void => add(b.kind, b.name, b.node, b.pattern, b.row, b.typeName());\n const block = (b: Block): void => {\n if (seen.has(b)) return;\n seen.add(b);\n if (b.bindings !== null) for (const x of b.bindings) binding(x);\n if (b instanceof RowView && b.slots !== null) {\n const lazy: Spec[] = b.plan.lazy;\n for (let k = 0; k < lazy.length; k++) {\n const made = b.bound?.[k];\n if (made !== undefined) binding(made);\n else add(lazy[k].kind, lazy[k].name, b.slots[2 * k] as Node, lazy[k].pattern!, b.row, lazy[k].kind === K_TEXT ? \"text\" : \"prop\");\n }\n }\n if (b.children !== null) for (const v of b.children) view(v);\n };\n const view = (v: ForView | IfView): void => {\n if (seen.has(v)) return;\n seen.add(v);\n if (v instanceof ForView) {\n // the list binding itself: v2 has one per `for`, on the anchor that replaced the template\n add(-1, \"for\", v.anchor, v.list.pattern, v.list.parentRow, \"for\");\n for (const rv of v.rowViews) block(rv);\n } else if (v.current !== null) block(v.current);\n };\n for (const bs of engine.rootBindings.values()) {\n for (const b of bs) {\n binding(b);\n if (b.chain !== null) view(b.chain);\n }\n }\n for (const l of engine.rootLists.values()) {\n if (l.view !== null) view(l.view);\n if (l.extra !== null) for (const v of l.extra) view(v);\n }\n return out;\n}\n\nlet ledgers = new WeakMap<Engine, Map<string, Entry>>();\n\n/** Reports the bindings added and removed since the last look. */\nfunction sync(engine: Engine): void {\n if (sink === null) return;\n const old = ledgers.get(engine);\n const now = live.has(engine) ? snapshot(engine, old) : new Map<string, Entry>();\n if (old !== undefined) for (const [k, e] of old) if (!now.has(k)) sink({ \"type\": \"state:binding-removed\", ...e });\n for (const [k, e] of now) if (old === undefined || !old.has(k)) sink({ \"type\": \"state:binding-added\", ...e });\n ledgers.set(engine, now);\n}\n\n// ---------------------------------------------------------------- the pulls\n\nfunction engineOf(root: Node): Engine {\n const e = byRoot.get(root);\n if (e === undefined) throw new Error(\"[@wcstack/state] devtools: no state tree on this root\");\n return e;\n}\n\nfunction summary(engine: Engine): Record<string, unknown> {\n const list = new Set<string>();\n const element = new Set<string>();\n const getter = new Set<string>();\n const setter = new Set<string>();\n for (const p of engine.patterns.all()) {\n for (let k = 1; k <= p.depth; k++) list.add(p.lists[k]!.path);\n if (p.last === \"*\") element.add(p.path);\n if (p.getter !== null) getter.add(p.path);\n if (p.setter !== null) setter.add(p.path);\n }\n const t = engine.target;\n return {\n \"rootNode\": engine.root,\n \"element\": engine.element,\n \"paths\": { \"list\": list, \"element\": element, \"getter\": getter, \"setter\": setter },\n \"commandTokenNames\": new Set(Object.keys(engine.commands)),\n \"eventTokenNames\": new Set(engine.events.keys()),\n \"staticDependency\": new Map(),\n \"dynamicDependency\": new Map(),\n \"watchPaths\": t.$watch !== null && typeof t.$watch === \"object\" ? new Set(Object.keys(t.$watch)) : null,\n \"keyedListPaths\": t.$listKeys !== null && typeof t.$listKeys === \"object\" ? new Set(Object.keys(t.$listKeys)) : null,\n };\n}\n\nfunction keyedSubscriptions(engine: Engine): Record<string, unknown>[] {\n const out: Record<string, unknown>[] = [];\n for (const p of engine.patterns.all()) {\n const subs = p.eqSubs;\n const lists = p.eqIndexWatchers?.length ?? 0;\n if ((subs === null || subs.size === 0) && lists === 0) continue;\n let rows = 0;\n if (subs !== null) for (const s of subs.values()) rows += s.size;\n let lastValue: unknown;\n try { lastValue = p.depth === 0 ? engine.readUntracked(p, null) : undefined; } catch { lastValue = undefined; }\n out.push({ \"path\": p.path, \"tracked\": false, \"rows\": rows, \"keys\": subs === null ? 0 : subs.size, \"lists\": lists, \"lastValue\": lastValue });\n }\n return out;\n}\n\nfunction createSource(): Source {\n return {\n \"id\": `state:${Math.random().toString(36).slice(2, 10)}`,\n \"kind\": \"state\",\n \"packageVersion\": VERSION,\n \"getStateElements\": () => [...live].map(summary),\n \"overlays\": () => [],\n \"keyedSubscriptions\": (root: Node) => keyedSubscriptions(engineOf(root)),\n \"keys\"(root: Node): string[] {\n const t = engineOf(root).target;\n return Object.keys(t).filter((k) => {\n if (k.includes(\"*\") || k[0] === \"$\") return false;\n const d = Object.getOwnPropertyDescriptor(t, k)!;\n return d.get !== undefined || typeof d.value !== \"function\";\n });\n },\n \"read\"(root: Node, path: string, indexes?: number[]): unknown {\n const el = engineOf(root).element as any;\n let v: unknown;\n el.createState(\"readonly\", (s: any) => { v = s.$resolve(path, indexes ?? []); });\n return v;\n },\n \"write\"(root: Node, path: string, value: unknown, indexes?: number[]): void {\n const el = engineOf(root).element as any;\n el.createState(\"writable\", (s: any) => { s.$resolve(path, indexes ?? [], value); });\n },\n \"_setSink\"(next: Sink | null): void {\n const attached = sink === null && next !== null;\n sink = next;\n // detached: the ledgers go — an attach after it is told every binding there, and none of\n // their nodes is held meanwhile\n if (next === null) ledgers = new WeakMap();\n // what the add-ons notice ($watch fired / threw / cut, a path that does not resolve), with the\n // tree it came from (`stateElement`): built only while a DevTools is attached\n hooks.noticed = next && ((engine, event) => sink?.({ ...event, \"stateElement\": engine.element }));\n // a DevTools that attaches late sees the bindings there already\n if (attached) queueMicrotask(() => { for (const e of live) sync(e); });\n },\n };\n}\n\n// ---------------------------------------------------------------- the hooks\n\nconst wrapped = new WeakSet<Token>();\n\nfunction wrapTokens(engine: Engine): void {\n const wrap = (t: Token, kind: \"command\" | \"event\"): void => {\n if (wrapped.has(t)) return;\n wrapped.add(t);\n const emit = t.emit;\n t.emit = (...args: unknown[]) => {\n if (sink !== null) sink({ \"type\": \"state:token-emit\", \"kind\": kind, \"tokenName\": t.name, \"args\": args, \"subscriberCount\": t.size, \"stateElement\": engine.element });\n return emit.apply(t, args);\n };\n };\n for (const t of Object.values(engine.commands)) wrap(t, \"command\");\n for (const t of engine.events.values()) wrap(t, \"event\");\n}\n\nconst batches = new WeakMap<Engine, Set<unknown>>();\n\nexport function devtoolsElement(engine: Engine, phase: string): void {\n if (phase === \"mounting\" || phase === \"reset\") wrapTokens(engine);\n if (phase === \"connected\") {\n if (live.has(engine)) return;\n live.add(engine);\n sink?.({ \"type\": \"state:element-registered\", \"rootNode\": engine.root, \"element\": engine.element });\n sync(engine);\n } else if (phase === \"disconnected\") {\n live.delete(engine);\n sync(engine);\n sink?.({ \"type\": \"state:element-unregistered\", \"rootNode\": engine.root, \"element\": engine.element });\n }\n}\n\nexport function devtoolsWritten(engine: Engine, p: Pattern, row: StateRow | null, old: unknown, value: unknown, direct: boolean): void {\n if (sink === null) return;\n const a = address(engine, p, p.depth === 0 ? null : row);\n let batch = batches.get(engine);\n if (batch === undefined) batches.set(engine, (batch = new Set()));\n batch.add(a);\n if (direct) sink({ \"type\": \"state:write\", \"absoluteAddress\": a, \"value\": value, \"oldValue\": old, \"hasOldValue\": true });\n}\n\nexport function devtoolsDrained(engine: Engine): void {\n if (sink === null) return;\n const batch = batches.get(engine);\n batches.delete(engine);\n if (batch !== undefined) sink({ \"type\": \"state:update-batch\", \"addresses\": batch });\n sync(engine);\n}\n\nexport function devtoolsFailed(_engine: Engine, error: unknown, b: Binding): void {\n sink?.({ \"type\": \"state:binding-apply-error\", \"path\": b.pattern.path, \"bindingType\": b.typeName(), \"error\": error });\n}\n\nexport function registerSource(): void {\n if (typeof document === \"undefined\" || document.documentElement?.hasAttribute(\"data-wcs-server\")) return;\n const g = globalThis as any;\n const registry = g[HOOK] ?? (g[HOOK] = createRegistry());\n if (registry[\"version\"] !== PROTOCOL) console.warn(`[@wcstack/state] devtools hook registry version ${registry[\"version\"]}, expected ${PROTOCOL}: keeping the existing one.`);\n registry[\"register\"](createSource());\n}\n","/**\n * The DevTools add-on (@wcstack/state/features/devtools): `@wcstack/devtools` over the hook\n * protocol v2 — see src/devtools/devtools.ts.\n */\nimport { chain, hooks, type Feature } from \"../hooks\";\nimport { devtoolsDrained, devtoolsElement, devtoolsFailed, devtoolsWritten, registerSource } from \"../devtools/devtools\";\n\nexport const devtools: Feature = {\n name: \"devtools\",\n hooks,\n install(): void {\n hooks.element = chain(hooks.element, devtoolsElement);\n hooks.written = chain(hooks.written, devtoolsWritten);\n hooks.drained = chain(hooks.drained, devtoolsDrained);\n hooks.failed = chain(hooks.failed, devtoolsFailed);\n registerSource();\n },\n};\nexport default devtools;\n","/**\n * Native element commands (the native-commands add-on): `command.<method>:` on an element with no\n * wc-bindable declaration — `<dialog data-wcs=\"command.showModal: $command.open\">` — so a state\n * opens a dialog, focuses an input or plays a video by emitting a token, never by reaching the\n * element (docs/state-engine-rewrite/native-commands.ja.md).\n */\nimport type { NativeCall } from \"../hooks\";\nimport { raise, M } from \"../messages\";\n\n/**\n * The methods a native element's `command.<method>:` may call, by tag (`*`: every element). None\n * writes HTML, an attribute or the tree, or changes a control's value without its `input` event\n * (the state would not see it). Decided by this table alone, not by what the element has: a\n * binding binds in every browser (and on the server) alike, and a method a browser lacks fails\n * when it is called. The tooling manifest publishes a copy as `nativeCommands`.\n */\nexport const NATIVE_COMMANDS: Readonly<Record<string, readonly string[]>> = {\n \"*\": [\"focus\", \"blur\", \"click\", \"scrollIntoView\", \"showPopover\", \"hidePopover\", \"togglePopover\"],\n \"dialog\": [\"show\", \"showModal\", \"close\", \"requestClose\"],\n \"form\": [\"requestSubmit\", \"checkValidity\", \"reportValidity\"],\n \"input\": [\"select\", \"setSelectionRange\", \"showPicker\", \"setCustomValidity\", \"checkValidity\", \"reportValidity\"],\n \"textarea\": [\"select\", \"setSelectionRange\", \"setCustomValidity\", \"checkValidity\", \"reportValidity\"],\n \"select\": [\"showPicker\", \"setCustomValidity\", \"checkValidity\", \"reportValidity\"],\n \"audio\": [\"play\", \"pause\", \"load\"],\n \"video\": [\"play\", \"pause\", \"load\"],\n};\n\n/** What a native `tag` may be commanded to run (its own row only: `<constructor>` reads no prototype). */\nexport const nativeCommandsOf = (tag: string): readonly string[] =>\n [...NATIVE_COMMANDS[\"*\"], ...(Object.hasOwn(NATIVE_COMMANDS, tag) ? NATIVE_COMMANDS[tag] : [])];\n\n/** `hooks.nativeCommand`: null for a custom element (it declares its commands); throws for a method outside the table. */\nexport function nativeCommand(el: Element, method: string): NativeCall | null {\n const tag = el.localName;\n if (tag.includes(\"-\")) return null;\n const allowed = nativeCommandsOf(tag);\n if (!allowed.includes(method)) raise(M.NativeNoCommand, [tag, method, allowed.join(\", \")], method, allowed);\n // an event's emit (`onclick: $command.x`: the event, then the list indexes) is no argument of a\n // native method — `close(event)` would set the dialog's returnValue to \"[object PointerEvent]\"\n return (target, args) => (target as any)[method](...(args[0] instanceof Event ? [] : args));\n}\n","import { define } from \"./element\";\nimport { installFeatures } from \"./hooks\";\nimport { ALL_FEATURES } from \"./features/all\";\n\n// the auto bundle is the full engine: the core and every add-on\ninstallFeatures(ALL_FEATURES);\ndefine();\n","/**\n * Every add-on: what `@wcstack/state` (`bootstrapState`) and the auto bundle install. A page\n * that installs only some imports `@wcstack/state/core` and `features/<name>` instead.\n */\nimport type { Feature } from \"../hooks\";\nimport { formats } from \"./formats\";\nimport { diagnostics } from \"./diagnostics\";\nimport { temporal } from \"./temporal\";\nimport { listKeys } from \"./list-keys\";\nimport { scopes } from \"./scopes\";\nimport { recursion } from \"./recursion\";\nimport { ssr } from \"./ssr\";\nimport { devtools } from \"./devtools\";\nimport { nativeCommands } from \"./native-commands\";\n\nexport const ALL_FEATURES: readonly Feature[] = [formats, diagnostics, temporal, listKeys, scopes, recursion, ssr, devtools, nativeCommands];\n","/**\n * The native-commands add-on (@wcstack/state/features/native-commands): `command.<method>:` on a\n * native element (README \"Native element commands\") — `showModal` / `close` on a `<dialog>`,\n * `focus` on an `<input>`, `play` / `pause` on a `<video>`, from the table in native/commands.ts.\n * Without it a native element's `command.` fails as before (`[wcs/token-misconfigured]`).\n */\nimport { hooks, type Feature } from \"../hooks\";\nimport { nativeCommand } from \"../native/commands\";\n\nexport const nativeCommands: Feature = {\n name: \"native-commands\",\n hooks,\n install(): void {\n hooks.nativeCommand = nativeCommand;\n },\n};\nexport default nativeCommands;\n"],"mappings":"AAWO,IAAMA,EAAN,MAiDL,WAAAC,CAAYC,EAAcC,EAAcC,GAvCxCC,KAAAC,EAAsB,GAGtBD,KAAAE,OAAiC,KACjCF,KAAAG,GAA4C,KAE5CH,KAAAI,IAAc,EAEdJ,KAASK,EAAwB,GAEjCL,KAAAM,EAAqB,GAErBN,KAAAO,GAAoC,KAEpCP,KAAAQ,GAAO,EAEPR,KAAAS,EAAqBC,EAErBV,KAAAW,GAA+D,KAE/DX,KAAAY,GAA6D,KAE7DZ,KAAAa,GAAkC,KAElCb,KAAAc,EAA0C,KAK1Cd,KAAAe,IAAS,EAETf,KAAAgB,IAAO,EAEPhB,KAAAiB,IAAS,EAETjB,KAAAkB,EAAO,EAEPlB,KAAiBmB,GAAe,IAAIC,IAGlCpB,KAAKH,EAAOA,EACZG,KAAKD,EAASA,EACdC,KAAKF,EAAOA,EAEZ,IAAMuB,EAAuC,OAAXtB,EAAkB,CAAC,MAAQA,EAAOsB,EAAMC,QACpEC,EAAa,MAATzB,EACNyB,GAAGF,EAAMG,KAAKzB,GAClBC,KAAKyB,EAAQJ,EAAMK,OAAS,EAC5B1B,KAAK2B,EAAOJ,EAAI,GAAgB,OAAXxB,EAAkB,CAACD,GAAQ,IAAIC,EAAO4B,EAAM7B,GACjEE,KAAKqB,EAAQA,CACf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