@wcstack/state 4.2.0 → 4.3.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.
Files changed (41) hide show
  1. package/README.ja.md +7 -6
  2. package/README.md +7 -6
  3. package/dist/auto.min.js +1 -1
  4. package/dist/auto.min.js.map +1 -1
  5. package/dist/index.esm.js +1 -1
  6. package/dist/index.esm.js.map +1 -1
  7. package/dist/manifest.esm.js +5 -4
  8. package/dist/split/auto.js +1 -1
  9. package/dist/split/chunks/{chunk-JK3B3LLB.js → chunk-5Q4M6A3C.js} +2 -2
  10. package/dist/split/chunks/{chunk-UPSLR4FS.js → chunk-6I7GGFNJ.js} +2 -2
  11. package/dist/split/chunks/chunk-BKLFDVOP.js +2 -0
  12. package/dist/split/chunks/chunk-BKLFDVOP.js.map +1 -0
  13. package/dist/split/chunks/{chunk-BYQBV3ZC.js → chunk-DOWWBZVS.js} +2 -2
  14. package/dist/split/chunks/chunk-F3DVWVH3.js +2 -0
  15. package/dist/split/chunks/chunk-F3DVWVH3.js.map +1 -0
  16. package/dist/split/chunks/chunk-M67C46SN.js +2 -0
  17. package/dist/split/chunks/{chunk-OKBVNGFK.js.map → chunk-M67C46SN.js.map} +1 -1
  18. package/dist/split/chunks/chunk-NMOSSDKJ.js +2 -0
  19. package/dist/split/chunks/chunk-NMOSSDKJ.js.map +1 -0
  20. package/dist/split/core.js +1 -1
  21. package/dist/split/features/devtools.js +1 -1
  22. package/dist/split/features/diagnostics.js +1 -1
  23. package/dist/split/features/diagnostics.js.map +1 -1
  24. package/dist/split/features/list-keys.js +1 -1
  25. package/dist/split/features/recursion.js +1 -1
  26. package/dist/split/features/scopes.js +1 -1
  27. package/dist/split/features/ssr.js +1 -1
  28. package/dist/split/features/ssr.js.map +1 -1
  29. package/dist/split/features/temporal.js +1 -1
  30. package/dist/wcs-manifest.json +4 -8
  31. package/package.json +1 -1
  32. package/dist/split/chunks/chunk-3Q7LGONS.js +0 -2
  33. package/dist/split/chunks/chunk-3Q7LGONS.js.map +0 -1
  34. package/dist/split/chunks/chunk-4ECL4ITF.js +0 -2
  35. package/dist/split/chunks/chunk-4ECL4ITF.js.map +0 -1
  36. package/dist/split/chunks/chunk-BI4645UG.js +0 -2
  37. package/dist/split/chunks/chunk-BI4645UG.js.map +0 -1
  38. package/dist/split/chunks/chunk-OKBVNGFK.js +0 -2
  39. /package/dist/split/chunks/{chunk-JK3B3LLB.js.map → chunk-5Q4M6A3C.js.map} +0 -0
  40. /package/dist/split/chunks/{chunk-UPSLR4FS.js.map → chunk-6I7GGFNJ.js.map} +0 -0
  41. /package/dist/split/chunks/{chunk-BYQBV3ZC.js.map → chunk-DOWWBZVS.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"names":["majorMinor","v","split","slice","join","Ssr","HTMLElementBase","find","root","querySelector","config","tagNames","ssr","version","this","getAttribute","stateData","script","JSON","parse","textContent","templates","map","Map","t","Array","from","children","localName","set","id","hydrateProps","getTemplate","get","verifyVersion","VERSION","defineSsr","registry","tag","define","BUILDER","Symbol","for","isServer","document","documentElement","hasAttribute","mark","data","createComment","isMark","n","nodeType","startsMark","prefix","startsWith","anchors","WeakMap","enginesByRoot","kept","skip","WeakSet","rawTexts","range","to","out","push","nextSibling","attrs","content","a","attributes","setAttribute","name","value","append","lastOf","b","nodes","first","length","region","after","blocks","branch","add","visitView","ForView","anchor","rowViews","visitBlock","cur","current","branches","index","c","RAW","Set","RAW_ATTR","raw","el","has","protectTexts","parent","childNodes","replaceWith","ids","snapshot","engine","getRootNode","engines","E","element","own","byAnchor","l","rootLists","values","view","extra","bs","rootBindings","chain","br","done","template","isConnected","h","querySelectorAll","w","createTreeWalker","acceptNode","scoped","nextNode","p","previousSibling","includes","parentNode","remove","cs","some","body","createElement","type","stringify","replace","charCodeAt","toString","padStart","json","target","key","Object","keys","d","getOwnPropertyDescriptor","e","parentElement","svg","importNode","templateContent","x","namespaceURI","createElementNS","before","build","doc","state","o","options","multiple","selectedIndex","disabled","toggleAttribute","selected","defaultValue","checked","forms","previousElementSibling","IMPL","held","deferred","hooks","componentScope","enters","nodesOf","r","rows","flat","concat","tail","drop","read","start","keep","row","m","exec","next","strip","Number","appendChild","walked","firstChild","prepare","container","adopt","walk","text","decodeURIComponent","copy","removeAttribute","replaceChild","run","isBlank","unshift","open","forEach","i","depth","prepend","mend","adoptScope","host","delete","prev","release","clear","comments","scope","currentNode","across","wiring","path","best","k","rest","ssrMark","node","source","isOuter","splice","setsContent","encodeURIComponent","close","es","size","isIfAnchor","commentIfPrefix","commentElseIfPrefix","commentElsePrefix","trim","fits","plan","fragment","paths","nodePaths","j","nodeName","scratch","isFor","head","shift","inner","fresh","single","cloneNode","install","phase","found","same","callHook","args","call","old","parseInt","console","warn","snap","hydrated","wirings","wiringOf","up","prop","parseBindTextsForElement","bindAttributeName","at","statePathName","propSegments","asIs","reverse","restore","_","f","test","legacy","queueMicrotask","hydrate","g","globalThis","reset","protocol","installBuilder","tags","registries","ssr_default"],"sources":["../../../src/ssr/element.ts","../../../src/ssr/ssr.ts","../../../src/features/ssr.ts"],"sourcesContent":["/**\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`).\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, 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/** Moves the blocks' nodes right after `after`, as one region. */\nfunction region(after: Node, blocks: Block[], branch: number | null): void {\n const nodes: Node[] = [mark(branch === null ? \"wcs-[\" : `wcs-[:${branch}`)];\n for (const b of blocks) {\n if (branch === null) nodes.push(mark(\"wcs-|\"));\n nodes.push(...range(b.first, lastOf(b)));\n }\n nodes.push(mark(\"wcs-]\"));\n (after as ChildNode).after(...nodes);\n for (const n of nodes) skip.add(n);\n}\n\nfunction visitView(v: ForView | IfView): void {\n if (v instanceof ForView) {\n region(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.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): (() => void) | null {\n const d = deferred.get(host);\n if (d === undefined) return null;\n deferred.delete(host);\n prepare(host, d.ssr, d.adopt);\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/** 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 if (old) legacy(container, ssr!, fresh);\n else prepare(container, ssr!, same);\n ssr!.remove();\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 => (held.get(n)?.tail ?? n).nextSibling;\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 = 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)\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 }\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 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"],"mappings":"yfAwBO,IAAMA,EAAcC,GAAsBA,EAAEC,MAAM,KAAKC,MAAM,EAAG,GAAGC,KAAK,KAElEC,EAAN,cAAkBC,EAEvB,WAAOC,CAAKC,GACV,OAASA,EAAoBC,gBAAgBC,EAAOC,SAASC,MAAuB,IACtF,CAEA,WAAIC,GACF,OAAOC,KAAKC,aAAa,YAAc,EACzC,CAEA,aAAIC,GACF,IAAMC,EAASH,KAAKL,cAAc,mCAClC,OAAkB,OAAXQ,EAAkB,CAAC,EAAIC,KAAKC,MAAMF,EAAOG,aAAe,KACjE,CAEA,aAAIC,GACF,IAAMC,EAAM,IAAIC,IAEhB,QAAWC,KAAKC,MAAMC,KAAKZ,KAAKa,UAAkC,aAAhBH,EAAEI,WAA0BN,EAAIO,IAAIL,EAAEM,GAAIN,GAC5F,OAAOF,CACT,CAEA,gBAAIS,GACF,MAAO,CAAC,CACV,CAEA,WAAAC,CAAYF,GACV,OAAOhB,KAAKO,UAAUY,IAAIH,IAAO,IACnC,CAEA,aAAAI,GACE,OAAOlC,EAAWc,KAAKD,WAAab,EAAWmC,EACjD,GAIK,SAASC,EAAUC,GACxB,IAAMC,EAAM5B,EAAOC,SAASC,SACF,I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C,WAAa,CAAC0G,GACnG,GAEFiF,EAAQtF,GACR,QAAWjD,KAAKnI,MAAMC,KAAMmL,EAAyB7E,iBAAiB,sBAAuB4B,EAAEuD,gBAAgB,kBACjH,CA8CWoF,CAAO1F,EAAWjM,EAAM4P,GAC5B5D,EAAQC,EAAWjM,EAAMkQ,GAC9BlQ,EAAK8H,SACDoI,IAGFxF,EAAMwB,GAAQA,GACd0F,eAAe,KACbtE,IACA5C,EAAMwB,GAAQ,OAGpB,CC9pBgC2F,CAAQ7L,GAClCqH,IAAOrH,EAAQgK,IDuRd,WACL,IAAM8B,EAAIC,WACVD,EAAEvH,GAAQ,CAAEd,QAAO,KAAAuI,GAAUlM,EAAM,CAAG,QAEnB,IAAfgM,EAAElQ,KACJkQ,EAAElQ,GAAW,CAAEqQ,SAAU,mBAAoBhS,QAAS,EAAGwJ,MAAQC,GAAkBoI,EAAEvH,GAAMd,MAAMC,GAAMsI,MAAO,IAAMF,EAAEvH,GAAMyH,SAEhI,CC5RIE,GAEAxH,EAAMyH,GAAOrL,EAAM4D,EAAMyH,GAAM3Q,GAC/B,QAAWsJ,KAAKsH,IAAc5Q,EAAUsJ,EAC1C,GAEKuH,GAAQrS","ignoreList":[]}
1
+ {"version":3,"names":["majorMinor","v","split","slice","join","Ssr","HTMLElementBase","find","root","querySelector","config","tagNames","ssr","version","this","getAttribute","stateData","script","JSON","parse","textContent","templates","map","Map","t","Array","from","children","localName","set","id","hydrateProps","getTemplate","get","verifyVersion","VERSION","defineSsr","registry","tag","define","BUILDER","Symbol","for","isServer","document","documentElement","hasAttribute","mark","data","createComment","isMark","n","nodeType","startsMark","prefix","startsWith","anchors","WeakMap","enginesByRoot","kept","skip","WeakSet","rawTexts","range","to","out","push","nextSibling","attrs","content","a","attributes","setAttribute","name","value","append","beside","anchorElement","region","blocks","branch","open","close","length","head","before","after","b","last","nodes","first","lastOf","add","visitView","ForView","anchor","rowViews","visitBlock","cur","current","branches","index","c","RAW","Set","RAW_ATTR","raw","el","has","protectTexts","parent","childNodes","replaceWith","ids","snapshot","engine","getRootNode","engines","E","element","own","byAnchor","l","rootLists","values","view","extra","bs","rootBindings","chain","br","done","template","isConnected","h","querySelectorAll","w","createTreeWalker","acceptNode","scoped","nextNode","p","previousSibling","includes","parentNode","remove","cs","some","body","createElement","type","stringify","replace","charCodeAt","toString","padStart","json","target","key","Object","keys","d","getOwnPropertyDescriptor","e","parentElement","svg","importNode","templateContent","x","namespaceURI","createElementNS","build","doc","state","o","options","multiple","selectedIndex","disabled","toggleAttribute","selected","defaultValue","checked","forms","previousElementSibling","IMPL","held","deferred","hooks","componentScope","enters","nodesOf","r","rows","flat","concat","tail","drop","read","start","keep","row","m","exec","next","strip","Number","appendChild","walked","firstChild","prepare","container","adopt","walk","text","decodeURIComponent","copy","removeAttribute","replaceChild","run","isBlank","unshift","forEach","i","depth","prepend","mend","adoptScope","host","delete","prev","release","clear","comments","scope","currentNode","across","wiring","path","best","k","rest","ssrMark","node","source","isOuter","splice","setsContent","encodeURIComponent","es","size","isIfAnchor","commentIfPrefix","commentElseIfPrefix","commentElsePrefix","trim","fits","plan","fragment","paths","nodePaths","j","nodeName","scratch","isFor","shift","inner","fresh","single","cloneNode","install","phase","found","same","callHook","args","call","old","parseInt","console","warn","snap","hydrated","queueMicrotask","edits","sel","marked","at","lastIndexOf","findIndex","defaultChecked","put","dispatchEvent","Event","bubbles","typed","wirings","wiringOf","up","prop","parseBindTextsForElement","bindAttributeName","statePathName","propSegments","asIs","reverse","restore","_","f","test","legacy","hydrate","g","globalThis","reset","protocol","installBuilder","tags","registries","ssr_default"],"sources":["../../../src/ssr/element.ts","../../../src/ssr/ssr.ts","../../../src/features/ssr.ts"],"sourcesContent":["/**\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`).\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, 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): (() => void) | null {\n const d = deferred.get(host);\n if (d === undefined) return null;\n deferred.delete(host);\n prepare(host, d.ssr, d.adopt);\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/** 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 // (taken before the page is bound, which writes the state's values; given back right after)\n queueMicrotask(typed(container));\n if (old) legacy(container, ssr!, fresh);\n else prepare(container, ssr!, same);\n ssr!.remove();\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 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.t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G,EAAEU,eAAgB,iBAAiBqM,KAAKD,GAAGrS,eAAeuD,IAAM,IAAMkJ,EAAKnJ,QAAQ0C,WAAa,CAACyG,GACnG,GAEF0F,EAAQ/F,GACR,QAAWhD,KAAK1I,MAAMC,KAAMyL,EAAyB5E,iBAAiB,sBAAuB4B,EAAEsD,gBAAgB,kBACjH,CAuFW6F,CAAOnG,EAAWvM,EAAM+P,GAC5BzD,EAAQC,EAAWvM,EAAMqQ,GAC9BrQ,EAAKqI,SACDgI,IAGFrF,EAAMwB,GAAQA,GACduE,eAAe,KACbpD,IACA3C,EAAMwB,GAAQ,OAGpB,CCttBgCmG,CAAQpM,GAClCmH,IAAOnH,EAAQ4J,IDsSd,WACL,IAAMyC,EAAIC,WACVD,EAAE/H,GAAQ,CAAEd,QAAO,KAAA+I,GAAUzM,EAAM,CAAG,QAEnB,IAAfuM,EAAEhR,KACJgR,EAAEhR,GAAW,CAAEmR,SAAU,mBAAoB9S,QAAS,EAAG8J,MAAQC,GAAkB4I,EAAE/H,GAAMd,MAAMC,GAAM8I,MAAO,IAAMF,EAAE/H,GAAMiI,SAEhI,CC3SIE,GAEAhI,EAAMiI,GAAO5L,EAAM2D,EAAMiI,GAAMzR,GAC/B,QAAW4J,KAAK8H,IAAc1R,EAAU4J,EAC1C,GAEK+H,GAAQnT","ignoreList":[]}
@@ -1,2 +1,2 @@
1
- import{a as t,c as e}from"../chunks/chunk-JK3B3LLB.js";import{a as n,b as r,c as s,d as i,e as l,j as o}from"../chunks/chunk-BGUJ3HF6.js";var a={},h=/\.\d/,u=new Set(Object.getOwnPropertyNames(Object.prototype)),f=0,c=!1,d=null,p=()=>{c=!1,f++};function m(){if(null===d)if("function"==typeof MessageChannel){let t=new MessageChannel;t.port1.onmessage=p,t.port1.unref?.(),d=()=>t.port2.postMessage(0)}else d=()=>setTimeout(p,0);return c||(c=!0,d()),f}function g(t,e){let n=new Set,r=[t];for(;r.length>0;){let t=r.pop();if(!n.has(t)){n.add(t);for(let n of t.Q){for(let r of e)if(n.ee(r)&&(n.n===r.n||!(r.n<t.n&&t.h[r.n+1].ee(r))))return!0;null!==n.getter&&r.push(n)}}}return!1}var y=class{constructor(t,e){this.active=!1,this.Pe=new Map,this.early=[],this.n=0,this.Ao=-1,this.Bn=new Set,this.He=null,this.engine=t,this.Ie=e}ur(){let t=this.engine;this.Pe.clear();let e=this.early;this.early=[];for(let e of this.Ie)e.getter=null!==e.p.getter||e.p.se,e.s=new WeakMap,this.prime(e,()=>{0===e.p.n?e.getter&&e.s.set(a,t.v(e.p,null)):this.Mn(e.p,1,null,n=>{e.getter&&this.prime(e,()=>e.s.set(n,t.v(e.p,n)))})});this.active=!0;let n=new Set;for(let[r,s,i,l]of e)if((null===s||s.y)&&Object.is(t.v(r,s),l)){n.add(r);for(let t of this.Ie)t.p===r&&this.ut(t,s,i,!0)}for(let t of this.Ie)t.getter&&0===t.p.n&&!this.Pe.has(t)&&g(v(t.p),n)&&this.ut(t,null,void 0,!0);this.Pe.size>0&&t.we()}prime(t,e){try{e()}catch(e){console.error(`[@wcstack/state] $watch initial evaluation of "${t.t}" threw.`,e),n.at?.(this.engine,{type:"state:watch-error",phase:"prime",path:t.t,error:e})}}Fo(){this.active=!1,this.Pe.clear(),this.early=[]}Mn(t,e,n,r){let s=this.engine.Ve(n,t.h[e]);for(let n of s.f)e===t.n?r(n):this.Mn(t,e+1,n,r)}ut(t,e,n,r){let s=this.Pe.get(t);void 0===s&&this.Pe.set(t,s=new Map);let i=s.get(e);void 0===i?s.set(e,[n,this.n,r]):(i[1]<this.n&&(i[1]=this.n),i[2]||=r)}ve(t,e,n,r,s,i){if(this.active){(this.He??=new Set).add(t);for(let i of this.Ie){let l=i.p;l.n!==t.n||!l.ee(t)||this.ut(i,e,i.getter?i.s.get(e??a):l===t&&s&&this.engine._t&&(null===r||"object"!=typeof r&&"function"!=typeof r)?n:void 0,!0)}}else i&&this.early.push([t,e,n,r])}ke(t,e){if(this.active)for(let n of this.Ie)(n.getter||=null!==n.p.getter||n.p.se)&&n.p.n===t.n&&n.p.ee(t)&&this.ut(n,e,n.s.get(e??a),!1)}Qt(t,e){if(!this.active)return;let n=null;for(let r of this.Ie){let s=r.p;if(!(s.n<t.n||s.h[t.n]!==t.o)){n??=new Set(e);for(let e of t.f)n.has(e)||(s.n===t.n?this.ut(r,e,void 0,!0):this.Mn(s,t.n+1,e,t=>this.ut(r,t,void 0,!0)))}}}Oe(){let t=this.He;if(this.He=null,!this.active||0===this.Pe.size)return;let e=this.Pe;this.Pe=new Map;let r=this.engine,s=[];for(let i of this.Ie){let l=e.get(i);if(void 0===l)continue;let o,u=[...l].filter(([t])=>null===t||t.y);u.length>1&&u.sort((t,e)=>$(t[0],e[0]));for(let[e,[l,f,c]]of u){let u,d="evaluate",p=r.u;this.n=f+1,r.Ae++;try{if(u=r.v(i.p,e),i.getter&&(i.s.set(e??a,u),Object.is(u,l)&&(h.test(i.t)||null!==e&&!c&&!(o??=null!==t&&g(v(i.p),t)))))continue;if(f>32){s.includes(i.t)||s.push(i.t);continue}r.u=e,n.at?.(r,{type:"state:watch-fired",path:i.t}),d="handler",i.handler.call(r.proxy,u,l,...r.H(e))}catch(t){console.error(`[@wcstack/state] $watch "${i.t}" failed; the other watches still run.`,t),n.at?.(r,{type:"state:watch-error",phase:d,path:i.t,error:t})}finally{r.u=p,this.n=0,r.Ae--}}}s.length>0&&this.Oo(s)}Oo(t){let e=m();e!==this.Ao&&(this.Ao=e,this.Bn.clear());let r=t.filter(t=>!this.Bn.has(t));if(0!==r.length){for(let t of r)this.Bn.add(t);console.error("[@wcstack/state] $watch handlers / $stream restarts kept writing for 32 batches; the chain is cut (nothing is rolled back)."),n.at?.(this.engine,{type:"state:watch-chain-limit",maxDepth:32,paths:r})}}};function v(t){for(;null===t.getter&&null!==t.d;)t=t.d;return t}function $(t,e){let n=[],r=[];for(let e=t;null!==e;e=e.l.ae)n.unshift(e.b);for(let t=e;null!==t;t=t.l.ae)r.unshift(t.b);for(let t=0;t<n.length&&t<r.length;t++)if(n[t]!==r[t])return n[t]-r[t];return n.length-r.length}var w="$streamStatus",b="$streamError",M=new Set(Object.getOwnPropertyNames(Object.prototype)),O=!1;function k(t,e){for(let n=t;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return void 0!==t.get||void 0!==t.set||"function"==typeof t.value}return!1}var j=class{constructor(t,e,n){this.engine=t,this.entries=e,this.M=n}set(t,e,n){O=!0;try{this.engine.T(this.engine.o(`${t}.${e}`),null,n)}finally{O=!1}}dr(){for(let t of this.entries)this.start(t,!0)}fr(){for(let t of this.entries)t.dt=!1,t.J?.abort(),t.J=null}pr(){for(let t of this.entries)t.dt=!1,null!==t.J&&(t.J.abort(),t.J=null),this.set(w,t.name,"idle")}ke(t){let e=this.M.n;for(let n of this.entries)n.g===t&&(n.n=n.dt?Math.max(n.n,e):e,n.dt=!0)}Oe(){let t=this.engine,n=this.M,r=[];for(let s of this.entries){if(!s.dt)continue;let i=s.n;if(s.dt=!1,i>32)r.push(s.name),s.g.z=e;else{n.n=i+1,t.Ae++;try{this.start(s,!1)}finally{t.Ae--,n.n=0}}}r.length>0&&n.Oo(r)}start(t,n){let r,s=this.engine;if(null!==t.J&&t.J.abort(),t.J=null,null!==t.g){let i=t.g;i.getter=t.args;let l=i.Q.slice();J(i);try{r=s.read(i,null),function(t,e,n){null!==n&&"function"==typeof n?.then&&o(`$stream "${t}": args must be synchronous (it returned a Promise).`);for(let n of e.Q)n.n>0&&o(`$stream "${t}": args must not read a wildcard path ("${n.t}").`),(n.t===t||n.t===`${w}.${t}`||n.t===`${b}.${t}`)&&o(`$stream "${t}": args must not read the stream itself ("${n.t}").`)}(t.name,i,r)}catch(r){J(i);for(let t of l)t._n(i);if(i.z=e,n)throw r;return this.set(b,t.name,r),void this.set(w,t.name,"error")}}let i=new AbortController;t.J=i,s.T(s.o(t.name),null,t.U),this.set(b,t.name,null),this.set(w,t.name,"active"),this.mr(t,i,r)}async mr(t,e,n){let r=this.engine,s=e.signal,i=()=>!s.aborted&&t.J===e,l=r.o(t.name),o=this.M.n,a=m(),h=t=>{m()===a&&(this.M.n=o);try{t()}finally{this.M.n=0}},u=t.U;try{let e=await t.source(n,s);if(!i())return;let o=e=>{u=void 0!==t.Co?t.Co(u,e):e,h(()=>r.T(l,null,u))};if(null!==e&&"function"==typeof e?.getReader){let t=e.getReader();for(s.addEventListener("abort",()=>{t.cancel().catch(()=>{})});;){let e=await t.read();if(!i())return;if(e.done)break;o(e.value)}}else{if(null===e||"function"!=typeof e?.[Symbol.asyncIterator])throw new TypeError(`$stream "${t.name}": source must return an async iterable or a ReadableStream`);{let t=e[Symbol.asyncIterator]();for(s.addEventListener("abort",()=>{t.return?.()});;){let e=await t.next();if(!i())return;if(e.done)break;o(e.value)}}}if(!i())return;t.J=null,h(()=>this.set(w,t.name,"done"))}catch(n){if(!i())return;t.J=null,e.abort(),h(()=>{this.set(b,t.name,n),this.set(w,t.name,"error")})}}};function J(e){for(let t of e.Q){let n=t.W.indexOf(e);n>=0&&t.W.splice(n,1),t.mt.delete(e)}e.Q.length=0,e.z=t}var P=new WeakMap;function C(t){let e=P.get(t);return e?.target===t.target?e:void 0}function S(t,e){let r=new y(t,function(t,e){if(void 0===e)return[];(null===e||"object"!=typeof e)&&o("$watch must be an object mapping paths to handler functions.");let r=[];for(let s of Object.keys(e)){let i=e[s];(""===s||"$"===s[0]||s.includes("@")||u.has(s))&&o(`$watch path "${s}" is not a path of the state tree.`),"function"!=typeof i&&o(`$watch entry "${s}" must be a function.`);let l=t.o(s);n.So?.(t,l,!0),r.push({t:s,p:l,handler:i,getter:!1,s:new WeakMap})}return r}(t,e.$watch)),s=new j(t,function(t,e){let n=e.$stream;if(void 0===n)return[];(null===n||"object"!=typeof n)&&o("$stream must be an object mapping stream names to definitions.");let r=[],s={},i={};for(let l of Object.keys(n)){let a=n[l];(""===l||"$"===l[0]||/[.*]/.test(l)||M.has(l))&&o(`$stream entry "${l}" must be a flat property name.`),(null===a||"object"!=typeof a)&&o(`$stream entry "${l}" must be an object.`);let h=a.source,u=a.fold,f=a.args,c=a.initial;"function"!=typeof h&&o(`$stream entry "${l}" needs a source function.`),void 0!==u&&"function"!=typeof u&&o(`$stream entry "${l}": fold must be a function.`),void 0!==u&&!("initial"in a)&&o(`$stream entry "${l}": fold needs an initial value.`),void 0!==f&&"function"!=typeof f&&o(`$stream entry "${l}": args must be a function.`),k(e,l)&&o(`$stream entry "${l}" collides with a getter, setter or method of the state.`),void 0===e[l]&&(e[l]=c),s[l]="idle",i[l]=null,r.push({name:l,source:h,Co:u,U:c,J:null,dt:!1,n:0,g:void 0===f?null:t.o(`$streamArgs.${l}`),args:void 0===f?null:function(){return f(this)}})}return e[w]=s,e[b]=i,r}(t,e),r),i=P.get(t);void 0!==i&&(i.M.Fo(),i.Ct.fr()),P.set(t,{M:r,Ct:s,Je:i?.Je??!1,target:e})}function A(t,e){let n=P.get(t);if(void 0!==n&&"mounting"!==e&&!document.documentElement?.hasAttribute("data-wcs-server")&&("reset"!==e&&(n.Je="connected"===e),n.target===t.target)){if("disconnected"===e)return n.M.Fo(),void n.Ct.pr();n.Je&&(n.M.ur(),n.Ct.dr())}}var I=["$streamStatus","$streamError"],Q={name:"temporal",install(){n.de=r(n.de,S),n.element=r(n.element,A),n.ve=r(n.ve,(t,e,n,r,s,i,l)=>C(t)?.M.ve(e,n,r,s,i,l)),n.ke=r(n.ke,(t,e,n)=>{let r=C(t);void 0!==r&&(r.M.ke(e,n),r.Ct.ke(e))}),n.Qt=r(n.Qt,(t,e,n)=>C(t)?.M.Qt(e,n)),n.Oe=r(n.Oe,t=>{let e=C(t);void 0!==e&&(e.M.Oe(),e.Ct.Oe())}),n.rt=s(l,n.rt,(t,e)=>{let n=e.split(".",1)[0];if(I.includes(n))return n===e?t.target[e]:t.read(t.o(e),null)}),n.Fe=s(i,n.Fe,(t,e)=>(!O&&36===e.t.charCodeAt(0)&&I.includes(e.t.split(".",1)[0])&&o(`"${e.t}" is read-only (the stream runtime owns it).`),!1))}},B=Q;export{B as default,Q as temporal};
1
+ import{a as t,c as e}from"../chunks/chunk-5Q4M6A3C.js";import{a as n,b as r,c as s,d as i,e as l,j as o}from"../chunks/chunk-BGUJ3HF6.js";var a={},h=/\.\d/,u=new Set(Object.getOwnPropertyNames(Object.prototype)),f=0,c=!1,d=null,p=()=>{c=!1,f++};function m(){if(null===d)if("function"==typeof MessageChannel){let t=new MessageChannel;t.port1.onmessage=p,t.port1.unref?.(),d=()=>t.port2.postMessage(0)}else d=()=>setTimeout(p,0);return c||(c=!0,d()),f}function g(t,e){let n=new Set,r=[t];for(;r.length>0;){let t=r.pop();if(!n.has(t)){n.add(t);for(let n of t.Q){for(let r of e)if(n.ee(r)&&(n.n===r.n||!(r.n<t.n&&t.h[r.n+1].ee(r))))return!0;null!==n.getter&&r.push(n)}}}return!1}var y=class{constructor(t,e){this.active=!1,this.Te=new Map,this.early=[],this.n=0,this.Ao=-1,this.Bn=new Set,this.Ke=null,this.engine=t,this.De=e}ur(){let t=this.engine;this.Te.clear();let e=this.early;this.early=[];for(let e of this.De)e.getter=null!==e.p.getter||e.p.se,e.s=new WeakMap,this.prime(e,()=>{0===e.p.n?e.getter&&e.s.set(a,t.v(e.p,null)):this.Mn(e.p,1,null,n=>{e.getter&&this.prime(e,()=>e.s.set(n,t.v(e.p,n)))})});this.active=!0;let n=new Set;for(let[r,s,i,l]of e)if((null===s||s.w)&&Object.is(t.v(r,s),l)){n.add(r);for(let t of this.De)t.p===r&&this.ut(t,s,i,!0)}for(let t of this.De)t.getter&&0===t.p.n&&!this.Te.has(t)&&g(v(t.p),n)&&this.ut(t,null,void 0,!0);this.Te.size>0&&t.we()}prime(t,e){try{e()}catch(e){console.error(`[@wcstack/state] $watch initial evaluation of "${t.t}" threw.`,e),n.st?.(this.engine,{type:"state:watch-error",phase:"prime",path:t.t,error:e})}}Fo(){this.active=!1,this.Te.clear(),this.early=[]}Mn(t,e,n,r){let s=this.engine.He(n,t.h[e]);for(let n of s.f)e===t.n?r(n):this.Mn(t,e+1,n,r)}ut(t,e,n,r){let s=this.Te.get(t);void 0===s&&this.Te.set(t,s=new Map);let i=s.get(e);void 0===i?s.set(e,[n,this.n,r]):(i[1]<this.n&&(i[1]=this.n),i[2]||=r)}ve(t,e,n,r,s,i){if(this.active){(this.Ke??=new Set).add(t);for(let i of this.De){let l=i.p;l.n!==t.n||!l.ee(t)||this.ut(i,e,i.getter?i.s.get(e??a):l===t&&s&&this.engine._t&&(null===r||"object"!=typeof r&&"function"!=typeof r)?n:void 0,!0)}}else i&&this.early.push([t,e,n,r])}ke(t,e){if(this.active)for(let n of this.De)(n.getter||=null!==n.p.getter||n.p.se)&&n.p.n===t.n&&n.p.ee(t)&&this.ut(n,e,n.s.get(e??a),!1)}Qt(t,e){if(!this.active)return;let n=null;for(let r of this.De){let s=r.p;if(!(s.n<t.n||s.h[t.n]!==t.o)){n??=new Set(e);for(let e of t.f)n.has(e)||(s.n===t.n?this.ut(r,e,void 0,!0):this.Mn(s,t.n+1,e,t=>this.ut(r,t,void 0,!0)))}}}Ce(){let t=this.Ke;if(this.Ke=null,!this.active||0===this.Te.size)return;let e=this.Te;this.Te=new Map;let r=this.engine,s=[];for(let i of this.De){let l=e.get(i);if(void 0===l)continue;let o,u=[...l].filter(([t])=>null===t||t.w);u.length>1&&u.sort((t,e)=>$(t[0],e[0]));for(let[e,[l,f,c]]of u){let u,d="evaluate",p=r.u;this.n=f+1,r.Fe++;try{if(u=r.v(i.p,e),i.getter&&(i.s.set(e??a,u),Object.is(u,l)&&(h.test(i.t)||null!==e&&!c&&!(o??=null!==t&&g(v(i.p),t)))))continue;if(f>32){s.includes(i.t)||s.push(i.t);continue}r.u=e,n.st?.(r,{type:"state:watch-fired",path:i.t}),d="handler",i.handler.call(r.proxy,u,l,...r.H(e))}catch(t){console.error(`[@wcstack/state] $watch "${i.t}" failed; the other watches still run.`,t),n.st?.(r,{type:"state:watch-error",phase:d,path:i.t,error:t})}finally{r.u=p,this.n=0,r.Fe--}}}s.length>0&&this.Oo(s)}Oo(t){let e=m();e!==this.Ao&&(this.Ao=e,this.Bn.clear());let r=t.filter(t=>!this.Bn.has(t));if(0!==r.length){for(let t of r)this.Bn.add(t);console.error("[@wcstack/state] $watch handlers / $stream restarts kept writing for 32 batches; the chain is cut (nothing is rolled back)."),n.st?.(this.engine,{type:"state:watch-chain-limit",maxDepth:32,paths:r})}}};function v(t){for(;null===t.getter&&null!==t.d;)t=t.d;return t}function $(t,e){let n=[],r=[];for(let e=t;null!==e;e=e.l.ae)n.unshift(e.y);for(let t=e;null!==t;t=t.l.ae)r.unshift(t.y);for(let t=0;t<n.length&&t<r.length;t++)if(n[t]!==r[t])return n[t]-r[t];return n.length-r.length}var w="$streamStatus",b="$streamError",M=new Set(Object.getOwnPropertyNames(Object.prototype)),k=!1;function j(t,e){for(let n=t;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return void 0!==t.get||void 0!==t.set||"function"==typeof t.value}return!1}var O=class{constructor(t,e,n){this.engine=t,this.entries=e,this.M=n}set(t,e,n){k=!0;try{this.engine.A(this.engine.o(`${t}.${e}`),null,n)}finally{k=!1}}dr(){for(let t of this.entries)this.start(t,!0)}fr(){for(let t of this.entries)t.dt=!1,t.J?.abort(),t.J=null}pr(){for(let t of this.entries)t.dt=!1,null!==t.J&&(t.J.abort(),t.J=null),this.set(w,t.name,"idle")}ke(t){let e=this.M.n;for(let n of this.entries)n.g===t&&(n.n=n.dt?Math.max(n.n,e):e,n.dt=!0)}Ce(){let t=this.engine,n=this.M,r=[];for(let s of this.entries){if(!s.dt)continue;let i=s.n;if(s.dt=!1,i>32)r.push(s.name),s.g.Y=e;else{n.n=i+1,t.Fe++;try{this.start(s,!1)}finally{t.Fe--,n.n=0}}}r.length>0&&n.Oo(r)}start(t,n){let r,s=this.engine;if(null!==t.J&&t.J.abort(),t.J=null,null!==t.g){let i=t.g;i.getter=t.args;let l=i.Q.slice();C(i);try{r=s.read(i,null),function(t,e,n){null!==n&&"function"==typeof n?.then&&o(`$stream "${t}": args must be synchronous (it returned a Promise).`);for(let n of e.Q)n.n>0&&o(`$stream "${t}": args must not read a wildcard path ("${n.t}").`),(n.t===t||n.t===`${w}.${t}`||n.t===`${b}.${t}`)&&o(`$stream "${t}": args must not read the stream itself ("${n.t}").`)}(t.name,i,r)}catch(r){C(i);for(let t of l)t._n(i);if(i.Y=e,n)throw r;return this.set(b,t.name,r),void this.set(w,t.name,"error")}}let i=new AbortController;t.J=i,s.A(s.o(t.name),null,t.U),this.set(b,t.name,null),this.set(w,t.name,"active"),this.mr(t,i,r)}async mr(t,e,n){let r=this.engine,s=e.signal,i=()=>!s.aborted&&t.J===e,l=r.o(t.name),o=this.M.n,a=m(),h=t=>{m()===a&&(this.M.n=o);try{t()}finally{this.M.n=0}},u=t.U;try{let e=await t.source(n,s);if(!i())return;let o=e=>{u=void 0!==t.Co?t.Co(u,e):e,h(()=>r.A(l,null,u))};if(null!==e&&"function"==typeof e?.getReader){let t=e.getReader();for(s.addEventListener("abort",()=>{t.cancel().catch(()=>{})});;){let e=await t.read();if(!i())return;if(e.done)break;o(e.value)}}else{if(null===e||"function"!=typeof e?.[Symbol.asyncIterator])throw new TypeError(`$stream "${t.name}": source must return an async iterable or a ReadableStream`);{let t=e[Symbol.asyncIterator]();for(s.addEventListener("abort",()=>{t.return?.()});;){let e=await t.next();if(!i())return;if(e.done)break;o(e.value)}}}if(!i())return;t.J=null,h(()=>this.set(w,t.name,"done"))}catch(n){if(!i())return;t.J=null,e.abort(),h(()=>{this.set(b,t.name,n),this.set(w,t.name,"error")})}}};function C(e){for(let t of e.Q){let n=t.W.indexOf(e);n>=0&&t.W.splice(n,1),t.mt.delete(e)}e.Q.length=0,e.Y=t}var J=new WeakMap;function S(t){let e=J.get(t);return e?.target===t.target?e:void 0}function T(t,e){let r=new y(t,function(t,e){if(void 0===e)return[];(null===e||"object"!=typeof e)&&o("$watch must be an object mapping paths to handler functions.");let r=[];for(let s of Object.keys(e)){let i=e[s];(""===s||"$"===s[0]||s.includes("@")||u.has(s))&&o(`$watch path "${s}" is not a path of the state tree.`),"function"!=typeof i&&o(`$watch entry "${s}" must be a function.`);let l=t.o(s);n.So?.(t,l,!0),r.push({t:s,p:l,handler:i,getter:!1,s:new WeakMap})}return r}(t,e.$watch)),s=new O(t,function(t,e){let n=e.$stream;if(void 0===n)return[];(null===n||"object"!=typeof n)&&o("$stream must be an object mapping stream names to definitions.");let r=[],s={},i={};for(let l of Object.keys(n)){let a=n[l];(""===l||"$"===l[0]||/[.*]/.test(l)||M.has(l))&&o(`$stream entry "${l}" must be a flat property name.`),(null===a||"object"!=typeof a)&&o(`$stream entry "${l}" must be an object.`);let h=a.source,u=a.fold,f=a.args,c=a.initial;"function"!=typeof h&&o(`$stream entry "${l}" needs a source function.`),void 0!==u&&"function"!=typeof u&&o(`$stream entry "${l}": fold must be a function.`),void 0!==u&&!("initial"in a)&&o(`$stream entry "${l}": fold needs an initial value.`),void 0!==f&&"function"!=typeof f&&o(`$stream entry "${l}": args must be a function.`),j(e,l)&&o(`$stream entry "${l}" collides with a getter, setter or method of the state.`),void 0===e[l]&&(e[l]=c),s[l]="idle",i[l]=null,r.push({name:l,source:h,Co:u,U:c,J:null,dt:!1,n:0,g:void 0===f?null:t.o(`$streamArgs.${l}`),args:void 0===f?null:function(){return f(this)}})}return e[w]=s,e[b]=i,r}(t,e),r),i=J.get(t);void 0!==i&&(i.M.Fo(),i.Ct.fr()),J.set(t,{M:r,Ct:s,Ge:i?.Ge??!1,target:e})}function A(t,e){let n=J.get(t);if(void 0!==n&&"mounting"!==e&&!document.documentElement?.hasAttribute("data-wcs-server")&&("reset"!==e&&(n.Ge="connected"===e),n.target===t.target)){if("disconnected"===e)return n.M.Fo(),void n.Ct.pr();n.Ge&&(n.M.ur(),n.Ct.dr())}}var D=["$streamStatus","$streamError"],Q={name:"temporal",install(){n.de=r(n.de,T),n.element=r(n.element,A),n.ve=r(n.ve,(t,e,n,r,s,i,l)=>S(t)?.M.ve(e,n,r,s,i,l)),n.ke=r(n.ke,(t,e,n)=>{let r=S(t);void 0!==r&&(r.M.ke(e,n),r.Ct.ke(e))}),n.Qt=r(n.Qt,(t,e,n)=>S(t)?.M.Qt(e,n)),n.Ce=r(n.Ce,t=>{let e=S(t);void 0!==e&&(e.M.Ce(),e.Ct.Ce())}),n.ot=s(l,n.ot,(t,e)=>{let n=e.split(".",1)[0];if(D.includes(n))return n===e?t.target[e]:t.read(t.o(e),null)}),n.Oe=s(i,n.Oe,(t,e)=>(!k&&36===e.t.charCodeAt(0)&&D.includes(e.t.split(".",1)[0])&&o(`"${e.t}" is read-only (the stream runtime owns it).`),!1))}},F=Q;export{F as default,Q as temporal};
2
2
  //# sourceMappingURL=temporal.js.map
@@ -134,8 +134,7 @@
134
134
  "hasArgs": true,
135
135
  "resultType": "boolean",
136
136
  "acceptTypes": [
137
- "number",
138
- "string"
137
+ "number"
139
138
  ],
140
139
  "minArgs": 1,
141
140
  "maxArgs": 1,
@@ -148,8 +147,7 @@
148
147
  "hasArgs": true,
149
148
  "resultType": "boolean",
150
149
  "acceptTypes": [
151
- "number",
152
- "string"
150
+ "number"
153
151
  ],
154
152
  "minArgs": 1,
155
153
  "maxArgs": 1,
@@ -162,8 +160,7 @@
162
160
  "hasArgs": true,
163
161
  "resultType": "boolean",
164
162
  "acceptTypes": [
165
- "number",
166
- "string"
163
+ "number"
167
164
  ],
168
165
  "minArgs": 1,
169
166
  "maxArgs": 1,
@@ -176,8 +173,7 @@
176
173
  "hasArgs": true,
177
174
  "resultType": "boolean",
178
175
  "acceptTypes": [
179
- "number",
180
- "string"
176
+ "number"
181
177
  ],
182
178
  "minArgs": 1,
183
179
  "maxArgs": 1,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wcstack/state",
3
- "version": "4.2.0",
3
+ "version": "4.3.0",
4
4
  "description": "Reactive state management with declarative data binding for Web Components. Zero dependencies, buildless.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.esm.js",
@@ -1,2 +0,0 @@
1
- import{b as t,c as e,d as s}from"./chunk-BYQBV3ZC.js";import{n as i,o as n}from"./chunk-4ECL4ITF.js";import{f as o}from"./chunk-BI4645UG.js";import{a,b as r}from"./chunk-CIBJLAA3.js";import{a as l,b as c}from"./chunk-UBGJGMSG.js";import{a as h,h as u,i as d}from"./chunk-BGUJ3HF6.js";var m=0,f=new WeakMap;function p(t,e=t.getRootNode()){f.set(e,[...f.get(e)??[],t].filter((t,e,s)=>t.isConnected&&s.lastIndexOf(t)===e))}function b(t){let e=f.get(t)??[],s=e.filter(e=>e.getRootNode()===t);return Promise.any(s.map(t=>t.initializePromise.then(()=>t.V||t.connectedCallbackPromise))).then(()=>{},i=>s.length?f.get(t)!==e?b(t):Promise.reject(i.errors[0]):void 0)}var g=typeof HTMLElement>"u"?class{}:HTMLElement,w=class extends g{constructor(){super(),this.engine=null,this.jn=!1,this.qe=!1,this.U=null,this.Ge=null,this.loaded=!1,this.un=null,this.connectedCallbackPromise=new Promise((t,e)=>{this.cn=t,this.Eo=e}),this.connectedCallbackPromise.catch(()=>{}),this.initializePromise=new Promise(t=>{this.an=t})}static{this.getBindingsReady=b}static{this.hasConnectedCallbackPromise=!0}connectedCallback(){if(this.jn){if(null!==this.Ge)return void this.Ge.Je();p(this);let e=this.engine;if(null!==e){let s=e.root;s===this.getRootNode()&&!i.has(s)&&i.set(s,e),t(),h.element?.(e,"back"),this.No("$connectedCallback",50,()=>{this.isConnected&&h.element?.(e,"connected")})}return}this.jn=!0;let e=this.getRootNode(),s=h.ct?.(this,e);if(s)return this.Ge=s,!s.xo&&this.parentNode instanceof ShadowRoot&&p(this),void(void 0===s.bt?this.Ro():s.bt()).then(t=>(this.loaded=!0,s.start(t,()=>this.Po()))).then(()=>{this.an(),this.cn()},t=>this.xt(t,s.xo));this.start(e),p(this)}disconnectedCallback(){if(null!==this.Ge)return void this.Ge.Ln();let t=this.engine;if(null===t)return;let e=t.root;i.get(e)===t&&i.delete(e),p(this,e),this.No("$disconnectedCallback",51),h.element?.(t,"disconnected")}setInitialState(t){if(this.qe&&c(14),this.loaded)this.Ge.reset(t);else if(null===this.engine)if(null!==this.un){let e=this.un;this.un=null,e(t)}else this.U=t;else this.engine.reset(t)}createState(t,e){let s=this.engine;null===s&&c(15),"readonly"===t&&s.Le++;try{e(s.proxy)}finally{"readonly"===t&&s.Le--}}async createStateAsync(t,e){let s=this.engine;null===s&&c(15),await e("writable"===t?s.proxy:new Proxy(s.proxy,{get(t,e,s){let i=Reflect.get(t,e,s);return"$setAll"===e||"$resolve"===e?(...t)=>(t.length>2&&c(8),i(...t)):i},set(){c(8)}}))}async Ro(){await 0;let t=this.getAttribute("state");if(null!==t){let e=e=>[...e.querySelectorAll('script[type="application/json"]')].find(e=>e.id===t),s=e(this.getRootNode())??e(document);return void 0===s?Promise.reject(new Error(`[@wcstack/state] ${l(16,[t])}`)):Promise.resolve(JSON.parse(s.textContent||"{}"))}let e=this.getAttribute("src");if(null!==e)return async function(t){let e=new URL(t,document.baseURI).href;if(/\.json(?:[?#]|$)/.test(e)){let s=await fetch(e);return s.ok||c(13,[t,s.status]),await s.json()}return(await(import(e))).default??{}}(e);let s=this.getAttribute("json");if(null!==s)return Promise.resolve(JSON.parse(s));let i=this.querySelector('script[type="module"]');return null!==i?async function(t){let e=!1,s=t=>{t.effectiveDirective.startsWith("script-src")&&(e=!0)};document.addEventListener("securitypolicyviolation",s);let i="function"==typeof URL.createObjectURL,n=i?URL.createObjectURL(new Blob([t.text],{type:"application/javascript"})):"data:text/javascript;charset=utf-8,"+encodeURIComponent(`${t.text}\n//${++m}`);try{return(await(import(n))).default??{}}catch(t){throw await new Promise(t=>setTimeout(t)),new Error(`[@wcstack/state] ${e?l(42):l(43,[t instanceof Error?t.message:String(t)])}`,{cause:t})}finally{document.removeEventListener("securitypolicyviolation",s),i&&URL.revokeObjectURL(n)}}(i):null!==this.U?Promise.resolve(this.U):new Promise(t=>{this.un=t})}async start(e){try{let a=e.host;(this.hasAttribute("mount")||this.hasAttribute("bind-component")||a?.hasAttribute("data-wc-definition"))&&d("scopes","<wcs-state>");let r=await this.Ro(),l=u(r);if(l&&await l,this.getRootNode()!==e)return this.U=r,this.jn=!1,void(this.isConnected&&this.connectedCallback());this.hasAttribute("enable-ssr")&&d("ssr","enable-ssr");let m=i.get(e)?.element;m?.isConnected&&(m.V||m.Ge)&&c(47);let f=new o(r,new s);f.element=this,this.engine=f,h.element?.(f,"mounting"),n(f,e),t(),f.En(),this.Po(),await f.Se("$connectedCallback"),this.isConnected&&h.element?.(f,"connected"),this.cn()}catch(t){this.qe=!this.V,this.xt(t)}}Po(){this.V=!0,this.an()}xt(t,e){this.Ue(this.V?50:49,t),this.an(),e?this.cn():this.Eo(t)}Ue(t,e){let s=["mount","bind-component","state","src"].flatMap(t=>this.hasAttribute(t)?[t,this.getAttribute(t)]:[]);console.error(`[@wcstack/state] ${l(t,[this.localName,...s])}`,e)}No(t,e,s){(async()=>this.engine.Se(t))().then(s,t=>this.Ue(e,t))}},y=[];function v(){return(y=y.filter(t=>t.deref())).map(t=>t.deref())}function k(t,s){t&&r(t),function(t=customElements){e(),v().includes(t)||y.push(new WeakRef(t));let s=a.tagNames.state;void 0===t.get(s)&&t.define(s,class extends w{}),h.To?.(t)}(s)}var R=t=>b(t);export{b as a,g as b,v as c,k as d,R as e};
2
- //# sourceMappingURL=chunk-3Q7LGONS.js.map
@@ -1 +0,0 @@
1
- {"version":3,"names":["loads","readyByRoot","WeakMap","enroll","el","root","getRootNode","set","get","filter","e","i","a","isConnected","lastIndexOf","getBindingsReady","list","els","Promise","any","map","initializePromise","then","bound","connectedCallbackPromise","length","reject","errors","HTMLElementBase","HTMLElement","WcsState","constructor","super","this","engine","started","failed","initial","claimed","loaded","receiveInitial","resolve","resolveConnected","rejectConnected","catch","resolveInitialize","hasConnectedCallbackPromise","connectedCallback","connected","engines","has","drainBinds","hooks","element","rerun","claim","lenient","parentNode","ShadowRoot","load","loadState","state","start","built","fail","disconnectedCallback","disconnected","delete","setInitialState","raise","reset","receive","createState","mutability","callback","readonlyDepth","proxy","createStateAsync","Proxy","t","k","receiver","v","Reflect","id","getAttribute","find","r","querySelectorAll","x","script","document","Error","text","JSON","parse","textContent","src","async","url","URL","baseURI","href","test","res","fetch","ok","status","json","default","loadSrc","querySelector","blocked","seen","effectiveDirective","startsWith","addEventListener","blob","createObjectURL","Blob","type","encodeURIComponent","setTimeout","message","String","cause","removeEventListener","revokeObjectURL","loadInnerScript","host","hasAttribute","requireFeature","loading","loadFeatures","other","Engine","DirtyStrategy","mount","watchRendered","callHook","report","at","flatMap","n","console","error","localName","name","refs","registries","deref","bootstrapState","partial","registry","setConfig","customElements","installBinder","includes","push","WeakRef","tag","config","tagNames","define","tags","buildBindings","b","j","I","z","q"],"sources":["../../../src/element.ts"],"sourcesContent":["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\";\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 const mod = await import(/* @vite-ignore */ 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 console.error(`[@wcstack/state] ${text(id, [this.localName, ...at])}`, e);\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"],"mappings":"4RAUA,IAOIA,EAAQ,EA2CNC,EAAc,IAAIC,QAMxB,SAASC,EAAOC,EAAcC,EAAaD,EAAGE,eAC5CL,EAAYM,IAAIF,EAAM,IAAKJ,EAAYO,IAAIH,IAAS,GAAKD,GAAIK,OAAO,CAACC,EAAGC,EAAGC,IAAMF,EAAEG,aAAeD,EAAEE,YAAYJ,KAAOC,GACzH,CAUO,SAASI,EAAiBV,GAC/B,IAAMW,EAAOf,EAAYO,IAAIH,IAAS,GAChCY,EAAMD,EAAKP,OAAQC,GAAMA,EAAEJ,gBAAkBD,GACnD,OAAOa,QAAQC,IAAIF,EAAIG,IAAKhB,GAAOA,EAAGiB,kBAAkBC,KAAK,IAAelB,EAAGmB,GAASnB,EAAGoB,4BAA4BF,KACrH,OAGCZ,GAAuBO,EAAIQ,OAASxB,EAAYO,IAAIH,KAAUW,EAAOD,EAAiBV,GAAQa,QAAQQ,OAAOhB,EAAEiB,OAAU,SAAM,EAEpI,CAOO,IAAMC,SAA0BC,YAAgB,IAAc,QAAWA,YAOnEC,EAAN,cAAuBF,EA2B5B,WAAAG,GACEC,QAvBFC,KAAAC,OAAwB,KAUxBD,KAAQE,IAAU,EAElBF,KAAQG,IAAS,EAC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