brumate 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/dist/cli.js +2 -2
  2. package/dist/{client-glvRglTB.js → client-De-7aGlO.js} +32 -8
  3. package/dist/client-De-7aGlO.js.map +1 -0
  4. package/dist/{defer-CNYYG-A5.js → defer-DlFYiAuK.js} +2 -2
  5. package/dist/{defer-CNYYG-A5.js.map → defer-DlFYiAuK.js.map} +1 -1
  6. package/dist/{devtools-D8EioKXs.js → devtools-Di_dI9tS.js} +4 -4
  7. package/dist/{devtools-D8EioKXs.js.map → devtools-Di_dI9tS.js.map} +1 -1
  8. package/dist/{devtools-panel-BKmBqkau.js → devtools-panel-BvIKX1LY.js} +2 -2
  9. package/dist/{devtools-panel-BKmBqkau.js.map → devtools-panel-BvIKX1LY.js.map} +1 -1
  10. package/dist/{files-ClQJlDcB.js → files-s4wmjcZV.js} +2 -2
  11. package/dist/{files-ClQJlDcB.js.map → files-s4wmjcZV.js.map} +1 -1
  12. package/dist/index.js +1 -1
  13. package/dist/{inspect-B8i6R3mZ.js → inspect-BLPt-dZZ.js} +16 -11
  14. package/dist/{inspect-B8i6R3mZ.js.map → inspect-BLPt-dZZ.js.map} +1 -1
  15. package/dist/{loader-DB0i9MwD.js → loader-krRrJuIv.js} +2 -2
  16. package/dist/{loader-DB0i9MwD.js.map → loader-krRrJuIv.js.map} +1 -1
  17. package/dist/{rpc-BHlxmeWe.js → rpc-BYYAj1vV.js} +2 -2
  18. package/dist/{rpc-BHlxmeWe.js.map → rpc-BYYAj1vV.js.map} +1 -1
  19. package/dist/runtime/client.js +1 -1
  20. package/dist/runtime/devtools.js +1 -1
  21. package/dist/runtime/loader.js +2 -2
  22. package/dist/runtime/static-loader.js +1 -1
  23. package/dist/runtime/testing.js +1 -1
  24. package/dist/{static-loader-D0ARlMxM.js → static-loader-DoHWsf9t.js} +2 -2
  25. package/dist/{static-loader-D0ARlMxM.js.map → static-loader-DoHWsf9t.js.map} +1 -1
  26. package/dist/vite.js +2 -2
  27. package/package.json +1 -1
  28. package/dist/client-glvRglTB.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"client-glvRglTB.js","names":["loading","loading","resolve","waiting","resolve","hold","give","noop","spreadText","resolve","fillRange","noop","within","noop"],"sources":["../src/runtime/client/state.ts","../src/runtime/client/blocks.ts","../src/runtime/client/code.ts","../src/runtime/client/scopes.ts","../src/runtime/client/titles.ts","../src/runtime/client/insert.ts","../src/runtime/client/references.ts","../src/runtime/client/children.ts","../src/runtime/client/errors.ts","../src/runtime/client/updates.ts","../src/runtime/client/context.ts","../src/runtime/client/guesses.ts","../src/runtime/client/handlers.ts","../src/runtime/client/resume.ts","../src/runtime/client/templates.ts","../src/runtime/client/components.ts","../src/runtime/client/props.ts","../src/runtime/client/inserts.ts","../src/runtime/client/waits.ts","../src/runtime/client/branches.ts","../src/runtime/client/lists.ts","../src/runtime/client/page.ts","../src/runtime/client.ts"],"sourcesContent":["// The types of the core and the state that its modules share: the options, the scopes, the loaded\n// modules and parts, and the indexes of comments and elements. It imports no code of the core.\n\nimport type { NavigationReport } from '../navigate.ts';\nimport type { PageState, ScopeId } from '../shared.ts';\nimport type { SerialEntry } from '../values.ts';\nimport type { HiddenBody, Hiding } from './branches.ts';\nimport type { Component } from './components.ts';\n\ntype Update = [kind: number, name: string];\n\n/** The entry of a compiled client module. */\nexport interface ClientModule {\n id: string;\n /** Prop names to slot indices. `*` is the slot of a props object. */\n props: Record<string, number>;\n /** Scope kind, then slot, to the updates that read it. */\n g: Record<number, Record<number, Update[]>>;\n /**\n * The render functions of components that this component sends as values, such as in a\n * prop. The state holds only their IDs, so `dynamic` finds them here.\n */\n components?: (Component & { brumateId: string })[];\n /** Server function ID to the memos that call it, as scope kind and update, for `refresh`. */\n refresh?: Record<string, Update[]>;\n /**\n * The `#try` blocks that catch errors of client code, by the scope kinds\n * inside their bodies: the kind of the scope that holds the block, the\n * anchor of the block, the render functions of the body and the `#catch`\n * body, and the kinds of both bodies, and the holder of a block in children.\n */\n t?: Record<\n number,\n [\n owner: number,\n anchor: number,\n body: string,\n fallback: string,\n kinds: number[],\n holderKind?: number,\n holderAnchor?: number,\n ]\n >;\n}\n\n/** The instance of a scope in the page. */\nexport interface Scope {\n id: ScopeId;\n /** The scope's ID in the compiled component. */\n k: number;\n p?: Scope;\n /** The component ID, for a component's root scope. */\n m?: string;\n s: unknown[];\n /** The item of a list item scope. */\n i?: unknown;\n c?: Record<number, ScopeId>;\n /** The scope that rendered a component's root scope. */\n o?: Scope;\n /** The root scopes of the components that this scope rendered, which go with it. */\n owned?: Set<Scope>;\n /** For children that a component inserted, the scope where they are, for contexts. */\n t?: Scope;\n /** For a component that passes its children on, the scope where they are finally inserted. */\n f?: Scope;\n /** For the scope of a template, the scope where it was called, which errors go to. */\n l?: Scope;\n /** The values that the scope provides, by context key. */\n v?: Record<string, unknown>;\n /** The slots that hold the contexts that the scope reads, by context key. */\n x?: Record<string, number>;\n /** The slots of a parent that the bound props of a component write, by the slot of the prop. */\n /**\n * What the bound props write, by the slot of the prop: a slot of a parent,\n * or the setter of `$bind(name, fn)`, as a function or a reference.\n */\n b?: Record<number, unknown>;\n /**\n * The slots that hold a promise prop. It stays a promise, which a read returns as it is,\n * whether or not it settled.\n */\n plain?: Set<number>;\n /** The promise props that the component received, until `setSlots` takes them. */\n props?: Promise<unknown>[] | undefined;\n /** The scopes inside it, made with the first one. */\n children?: Set<Scope>;\n /** The `b-root` of the render that the server rendered the scope in. */\n r?: string;\n cleanups?: Map<string, () => void>;\n keys?: Map<number, unknown>;\n /** Set while the scope is the body of an `#offscreen` block that is hidden. */\n h?: HiddenBody;\n /** Effects and `$client` callbacks to run when the `#offscreen` body around the scope shows. */\n w?: Set<string>;\n /**\n * The nodes that updates write, by anchor, of markup that the browser cloned: elements, and\n * the start comments of text inserts.\n */\n n?: Node[];\n /**\n * The latest value written at each place of the markup that was ever given a promise, by\n * anchor, or anchor and attribute name, so an older promise that settles later writes nothing.\n */\n q?: Record<string, unknown>;\n}\n\nexport interface CoreOptions {\n /** The exports of the serial entry, for the values of the app in the page state. */\n serial?: SerialEntry;\n /**\n * Imports the client module of a component. Undefined for a component that\n * has no client code, which a build leaves out.\n */\n load: (id: string) => Promise<ClientModule> | undefined;\n /** Adds event listeners for the `b-on` attributes in new markup. */\n listen: (root: ParentNode) => void;\n /** Tells the loader that the markup that `listen` scanned is in the page now. */\n inserted?: () => void;\n /** The URL prefix of server function calls. Defaults to `/_brumate`. */\n rpc?: string;\n /** The ID of the build of the page, for skew protection. Calls send it, and a deploy is noticed. */\n build?: string;\n /**\n * Receives every error of client code first: of a handler, an effect, a\n * `$client` callback or a memo that loads. `scope` is the ID of the scope\n * that the code belongs to, when it has one.\n */\n onError?: (error: unknown, info: { scope?: ScopeId }) => void;\n}\n\nexport let options: CoreOptions;\n\n/** The URL prefix of server function calls, from the options. */\nexport let rpcPrefix = '/_brumate';\n\n/** The ID of the build of the page, from the loader. Undefined on the dev server. */\nexport let build: string | undefined;\n\n/** Sets the options of the page, with the prefix of server function calls and the build. */\nexport function configure(value: CoreOptions): void {\n options = value;\n rpcPrefix = value.rpc ?? '/_brumate';\n build = value.build;\n}\n\n/**\n * Tells the page that the site changed since it loaded: a call answered 409\n * with another build, or the code of a handler is gone. The loader then\n * loads the next page in full, and an app can save a draft first.\n */\nexport function skew(reason: 'call' | 'code' | 'defer'): void {\n document.dispatchEvent(new CustomEvent('brumate:skew', { detail: reason }));\n}\n\n/** The scopes of the page, by ID. */\nexport const scopes: Map<ScopeId, Scope> = new Map();\n\n/** What modules of optional features add to the core. See `client-routes.ts` and `hot`. */\nexport const hooks: {\n /** Changes a state record before its scopes are added, such as for a page that navigation added. */\n record?: (script: Element, state: PageState) => PageState;\n /** Runs after the scopes of a state record are added. */\n added?: (added: Scope[]) => void;\n /**\n * Reads a bound element that a part owns, such as a `contenteditable`, when the core starts.\n * Returns `{ value }` when the user changed it since the server rendered it, `false` when\n * not, and nothing for an element of the core, which it reads itself.\n */\n field?: (element: Element) => { value: unknown } | false | undefined;\n} = {};\n\n/** What the devtools overlay hears from the core. It is set only in development. */\nexport interface DevtoolsHooks {\n /** The core started, with the scopes of the page, and a way to write a slot, as a handler does. */\n attach?(core: {\n scopes: Map<ScopeId, Scope>;\n set: (scope: Scope, slot: number, value: unknown) => void;\n /** Runs the code of a reference for an element, as an event or a trigger does. */\n handle?: (element: Element, ref: string, event?: Event) => Promise<unknown>;\n }): void;\n /** A handler starts for an event. */\n handler?(ref: string, element: Element, event?: Event): void;\n /**\n * A handler ran: when its event came, when its code was ready and the\n * handlers before it had started, when the call returned, and what it\n * returned, which is a promise for an async handler.\n */\n handled?(run: {\n ref: string;\n element: Element;\n event?: string;\n begun: number;\n ready: number;\n end: number;\n result: unknown;\n }): void;\n /** The updates of a write ran: how many, and how long they took with their effects. */\n updated?(count: number, start: number, end: number): void;\n /** The loader asks the server for the body of a `#defer` block. */\n defer?(template: Element, done: Promise<unknown>): void;\n /** A slot got a new value. */\n write?(scope: Scope, slot: number, value: unknown): void;\n /**\n * An effect or a `$client` callback, by its name in the update code, ran\n * and took `time` milliseconds, or its cleanup ran.\n */\n effect?(scope: Scope, name: string, kind: 'run' | 'cleanup', time: number): void;\n /** A client navigation changed the page: the routes that stayed, and those it replaced. */\n navigated?(report: NavigationReport): void;\n}\n\n/** The global key of the devtools hooks. */\nexport const DEVTOOLS: unique symbol = Symbol.for('brumate.devtools');\n\n/**\n * True on the dev server, which has the devtools. A Vite build replaces it\n * with `false`, so the calls of the devtools hooks are left out. Without\n * Vite, `import.meta.env` is undefined, and the hooks are off.\n */\nexport const DEV: boolean | undefined = (import.meta as { env?: { DEV?: boolean } }).env?.DEV;\n\nexport function devtools(): DevtoolsHooks | undefined {\n return (globalThis as Record<symbol, DevtoolsHooks | undefined>)[DEVTOOLS];\n}\n\nexport const modules: Map<string, ClientModule> = new Map();\n\nexport const loading: Map<string, Promise<ClientModule>> = new Map();\n\nexport const valueRenders: Record<string, Component> = {};\n\nexport const comments: Map<string, Comment> = new Map();\n\nexport const elements: Map<string, Element> = new Map();\n\n// Records of one render share references through an array, so a later record can settle a\n// promise of an earlier one. Each render on the page has its own array, by its `b-root`.\nexport const refs: Map<string, unknown[]> = new Map();\n\n// The latest load of each async memo, by `<scope>:<slot>`, so older results are dropped.\nexport const loads: Map<string, number> = new Map();\n\nexport const loadingSlots: Set<string> = new Set();\n\n/** The timers of debounced and throttled memos, by `scope:slot`, with when each last computed. */\nexport const timers: Map<string, { timer?: ReturnType<typeof setTimeout>; last: number }> =\n new Map();\n\n/** Aborts the server function calls of a memo's compute, by memo key. */\nexport const memoControllers: Map<string, AbortController> = new Map();\n\ninterface Guesses {\n /** Optimistic values that hold a guess, with the slot that each goes back to. */\n map: Map<string, { scope: Scope; slot: number; source?: [Scope, number]; base?: unknown }>;\n same: (key: string) => boolean;\n reset: () => void;\n}\n\n/**\n * The guesses of `$optimistic` values. The first `guess` sets it, so the\n * code that reads guesses is left out of a build that makes none.\n */\nexport let guesses: Guesses | undefined;\n\n/** Sets the guesses, which the first `guess` makes. */\nexport function setGuesses(value: Guesses): Guesses {\n return (guesses = value);\n}\n\n/**\n * The code of hidden `#offscreen` bodies. The first body that hides sets it\n * up, so the core of a page without one only checks that it is not there.\n * A body is hidden with an inline `display: none !important` on each element\n * at its top level, which no stylesheet overrides, and empty text for each\n * text node. The nodes stay in the page, so form fields, focus and media\n * keep their state.\n */\nexport let hiding: Hiding | undefined;\n\n/** Sets the code of hidden bodies, which the first body that hides makes, or drops it. */\nexport function setHiding(value: Hiding | undefined): Hiding | undefined {\n return (hiding = value);\n}\n\n/** Children that render where they are inserted, and the scopes that they find contexts from. */\nexport const insertedChildren: { from: Scope | undefined; at: Scope }[] = [];\n\n/**\n * Slots that the render of a component in the browser filled with a promise,\n * by `scope:slot`. The first compute of their memo takes that promise\n * instead of calling again, so a server function is called once per row.\n * A slot that `wait` filled with the settled value keeps it.\n */\nexport const renderedLoads: Set<string> = new Set();\n\n/**\n * The promises that the page knows are values still loading: a memo that the server streams, and\n * a memo that the browser rendered. Any other promise in a slot is a plain value.\n */\nexport const loadingValues: WeakSet<object> = new WeakSet();\n\n// More than 0 while code runs that updates the page. It reads a promise that is still loading as it\n// is, and does not throw.\nexport let exempt: number = 0;\n\n/** Runs code that updates the page: an update of a write, a refresh, or children that render late. */\nexport function updating<T>(run: () => T): T {\n exempt++;\n try {\n return run();\n } finally {\n exempt--;\n }\n}\n\n/** What `$resolve` waits in, with the scope of each, checked when a slot changes or a scope leaves. */\nexport const waiters: Map<() => void, Scope> = new Map();\n","// Indexes the comments that mark inserts and blocks and the elements with an anchor, finds them\n// again, and clears the range of a block.\n\nimport { HAS_CLIENT_HTML, HAS_LATE_MARKUP } from '../features.ts';\nimport { parseId } from '../shared.ts';\nimport type { ScopeId } from '../shared.ts';\nimport { comments, elements, scopes } from './state.ts';\nimport type { Scope } from './state.ts';\n\n/**\n * Indexes the markers of markup that others insert, such as streamed\n * `#loading` bodies and the pages that navigation adds, so `findComment` can\n * take its records at once.\n */\nexport let markerObserver: MutationObserver | undefined;\n\n/** Indexes the markers of markup that others insert from now on. */\nexport function observeMarkers(): void {\n markerObserver = new MutationObserver(indexAdded);\n markerObserver.observe(document, { childList: true, subtree: true });\n}\n\n/** Stops indexing the markup that others insert. */\nexport function stopObserving(): void {\n markerObserver?.disconnect();\n markerObserver = undefined;\n}\n\n// DOM\n\nexport const MARKER: RegExp = /^[btilP]-?\\d/;\n\nfunction markerKey(data: string): string {\n return data[0] === 'b' ? data.split(':').slice(0, 2).join(':') : data;\n}\n\nconst SCOPE_MARKER = /^[tb](-?[\\d.]+):/;\n\n/** True for markup that names a scope from the server: a `b-b` or marker with an ID that is not negative. */\nexport const SERVER_SCOPES: RegExp = /b-b=\"\\d|<!--[tb]\\d/;\n\n/** The scopes that the client made since the last insert, which the next insert holds. */\nexport const rendered: Scope[] = [];\n\n/** How many `#portal` markers the page has had, so a scope looks for its own only when any have. */\nexport let portals = 0;\n\n/**\n * Names a comment of cloned markup that names a scope, such as the start of an item. The start\n * of a portal, which its scope looks for when it goes, is indexed.\n */\nexport function nameComment(place: Comment, data: string): void {\n place.data = data;\n if (data[0] === 'P') {\n comments.set(data, place);\n portals++;\n }\n}\n\n/**\n * Indexes the markers and the bound elements under `root`, so that updates find them without a\n * search of the page. A search for each row of a long list takes time that grows with the list.\n * With `ids`, it also collects the IDs of the scopes that the markup names. The IDs of scopes\n * that the client made are negative.\n */\nexport function indexMarkers(root: Node, ids?: Set<ScopeId>, withElements = true): void {\n // The query finds the bound elements in native code, and the walk visits only comments, so\n // the code here runs for each marker, not for each node of a long list.\n if (withElements) {\n indexElements(root, ids);\n }\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n const data = (node as Comment).data;\n if (!MARKER.test(data)) {\n continue;\n }\n comments.set(markerKey(data), node as Comment);\n if (data[0] === 'P') {\n portals++;\n }\n const match = ids && SCOPE_MARKER.exec(data);\n if (match) {\n ids!.add(parseId(match[1]!));\n }\n }\n}\n\n/** The size of the indexes at which they next drop the nodes that left the page. */\nlet sweepAt = 4096;\n\n/**\n * Drops the nodes that left the page from the indexes, once they have grown to twice their size\n * after the last sweep, so a list that the client fills and empties again does not keep its old\n * rows. A node that comes back is indexed again when it is inserted.\n */\nexport function sweepIndexes(): void {\n if (comments.size + elements.size < sweepAt) {\n return;\n }\n for (const [key, node] of comments) {\n if (!node.isConnected) {\n comments.delete(key);\n }\n }\n for (const [key, node] of elements) {\n if (!node.isConnected) {\n elements.delete(key);\n }\n }\n sweepAt = Math.max(4096, 2 * (comments.size + elements.size));\n}\n\nfunction indexElements(root: Node, ids?: Set<ScopeId>): void {\n if (root.nodeType === 1) {\n indexElement(root as Element, ids);\n }\n if (root.nodeType === 1 || root.nodeType === 9 || root.nodeType === 11) {\n for (const element of (root as ParentNode).querySelectorAll('[b-b]')) {\n indexElement(element, ids);\n }\n }\n}\n\n/**\n * The nodes that inserts of the client put in the page, from the first to the last of each,\n * whose bound elements are not indexed yet. A list that the client creates is often never\n * updated row by row, so its elements are indexed when an update first needs one of them.\n */\nexport const unindexed: [first: Node, last: Node][] = [];\n\nexport function indexInserts(): void {\n for (const [first, last] of unindexed.splice(0)) {\n if (first.isConnected) {\n for (let node: Node | null = first; node; node = node.nextSibling) {\n indexElements(node);\n if (node === last) {\n break;\n }\n }\n } else if (last.isConnected) {\n // The first nodes left the page, such as the first rows of a list that were removed, so\n // the walk goes back from the last node, past the start of the insert if it must.\n for (let node: Node | null = last; node; node = node.previousSibling) {\n indexElements(node);\n }\n }\n }\n}\n\nfunction indexElement(element: Element, ids?: Set<ScopeId>): void {\n const key = element.getAttribute('b-b');\n if (key === null) {\n return;\n }\n elements.set(key, element);\n ids?.add(parseId(key.slice(0, key.indexOf(':'))));\n}\n\n/** Indexes the markers in the nodes that mutation records added. */\nexport function indexAdded(records: MutationRecord[]): void {\n for (const record of records) {\n for (const node of record.addedNodes) {\n if (node.nodeType === 1) {\n indexMarkers(node);\n } else if (node.nodeType === 8 && MARKER.test((node as Comment).data)) {\n const data = (node as Comment).data;\n comments.set(markerKey(data), node as Comment);\n if (data[0] === 'P') {\n portals++;\n }\n }\n }\n }\n}\n\n/**\n * Finds a marker in the page. Returns undefined when the markup is not in\n * the page, such as `children` inside a block that is closed. Updates to it\n * do nothing, and it updates when the client inserts it again.\n */\nexport function findComment(key: string): Comment | undefined {\n let comment = comments.get(key);\n if (!comment?.isConnected) {\n // The index has every marker in the page once it reads the records that\n // are waiting. Before the core starts, or between pages, it reads the page.\n // Without markup that others insert, the index has every marker of the page already, once\n // the browser has read all of it.\n if (HAS_LATE_MARKUP && markerObserver) {\n indexAdded(markerObserver.takeRecords());\n } else if (HAS_LATE_MARKUP || document.readyState === 'loading') {\n indexMarkers(document.documentElement);\n }\n comment = comments.get(key);\n }\n return comment?.isConnected ? comment : undefined;\n}\n\nexport function findElement(scope: ScopeId, anchor: number): Element | null {\n const own = scopes.get(scope)?.n?.[anchor];\n if (own?.isConnected) {\n return own as Element;\n }\n const key = `${scope}:${anchor}`;\n let element = elements.get(key);\n if (!element?.isConnected) {\n // As for markers: once the core starts, the index has every bound element in the page,\n // with those of the inserts that are waiting.\n if (HAS_LATE_MARKUP && markerObserver) {\n indexAdded(markerObserver.takeRecords());\n }\n // The inserts of the core are read when an update first needs one of their elements.\n if (HAS_CLIENT_HTML) {\n indexInserts();\n }\n element = elements.get(key);\n // An insert whose first node left the page, such as the first row of a list that was\n // removed, has elements that the walk did not reach.\n if (!element?.isConnected) {\n element = document.querySelector(`[b-b=\"${key}\"]`) ?? undefined;\n if (element) {\n elements.set(key, element);\n }\n }\n }\n return element?.isConnected ? element : null;\n}\n\n/** The start marker of a block: kept on its scope in a clone, or found in the page. */\nexport function blockStart(scope: Scope, anchor: number): Comment | undefined {\n const kept = scope.n?.[anchor];\n return kept?.isConnected && kept.nodeType === 8\n ? (kept as Comment)\n : findComment(`b${scope.id}:${anchor}`);\n}\n\n/** Returns the marker that ends the range that `start` opens. */\nexport function rangeEnd(start: Comment): Comment {\n let depth = 0;\n for (let node = start.nextSibling; node; node = node.nextSibling) {\n if (node.nodeType === 8) {\n const data = (node as Comment).data;\n if (data[0] === '/') {\n if (depth === 0) {\n return node as Comment;\n }\n depth--;\n } else if (MARKER.test(data)) {\n depth++;\n }\n }\n }\n // The markers sit in different parents when the browser's parser closes an element early, such\n // as a <p> that holds a <div>.\n throw new Error(\n `Missing end marker for <!--${start.data}-->. A <p> or another element that closes early around a block, such as a <div>, splits its markers.`,\n );\n}\n\nexport function clear(start: Node, end: Node): void {\n if (start.nextSibling === end || !start.nextSibling) {\n return;\n }\n // One removal of the whole range, which costs less than one for each node of a long list.\n const range = document.createRange();\n range.setStartAfter(start);\n range.setEndBefore(end);\n range.deleteContents();\n}\n","// Loads the code of components: their modules and the components of the page.\n\nimport type { Handler } from './references.ts';\nimport { loading, modules, options, valueRenders } from './state.ts';\nimport type { ClientModule } from './state.ts';\n\nexport function loadModule(id: string): Promise<ClientModule> {\n let promise = loading.get(id);\n if (!promise) {\n // A component without client code has nothing to update.\n promise = Promise.resolve(options.load(id)).then((loaded) => {\n const module = loaded ?? { id, props: {}, g: {} };\n modules.set(id, module);\n for (const render of module.components ?? []) {\n valueRenders[render.brumateId] = render;\n }\n return module;\n });\n loading.set(id, promise);\n }\n return promise;\n}\n\n/** True for a reference to a `#template` that a component got as a prop, such as `Page#t3`. */\nexport function isTemplate(ref: string): boolean {\n return /#t\\d/.test(ref);\n}\n\n/**\n * The code of the components on the page that is still loading. Handlers, updates and calls of\n * functions of other components wait for it, so the code that they call has loaded.\n */\nexport const loadingCode: Set<Promise<unknown>> = new Set();\n\n/** The components whose code loads, or has loaded, with the page. */\nexport const pageComponents: Set<string> = new Set();\n\n/** Loads the code of a component and all of its parts, as the page reads its scopes. */\nexport function loadComponent(id: string): void {\n // A render module that runs before the core starts, such as in a test, has nothing to load.\n if (options === undefined || pageComponents.has(id)) {\n return;\n }\n pageComponents.add(id);\n // The entry of a component holds all of its code. A load that fails is reported when a\n // handler or an update needs it.\n const code: Promise<unknown> = loadModule(id)\n .catch(() => {})\n .finally(() => loadingCode.delete(code));\n loadingCode.add(code);\n}\n\n/** Resolves when the code of the components on the page has loaded. */\nexport function codeReady(): Promise<unknown> | undefined {\n return loadingCode.size > 0 ? Promise.allSettled(loadingCode) : undefined;\n}\n\n/** The function of a reference, such as `Page#h3`, once its code has loaded. */\nexport function loadedFunction(ref: string): Handler | undefined {\n const [id, name] = ref.split('#') as [string, string];\n const module = modules.get(id);\n if (!module) {\n return undefined;\n }\n return (module as unknown as Record<string, Handler | undefined>)[name];\n}\n","// The tree of scopes: finding a scope, making one for markup that the client renders, and\n// removing one with what it owns.\n\nimport { parseId } from '../shared.ts';\nimport type { ScopeId } from '../shared.ts';\nimport { MARKER, clear, portals, rangeEnd, rendered, sweepIndexes } from './blocks.ts';\nimport type { Render } from './branches.ts';\nimport { loadComponent } from './code.ts';\nimport {\n comments,\n guesses,\n hiding,\n insertedChildren,\n loadingSlots,\n loads,\n memoControllers,\n scopes,\n waiters,\n timers,\n} from './state.ts';\nimport type { Scope } from './state.ts';\n\n// Scopes that the client creates get negative IDs, so they never match IDs\n// from state records that the server streams later.\nexport let nextId: number = -1;\n\n/** Starts the IDs of the scopes that the client makes again, for a new page. */\nexport function resetIds(): void {\n nextId = -1;\n}\n\n/** Returns the instance of a scope by its ID. */\nexport function getScope(id: ScopeId): Scope | undefined {\n return scopes.get(id);\n}\n\nexport function findRoot(scope: Scope): Scope {\n let current = scope;\n while (current.p) {\n current = current.p;\n }\n return current;\n}\n\n/** Counts changes to the scope tree, so `run` knows when the descendants it found are out of date. */\nexport let treeChanges: number = 0;\n\n/** Counts a change to the scope tree that `addScopes` makes. */\nexport function treeChanged(): void {\n treeChanges++;\n}\n\nexport function descendants(scope: Scope, kind: number, result: Scope[] = []): Scope[] {\n for (const child of scope.children ?? []) {\n if (child.k === kind) {\n result.push(child);\n }\n descendants(child, kind, result);\n }\n return result;\n}\n\nexport function destroy(scope: Scope): void {\n // A scope that a block already removed, such as one that is both owned and in the range.\n if (scopes.get(scope.id) !== scope) {\n return;\n }\n if (scope.children?.size) {\n for (const child of Array.from(scope.children ?? [])) {\n destroy(child);\n }\n }\n // The components that it rendered have no parent, so they go through their owner.\n if (scope.owned) {\n for (const child of Array.from(scope.owned)) {\n destroy(child);\n }\n }\n // The content of a `#portal` is elsewhere in the page, so it is removed by its markers.\n const start = portals > 0 ? comments.get(`P${scope.id}`) : undefined;\n if (start?.isConnected) {\n const end = rangeEnd(start);\n // The components in it go too, such as children that a component inserted there.\n destroyRange(scope, start, end);\n clear(start, end);\n start.remove();\n end.remove();\n }\n removeScope(scope);\n sweepIndexes();\n}\n\n/**\n * Removes a scope from the page: its cleanups run, and its memo state goes,\n * so a load that settles later is not written. Its markup stays.\n */\nexport function removeScope(scope: Scope): void {\n if (scope.cleanups) {\n for (const cleanup of scope.cleanups.values()) {\n cleanup();\n }\n }\n // The state of the slots that load or wait, which most scopes, such as rows of a list, have not.\n const waiting =\n memoControllers.size + timers.size + loads.size + loadingSlots.size + (guesses?.map.size ?? 0);\n for (let slot = 0; waiting > 0 && slot < scope.s.length; slot++) {\n const key = `${scope.id}:${slot}`;\n memoControllers.get(key)?.abort();\n memoControllers.delete(key);\n clearTimeout(timers.get(key)?.timer);\n timers.delete(key);\n loads.delete(key);\n loadingSlots.delete(key);\n guesses?.map.delete(key);\n }\n if (scope.h) {\n hiding?.bodies.delete(scope.h);\n }\n scopes.delete(scope.id);\n // A `$resolve` of a memo of the scope rejects.\n for (const [check, owner] of waiters) {\n if (owner === scope) {\n check();\n }\n }\n scope.p?.children?.delete(scope);\n scope.o?.owned?.delete(scope);\n treeChanges++;\n}\n\n/**\n * Removes the markup of a block of `scope`, between its markers, with the scopes in it: the\n * scopes of its kinds, and the scopes whose markup is in it. Those are the components that the\n * block rendered, whose owner can be `scope` itself, and the children that a component inserted\n * there. A scope that holds `scope` keeps its markers in the block, so it stays.\n */\nexport function removeBlock(scope: Scope, kinds: number[], start: Node, end: Node): void {\n disposeKinds(scope, kinds);\n destroyRange(scope, start, end);\n clear(start, end);\n}\n\n/**\n * Destroys the scopes whose markup is between two nodes, such as the components of a block that\n * closes, but not the scope of the block or those around it.\n */\nfunction destroyRange(scope: Scope, start: Node, end: Node): void {\n if (scopes.size > 0 && start.nextSibling !== end) {\n const above = new Set<Scope>();\n for (let current: Scope | undefined = scope; current; current = current.p ?? current.o) {\n above.add(current);\n }\n const inside = new Set<Scope>();\n function add(id: string): void {\n const found = scopes.get(parseId(id));\n if (found && !above.has(found)) {\n inside.add(found);\n }\n }\n for (let node = start.nextSibling; node && node !== end; node = node.nextSibling) {\n const walker = document.createTreeWalker(\n node,\n NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT,\n );\n for (let current: Node | null = walker.currentNode; current; current = walker.nextNode()) {\n if (current.nodeType === 1) {\n const key = (current as Element).getAttribute('b-b');\n if (key !== null) {\n add(key.slice(0, key.indexOf(':')));\n }\n } else if (MARKER.test((current as Comment).data)) {\n add((current as Comment).data.slice(1).split(':')[0]!);\n }\n }\n }\n for (const found of inside) {\n destroy(found);\n }\n }\n}\n\nexport function disposeKinds(scope: Scope, kinds: number[]): void {\n for (const child of Array.from(scope.children ?? [])) {\n if (kinds.includes(child.k)) {\n destroy(child);\n }\n }\n}\n\n/**\n * The component that holds a block of `scope` in its children, from the kind of the scope that\n * renders the component and the anchor of the component there, which the compiler gives.\n */\nfunction findHolder(scope: Scope, kind?: number, anchor?: number): Scope | undefined {\n if (kind === undefined || anchor === undefined) {\n return undefined;\n }\n for (let current: Scope | undefined = scope; current; current = current.p) {\n if (current.k === kind) {\n const id = current.c?.[anchor];\n const holder = id === undefined ? undefined : scopes.get(id);\n // A component that passes its children on holds them where they are finally inserted.\n return holder?.f ?? holder;\n }\n }\n return undefined;\n}\n\n/**\n * A render of a body of a block in the children of a component, which renders as children that\n * the component inserted, so the scopes that it makes read the contexts there, as the scopes\n * that the server made do.\n */\nexport function inPlace(\n scope: Scope,\n render: Render | undefined,\n kind?: number,\n anchor?: number,\n): Render | undefined {\n const holder = render && findHolder(scope, kind, anchor);\n if (!holder) {\n return render;\n }\n return (parent, item, index) => {\n const entry = { from: scope, at: holder };\n insertedChildren.push(entry);\n try {\n return render(parent, item, index);\n } finally {\n insertedChildren.splice(insertedChildren.indexOf(entry), 1);\n }\n };\n}\n\nexport function resolveScope(scope: Scope | ScopeId | undefined): Scope | undefined {\n if (typeof scope === 'object') {\n return scope;\n }\n return scope === undefined ? undefined : scopes.get(scope);\n}\n\n/** Work that waits until rendered markup is in the page. */\nexport const afterInsert: (() => void)[] = [];\n\n/** The scope that renders the next component, which becomes its owner. */\nlet owner: Scope | undefined;\n\n// The helpers below are what the server's render context does, for markup that the client\n// renders. Each is an export of its own, so a build keeps only those that its components call.\n\n/** Creates a scope for markup that the client renders, and returns its ID. */\nexport function createScope(\n kind: number,\n parent?: Scope | ScopeId,\n module?: string,\n nodes?: number,\n): number {\n const id = nextId--;\n const parentScope = resolveScope(parent);\n const created: Scope = { id, k: kind, p: parentScope, m: module, s: [] };\n // A clone keeps this many nodes on the scope, so the array does not grow.\n if (nodes) {\n // oxlint-disable-next-line unicorn/no-new-array -- A length, with no values written in yet.\n created.n = new Array(nodes);\n }\n rendered.push(created);\n // A component that the browser renders loads its code, as the components of the page do.\n if (module !== undefined) {\n loadComponent(module);\n }\n if (module !== undefined && owner) {\n created.o = owner;\n (owner.owned ??= new Set()).add(created);\n owner = undefined;\n }\n // A scope at the top of children that are inserted elsewhere finds its contexts there.\n const up = created.o ?? parentScope;\n for (let index = insertedChildren.length - 1; index >= 0; index--) {\n if (insertedChildren[index]!.from === up) {\n created.t = insertedChildren[index]!.at;\n break;\n }\n }\n if (parentScope) {\n (parentScope.children ??= new Set()).add(created);\n }\n treeChanges++;\n scopes.set(id, created);\n return id;\n}\n\n/**\n * The ID that `$id()` makes, as the server does. Client scope IDs are\n * negative, so they differ from the server's.\n */\nexport function makeId(scope: Scope | ScopeId, index: number): string {\n return `b${String(resolveScope(scope)!.id).replace(/\\./g, '_')}-${index}`;\n}\n\n/** Sets the owner of the next component's root scope. */\nexport function setOwner(scope: Scope | ScopeId): void {\n owner = resolveScope(scope);\n}\n\n/** The scope that `unbind` collects the promise props of its component in. */\nexport function sink(scope: ScopeId): Scope | undefined {\n return scopes.get(scope);\n}\n","// Keeps `document.title` in step with the `<title>` elements of markup.\n\nimport { HAS_TITLES } from '../features.ts';\n\n/** Sets the title of the page. */\nexport function title(value: unknown): void {\n setTitle(value === null || value === undefined ? '' : String(value));\n}\n\n/**\n * Sets `document.title`, which writes the first `<title>` of the document.\n * The head gets a `<title>` of its own first, so a `<title>` in markup keeps its text.\n */\nfunction setTitle(text: string): void {\n if (!document.head.querySelector('title:not([b-t])')) {\n document.head.prepend(document.createElement('title'));\n }\n document.title = text;\n}\n\n/** Watches the `<title>` elements of markup, once one is in the page. */\nlet titleObserver: MutationObserver | undefined;\n\nconst PAGE_TITLE = 'title[b-t]';\n\n/** True when a node is or holds a `<title>` of markup. */\nfunction holdsTitle(node: Node): boolean {\n return node instanceof Element && (node.matches(PAGE_TITLE) || !!node.querySelector(PAGE_TITLE));\n}\n\n/** Gives the page the text of its last `<title>` in markup. Without one, the title stays. */\nfunction syncTitle(): void {\n const titles = document.querySelectorAll(PAGE_TITLE);\n const last = titles[titles.length - 1];\n if (last && document.title !== last.textContent) {\n setTitle(last.textContent ?? '');\n }\n}\n\nfunction hasTitle(nodes: NodeList): boolean {\n for (const node of nodes) {\n if (holdsTitle(node)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Starts to follow the `<title>` elements of markup, when `root` has one. A\n * block that adds or removes one, or a change of its text, sets the title.\n */\nexport function watchTitles(root: ParentNode): void {\n if (!HAS_TITLES || titleObserver || !root.querySelector(PAGE_TITLE)) {\n return;\n }\n titleObserver = new MutationObserver((records) => {\n for (const record of records) {\n const target = record.target instanceof Element ? record.target : record.target.parentElement;\n if (\n target?.closest(PAGE_TITLE) ||\n hasTitle(record.addedNodes) ||\n hasTitle(record.removedNodes)\n ) {\n syncTitle();\n return;\n }\n }\n });\n titleObserver.observe(document, { childList: true, subtree: true, characterData: true });\n}\n","// Puts HTML or a clone into the page: the parse, the index of its markers, and the updates of the\n// scopes in it.\n\nimport { HAS_CLIENT_HTML, HAS_LATE_MARKUP } from '../features.ts';\nimport type { ScopeId } from '../shared.ts';\nimport { trustedHTML } from '../trusted.ts';\nimport {\n SERVER_SCOPES,\n indexAdded,\n indexInserts,\n indexMarkers,\n markerObserver,\n rendered,\n unindexed,\n} from './blocks.ts';\nimport { codeReady, loadModule } from './code.ts';\nimport { afterInsert, findRoot } from './scopes.ts';\nimport { hiding, options, scopes, updating } from './state.ts';\nimport type { ClientModule, Scope } from './state.ts';\nimport { watchTitles } from './titles.ts';\n\n/** True while `refresh` runs the updates of scopes that the server rendered. */\nexport let refreshing: boolean = false;\n\n/**\n * Updates scopes that the server rendered before values changed on the\n * client, such as the body of a `#loading` block that streams in after an\n * event. Effects do not run: they run only when a value changes. With\n * `memosOnly`, as for scopes that the client just rendered with its values,\n * only the memos run, so the ones that load start.\n */\nexport function refresh(added: Scope[], memosOnly = false): void {\n // The scopes of each module, which load it once.\n const byModule = new Map<string, Scope[]>();\n for (const scope of added) {\n const id = findRoot(scope).m;\n if (!id) {\n continue;\n }\n const list = byModule.get(id);\n if (list) {\n list.push(scope);\n } else {\n byModule.set(id, [scope]);\n }\n }\n for (const [id, list] of byModule) {\n void loadModule(id).then(async (module) => {\n // The names of the updates of each kind of scope, memos first, so the other updates read\n // their new values.\n const byKind = new Map<number, string[]>();\n for (const scope of list) {\n if (!byKind.has(scope.k)) {\n byKind.set(scope.k, refreshNames(module, scope.k, memosOnly));\n }\n }\n let any = false;\n for (const names of byKind.values()) {\n any ||= names.length > 0;\n }\n if (!any) {\n return;\n }\n const updates = module as unknown as Record<string, unknown>;\n // The updates can render templates and call functions of other components.\n await codeReady();\n refreshing = true;\n try {\n updating(() => {\n for (const scope of list) {\n for (const name of byKind.get(scope.k)!) {\n if (scopes.has(scope.id)) {\n (updates[name] as (scope: Scope) => void)(scope);\n }\n }\n }\n });\n } finally {\n refreshing = false;\n }\n });\n }\n}\n\n/** The names of the updates of a kind of scope that `refresh` runs, memos first. */\nfunction refreshNames(module: ClientModule, kind: number, memosOnly: boolean): string[] {\n const memos = new Set<string>();\n const others = new Set<string>();\n for (const slots of Object.values(module.g)) {\n for (const entries of Object.values(slots)) {\n for (const [entryKind, name] of entries) {\n if (entryKind !== kind || name[0] === 'e') {\n continue;\n }\n if (name[0] === 'm') {\n memos.add(name);\n } else if (!memosOnly) {\n others.add(name);\n }\n }\n }\n }\n return [...memos, ...others];\n}\n\n/**\n * Inserts rendered HTML before a node, or at the end of a parent, and runs\n * the work that waits for it.\n */\nexport function insertHTML(\n before: Node | { parent: ParentNode },\n html: string | DocumentFragment | DocumentFragment[],\n): void {\n // A fragment that the browser cloned from a template keeps its elements on their scopes, so\n // it is not parsed or indexed. The clones of a list go in one by one, so each node moves once.\n const cloned = typeof html !== 'string';\n let fragments: DocumentFragment[];\n if (typeof html === 'string') {\n fragments = [parseHTML(html, 'parent' in before ? before.parent : before)];\n } else {\n fragments = Array.isArray(html) ? html : [html];\n }\n // Markers that others inserted first, so the new markers win over them.\n if (HAS_LATE_MARKUP && markerObserver) {\n indexAdded(markerObserver.takeRecords());\n }\n // The scopes that the renders since the last insert made, whose markup this is.\n const client = rendered.splice(0);\n // Markup from the server, such as `children`, names scopes with IDs that are not negative.\n // Only then are the elements of the insert read for them now.\n const fromServer = !cloned && SERVER_SCOPES.test(html);\n const ids = fromServer ? new Set<ScopeId>() : undefined;\n const markup = clonedMarkup;\n for (const fragment of fragments) {\n if (!cloned || markup) {\n // The elements of HTML in a clone are read now, since the clone is not indexed later.\n indexMarkers(fragment, ids, fromServer || cloned || !HAS_CLIENT_HTML);\n // A clone's handlers were read from its template, unless it holds markup that it rendered.\n options.listen(fragment);\n }\n watchTitles(fragment);\n }\n clonedMarkup = false;\n const server: Scope[] = [];\n for (const id of ids ?? []) {\n const scope = typeof id === 'number' && id < 0 ? undefined : scopes.get(id);\n if (scope) {\n server.push(scope);\n }\n }\n const fragment = fragments[0]!;\n if (HAS_CLIENT_HTML && !cloned && !fromServer && fragment.firstChild) {\n unindexed.push([fragment.firstChild, fragment.lastChild!]);\n // Many inserts that no update read are indexed at once, so they do not hold their nodes.\n if (unindexed.length > 256) {\n indexInserts();\n }\n }\n // The nodes of the insert, when hidden `#offscreen` markup can contain them.\n let added: ChildNode[] | undefined;\n if (hiding?.bodies.size) {\n added = [];\n for (const part of fragments) {\n added.push(...part.childNodes);\n }\n }\n for (const part of fragments) {\n if ('parent' in before) {\n before.parent.append(part);\n } else {\n before.parentNode!.insertBefore(part, before);\n }\n }\n if (added) {\n hiding!.added(added);\n }\n // The records of this insert, whose markers are indexed and whose handlers listen already.\n if (HAS_LATE_MARKUP) {\n markerObserver?.takeRecords();\n }\n options.inserted?.();\n // A callback can add more, such as the call of a setter after the write of a ref. Those run\n // in this insert too, and a callback must not add itself again, or this never ends. The queue\n // is taken first, so a throw leaves nothing for the next insert, and a nested insert runs\n // only its own.\n const queued = afterInsert.splice(0);\n try {\n for (let fn = queued.shift(); fn; fn = queued.shift()) {\n fn();\n queued.push(...afterInsert.splice(0));\n }\n } finally {\n afterInsert.length = 0;\n }\n // HTML from the server, such as `children`, can be older than the values on the client.\n if (server.length > 0) {\n refresh(server);\n }\n // Scopes that the client just rendered have its values, but the memos that load start here.\n const live: Scope[] = [];\n for (const scope of client) {\n if (scopes.has(scope.id)) {\n live.push(scope);\n }\n }\n if (live.length > 0) {\n refresh(live, true);\n }\n}\n\n/** True when a clone holds markup that it rendered as HTML, whose markers its insert indexes. */\nlet clonedMarkup = false;\n\n/** Notes that a clone holds markup that it rendered as HTML. */\nexport function markCloned(): void {\n clonedMarkup = true;\n}\n\n/**\n * The clones of components that HTML holds a place for, by the number in the place,\n * `<!--f` and the number. HTML that the browser parses gets them back in their places.\n */\nconst placed = new Map<number, DocumentFragment>();\n\nlet placedCount = 0;\n\n/**\n * `svg` or `math` when markup in an element, or next to a node, is SVG or MathML. HTML that the\n * browser parses there needs one around it, as the parser of a page would have one.\n */\nexport function findForeign(near: Node | null | undefined): string | undefined {\n const element = near?.nodeType === 1 ? (near as Element) : near?.parentNode;\n if (element?.nodeType !== 1 || (element as Element).localName === 'foreignObject') {\n return undefined;\n }\n const space = (element as Element).namespaceURI;\n if (space === 'http://www.w3.org/2000/svg') {\n return 'svg';\n }\n return space === 'http://www.w3.org/1998/Math/MathML' ? 'math' : undefined;\n}\n\n/**\n * Parses HTML that the browser renders, with the clones that it holds places for. `near` is\n * the element that it goes in, or a node next to where it goes.\n */\nexport function parseHTML(\n html: string,\n near?: Node | null,\n foreign: string | undefined = findForeign(near),\n): DocumentFragment {\n const template = document.createElement('template');\n template.innerHTML = trustedHTML(foreign ? `<${foreign}>${html}</${foreign}>` : html);\n const fragment = template.content;\n if (foreign) {\n fragment.replaceChildren(...fragment.firstChild!.childNodes);\n }\n if (HAS_CLIENT_HTML && placed.size > 0 && html.includes('<!--f')) {\n const walker = document.createTreeWalker(fragment, NodeFilter.SHOW_COMMENT);\n const places: Comment[] = [];\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n if (/^f\\d+$/.test((node as Comment).data)) {\n places.push(node as Comment);\n }\n }\n for (const place of places) {\n const key = Number(place.data.slice(1));\n const nodes = placed.get(key);\n if (nodes) {\n placed.delete(key);\n place.replaceWith(nodes);\n }\n }\n }\n return fragment;\n}\n\n/** The markup of a render, or for a clone, a comment that holds its place, which a parse fills. */\nexport function holdPlace(out: string | DocumentFragment): string {\n if (typeof out === 'string') {\n return out;\n }\n const key = placedCount++;\n placed.set(key, out);\n return `<!--f${key}-->`;\n}\n","// Calls the function that a reference names, such as `Page#h3`, once its code has loaded.\n\nimport { loadOnce } from '../skew.ts';\nimport { codeReady, loadModule, loadedFunction } from './code.ts';\nimport { build, rpcPrefix, skew } from './state.ts';\nimport type { Scope } from './state.ts';\n\nexport type Handler = (scope: Scope | undefined, ...args: unknown[]) => unknown;\n\n/** Waits forever once the page loads again, so no error shows before it goes. */\nlet reloading: Promise<never> | undefined;\n\nexport async function resolve(ref: string): Promise<Handler> {\n const [id, name] = ref.split('#') as [string, string];\n try {\n const module = await loadModule(id);\n return (module as unknown as Record<string, Handler>)[name]!;\n } catch (error) {\n // After a deploy, the files of a build can be gone. The page loads again, with the new code,\n // once for each build. Any other error, such as a module that throws, goes to `#try`.\n const next = await serverBuild();\n if (!reloading && next !== undefined && loadOnce(next)) {\n skew('code');\n location.reload();\n reloading = new Promise(() => {});\n }\n if (reloading) {\n return reloading;\n }\n throw error;\n }\n}\n\n/**\n * Asks the server for its build, after the code of a handler failed to\n * load. Returns it when it is not the build of the page. Undefined without\n * a build, when the request fails, or when the builds are the same.\n */\nasync function serverBuild(): Promise<string | undefined> {\n if (build === undefined) {\n return undefined;\n }\n try {\n const response = await fetch(`${rpcPrefix}/`, {\n method: 'POST',\n headers: { 'x-brumate-build': build },\n });\n const current = response.headers.get('x-brumate-build');\n return current !== null && current !== build ? current : undefined;\n } catch {\n return undefined;\n }\n}\n\n// Runs a call as a pass. `updates.ts` sets it, since it imports this module.\nlet inPass: <T>(run: () => T) => T = (run) => run();\n\nexport function setPass(pass: <T>(run: () => T) => T): void {\n inPass = pass;\n}\n\n// The calls that wait for their turn or their code.\nlet waiting = 0;\n\n/**\n * Calls a function of another component at once, as a pass, when its code has loaded and no call\n * waits before it, so the caller reads what the function wrote. Returns false when it did not\n * call, and `call` is the way then.\n */\nexport function callNow(ref: string, scope: Scope | undefined, args: unknown[]): boolean {\n const fn = waiting === 0 && !codeReady() ? loadedFunction(ref) : undefined;\n if (!fn) {\n return false;\n }\n inPass(() => fn(scope, ...args));\n return true;\n}\n\n// The previous call of a function prop or a provided function, once it has started.\nlet lastCall: Promise<unknown> = Promise.resolve();\n\n/**\n * Calls a function of another component, such as a function prop or a provided function. The\n * code of each loads in parallel, but the calls start in the order that they were made, so an\n * `onChange` that an input event calls runs before an `onKeyDown` of a later key. The result is\n * wrapped, so a call that its code makes does not wait for the call around it.\n */\nexport function call(ref: string, scope: Scope | undefined, args: unknown[]): Promise<unknown> {\n const code = codeReady();\n const loaded = code ? Promise.all([resolve(ref), code]).then(([fn]) => fn) : resolve(ref);\n waiting++;\n const started = lastCall\n .then(() => loaded)\n // A call whose code fails to load stops waiting too, so the next setter can run at once.\n .finally(() => {\n waiting--;\n })\n .then((fn) => ({ value: inPass(() => fn(scope, ...args)) }));\n lastCall = started.catch(() => {});\n return started.then((result) => result.value);\n}\n","// Children, and the calls of `#template` values: markup that renders where it is inserted.\n\nimport { HAS_CHILDREN, HAS_CLIENT_HTML, HAS_TEMPLATES } from '../features.ts';\nimport { insertValue, isRaw } from '../html.ts';\nimport type { ScopeId } from '../shared.ts';\nimport { loadedFunction } from './code.ts';\nimport { holdPlace, insertHTML } from './insert.ts';\nimport { resolve } from './references.ts';\nimport type { Handler } from './references.ts';\nimport { resolveScope } from './scopes.ts';\nimport { insertedChildren, scopes, updating } from './state.ts';\nimport type { Scope } from './state.ts';\n\n/**\n * A `#template` of another component, which renders at once, as markup does. Its code loads\n * with the page, and updates wait for it.\n */\nexport function templateReference(\n ref: string,\n scope: Scope | undefined,\n): (...args: unknown[]) => unknown {\n // The markup renders where the component inserts it, so it reads the contexts there, as\n // children do.\n return (...args) =>\n new TemplateCall(ref, scope, args, (at) => {\n const render = loadedFunction(ref);\n // The insert links the template's scope to where it is inserted.\n return render ? insert(render(scope, ...args), undefined, at) : '';\n });\n}\n\n// Rendering on the client\n\n/** Renders a value inserted in markup. Children render here, at `scope`, for their contexts. */\nexport function insert(value: unknown, _ctx?: unknown, scope?: Scope | ScopeId): string {\n linkCalls(value, scope);\n if (!((HAS_CHILDREN || HAS_TEMPLATES) && value instanceof Children)) {\n return insertValue(value);\n }\n const out = value.render(resolveScope(scope));\n return HAS_CLIENT_HTML ? holdPlace(out) : (out as string);\n}\n\n/**\n * Links the scope of each template whose output a value holds to `at`, the scope where it is\n * inserted, so an error in the template goes to a `#try` there.\n */\nexport function linkCalls(value: unknown, at: Scope | ScopeId | undefined): void {\n if (Array.isArray(value)) {\n for (const item of value) {\n linkCalls(item, at);\n }\n return;\n }\n const scope = isRaw(value) && value.s !== undefined ? scopes.get(value.s) : undefined;\n if (scope && at !== undefined) {\n scope.l = resolveScope(at);\n }\n}\n\n/**\n * Children of a component that the client renders. They render where the\n * component inserts them, so they read the contexts that it provides. `from`\n * is the scope of the markup that wrote them.\n */\nexport class Children {\n private given: Scope | ScopeId | undefined;\n private readonly html: (at?: Scope) => string | DocumentFragment;\n\n constructor(from: Scope | ScopeId | undefined, html: (at?: Scope) => string | DocumentFragment) {\n this.given = from;\n this.html = html;\n }\n\n /** The scope that the children were written in, found when they render. */\n protected get from(): Scope | undefined {\n const scope = resolveScope(this.given);\n if (scope) {\n this.given = scope;\n }\n return scope;\n }\n\n render(at: Scope | undefined): string | DocumentFragment {\n if (!at) {\n return this.html();\n }\n // Children that a component passes on render where the component that gets them inserts\n // them, so they find their contexts there too.\n let target = at;\n for (let index = insertedChildren.length - 1; index >= 0; index--) {\n if (insertedChildren[index]!.from === at) {\n target = insertedChildren[index]!.at;\n // A block in these children finds the component that holds them by this.\n at.f = target;\n break;\n }\n }\n const entry = { from: this.from, at: target };\n insertedChildren.push(entry);\n try {\n return this.html(target);\n } finally {\n insertedChildren.splice(insertedChildren.indexOf(entry), 1);\n }\n }\n}\n\n/** A call of a `#template` of another component, which an insert can update in place. */\nexport class TemplateCall extends Children {\n readonly ref: string;\n /** The scope of the component that wrote the template. */\n readonly owner: Scope | undefined;\n readonly args: unknown[];\n\n constructor(\n ref: string,\n owner: Scope | undefined,\n args: unknown[],\n html: (at?: Scope) => string,\n ) {\n super(owner, html);\n this.ref = ref;\n this.owner = owner;\n this.args = args;\n }\n}\n\n/**\n * Children that the server rendered, which the browser renders with their own export each time\n * a component inserts them, so each insert makes new scopes, as the body of a block does. The\n * code of the export loads before the code that can insert them runs. See `childrenReady`.\n */\nexport class RenderedChildren extends Children {\n readonly ref: string;\n /** The scope and the anchor of the insert where the server rendered them, if it did. */\n readonly at: ScopeId | undefined;\n readonly anchor: number | undefined;\n private code: Handler | undefined;\n private loading: Promise<void> | undefined;\n\n constructor(scope: ScopeId, ref: string, at?: ScopeId, anchor?: number) {\n // The export returns HTML, as the render of a block does.\n super(scope, () => {\n const out = this.code!(this.from);\n return out instanceof DocumentFragment ? out : String(out);\n });\n this.ref = ref;\n this.at = at;\n this.anchor = anchor;\n }\n\n override render(at: Scope | undefined): string | DocumentFragment {\n if (this.code && this.from) {\n return super.render(at);\n }\n // An insert that ran before the code, such as an update that a parent ran at once, or before\n // the state of its scope, such as markup of a page that navigation is still reading. A marker\n // holds the place, and the children render there once both are ready, where they were\n // inserted, so they read the contexts there.\n const marker = `C${(nextChildren += 1)}`;\n // An arrow: it reads `this` and `super` of the class.\n const fill = (tries: number): void => {\n const node = findMarker(marker);\n if (!node) {\n return;\n }\n if (!this.from) {\n if (tries > 0) {\n setTimeout(() => fill(tries - 1), 0);\n }\n return;\n }\n insertHTML(\n node,\n updating(() => super.render(at)),\n );\n node.remove();\n };\n void this.load().then(() => fill(100));\n return `<!--${marker}-->`;\n }\n\n get loaded(): boolean {\n return this.code !== undefined;\n }\n\n load(): Promise<void> {\n this.loading ??= resolve(this.ref).then((handler) => {\n this.code = handler;\n });\n return this.loading;\n }\n}\n\n/** The count of the markers of children that wait for their code. */\nlet nextChildren = 0;\n\n/** The comment of a marker, such as of children that wait for their code. */\nfunction findMarker(data: string): Comment | undefined {\n const walker = document.createTreeWalker(document, NodeFilter.SHOW_COMMENT);\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n if ((node as Comment).data === data) {\n return node as Comment;\n }\n }\n return undefined;\n}\n\n/**\n * Loads the code of the children that the scope, or a component around it, holds, so code that\n * runs in the scope can insert them at once. Undefined when there is nothing to load.\n */\nexport function childrenReady(scope: Scope | undefined): Promise<unknown> | undefined {\n if (!HAS_CHILDREN) {\n return undefined;\n }\n const waiting: Promise<void>[] = [];\n const seen = new Set<Scope>();\n for (let current = scope; current && !seen.has(current); current = current.p ?? current.o) {\n seen.add(current);\n for (const value of current.s) {\n if (value instanceof RenderedChildren && !value.loaded) {\n waiting.push(value.load());\n }\n }\n }\n return waiting.length > 0 ? Promise.allSettled(waiting) : undefined;\n}\n\n/** The children of a component that the client renders. See `Children`. */\nexport function children(\n from: Scope | ScopeId | undefined,\n html: () => string | DocumentFragment,\n): Children {\n return new Children(from, html);\n}\n","// Reports an error of client code to the nearest `#try`.\n\nimport { blockStart, rangeEnd } from './blocks.ts';\nimport type { Render } from './branches.ts';\nimport { loadModule } from './code.ts';\nimport { insertHTML } from './insert.ts';\nimport { inPlace, removeBlock, findRoot } from './scopes.ts';\nimport { HAS_TRIES } from '../features.ts';\nimport { options, scopes } from './state.ts';\nimport { parseId } from '../shared.ts';\nimport type { ClientModule, Scope } from './state.ts';\n\n/**\n * Reports an error of client code: a handler, an effect, a `$client`\n * callback or a memo that loads. It renders the `#catch` body of the nearest\n * `#try` around the scope of the code, through the parents and the owners of\n * scopes. A template's scope goes on from the scope where it was called.\n * Without a `#try`, the page gets a `brumate:error` event on `window`, with\n * the error and the scope, and the error is logged.\n */\nexport function fail(scope: Scope | undefined, error: unknown): void {\n options.onError?.(error, { scope: scope?.id });\n if (!HAS_TRIES) {\n unhandled(error, scope);\n return;\n }\n void (async () => {\n for (let current = scope; current; current = current.l ?? current.p ?? current.o) {\n const id = findRoot(current).m;\n if (!id) {\n continue;\n }\n // A component whose code fails to load, which can be the error itself, cannot render its\n // `#catch`, so a `#try` further out catches the error.\n // oxlint-disable-next-line no-await-in-loop -- Each scope can belong to another component.\n const module = await loadModule(id).catch(() => undefined);\n const entry = module?.t?.[current.k];\n if (!entry) {\n continue;\n }\n // The scope that holds the block, which the anchor of the block counts from, and the\n // scope of the body below it.\n let owner = current.p;\n let body = current;\n while (owner && owner.k !== entry[0]) {\n body = owner;\n owner = owner.p;\n }\n if (owner) {\n // oxlint-disable-next-line no-await-in-loop -- The first `#try` found catches the error.\n await catchInto(owner, body, module!, entry, error);\n return;\n }\n }\n unhandled(error, scope);\n })();\n}\n\n/** Tells the page about an error that no `#try` caught. */\nfunction unhandled(error: unknown, scope?: Scope): void {\n window.dispatchEvent(new CustomEvent('brumate:error', { detail: { error, scope } }));\n console.error(error);\n}\n\n/**\n * Shows the `#catch` body that the server rendered, in the template `b-c`, in place of the body\n * of a `#try`. The server sends it when a `#loading` body inside the `#try` failed. `key` is the\n * scope and the anchor of the block.\n */\nexport function replaceTry(key: string): void {\n const template = document.querySelector(`template[b-c=\"${key}\"]`);\n const [id, anchor] = key.split(':') as [string, string];\n const owner = scopes.get(parseId(id));\n const start = owner && blockStart(owner, Number(anchor));\n if (template && start) {\n const end = rangeEnd(start);\n removeBlock(owner, [], start, end);\n insertHTML(end, (template as HTMLTemplateElement).innerHTML);\n }\n template?.remove();\n}\n\n/**\n * The scope that each rejection was reported to, as an unread memo and the waits of a render in\n * one scope can hold the same promise.\n */\nconst reported = new WeakMap<object, Scope | undefined>();\n\n/** `fail`, once per error and scope. */\nexport function reportOnce(scope: Scope | undefined, error: unknown): void {\n if (typeof error === 'object' && error !== null) {\n if (reported.has(error) && reported.get(error) === scope) {\n return;\n }\n reported.set(error, scope);\n }\n fail(scope, error);\n}\n\n/** Reports the error of a `#loading` body that failed on the server, with no `#try` around it. */\nexport function failBoundary(error: unknown): void {\n options.onError?.(error, {});\n unhandled(error);\n}\n\n/**\n * Renders the `#catch` body of a `#try` with an error, in place of `body`, the body that failed.\n */\nasync function catchInto(\n owner: Scope,\n body: Scope,\n module: ClientModule,\n [, anchor, , fallback, kinds, holderKind, holderAnchor]: NonNullable<ClientModule['t']>[number],\n error: unknown,\n): Promise<void> {\n const updates = module as unknown as Record<string, unknown>;\n // The `#catch` body already replaced the body that failed, for an error of the same body that\n // came first, such as another effect that threw in the same update. The `#try` shows the first\n // error, as on the server, and `onError` saw this one.\n if (scopes.get(body.id) !== body) {\n return;\n }\n const start = blockStart(owner, anchor);\n if (!start) {\n return;\n }\n const end = rangeEnd(start);\n removeBlock(owner, kinds, start, end);\n const render = inPlace(owner, updates[fallback] as Render, holderKind, holderAnchor)!;\n insertHTML(end, (render as unknown as (parent: Scope, error: unknown) => string)(owner, error));\n}\n","// Slots and what reads them: reads and writes of a slot, memos, effects, and the updates that a\n// write runs.\n\nimport { HAS_BINDINGS } from '../features.ts';\nimport {\n Binding,\n ElementReference,\n MemoError,\n FunctionReference,\n SlotReference,\n isAsyncIterable,\n isBinding,\n isSlotReference,\n} from '../shared.ts';\nimport type { ScopeId } from '../shared.ts';\nimport { findElement } from './blocks.ts';\nimport { childrenReady } from './children.ts';\nimport { loadModule, loadingCode } from './code.ts';\nimport { fail, reportOnce } from './errors.ts';\nimport { call, callNow, setPass } from './references.ts';\nimport { afterInsert, descendants, findRoot, resolveScope } from './scopes.ts';\nimport {\n DEV,\n devtools,\n guesses,\n hiding,\n loadingSlots,\n loads,\n memoControllers,\n modules,\n exempt,\n loadingValues,\n renderedLoads,\n scopes,\n timers,\n updating,\n waiters,\n} from './state.ts';\nimport type { Scope } from './state.ts';\n\n// Slots\n\n// oxlint-disable-next-line typescript/no-explicit-any -- Slots hold any value.\nexport function get(scope: Scope, slot: number): any {\n if (dirty.size > 0 && !draining) {\n settle(scope);\n }\n const value = scope.s[slot];\n // Update code reads a slot that the scope has not reached, as it waits at an earlier `await`:\n // `setSlots` and resumed records write every slot, so only a wait leaves one out. The queued\n // update skips on `NotReady`, since the rest of the render writes the page from the slots.\n if (value === undefined && exempt > 0 && !(slot in scope.s)) {\n throw new NotReady(Promise.resolve());\n }\n if (value instanceof Promise && !scope.plain?.has(slot)) {\n // A memo that reads any promise waits for it.\n if (computing > 0) {\n throw new NotReady(value);\n }\n if (loadingValues.has(value)) {\n // An effect skips the run, and runs again when the value arrives.\n if (runningEffects > 0) {\n throw new NotReady(value);\n }\n // Code that updates the page reads the promise. Anything else has no value to read.\n if (exempt === 0) {\n throw new Error(\n 'This value is still loading. Wait for it with await $resolve(memo), or check $isPending(memo) first',\n );\n }\n }\n }\n // A memo that threw holds its error, and each read of it throws.\n if (value instanceof MemoError) {\n throw value.error;\n }\n if (value instanceof ElementReference) {\n const element = findElement(value.scope, value.anchor);\n if (element) {\n scope.s[slot] = element;\n }\n return element ?? undefined;\n }\n return value;\n}\n\n/**\n * A memo that threw holds the error in place of a value, and its readers update. Each one that\n * reads it throws into the nearest `#try` around it, and the code that does not read it runs as\n * usual. A memo that computes again without a throw holds its value again.\n */\nfunction hold(scope: Scope, slot: number, key: string, error: unknown): void {\n loadingSlots.delete(key);\n loads.delete(key);\n guesses?.map.delete(key);\n set(scope, slot, new MemoError(error));\n}\n\n// The number of writes since the page loaded, so scopes that stream in later know to update.\nexport let writes: number = 0;\n\n/** Starts the count of writes again. */\nexport function resetWrites(): void {\n writes = 0;\n}\n\n/**\n * Writes a slot from code of a component. A prop that a parent bound with\n * `$bind` writes the parent's slot too, through any number of levels, and\n * the parent's update of the prop then finds the value already there. A\n * binding with a setter, `$bind(name, fn)`, calls it in place of the write,\n * and the parent's update of the prop writes the value that it keeps, before\n * the call returns.\n */\nexport function set<T>(scope: Scope, slot: number, value: T): T {\n const bound = scope.b?.[slot];\n if (bound === undefined || isSlotReference(bound)) {\n const target = bound && scopes.get(bound.scope);\n if (target) {\n // Both slots change in one pass, so the memos of each read both new values.\n pass(() => {\n writeSlot(scope, slot, value);\n set(target, bound.slot, value);\n });\n } else {\n writeSlot(scope, slot, value);\n }\n } else {\n send(bound, value);\n // The setter wrote the caller's signal, so the update of this prop runs now, and a read\n // right after the write gets what the setter kept.\n flush();\n }\n return value;\n}\n\n/**\n * Calls the setter of a binding. An element reference arrives only while a render writes its ref,\n * so the element goes once the render has inserted it.\n */\nexport function send(bound: unknown, value: unknown): void {\n if (value instanceof ElementReference) {\n afterInsert.push(() => {\n const element = findElement(value.scope, value.anchor);\n if (element) {\n send(bound, element);\n }\n });\n } else if (bound instanceof FunctionReference) {\n const args = [...(bound.args ?? []), value];\n // A loaded setter runs at once, so the writer reads what it kept.\n if (!callNow(bound.ref, scopes.get(bound.scope), args)) {\n void call(bound.ref, scopes.get(bound.scope), args);\n }\n } else if (typeof bound === 'function') {\n void bound(value);\n }\n}\n\n/** The setters that were given each element, so an update of a spread does not call them again. */\nconst given = new WeakMap<Element, Set<unknown>>();\n\n/** Calls the setter of a binding with an element, once for each element and setter. */\nexport function give(bound: unknown, element: Element): void {\n // A reference is new at each update, so its text is the key.\n const key = bound instanceof FunctionReference ? `${bound.scope}#${bound.ref}` : bound;\n const seen = given.get(element) ?? new Set();\n if (!seen.has(key)) {\n given.set(element, seen.add(key));\n send(bound, element);\n }\n}\n\n/** Writes a slot, and updates what reads it. */\nexport function writeSlot(scope: Scope, slot: number, value: unknown): void {\n if (!Object.is(scope.s[slot], value)) {\n writes++;\n scope.s[slot] = value;\n if (DEV) {\n devtools()?.write?.(scope, slot, value);\n }\n trigger(scope, slot);\n }\n}\n\n/** What `$bind(name)` passes a child, in markup that the browser renders. */\nexport function binding<T>(\n value: T,\n scope: Scope | ScopeId,\n slot: number,\n setter?: unknown,\n): Binding<T> {\n return new Binding(\n value,\n new SlotReference(typeof scope === 'object' ? scope.id : scope, slot),\n setter,\n );\n}\n\n/**\n * Records the props that a parent bound with `$bind`, among the props that a\n * component the browser renders writes: `slots` has the slot of each, by its name.\n */\nexport function bindings(\n scope: Scope | ScopeId,\n props: Record<string, unknown>,\n slots: Record<string, number>,\n): void {\n const target = typeof scope === 'object' ? scope : scopes.get(scope);\n for (const [name, slot] of Object.entries(slots)) {\n const value = props[name];\n if (target && HAS_BINDINGS && isBinding(value)) {\n (target.b ??= {})[slot] = value.target;\n // An element that the component wrote into its prop goes up once the markup is in the page,\n // when the scope that holds the signal has its slots.\n const written = target.s[slot];\n if (written instanceof ElementReference) {\n afterInsert.push(() => {\n if (scopes.get(target.id) === target) {\n set(target, slot, written);\n }\n });\n }\n }\n }\n}\n\n/**\n * The names of a call of a module function, for its shared code. Each ref\n * is a slot of `scope`, `[scope, slot]` for a slot of another scope, or\n * `[value]` for a value that does not change, such as a literal argument.\n */\nexport function cells(scope: Scope, links: unknown[], names: string[]): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [index, name] of names.entries()) {\n const ref = links[index];\n let owner = scope;\n let slot: number;\n if (typeof ref === 'number') {\n slot = ref;\n } else if ((ref as unknown[]).length === 2) {\n [owner, slot] = ref as [Scope, number];\n } else {\n Object.defineProperty(result, name, { get: () => (ref as unknown[])[0], set: () => {} });\n continue;\n }\n Object.defineProperty(result, name, {\n get: () => get(owner, slot),\n set: (value: unknown) => set(owner, slot, value),\n });\n }\n return result;\n}\n\n// Numbers loads across all memos, so a load is never numbered like an older one still in flight.\nlet loadCount = 0;\n\n/** Marks a memo as loading. Its readers update the first time, so `$isPending` becomes true. */\nfunction startLoading(scope: Scope, slot: number, key: string): void {\n if (!loadingSlots.has(key)) {\n loadingSlots.add(key);\n trigger(scope, slot);\n }\n}\n\n/**\n * Computes a memo of `$debounced` after its value stops changing for `ms`,\n * or one of `$throttled` at most once every `ms`, with the last value after\n * the wait. The memo is pending while it waits.\n */\nexport function timed(\n scope: Scope,\n slot: number,\n ms: number,\n throttle: boolean,\n compute: () => unknown,\n): void {\n const key = `${scope.id}:${slot}`;\n const state = timers.get(key) ?? { last: -Infinity };\n timers.set(key, state);\n function recompute(): void {\n state.timer = undefined;\n state.last = Date.now();\n // A scope that left the page computes no more.\n if (scopes.get(scope.id) === scope) {\n memo(scope, slot, compute);\n }\n }\n const since = Date.now() - state.last;\n if (throttle && state.timer === undefined && since >= ms) {\n recompute();\n return;\n }\n if (!throttle) {\n clearTimeout(state.timer);\n state.timer = undefined;\n }\n state.timer ??= setTimeout(recompute, throttle ? ms - since : ms);\n startLoading(scope, slot, key);\n}\n\n/** True for a promise, or any object with a `then` method. */\nexport function isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as PromiseLike<unknown>).then === 'function'\n );\n}\n\n/**\n * Reports the rejection of a memo that the browser renders and nothing reads, so it has no slot.\n * The error reaches the nearest `#try` around the scope, or `onError`.\n */\nexport function unreadMemo(scope: Scope | ScopeId, value: unknown): void {\n if (isThenable(value)) {\n const at = resolveScope(scope);\n value.then(undefined, (error: unknown) => reportOnce(at, error));\n }\n}\n\n/**\n * Writes the result of an async memo when it arrives. Until then the slot\n * keeps its value, and `pending` is true. Only the latest load is written.\n */\nexport function asyncMemo(scope: Scope, slot: number, promise: Promise<unknown>): void {\n const key = `${scope.id}:${slot}`;\n const load = ++loadCount;\n loads.set(key, load);\n startLoading(scope, slot, key);\n function settle(value?: unknown): void {\n if (loads.get(key) !== load) {\n return;\n }\n loadingSlots.delete(key);\n if (!Object.is(scope.s[slot], value)) {\n set(scope, slot, value);\n } else {\n trigger(scope, slot);\n }\n }\n function failed(error: unknown): void {\n // A newer load of the memo aborted this one, so only the latest load holds its error.\n if (loads.get(key) === load) {\n hold(scope, slot, key, error);\n }\n }\n promise.then((value) => {\n if (!isAsyncIterable(value)) {\n settle(value);\n return;\n }\n // A stream, such as a server function that yields: the memo takes each\n // value, and is pending until the first arrives. A newer load stops it.\n void (async () => {\n try {\n for await (const item of value) {\n if (loads.get(key) !== load) {\n break;\n }\n if (loadingSlots.has(key)) {\n settle(item);\n } else if (!Object.is(scope.s[slot], item)) {\n set(scope, slot, item);\n }\n }\n } catch (error) {\n failed(error);\n }\n })();\n }, failed);\n}\n\n/** Thrown when a memo reads a value that is still loading. */\nclass NotReady extends Error {\n readonly source: Promise<unknown>;\n\n constructor(source: Promise<unknown>) {\n super('The value is still loading');\n this.source = source;\n }\n}\n\n// More than 0 while a memo computes, so reading a value that is still loading stops it.\nlet computing = 0;\n\n// The effect whose run causes the writes in progress, so a context that the effect writes through\n// does not run it again. `viaContext` is true while a context sends a value.\nlet origin: string | undefined;\nlet viaContext = false;\nexport function sendContext(send: () => void): void {\n const before = viaContext;\n viaContext = true;\n try {\n send();\n } finally {\n viaContext = before;\n }\n}\n\n// More than 0 while an effect runs, so reading a value that is still loading skips the run.\nlet runningEffects = 0;\n\n/**\n * `$resolve(memo, { timeout, signal })`: resolves with the value of the memo once it is no longer\n * pending, also after a load that its inputs started. `isLoading` tells whether the memo or a\n * memo that it reads loads, and `read` gives the value or throws the error of the memo.\n */\nexport function resolve(\n scope: Scope,\n isLoading: () => boolean,\n read: () => unknown,\n options?: { timeout?: number; signal?: AbortSignal },\n): Promise<unknown> {\n return new Promise((done, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n function end(finish: () => void): void {\n clearTimeout(timer);\n waiters.delete(check);\n options?.signal?.removeEventListener('abort', abort);\n finish();\n }\n function abort(): void {\n end(() => reject(options!.signal!.reason));\n }\n function check(): void {\n // The memo left the page with its component.\n if (scopes.get(scope.id) !== scope) {\n const gone = new Error('The component left the page');\n gone.name = 'AbortError';\n end(() => reject(gone));\n return;\n }\n // Writes that wait for the code of an update can start a load of the memo.\n if (loadingUpdates.size > 0) {\n void Promise.allSettled(loadingUpdates).then(check);\n return;\n }\n if (!draining) {\n for (const scope of dirty) {\n settle(scope);\n }\n }\n if (isLoading()) {\n return;\n }\n try {\n const value = read();\n end(() => done(value));\n } catch (error) {\n end(() => reject(error));\n }\n }\n if (options?.signal?.aborted) {\n abort();\n return;\n }\n options?.signal?.addEventListener('abort', abort);\n if (options?.timeout !== undefined) {\n timer = setTimeout(\n () => end(() => reject(new Error(`The value did not load in ${options.timeout} ms`))),\n options.timeout,\n );\n }\n waiters.set(check, scope);\n check();\n });\n}\n\n// The effects that skipped their run, by scope and name, so one run follows the value.\nconst skipped: Map<string, object> = new Map();\n\n/** The key of the memo that computes, if any. */\nlet memoKey: string | undefined;\n\n/** The signal for server function calls while a memo computes. It is made on the first call. */\nexport function memoSignal(): AbortSignal | undefined {\n if (memoKey === undefined) {\n return undefined;\n }\n let controller = memoControllers.get(memoKey);\n if (!controller) {\n controller = new AbortController();\n memoControllers.set(memoKey, controller);\n }\n return controller.signal;\n}\n\n/**\n * Computes a memo. A promise loads, and the memo keeps its value until it\n * settles. A memo that reads a value that is still loading keeps its value\n * too, and is pending until that value arrives and the memo computes again.\n * A throw is held as the value of the memo, and its readers throw.\n */\nexport function memo(scope: Scope, slot: number, compute: () => unknown): void {\n const key = `${scope.id}:${slot}`;\n // A guess stays while its source has not changed, such as when a value the server streamed arrives.\n if (guesses?.same(key)) {\n return;\n }\n // The render computed the memo: a promise loads, and a value stays. A key with a value here\n // comes from `wait`, or from a promise of the render that settled before this first compute.\n const rendered = scope.s[slot];\n if (renderedLoads.delete(key)) {\n if (isThenable(rendered)) {\n asyncMemo(scope, slot, Promise.resolve(rendered));\n }\n return;\n }\n let value: unknown;\n let threw = false;\n // Server function calls of the last compute are aborted, because their answers are out of date.\n memoControllers.get(key)?.abort();\n memoControllers.delete(key);\n const outer = memoKey;\n memoKey = key;\n computing++;\n try {\n value = compute();\n } catch (error) {\n if (error instanceof NotReady) {\n startLoading(scope, slot, key);\n return;\n }\n threw = true;\n value = error;\n } finally {\n computing--;\n memoKey = outer;\n }\n // Held after the compute ends, since the write runs the readers.\n if (threw) {\n hold(scope, slot, key, value);\n return;\n }\n if (isThenable(value) || isAsyncIterable(value)) {\n asyncMemo(scope, slot, Promise.resolve(value));\n return;\n }\n // The values it read have arrived, so it is no longer pending.\n const waited = loadingSlots.delete(key);\n loads.delete(key);\n // An optimistic value that computes again follows its source, and drops its guess.\n guesses?.map.delete(key);\n if (!Object.is(scope.s[slot], value)) {\n set(scope, slot, value);\n } else if (waited) {\n trigger(scope, slot);\n }\n}\n\n/** True while a new value of a memo loads, or while the server still streams its value. */\nexport function pending(scope: Scope, slot: number): boolean {\n return (\n loadingSlots.has(`${scope.id}:${slot}`) ||\n (scope.s[slot] instanceof Promise && !scope.plain?.has(slot))\n );\n}\n\n/** True when a parent bound the prop of the slot with `$bind`. */\nexport function isBound(scope: Scope, slot: number): boolean {\n return scope.b?.[slot] !== undefined;\n}\n\n/** `x++`, `x--`, `++x` and `--x`. */\nexport function update(scope: Scope, slot: number, delta: number, prefix: boolean): number {\n const previous = get(scope, slot) as number;\n set(scope, slot, previous + delta);\n return prefix ? previous + delta : previous;\n}\n\nfunction trigger(scope: Scope, slot: number): void {\n for (const check of waiters.keys()) {\n check();\n }\n const id = findRoot(scope).m!;\n const children = childrenReady(scope);\n if (modules.has(id) && loadingCode.size === 0 && !children) {\n pass(() => queueWrite(scope, slot));\n return;\n }\n // The first write to a component loads its update code. Later writes wait in order, and for\n // the code of the page, which the updates can render and call. The writes of one pass that\n // wait, such as the props of a child, join its list and run as one pass, so a child computes once.\n // `waiting` is set only while a pass runs.\n if (waiting) {\n // Its code starts to load now, so the pass waits no longer than the first write.\n waiting.push([\n scope,\n slot,\n loadModule(id)\n .then(() => childrenReady(scope))\n .catch((error) => fail(scope, error)),\n ]);\n return;\n }\n const from = origin;\n const via = viaContext;\n const list: [Scope, number, Promise<unknown>?][] = [[scope, slot]];\n if (running > 0) {\n waiting = list;\n }\n const loading = loadModule(id)\n .then(async () => {\n const waits: unknown[] = [...loadingCode, children];\n for (const [, , load] of list) {\n waits.push(load);\n }\n await Promise.allSettled(waits);\n const before = origin;\n const viaBefore = viaContext;\n origin = from;\n viaContext = via;\n try {\n pass(() => {\n for (const [target, at] of list) {\n queueWrite(target, at);\n }\n });\n } finally {\n origin = before;\n viaContext = viaBefore;\n }\n })\n .catch((error: unknown) => {\n // The write cannot run. Its effects do not wait for it any longer.\n fail(scope, error);\n flushEffects();\n });\n loadingUpdates.add(loading);\n void loading.finally(() => {\n loadingUpdates.delete(loading);\n // The effects that the pass of another handler held back, until the writes landed.\n if (loadingUpdates.size === 0 && running === 0) {\n flushEffects();\n }\n });\n}\n\n/** The writes of the pass that runs that wait for code, to run as one pass of their own. */\nlet waiting: [Scope, number, Promise<unknown>?][] | undefined;\n\n/** The updates that wait for their code. */\nconst loadingUpdates = new Set<Promise<unknown>>();\n\n/**\n * Resolves when the updates of the writes so far have run, including those\n * whose code is loading. `transition` of `brumate/events` waits for it.\n */\nexport async function updated(): Promise<void> {\n while (loadingUpdates.size > 0) {\n // oxlint-disable-next-line no-await-in-loop -- An update can start more loads.\n await Promise.allSettled(loadingUpdates);\n }\n}\n\n(globalThis as { [key: symbol]: unknown })[Symbol.for('brumate.updated')] = updated;\n\n// Effects wait until every other update of a write has run, and run once each.\nexport const pendingEffects: Map<string, () => void> = new Map();\n\n/**\n * The updates that wait in the pass at one depth of scopes, so each runs once.\n * A memo has its rank, the number in its name: memos are numbered in the\n * order they are declared, after the memos they read.\n */\ninterface Level {\n /** The memos, in buckets by rank. */\n m: Map<string, () => void>[];\n /** The bindings. */\n b: Map<string, () => void>;\n /** The effects. */\n e: Map<string, () => void>;\n}\n\nlet levels: Level[] = [];\n\nlet running = 0;\n\nlet flushing = false;\n\n/** The updates that ran since the outermost pass started, and when it started, for the devtools. */\nlet updateCount = 0;\n\nlet updateStart = 0;\n\n/**\n * Runs a pass: `write` queues updates. The outermost pass runs them by the\n * depth of their scope, so the bindings of a component, such as its props\n * and contexts, reach the components inside before their memos compute. At\n * each depth, the memos in the order of their ranks, then the bindings as\n * one round. Effects run after them, the deepest first, so the effects of\n * a child run before those of its parent.\n */\nexport function pass<T>(write: () => T): T {\n if (DEV && running === 0) {\n updateCount = 0;\n updateStart = performance.now();\n }\n // Effects run after the pass, so an error of one stops the effects after it until a pass starts.\n if (running++ === 0) {\n failed = false;\n }\n let result!: T;\n let held = false;\n try {\n result = write();\n } finally {\n // The writes of a handler that throws still reach the page.\n if (running === 1) {\n drain();\n }\n if (--running === 0) {\n // The deepest effects first. An effect that waits already keeps its place.\n // oxlint-disable-next-line unicorn/no-array-reverse -- The levels are dropped right after.\n for (const level of levels.reverse()) {\n for (const [key, runEffect] of level?.e ?? []) {\n pendingEffects.set(key, runEffect);\n }\n }\n levels = [];\n // Writes that wait for code run as a pass of their own, and the effects wait for it.\n held = waiting !== undefined;\n waiting = undefined;\n depths.clear();\n failed = false;\n stuck = false;\n dirty.clear();\n }\n }\n if (running === 0) {\n // Effects wait for the writes that wait for code, so they never see the page half updated.\n if (!held && loadingUpdates.size === 0) {\n flushEffects();\n }\n if (DEV) {\n devtools()?.updated?.(updateCount, updateStart, performance.now());\n }\n }\n return result;\n}\n\nsetPass(pass);\n\n// The scopes with memos that wait in the pass, so a read computes the ones of its scope.\nconst dirty: Set<Scope> = new Set();\n\n/** Computes the memos of a scope that wait, so code that reads one in a handler reads the new value. */\nfunction settle(scope: Scope): void {\n // A memo that reads another memo of the scope settles it through `get`, so the order here does not matter.\n if (dirty.delete(scope)) {\n for (const [rank, bucket] of (levels[getDepth(scope)]?.m ?? []).entries()) {\n const key = `${scope.id}:m${rank}`;\n const compute = bucket?.get(key);\n bucket?.delete(key);\n compute?.();\n }\n }\n}\n\n// True while `drain` runs.\nlet draining = false;\n\n/**\n * Runs the memos and bindings that wait in the pass at once, such as for a handler that must focus\n * or measure what it rendered. Effects still wait for the end of the pass.\n */\nexport function flush(): void {\n if (running > 0 && !draining) {\n drain();\n }\n}\n\n(globalThis as { [key: symbol]: unknown })[Symbol.for('brumate.flush')] = flush;\n\n/**\n * Queues the updates that read a slot, on the scope and on its descendants of\n * each kind, once the code of the component has loaded.\n */\nfunction queueWrite(scope: Scope, slot: number): void {\n const id = findRoot(scope).m!;\n const module = modules.get(id);\n if (!module) {\n return;\n }\n for (const [kind, name] of module.g[scope.k]?.[slot] ?? []) {\n for (const target of kind === scope.k ? [scope] : descendants(scope, kind)) {\n queue((module as unknown as Record<string, (scope: Scope) => void>)[name]!, name, target);\n }\n }\n}\n\n/** Queues an update of a scope, once. */\nfunction queue(fn: (scope: Scope) => void, name: string, target: Scope): void {\n if (DEV) {\n updateCount++;\n }\n const key = `${target.id}:${name}`;\n // An effect does not run again on a change of a context that its own run caused.\n const from = origin;\n if (name[0] === 'e' && viaContext && from === key) {\n return;\n }\n // An update of a scope that left the page in the pass does not run. An error goes to the\n // nearest `#try` around the update, whether its write ran at once or waited for code.\n function later(): void {\n if (!failed && scopes.get(target.id) === target) {\n try {\n // Past the limit of rounds, the next update fails in place of running.\n if (stuck) {\n // The rest of the pass does not run.\n failed = true;\n throw new Error(\n DEV\n ? `The ${name[0] === 'e' ? 'effect' : 'update'} ${name} of ${findRoot(target).m} did not settle: it writes a value that it reads, and runs again without end. Wrap the read or the write in $untrack, or write only when the value changes [BRM187]`\n : `Update loop ${key} [BRM187]`,\n );\n }\n const before = origin;\n origin = from;\n try {\n updating(() => fn(target));\n } finally {\n origin = before;\n }\n } catch (error) {\n if (!(error instanceof NotReady)) {\n fail(target, error);\n }\n }\n }\n }\n const depth = getDepth(target);\n const level = (levels[depth] ??= { m: [], b: new Map(), e: new Map() });\n if (name[0] === 'm') {\n (level.m[+name.slice(1)] ??= new Map()).set(key, later);\n dirty.add(target);\n } else {\n (name[0] === 'e' ? level.e : level.b).set(key, later);\n }\n}\n\n/**\n * The depth of a scope: one more than the deeper of the scope where it renders, for children\n * and templates that another component inserts, and of its parent. So children that a provider\n * inserts come after the provider, and a template that a shallower component renders comes after\n * the component that wrote it.\n */\nfunction getDepth(scope: Scope | undefined): number {\n if (!scope) {\n return -1;\n }\n if (!scope.t) {\n return 1 + getDepth(scope.p ?? scope.o);\n }\n // Kept for the pass, since the scope where it renders and its parent can reach the same scope.\n let depth = depths.get(scope);\n if (depth === undefined) {\n depth = 1 + Math.max(getDepth(scope.t), getDepth(scope.p ?? scope.o));\n depths.set(scope, depth);\n }\n return depth;\n}\n\n// The depths of the scopes of the pass.\nconst depths: Map<Scope, number> = new Map();\n\n// True once the pass was stopped for running too many rounds.\nlet failed = false;\n\n// True once the pass ran 10000 rounds of bindings, or the effects 1000 rounds, for updates that\n// keep writing what they read.\nlet stuck = false;\n\n/**\n * Runs what waits, the lowest depth first: its memo of the lowest rank, until\n * none waits, then its bindings as one round. After each, it looks again from\n * the top, since a write can queue updates of a lower depth, such as a `$bind`\n * write into a parent.\n */\nfunction drain(): void {\n let rounds = 0;\n let depth = 0;\n draining = true;\n try {\n while (depth < levels.length) {\n const level = levels[depth];\n if (!level) {\n depth++;\n continue;\n }\n // The bucket of the lowest rank. Each runs whole, so the scan is short.\n const memos = level.m;\n let rank = 0;\n while (rank < memos.length && !memos[rank]?.size) {\n rank++;\n }\n const bucket = memos[rank];\n if (bucket) {\n // The whole bucket runs in one loop, with the memos that join it while it runs. A memo that\n // queues a lower rank or a lower depth, such as of a template that a shallower component\n // renders, runs after the bucket, since the scan starts again.\n for (const [key, compute] of bucket) {\n bucket.delete(key);\n compute();\n }\n } else if (level.b.size > 0) {\n stuck = ++rounds > 10_000;\n const round = [...level.b.values()];\n level.b.clear();\n for (const waiter of round) {\n waiter();\n }\n } else {\n depth++;\n continue;\n }\n depth = 0;\n }\n } finally {\n draining = false;\n }\n}\n\n/**\n * Runs the effects that writes scheduled, in the order they were first\n * scheduled. Writes in an effect schedule more effects, which run after.\n */\nfunction flushEffects(): void {\n if (flushing) {\n return;\n }\n flushing = true;\n let rounds = 0;\n try {\n // The effects that wait run as one pass, so their writes update the page once. A pass that\n // they start puts the effects it schedules back, and they run next.\n while (pendingEffects.size > 0) {\n const run = [...pendingEffects.values()];\n pendingEffects.clear();\n // Effects that keep writing what they read stop after 1000 rounds: the next one fails. An\n // effect that waits after it starts with a new count.\n if ((stuck = ++rounds > 1000)) {\n rounds = 0;\n }\n pass(() => {\n for (const runEffect of run) {\n runEffect();\n }\n });\n }\n } finally {\n flushing = false;\n }\n}\n\n/**\n * Runs an effect, or a `$client` callback when `client` is set, after the cleanup of its previous\n * run. An effect that reads a value that is still loading skips the run, and runs again when the\n * value arrives. A `$client` callback is a handler: the same read throws.\n */\nexport function effect(\n scope: Scope,\n name: string,\n callback: () => unknown,\n client?: boolean,\n): void {\n // In a hidden `#offscreen` body, it runs when the body shows.\n if (hiding?.paused(scope, name)) {\n return;\n }\n const key = `${scope.id}:${name}`;\n skipped.delete(key);\n scope.cleanups ??= new Map();\n scope.cleanups.get(name)?.();\n let cleanup: unknown;\n const start = DEV ? performance.now() : 0;\n const outer = origin;\n origin = key;\n if (!client) {\n runningEffects++;\n }\n try {\n cleanup = callback();\n } catch (error) {\n if (error instanceof NotReady) {\n // The run is skipped. It runs again when the value arrives, unless a change ran it first.\n const token = {};\n skipped.set(key, token);\n scope.cleanups.set(name, noop);\n function again(): void {\n if (skipped.get(key) === token && scopes.get(scope.id) === scope) {\n effect(scope, name, callback);\n }\n }\n // After the writes that the value starts, which can run the effect themselves.\n void error.source.then(\n () => Promise.allSettled(loadingUpdates).then(again),\n // The error reaches the nearest `#try`.\n (reason: unknown) => {\n if (skipped.get(key) === token) {\n skipped.delete(key);\n fail(scope, reason);\n }\n },\n );\n return;\n }\n // The error goes to the nearest `#try` around the effect. The effect runs again on the next change.\n fail(scope, error);\n } finally {\n origin = outer;\n if (!client) {\n runningEffects--;\n }\n }\n // An entry without a cleanup too, so a hidden `#offscreen` body knows what to run again.\n let stored = typeof cleanup === 'function' ? (cleanup as () => void) : noop;\n if (DEV) {\n devtools()?.effect?.(scope, name, 'run', performance.now() - start);\n // Each way that a cleanup runs calls this function: the next run, a removed scope, a hidden\n // `#offscreen` body, or a page that navigation leaves.\n const own = stored;\n stored = () => {\n devtools()?.effect?.(scope, name, 'cleanup', 0);\n own();\n };\n }\n scope.cleanups.set(name, stored);\n}\n\nexport function noop(): void {}\n","// Contexts that components provide and read, and the values that the runtime provides to the\n// whole page.\n\nimport { HAS_ROUTES } from '../features.ts';\nimport { ROUTE_KEY } from '../context.ts';\nimport type { Context as ContextValue, Route } from '../context.ts';\nimport type { ScopeId } from '../shared.ts';\nimport { resolveScope } from './scopes.ts';\nimport { scopes } from './state.ts';\nimport type { Scope } from './state.ts';\nimport { sendContext, set } from './updates.ts';\n\n/** The scope that provides a context to `scope`: itself or the nearest one above it. */\nfunction findProvider(scope: Scope, key: string): Scope | undefined {\n // A scope reads the contexts of the scopes above it, not its own, so a component can read a\n // context and provide it again to the scopes inside it. Children that a component inserted\n // find their contexts where they are, through `t`.\n for (\n let current: Scope | undefined = scope.t ?? scope.p ?? scope.o;\n current;\n current = current.t ?? current.p ?? current.o\n ) {\n if (current.v && key in current.v) {\n return current;\n }\n }\n return undefined;\n}\n\n/**\n * Writes a provided value, and the slot of every scope that reads it from this provider. The\n * provider can read the same context from above, which this does not write.\n */\nexport function updateContext(scope: Scope, context: ContextValue<unknown>, value: unknown): void {\n scope.v ??= {};\n scope.v[context.key] = value;\n sendContext(() => {\n for (const target of scopes.values()) {\n const slot = target.x?.[context.key];\n if (slot !== undefined && findProvider(target, context.key) === scope) {\n set(target, slot, value);\n }\n }\n });\n}\n\n/** Provides a value of a context to the scopes inside `scope`. */\nexport function provideValue<T>(context: ContextValue<T>, value: T, scope: Scope | ScopeId): void {\n const target = resolveScope(scope)!;\n target.v ??= {};\n target.v[context.key] = value;\n}\n\n/** Reads a context, and records its slot so that changes to the provided value reach it. */\nexport function consumeContext<T>(\n context: ContextValue<T>,\n scope: Scope | ScopeId,\n slot?: number,\n): T {\n const target = resolveScope(scope)!;\n if (slot !== undefined) {\n target.x ??= {};\n target.x[context.key] = slot;\n }\n const provider = findProvider(target, context.key);\n if (provider) {\n return provider.v![context.key] as T;\n }\n if (HAS_ROUTES && context.key === ROUTE_KEY && !globals.has(ROUTE_KEY)) {\n globals.set(ROUTE_KEY, currentRoute());\n }\n return (globals.has(context.key) ? globals.get(context.key) : context.defaultValue) as T;\n}\n\n/** The values of the contexts that the runtime provides to the whole page, by key. */\nconst globals = new Map<string, unknown>();\n\n/** The route of the page: `location`, and the params of the route from the last page state. */\nfunction currentRoute(): Route {\n const records = document.querySelectorAll('script[b-state][b-params]');\n const params = records[records.length - 1]?.getAttribute('b-params');\n const url = new URL(location.href);\n return { url, search: url.searchParams, params: params ? JSON.parse(params) : {} };\n}\n\n/**\n * Writes a context that the runtime provides to the whole page, and the\n * slot of every scope that reads it without a provider above it.\n */\nexport function setGlobal(key: string, value: unknown): void {\n globals.set(key, value);\n for (const target of scopes.values()) {\n const slot = target.x?.[key];\n if (slot !== undefined && !findProvider(target, key)) {\n set(target, slot, value);\n }\n }\n}\n\n/** Reads the route of the page again, after navigation changed it. */\nexport function updateRoute(): void {\n setGlobal(ROUTE_KEY, currentRoute());\n}\n","// The guesses of `$optimistic` values, and the count of server calls that puts them back.\n\nimport { guesses, scopes, setGuesses } from './state.ts';\nimport type { Scope } from './state.ts';\nimport { pending, set } from './updates.ts';\n\n/** The values of promises that the server streamed, so a guess knows its source did not change. */\nexport const settled: WeakMap<Promise<unknown>, unknown> = new WeakMap();\n\n/** True while the source of a guess holds the value it had when the guess was made. */\nfunction sameSource(key: string): boolean {\n const entry = guesses!.map.get(key);\n if (!entry?.source) {\n return false;\n }\n const current = entry.source[0].s[entry.source[1]];\n return (\n Object.is(current, entry.base) ||\n (entry.base instanceof Promise && settled.get(entry.base) === current)\n );\n}\n\n/** Server calls that have not finished, from forms and from `rpc`. */\nexport let calling: number = 0;\n\n/** Counts the pages that client navigation left, so calls of an old page are not counted down. */\nexport let callEpoch: number = 0;\n\n/** Calls of the old page that are still out no longer count for its guesses. */\nexport function leaveGuesses(): void {\n calling = 0;\n callEpoch++;\n}\n\n/**\n * Writes a guess into an optimistic value. It goes back to its source when\n * the source changes, which computes it again, or when every server call of\n * the page finishes, such as after a post failed.\n */\nexport function guess<T>(\n scope: Scope,\n slot: number,\n ...rest: [value: T] | [sourceScope: Scope, sourceSlot: number, value: T]\n): T {\n const value = rest.at(-1) as T;\n const source = rest.length === 3 ? ([rest[0], rest[1]] as [Scope, number]) : undefined;\n const base = source && source[0].s[source[1]];\n const held = guesses ?? setGuesses({ map: new Map(), same: sameSource, reset: resetGuesses });\n held.map.set(`${scope.id}:${slot}`, { scope, slot, source, base });\n return set(scope, slot, value);\n}\n\n/** Counts a server call, and puts guesses back when the last one finishes. */\nexport function track<T>(request: Promise<T>): Promise<T> {\n calling++;\n const epoch = callEpoch;\n function done(): void {\n if (epoch !== callEpoch) {\n return;\n }\n calling--;\n // Waits a task, so memos that the answer refreshed start to load first.\n setTimeout(() => calling || guesses?.reset(), 0);\n }\n request.then(done, done);\n return request;\n}\n\nfunction resetGuesses(): void {\n for (const [key, { scope, slot, source }] of guesses!.map) {\n // A source that loads again, such as a refreshed list, resets the guess when it arrives.\n if (source && pending(source[0], source[1])) {\n continue;\n }\n guesses!.map.delete(key);\n if (source && scopes.has(scope.id) && !Object.is(scope.s[slot], source[0].s[source[1]])) {\n set(scope, slot, source[0].s[source[1]]);\n }\n }\n}\n","// Handlers of events: the handler of an element, the handlers that one event merges from spreads\n// and props, and the calls of server functions from forms and `rpc`.\n\nimport { HAS_BINDINGS, HAS_CHILDREN, HAS_TEMPLATES } from '../features.ts';\nimport {\n actionAttributes,\n bindEntry,\n handlerEntry,\n ownValue,\n spread as spreadText,\n} from '../html.ts';\nimport {\n ChildrenReference,\n FunctionReference,\n PARTS,\n isBinding,\n mergeHandlers,\n parseId,\n} from '../shared.ts';\nimport type { ScopeId } from '../shared.ts';\nimport { RenderedChildren, childrenReady, templateReference } from './children.ts';\nimport { codeReady, isTemplate, loadedFunction } from './code.ts';\nimport { fail } from './errors.ts';\nimport { track } from './guesses.ts';\nimport { call, resolve } from './references.ts';\nimport { resolveScope } from './scopes.ts';\nimport { DEV, build, devtools, hiding, rpcPrefix, scopes } from './state.ts';\nimport type { Scope } from './state.ts';\nimport { isThenable, memoSignal, pass, set } from './updates.ts';\n\n/**\n * The handlers that the core makes from references, with their references,\n * so a spread in markup that the browser renders passes them on in `b-on`,\n * as a spread on the server does.\n */\nconst handlerReferences = new WeakMap<object, FunctionReference>();\n\n/** The modifiers that the wrappers of `brumate/events` put on a handler. */\nconst MODIFIERS = Symbol.for('brumate.modifiers');\n\n/**\n * Renders an object of attributes. With `on`, a handler in it that the core\n * made from a reference goes into `on` as a `b-on` entry, with the scope and\n * the arguments of its reference and the modifiers of its wrappers.\n */\nexport function spread(\n attributes: Record<string, unknown>,\n on?: string[],\n names?: boolean,\n): string {\n if (on) {\n on.push(...spreadEntries(attributes));\n // The `b-on` of a dynamic tag that names a component is in `on`, not written as an attribute.\n return spreadText({ ...attributes, 'b-on': undefined }, names);\n }\n return spreadText(attributes, names);\n}\n\n/** The `b-on` entries of the handlers and bindings of an object of attributes. */\nexport function spreadEntries(attributes: Record<string, unknown>): string[] {\n const on: string[] = [];\n for (const [name, value] of Object.entries(attributes)) {\n if (name === 'b-on' && ownValue(name, value)) {\n on.unshift(ownValue(name, value) as string);\n }\n // A merged handler writes one entry for each of its parts.\n const parts =\n /^on[A-Z]/.test(name) && typeof value === 'function'\n ? ((value as { [PARTS]?: object[] })[PARTS] ?? [value])\n : [];\n for (const part of parts) {\n const reference = handlerReferences.get(part);\n if (reference) {\n on.push(\n handlerEntry(name, reference.ref, reference.scope, reference.modifiers, reference.args),\n );\n }\n }\n // A binding that a rest prop passed on writes its slot, or calls its setter.\n if ((name === 'value' || name === 'checked') && HAS_BINDINGS && isBinding(value)) {\n on.push(bindEntry(name, value.ref, setterReference(value.set)));\n }\n }\n return on;\n}\n\n/** The reference of the setter of a binding: as the state has it, or of a handler that the core made. */\nfunction setterReference(setter: unknown): FunctionReference | undefined {\n if (setter instanceof FunctionReference) {\n return setter;\n }\n return typeof setter === 'function' ? handlerReferences.get(setter) : undefined;\n}\n\n/** Replaces function references with functions that call them. */\nexport function callable(value: unknown, seen: Set<object>): unknown {\n if (HAS_CHILDREN && value instanceof ChildrenReference) {\n // The scope can come later in the state, such as of a page that navigation loads.\n return new RenderedChildren(value.scope, value.ref, value.at, value.anchor);\n }\n if (value instanceof FunctionReference) {\n if (HAS_TEMPLATES && isTemplate(value.ref)) {\n return templateReference(value.ref, scopes.get(value.scope));\n }\n // The code of the components on the page loads with the page, and handlers and updates wait\n // for it. So the function runs at once and returns its result, as on the server.\n // An arrow, to keep the narrowing of `value`.\n const handler = (...args: unknown[]): unknown => {\n const fn = loadedFunction(value.ref);\n const all = [...(value.args ?? []), ...args];\n return fn\n ? fn(scopes.get(value.scope), ...all)\n : call(value.ref, scopes.get(value.scope), all);\n };\n handlerReferences.set(handler, value);\n return handler;\n }\n if (typeof value === 'object' && value !== null && !seen.has(value)) {\n seen.add(value);\n const prototype = Object.getPrototypeOf(value);\n if (Array.isArray(value) || prototype === Object.prototype || prototype === null) {\n const record = value as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n record[key] = callable(record[key], seen);\n }\n // The parts of a merged handler.\n if (PARTS in record) {\n return mergeHandlers(value as ((...args: unknown[]) => unknown)[]);\n }\n }\n }\n return value;\n}\n\n// The handler of the previous event, once it has started.\nexport let lastHandler: Promise<unknown> = Promise.resolve();\n\n/** Forgets the handler of the previous event, for a new page. */\nexport function resetHandler(): void {\n lastHandler = Promise.resolve();\n}\n\n/**\n * Keeps `currentTarget` on an event. The handler runs after the event has\n * finished dispatching, when the browser has already cleared it.\n */\nfunction withTarget(event: Event, element: Element): Event {\n return new Proxy(event, {\n get(target, key) {\n if (key === 'currentTarget') {\n return element;\n }\n const value: unknown = Reflect.get(target, key);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n}\n\n/** Whether an input is a checkbox or a radio, which a binding reads by `checked`. */\nexport function isBox(field: HTMLInputElement): boolean {\n return /^(checkbox|radio)$/i.test(field.type);\n}\n\n/** The value a binding writes: of a field of a part, whether a box is checked, or the value. */\nfunction fieldValue(element: Element, typed?: { value: unknown }): unknown {\n const field = element as HTMLInputElement;\n if (typed) {\n return typed.value;\n }\n return isBox(field) ? field.checked : field.value;\n}\n\n/**\n * Runs the handler `ref` for an element. The scope comes from the element's\n * `b-b` anchor, or from the nearest element around it that has one, which\n * the compiler checks is in the same scope.\n */\nexport function handle(\n element: Element,\n entry: string,\n event?: Event,\n typed?: { value: unknown },\n): Promise<unknown> {\n // A handler that a spread passed on, such as `Parent#h1@3`, runs in the scope of its owner.\n // A handler that `$handler` made has its arguments after another `@`.\n const [ref, owner, encoded] = entry.split('@') as [string, string | undefined, string?];\n const bound = encoded ? (JSON.parse(decodeURIComponent(encoded)) as unknown[]) : [];\n const anchor = owner ?? element.closest('[b-b]')?.getAttribute('b-b')?.split(':')[0];\n const scope = anchor ? scopes.get(parseId(anchor)) : undefined;\n // A callback that the browser runs later, such as a `$client` callback for when the page is\n // idle, does not run once its element and its scope are gone, such as after the block or the\n // page that held it was removed.\n if (anchor && !scope && !element.isConnected) {\n return Promise.resolve();\n }\n // A `<window>` or `<document>` listener in a hidden `#offscreen` body does not run.\n if (scope && hiding?.hidden(scope) && element.hasAttribute('b-listen')) {\n return Promise.resolve();\n }\n // `value=$bind(name)` on an element: the core writes the slot of the name, `hops` parents up\n // from the element's scope, from the value of the element, or whether a box is checked.\n // `value=$bind(name, fn)`: the setter takes the value of the element. A ref names its scope\n // after `@`, so the prefix is `$set:`.\n // `typed` is a value that `readFields` took from a field of a part, in place of the element's own.\n if (ref.startsWith('$set:')) {\n return call(ref.slice(5), scope, [fieldValue(element, typed)]);\n }\n if (ref.startsWith('$bind#')) {\n const [hopsText, slotText] = ref.slice(6).split('.');\n const hops = Number(hopsText ?? 0);\n const slot = Number(slotText ?? 0);\n let target = scope;\n for (let hop = 0; hop < hops; hop++) {\n target = target?.p;\n }\n if (target) {\n set(target, slot, fieldValue(element, typed));\n }\n return Promise.resolve();\n }\n const args = event ? [...bound, withTarget(event, element)] : bound;\n const begun = DEV ? performance.now() : 0;\n if (DEV) {\n devtools()?.handler?.(ref, element, event);\n }\n // Modules load in parallel, but handlers start in the order of their events,\n // so an input handler runs before the submit handler of a later event.\n // The code of the children that the handler can insert loads with it.\n // So does the code of the page, which the handler can call.\n const children = childrenReady(scope);\n const code = codeReady();\n const loaded = Promise.all([resolve(ref), children, code]).then(([handler]) => handler);\n const started = lastHandler\n .then(() => loaded)\n .then((handler) => {\n if (!DEV) {\n return { value: pass(() => handler(scope, ...args)) };\n }\n const ready = performance.now();\n const value = pass(() => handler(scope, ...args));\n devtools()?.handled?.({\n ref,\n element,\n event: event?.type,\n begun,\n ready,\n end: performance.now(),\n result: value,\n });\n return { value };\n });\n lastHandler = started.catch(() => {});\n // An error of the handler, or of the promise that an async one returns, goes to the nearest\n // `#try` around its scope.\n return started\n .then((result) => result.value)\n .catch((error: unknown) => {\n fail(scope, error);\n });\n}\n\n/** Renders the attributes of a form or button that posts to a server function. */\nexport function action(name: string, id: string, method?: string, result?: string): string {\n return actionAttributes(rpcPrefix, name, id, method, result, build);\n}\n\n/**\n * Sends a form of an `$action`. The code is in `rpc.ts`, which every server\n * call loads, so the core holds only this.\n */\nexport function submitAction(form: HTMLFormElement, submitter: HTMLElement | null): void {\n void import('../rpc.ts').then((module) => module.sendAction(form, submitter));\n}\n\n/** Calls a server function. */\nexport async function rpc(id: string, args: unknown[]): Promise<unknown> {\n // Read before the import, while the memo that calls it computes.\n const signal = memoSignal();\n return track(import('../rpc.ts').then((module) => module.call(rpcPrefix, id, args, signal)));\n}\n\n/** A function prop rendered on the client calls the parent's exported handler. */\nexport function handlerProp(\n value: unknown,\n ref: string,\n scope: Scope | number,\n bound: unknown[] = [],\n modifiers?: string[],\n): unknown {\n // A promise is no handler. Production passes it on as it is.\n if (DEV && isThenable(value)) {\n throw new Error(\n `The handler prop of ${ref} gives a promise, and an event handler cannot wait for one [BRM188]. Await it in the code that runs, or read its value with $memo`,\n );\n }\n // A template renders at once, and the client has its code already.\n if (typeof value !== 'function' || isTemplate(ref)) {\n return value;\n }\n const instance = resolveScope(scope);\n // The function runs at once and returns its result, as a reference in the page state does.\n // Its export reads the current values of its scope. Before the code of its component loads,\n // such as while the browser renders the component for the first time, the function of the\n // render runs.\n function handler(...args: unknown[]): unknown {\n const fn = loadedFunction(ref);\n const all = [...bound, ...args];\n return fn ? fn(instance, ...all) : (value as (...rest: unknown[]) => unknown)(...all);\n }\n // A spread of markup that the browser renders passes it on, with the modifiers of its wrappers.\n // A scope that is not in the page yet has its ID in `scope`.\n handlerReferences.set(\n handler,\n new FunctionReference(\n ref,\n instance?.id ?? (scope as ScopeId),\n bound.length > 0 ? bound : undefined,\n modifiers ?? (value as { [MODIFIERS]?: string[] })[MODIFIERS],\n ),\n );\n return handler;\n}\n","// Reads the state of the page and starts the core: the state records, the scopes they hold, and\n// what leaving a page or some routes drops.\n\nimport { HAS_BINDINGS, HAS_FIELDS, HAS_LATE_MARKUP, HAS_TRIES } from '../features.ts';\nimport {\n CHILDREN,\n ElementReference,\n ITEM,\n ITEM_SLOT,\n MODULE,\n OWNER,\n PREFIX,\n SOURCE,\n isPropWrapper,\n isSlotReference,\n parseId,\n stateValues,\n useSerialEntry,\n} from '../shared.ts';\nimport type { PackedState, PageState, ScopeId, ScopeState } from '../shared.ts';\nimport {\n findElement,\n indexMarkers,\n observeMarkers,\n rendered,\n stopObserving,\n unindexed,\n} from './blocks.ts';\nimport { loadComponent, pageComponents } from './code.ts';\nimport { leaveGuesses, settled } from './guesses.ts';\nimport { failBoundary, replaceTry } from './errors.ts';\nimport { callable, handle, isBox, resetHandler } from './handlers.ts';\nimport { refresh } from './insert.ts';\nimport { removeScope, resetIds, treeChanged } from './scopes.ts';\nimport {\n DEV,\n comments,\n configure,\n devtools,\n elements,\n guesses,\n hooks,\n loading,\n loadingSlots,\n loads,\n memoControllers,\n modules,\n refs,\n loadingValues,\n renderedLoads,\n scopes,\n setHiding,\n timers,\n} from './state.ts';\nimport type { CoreOptions, Scope } from './state.ts';\nimport { watchTitles } from './titles.ts';\nimport { give, pendingEffects, resetWrites, send, set, writes } from './updates.ts';\n\n/**\n * A state record: its script, and its code, which seroval wrote. The code\n * takes the references of its render and the functions that make brumate's\n * values, and returns the value of the record.\n */\ntype StateRecord = [\n script: HTMLScriptElement | null,\n code: (refs: unknown[], values: typeof stateValues) => unknown,\n];\n\n/**\n * The records that ran before the core started, or while it stopped. Each\n * state script hands its record to `push`, which the core replaces while it\n * runs, so it reads later records at once.\n */\nfunction stateQueue(): StateRecord[] {\n const global = globalThis as { $brm?: StateRecord[] };\n return (global.$brm ??= []);\n}\n\n/** Reads the records that later state scripts hand over. Set while the core runs. */\nfunction pushRecords(...added: StateRecord[]): number {\n for (const record of added) {\n readRecord(record);\n }\n return 0;\n}\n\n/**\n * Reads a state record. The first record holds the page state, and later\n * records settle the promises in it.\n */\nfunction readRecord([script, code]: StateRecord): void {\n // A record of a page that navigation replaced before the core started.\n if (!script?.isConnected) {\n return;\n }\n const root = script.getAttribute('b-root') ?? '0';\n if (!refs.has(root)) {\n refs.set(root, []);\n }\n const decoded = code(refs.get(root)!, stateValues);\n // The `#catch` body of a `#try` around a `#loading` body that failed on the server.\n const catches = HAS_TRIES ? script.getAttribute('b-catch') : null;\n if (catches !== null) {\n replaceTry(catches);\n return;\n }\n // The error of a `#loading` body that failed on the server, with no `#try` around it.\n const failed = HAS_LATE_MARKUP ? script.getAttribute('b-fail') : null;\n if (failed !== null) {\n failBoundary(decoded);\n return;\n }\n // Records with scopes: the page state, and the state of each `#loading` body.\n if (script.hasAttribute('b-scopes')) {\n const unpacked = unpackState(decoded as PackedState);\n const added = addScopes(hooks.record ? hooks.record(script, unpacked) : unpacked, root);\n if (writes > 0) {\n refresh(added);\n }\n }\n}\n\n/** Reads the groups of scope records back into one record per scope. See `PackedState`. */\nfunction unpackState(state: PackedState): PageState {\n // Items to take from the list in a slot of another record, once every record is read.\n const taken: [records: ScopeState[], source: ScopeId, slot: number, first: number][] = [];\n for (const group of state.g ?? []) {\n const [k, base, flags] = group as number[];\n const count = group[3] as number;\n let at = 4;\n const m = flags & MODULE ? (group[at++] as string) : undefined;\n const source: ScopeState[] | undefined = flags & SOURCE ? [] : undefined;\n if (source) {\n taken.push([source, group[at++] as ScopeId, group[at++] as number, flags & ITEM_SLOT]);\n }\n // Scopes inside a `#loading` body: their IDs are this prefix and a number.\n const prefix = flags & PREFIX ? (group[at++] as string) : '';\n function id(n: number): ScopeId {\n return prefix ? prefix + n : n;\n }\n // The first slot of a taken item is not written. The gap before the slots holds its place.\n const skip = source && flags & ITEM_SLOT ? 1 : 0;\n let n = flags & (OWNER | PREFIX) ? 0 : base;\n while (at < group.length) {\n n += group[at++] as number;\n const s = group.slice(at - skip, (at += count - skip));\n const record: ScopeState = flags & OWNER ? { k, o: id(n - base) } : { k, p: base };\n record.s = s;\n if (m !== undefined) {\n record.m = m;\n }\n if (source) {\n source.push(record);\n } else if (flags & ITEM_SLOT) {\n record.i = s[0];\n } else if (flags & ITEM) {\n record.i = group[at++];\n }\n if (flags & CHILDREN) {\n record.c = group[at++] as Record<number, ScopeId>;\n }\n state[id(n)] = record;\n }\n }\n delete state.g;\n for (const [records, source, slot, first] of taken) {\n // An array, or a Set, whose order the state keeps.\n const values = Array.from(state[source]!.s![slot] as Iterable<unknown>);\n for (let n = 0; n < records.length; n++) {\n const record = records[n]!;\n record.i = values[n];\n if (first) {\n record.s![0] = values[n];\n }\n }\n }\n return state;\n}\n\nfunction addScopes(state: PageState, root: string): Scope[] {\n const added: Scope[] = [];\n for (const [key, record] of Object.entries(state)) {\n const id = parseId(key);\n const scope: Scope = {\n id,\n k: record.k ?? 0,\n m: record.m,\n s: record.s ?? [],\n i: record.i,\n c: record.c,\n v: record.v,\n x: record.x,\n b: record.b,\n r: root,\n };\n scopes.set(id, scope);\n added.push(scope);\n }\n for (const scope of added) {\n const record = state[scope.id]!;\n if (record.p !== undefined) {\n scope.p = scopes.get(record.p);\n if (scope.p) {\n (scope.p.children ??= new Set()).add(scope);\n }\n treeChanged();\n }\n if (record.o !== undefined) {\n scope.o = scopes.get(record.o);\n if (scope.o) {\n (scope.o.owned ??= new Set()).add(scope);\n }\n }\n if (record.t !== undefined) {\n scope.t = scopes.get(record.t);\n }\n if (record.f !== undefined) {\n scope.f = scopes.get(record.f);\n }\n if (record.l !== undefined) {\n scope.l = scopes.get(record.l);\n }\n }\n for (const scope of added) {\n if (scope.m) {\n loadComponent(scope.m);\n }\n }\n const seen = new Set<object>();\n for (const scope of added) {\n // A provided value can hold functions, which a component that reads the context calls.\n for (const key of Object.keys(scope.v ?? {})) {\n scope.v![key] = callable(scope.v![key], seen);\n }\n for (let i = 0; i < scope.s.length; i++) {\n const value = callable(scope.s[i], seen);\n scope.s[i] = value;\n // A promise prop stays a promise, which the stream settles. Nothing handles its rejection.\n if (isPropWrapper(value)) {\n scope.s[i] = value.promise;\n (scope.plain ??= new Set()).add(i);\n value.promise.catch(() => {});\n continue;\n }\n // A value that a later state record settles replaces its promise.\n if (value instanceof Promise) {\n loadingValues.add(value);\n void value.then((result) => {\n settled.set(value, result);\n // A memo that loads again in the browser has a newer load, and the record is old.\n if (scope.s[i] === value && !loads.has(`${scope.id}:${i}`)) {\n set(scope, i, result);\n }\n });\n }\n }\n }\n if (HAS_BINDINGS) {\n // A prop that the server bound with a setter, and that the component wrote an element into.\n for (const scope of added) {\n for (const [slot, bound] of Object.entries(scope.b ?? {})) {\n const value = scope.s[+slot];\n const element =\n value instanceof ElementReference ? findElement(value.scope, value.anchor) : null;\n if (element && !isSlotReference(bound)) {\n send(bound, element);\n }\n }\n }\n // A setter ref in the rest props of a component, by the anchor of the element that spreads them.\n for (const scope of added) {\n for (const [anchor, bound] of Object.entries(state[scope.id]!.r ?? {})) {\n const element = findElement(scope.id, +anchor);\n if (element) {\n give(bound, element);\n }\n }\n }\n }\n hooks.added?.(added);\n return added;\n}\n\n/** Stops reading state records and markers that arrive later. Later records wait for `init`. */\nexport function dispose(): void {\n const queue = stateQueue();\n if (queue.push === pushRecords) {\n // The array's own `push` again, so records wait in it.\n delete (queue as { push?: unknown }).push;\n }\n stopObserving();\n}\n\n/**\n * Stops reading, before client navigation replaces only some routes. The\n * server renders the new routes with its current values, so only the writes\n * that come after count for the records that stream in later.\n */\nexport function leaveRoutes(): void {\n dispose();\n resetWrites();\n}\n\n/**\n * Removes the scopes of a render, by its `b-root`, with the scopes inside\n * them. Their cleanups run, and their memos no longer load. Its markup\n * stays. `brumate/testing` calls it when a mounted component unmounts.\n */\nexport function removeRoot(root: string): void {\n function inside(scope: Scope): boolean {\n for (let current: Scope | undefined = scope; current; current = current.p ?? current.o) {\n if (current.r === root) {\n return true;\n }\n }\n return false;\n }\n // Deleting from a map while iterating it is safe.\n for (const scope of scopes.values()) {\n if (inside(scope)) {\n removeScope(scope);\n }\n }\n refs.delete(root);\n for (const cache of [comments, elements]) {\n for (const [key, node] of cache) {\n if (!node.isConnected) {\n cache.delete(key);\n }\n }\n }\n}\n\n/**\n * Forgets the code of components that changed on the dev server, so the next\n * event or update loads the new code. Their state stays. `brumate/hot` calls it.\n */\nexport function forget(ids: string[]): void {\n for (const id of ids) {\n modules.delete(id);\n loading.delete(id);\n // The new code loads when a scope of the component is read or rendered again.\n pageComponents.delete(id);\n }\n}\n\n/** The values of the signals of components whose markup changed, for when the page renders again. */\nconst remounts = new Map<\n string,\n { after: Record<number, string[]>; values: Record<string, unknown>[] }\n>();\n\n/**\n * Keeps the values of the signals of each instance of a component, by\n * name, before the page renders again with its new markup. `brumate/hot` calls it.\n */\nexport function remount(\n detail: {\n id: string;\n before: Record<number, string[]>;\n after: Record<number, string[]>;\n signals: string[];\n }[],\n): void {\n hooks.added = restoreRemounts;\n for (const { id, before, after, signals } of detail) {\n const names = new Set(signals);\n // The signals of the script of the component. Signals of blocks, such as of a `#for`\n // body, start again.\n const kept: Record<string, unknown>[] = [];\n for (const root of scopes.values()) {\n if (root.m === id) {\n const values: Record<string, unknown> = {};\n for (const [slot, name] of (before[root.k] ?? []).entries()) {\n if (names.has(name)) {\n values[name] = root.s[slot];\n }\n }\n kept.push(values);\n }\n }\n remounts.set(id, { after, values: kept });\n }\n}\n\n/** Writes back the values of signals that `onRemount` kept, into the instances of the new page. */\nfunction restoreRemounts(added: Scope[]): void {\n for (const [id, { after, values }] of remounts) {\n const instances: Scope[] = [];\n for (const scope of added) {\n if (scope.m === id) {\n instances.push(scope);\n }\n }\n if (instances.length === 0) {\n continue;\n }\n remounts.delete(id);\n for (const [index, root] of instances.entries()) {\n const saved = values[index];\n for (const [slot, name] of (after[root.k] ?? []).entries()) {\n if (saved && name in saved) {\n set(root, slot, saved[name]);\n }\n }\n }\n }\n}\n\n/**\n * Forgets the page, before another page replaces it. Cleanups run. Loaded\n * modules and parts stay, so the next page does not load them again. Only\n * client navigation calls it.\n */\nexport function leavePage(): void {\n dispose();\n for (const scope of scopes.values()) {\n for (const cleanup of scope.cleanups?.values() ?? []) {\n cleanup();\n }\n }\n scopes.clear();\n comments.clear();\n elements.clear();\n unindexed.length = 0;\n rendered.length = 0;\n pendingEffects.clear();\n setHiding(undefined);\n loads.clear();\n loadingSlots.clear();\n for (const memoController of memoControllers.values()) {\n memoController.abort();\n }\n memoControllers.clear();\n renderedLoads.clear();\n for (const { timer } of timers.values()) {\n clearTimeout(timer);\n }\n timers.clear();\n // The next page reuses scope IDs, so a guess left here would match its memos.\n guesses?.map.clear();\n resetIds();\n refs.clear();\n resetWrites();\n leaveGuesses();\n resetHandler();\n}\n\n/**\n * Whether the user changed a field since the server rendered it. The server's value is in\n * `defaultValue`, `defaultChecked` and `defaultSelected`. This runs only when the core starts,\n * before any update wrote the field. A value that the browser cleans, such as a number or a\n * range input, can differ from `defaultValue` without the user, and counts as typed.\n */\nfunction typedInto(element: Element): boolean {\n const field = element as HTMLInputElement;\n if (element instanceof HTMLSelectElement) {\n // The last `selected` option wins. Without one, a single select shows its first option that\n // is not disabled, also by a disabled optgroup (`:disabled` knows, `option.disabled` does not), and a list box or a `multiple` select shows none. The test DOM has no\n // `defaultSelected`, so the `selected` attribute is read.\n let expected = -1;\n let first = -1;\n let changed = false;\n for (let i = 0; i < element.options.length; i++) {\n const option = element.options[i]!;\n const rendered = option.hasAttribute('selected');\n if (rendered) {\n expected = i;\n }\n if (first < 0 && !option.matches(':disabled')) {\n first = i;\n }\n changed ||= option.selected !== rendered;\n }\n if (element.multiple) {\n return changed;\n }\n const shown = Number(element.getAttribute('size')) > 1 ? -1 : first;\n return element.selectedIndex !== (expected >= 0 ? expected : shown);\n }\n return isBox(field) ? field.checked !== field.defaultChecked : field.value !== field.defaultValue;\n}\n\n/**\n * Writes the signal of each bound field that the user changed before the code loaded, as an\n * `input` event would. The text is in the DOM, and the first update would write the old value\n * back. A field that still has the value the server rendered is not read.\n */\nfunction readFields(): void {\n for (const element of document.querySelectorAll('[b-on*=\"=$bind#\"],[b-on*=\"=$set:\"]')) {\n const custom = hooks.field?.(element);\n if (custom === false || (!custom && !typedInto(element))) {\n continue;\n }\n for (const entry of element.getAttribute('b-on')!.split(' ')) {\n const ref = entry.slice(entry.indexOf('=') + 1);\n if (/^\\$(bind#|set:)/.test(ref)) {\n void handle(element, ref, undefined, custom);\n }\n }\n }\n}\n\n/** Reads the page state. The loader calls it once, before the first handler. */\nexport function init(value: CoreOptions): void {\n configure(value);\n if (value.serial) {\n useSerialEntry(value.serial);\n }\n const queue = stateQueue();\n // Records that are still streaming settle their promises when their scripts run. A promise of\n // the page state streams in a later record without any markup that comes later.\n queue.push = pushRecords;\n for (const record of queue.splice(0)) {\n readRecord(record);\n }\n if (HAS_LATE_MARKUP) {\n observeMarkers();\n } else if (document.readyState === 'loading') {\n // The page that the browser reads after an `async` script starts is indexed when it ends.\n document.addEventListener('DOMContentLoaded', () => indexMarkers(document.documentElement), {\n once: true,\n });\n }\n // The whole document, because `#head` content is in the head.\n indexMarkers(document.documentElement);\n if (HAS_FIELDS) {\n readFields();\n }\n watchTitles(document);\n if (DEV) {\n devtools()?.attach?.({ scopes, set, handle });\n }\n}\n","// Markup that the browser clones: a template parsed once, the walk to its nodes, and the helpers\n// that fill a clone.\n\nimport { HAS_CHILDREN } from '../features.ts';\nimport { attributeText, onValue } from '../html.ts';\nimport type { ScopeId } from '../shared.ts';\nimport { trustedHTML } from '../trusted.ts';\nimport type { Render } from './branches.ts';\nimport { Children, TemplateCall, insert } from './children.ts';\nimport { spread } from './handlers.ts';\nimport { findForeign, holdPlace, markCloned, parseHTML } from './insert.ts';\nimport { resolveScope } from './scopes.ts';\nimport { options, scopes } from './state.ts';\nimport type { Scope } from './state.ts';\n\n/** Markup that the browser clones, and the paths to the elements that its render writes. */\ninterface Template {\n html: string;\n /** How many elements the render writes, which have `b-x` in `html`. */\n count: number;\n /** `svg` or `math`, for markup whose elements are of SVG or MathML, which parses inside one. */\n foreign?: string;\n t?: HTMLTemplateElement;\n /** The moves that reach the marked nodes of a clone. See `encodeWalk`. */\n walk?: number[];\n}\n\n/** A template of the markup of a render, which `clone` parses once. */\nexport function template(html: string, count: number, foreign?: string): Template {\n return { html, count, foreign };\n}\n\n/**\n * Parses a template, and finds the path to each element that it marks with `b-x`, as the parser\n * placed it: after the parser's own changes, such as a `<tbody>` that it adds.\n */\nfunction parseTemplate(source: Template): number[][] {\n const element = document.createElement('template');\n element.innerHTML = trustedHTML(\n source.foreign ? `<${source.foreign}>${source.html}</${source.foreign}>` : source.html,\n );\n const root = element.content;\n if (source.foreign) {\n root.replaceChildren(...root.firstChild!.childNodes);\n }\n const paths: number[][] = Array.from({ length: source.count });\n function findPath(marked: Node): number[] {\n const path: number[] = [];\n for (let node: Node = marked; node !== root; node = node.parentNode!) {\n let index = 0;\n for (let before = node.previousSibling; before; before = before.previousSibling) {\n index++;\n }\n path.unshift(index);\n }\n return path;\n }\n for (const marked of root.querySelectorAll('[b-x]')) {\n paths[Number(marked.getAttribute('b-x'))] = findPath(marked);\n marked.removeAttribute('b-x');\n }\n // The start comments of text inserts, `<!--x` and an index, which each clone names.\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n const mark = /^x(\\d+)$/.exec((node as Comment).data);\n if (mark) {\n paths[Number(mark[1])] = findPath(node);\n }\n }\n // The loader listens to the events of the handlers of the template once, not of each clone.\n // A render before the core starts, such as in a test, has nothing that listens yet.\n options?.listen(root);\n source.t = element;\n return paths;\n}\n\n// The moves of a walk: a number from 0 is the index of the node that the walk is at, and the\n// others move it.\nconst FIRST_CHILD = -1;\n\nconst PARENT = -2;\n\n// `NEXT - n` moves to the `n`th next sibling.\nconst NEXT = -2;\n\n/**\n * The moves that reach the marked nodes of a template, in the order of the markup, from one to\n * the next: up to the ancestor that they share, along its children, and down. A clone makes\n * them once for its template, as Marko encodes a walk, so the clones of a render do not walk\n * from the top for each node or make an array of paths.\n */\nfunction encodeWalk(paths: number[][]): number[] {\n const marked: { path: number[]; mark: number }[] = [];\n for (const [mark, path] of paths.entries()) {\n marked.push({ path, mark });\n }\n const order = marked.sort((a, b) => {\n for (let depth = 0; depth < Math.min(a.path.length, b.path.length); depth++) {\n if (a.path[depth] !== b.path[depth]) {\n return a.path[depth]! - b.path[depth]!;\n }\n }\n return a.path.length - b.path.length;\n });\n const moves: number[] = [];\n function along(count: number): void {\n if (count > 0) {\n moves.push(NEXT - count);\n }\n }\n let current: number[] = [];\n for (const { path, mark } of order) {\n let shared = 0;\n while (shared < current.length && current[shared] === path[shared]) {\n shared++;\n }\n let depth = shared;\n if (shared < current.length) {\n // Up to the child of the shared ancestor that holds the last node, then along to the\n // child that holds this one.\n for (let up = current.length - 1; up > shared; up--) {\n moves.push(PARENT);\n }\n along(path[shared]! - current[shared]!);\n depth++;\n }\n for (; depth < path.length; depth++) {\n moves.push(FIRST_CHILD);\n along(path[depth]!);\n }\n moves.push(mark);\n current = path;\n }\n return moves;\n}\n\n/**\n * A node of a clone: an element, the comment of an insert, or the fragment. The type lets the\n * render pass each to the write that takes it.\n */\ntype ClonedNode = Element & Comment & DocumentFragment;\n\n/**\n * Clones a template. Returns the nodes that the template marks, by their index, and the fragment\n * after them, in one array.\n */\nexport function clone(source: Template): ClonedNode[] {\n const walk = (source.walk ??= encodeWalk(parseTemplate(source)));\n const fragment = source.t!.content.cloneNode(true);\n // oxlint-disable-next-line unicorn/no-new-array -- A length, with no values written in yet.\n const cloned: Node[] = new Array(source.count + 1);\n cloned[source.count] = fragment;\n let node: Node = fragment;\n for (let index = 0; index < walk.length; index++) {\n const move = walk[index]!;\n if (move >= 0) {\n cloned[move] = node;\n } else if (move === FIRST_CHILD) {\n node = node.firstChild!;\n } else if (move === PARENT) {\n node = node.parentNode!;\n } else {\n for (let step = NEXT - move; step > 0; step--) {\n node = node.nextSibling!;\n }\n }\n }\n return cloned as ClonedNode[];\n}\n\n/**\n * Keeps an element of cloned markup on its scope, where updates find it. An element at the top\n * of the clone, or one with handlers, gets its `b-b` too, which `list` and the handlers read to\n * find the scope.\n */\nexport function keep(scope: ScopeId, anchor: number, element: Element, named?: boolean): void {\n const found = scopes.get(scope);\n if (found) {\n (found.n ??= [])[anchor] = element;\n }\n // `named`: elements inside it have handlers and find their scope from it with `closest`.\n if (named || element.parentNode?.nodeType === 11 || element.hasAttribute('b-on')) {\n element.setAttribute('b-b', `${scope}:${anchor}`);\n }\n}\n\n/**\n * Puts the value of a text insert of cloned markup in the place of its comment. A text value is\n * a text node, which the scope keeps, as Solid keeps it, so an update sets its data. Other\n * values render between the markers of an insert, as in HTML.\n */\nexport function keepText(\n scope: ScopeId,\n anchor: number,\n place: Comment,\n value: unknown,\n at: ScopeId | Scope = scope,\n): void {\n const found = scopes.get(scope);\n if (typeof value === 'string' || typeof value === 'number') {\n const node = document.createTextNode(String(value));\n place.replaceWith(node);\n if (found) {\n (found.n ??= [])[anchor] = node;\n }\n return;\n }\n keepMarkers(scope, anchor, place, value, at);\n}\n\n/** Puts a text insert at the end of an element of cloned markup, as `keepText` does. */\nexport function appendText(\n scope: ScopeId,\n anchor: number,\n parent: Element,\n value: unknown,\n at: ScopeId | Scope = scope,\n): void {\n if (typeof value === 'string' || typeof value === 'number') {\n const node = document.createTextNode(String(value));\n parent.append(node);\n const found = scopes.get(scope);\n if (found) {\n (found.n ??= [])[anchor] = node;\n }\n return;\n }\n const place = document.createComment('');\n parent.append(place);\n keepMarkers(scope, anchor, place, value, at);\n}\n\n/** Gives a value that is not text the markers of an insert, and renders it between them. */\nfunction keepMarkers(\n scope: ScopeId,\n anchor: number,\n place: Comment,\n value: unknown,\n at: ScopeId | Scope,\n): void {\n const found = scopes.get(scope);\n place.data = `t${scope}:${anchor}`;\n place.after(document.createComment('/t'));\n if (found) {\n (found.n ??= [])[anchor] = place;\n }\n if (value !== null && value !== undefined && typeof value !== 'boolean') {\n // Children, a template or raw HTML.\n place.after(insertNodes(value, at, place));\n }\n}\n\n/** Names the start marker of a nested block of cloned markup, and keeps it on its scope. */\nfunction keepBlock(\n place: Comment,\n scope: ScopeId,\n data: string,\n anchor: number,\n): Scope | undefined {\n place.data = data;\n const found = scopes.get(scope);\n if (found) {\n (found.n ??= [])[anchor] = place;\n }\n return found;\n}\n\n/** Puts what renders gave into the range that a marker of cloned markup opens. */\nfunction fillRange(place: Comment, html: string, inserted: DocumentFragment | undefined): void {\n if (html) {\n // Markup that a render gave as HTML, which the insert of the clone indexes.\n place.after(parseHTML(html, place));\n markCloned();\n } else if (inserted) {\n place.after(inserted);\n }\n}\n\n/** Names the start marker of a block whose markup is in the clone, and keeps it on its scope. */\nexport function markBlock(place: Comment, scope: ScopeId, anchor: number, suffix: string): void {\n keepBlock(place, scope, `b${scope}:${anchor}${suffix}`, anchor);\n}\n\n/**\n * Fills a nested `#if` of cloned markup with the branch at `index`, or nothing for -1, before\n * the clone is in the page. `branch` updates it later.\n */\nexport function fillBranch(\n place: Comment,\n scope: ScopeId,\n anchor: number,\n index: number,\n renders: Render[],\n): void {\n const found = keepBlock(place, scope, `b${scope}:${anchor}:${index}`, anchor);\n const render = renders[index];\n if (found && render) {\n const out = render(found);\n fillRange(place, typeof out === 'string' ? out : '', typeof out === 'string' ? undefined : out);\n }\n}\n\n/** Fills a nested `#for` of cloned markup with its items, before the clone is in the page. */\nexport function fillList(\n place: Comment,\n scope: ScopeId,\n anchor: number,\n items: unknown[],\n render: Render,\n): void {\n const found = keepBlock(place, scope, `b${scope}:${anchor}`, anchor);\n if (!found) {\n return;\n }\n let html = '';\n let parts: DocumentFragment | undefined;\n for (let index = 0; index < items.length; index++) {\n const out = render(found, items[index], index);\n if (typeof out === 'string') {\n html += out;\n } else {\n (parts ??= document.createDocumentFragment()).append(out);\n }\n }\n fillRange(place, html, parts);\n}\n\n/** Writes an attribute of an element of cloned markup, as `attribute` writes it in HTML. */\nexport function setAttr(element: Element, name: string, value: unknown): void {\n const written = attributeText(name, value);\n if (written !== undefined) {\n element.setAttribute(name, written);\n }\n}\n\n/** The nodes of a block that renders where it is, in HTML: a place, which the parse fills. */\nexport function nodes(fragment: DocumentFragment): string {\n return holdPlace(fragment);\n}\n\n/** What a body gave, as nodes: its clone, or its HTML, which the insert of the clone indexes. */\nfunction bodyNodes(out: string | DocumentFragment): DocumentFragment {\n if (typeof out !== 'string') {\n return out;\n }\n markCloned();\n return parseHTML(out);\n}\n\n/** The markers of a block that renders where it is, around its nodes, with the start kept. */\nfunction blockNodes(\n scope: ScopeId | undefined,\n anchor: number | undefined,\n data: string,\n content: DocumentFragment,\n): DocumentFragment {\n if (scope === undefined || anchor === undefined) {\n return content;\n }\n const start = document.createComment(data);\n keepBlock(start, scope, data, anchor);\n content.prepend(start);\n content.append(document.createComment('/b'));\n return content;\n}\n\n/**\n * Renders an `#if` or a `#switch` where it is: the branch at `index`, or nothing for -1, between\n * its markers when it has them, which `branch` updates later.\n */\nexport function branchNodes(\n scope: ScopeId | undefined,\n anchor: number | undefined,\n index: number,\n bodies: (() => string | DocumentFragment)[],\n): DocumentFragment {\n const body = bodies[index];\n const content = body ? bodyNodes(body()) : document.createDocumentFragment();\n return blockNodes(scope, anchor, `b${scope}:${anchor}:${index}`, content);\n}\n\n/**\n * Renders a `#for` or a `#repeat` where it is: its items, or its fallback for none, between its\n * markers when it has them, which `list` updates later.\n */\nexport function listNodes(\n scope: ScopeId | undefined,\n anchor: number | undefined,\n items: unknown[],\n body: (item: unknown, index: number) => string | DocumentFragment,\n fallback: (() => string | DocumentFragment) | undefined,\n): DocumentFragment {\n const content = document.createDocumentFragment();\n for (let index = 0; index < items.length; index++) {\n content.append(bodyNodes(body(items[index], index)));\n }\n if (items.length === 0 && fallback) {\n content.append(bodyNodes(fallback()));\n }\n return blockNodes(scope, anchor, `b${scope}:${anchor}`, content);\n}\n\n/** Writes attributes that code of a start tag gave as their text, as HTML has them. */\nexport function setAttrText(element: Element, text: string): void {\n if (text) {\n // On an element of SVG or MathML, the parser gives the names their case, such as `viewBox`,\n // and their namespace, such as of `xlink:href`.\n const foreign = findForeign(element);\n const tag = foreign === 'math' ? 'mi' : 'g';\n const parsed = parseHTML(foreign ? `<${tag}${text}/>` : `<b${text}>`, undefined, foreign)\n .firstChild as Element;\n // The parsed attribute moves, so a name that `setAttribute` would reject, such as `@click`,\n // is written as the parser read it.\n for (const attribute of Array.from(parsed.attributes)) {\n parsed.removeAttributeNode(attribute);\n element.setAttributeNode(attribute);\n }\n }\n}\n\n/** Puts a value with no markers in the place of a comment of cloned markup, as `insert` does. */\nexport function putText(place: Comment, value: unknown, at?: ScopeId | Scope): void {\n place.replaceWith(\n typeof value === 'string' || typeof value === 'number'\n ? document.createTextNode(String(value))\n : insertNodes(value, at, place),\n );\n}\n\n/** Writes the spreads of an element of cloned markup, as `spread` writes them in HTML. */\nexport function setSpread(\n element: Element,\n attributes: Record<string, unknown>,\n on?: string[],\n names?: boolean,\n): void {\n setAttrText(element, spread(attributes, on, names));\n}\n\n/** Writes the `b-on` of an element of cloned markup with spreads, as `onAttribute` does. */\nexport function setOn(element: Element, on: string[], own: string): void {\n const value = onValue(on, own);\n if (value) {\n // Before `keep`, which then writes the `b-b` that the handlers read.\n element.setAttribute('b-on', value);\n // The loader listens to the events of the handlers of the spreads.\n options?.listen(element);\n }\n}\n\n/** Writes the content of an element of cloned markup, as `insert` writes it in HTML. */\nexport function setContent(element: Element, value: unknown, at?: ScopeId | Scope): void {\n if (typeof value === 'string' || typeof value === 'number') {\n element.textContent = String(value);\n return;\n }\n // Children, a template or raw HTML render here. Their work after the insert waits for it.\n element.replaceChildren(insertNodes(value, at, element));\n}\n\n/**\n * The nodes of children, a template or raw HTML in cloned markup: the clone of children whose\n * markup clones, or the markup, which the insert of the clone indexes, as it would in HTML.\n */\nfunction insertNodes(\n value: unknown,\n at: ScopeId | Scope | undefined,\n near: Node,\n): DocumentFragment {\n const out =\n HAS_CHILDREN && value instanceof Children && !(value instanceof TemplateCall)\n ? value.render(resolveScope(at))\n : insert(value, undefined, at);\n if (typeof out !== 'string') {\n return out;\n }\n markCloned();\n return parseHTML(out, near);\n}\n","// Child components that the browser renders, dynamic tags, and the slots and items that a render\n// sets.\n\nimport { VOID_ELEMENTS, onAttribute, ownValue } from '../html.ts';\nimport type { Raw } from '../html.ts';\nimport { ElementReference, addEntryHandlers } from '../shared.ts';\nimport type { ComponentValue, ScopeId } from '../shared.ts';\nimport { insert } from './children.ts';\nimport type { Children } from './children.ts';\nimport { callable, spread } from './handlers.ts';\nimport { holdPlace, markCloned, parseHTML } from './insert.ts';\nimport { nextId, resolveScope, setOwner } from './scopes.ts';\nimport { loadingValues, loads, renderedLoads, scopes, valueRenders } from './state.ts';\nimport type { Scope } from './state.ts';\nimport { setContent } from './templates.ts';\nimport { isThenable, noop, set } from './updates.ts';\n\n/** A component's client render function, from its `?brumate-render` module. */\n// oxlint-disable-next-line typescript/no-explicit-any -- Components take any props.\nexport type Component<P = any> = (props: P) => string | DocumentFragment;\n\n/** Puts a child component that a clone renders in the place of its comment. */\nexport function place(at: Comment, out: string | Node): void {\n if (typeof out === 'string') {\n // A component that renders HTML: its markup, which the insert of the clone indexes.\n at.replaceWith(parseHTML(out, at));\n markCloned();\n } else {\n at.replaceWith(out);\n }\n}\n\n/**\n * Renders a child component on the client. With `scope` and `anchor`,\n * records the child's scope so the parent can update its props.\n */\nexport function component<P>(\n Child: Component<P>,\n props: P,\n _ctx?: unknown,\n scope?: Scope | number,\n anchor?: number,\n): string {\n const parent = resolveScope(scope);\n if (parent && anchor !== undefined) {\n parent.c ??= {};\n parent.c[anchor] = nextId;\n }\n if (parent) {\n setOwner(parent);\n }\n return holdPlace(Child(props));\n}\n\n/** Renders a child component for a clone: its markup as HTML, or the clone that it made. */\nexport function componentNodes<P>(\n Child: Component<P>,\n props: P,\n _ctx?: unknown,\n scope?: Scope | number,\n anchor?: number,\n): string | DocumentFragment {\n const parent = resolveScope(scope);\n if (parent && anchor !== undefined) {\n parent.c ??= {};\n parent.c[anchor] = nextId;\n }\n if (parent) {\n setOwner(parent);\n }\n return Child(props);\n}\n\n/** The attributes of a dynamic element, with one `b-on` for its own handlers and those of its props. */\nfunction startAttributes(attributes: Record<string, unknown>): string {\n const on: string[] = [];\n return spread(attributes, on) + onAttribute(on, '');\n}\n\n/**\n * Renders a dynamic tag for a clone: the element, with its attributes and content, or what a\n * component renders.\n */\nexport function dynamicNodes(\n tag: unknown,\n attributes: Record<string, unknown>,\n inner: Raw | Children | undefined,\n _ctx?: unknown,\n scope?: Scope | number,\n ref?: unknown,\n foreign?: string,\n): string | Node {\n if (typeof tag === 'function') {\n // The anchor links the component to the tag, so updates reach its props. It is no prop.\n const {\n 'b-b': bound,\n 'b-on': entries,\n ...props\n } = ref === undefined ? attributes : { ...attributes, ref };\n // Its handlers reach the component as props, as the server passes them.\n addEntryHandlers(\n props,\n entries,\n typeof scope === 'object' ? scope.id : scope,\n (reference) => callable(reference, new Set()) as (...args: unknown[]) => unknown,\n );\n if (inner) {\n props.children = inner;\n }\n return componentNodes(\n valueRenders[(tag as ComponentValue).brumateId] ?? (tag as Component),\n props,\n undefined,\n scope,\n bound ? Number((ownValue('b-b', bound) as string).split(':')[1]) : undefined,\n );\n }\n const name = String(tag);\n // The start tag as HTML, so the attributes are written as `dynamic` writes them.\n const element = parseHTML(`<${name}${startAttributes(attributes)}>`, undefined, foreign)\n .firstChild as Element;\n const bound = element.getAttribute('b-b');\n if (bound) {\n const [id, anchor] = bound.split(':');\n const kept = scopes.get(Number(id));\n if (kept) {\n (kept.n ??= [])[Number(anchor)] = element;\n }\n }\n if (element.hasAttribute('b-on')) {\n // The insert of the clone listens to the events of the handlers.\n markCloned();\n }\n if (inner && !VOID_ELEMENTS.has(name)) {\n setContent(element, inner, scope);\n }\n return element;\n}\n\n/** `dynamicNodes` for a dynamic tag inside SVG or MathML, `svg` or `math`. */\nexport function foreignNodes(\n foreign: string,\n tag: unknown,\n attributes: Record<string, unknown>,\n inner: Raw | Children | undefined,\n ctx?: unknown,\n scope?: Scope | number,\n ref?: unknown,\n): string | Node {\n return dynamicNodes(tag, attributes, inner, ctx, scope, ref, foreign);\n}\n\nexport function dynamic(\n tag: unknown,\n attributes: Record<string, unknown>,\n inner: Raw | Children | undefined,\n _ctx?: unknown,\n scope?: Scope | number,\n ref?: unknown,\n): string {\n if (typeof tag === 'function') {\n return holdPlace(\n dynamicNodes(tag, attributes, inner, _ctx, scope, ref) as string | DocumentFragment,\n );\n }\n const name = String(tag);\n const open = `<${name}${startAttributes(attributes)}>`;\n return VOID_ELEMENTS.has(name)\n ? open\n : `${open}${inner ? insert(inner, undefined, scope) : ''}</${name}>`;\n}\n\nexport function setSlots(id: ScopeId, values: unknown[]): void {\n scopes.get(id)!.s = values;\n // A render function computes a memo that loads as a promise, which the first compute of the\n // memo takes. Its failure is the memo's to report, not an unhandled rejection.\n for (let slot = 0; slot < values.length; slot++) {\n const value = values[slot];\n // A promise that a parent passed as a prop stays a promise. A memo of the prop holds the same\n // promise in a later slot, which loads.\n if (\n value instanceof Promise &&\n scopes.get(id)!.props?.includes(value) &&\n values.indexOf(value) === slot\n ) {\n (scopes.get(id)!.plain ??= new Set()).add(slot);\n // Nothing handles its rejection unless the child reads it.\n value.catch(noop);\n } else if (isThenable(value)) {\n const key = `${id}:${slot}`;\n renderedLoads.add(key);\n loadingValues.add(value);\n // A memo that no markup reads, and no change has computed yet, takes its value from the render.\n // The key stays, so the first refresh of the memo keeps that value and does not load again.\n Promise.resolve(value).then((result) => {\n const scope = scopes.get(id);\n if (scope?.s[slot] === value && !loads.has(key)) {\n set(scope, slot, result);\n }\n }, noop);\n }\n }\n scopes.get(id)!.props = undefined;\n}\n\nexport function setItem(id: ScopeId, value: unknown): void {\n scopes.get(id)!.i = value;\n}\n\nexport function elementAt(scope: ScopeId, anchor: number): ElementReference {\n return new ElementReference(scope, anchor);\n}\n","// Writes the props of child components that the browser renders.\n\nimport { HAS_BINDINGS } from '../features.ts';\nimport { isBinding } from '../shared.ts';\nimport { loadModule } from './code.ts';\nimport { fail } from './errors.ts';\nimport { modules, scopes } from './state.ts';\nimport type { ClientModule, Scope } from './state.ts';\nimport { get, set, writeSlot } from './updates.ts';\n\n/** Writes a prop of a child component. */\n// The keys that the spreads of child components passed last, by the child's scope and anchor.\nconst spreadKeys = new WeakMap<Scope, Map<number, Set<string>>>();\n\n/**\n * Updates the props of a child component from a spread. A key that the\n * spread passed before and no longer has becomes undefined. `after` names\n * the props after the spread, which win over it.\n */\nexport function spreadProps(\n scope: Scope,\n anchor: number,\n value: Record<string, unknown> | null | undefined,\n after: string[],\n): void {\n const byAnchor = spreadKeys.get(scope) ?? new Map<number, Set<string>>();\n spreadKeys.set(scope, byAnchor);\n const before = byAnchor.get(anchor) ?? new Set();\n // The `b-` names are brumate's own, such as the handlers of a dynamic tag.\n const keys = new Set<string>();\n for (const key of Object.keys(value ?? {})) {\n if (!after.includes(key) && !key.startsWith('b-')) {\n keys.add(key);\n }\n }\n byAnchor.set(anchor, keys);\n for (const key of keys) {\n prop(scope, anchor, key, value![key]);\n }\n for (const key of before) {\n if (!keys.has(key)) {\n prop(scope, anchor, key, undefined);\n }\n }\n}\n\nexport function prop(scope: Scope, anchor: number, name: string, value: unknown): void {\n // A prop that the parent binds passes its value. The child keeps the slot it writes from its render.\n // A rest prop keeps the binding, for the element that spreads it.\n const bound = value;\n if (HAS_BINDINGS && isBinding(value)) {\n value = value.value;\n }\n const id = scope.c?.[anchor];\n const child = id === undefined ? undefined : scopes.get(id);\n if (!child?.m) {\n return;\n }\n // An arrow, to keep the narrowing of `module` and `value`.\n const apply = (module: ClientModule): void => {\n const slot = module.props[name];\n if (slot !== undefined) {\n // The parent's value. A promise stays a promise: the child awaits it, or loads it with $memo.\n if (value instanceof Promise) {\n (child.plain ??= new Set()).add(slot);\n } else {\n child.plain?.delete(slot);\n }\n // A bound prop does not write it back.\n writeSlot(child, slot, value);\n return;\n }\n const all = module.props['*'];\n if (all !== undefined) {\n set(child, all, { ...(get(child, all) as object), [name]: value });\n }\n // A rest prop, `...rest`, holds the props that the component does not name.\n const rest = module.props['...'];\n if (rest !== undefined) {\n const next: Record<string, unknown> = { ...(get(child, rest) as object) };\n if (value === undefined) {\n delete next[name];\n } else {\n next[name] = bound;\n }\n set(child, rest, next);\n }\n };\n const module = modules.get(child.m);\n if (module) {\n apply(module);\n } else {\n loadModule(child.m).then(apply, (error: unknown) => fail(child, error));\n }\n}\n","// Writes of the values that markup inserts: text, content, attributes and spreads of elements, and\n// `#portal` bodies.\n\nimport { HAS_BINDINGS, HAS_CHILDREN, HAS_DYNAMIC, HAS_TEMPLATES } from '../features.ts';\nimport { attributeText, insertValue, onValue, textValue } from '../html.ts';\nimport { isBinding, isSlotReference } from '../shared.ts';\nimport type { ScopeId } from '../shared.ts';\nimport { findComment, findElement, rangeEnd } from './blocks.ts';\nimport type { Render } from './branches.ts';\nimport { Children, RenderedChildren, TemplateCall, linkCalls } from './children.ts';\nimport { loadedFunction } from './code.ts';\nimport { spreadEntries } from './handlers.ts';\nimport { insertHTML, refreshing } from './insert.ts';\nimport { prop, spreadProps } from './props.ts';\nimport { afterInsert, disposeKinds, inPlace, nextId } from './scopes.ts';\nimport { hiding, options, scopes } from './state.ts';\nimport type { Scope } from './state.ts';\nimport { give, set } from './updates.ts';\n\n/**\n * Renders a `#portal` body into its target, between markers with its scope\n * ID. `kinds` names the body, so a new target first removes it from the old one.\n */\nexport function portalTo(\n scope: Scope,\n target: unknown,\n render: Render,\n kinds: number[] = [],\n holderKind?: number,\n holderAnchor?: number,\n): void {\n disposeKinds(scope, kinds);\n const element = typeof target === 'string' ? document.querySelector(target) : target;\n if (!(element instanceof Element)) {\n return;\n }\n // The body's scope is the first scope that the render creates.\n const id = nextId;\n const body = inPlace(scope, render, holderKind, holderAnchor)!;\n insertHTML({ parent: element }, `<!--P${id}-->${body(scope)}<!--/P-->`);\n}\n\n/** Writes an inserted value between `<!--t…-->` and `<!--/t-->`. */\nexport function text(scope: Scope, anchor: number, value: unknown): void {\n // A clone keeps the text node of the insert, or the start comment of its markers.\n let kept = scope.n?.[anchor];\n if (kept?.nodeType === 3 && kept.isConnected) {\n if (typeof value === 'string' || typeof value === 'number') {\n const data = String(value);\n if ((kept as Text).data !== data) {\n (kept as Text).data = data;\n }\n return;\n }\n // Another value needs the markers of an insert around it, which the text node gets now.\n const start = document.createComment(`t${scope.id}:${anchor}`);\n (kept as Text).before(start);\n (kept as Text).after(document.createComment('/t'));\n scope.n![anchor] = kept = start;\n }\n const start = kept?.isConnected ? (kept as Comment) : findComment(`t${scope.id}:${anchor}`);\n if (start) {\n write(start.parentNode!, start.nextSibling, rangeEnd(start), value, scope, start, anchor);\n }\n}\n\n/** Writes an inserted value that is the whole content of the element with the anchor. */\nexport function content(scope: Scope, anchor: number, value: unknown): void {\n const element = findElement(scope.id, anchor);\n if (element) {\n write(element, element.firstChild, null, value, scope, element, anchor);\n }\n}\n\n/**\n * Writes the text of an element whose content is text, such as a `<textarea>`\n * or a `<title>`. A `<textarea>` gets the value too, as `value` does on an\n * `<input>`, so a change replaces what the user typed.\n */\nexport function writeText(scope: Scope, anchor: number, value: unknown): void {\n const element = findElement(scope.id, anchor);\n if (element) {\n const written = textValue(value);\n // Each is written only when it differs, as a write of the same text still notifies observers.\n if (element.textContent !== written) {\n element.textContent = written;\n }\n if (element instanceof HTMLTextAreaElement && element.value !== written) {\n element.value = written;\n }\n }\n}\n\n/**\n * Replaces the nodes of `parent` from `first` up to `end`, or to its last\n * child, with a value. A text node that stays a text node keeps its node.\n */\nfunction write(\n parent: Node & ParentNode,\n first: ChildNode | null,\n end: Node | null,\n value: unknown,\n at?: Scope,\n key?: Node,\n anchor?: number,\n): void {\n // The same template again at an insert updates in place, with its new arguments, as a snippet\n // of Svelte does. Its elements and their focus stay.\n // The server rendered what an insert shows until its first write in the browser.\n const firstWrite = key !== undefined && !writtenInserts.has(key);\n // A refresh of markup from the server keeps the children that the server rendered at this\n // insert, so their nodes and focus stay. Their scopes refresh on their own.\n if (\n HAS_CHILDREN &&\n refreshing &&\n firstWrite &&\n value instanceof RenderedChildren &&\n value.at !== undefined &&\n value.at === at?.id &&\n value.anchor === anchor\n ) {\n return;\n }\n if (key) {\n writtenInserts.add(key);\n }\n if (HAS_TEMPLATES && key && value instanceof TemplateCall) {\n const known =\n templateInserts.get(key) ??\n (firstWrite\n ? renderedTemplate(value, at, loadedFunction(`${value.ref}k`) as unknown as number)\n : undefined);\n // The template's `a` export gives the slots of its arguments, also of destructured ones.\n const getSlots = loadedFunction(`${value.ref}a`) as\n | ((...args: unknown[]) => [number, unknown][])\n | undefined;\n if (known && getSlots && known.ref === value.ref && scopes.has(known.scope.id)) {\n templateInserts.set(key, known);\n for (const [slot, next] of getSlots(...value.args)) {\n set(known.scope, slot, next);\n }\n return;\n }\n }\n if (\n (typeof value === 'string' || typeof value === 'number') &&\n first?.nodeType === 3 &&\n first.nextSibling === end\n ) {\n // Hidden text keeps its new value for when it shows.\n const saved = hiding?.nodes.get(first);\n const data = String(value);\n if (saved) {\n saved.v = data;\n } else if ((first as Text).data !== data) {\n // The same text again changes nothing, and a write would still notify observers.\n (first as Text).data = data;\n }\n return;\n }\n while (first && first !== end) {\n const next = first.nextSibling;\n first.remove();\n first = next;\n }\n // Children and templates render here, at the scope of the insert, for its contexts. The first\n // scope that a template makes is its own, which holds its arguments.\n const made = nextId;\n linkCalls(value, at);\n insertHTML(\n end ?? { parent },\n (HAS_CHILDREN || HAS_TEMPLATES) && value instanceof Children\n ? value.render(at)\n : insertValue(value),\n );\n if (HAS_TEMPLATES && key) {\n const scope = value instanceof TemplateCall ? scopes.get(made) : undefined;\n if (scope) {\n templateInserts.set(key, { ref: (value as TemplateCall).ref, scope });\n } else {\n templateInserts.delete(key);\n }\n }\n}\n\n/** The scope of the template that each insert shows, by the node that marks the insert. */\nconst templateInserts = new WeakMap<Node, { ref: string; scope: Scope }>();\n\n/** The inserts that the browser wrote, which no longer show what the server rendered. */\nconst writtenInserts = new WeakSet<Node>();\n\n/**\n * The scope of a template that the server rendered at an insert: the scope that the template's\n * component made, and that finds its contexts from the insert.\n */\nfunction renderedTemplate(\n call: TemplateCall,\n at: Scope | undefined,\n k: number | undefined,\n): { ref: string; scope: Scope } | undefined {\n if (k === undefined) {\n return undefined;\n }\n let found: Scope | undefined;\n for (const scope of scopes.values()) {\n // The scope is of this template, not of another template of the same component.\n if (call.owner && scope.p === call.owner && scope.t === at && scope.k === k) {\n // Two templates of the same component at one insert cannot be told apart.\n if (found) {\n return undefined;\n }\n found = scope;\n }\n }\n return found && { ref: call.ref, scope: found };\n}\n\n/** The `value` and `checked` that updates last wrote to each field. */\nconst fieldValues = new WeakMap<Element, Map<string, unknown>>();\n\nfunction setAttribute(element: Element, name: string, value: unknown, spread = false): void {\n if (HAS_BINDINGS && isBinding(value)) {\n value = value.value;\n }\n // A write of the same value changes nothing on screen, yet it still costs a style check and\n // notifies observers, so each write is skipped when the element already has the value.\n if (name === 'value' || name === 'checked') {\n const field = element as unknown as Record<string, unknown>;\n const next = name === 'checked' ? Boolean(value) : String(value ?? '');\n // The field takes the value when it differs from the value that updates wrote last, not each\n // time an update runs, so what the user typed or checked stays while the value stays, such\n // as the posted values of a form that validation reads again. Before the first write, the\n // field is compared as it is now. Two first writes compare it with what the server rendered,\n // so what the user typed or checked before the code loaded stays: an update of a scope that\n // resumed late, and an update of a spread, which another of its attributes can start.\n const written = fieldValues.get(element) ?? new Map<string, unknown>();\n fieldValues.set(element, written);\n let rendered: unknown;\n if (refreshing || spread) {\n rendered = name === 'checked' ? field.defaultChecked : field.defaultValue;\n }\n const before = written.has(name) ? written.get(name) : (rendered ?? field[name]);\n written.set(name, next);\n if (!Object.is(before, next) && field[name] !== next) {\n field[name] = next;\n }\n }\n let written = attributeText(name, value);\n if (name === 'style' && element.hasAttribute('b-v')) {\n written = withVariables(element as HTMLElement, written);\n }\n if (element.getAttribute(name) === (written ?? null)) {\n return;\n }\n if (written === undefined) {\n element.removeAttribute(name);\n } else {\n element.setAttribute(name, written);\n }\n if (name === 'style') {\n hiding?.styled(element);\n }\n}\n\n/**\n * A new style for a top-level element of a component, with the style variables of the component\n * that the element has now, so a style that a spread passes on does not remove them.\n */\nfunction withVariables(element: HTMLElement, style: string | undefined): string | undefined {\n const variables: string[] = [];\n for (const property of Array.from(element.style)) {\n if (/^--s-[\\w-]+-\\d+$/.test(property)) {\n variables.push(`${property}:${element.style.getPropertyValue(property)}`);\n }\n }\n if (variables.length === 0) {\n return style;\n }\n // After the style: the variable has the live value, and a style that holds an older one loses.\n return style ? `${style};${variables.join(';')}` : variables.join(';');\n}\n\nexport function attr(scope: Scope, anchor: number, name: string, value: unknown): void {\n // A dynamic tag that names a component passes the value on as a prop.\n if (HAS_DYNAMIC && scope.c?.[anchor] !== undefined) {\n prop(scope, anchor, name, value);\n return;\n }\n const element = findElement(scope.id, anchor);\n if (element) {\n setAttribute(element, name, value);\n }\n}\n\n/** The attributes that the last update of a spread wrote, so the next one removes those it drops. */\nconst spreadNames = new WeakMap<Element, Set<string>>();\n\n/**\n * Gives the element of a spread to the signal that a `ref` in its attributes is bound to, or to\n * the setter of the binding.\n */\nfunction forwardRef(element: Element | null, values: Record<string, unknown>): void {\n const bound = values.ref;\n if (HAS_BINDINGS && element && isBinding(bound)) {\n const { target } = bound;\n if (isSlotReference(target)) {\n const owner = scopes.get(target.scope);\n if (owner) {\n set(owner, target.slot, element);\n }\n } else {\n give(target, element);\n }\n }\n}\n\n/** The element of a spread in markup that the browser renders goes to the `ref` of its attributes. */\nexport function restRef<T extends Record<string, unknown>>(\n values: T,\n scope: ScopeId,\n anchor: number,\n tag?: unknown,\n): T {\n // A tag that names a component passes `ref` on as a prop.\n if (typeof tag !== 'function') {\n afterInsert.push(() => forwardRef(findElement(scope, anchor), values));\n }\n return values;\n}\n\nexport function attrs(\n scope: Scope,\n anchor: number,\n values: Record<string, unknown>,\n own: string[] = [],\n): void {\n // A dynamic tag that names a component passes the attributes on as props.\n if (scope.c?.[anchor] !== undefined) {\n spreadProps(scope, anchor, values, []);\n return;\n }\n const element = findElement(scope.id, anchor);\n if (element) {\n // The first update in the browser takes the attributes that `b-s` names as the ones that\n // the spread wrote, so it keeps the attributes that other code set, such as an\n // `aria-controls` that a `$client` callback added. Without `b-s`, it takes the attributes\n // that are not the element's own, nor those of brumate.\n if (!spreadNames.has(element)) {\n const written = element.getAttribute('b-s');\n const known = new Set<string>();\n for (const name of written === null ? element.getAttributeNames() : written.split(' ')) {\n if (name !== '' && !own.includes(name) && !name.startsWith('b-')) {\n known.add(name);\n }\n }\n spreadNames.set(element, known);\n }\n const names = new Set<string>();\n for (const [name, value] of Object.entries(values)) {\n // Brumate writes its own `b-` attributes apart, and data cannot write them.\n if (\n name !== 'children' &&\n !/^on[A-Z]/.test(name) &&\n !name.startsWith('b-') &&\n !(name === 'ref' && isBinding(value))\n ) {\n names.add(name);\n setAttribute(element, name, value, true);\n }\n }\n for (const name of spreadNames.get(element) ?? []) {\n if (!names.has(name)) {\n setAttribute(element, name, undefined);\n }\n }\n spreadNames.set(element, names);\n updateSpreadEntries(element, values);\n forwardRef(element, values);\n }\n}\n\n/**\n * Writes the handlers and bindings of a spread into `b-on` again, as they are now. The entries of\n * a spread name their scope after `@`, and the element's own entries do not, so those stay.\n */\nfunction updateSpreadEntries(element: Element, values: Record<string, unknown>): void {\n const before = element.getAttribute('b-on') ?? '';\n const kept: string[] = [];\n for (const entry of before.split(' ')) {\n if (entry && !entry.includes('@')) {\n kept.push(entry);\n }\n }\n const own = kept.join(' ');\n const after = onValue(spreadEntries(values), own);\n if (after === before) {\n return;\n }\n if (after) {\n element.setAttribute('b-on', after);\n } else {\n element.removeAttribute('b-on');\n }\n // The loader listens to the events of the new entries, and prevents what their wrappers name.\n options.listen(element);\n}\n","// A browser render that waits for memos: at `await $memo`, in cloned markup that reads a memo\n// which never changes, and at the memos that markup reads. The boundaries count such waits, and\n// `#loading` shows its fallback until they end.\n\nimport { MemoError } from '../shared.ts';\nimport type { ScopeId } from '../shared.ts';\nimport { HAS_LOADING, HAS_ROOT_WAIT } from '../features.ts';\nimport { clear, findElement, rangeEnd, rendered } from './blocks.ts';\nimport { setSlots } from './components.ts';\nimport { fail, reportOnce } from './errors.ts';\nimport { insertHTML, markCloned, parseHTML, refresh } from './insert.ts';\nimport { attr, attrs } from './inserts.ts';\nimport { afterInsert, destroy, removeBlock, resolveScope } from './scopes.ts';\nimport { appendText, keepText, setAttr, setSpread } from './templates.ts';\nimport { loadingValues, renderedLoads, scopes, updating, waiters } from './state.ts';\nimport type { Scope } from './state.ts';\nimport { isThenable, noop, pending, writes } from './updates.ts';\n\n/** What a render function of the browser returns. */\nexport type Out = string | DocumentFragment;\n\n/** The scopes that renders made, and the work that waits for their insert. */\nexport type Work = [made: Scope[], queued: (() => void)[]];\n\n/**\n * The waits of a body that a boundary renders. `n` counts the waits that have not settled, and\n * `done` runs when it reaches 0. `f` runs for a wait that fails, in place of its count-down.\n * `w` holds the work of the body until the body enters the page.\n */\nexport interface Boundary {\n n: number;\n done?: () => void;\n f?: (error: unknown) => void;\n w?: Work;\n /** The count of writes when the body rendered, so `give` knows whether updates missed it. */\n c: number;\n /** The boundary of the render around the body, which takes its work while it holds its own. */\n o?: Boundary;\n}\n\n/** The slots of a scope whose awaits settled, until the insert that shows the scope. */\nconst settledSlots: WeakMap<Scope, number[]> = new WeakMap();\n\n/** The boundary of the render that runs, if any. */\nlet boundary: Boundary | undefined;\n\n/** The scope whose rest of a render runs after a wait, if any. */\nlet resting: Scope | undefined;\n\n/** Runs a render with `own` as the boundary that its waits count in. */\nfunction within(own: Boundary | undefined, render: () => Out): Out {\n const outer = boundary;\n boundary = own;\n try {\n return render();\n } finally {\n boundary = outer;\n }\n}\n\n/**\n * Renders `body` in a boundary of its own. Returns what it rendered, and the boundary when a wait\n * in it has not settled. That boundary holds the scopes and the `afterInsert` work of the body,\n * so the insert of anything else does not take them. `give` puts them back before the body goes\n * in, and the caller sets `done`, and `f` if it handles failures, before any wait settles.\n */\nexport function bound(body: () => Out): [Out, Boundary?] {\n const own: Boundary = { n: 0, c: writes, o: boundary };\n // The work of the render around it stays there.\n const made = rendered.length;\n const queued = afterInsert.length;\n const out = within(own, body);\n if (own.n === 0) {\n return [out];\n }\n own.w = [rendered.splice(made), afterInsert.splice(queued)];\n return [out, own];\n}\n\n/**\n * Puts back the work that a boundary held, for the insert of its body. Updates do not reach a\n * body that is not in the page, since blocks find their markers in the page. So when anything\n * was written during the hold, the updates of the body's scopes all run once it is in.\n */\nexport function give(own: Boundary): void {\n const [made, queued] = own.w ?? [[], []];\n own.w = undefined;\n // A body that goes into an outer body that is not in the page yet: the outer one holds the\n // work, and its own `give` runs the updates that either missed.\n const outer = own.o?.w;\n if (outer) {\n outer[0].push(...made);\n outer[1].push(...queued);\n return;\n }\n if (own.c === writes) {\n rendered.push(...made);\n } else {\n queued.push(() => refresh(made));\n }\n afterInsert.push(...queued);\n}\n\n/**\n * The body of a `#try` that the browser renders, in a boundary of its own that counts as one wait\n * of the boundary around it. A wait of the body that fails ends there, so a `#loading` around the\n * `#try` shows its body, and `fail` renders the `#catch` body in place of the `#try`. Outside a\n * boundary, the body fills in place.\n */\nexport function attempt(body: () => Out): DocumentFragment {\n if (!boundary) {\n return toNodes(body());\n }\n const [out, own] = bound(body);\n if (own) {\n const outer = join();\n own.done = () => {\n give(own);\n leave(outer);\n };\n own.f = () => {\n // The `#catch` body replaces the body, so its held work goes, and a later failure of the\n // body ends here.\n own.done = undefined;\n own.f = noop;\n own.w = undefined;\n leave(outer);\n };\n }\n return toNodes(out);\n}\n\n/** Counts a new wait in the boundary of the render that runs, and returns that boundary. */\nexport function join(): Boundary | undefined {\n const own = boundary;\n if (own) {\n own.n++;\n }\n return own;\n}\n\n/** True when the wait of `scope` in the range that `end` closes is gone with its block. */\nfunction gone(scope: Scope, end: Node): boolean {\n return scopes.get(scope.id) !== scope || !end.parentNode;\n}\n\n/**\n * Waits until `ready()`, then runs `run` a microtask later, outside the write that made it ready.\n * Each write of a slot, and the removal of `scope`, checks again. A scope or range that goes ends\n * the wait with `leave`. `run` gets the check, to wait again with `waiters.set(check, scope)`.\n */\nexport function until(\n own: Boundary | undefined,\n scope: Scope,\n end: Node,\n ready: () => boolean,\n run: (check: () => void) => void,\n): () => void {\n function check(): void {\n if (gone(scope, end)) {\n waiters.delete(check);\n leave(own);\n } else if (ready()) {\n waiters.delete(check);\n queueMicrotask(() => {\n if (gone(scope, end)) {\n leave(own);\n } else {\n run(check);\n }\n });\n }\n }\n waiters.set(check, scope);\n return check;\n}\n\n/** Ends a wait that `join` counted. At 0, the boundary runs `done`. */\nexport function leave(own: Boundary | undefined): void {\n if (own && --own.n === 0) {\n own.done?.();\n }\n}\n\n/** Ends a wait that failed: its boundary's `f`, or the count-down when the boundary has none. */\nexport function fault(own: Boundary | undefined, error: unknown): void {\n if (own?.f) {\n own.f(error);\n } else {\n leave(own);\n }\n}\n\n/** Ends a wait for a value that rejected: `fail`, once per error and scope, then `fault`. */\nfunction failOnce(scope: Scope, own: Boundary | undefined, error: unknown): void {\n // A closed block shows nothing, so its error has no `#catch` to show.\n if (scopes.get(scope.id) !== scope) {\n leave(own);\n return;\n }\n try {\n // `onError` of the page can throw.\n reportOnce(scope, error);\n } finally {\n fault(own, error);\n }\n}\n\n/**\n * The wait of cloned markup that reads memos which never change: `write` runs once the ones\n * that are promises settle, as no update writes their values. It counts in the boundary of the\n * render, as `wait` does. A rejection goes to `fail`, once per error and scope, then to `fault`.\n * A scope that goes during the wait ends it with `leave`.\n */\nexport function fillSettled(\n id: ScopeId | Scope,\n values: unknown[],\n write: (...values: unknown[]) => void,\n): void {\n let promised = false;\n for (const value of values) {\n promised ||= isThenable(value);\n }\n if (!promised) {\n write(...values);\n return;\n }\n const scope = resolveScope(id)!;\n const own = join();\n Promise.all(values).then(\n (settled) => {\n try {\n // A closed block removed the nodes.\n if (scopes.get(scope.id) === scope) {\n write(...settled);\n }\n } finally {\n leave(own);\n }\n },\n (error: unknown) => failOnce(scope, own, error),\n );\n}\n\n/**\n * A value of markup that the browser writes, in text or an attribute, which can be a promise.\n * A value that is not one is written at once. A promise counts in the boundary of the render, as\n * a memo of `fillSettled` does, and `write` gets its value once it settles. The scope keeps the\n * latest value of each place, by `key`, so a promise that an update replaced before it settled\n * writes nothing: the latest wins.\n */\nexport function fillValue(\n id: ScopeId | Scope,\n key: number | string,\n value: unknown,\n write: (value: unknown) => void,\n): void {\n const scope = resolveScope(id)!;\n if (!isThenable(value)) {\n if (scope.q) {\n scope.q[key] = value;\n }\n write(value);\n return;\n }\n const latest = (scope.q ??= {});\n latest[key] = value;\n fillSettled(scope, [value], (settled) => {\n if (latest[key] === value) {\n write(settled);\n }\n });\n}\n\n/**\n * A text insert of cloned markup whose value can be a promise, as `keepText` writes it, or as\n * `appendText` does at the end of the element when `append` is set. A promise leaves an empty\n * text node, which the scope keeps, so an update finds it, and its value takes the place of that\n * node once it settles, in or out of the page.\n */\nexport function keepValue(\n id: ScopeId,\n anchor: number,\n place: Comment | Element,\n value: unknown,\n at: ScopeId | Scope = id,\n append?: boolean,\n): void {\n const promised = isThenable(value);\n if (append) {\n appendText(id, anchor, place as Element, promised ? '' : value, at);\n } else {\n keepText(id, anchor, place as Comment, promised ? '' : value, at);\n }\n if (promised) {\n fillValue(id, anchor, value, (settled) => {\n const comment = document.createComment('');\n (resolveScope(id)!.n![anchor] as ChildNode).replaceWith(comment);\n keepText(id, anchor, comment, settled, at);\n });\n }\n}\n\n/**\n * The update of the spreads of an element whose values can be promises, as `attrs` writes them.\n * An attribute whose value is a promise keeps what it shows until the promise settles.\n */\nexport function fillAttrs(\n scope: Scope,\n anchor: number,\n values: Record<string, unknown>,\n own?: string[],\n): void {\n const now: Record<string, unknown> = {};\n for (const [name, value] of Object.entries(values)) {\n const key = `${anchor} ${name}`;\n if (isThenable(value)) {\n now[name] = findElement(scope.id, anchor)?.getAttribute(name) ?? undefined;\n fillValue(scope, key, value, (settled) => attr(scope, anchor, name, settled));\n } else {\n fillValue(scope, key, value, (settled) => {\n now[name] = settled;\n });\n }\n }\n attrs(scope, anchor, now, own);\n}\n\n/**\n * The spreads of an element of cloned markup whose values can be promises, as `setSpread` writes\n * them. An attribute whose value is a promise is written once it settles. `place` names the\n * element among the places of the scope: its anchor, which the update of the spread uses too.\n */\nexport function fillSpread(\n id: ScopeId,\n place: number | string,\n element: Element,\n attributes: Record<string, unknown>,\n on?: string[],\n names?: boolean,\n): void {\n setSpread(element, attributes, on, names);\n for (const [name, value] of Object.entries(attributes)) {\n if (isThenable(value)) {\n fillValue(id, `${place} ${name}`, value, (settled) => setAttr(element, name, settled));\n }\n }\n}\n\n/**\n * Renders the rest of a wait in its boundary and puts it before `end`. In a boundary whose body\n * is not in the page yet, the scopes and work of the rest join the body's. A throw drops them.\n */\nexport function fillRange(own: Boundary | undefined, end: Node, rest: () => Out): void {\n const made = rendered.length;\n const queued = afterInsert.length;\n let out: Out;\n try {\n out = within(own, rest);\n } catch (error) {\n rendered.length = made;\n afterInsert.length = queued;\n throw error;\n }\n if (own?.w) {\n own.w[0].push(...rendered.splice(made));\n own.w[1].push(...afterInsert.splice(queued));\n }\n insertHTML(end, out);\n}\n\n/**\n * The rest of a render after `const x = await $memo(...)`. `slots` are the slots that the code\n * before the `await` set, with the value of the memo at `slot`, and `rest` gets them back.\n *\n * A value goes on at once, in the same render. A promise leaves a range of two comments, and\n * the scope holds `slots` while it waits, so a parent can write its props. The rest renders when\n * the slot holds a value: the first load's, or a newer load's that a prop started, whichever\n * settles as the latest. Its markup fills the range. A rejection, or a throw of `rest`, goes to\n * `fail`. A scope that goes during the wait ends it, and its boundary counts down.\n */\nexport function wait(\n id: ScopeId,\n slots: unknown[],\n slot: number,\n // oxlint-disable-next-line typescript/no-explicit-any -- The rest assigns the slots by name.\n rest: (slots: any[]) => Out,\n): Out {\n const scope = resolveScope(id)!;\n // A load that an update started during an earlier wait of the scope is newer than one that\n // started before the `await`.\n if (scope.s[slot] !== undefined) {\n slots[slot] = scope.s[slot];\n }\n const first = slots[slot];\n if (!isThenable(first)) {\n return rest(slots);\n }\n const promise = Promise.resolve(first);\n // The setup of the slots that the code before the `await` set, such as a promise prop or an\n // async memo, whose rejection the memo reports. The slot of the memo is this wait's.\n // The props stay for the rest's own `setSlots`, which keeps a promise prop a plain promise.\n slots[slot] = undefined;\n const props = scope.props;\n setSlots(id, slots);\n scope.props = props;\n scope.s[slot] = promise;\n // Update code that runs during the wait reads the promise, as it reads a memo that loads.\n loadingValues.add(promise);\n // The scope is not in the page until the rest runs, so the insert around it does not run its\n // memos.\n const at = rendered.indexOf(scope);\n if (at !== -1) {\n rendered.splice(at, 1);\n }\n // `l` and the scope ID match `MARKER`, so a block that closes removes the whole range. Client\n // scope IDs are negative, so no other reader of `l` comments matches it. The range of an item\n // of a list that waits in its own script, outside an earlier range of it, marks the item.\n const item = 'i' in scope && resting !== scope;\n const start = document.createComment(item ? `i${scope.id}` : `l${scope.id}:w`);\n const end = document.createComment(item ? '/i' : '/w');\n const range = document.createDocumentFragment();\n range.append(start, end);\n const own = join();\n function settle(check: () => void): void {\n if (pending(scope, slot)) {\n waiters.set(check, scope);\n return;\n }\n const value = scope.s[slot];\n if (value instanceof MemoError) {\n fail(scope, value.error);\n fault(own, value.error);\n return;\n }\n // A rest that waits again at a later `await` takes the scope out of the insert.\n let shown = false;\n try {\n fillRange(own, end, () => {\n // The scope goes with the markup of the rest.\n rendered.push(scope);\n const outer = resting;\n resting = scope;\n try {\n // The rest renders as an update does: it reads a memo that still loads as a promise.\n const out = updating(() => rest(scope.s));\n shown = rendered.includes(scope);\n return out;\n } finally {\n resting = outer;\n }\n });\n } catch (error) {\n fail(scope, error);\n fault(own, error);\n return;\n }\n // The memos have their values, so the refresh after the insert that shows the scope does\n // not load them again.\n const done = settledSlots.get(scope) ?? [];\n done.push(slot);\n settledSlots.set(scope, done);\n if (shown) {\n settledSlots.delete(scope);\n for (const settled of done) {\n if (settled < scope.s.length) {\n renderedLoads.add(`${scope.id}:${settled}`);\n }\n }\n }\n leave(own);\n }\n const check = until(own, scope, end, () => !pending(scope, slot), settle);\n function write(value: unknown): void {\n // A newer load wrote the slot already.\n if (scope.s[slot] === promise) {\n scope.s[slot] = value;\n }\n if (waiters.has(check)) {\n check();\n }\n }\n promise.then(write, (error: unknown) => write(new MemoError(error)));\n return range;\n}\n\n/**\n * Starts the load of an awaited memo before its `await`, where its inputs are ready. A throw\n * becomes a rejected promise, and a rejection is handled here, so neither surfaces before the\n * `await` waits for the load, which gets the same rejection.\n */\nexport function started(load: () => unknown): unknown {\n let value: unknown;\n try {\n value = load();\n } catch (error) {\n value = Promise.reject(error);\n }\n if (isThenable(value)) {\n value.then(undefined, noop);\n }\n return value;\n}\n\n/**\n * Starts the load of an awaited memo that reads other awaited memos once their loads settle.\n * `load` gets their values. A rejection of theirs rejects it too.\n */\n// oxlint-disable-next-line typescript/no-explicit-any -- The load names the values.\nexport function after(loads: unknown[], load: (...values: any[]) => unknown): unknown {\n return started(() => Promise.all(loads).then((values) => load(...values)));\n}\n\n/**\n * Gives back the work of a held body for its insert, and returns true. A body that went stale,\n * whose block left the page or whose scopes went, drops its scopes instead.\n */\nfunction take(own: Boundary, at: Node, stale?: boolean): boolean {\n let gone = stale || !at.isConnected;\n for (const scope of own.w?.[0] ?? []) {\n gone ||= scopes.get(scope.id) !== scope;\n }\n if (gone) {\n own.done = undefined;\n for (const scope of own.w?.[0] ?? []) {\n destroy(scope);\n }\n own.w = undefined;\n return false;\n }\n give(own);\n // The body can hold HTML that the insert reads, as a clone that a render made.\n markCloned();\n return true;\n}\n\n/**\n * The new body that a block holds: the key that the block renders it for, its boundary, and\n * true once the block went back to what it shows.\n */\ntype Held = [key: unknown, own: Boundary, stale?: boolean];\n\n/** The held body of each block, by the start comment of the block. */\nconst holds = new WeakMap<Node, Held>();\n\n/** Drops the body that the block at `at` holds, if any. */\nfunction drop(at: Node): void {\n const held = holds.get(at);\n if (held) {\n holds.delete(at);\n take(held[1], at, true);\n }\n}\n\n/**\n * The root boundary. The server holds the page outside every `#loading` until its waits end,\n * so a block there keeps what it shows until the waits of its new body end. `render` renders\n * the body for `key` in a boundary, and `show` puts it in place of the old one: at once when\n * nothing waits, otherwise when the waits end. A block that asks again for the key that it\n * holds keeps waiting, and another key drops the held body.\n */\nexport function hold(at: Node, key: unknown, render: () => Out, show: (out: Out) => void): void {\n const held = holds.get(at);\n if (held && Object.is(held[0], key)) {\n held[2] = false;\n return;\n }\n drop(at);\n const [out, own] = bound(render);\n if (!own) {\n show(out);\n return;\n }\n const entry: Held = [key, own];\n holds.set(at, entry);\n own.done = () => {\n holds.delete(at);\n if (take(own, at, entry[2])) {\n show(out);\n }\n };\n}\n\n/**\n * Renders a new body of a block in the root boundary, and puts it in place of the old body when\n * its waits end. The new body renders before the old one goes, so the script of a new body runs\n * before the cleanups of the old one, and its effects after them.\n */\nexport function swap(\n scope: Scope,\n kinds: number[],\n start: Comment,\n key: unknown,\n render: () => Out,\n mark?: () => void,\n): void {\n // The scopes that the render of the new body adds. Those of the old body, also the ones that\n // it adds during the hold, go when the new body shows. Both have the same kinds.\n const made: Scope[] = [];\n function renderNew(): Out {\n const old = new Set(scope.children);\n const out = render();\n for (const child of scope.children ?? []) {\n if (!old.has(child)) {\n made.push(child);\n }\n }\n return out;\n }\n hold(start, key, renderNew, (out) => {\n for (const child of Array.from(scope.children ?? [])) {\n if (kinds.includes(child.k) && !made.includes(child)) {\n destroy(child);\n }\n }\n const end = rangeEnd(start);\n removeBlock(scope, [], start, end);\n mark?.();\n insertHTML(end, out);\n });\n}\n\n/**\n * The block at `at` went back to what it shows. Its held body goes when it settles, unless the\n * block asks for it again before, which then does not render and load it again.\n */\nexport function release(at: Node): void {\n const held = holds.get(at);\n if (held) {\n held[2] = true;\n }\n}\n\n/**\n * A new row of a list outside every `#loading`, which shows when its waits end. A row that waits\n * leaves an empty item marker in its place, so the next update of the list finds it and does\n * not render it again.\n */\nexport function holdRow(list: Scope, render: () => Out): Out {\n const [out, own] = bound(render);\n if (!own) {\n return out;\n }\n let row: Scope | undefined;\n for (const scope of own.w![0]) {\n if (scope.p === list) {\n row ??= scope;\n }\n }\n // A row that waits in its own script is out of `rendered` until its rest runs, and the range of\n // its wait, which `out` starts with, names it.\n const first = typeof out === 'string' ? undefined : out.firstChild;\n let mark = `i${(row ?? own.w![0][0])?.id}`;\n if (!row && first?.nodeType === 8 && (first as Comment).data[0] === 'i') {\n mark = (first as Comment).data;\n }\n const start = document.createComment(mark);\n const end = document.createComment('/i');\n const range = document.createDocumentFragment();\n range.append(start, end);\n own.done = () => {\n if (take(own, end)) {\n insertHTML(end, out);\n }\n };\n return range;\n}\n\n/**\n * Counts the memos that markup of a browser render reads and that still load, in the boundary of\n * the render, as the server waits for them. The compiler passes the memos of a scope that markup\n * outside every `#loading` body reads, and the memos that a `#loading` body reads from outside.\n * Each counts down when its value settles. A rejection goes to `fail` and `fault`, as in\n * `fillSettled`. Outside a boundary, the markup fills in when the values arrive.\n */\nexport function countLoads(id: ScopeId | Scope, values: unknown[]): void {\n if (!(HAS_LOADING || HAS_ROOT_WAIT) || !boundary) {\n return;\n }\n for (const value of values) {\n if (isThenable(value)) {\n const scope = resolveScope(id)!;\n const own = join();\n Promise.resolve(value).then(\n () => leave(own),\n (error: unknown) => failOnce(scope, own, error),\n );\n }\n }\n}\n\n/** The order of a `#reveal` block. */\ntype RevealOrder = 'sequential' | 'backwards' | 'together' | 'natural';\n\n/** A `#loading` block of a `#reveal` block that the browser renders. */\ninterface Member {\n /** Shows the body, once the body is ready. */\n s?: () => void;\n /** True once the body showed. */\n d?: boolean;\n /** Shows the fallback that `collapsed` held back. */\n f?: () => void;\n}\n\n/**\n * The `#loading` blocks of a `#reveal` block that the browser renders, in the order of the\n * markup, as the server orders the bodies that stream. One group is one chain of bodies.\n */\nexport interface Reveal {\n o: RevealOrder;\n c: boolean;\n m: Member[];\n /** True once the render of the block ended, so the group knows its last body. */\n e?: boolean;\n /** Shows the bodies that are ready and whose turn it is. A page without `#reveal` has no code for it. */\n t: () => void;\n}\n\n/** The `#reveal` block whose body renders, which the `#loading` blocks of the render join. */\nlet revealing: Reveal | undefined;\n\n/**\n * A `#reveal` block in a browser render: the `#loading` blocks that its body renders, also in\n * the components inside it, join one group, as on the server. The group ends with the render,\n * before any body settles, so a block that a later update adds there is not ordered.\n */\nexport function reveal(order: RevealOrder, collapsed: boolean, body: () => Out): DocumentFragment {\n const group: Reveal = { o: order, c: collapsed, m: [], t: () => showTurns(group) };\n queueMicrotask(() => {\n group.e = true;\n group.t();\n });\n const outer = revealing;\n revealing = group;\n try {\n return toNodes(body());\n } finally {\n revealing = outer;\n }\n}\n\n/** Shows the bodies of a `#reveal` block that are ready and whose turn it is. */\nfunction showTurns(group: Reveal): void {\n const { m: members, o: order } = group;\n function showAt(index: number): void {\n const member = members[index]!;\n member.d = true;\n member.s!();\n // `collapsed`: the body that shows brings the fallback of the next one in.\n members[index + 1]?.f?.();\n }\n if (order === 'natural') {\n for (const [index, member] of members.entries()) {\n if (member.s && !member.d) {\n showAt(index);\n }\n }\n } else if (order === 'sequential') {\n for (let index = 0; index < members.length && members[index]!.s; index++) {\n if (!members[index]!.d) {\n showAt(index);\n }\n }\n } else if (group.e && order === 'backwards') {\n for (let index = members.length - 1; index >= 0 && members[index]!.s; index--) {\n if (!members[index]!.d) {\n showAt(index);\n }\n }\n } else if (group.e) {\n // `together`: every body must be ready before any shows.\n let ready = true;\n for (const member of members) {\n ready &&= member.s !== undefined;\n }\n for (const [index, member] of members.entries()) {\n if (ready && !member.d) {\n showAt(index);\n }\n }\n }\n}\n\n/** What a body or a fallback rendered, as nodes. HTML holds clones that it parses back in. */\nfunction toNodes(out: Out): DocumentFragment {\n if (typeof out !== 'string') {\n return out;\n }\n markCloned();\n return parseHTML(out);\n}\n\n/**\n * A `#loading` block that the browser renders, as a streamed one shows: the body at once when\n * nothing that it reads loads, and otherwise the fallback, until every wait of the body ends.\n * The body renders now, in a boundary of its own, and enters the page in one insert with its\n * work. A body whose wait fails keeps the fallback, and `fail` reported the error. The `#reveal`\n * block around it can hold a body that is ready for its turn. Updates after that keep the\n * content, since they render no boundary.\n */\nexport function loading(body: () => Out, fallback?: () => Out): DocumentFragment {\n const group = revealing;\n // A `#reveal` inside the body or the fallback orders only its own blocks, as on the server.\n revealing = undefined;\n try {\n return renderLoading(group, body, fallback);\n } finally {\n revealing = group;\n }\n}\n\n/** `loading` with the `#reveal` group of the render, and none for its own body and fallback. */\nfunction renderLoading(\n group: Reveal | undefined,\n body: () => Out,\n fallback?: () => Out,\n): DocumentFragment {\n const made = rendered.length;\n const queued = afterInsert.length;\n // A body that is ready shows at once, unless the `#reveal` around it holds it for its turn.\n const turn =\n group && !(group.o === 'natural' || (group.o === 'sequential' && group.m.length === 0));\n const result = bound(body);\n const nodes = toNodes(result[0]);\n let own = result[1];\n if (!own) {\n if (!turn) {\n return nodes;\n }\n // Held for its turn: its scopes and work wait, as those of a body that waits do.\n own = { n: 0, c: writes, o: boundary, w: [rendered.splice(made), afterInsert.splice(queued)] };\n }\n const held = own;\n // The range that the fallback fills, and then the body. Its comments name no block.\n const start = document.createComment('');\n const end = document.createComment('');\n const range = document.createDocumentFragment();\n // The scopes that the fallback made, which go when the body shows.\n let fallbackScopes: Scope[] = [];\n function showFallback(): DocumentFragment {\n const first = rendered.length;\n const fallbackNodes = fallback ? toNodes(fallback()) : document.createDocumentFragment();\n fallbackScopes = rendered.slice(first);\n return fallbackNodes;\n }\n const member: Member = {};\n // `#reveal (collapsed)` holds the fallback until the body before it shows.\n const hidden = group?.c && group.m.length > 0;\n range.append(start);\n if (!hidden) {\n range.append(showFallback());\n }\n range.append(end);\n if (hidden) {\n member.f = () => {\n if (end.parentNode) {\n insertHTML(end, showFallback());\n }\n };\n }\n function showBody(): void {\n // A block that closed during the wait dropped the body and its scopes.\n let dropped = !end.parentNode;\n for (const scope of held.w?.[0] ?? []) {\n dropped ||= scopes.get(scope.id) !== scope;\n }\n if (dropped) {\n held.w = undefined;\n return;\n }\n for (const scope of fallbackScopes) {\n destroy(scope);\n }\n clear(start, end);\n give(held);\n // The body can hold HTML that the insert reads, as a clone that a render made.\n markCloned();\n insertHTML(end, nodes);\n }\n if (group) {\n group.m.push(member);\n }\n held.done = () => {\n if (group) {\n member.s = showBody;\n group.t();\n } else {\n showBody();\n }\n };\n held.f = () => {\n // The fallback stays, as on the server, and the scopes of the body go. A body that fails\n // takes its turn, so the bodies after it still show.\n held.done = undefined;\n held.f = noop;\n for (const scope of held.w?.[0] ?? []) {\n destroy(scope);\n }\n held.w = undefined;\n if (group) {\n member.s = noop;\n group.t();\n }\n };\n if (held.n === 0) {\n held.done();\n }\n return range;\n}\n","// Blocks that show one body of several: `#if`, `#switch`, `#key`, a dynamic tag, `#try`, `#client`\n// and `#offscreen`.\n\nimport { HAS_ROOT_WAIT } from '../features.ts';\nimport { parseId } from '../shared.ts';\nimport type { ComponentValue } from '../shared.ts';\nimport { blockStart, rangeEnd } from './blocks.ts';\nimport { loadModule } from './code.ts';\nimport { insertHTML } from './insert.ts';\nimport { call } from './references.ts';\nimport { afterInsert, disposeKinds, inPlace, removeBlock, findRoot } from './scopes.ts';\nimport { comments, hiding, scopes, setHiding } from './state.ts';\nimport type { Scope } from './state.ts';\nimport { hold, release, swap } from './waits.ts';\n\nexport type Render = (parent: Scope, item?: unknown, index?: number) => string | DocumentFragment;\n\n/** Shows the branch at `index` of `#if` or `#switch`, or nothing for -1. */\nexport function branch(\n scope: Scope,\n anchor: number,\n index: number,\n renders: (Render | undefined)[],\n kinds: number[],\n holderKind?: number,\n holderAnchor?: number,\n): void {\n const start = blockStart(scope, anchor);\n if (!start) {\n return;\n }\n if (Number(start.data.split(':')[2]) === index) {\n if (HAS_ROOT_WAIT) {\n release(start);\n }\n return;\n }\n if (HAS_ROOT_WAIT) {\n const body = inPlace(scope, renders[index], holderKind, holderAnchor);\n swap(\n scope,\n kinds,\n start,\n index,\n () => (body ? body(scope) : ''),\n () => {\n start.data = `b${scope.id}:${anchor}:${index}`;\n },\n );\n return;\n }\n const end = rangeEnd(start);\n removeBlock(scope, kinds, start, end);\n start.data = `b${scope.id}:${anchor}:${index}`;\n const render = inPlace(scope, renders[index], holderKind, holderAnchor);\n if (render) {\n insertHTML(end, render(scope));\n }\n}\n\n/** Renders the body of `#key` again when its value changes. */\nexport function rekey(\n scope: Scope,\n anchor: number,\n value: unknown,\n render: Render,\n kinds: number[],\n holderKind?: number,\n holderAnchor?: number,\n): void {\n scope.keys ??= new Map();\n if (scope.keys.has(anchor) && Object.is(scope.keys.get(anchor), value)) {\n const start = HAS_ROOT_WAIT && blockStart(scope, anchor);\n if (start) {\n release(start);\n }\n return;\n }\n if (HAS_ROOT_WAIT) {\n const start = blockStart(scope, anchor);\n const keys = scope.keys;\n if (!start) {\n keys.set(anchor, value);\n return;\n }\n const body = inPlace(scope, render, holderKind, holderAnchor)!;\n swap(\n scope,\n kinds,\n start,\n value,\n () => body(scope),\n () => keys.set(anchor, value),\n );\n return;\n }\n scope.keys.set(anchor, value);\n const start = blockStart(scope, anchor);\n if (!start) {\n return;\n }\n const end = rangeEnd(start);\n removeBlock(scope, kinds, start, end);\n insertHTML(end, inPlace(scope, render, holderKind, holderAnchor)!(scope));\n}\n\n/**\n * `rekey` for the block around a dynamic tag. The first update keeps the element that the server\n * rendered, when it has the tag already, such as an update of a scope that streams in after an\n * event.\n */\nexport function retag(\n scope: Scope,\n anchor: number,\n value: unknown,\n render: Render,\n kinds: number[],\n holderKind?: number,\n holderAnchor?: number,\n): void {\n scope.keys ??= new Map();\n if (!scope.keys.has(anchor) && typeof value === 'string') {\n const start = blockStart(scope, anchor);\n let node = start?.nextSibling;\n while (node && node.nodeType !== 1 && node.nodeType !== 8) {\n node = node.nextSibling;\n }\n if (node?.nodeType === 1 && (node as Element).localName === value.toLowerCase()) {\n scope.keys.set(anchor, value);\n return;\n }\n }\n // A component in the tag: the first update keeps it when the block holds the same component.\n if (!scope.keys.has(anchor) && typeof value === 'function') {\n for (const block of scopes.values()) {\n if (block.p === scope && kinds.includes(block.k)) {\n for (const id of Object.values(block.c ?? {})) {\n if (scopes.get(id)?.m === (value as ComponentValue).brumateId) {\n scope.keys.set(anchor, value);\n return;\n }\n }\n }\n }\n }\n rekey(scope, anchor, value, render, kinds, holderKind, holderAnchor);\n}\n\n/**\n * Renders the body of a `#try` block again, for its `reset` function. If the\n * body throws, the fallback renders again with the error.\n */\nexport async function reset(\n scope: Scope,\n anchor: number,\n id: string,\n body: string,\n fallback: string,\n kinds: number[],\n holderKind?: number,\n holderAnchor?: number,\n): Promise<void> {\n const updates = (await loadModule(id)) as unknown as Record<string, unknown>;\n const start = blockStart(scope, anchor);\n if (!start) {\n return;\n }\n const end = rangeEnd(start);\n removeBlock(scope, kinds, start, end);\n let html: string | DocumentFragment;\n try {\n html = inPlace(scope, updates[body] as Render, holderKind, holderAnchor)!(scope);\n } catch (error) {\n // Scopes that the body created before it threw.\n disposeKinds(scope, kinds);\n afterInsert.length = 0;\n const render = inPlace(scope, updates[fallback] as Render, holderKind, holderAnchor)!;\n html = (render as unknown as (parent: Scope, error: unknown) => string)(scope, error);\n }\n insertHTML(end, html);\n}\n\n/**\n * Renders the body of a `#client` block once, in place of its fallback.\n * `kinds` are the scope IDs inside the fallback, whose instances go.\n */\nexport function fill(\n scope: Scope,\n anchor: number,\n render: Render,\n kinds: number[] = [],\n holderKind?: number,\n holderAnchor?: number,\n): void {\n const start = blockStart(scope, anchor);\n // A block that rendered its body has a third number.\n if (!start || start.data.split(':').length > 2) {\n return;\n }\n if (HAS_ROOT_WAIT) {\n const body = inPlace(scope, render, holderKind, holderAnchor)!;\n // The fallback stays until the body is ready.\n hold(\n start,\n 1,\n () => body(scope),\n (out) => {\n start.data += ':1';\n const end = rangeEnd(start);\n removeBlock(scope, kinds, start, end);\n insertHTML(end, out);\n },\n );\n return;\n }\n start.data += ':1';\n const end = rangeEnd(start);\n removeBlock(scope, kinds, start, end);\n insertHTML(end, inPlace(scope, render, holderKind, holderAnchor)!(scope));\n}\n\n/**\n * Shows or hides the body of an `#offscreen` block. A body that the page\n * does not have yet renders the first time it shows. `kind` is the body's\n * scope ID in the compiled component.\n */\nexport function offscreen(\n scope: Scope,\n anchor: number,\n value: unknown,\n render: Render,\n kind: number,\n holderKind?: number,\n holderAnchor?: number,\n): void {\n const start = blockStart(scope, anchor);\n if (!start) {\n return;\n }\n const visible = Boolean(value);\n // 1 for a body that shows, 0 for one that is hidden, and -1 for one that has not rendered.\n const state = start.data.split(':')[2];\n if (visible ? state === '1' : state !== '1') {\n return;\n }\n start.data = `b${scope.id}:${anchor}:${visible ? 1 : 0}`;\n const end = rangeEnd(start);\n if (state === '-1') {\n if (HAS_ROOT_WAIT) {\n const body = inPlace(scope, render, holderKind, holderAnchor)!;\n hold(\n start,\n 1,\n () => body(scope),\n (out) => insertHTML(end, out),\n );\n return;\n }\n insertHTML(end, inPlace(scope, render, holderKind, holderAnchor)!(scope));\n return;\n }\n let body: Scope | undefined;\n for (const child of scope.children ?? []) {\n if (child.k === kind) {\n body = child;\n }\n }\n if (body) {\n const holder = hiding ?? setHiding(createHiding())!;\n if (visible) {\n holder.show(body);\n } else {\n holder.hide(body, start, end);\n }\n }\n}\n\n/** The ranges of the fallbacks that `#loading (memo)` blocks show, by the start of the body. */\nconst fallbacks: WeakMap<Comment, [Comment, Comment]> = new WeakMap();\n\n/**\n * Hides the body of a `#loading (memo)` block that has shown, and shows its fallback after it,\n * while a memo of the header loads, then shows the body again. The body stays in the page and\n * follows the `#offscreen` rules. A body that has not shown yet has no markers in the page, so\n * its boundary shows the fallback. `kind` is the body's scope ID in the compiled component, and\n * `kinds` are the scope IDs inside the fallback, whose instances go with it.\n */\nexport function held(\n scope: Scope,\n anchor: number,\n pending: boolean,\n kind: number,\n render: Render | undefined,\n kinds: number[],\n holderKind?: number,\n holderAnchor?: number,\n): void {\n const start = blockStart(scope, anchor);\n // 1 for a body that shows, 0 for one that is held.\n if (!start || (start.data.split(':')[2] === '0') === pending) {\n return;\n }\n start.data = `b${scope.id}:${anchor}:${pending ? 0 : 1}`;\n const end = rangeEnd(start);\n let body: Scope | undefined;\n for (const child of scope.children ?? []) {\n if (child.k === kind) {\n body = child;\n }\n }\n const holder = hiding ?? setHiding(createHiding())!;\n if (pending) {\n // Comments that name no block, so the range of a block around it still ends at its marker.\n const range: [Comment, Comment] = [document.createComment(''), document.createComment('')];\n end.after(...range);\n fallbacks.set(start, range);\n if (body) {\n holder.hide(body, start, end);\n }\n if (render) {\n insertHTML(range[1], inPlace(scope, render, holderKind, holderAnchor)!(scope));\n }\n return;\n }\n const range = fallbacks.get(start);\n if (range) {\n fallbacks.delete(start);\n removeBlock(scope, kinds, range[0], range[1]);\n range[0].remove();\n range[1].remove();\n }\n if (body) {\n holder.show(body);\n }\n}\n\n/** A hidden `#offscreen` body: its scope, and the ranges of its markup and of its portals. */\nexport interface HiddenBody {\n scope: Scope;\n ranges: [start: Comment, end: Comment][];\n}\n\n/**\n * What a hidden node had before it was hidden: `n` hidden bodies that hide\n * it, and the text of a text node, or the inline `display` of an element\n * with its priority and whether it had a `style` attribute.\n */\ninterface Saved {\n n: number;\n v: string;\n p?: string;\n a?: boolean;\n}\n\nexport interface Hiding {\n bodies: Set<HiddenBody>;\n nodes: WeakMap<Node, Saved>;\n hide: (body: Scope, start: Comment, end: Comment) => void;\n show: (body: Scope) => void;\n /** True for a scope in a hidden body. */\n hidden: (scope: Scope) => boolean;\n /** Keeps an effect for when its body shows, and returns true, if its scope is hidden. */\n paused: (scope: Scope, name: string) => boolean;\n /** Hides the nodes that an insert added to hidden markup. */\n added: (nodes: Node[]) => void;\n /** Keeps an element hidden after its `style` attribute changed. */\n styled: (element: Element) => void;\n}\n\n/** True for a scope that is `ancestor` or inside it, also through the owner of a component. */\nfunction within(scope: Scope, ancestor: Scope): boolean {\n for (let current: Scope | undefined = scope; current; current = current.p ?? current.o) {\n if (current === ancestor) {\n return true;\n }\n }\n return false;\n}\n\n/** True for a scope in a hidden `#offscreen` body. */\nfunction hidden(scope: Scope): boolean {\n for (let current: Scope | undefined = scope; current; current = current.p ?? current.o) {\n if (current.h) {\n return true;\n }\n }\n return false;\n}\n\n/** The nodes between two markers. */\nfunction between([start, end]: [Comment, Comment]): Node[] {\n const result: Node[] = [];\n for (let node = start.nextSibling; node && node !== end; node = node.nextSibling) {\n result.push(node);\n }\n return result;\n}\n\n/** The inline style of an element, which an element that is not HTML or SVG may not have. */\nfunction display(element: Element): CSSStyleDeclaration | undefined {\n return (element as HTMLElement).style;\n}\n\nfunction createHiding(): Hiding {\n const bodies = new Set<HiddenBody>();\n const nodes = new WeakMap<Node, Saved>();\n function hideNode(node: Node): void {\n const saved = nodes.get(node);\n if (saved) {\n saved.n++;\n return;\n }\n if (node.nodeType === 3) {\n nodes.set(node, { n: 1, v: (node as Text).data });\n (node as Text).data = '';\n return;\n }\n const style = node.nodeType === 1 ? display(node as Element) : undefined;\n if (style) {\n nodes.set(node, {\n n: 1,\n v: style.getPropertyValue('display'),\n p: style.getPropertyPriority('display'),\n a: (node as Element).hasAttribute('style'),\n });\n style.setProperty('display', 'none', 'important');\n }\n }\n function showNode(node: Node): void {\n const saved = nodes.get(node);\n if (!saved || --saved.n > 0) {\n return;\n }\n nodes.delete(node);\n if (node.nodeType === 3) {\n (node as Text).data = saved.v;\n return;\n }\n const element = node as Element;\n const style = display(element)!;\n if (saved.v) {\n style.setProperty('display', saved.v, saved.p);\n } else {\n style.removeProperty('display');\n }\n if (!saved.a && element.getAttribute('style') === '') {\n element.removeAttribute('style');\n }\n }\n return {\n bodies,\n nodes,\n hidden,\n hide(body, start, end) {\n const record: HiddenBody = { scope: body, ranges: [[start, end]] };\n body.h = record;\n bodies.add(record);\n const inside: Scope[] = [];\n for (const scope of scopes.values()) {\n if (within(scope, body)) {\n inside.push(scope);\n }\n }\n for (const scope of inside) {\n // The content of a `#portal` in the body, elsewhere in the page.\n const portal = comments.get(`P${scope.id}`);\n if (portal?.isConnected) {\n record.ranges.push([portal, rangeEnd(portal)]);\n }\n }\n for (const range of record.ranges) {\n for (const node of between(range)) {\n hideNode(node);\n }\n }\n // Effects and `$client` callbacks that ran stop, and run again when the body shows.\n for (const scope of inside) {\n for (const [name, cleanup] of scope.cleanups ?? []) {\n cleanup();\n (scope.w ??= new Set()).add(name);\n }\n scope.cleanups?.clear();\n }\n },\n show(body) {\n const record = body.h;\n if (!record) {\n return;\n }\n body.h = undefined;\n bodies.delete(record);\n for (const range of record.ranges) {\n if (range[0].isConnected) {\n for (const node of between(range)) {\n showNode(node);\n }\n }\n }\n for (const scope of scopes.values()) {\n if (scope.w && within(scope, body) && !hidden(scope)) {\n const ref = `${findRoot(scope).m}#`;\n for (const name of scope.w) {\n void call(ref + name, scope, []);\n }\n scope.w = undefined;\n }\n }\n },\n paused(scope, name) {\n if (bodies.size === 0 || !hidden(scope)) {\n return false;\n }\n (scope.w ??= new Set()).add(name);\n return true;\n },\n added(added) {\n for (const node of added) {\n for (const record of bodies) {\n for (const [start, end] of record.ranges) {\n if (\n node.parentNode === start.parentNode &&\n start.compareDocumentPosition(node) & 4 &&\n node.compareDocumentPosition(end) & 4\n ) {\n hideNode(node);\n }\n }\n // A `#portal` that renders in a hidden body, whose nodes follow its marker.\n const data = node.nodeType === 8 ? (node as Comment).data : '';\n const scope = /^P-?[\\d.]+$/.test(data) ? scopes.get(parseId(data.slice(1))) : undefined;\n if (scope && within(scope, record.scope)) {\n record.ranges.push([node as Comment, rangeEnd(node as Comment)]);\n }\n }\n }\n },\n styled(element) {\n const saved = nodes.get(element);\n const style = display(element);\n if (saved && style) {\n saved.v = style.getPropertyValue('display');\n saved.p = style.getPropertyPriority('display');\n saved.a = element.hasAttribute('style');\n style.setProperty('display', 'none', 'important');\n }\n },\n };\n}\n","// `#for` and `#repeat` lists, and the windowed lists that draw only the items in view.\n\nimport { HAS_ROOT_WAIT, HAS_WINDOWS } from '../features.ts';\nimport { parseId } from '../shared.ts';\nimport { blockStart, clear, rangeEnd } from './blocks.ts';\nimport type { Render } from './branches.ts';\nimport { insertHTML, refresh } from './insert.ts';\nimport { destroy, disposeKinds, inPlace, removeBlock } from './scopes.ts';\nimport { DEV, scopes } from './state.ts';\nimport type { Scope } from './state.ts';\nimport { isThenable } from './updates.ts';\nimport { hold, holdRow, release } from './waits.ts';\n\ninterface Item {\n scope: Scope;\n /** The first and last node of the item, which are the same node for one element. */\n first: Node;\n last: Node;\n /** The place of the item in the list before the update. */\n position: number;\n /** True for an item whose key is in the new list. */\n kept: boolean;\n /** True for a kept item that stays in place. */\n still: boolean;\n}\n\nconst ITEM_MARKER = /^i(-?[\\d.]+)$/;\n\n/** The items of a `#for` list: an array as it is, since `list` only reads it, or any iterable as an array. */\nexport function toList(value: Iterable<unknown> | ArrayLike<unknown>): unknown[] {\n return Array.isArray(value) ? value : Array.from(value);\n}\n\n/** Updates the items of `#for` or `#repeat`, keeping the elements of items whose keys stay. */\nexport function list(\n scope: Scope,\n anchor: number,\n items: unknown[],\n key: (item: unknown, index: number) => unknown,\n given: Render,\n assign: (scope: Scope, item: unknown, index: number) => void,\n givenFallback: Render | undefined,\n fallbackKinds: number[],\n holderKind?: number,\n holderAnchor?: number,\n givenPark?: Parking,\n): void {\n const park = HAS_WINDOWS ? givenPark : undefined;\n const start = blockStart(scope, anchor);\n if (!start) {\n return;\n }\n const render = inPlace(scope, given, holderKind, holderAnchor)!;\n const fallback = inPlace(scope, givenFallback, holderKind, holderAnchor);\n const end = rangeEnd(start);\n const previous = new Map<unknown, Item>();\n let others: Node[] | undefined;\n let position = 0;\n for (let node = start.nextSibling; node && node !== end;) {\n // An item between `<!--i…-->` and `<!--/i-->`, or one element whose `b-b` names the scope.\n let data: string | undefined;\n let id: string | undefined;\n if (node.nodeType === 8) {\n data = (node as Comment).data;\n id = ITEM_MARKER.exec(data)?.[1];\n } else if (node.nodeType === 1) {\n const bound = (node as Element).getAttribute('b-b');\n id = bound === null ? undefined : bound.slice(0, bound.indexOf(':'));\n }\n const item = id === undefined ? undefined : scopes.get(parseId(id));\n let last: Node = node;\n // The elements of the fallback have scopes of its kinds.\n if (item && (data !== undefined || (item.p === scope && !fallbackKinds.includes(item.k)))) {\n if (data !== undefined) {\n last = rangeEnd(node as Comment);\n }\n // An item of a windowed list has the index that it had in the whole list in its key.\n previous.set(key(item.i, position + (park?.was ?? 0)), {\n scope: item,\n first: node,\n last,\n position: position++,\n kept: false,\n still: false,\n });\n } else {\n (others ??= []).push(node);\n }\n node = last.nextSibling;\n }\n\n const count = items.length;\n // An item that leaves a windowed list, but stays in its list, keeps its scope and nodes.\n function leave(id: unknown, item: Item): void {\n if (park?.stays(id)) {\n const nodes = document.createDocumentFragment();\n for (let node: Node | null = item.first; node;) {\n const next: Node | null = node === item.last ? null : node.nextSibling;\n nodes.append(node);\n node = next;\n }\n park.items.set(id, { scope: item.scope, nodes });\n return;\n }\n destroy(item.scope);\n for (let node: Node | null = item.first; node;) {\n const next: Node | null = node === item.last ? null : node.nextSibling;\n node.parentNode?.removeChild(node);\n node = next;\n }\n }\n // A windowed list with no item in view is not empty, so it does not show its fallback.\n if (count === 0 && !(park && park.total > 0)) {\n if (previous.size === 0 && others) {\n return;\n }\n if (HAS_ROOT_WAIT) {\n // The items stay until the fallback is ready.\n hold(\n start,\n 0,\n () => (fallback ? fallback(scope) : ''),\n (out) => {\n // The items as they are when it shows.\n removeBlock(scope, [], start, end);\n insertHTML(end, out);\n },\n );\n return;\n }\n for (const [id, item] of previous) {\n leave(id, item);\n }\n clear(start, end);\n if (fallback) {\n insertHTML(end, fallback(scope));\n }\n return;\n }\n if (HAS_ROOT_WAIT) {\n release(start);\n }\n\n disposeKinds(scope, fallbackKinds);\n if (others) {\n for (const node of others) {\n node.parentNode?.removeChild(node);\n }\n }\n const parent = end.parentNode!;\n // The key of each item, and the items that stay, in the new order. A key that repeats keeps\n // its item once, as below.\n const keys: unknown[] = Array.from({ length: count });\n const kept: Item[] = [];\n for (let index = 0; index < count; index++) {\n const id = (keys[index] = key(items[index], index + (park?.from ?? 0)));\n // Markup waits for a promise in text and attributes only. Production uses the key as it is.\n if (DEV && isThenable(id)) {\n throw new Error(\n 'The key of a #for row gives a promise, and the key of a #for cannot wait for one [BRM188]. Await it in the code that runs, or read its value with $memo',\n );\n }\n const item = previous.get(id);\n if (item && !item.kept) {\n item.kept = true;\n kept.push(item);\n }\n }\n // The items that stay in place: the longest run of them that keeps the old order. Only the\n // others move, because moving a node restarts its animations and drops its focus.\n markInPlace(kept);\n // When no item stays, the old ones go first, in one removal, and the new ones go in after.\n if (kept.length === 0 && previous.size > 0 && !park) {\n for (const item of previous.values()) {\n destroy(item.scope);\n }\n previous.clear();\n clear(start, end);\n }\n // The first node after the items placed so far.\n let cursor: Node = start.nextSibling!;\n // New items next to each other go into the page with one insert: their HTML, or the\n // fragments that they cloned.\n let added = '';\n let addedNodes: DocumentFragment[] | undefined;\n function flushAdded(): void {\n if (added) {\n insertHTML(cursor, added);\n added = '';\n } else if (addedNodes) {\n insertHTML(cursor, addedNodes);\n }\n addedNodes = undefined;\n }\n for (let index = 0; index < count; index++) {\n const id = keys[index];\n const item = previous.get(id);\n const parked = item ? undefined : park?.items.get(id);\n if (parked) {\n // An item of a windowed list that comes back into view, with its scope and nodes.\n flushAdded();\n park!.items.delete(id);\n parent.insertBefore(parked.nodes, cursor);\n assign(parked.scope, items[index], index);\n (park!.back ??= []).push(parked.scope);\n continue;\n }\n if (!item) {\n let out: string | DocumentFragment;\n if (HAS_ROOT_WAIT) {\n // A new row outside every `#loading` shows when its waits end.\n out = holdRow(scope, () => render(scope, items[index], index));\n // A row that waits gives nodes, which go in after the HTML of the rows before it.\n if (typeof out === 'string' ? addedNodes : added) {\n flushAdded();\n }\n } else {\n out = render(scope, items[index], index);\n }\n if (typeof out === 'string') {\n added += out;\n } else {\n (addedNodes ??= []).push(out);\n }\n continue;\n }\n // Before the item's updates run, so they see the new items before it.\n flushAdded();\n previous.delete(id);\n // Slots that keep their values do not trigger updates.\n assign(item.scope, items[index], index);\n if (item.still) {\n // The nodes between the cursor and the item belong to items that move or go.\n cursor = item.last.nextSibling!;\n } else {\n for (let node = item.first; ;) {\n const next = node.nextSibling;\n parent.insertBefore(node, cursor);\n if (node === item.last) {\n break;\n }\n node = next!;\n }\n }\n }\n flushAdded();\n for (const [id, item] of previous) {\n leave(id, item);\n }\n // The updates of an item that was out of the page did not reach its nodes, so it catches up.\n if (park?.back) {\n const back = park.back.splice(0);\n refresh(back);\n // The windows inside an item that came back draw for the box as it is now.\n for (const item of back) {\n redraw(item);\n }\n }\n}\n\n/** Draws the windowed lists of a scope and of the scopes inside it. */\nfunction redraw(scope: Scope): void {\n for (const state of windows.get(scope)?.values() ?? []) {\n state.draw?.();\n }\n for (const child of scope.children ?? []) {\n redraw(child);\n }\n}\n\n/** What a windowed list keeps between draws: its parked items and the height of an item. */\ninterface WindowState {\n parked: Parking['items'];\n /** The height of an item, from the items that rendered, once they have. */\n measured?: number;\n /** Draws the window with the latest items, for a scroll. */\n draw?: () => void;\n /** The index in the whole list of the first item that is in the page. */\n from: number;\n frame?: number;\n}\n\nconst windows = new WeakMap<Scope, Map<number, WindowState>>();\n\n/**\n * The element that scrolls a windowed list, or none for the page. An element scrolls the list\n * when it can scroll vertically: its overflow allows it, and its content is taller than it.\n * A wrapper without a height, such as one that scrolls sideways, grows with the list and has\n * nothing to scroll, so the list looks further up. The server renders enough items to fill\n * the box, so its content is taller from the first draw on.\n */\nfunction findScroller(node: Node): HTMLElement | undefined {\n for (let element = node.parentElement; element; element = element.parentElement) {\n const style = getComputedStyle(element);\n if (\n /^(auto|scroll|overlay)$/.test(style.overflowY || style.overflow) &&\n element.scrollHeight > element.clientHeight\n ) {\n return element;\n }\n }\n return undefined;\n}\n\n/**\n * Renders the items of a windowed list that are in view, from `#for … window(height, count)`,\n * with `list`, between the spacers that the server wrote before and after the block. Items that\n * leave the view keep their scopes and nodes while they are in the list.\n */\nexport function windowList(\n scope: Scope,\n anchor: number,\n items: unknown[],\n key: (item: unknown, index: number) => unknown,\n render: Render,\n assign: (scope: Scope, item: unknown, index: number) => void,\n fallback: Render | undefined,\n fallbackKinds: number[],\n height: number,\n holderKind?: number,\n holderAnchor?: number,\n): void {\n const byAnchor = windows.get(scope) ?? new Map<number, WindowState>();\n windows.set(scope, byAnchor);\n let state = byAnchor.get(anchor);\n if (!state) {\n state = { parked: new Map(), from: 0 };\n byAnchor.set(anchor, state);\n }\n const window = state;\n window.draw = () => {\n const start = blockStart(scope, anchor);\n if (!start) {\n return;\n }\n const end = rangeEnd(start);\n const before = start.previousSibling as HTMLElement | null;\n const after = end.nextSibling as HTMLElement | null;\n if (!before?.hasAttribute?.('data-window') || !after?.hasAttribute?.('data-window')) {\n return;\n }\n const size = window.measured ?? height;\n const top = before.getBoundingClientRect().top;\n const scroller = findScroller(start);\n const view = scroller\n ? scroller.getBoundingClientRect()\n : { top: 0, bottom: document.documentElement.clientHeight };\n // A few items more on each side, so a scroll shows rendered items.\n const extra = 3;\n const count = items.length;\n const from = Math.min(count, Math.max(0, Math.floor((view.top - top) / size) - extra));\n const to = Math.min(count, Math.max(from, Math.ceil((view.bottom - top) / size) + extra));\n const keys = new Set<unknown>();\n for (const [index, item] of items.entries()) {\n keys.add(key(item, index));\n }\n const was = window.from;\n window.from = from;\n list(\n scope,\n anchor,\n items.slice(from, to),\n key,\n (parent, item, index) => render(parent, item, index === undefined ? index : index + from),\n (item, value, index) => assign(item, value, index + from),\n fallback,\n fallbackKinds,\n holderKind,\n holderAnchor,\n { items: window.parked, stays: (id) => keys.has(id), was, from, total: count },\n );\n // Items that left the list for good go.\n for (const [id, parked] of window.parked) {\n if (!keys.has(id)) {\n window.parked.delete(id);\n destroy(parked.scope);\n }\n }\n before.style.height = `${from * size}px`;\n after.style.height = `${(count - to) * size}px`;\n // The height of an item, from those that rendered.\n if (to > from) {\n const rendered = after.getBoundingClientRect().top - before.getBoundingClientRect().bottom;\n if (rendered > 0) {\n window.measured = rendered / (to - from);\n }\n }\n };\n window.draw();\n}\n\n/**\n * Starts the window of a windowed list that the server rendered: it draws now, and again as\n * the page or the element that scrolls the list scrolls or resizes.\n */\nexport function windowStart(scope: Scope, anchor: number, draw: () => void): void {\n draw();\n const window = windows.get(scope)?.get(anchor);\n const start = blockStart(scope, anchor);\n if (!window || !start) {\n return;\n }\n const scroller = findScroller(start);\n const target: EventTarget = scroller ?? globalThis;\n let observer: ResizeObserver | undefined;\n // An arrow, to keep the narrowing of `start` and `window`.\n const schedule = (): void => {\n // A scope that is gone stops listening for good.\n if (!scopes.has(scope.id)) {\n target.removeEventListener('scroll', schedule);\n globalThis.removeEventListener('resize', schedule);\n observer?.disconnect();\n return;\n }\n // An item that is out of the page for a while draws when it comes back.\n if (!start.isConnected) {\n return;\n }\n if (window.frame === undefined) {\n window.frame = requestAnimationFrame(() => {\n window.frame = undefined;\n window.draw?.();\n });\n }\n };\n target.addEventListener('scroll', schedule, { passive: true });\n globalThis.addEventListener('resize', schedule, { passive: true });\n // The box can change its size without the window, such as when a panel around it opens.\n if (scroller && typeof ResizeObserver !== 'undefined') {\n observer = new ResizeObserver(schedule);\n observer.observe(scroller);\n }\n}\n\n/** The items of a windowed list that are out of view, which keep their scopes and nodes. */\ninterface Parking {\n items: Map<unknown, { scope: Scope; nodes: DocumentFragment }>;\n /** Whether a key is still in the list, so its item keeps its scope when it leaves the view. */\n stays: (key: unknown) => boolean;\n /** The index in the whole list of the first item that was in the page before. */\n was: number;\n /** The index in the whole list of the first item that is in the page now. */\n from: number;\n /** The number of items in the whole list, also when none is in view. */\n total: number;\n /** The scopes of items that came back, which refresh. */\n back?: Scope[];\n}\n\n/**\n * Marks the items of a list that keep their places: the longest run of `kept`, the items that\n * stay in their new order, whose old positions go up.\n */\nfunction markInPlace(kept: Item[]): void {\n let sorted = true;\n for (let index = 1; index < kept.length; index++) {\n if (kept[index - 1]!.position > kept[index]!.position) {\n sorted = false;\n break;\n }\n }\n if (sorted) {\n for (const item of kept) {\n item.still = true;\n }\n return;\n }\n // `tails[length - 1]` is the index of the item that ends the run of that length with the\n // lowest position, and `before` links each item to the item before it in its run.\n const tails: number[] = [];\n const before: number[] = [];\n for (let index = 0; index < kept.length; index++) {\n const position = kept[index]!.position;\n let low = 0;\n let high = tails.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n if (kept[tails[middle]!]!.position < position) {\n low = middle + 1;\n } else {\n high = middle;\n }\n }\n before[index] = low > 0 ? tails[low - 1]! : -1;\n tails[low] = index;\n }\n for (let index = tails.at(-1) ?? -1; index >= 0; index = before[index]!) {\n kept[index]!.still = true;\n }\n}\n","// Parts of the page outside a component: style variables, `#head` and `#portal` markup,\n// stylesheets and `#defer` in the browser.\n\nimport { insertHTML } from './insert.ts';\nimport { afterInsert } from './scopes.ts';\nimport { DEV } from './state.ts';\nimport type { Scope } from './state.ts';\n\n/** Sets a style variable on the top-level elements of a component instance. */\nexport function setVar(scope: Scope, name: string, value: unknown): void {\n const css = value === null || value === undefined || value === false ? '' : String(value);\n for (const element of document.querySelectorAll<HTMLElement>(`[b-v=\"${scope.id}\"]`)) {\n if (element.style.getPropertyValue(name) !== css) {\n element.style.setProperty(name, css);\n }\n }\n}\n\n/**\n * Warns in development that the browser renders a `#defer` block of a\n * component, such as inside a `#client` body of its parent. Only the server\n * renders the body, so the fallback stays.\n */\nexport function deferInBrowser(id: string): void {\n if (DEV) {\n console.warn(\n `${id} renders a #defer block in the browser, so it shows its fallback only. Render the component in markup that the server renders.`,\n );\n }\n}\n\n/** Adds the markup of a `#head` block to the document's head. */\nexport function addHead(html: string | DocumentFragment): void {\n afterInsert.push(() => insertHTML({ parent: document.head }, html));\n}\n\n/** Adds the markup of a `#portal` block at the end of the page, after the markup around it. */\nexport function addPortal(html: string | DocumentFragment): void {\n afterInsert.push(() => insertHTML({ parent: document.body }, html));\n}\n\n/** Adds a component's stylesheet to the page, if the server did not. */\nexport function addStyle(id: string, css: string): string {\n if (!document.querySelector(`style[b-style=\"${id}\"]`)) {\n const sheet = document.createElement('style');\n sheet.setAttribute('b-style', id);\n sheet.textContent = css;\n document.head.append(sheet);\n }\n return '';\n}\n","// The core keeps only what every page needs: it reads the state, runs handlers and updates.\n// Each helper that compiled code calls is an export of its own, so a build leaves out the ones\n// that no component calls. Features that change how the core reads the page, such as client\n// navigation and hot updates, live in their own modules and set `hooks` when they load.\n//\n// The code is in `client/`, one module for each feature. A module imports only the modules that\n// come before it in this order, so there are no cycles: state, code, blocks, references, scopes,\n// titles, insert, children, errors, updates, guesses, props, handlers, context, templates,\n// branches, lists, inserts, components, page, waits, resume. This module exports what compiled\n// code and the other modules of the package use.\nimport { setGlobal, updateRoute } from './client/context.ts';\nimport { HAS_ROUTES } from './features.ts';\nimport { handle, submitAction } from './client/handlers.ts';\nimport { dispose, init } from './client/resume.ts';\n\nexport { navigationContext, routeContext } from './context.ts';\nexport {\n affix,\n attribute,\n classAttribute,\n escape,\n internal,\n mergeAttributes,\n onAttribute,\n raw,\n vars,\n} from './html.ts';\nexport type { Raw } from './html.ts';\nexport { produce } from './produce.ts';\n// For `client-routes.ts`, which reads the core with `import()`.\nexport { SCOPE_IDS as scopeIds, unbind } from './shared.ts';\nexport { createContext } from './context.ts';\nexport { nameComment } from './client/blocks.ts';\nexport { branch, fill, held, offscreen, rekey, reset, retag } from './client/branches.ts';\nexport type { HiddenBody } from './client/branches.ts';\nexport { children, insert } from './client/children.ts';\nexport { loadModule } from './client/code.ts';\nexport {\n component,\n componentNodes,\n dynamic,\n dynamicNodes,\n elementAt,\n foreignNodes,\n place,\n setItem,\n setSlots,\n} from './client/components.ts';\nexport type { Component } from './client/components.ts';\nexport {\n consumeContext,\n provideValue,\n setGlobal,\n updateContext,\n updateRoute,\n} from './client/context.ts';\nexport { fail } from './client/errors.ts';\nexport {\n after,\n attempt,\n countLoads,\n fillAttrs,\n fillSettled,\n fillSpread,\n fillValue,\n keepValue,\n loading,\n reveal,\n started,\n wait,\n} from './client/waits.ts';\nexport { guess, track } from './client/guesses.ts';\nexport { action, handle, handlerProp, rpc, spread, submitAction } from './client/handlers.ts';\nexport { attr, attrs, content, portalTo, restRef, text, writeText } from './client/inserts.ts';\nexport { list, toList, windowList, windowStart } from './client/lists.ts';\nexport { addHead, addPortal, addStyle, deferInBrowser, setVar } from './client/page.ts';\nexport { prop, spreadProps } from './client/props.ts';\nexport {\n dispose,\n forget,\n init,\n leavePage,\n leaveRoutes,\n remount,\n removeRoot,\n} from './client/resume.ts';\nexport {\n afterInsert,\n createScope,\n descendants,\n makeId,\n removeScope,\n getScope,\n setOwner,\n sink,\n} from './client/scopes.ts';\nexport { DEVTOOLS, build, hooks, rpcPrefix, scopes, skew } from './client/state.ts';\nexport type { ClientModule, CoreOptions, DevtoolsHooks, Scope } from './client/state.ts';\nexport {\n appendText,\n branchNodes,\n clone,\n fillBranch,\n fillList,\n keep,\n keepText,\n listNodes,\n markBlock,\n nodes,\n putText,\n setAttr,\n setAttrText,\n setContent,\n setOn,\n setSpread,\n template,\n} from './client/templates.ts';\nexport { title } from './client/titles.ts';\nexport {\n asyncMemo,\n binding,\n bindings,\n cells,\n effect,\n get,\n isBound,\n memo,\n pending,\n resolve,\n set,\n timed,\n update,\n unreadMemo,\n updated,\n} from './client/updates.ts';\n\n/**\n * What the loader calls. It is one export, so the loader's import of the core\n * names one export, and a build keeps the rest only when components call them.\n */\nexport const loader: {\n init: typeof init;\n handle: typeof handle;\n dispose: typeof dispose;\n submitAction: typeof submitAction;\n setGlobal: typeof setGlobal;\n updateRoute: typeof updateRoute;\n} = {\n init,\n handle,\n dispose,\n submitAction,\n // Only `$route`, `$navigation` and client navigation read what these write.\n setGlobal: HAS_ROUTES ? setGlobal : noop,\n updateRoute: HAS_ROUTES ? updateRoute : noop,\n};\n\nfunction noop(): void {}\n"],"mappings":";;;;;;AAkIA,IAAW;;AAGX,IAAW,YAAY;;AAGvB,IAAW;;AAGX,SAAgB,UAAU,OAA0B;CAClD,UAAU;CACV,YAAY,MAAM,OAAO;CACzB,QAAQ,MAAM;AAChB;;;;;;AAOA,SAAgB,KAAK,QAAyC;CAC5D,SAAS,cAAc,IAAI,YAAY,gBAAgB,EAAE,QAAQ,OAAO,CAAC,CAAC;AAC5E;;AAGA,MAAa,yBAA8B,IAAI,IAAI;;AAGnD,MAAa,QAWT,CAAC;;AA2CL,MAAa,WAA0B,OAAO,IAAI,kBAAkB;;;;;;AAOpE,MAAa,MAA4B,YAA4C,KAAK;AAE1F,SAAgB,WAAsC;CACpD,OAAQ,WAAyD;AACnE;AAEA,MAAa,0BAAqC,IAAI,IAAI;AAE1D,MAAaA,4BAA8C,IAAI,IAAI;AAEnE,MAAa,eAA0C,CAAC;AAExD,MAAa,2BAAiC,IAAI,IAAI;AAEtD,MAAa,2BAAiC,IAAI,IAAI;AAItD,MAAa,uBAA+B,IAAI,IAAI;AAGpD,MAAa,wBAA6B,IAAI,IAAI;AAElD,MAAa,+BAA4B,IAAI,IAAI;;AAGjD,MAAa,yBACX,IAAI,IAAI;;AAGV,MAAa,kCAAgD,IAAI,IAAI;;;;;A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