@bquery/bquery 1.11.0 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +79 -59
- package/dist/{a11y-DgUQ8-fI.js → a11y-IV_bfLyn.js} +3 -3
- package/dist/{a11y-DgUQ8-fI.js.map → a11y-IV_bfLyn.js.map} +1 -1
- package/dist/a11y.es.mjs +1 -1
- package/dist/{component-D8ydhe58.js → component-BtsRbf6c.js} +7 -7
- package/dist/{component-D8ydhe58.js.map → component-BtsRbf6c.js.map} +1 -1
- package/dist/component.es.mjs +1 -1
- package/dist/{concurrency-BU1wPEsZ.js → concurrency-kycgAZvW.js} +3 -3
- package/dist/{concurrency-BU1wPEsZ.js.map → concurrency-kycgAZvW.js.map} +1 -1
- package/dist/concurrency.es.mjs +1 -1
- package/dist/{config-DhT9auRm.js → config-BP7KwiR5.js} +1 -1
- package/dist/{config-DhT9auRm.js.map → config-BP7KwiR5.js.map} +1 -1
- package/dist/constraints-Dlbx_m1b.js.map +1 -1
- package/dist/core-tOP6QOrY.js.map +1 -1
- package/dist/{core-CongXJuo.js → core-yg9rJXiR.js} +1 -1
- package/dist/{core-CongXJuo.js.map → core-yg9rJXiR.js.map} +1 -1
- package/dist/custom-directives-5DlKqvd2.js.map +1 -1
- package/dist/devtools-QosAqo0T.js.map +1 -1
- package/dist/dnd-d2OU4len.js.map +1 -1
- package/dist/{effect-Cc51IH91.js → effect-v8OIEmPs.js} +2 -2
- package/dist/{effect-Cc51IH91.js.map → effect-v8OIEmPs.js.map} +1 -1
- package/dist/env-PvwYHnJq.js.map +1 -1
- package/dist/{forms-BLx4ZzT7.js → forms-DYcdlk_h.js} +8 -8
- package/dist/{forms-BLx4ZzT7.js.map → forms-DYcdlk_h.js.map} +1 -1
- package/dist/forms.es.mjs +1 -1
- package/dist/full.d.ts +11 -11
- package/dist/full.d.ts.map +1 -1
- package/dist/full.es.mjs +324 -279
- package/dist/full.iife.js +26 -26
- package/dist/full.iife.js.map +1 -1
- package/dist/full.umd.js +26 -26
- package/dist/full.umd.js.map +1 -1
- package/dist/function-Cybd57JV.js.map +1 -1
- package/dist/{i18n--p7PM-9r.js → i18n-unHU1jMo.js} +3 -3
- package/dist/{i18n--p7PM-9r.js.map → i18n-unHU1jMo.js.map} +1 -1
- package/dist/i18n.es.mjs +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.es.mjs +198 -196
- package/dist/match-CrZRVC4z.js.map +1 -1
- package/dist/{media-gjbWNq50.js → media-Chh6mA0v.js} +3 -3
- package/dist/{media-gjbWNq50.js.map → media-Chh6mA0v.js.map} +1 -1
- package/dist/media.es.mjs +1 -1
- package/dist/{motion-BBMso9Ir.js → motion-27Od9aFE.js} +2 -2
- package/dist/{motion-BBMso9Ir.js.map → motion-27Od9aFE.js.map} +1 -1
- package/dist/motion.es.mjs +1 -1
- package/dist/{mount-0A9qtcRJ.js → mount-DwUFujZ_.js} +4 -4
- package/dist/{mount-0A9qtcRJ.js.map → mount-DwUFujZ_.js.map} +1 -1
- package/dist/object-BCk-1c8T.js.map +1 -1
- package/dist/{platform-BPHIXbw8.js → platform-2YkFA11t.js} +4 -4
- package/dist/{platform-BPHIXbw8.js.map → platform-2YkFA11t.js.map} +1 -1
- package/dist/platform.es.mjs +2 -2
- package/dist/plugin-SZEirbwq.js.map +1 -1
- package/dist/reactive/index.d.ts +2 -2
- package/dist/reactive/index.d.ts.map +1 -1
- package/dist/reactive/signal.d.ts +7 -7
- package/dist/reactive/signal.d.ts.map +1 -1
- package/dist/reactive/websocket.d.ts +15 -3
- package/dist/reactive/websocket.d.ts.map +1 -1
- package/dist/{reactive-BAd2hfl8.js → reactive-BvPR_FYA.js} +10 -10
- package/dist/{reactive-BAd2hfl8.js.map → reactive-BvPR_FYA.js.map} +1 -1
- package/dist/reactive.es.mjs +40 -40
- package/dist/{readonly-C0ZwS1Tf.js → readonly-Br-6pAgj.js} +2 -2
- package/dist/{readonly-C0ZwS1Tf.js.map → readonly-Br-6pAgj.js.map} +1 -1
- package/dist/registry-jpUQHf4E.js.map +1 -1
- package/dist/{router-C4weu0QL.js → router-CbnWKprL.js} +7 -7
- package/dist/{router-C4weu0QL.js.map → router-CbnWKprL.js.map} +1 -1
- package/dist/router.es.mjs +1 -1
- package/dist/sanitize-DOMkRO9G.js.map +1 -1
- package/dist/server/create-server.d.ts.map +1 -1
- package/dist/server/types.d.ts.map +1 -1
- package/dist/{server-QdyKtCS1.js → server-Dwiq_F49.js} +2 -2
- package/dist/server-Dwiq_F49.js.map +1 -0
- package/dist/server.es.mjs +1 -1
- package/dist/ssr/context.d.ts.map +1 -1
- package/dist/ssr/renderer.d.ts.map +1 -1
- package/dist/ssr/suspense.d.ts.map +1 -1
- package/dist/{ssr-Bt6BQA3J.js → ssr-CqJU1Ogp.js} +8 -8
- package/dist/ssr-CqJU1Ogp.js.map +1 -0
- package/dist/ssr.es.mjs +1 -1
- package/dist/store/index.d.ts +1 -1
- package/dist/store/index.d.ts.map +1 -1
- package/dist/store/plugins.d.ts +38 -0
- package/dist/store/plugins.d.ts.map +1 -1
- package/dist/{store-DnXuu6Li.js → store-DzrhVQ29.js} +69 -62
- package/dist/store-DzrhVQ29.js.map +1 -0
- package/dist/store.es.mjs +13 -11
- package/dist/storybook.es.mjs.map +1 -1
- package/dist/{testing-CeMUwrRD.js → testing-ByjwS2_D.js} +3 -3
- package/dist/{testing-CeMUwrRD.js.map → testing-ByjwS2_D.js.map} +1 -1
- package/dist/testing.es.mjs +1 -1
- package/dist/type-guards-BMX2c0LP.js.map +1 -1
- package/dist/{untrack-bjWDNdyE.js → untrack-uzz3JDNK.js} +3 -3
- package/dist/{untrack-bjWDNdyE.js.map → untrack-uzz3JDNK.js.map} +1 -1
- package/dist/view.es.mjs +8 -8
- package/package.json +12 -11
- package/src/full.ts +75 -6
- package/src/index.ts +2 -2
- package/src/reactive/index.ts +5 -4
- package/src/reactive/signal.ts +7 -6
- package/src/reactive/websocket.ts +15 -2
- package/src/server/create-server.ts +10 -5
- package/src/server/types.ts +1 -5
- package/src/ssr/context.ts +6 -2
- package/src/ssr/renderer.ts +5 -2
- package/src/ssr/suspense.ts +17 -8
- package/src/store/index.ts +1 -1
- package/src/store/plugins.ts +48 -1
- package/dist/server-QdyKtCS1.js.map +0 -1
- package/dist/ssr-Bt6BQA3J.js.map +0 -1
- package/dist/store-DnXuu6Li.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ssr-CqJU1Ogp.js","names":[],"sources":["../src/ssr/hydrate.ts","../src/ssr/config.ts","../src/ssr/hash.ts","../src/ssr/expression.ts","../src/ssr/html-parser.ts","../src/ssr/renderer.ts","../src/ssr/escape.ts","../src/ssr/serialize.ts","../src/ssr/render.ts","../src/ssr/runtime.ts","../src/ssr/defer-brand.ts","../src/ssr/async.ts","../src/ssr/head.ts","../src/ssr/context.ts","../src/ssr/render-async.ts","../src/ssr/strategies.ts","../src/ssr/mismatch.ts","../src/ssr/suspense.ts","../src/ssr/router-bridge.ts","../src/ssr/store-snapshot.ts","../src/ssr/resumability.ts","../src/ssr/adapters.ts"],"sourcesContent":["/**\n * Hydration support for server-rendered DOM.\n *\n * Enables the client-side view system to reuse existing server-rendered DOM\n * elements instead of re-rendering them, by attaching reactive bindings\n * to the pre-existing DOM structure.\n *\n * @module bquery/ssr\n */\n\nimport type { BindingContext, MountOptions, View } from '../view/types';\nimport { mount } from '../view/mount';\n\n/**\n * Extended mount options that include hydration mode.\n */\nexport type HydrateMountOptions = MountOptions & {\n /**\n * When present, must be `true` so the mount operation reuses existing DOM elements\n * instead of re-rendering them. Reactive bindings (effects) are\n * still attached so the DOM updates reactively from that point on.\n *\n * @default true\n */\n hydrate?: true;\n};\n\n/**\n * Mounts a reactive view with optional hydration support.\n *\n * When `hydrate: true` is set, the existing server-rendered DOM is preserved\n * and reactive bindings are attached on top. The DOM is NOT re-rendered;\n * instead, effects begin tracking signals so future changes update the DOM.\n *\n * This is the client-side counterpart to `renderToString()`. The typical flow:\n * 1. Server: `renderToString(template, data)` → send HTML to client\n * 2. Client: `hydrateMount('#app', reactiveContext, { hydrate: true })`\n *\n * Under the hood, `hydrateMount` simply delegates to the standard `mount()`\n * function. The `mount()` function already processes existing DOM elements\n * and attaches reactive effects to them — it does not clear/replace content.\n * The `hydrate` flag is a semantic marker indicating developer intent and\n * ensures the existing DOM structure is preserved.\n *\n * @param selector - CSS selector or Element to hydrate\n * @param context - Binding context with signals, computed values, and functions\n * @param options - Mount options with `hydrate: true`\n * @returns The mounted View instance\n *\n * @example\n * ```ts\n * import { hydrateMount } from '@bquery/bquery/ssr';\n * import { signal, computed } from '@bquery/bquery/reactive';\n *\n * // Server rendered:\n * // <div id=\"app\"><h1>Welcome</h1><p>Hello, World!</p></div>\n *\n * // Client hydration — attaches reactivity to existing DOM:\n * const name = signal('World');\n * const greeting = computed(() => `Hello, ${name.value}!`);\n *\n * const view = hydrateMount('#app', { name, greeting }, { hydrate: true });\n *\n * // Now updating `name.value` will reactively update the DOM\n * name.value = 'Alice'; // <p> updates to \"Hello, Alice!\"\n * ```\n */\nexport const hydrateMount = (\n selector: string | Element,\n context: BindingContext,\n options: HydrateMountOptions = {}\n): View => {\n const { hydrate = true, ...mountOptions } = options;\n\n if (!hydrate) {\n throw new Error(\n 'bQuery ssr: hydrateMount() requires { hydrate: true } when options are provided.'\n );\n }\n\n // Hydration uses the standard mount which processes existing DOM\n // and attaches reactive effects without clearing content.\n return mount(selector, context, mountOptions);\n};\n","/**\n * Global SSR configuration.\n *\n * Lets users opt into a custom DOM implementation (`linkedom`, `happy-dom`,\n * `jsdom`, …) for the legacy `DOMParser`-based renderer, or force the\n * DOM-free renderer everywhere. Defaults are runtime-aware: if a global\n * `DOMParser` exists, it is used (preserves legacy behaviour); otherwise the\n * DOM-free renderer kicks in automatically.\n *\n * @module bquery/ssr\n */\n\n/**\n * Backend used by `renderToString()` and `renderToStringAsync()`.\n */\nexport type SSRRendererBackend = 'auto' | 'pure' | 'dom';\n\n/**\n * DOM implementation injected by `configureSSR()` for the `'dom'` backend.\n */\nexport interface SSRDocumentImpl {\n /** A `DOMParser` constructor compatible with the WHATWG spec. */\n DOMParser: typeof globalThis.DOMParser;\n}\n\ninterface SSRConfig {\n backend: SSRRendererBackend;\n documentImpl: SSRDocumentImpl | null;\n}\n\nconst config: SSRConfig = {\n backend: 'auto',\n documentImpl: null,\n};\n\n/**\n * Updates the global SSR configuration. All options are optional and merged\n * shallowly with the existing configuration.\n *\n * @example\n * ```ts\n * import { configureSSR } from '@bquery/bquery/ssr';\n * import { DOMParser } from 'linkedom';\n *\n * configureSSR({ backend: 'dom', documentImpl: { DOMParser } });\n * ```\n */\nexport const configureSSR = (\n options: Partial<{ backend: SSRRendererBackend; documentImpl: SSRDocumentImpl | null }>\n): void => {\n if (options.backend !== undefined) config.backend = options.backend;\n if (options.documentImpl !== undefined) config.documentImpl = options.documentImpl;\n};\n\n/**\n * Returns a snapshot of the current SSR configuration.\n */\nexport const getSSRConfig = (): Readonly<SSRConfig> => ({\n backend: config.backend,\n documentImpl: config.documentImpl,\n});\n\n/**\n * Resolves the renderer backend that should actually be used right now.\n * Honours `configureSSR()` and falls back to runtime feature detection.\n *\n * @internal\n */\nexport const resolveBackend = (): 'pure' | 'dom' => {\n if (config.backend === 'pure') return 'pure';\n if (config.backend === 'dom') return 'dom';\n\n if (config.documentImpl) return 'dom';\n if (typeof globalThis.DOMParser === 'function') return 'dom';\n return 'pure';\n};\n\n/**\n * Returns the configured `DOMParser` constructor or the global one.\n * @internal\n */\nexport const getDOMParserImpl = (): typeof globalThis.DOMParser | null => {\n if (config.documentImpl) return config.documentImpl.DOMParser;\n if (typeof globalThis.DOMParser === 'function') return globalThis.DOMParser;\n return null;\n};\n","/**\n * Shared hashing helpers used by the SSR renderer and the client-side\n * hydration mismatch verifier.\n *\n * The hash is intentionally cheap (DJB2 → base36) — its goal is to spot\n * Server↔Client divergence in dev, not to provide cryptographic guarantees.\n *\n * @module bquery/ssr\n */\n\n/**\n * Computes a stable, very small hash for a string. Used to attach a hydration\n * annotation that the client can compare against during dev-time hydration.\n *\n * Collisions are acceptable here: the goal is a mismatch *warning*, not\n * security.\n *\n * @internal\n */\nexport const cheapHash = (input: string): string => {\n let h = 5381;\n for (let i = 0; i < input.length; i++) {\n h = ((h << 5) + h + input.charCodeAt(i)) | 0;\n }\n return (h >>> 0).toString(36);\n};\n\n/**\n * The attribute that holds the directive-signature hash on a server-rendered\n * element. Public name so userland can read/write it deterministically.\n */\nexport const HYDRATION_HASH_ATTR = 'data-bq-h';\n\n/**\n * Collects the directive signature for a virtual element (used by the pure\n * renderer).\n *\n * @internal\n */\nexport const collectDirectiveSignatureFromAttrs = (\n attributeOrder: readonly string[],\n attributes: Readonly<Record<string, string | undefined>>,\n prefix: string\n): string => {\n const parts: string[] = [];\n for (const name of attributeOrder) {\n if (name === HYDRATION_HASH_ATTR) continue;\n if (name.startsWith(`${prefix}-`) || name.startsWith(':')) {\n parts.push(`${name}=${attributes[name] ?? ''}`);\n }\n }\n return parts.join('|');\n};\n\n/**\n * Collects the directive signature for a real DOM `Element`. Used by the\n * client-side mismatch verifier and the DOM-backed renderer.\n *\n * @internal\n */\nexport const collectDirectiveSignatureFromElement = (el: Element, prefix: string): string => {\n const parts: string[] = [];\n // Iterate in attribute insertion order to match the pure renderer.\n for (const attr of Array.from(el.attributes)) {\n if (attr.name === HYDRATION_HASH_ATTR) continue;\n if (attr.name.startsWith(`${prefix}-`) || attr.name.startsWith(':')) {\n parts.push(`${attr.name}=${attr.value}`);\n }\n }\n return parts.join('|');\n};\n","/**\n * CSP-safe expression evaluator for SSR templates.\n *\n * Evaluates a tightly scoped subset of JavaScript expressions against a\n * binding context without using `eval` or `new Function()`. Runs in any\n * runtime (Bun, Deno, Node, browsers) and is safe under strict CSP without\n * `'unsafe-eval'`.\n *\n * Supported grammar (operator-precedence Pratt parser):\n *\n * - Literals: numbers, single/double-quoted strings, `true`, `false`, `null`,\n * `undefined`.\n * - Identifiers and member access (`a.b`, `a['b']`, `a[0]`).\n * - Optional chaining (`a?.b`, `a?.[b]`).\n * - Unary `!`, `+`, `-`, `typeof`.\n * - Binary `+`, `-`, `*`, `/`, `%`, `==`, `===`, `!=`, `!==`, `<`, `<=`,\n * `>`, `>=`, `&&`, `||`, `??`.\n * - Ternary `cond ? a : b`.\n * - Parentheses for grouping.\n * - Function calls `fn(arg1, arg2, ...)` (only on identifiers / member chains\n * resolved against the context — no arbitrary expression invocation).\n *\n * Anything outside this grammar throws a parse error which the caller\n * converts into the standard SSR fallback (`undefined`).\n *\n * @module bquery/ssr\n * @internal\n */\n\nimport { isComputed, isSignal, type Signal } from '../reactive/index';\nimport { isPrototypePollutionKey } from '../core/utils/object';\nimport type { BindingContext } from '../view/types';\n\nconst unwrap = (value: unknown): unknown => {\n if (isSignal(value) || isComputed(value)) {\n return (value as Signal<unknown>).value;\n }\n return value;\n};\n\n/* ---------------------------------------------------------------------------\n * Tokenizer\n * ------------------------------------------------------------------------- */\n\ntype TokenKind = 'number' | 'string' | 'ident' | 'punct' | 'eof';\n\ninterface Token {\n kind: TokenKind;\n value: string;\n start: number;\n}\n\nconst PUNCT_MULTI = ['===', '!==', '==', '!=', '<=', '>=', '&&', '||', '??', '?.'];\n\nconst PUNCT_SINGLE = '+-*/%<>!?:,.()[]';\n\nconst isIdentStart = (ch: string): boolean =>\n (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch === '_' || ch === '$';\n\nconst isIdentCont = (ch: string): boolean => isIdentStart(ch) || (ch >= '0' && ch <= '9');\n\nconst isDigit = (ch: string): boolean => ch >= '0' && ch <= '9';\n\nconst tokenize = (input: string): Token[] => {\n const tokens: Token[] = [];\n const len = input.length;\n let i = 0;\n\n while (i < len) {\n const ch = input[i];\n\n if (ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r') {\n i++;\n continue;\n }\n\n // Strings\n if (ch === '\"' || ch === \"'\") {\n const quote = ch;\n const start = i;\n i++;\n let value = '';\n while (i < len && input[i] !== quote) {\n if (input[i] === '\\\\' && i + 1 < len) {\n const next = input[i + 1];\n if (next === 'n') value += '\\n';\n else if (next === 't') value += '\\t';\n else if (next === 'r') value += '\\r';\n else if (next === '\\\\') value += '\\\\';\n else if (next === quote) value += quote;\n else value += next;\n i += 2;\n continue;\n }\n value += input[i];\n i++;\n }\n if (i >= len) {\n throw new Error('Unterminated string literal in SSR expression');\n }\n i++; // closing quote\n tokens.push({ kind: 'string', value, start });\n continue;\n }\n\n // Numbers\n if (isDigit(ch) || (ch === '.' && i + 1 < len && isDigit(input[i + 1]))) {\n const start = i;\n while (i < len && (isDigit(input[i]) || input[i] === '.')) {\n i++;\n }\n tokens.push({ kind: 'number', value: input.slice(start, i), start });\n continue;\n }\n\n // Identifiers / keywords\n if (isIdentStart(ch)) {\n const start = i;\n while (i < len && isIdentCont(input[i])) {\n i++;\n }\n tokens.push({ kind: 'ident', value: input.slice(start, i), start });\n continue;\n }\n\n // Multi-char punctuation\n let matched = false;\n for (const p of PUNCT_MULTI) {\n if (input.startsWith(p, i)) {\n tokens.push({ kind: 'punct', value: p, start: i });\n i += p.length;\n matched = true;\n break;\n }\n }\n if (matched) continue;\n\n if (PUNCT_SINGLE.includes(ch)) {\n tokens.push({ kind: 'punct', value: ch, start: i });\n i++;\n continue;\n }\n\n throw new Error(`Unexpected character \"${ch}\" in SSR expression`);\n }\n\n tokens.push({ kind: 'eof', value: '', start: len });\n return tokens;\n};\n\n/* ---------------------------------------------------------------------------\n * Parser → directly evaluated AST\n * ------------------------------------------------------------------------- */\n\ninterface ParserState {\n tokens: Token[];\n pos: number;\n context: BindingContext;\n}\n\nconst peek = (s: ParserState): Token => s.tokens[s.pos];\nconst advance = (s: ParserState): Token => s.tokens[s.pos++];\n\nconst expectPunct = (s: ParserState, value: string): void => {\n const t = peek(s);\n if (t.kind !== 'punct' || t.value !== value) {\n throw new Error(`Expected \"${value}\" in SSR expression, got \"${t.value}\"`);\n }\n s.pos++;\n};\n\nconst matchPunct = (s: ParserState, value: string): boolean => {\n const t = peek(s);\n if (t.kind === 'punct' && t.value === value) {\n s.pos++;\n return true;\n }\n return false;\n};\n\nconst skipBalancedGroup = (s: ParserState, open: '(' | '[', close: ')' | ']'): void => {\n expectPunct(s, open);\n const stack: Array<'(' | '['> = [open];\n while (stack.length > 0) {\n const t = advance(s);\n if (!t || t.kind === 'eof') {\n throw new Error(`Unterminated \"${open}${close}\" group in SSR expression`);\n }\n if (t.kind !== 'punct') continue;\n if (t.value === '(' || t.value === '[') {\n stack.push(t.value);\n continue;\n }\n if (t.value === ')' || t.value === ']') {\n const current = stack[stack.length - 1];\n const expected = current === '(' ? ')' : ']';\n if (t.value !== expected) {\n throw new Error(`Mismatched \"${current}${expected}\" group in SSR expression`);\n }\n stack.pop();\n }\n }\n};\n\nconst skipShortCircuitedChainTarget = (s: ParserState): void => {\n const next = peek(s);\n if (next.kind === 'punct' && next.value === '[') {\n skipBalancedGroup(s, '[', ']');\n return;\n }\n if (next.kind === 'punct' && next.value === '(') {\n skipBalancedGroup(s, '(', ')');\n return;\n }\n if (next.kind === 'ident') {\n s.pos++;\n return;\n }\n throw new Error('Invalid optional chain in SSR expression');\n};\n\nconst skipShortCircuitedChainRemainder = (s: ParserState): void => {\n while (true) {\n const t = peek(s);\n if (t.kind !== 'punct') break;\n if (t.value === '.') {\n s.pos++;\n const id = advance(s);\n if (id.kind !== 'ident') {\n throw new Error('Expected identifier after \".\"');\n }\n continue;\n }\n if (t.value === '[') {\n skipBalancedGroup(s, '[', ']');\n continue;\n }\n if (t.value === '(') {\n skipBalancedGroup(s, '(', ')');\n continue;\n }\n if (t.value === '?.') {\n s.pos++;\n skipShortCircuitedChainTarget(s);\n continue;\n }\n break;\n }\n};\n\n/**\n * Advances through expression tokens without evaluating them.\n *\n * Mirrors the `parsePrimary()` / `parsePostfix()` / `parseUnary()` /\n * `parseExpression()` hierarchy so `parseExpression()` can preserve JavaScript\n * short-circuit semantics for `&&`, `||`, `??`, and ternaries while still\n * leaving the parser in the correct token position.\n *\n * @internal\n */\nconst skipPrimary = (s: ParserState): void => {\n const t = advance(s);\n if (!t || t.kind === 'eof') {\n throw new Error('Unexpected end of SSR expression');\n }\n if (t.kind === 'number' || t.kind === 'string' || t.kind === 'ident') {\n return;\n }\n if (t.kind === 'punct' && t.value === '(') {\n skipExpression(s, 0);\n expectPunct(s, ')');\n return;\n }\n throw new Error(`Unexpected token \"${t.value}\" in SSR expression`);\n};\n\n/** Skips a function-call argument list without evaluating any argument expressions. */\nconst skipCall = (s: ParserState): void => {\n expectPunct(s, '(');\n if (!matchPunct(s, ')')) {\n while (true) {\n skipExpression(s, 0);\n if (matchPunct(s, ',')) continue;\n expectPunct(s, ')');\n break;\n }\n }\n};\n\n/** Skips postfix chains such as member access, indexing, optional chaining, and calls. */\nconst skipPostfix = (s: ParserState): void => {\n skipPrimary(s);\n\n while (true) {\n const t = peek(s);\n if (t.kind !== 'punct') break;\n\n if (t.value === '.') {\n s.pos++;\n const id = advance(s);\n if (id.kind !== 'ident') {\n throw new Error('Expected identifier after \".\"');\n }\n continue;\n }\n\n if (t.value === '?.') {\n s.pos++;\n skipShortCircuitedChainTarget(s);\n continue;\n }\n\n if (t.value === '[') {\n s.pos++;\n skipExpression(s, 0);\n expectPunct(s, ']');\n continue;\n }\n\n if (t.value === '(') {\n skipCall(s);\n continue;\n }\n\n break;\n }\n};\n\n/** Skips unary operators before delegating to the postfix-skipping parser path. */\nconst skipUnary = (s: ParserState): void => {\n const t = peek(s);\n if (t.kind === 'punct' && (t.value === '!' || t.value === '-' || t.value === '+')) {\n s.pos++;\n skipUnary(s);\n return;\n }\n if (t.kind === 'ident' && t.value === 'typeof') {\n s.pos++;\n skipUnary(s);\n return;\n }\n skipPostfix(s);\n};\n\n/** Skips a full expression subtree while preserving operator precedence and token position. */\nconst skipExpression = (s: ParserState, minPrec = 0): void => {\n skipUnary(s);\n\n while (true) {\n const t = peek(s);\n if (t.kind !== 'punct') break;\n\n if (t.value === '?' && minPrec <= 0) {\n s.pos++;\n skipExpression(s, 0);\n expectPunct(s, ':');\n skipExpression(s, 0);\n continue;\n }\n\n const prec = BIN_PRECEDENCE[t.value];\n if (prec === undefined || prec < minPrec) break;\n s.pos++;\n skipExpression(s, prec + 1);\n }\n};\n\nconst lookupIdent = (s: ParserState, name: string): unknown => {\n if (name === 'true') return true;\n if (name === 'false') return false;\n if (name === 'null') return null;\n if (name === 'undefined') return undefined;\n if (isPrototypePollutionKey(name)) return undefined;\n return unwrap((s.context as Record<string, unknown>)[name]);\n};\n\nconst safeMember = (obj: unknown, key: PropertyKey): unknown => {\n if (obj == null) return undefined;\n if (typeof key === 'string' && isPrototypePollutionKey(key)) return undefined;\n return (obj as Record<PropertyKey, unknown>)[key];\n};\n\n// Pratt-parser precedence table for binary operators.\nconst BIN_PRECEDENCE: Record<string, number> = {\n '||': 1,\n '??': 1,\n '&&': 2,\n '==': 3,\n '!=': 3,\n '===': 3,\n '!==': 3,\n '<': 4,\n '<=': 4,\n '>': 4,\n '>=': 4,\n '+': 5,\n '-': 5,\n '*': 6,\n '/': 6,\n '%': 6,\n};\n\nconst parseExpression = (s: ParserState, minPrec = 0): unknown => {\n let left = parseUnary(s);\n\n while (true) {\n const t = peek(s);\n if (t.kind !== 'punct') break;\n\n // Ternary\n if (t.value === '?' && minPrec <= 0) {\n s.pos++;\n if (left) {\n const consequent = parseExpression(s, 0);\n expectPunct(s, ':');\n skipExpression(s, 0);\n left = consequent;\n } else {\n skipExpression(s, 0);\n expectPunct(s, ':');\n left = parseExpression(s, 0);\n }\n continue;\n }\n\n const prec = BIN_PRECEDENCE[t.value];\n if (prec === undefined || prec < minPrec) break;\n s.pos++;\n if (t.value === '&&') {\n if (!left) {\n skipExpression(s, prec + 1);\n } else {\n left = parseExpression(s, prec + 1);\n }\n continue;\n }\n if (t.value === '||') {\n if (left) {\n skipExpression(s, prec + 1);\n } else {\n left = parseExpression(s, prec + 1);\n }\n continue;\n }\n if (t.value === '??') {\n if (left !== null && left !== undefined) {\n skipExpression(s, prec + 1);\n } else {\n left = parseExpression(s, prec + 1);\n }\n continue;\n }\n const right = parseExpression(s, prec + 1);\n left = applyBinary(t.value, left, right);\n }\n\n return left;\n};\n\nconst applyBinary = (op: string, l: unknown, r: unknown): unknown => {\n switch (op) {\n case '||':\n return l || r;\n case '&&':\n return l && r;\n case '??':\n return l ?? r;\n case '==':\n // Intentional loose equality: the SSR expression grammar mirrors the\n // JavaScript operators users write in templates. `===` and `!==` are\n // available for strict comparisons.\n\n return l == r;\n case '!=':\n // Intentional loose inequality (see `==` note above).\n\n return l != r;\n case '===':\n return l === r;\n case '!==':\n return l !== r;\n case '<':\n return (l as number) < (r as number);\n case '<=':\n return (l as number) <= (r as number);\n case '>':\n return (l as number) > (r as number);\n case '>=':\n return (l as number) >= (r as number);\n case '+':\n // String concat for either operand is a string\n if (typeof l === 'string' || typeof r === 'string') {\n return String(l ?? '') + String(r ?? '');\n }\n return (l as number) + (r as number);\n case '-':\n return (l as number) - (r as number);\n case '*':\n return (l as number) * (r as number);\n case '/':\n return (l as number) / (r as number);\n case '%':\n return (l as number) % (r as number);\n default:\n throw new Error(`Unsupported binary operator \"${op}\"`);\n }\n};\n\nconst parseUnary = (s: ParserState): unknown => {\n const t = peek(s);\n if (t.kind === 'punct') {\n if (t.value === '!') {\n s.pos++;\n return !parseUnary(s);\n }\n if (t.value === '-') {\n s.pos++;\n return -(parseUnary(s) as number);\n }\n if (t.value === '+') {\n s.pos++;\n return +(parseUnary(s) as number);\n }\n }\n if (t.kind === 'ident' && t.value === 'typeof') {\n s.pos++;\n return typeof parseUnary(s);\n }\n return parsePostfix(s);\n};\n\nconst parsePostfix = (s: ParserState): unknown => {\n let value = parsePrimary(s);\n let thisArg: unknown = undefined;\n\n while (true) {\n const t = peek(s);\n if (t.kind !== 'punct') break;\n\n if (t.value === '.') {\n s.pos++;\n const id = advance(s);\n if (id.kind !== 'ident') {\n throw new Error('Expected identifier after \".\"');\n }\n thisArg = value;\n value = safeMember(value, id.value);\n continue;\n }\n\n if (t.value === '?.') {\n s.pos++;\n if (value == null) {\n skipShortCircuitedChainTarget(s);\n skipShortCircuitedChainRemainder(s);\n value = undefined;\n thisArg = undefined;\n continue;\n }\n const next = peek(s);\n if (next.kind === 'punct' && next.value === '[') {\n s.pos++;\n const receiver = value;\n const key = parseExpression(s, 0);\n expectPunct(s, ']');\n thisArg = receiver;\n value = safeMember(value, key as PropertyKey);\n } else if (next.kind === 'punct' && next.value === '(') {\n value = parseCall(s, value, thisArg);\n thisArg = undefined;\n } else if (next.kind === 'ident') {\n s.pos++;\n thisArg = value;\n value = safeMember(value, next.value);\n } else {\n throw new Error('Invalid optional chain in SSR expression');\n }\n continue;\n }\n\n if (t.value === '[') {\n s.pos++;\n const receiver = value;\n const key = parseExpression(s, 0);\n expectPunct(s, ']');\n thisArg = receiver;\n value = safeMember(value, key as PropertyKey);\n continue;\n }\n\n if (t.value === '(') {\n // Function call\n value = parseCall(s, value, thisArg);\n thisArg = undefined;\n continue;\n }\n\n break;\n }\n\n return value;\n};\n\nconst parseCall = (s: ParserState, callee: unknown, thisArg: unknown): unknown => {\n expectPunct(s, '(');\n const args: unknown[] = [];\n if (!matchPunct(s, ')')) {\n while (true) {\n args.push(parseExpression(s, 0));\n if (matchPunct(s, ',')) continue;\n expectPunct(s, ')');\n break;\n }\n }\n if (typeof callee !== 'function') {\n return undefined;\n }\n return (callee as (...a: unknown[]) => unknown).apply(thisArg, args);\n};\n\nconst parsePrimary = (s: ParserState): unknown => {\n const t = advance(s);\n if (t.kind === 'number') {\n return Number(t.value);\n }\n if (t.kind === 'string') {\n return t.value;\n }\n if (t.kind === 'ident') {\n return lookupIdent(s, t.value);\n }\n if (t.kind === 'punct' && t.value === '(') {\n const value = parseExpression(s, 0);\n expectPunct(s, ')');\n return value;\n }\n throw new Error(`Unexpected token \"${t.value}\" in SSR expression`);\n};\n\n/**\n * Evaluates a tightly scoped expression against a binding context.\n *\n * Returns `undefined` when the expression cannot be parsed or evaluated.\n * This matches the behaviour of the previous `new Function()`-based fallback\n * but never invokes dynamic code generation.\n *\n * @param expression - Expression source.\n * @param context - Binding context whose top-level signal/computed values are\n * automatically unwrapped.\n *\n * @internal\n */\nexport const evaluateExpression = <T = unknown>(expression: string, context: BindingContext): T => {\n const trimmed = expression.trim();\n if (trimmed === '') return undefined as T;\n\n try {\n const tokens = tokenize(trimmed);\n const state: ParserState = { tokens, pos: 0, context };\n const value = parseExpression(state, 0);\n if (peek(state).kind !== 'eof') {\n // Unexpected trailing tokens — fall back to undefined.\n return undefined as T;\n }\n return value as T;\n } catch {\n return undefined as T;\n }\n};\n","/**\n * Minimal, runtime-agnostic HTML parser for the SSR renderer.\n *\n * This is intentionally a small, linear scanner rather than a full HTML5\n * tokenizer. It is sufficient for templates authored against the `bQuery`\n * directive vocabulary (HTML fragments, common void/raw elements, attributes)\n * and lets the SSR pipeline run on Bun, Deno and Node without depending on a\n * `DOMParser` polyfill.\n *\n * Output: a tiny virtual node tree (`SSRNode`) compatible with the pluggable\n * DOM adapter API used by `renderer.ts`.\n *\n * @module bquery/ssr\n * @internal\n */\n\nconst VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n\nconst RAW_TEXT_ELEMENTS = new Set(['script', 'style', 'textarea', 'title']);\n\n/** A DOM-free node structure produced by `parseTemplate()`. */\nexport type SSRNode = SSRElement | SSRText | SSRComment | SSRDocumentFragment;\n\nexport interface SSRElement {\n type: 'element';\n tag: string;\n attributes: Record<string, string>;\n /** Order-preserving attribute list (so output is deterministic). */\n attributeOrder: string[];\n children: SSRNode[];\n /** Whether this element should be serialised as a void element. */\n void: boolean;\n /** Whether the children are raw (e.g. `<script>` content). */\n raw: boolean;\n}\n\nexport interface SSRText {\n type: 'text';\n value: string;\n}\n\nexport interface SSRComment {\n type: 'comment';\n value: string;\n}\n\nexport interface SSRDocumentFragment {\n type: 'fragment';\n children: SSRNode[];\n}\n\nconst HTML_ENTITIES: Record<string, string> = {\n amp: '&',\n lt: '<',\n gt: '>',\n quot: '\"',\n apos: \"'\",\n nbsp: '\\u00a0',\n};\n\n/**\n * Decodes the named/numeric HTML entities the SSR parser actually needs.\n * Anything else is preserved verbatim.\n */\nexport const decodeEntities = (input: string): string => {\n if (input.indexOf('&') === -1) return input;\n return input.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g, (match, code: string) => {\n if (code[0] === '#') {\n const isHex = code[1] === 'x' || code[1] === 'X';\n const num = parseInt(code.slice(isHex ? 2 : 1), isHex ? 16 : 10);\n if (Number.isFinite(num)) {\n try {\n return String.fromCodePoint(num);\n } catch {\n return match;\n }\n }\n return match;\n }\n const name = code.toLowerCase();\n return HTML_ENTITIES[name] ?? match;\n });\n};\n\ninterface ParseState {\n src: string;\n pos: number;\n}\n\nconst isWs = (ch: string): boolean =>\n ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r' || ch === '\\f';\n\nconst skipWs = (s: ParseState): void => {\n while (s.pos < s.src.length && isWs(s.src[s.pos])) s.pos++;\n};\n\nconst readUntil = (s: ParseState, stop: string): string => {\n const start = s.pos;\n const idx = s.src.indexOf(stop, start);\n if (idx === -1) {\n s.pos = s.src.length;\n return s.src.slice(start);\n }\n s.pos = idx;\n return s.src.slice(start, idx);\n};\n\nconst readTagName = (s: ParseState): string => {\n const start = s.pos;\n while (s.pos < s.src.length) {\n const ch = s.src[s.pos];\n if (isWs(ch) || ch === '>' || ch === '/') break;\n s.pos++;\n }\n return s.src.slice(start, s.pos).toLowerCase();\n};\n\nconst readAttrName = (s: ParseState): string => {\n const start = s.pos;\n while (s.pos < s.src.length) {\n const ch = s.src[s.pos];\n if (isWs(ch) || ch === '=' || ch === '>' || ch === '/') break;\n s.pos++;\n }\n return s.src.slice(start, s.pos);\n};\n\nconst readAttrValue = (s: ParseState): string => {\n const ch = s.src[s.pos];\n if (ch === '\"' || ch === \"'\") {\n const quote = ch;\n s.pos++;\n const start = s.pos;\n while (s.pos < s.src.length && s.src[s.pos] !== quote) s.pos++;\n const value = s.src.slice(start, s.pos);\n if (s.pos < s.src.length) s.pos++; // consume closing quote\n return decodeEntities(value);\n }\n // Unquoted\n const start = s.pos;\n while (s.pos < s.src.length) {\n const c = s.src[s.pos];\n if (isWs(c) || c === '>' || (c === '/' && s.src[s.pos + 1] === '>')) break;\n s.pos++;\n }\n return decodeEntities(s.src.slice(start, s.pos));\n};\n\nconst parseAttributes = (\n s: ParseState\n): { attributes: Record<string, string>; order: string[]; selfClose: boolean } => {\n const attributes: Record<string, string> = Object.create(null) as Record<string, string>;\n const order: string[] = [];\n let selfClose = false;\n\n while (s.pos < s.src.length) {\n skipWs(s);\n const ch = s.src[s.pos];\n if (ch === '>') {\n s.pos++;\n break;\n }\n if (ch === '/') {\n s.pos++;\n skipWs(s);\n if (s.src[s.pos] === '>') {\n selfClose = true;\n s.pos++;\n break;\n }\n continue;\n }\n if (s.pos >= s.src.length) break;\n\n const rawName = readAttrName(s);\n if (!rawName) {\n // Defensive: skip ahead to the next whitespace, '/' or '>' to avoid\n // pathological 1-char-per-iteration advancement on malformed input.\n while (s.pos < s.src.length) {\n const c = s.src[s.pos];\n if (isWs(c) || c === '>' || c === '/') break;\n s.pos++;\n }\n continue;\n }\n const name = rawName.toLowerCase();\n skipWs(s);\n let value = '';\n if (s.src[s.pos] === '=') {\n s.pos++;\n skipWs(s);\n value = readAttrValue(s);\n }\n if (!(name in attributes)) {\n order.push(name);\n }\n attributes[name] = value;\n }\n\n return { attributes, order, selfClose };\n};\n\n/**\n * Parses an HTML template string into a virtual node tree without depending\n * on a DOM implementation. The parser is intentionally permissive: it does\n * not validate nesting, but it preserves attribute order and never throws on\n * malformed input.\n */\nexport const parseTemplate = (template: string): SSRDocumentFragment => {\n const s: ParseState = { src: template, pos: 0 };\n const root: SSRDocumentFragment = { type: 'fragment', children: [] };\n // Open-element stack so children attach to the correct parent.\n const stack: Array<SSRElement | SSRDocumentFragment> = [root];\n\n const top = (): SSRElement | SSRDocumentFragment => stack[stack.length - 1];\n\n while (s.pos < s.src.length) {\n if (s.src[s.pos] === '<') {\n // Comment\n if (s.src.startsWith('<!--', s.pos)) {\n s.pos += 4;\n const end = s.src.indexOf('-->', s.pos);\n const value = end === -1 ? s.src.slice(s.pos) : s.src.slice(s.pos, end);\n s.pos = end === -1 ? s.src.length : end + 3;\n top().children.push({ type: 'comment', value });\n continue;\n }\n // Doctype/processing instruction — skip silently\n if (s.src.startsWith('<!', s.pos) || s.src.startsWith('<?', s.pos)) {\n const end = s.src.indexOf('>', s.pos);\n s.pos = end === -1 ? s.src.length : end + 1;\n continue;\n }\n\n // Closing tag\n if (s.src[s.pos + 1] === '/') {\n s.pos += 2;\n const name = readTagName(s);\n const end = s.src.indexOf('>', s.pos);\n s.pos = end === -1 ? s.src.length : end + 1;\n // Pop the matching element if found, otherwise ignore.\n for (let i = stack.length - 1; i > 0; i--) {\n const node = stack[i];\n if (node.type === 'element' && node.tag === name) {\n stack.length = i;\n break;\n }\n }\n continue;\n }\n\n // Opening tag\n if (s.pos + 1 < s.src.length && /[a-zA-Z]/.test(s.src[s.pos + 1])) {\n s.pos++;\n const tag = readTagName(s);\n const { attributes, order, selfClose } = parseAttributes(s);\n const isVoid = VOID_ELEMENTS.has(tag);\n const element: SSRElement = {\n type: 'element',\n tag,\n attributes,\n attributeOrder: order,\n children: [],\n void: isVoid,\n raw: RAW_TEXT_ELEMENTS.has(tag),\n };\n top().children.push(element);\n\n if (isVoid || selfClose) {\n // Don't push onto stack.\n continue;\n }\n\n if (element.raw) {\n // Raw-text element: read until matching close tag.\n const closeTag = `</${tag}`;\n const start = s.pos;\n const lower = s.src.toLowerCase();\n const idx = lower.indexOf(closeTag, start);\n const rawText = idx === -1 ? s.src.slice(start) : s.src.slice(start, idx);\n if (rawText) {\n element.children.push({ type: 'text', value: rawText });\n }\n if (idx === -1) {\n s.pos = s.src.length;\n } else {\n s.pos = idx;\n // Consume the </tag>\n const close = s.src.indexOf('>', s.pos);\n s.pos = close === -1 ? s.src.length : close + 1;\n }\n continue;\n }\n\n stack.push(element);\n continue;\n }\n\n top().children.push({ type: 'text', value: '<' });\n s.pos++;\n continue;\n }\n\n // Plain text\n const text = readUntil(s, '<');\n if (text) {\n top().children.push({ type: 'text', value: decodeEntities(text) });\n }\n }\n\n return root;\n};\n\nconst escapeText = (value: string): string =>\n value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n\nconst escapeAttr = (value: string): string =>\n value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"');\n\n/** Serialises a virtual node tree to an HTML string. */\nexport const serializeTree = (node: SSRNode): string => {\n if (node.type === 'text') return escapeText(node.value);\n if (node.type === 'comment') return `<!--${node.value}-->`;\n if (node.type === 'fragment') {\n let out = '';\n for (const child of node.children) out += serializeTree(child);\n return out;\n }\n\n const el = node;\n let attrs = '';\n for (const name of el.attributeOrder) {\n const value = el.attributes[name];\n attrs += ` ${name}=\"${escapeAttr(value)}\"`;\n }\n\n if (el.void) {\n return `<${el.tag}${attrs}>`;\n }\n\n let inner = '';\n if (el.raw) {\n // Raw-text elements: don't escape children, they're already raw text.\n for (const child of el.children) {\n if (child.type === 'text') inner += child.value;\n }\n } else {\n for (const child of el.children) inner += serializeTree(child);\n }\n\n return `<${el.tag}${attrs}>${inner}</${el.tag}>`;\n};\n\n/** Recursively clones a virtual node (used by `bq-for`). */\nexport const cloneNode = (node: SSRNode): SSRNode => {\n if (node.type === 'element') {\n return {\n type: 'element',\n tag: node.tag,\n attributes: { ...node.attributes },\n attributeOrder: [...node.attributeOrder],\n children: node.children.map(cloneNode),\n void: node.void,\n raw: node.raw,\n };\n }\n if (node.type === 'fragment') {\n return { type: 'fragment', children: node.children.map(cloneNode) };\n }\n if (node.type === 'text') return { type: 'text', value: node.value };\n return { type: 'comment', value: node.value };\n};\n","/**\n * DOM-free SSR renderer.\n *\n * Operates on the virtual node tree produced by `html-parser.ts` and\n * evaluates `bq-*` directives without depending on any browser DOM API.\n * Runs unmodified on Bun, Deno and Node and is the default backend used by\n * `renderToString()` whenever the global `DOMParser` is not configured to\n * take precedence.\n *\n * @module bquery/ssr\n * @internal\n */\n\nimport {\n DANGEROUS_ATTR_PREFIXES,\n DANGEROUS_PROTOCOLS,\n DANGEROUS_TAGS,\n DEFAULT_ALLOWED_ATTRIBUTES,\n DEFAULT_ALLOWED_TAGS,\n RESERVED_IDS,\n} from '../security/constants';\nimport type { BindingContext } from '../view/types';\nimport { evaluateExpression } from './expression';\nimport { cheapHash, collectDirectiveSignatureFromAttrs, HYDRATION_HASH_ATTR } from './hash';\nimport {\n cloneNode,\n parseTemplate,\n serializeTree,\n type SSRElement,\n type SSRNode,\n} from './html-parser';\n\nconst isUnsafeUrlAttribute = (name: string): boolean => {\n const n = name.toLowerCase();\n return (\n n === 'href' ||\n n === 'src' ||\n n === 'xlink:href' ||\n n === 'formaction' ||\n n === 'action' ||\n n === 'poster' ||\n n === 'background' ||\n n === 'cite' ||\n n === 'data'\n );\n};\n\nconst sanitizeUrlForProtocolCheck = (value: string): string =>\n value\n .trim()\n .replace(/[\\u0000-\\u001F\\u007F]+/g, '')\n .replace(/[\\u200B-\\u200D\\uFEFF\\u2028\\u2029]+/g, '')\n .replace(/\\\\u[\\da-fA-F]{4}/g, '')\n .replace(/\\s+/g, '')\n .toLowerCase();\n\nconst isUnsafeUrlValue = (value: string): boolean => {\n const normalized = sanitizeUrlForProtocolCheck(value);\n return DANGEROUS_PROTOCOLS.some((protocol) => normalized.startsWith(protocol));\n};\n\nconst URL_PROTOCOL_PATTERN = /^[a-zA-Z][a-zA-Z0-9+.-]*:/;\nconst REL_SPLIT_PATTERN = /\\s+/;\n\nconst isAllowedHtmlAttribute = (name: string): boolean => {\n const lowerName = name.toLowerCase();\n\n for (const prefix of DANGEROUS_ATTR_PREFIXES) {\n if (lowerName.startsWith(prefix)) return false;\n }\n\n if (lowerName.startsWith('data-')) return true;\n if (lowerName.startsWith('aria-')) return true;\n\n return DEFAULT_ALLOWED_ATTRIBUTES.has(lowerName);\n};\n\nconst isSafeHtmlIdOrName = (value: string): boolean =>\n !RESERVED_IDS.has(value.toLowerCase().trim());\n\nconst isExternalHtmlUrl = (url: string): boolean => {\n try {\n const trimmedUrl = url.trim();\n if (trimmedUrl.startsWith('//')) return true;\n\n const lowerUrl = trimmedUrl.toLowerCase();\n if (!lowerUrl.startsWith('http://') && !lowerUrl.startsWith('https://')) {\n if (!URL_PROTOCOL_PATTERN.test(trimmedUrl)) {\n return false;\n }\n return true;\n }\n\n if (typeof window === 'undefined' || !window.location) {\n return true;\n }\n\n const urlObj = new URL(trimmedUrl, window.location.href);\n return urlObj.origin !== window.location.origin;\n } catch {\n return true;\n }\n};\n\ninterface RenderOpts {\n prefix: string;\n stripDirectives: boolean;\n /** Whether to add `data-bq-h` mismatch hashes to elements with directives. */\n annotateHydration: boolean;\n}\n\n/**\n * `cheapHash` and `HYDRATION_HASH_ATTR` are imported from `./hash` so the\n * server-side annotation and client-side verifier stay in lock-step.\n */\n\nconst setClass = (el: SSRElement, cls: string): void => {\n if (!cls) return;\n const existing = el.attributes['class'];\n const merged = existing ? `${existing} ${cls}` : cls;\n if (!('class' in el.attributes)) el.attributeOrder.push('class');\n el.attributes['class'] = merged;\n};\n\nconst setStyle = (el: SSRElement, declarations: Record<string, unknown>): void => {\n let css = el.attributes['style'] ?? '';\n for (const [prop, val] of Object.entries(declarations)) {\n if (val === undefined || val === null || val === false) continue;\n const cssProp = prop.replace(/([A-Z])/g, '-$1').toLowerCase();\n if (css && !css.endsWith(';')) css += '; ';\n css += `${cssProp}: ${String(val)};`;\n }\n if (!('style' in el.attributes)) el.attributeOrder.push('style');\n el.attributes['style'] = css;\n};\n\nconst removeAttr = (el: SSRElement, name: string): void => {\n if (name in el.attributes) {\n delete el.attributes[name];\n const idx = el.attributeOrder.indexOf(name);\n if (idx !== -1) el.attributeOrder.splice(idx, 1);\n }\n};\n\nconst setAttr = (el: SSRElement, name: string, value: string): void => {\n if (!(name in el.attributes)) el.attributeOrder.push(name);\n el.attributes[name] = value;\n};\n\nconst collectDirectiveSignature = (el: SSRElement, prefix: string): string =>\n collectDirectiveSignatureFromAttrs(el.attributeOrder, el.attributes, prefix);\n\nconst parseForExpression = (\n expression: string\n): { itemName: string; indexName?: string; listExpr: string } | null => {\n const match = expression.match(/^\\(?(\\w+)(?:\\s*,\\s*(\\w+))?\\)?\\s+in\\s+(\\S.*)$/);\n if (!match) return null;\n return {\n itemName: match[1],\n indexName: match[2] || undefined,\n listExpr: match[3].trim(),\n };\n};\n\nconst stripDirectiveAttributes = (node: SSRNode, prefix: string): void => {\n if (node.type !== 'element') {\n if (node.type === 'fragment') {\n for (const child of node.children) stripDirectiveAttributes(child, prefix);\n }\n return;\n }\n for (const name of [...node.attributeOrder]) {\n if (name.startsWith(`${prefix}-`) || name.startsWith(':')) {\n removeAttr(node, name);\n }\n }\n for (const child of node.children) stripDirectiveAttributes(child, prefix);\n};\n\nconst setText = (el: SSRElement, value: string): void => {\n el.children = [{ type: 'text', value }];\n};\n\nconst setHtml = (el: SSRElement, raw: string): void => {\n // Parse the sanitized HTML and replace children with the resulting tree.\n const fragment = parseTemplate(raw);\n el.children = fragment.children;\n};\n\nexport const sanitizeHtmlForSSR = (raw: string): string => {\n const sanitizeNode = (node: SSRNode): SSRNode | null => {\n if (node.type === 'fragment') {\n node.children = node.children.flatMap((child) => {\n const sanitized = sanitizeNode(child);\n return sanitized ? [sanitized] : [];\n });\n return node;\n }\n\n if (node.type !== 'element') {\n return node;\n }\n\n if (DANGEROUS_TAGS.has(node.tag) || !DEFAULT_ALLOWED_TAGS.has(node.tag)) {\n return null;\n }\n\n for (const name of [...node.attributeOrder]) {\n const value = node.attributes[name];\n const attrName = name.toLowerCase();\n\n if (!isAllowedHtmlAttribute(attrName)) {\n removeAttr(node, name);\n continue;\n }\n\n if ((attrName === 'id' || attrName === 'name') && !isSafeHtmlIdOrName(value)) {\n removeAttr(node, name);\n continue;\n }\n\n if ((attrName === 'href' || attrName === 'src') && isUnsafeUrlValue(value)) {\n removeAttr(node, name);\n continue;\n }\n }\n\n if (node.tag === 'a') {\n const href = node.attributes.href;\n const target = node.attributes.target;\n const hasTargetBlank = target?.toLowerCase() === '_blank';\n const isExternal = href ? isExternalHtmlUrl(href) : false;\n\n if (hasTargetBlank || isExternal) {\n const relValues = new Set(\n (node.attributes.rel ?? '').trim().split(REL_SPLIT_PATTERN).filter(Boolean)\n );\n relValues.add('noopener');\n relValues.add('noreferrer');\n setAttr(node, 'rel', Array.from(relValues).join(' '));\n }\n }\n\n node.children = node.children.flatMap((child) => {\n const sanitized = sanitizeNode(child);\n return sanitized ? [sanitized] : [];\n });\n\n return node;\n };\n\n return serializeTree(sanitizeNode(parseTemplate(raw)) ?? { type: 'fragment', children: [] });\n};\n\nconst evaluateChildren = (parent: SSRElement, context: BindingContext, opts: RenderOpts): void => {\n const out: SSRNode[] = [];\n for (const child of parent.children) {\n if (child.type !== 'element') {\n out.push(child);\n continue;\n }\n const result = evaluateElement(child, context, opts);\n if (result === null) continue;\n if (Array.isArray(result)) {\n for (const r of result) out.push(r);\n } else {\n out.push(result);\n }\n }\n parent.children = out;\n};\n\n/**\n * Evaluates directives on a single element. Returns:\n * - `null` to remove the element (e.g. `bq-if` falsy);\n * - an array to replace the element with N siblings (e.g. `bq-for`);\n * - the element itself (possibly mutated) otherwise.\n */\nconst evaluateElement = (\n el: SSRElement,\n context: BindingContext,\n opts: RenderOpts\n): SSRNode | SSRNode[] | null => {\n const { prefix } = opts;\n\n // bq-for: handled before bq-if/etc. so each clone is processed independently.\n const forExpr = el.attributes[`${prefix}-for`];\n if (forExpr !== undefined) {\n const parsed = parseForExpression(forExpr);\n if (!parsed) {\n removeAttr(el, `${prefix}-for`);\n }\n if (parsed) {\n const list = evaluateExpression<unknown>(parsed.listExpr, context);\n if (!Array.isArray(list)) return null;\n const out: SSRNode[] = [];\n for (let i = 0; i < list.length; i++) {\n const clone = cloneNode(el) as SSRElement;\n removeAttr(clone, `${prefix}-for`);\n removeAttr(clone, `${prefix}-key`);\n removeAttr(clone, ':key');\n const childCtx: BindingContext = {\n ...context,\n [parsed.itemName]: list[i],\n };\n if (parsed.indexName) childCtx[parsed.indexName] = i;\n const result = evaluateElement(clone, childCtx, opts);\n if (result === null) continue;\n if (Array.isArray(result)) out.push(...result);\n else out.push(result);\n }\n return out;\n }\n }\n\n // Capture directive signature for hydration mismatch detection (before stripping).\n const signature = opts.annotateHydration ? collectDirectiveSignature(el, prefix) : '';\n\n // bq-if\n const ifExpr = el.attributes[`${prefix}-if`];\n if (ifExpr !== undefined) {\n const cond = evaluateExpression<unknown>(ifExpr, context);\n if (!cond) return null;\n }\n\n // bq-show\n const showExpr = el.attributes[`${prefix}-show`];\n if (showExpr !== undefined) {\n const cond = evaluateExpression<unknown>(showExpr, context);\n if (!cond) {\n setStyle(el, { display: 'none' });\n }\n }\n\n // bq-text\n const textExpr = el.attributes[`${prefix}-text`];\n if (textExpr !== undefined) {\n const value = evaluateExpression<unknown>(textExpr, context);\n setText(el, String(value ?? ''));\n }\n\n // bq-html\n const htmlExpr = el.attributes[`${prefix}-html`];\n if (htmlExpr !== undefined) {\n const value = evaluateExpression<unknown>(htmlExpr, context);\n setHtml(el, sanitizeHtmlForSSR(String(value ?? '')));\n }\n\n // bq-class\n const classExpr = el.attributes[`${prefix}-class`];\n if (classExpr !== undefined) {\n const trimmed = classExpr.trim();\n if (trimmed.startsWith('{')) {\n const inner = trimmed.slice(1, -1);\n const pairs = inner.split(',');\n for (const pair of pairs) {\n const colon = pair.indexOf(':');\n if (colon < 0) continue;\n const name = pair\n .slice(0, colon)\n .trim()\n .replace(/^['\"]|['\"]$/g, '');\n const cond = evaluateExpression<unknown>(pair.slice(colon + 1), context);\n if (cond) setClass(el, name);\n }\n } else {\n const result = evaluateExpression<unknown>(classExpr, context);\n if (typeof result === 'string') {\n for (const cls of result.split(/\\s+/).filter(Boolean)) setClass(el, cls);\n } else if (Array.isArray(result)) {\n for (const cls of result) {\n if (typeof cls === 'string' && cls) setClass(el, cls);\n }\n } else if (result && typeof result === 'object') {\n for (const [name, cond] of Object.entries(result as Record<string, unknown>)) {\n if (cond) setClass(el, name);\n }\n }\n }\n }\n\n // bq-style\n const styleExpr = el.attributes[`${prefix}-style`];\n if (styleExpr !== undefined) {\n const result = evaluateExpression<unknown>(styleExpr, context);\n if (result && typeof result === 'object') {\n setStyle(el, result as Record<string, unknown>);\n }\n }\n\n // bq-bind:*\n for (const name of [...el.attributeOrder]) {\n if (!name.startsWith(`${prefix}-bind:`)) continue;\n const attrName = name.slice(`${prefix}-bind:`.length);\n const value = evaluateExpression<unknown>(el.attributes[name], context);\n if (value === false || value == null) {\n removeAttr(el, attrName);\n } else if (value === true) {\n setAttr(el, attrName, '');\n } else {\n setAttr(el, attrName, String(value));\n }\n }\n\n // Drop on*-attributes and unsafe URL attributes for security parity with the\n // legacy serializer.\n for (const name of [...el.attributeOrder]) {\n const n = name.toLowerCase();\n if (n.startsWith('on')) {\n removeAttr(el, name);\n continue;\n }\n if (isUnsafeUrlAttribute(n) && isUnsafeUrlValue(el.attributes[name] ?? '')) {\n removeAttr(el, name);\n }\n }\n\n if (el.tag === 'script') {\n return null;\n }\n\n // Recurse into children\n evaluateChildren(el, context, opts);\n\n if (signature) {\n setAttr(el, HYDRATION_HASH_ATTR, cheapHash(signature));\n }\n\n return el;\n};\n\n/**\n * Renders a template through the DOM-free pipeline.\n *\n * @internal\n */\nexport const renderTemplatePure = (\n template: string,\n data: BindingContext,\n options: { prefix?: string; stripDirectives?: boolean; annotateHydration?: boolean } = {}\n): string => {\n const opts: RenderOpts = {\n prefix: options.prefix ?? 'bq',\n stripDirectives: options.stripDirectives ?? false,\n annotateHydration: options.annotateHydration ?? false,\n };\n\n const fragment = parseTemplate(template);\n evaluateChildren(fragment as unknown as SSRElement, data, opts);\n\n if (opts.stripDirectives) {\n stripDirectiveAttributes(fragment, opts.prefix);\n }\n\n return serializeTree(fragment);\n};\n","/**\n * Shared escaping helpers for SSR inline script payloads and HTML attributes.\n *\n * @module bquery/ssr\n * @internal\n */\n\n/**\n * Escapes a string for safe embedding in an inline `<script>` body.\n * @internal\n */\nexport const escapeForScript = (str: string): string =>\n str\n .replace(/</g, '\\\\u003c')\n .replace(/>/g, '\\\\u003e')\n .replace(/\\//g, '\\\\u002f')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029');\n\n/**\n * Escapes a string for safe embedding in an HTML attribute value.\n * @internal\n */\nexport const escapeForHtmlAttribute = (str: string): string =>\n str.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<').replace(/>/g, '>');\n","/**\n * Store state serialization for SSR.\n *\n * Provides utilities to serialize store state into a `<script>` tag\n * for client-side hydration, and to deserialize state on the client.\n *\n * @module bquery/ssr\n */\n\nimport { getStore, listStores } from '../store/index';\nimport { isPrototypePollutionKey } from '../core/utils/object';\nimport { escapeForHtmlAttribute, escapeForScript } from './escape';\nimport type { DeserializedStoreState, SerializeOptions } from './types';\n\nconst isStoreStateObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst sanitizeHydrationState = (value: Record<string, unknown>): Record<string, unknown> => {\n const sanitized: Record<string, unknown> = {};\n for (const [key, entryValue] of Object.entries(value)) {\n if (isPrototypePollutionKey(key)) continue;\n sanitized[key] = entryValue;\n }\n return sanitized;\n};\n\n/**\n * Result of store state serialization.\n */\nexport type SerializeResult = {\n /** JSON string of the state map */\n stateJson: string;\n /** Complete `<script>` tag ready to embed in HTML */\n scriptTag: string;\n};\n\n/**\n * Serializes the state of registered stores into a JSON string and\n * a `<script>` tag suitable for embedding in server-rendered HTML.\n *\n * The serialized state can be picked up on the client using\n * `deserializeStoreState()` to restore stores to their server-side values.\n *\n * @param options - Serialization options\n * @returns Object with JSON string and ready-to-use script tag\n *\n * @example\n * ```ts\n * import { serializeStoreState } from '@bquery/bquery/ssr';\n * import { createStore } from '@bquery/bquery/store';\n *\n * const store = createStore({\n * id: 'counter',\n * state: () => ({ count: 42 }),\n * });\n *\n * const { scriptTag } = serializeStoreState();\n * // '<script id=\"__BQUERY_STORE_STATE__\">window.__BQUERY_INITIAL_STATE__={\"counter\":{\"count\":42}}</script>'\n * ```\n *\n * @example\n * ```ts\n * // Serialize only specific stores\n * const { scriptTag } = serializeStoreState({ storeIds: ['counter'] });\n * ```\n */\nexport const serializeStoreState = (options: SerializeOptions = {}): SerializeResult => {\n const {\n scriptId = '__BQUERY_STORE_STATE__',\n globalKey = '__BQUERY_INITIAL_STATE__',\n storeIds,\n serialize = JSON.stringify,\n } = options;\n\n if (isPrototypePollutionKey(globalKey)) {\n throw new Error(\n `serializeStoreState: invalid globalKey \"${globalKey}\" - prototype-pollution keys are not allowed.`\n );\n }\n\n if (isPrototypePollutionKey(scriptId)) {\n throw new Error(\n `serializeStoreState: invalid scriptId \"${scriptId}\" - prototype-pollution keys are not allowed.`\n );\n }\n\n const ids = storeIds ?? listStores();\n const stateMap = Object.create(null) as Record<string, Record<string, unknown>>;\n\n for (const id of ids) {\n if (isPrototypePollutionKey(id)) {\n continue;\n }\n\n const store = getStore<{ $state: Record<string, unknown> }>(id);\n if (store) {\n stateMap[id] = sanitizeHydrationState(store.$state);\n }\n }\n\n const stateJson = serialize(stateMap);\n if (typeof stateJson !== 'string') {\n throw new Error('serializeStoreState: custom serialize function must return a string.');\n }\n\n if (serialize !== JSON.stringify) {\n let parsedStateJson: unknown;\n try {\n parsedStateJson = JSON.parse(stateJson);\n } catch {\n throw new Error('serializeStoreState: custom serialize function returned invalid JSON.');\n }\n\n if (!isStoreStateObject(parsedStateJson)) {\n throw new Error(\n 'serializeStoreState: custom serialize function must return a JSON object string.'\n );\n }\n }\n\n const escapedJson = escapeForScript(stateJson);\n const escapedGlobalKey = escapeForScript(JSON.stringify(globalKey));\n const escapedScriptId = escapeForHtmlAttribute(scriptId);\n const scriptTag = `<script id=\"${escapedScriptId}\">window[${escapedGlobalKey}]=${escapedJson}</script>`;\n\n return { stateJson, scriptTag };\n};\n\n/**\n * Deserializes store state from the global variable set by the SSR script tag.\n *\n * Call this on the client before creating stores to pre-populate them with\n * server-rendered state. After deserialization, the script tag and global\n * variable are cleaned up automatically.\n *\n * @param globalKey - The global variable name where state was serialized\n * @param scriptId - The ID of the SSR script tag to remove after hydration\n * @returns The deserialized state map, or an empty object if not found\n *\n * @example\n * ```ts\n * import { deserializeStoreState } from '@bquery/bquery/ssr';\n *\n * // Call before creating stores\n * const state = deserializeStoreState();\n * // state = { counter: { count: 42 } }\n * ```\n */\nexport const deserializeStoreState = (\n globalKey = '__BQUERY_INITIAL_STATE__',\n scriptId = '__BQUERY_STORE_STATE__'\n): DeserializedStoreState => {\n if (isPrototypePollutionKey(globalKey)) {\n throw new Error(\n `deserializeStoreState: invalid globalKey \"${globalKey}\" - prototype-pollution keys are not allowed.`\n );\n }\n\n if (isPrototypePollutionKey(scriptId)) {\n throw new Error(\n `deserializeStoreState: invalid scriptId \"${scriptId}\" - prototype-pollution keys are not allowed.`\n );\n }\n\n if (typeof window === 'undefined') {\n return {};\n }\n\n const state = (window as unknown as Record<string, unknown>)[globalKey];\n if (!state) {\n return {};\n }\n\n // Clean up global variable\n try {\n delete (window as unknown as Record<string, unknown>)[globalKey];\n } catch {\n // In strict mode on some environments, delete may fail\n (window as unknown as Record<string, unknown>)[globalKey] = undefined;\n }\n\n // Clean up script tag\n if (typeof document !== 'undefined' && typeof document.getElementById === 'function') {\n const scriptEl = document.getElementById(scriptId);\n if (scriptEl) {\n scriptEl.remove();\n }\n }\n\n if (!isStoreStateObject(state)) {\n return {};\n }\n\n for (const value of Object.values(state)) {\n if (!isStoreStateObject(value)) {\n return {};\n }\n }\n\n const sanitizedStateMap = Object.create(null) as DeserializedStoreState;\n\n for (const [storeId, storeState] of Object.entries(state)) {\n if (isPrototypePollutionKey(storeId) || !isStoreStateObject(storeState)) {\n continue;\n }\n\n sanitizedStateMap[storeId] = sanitizeHydrationState(storeState);\n }\n\n return sanitizedStateMap;\n};\n\n/**\n * Hydrates a store with pre-serialized state from SSR.\n *\n * If the store exists and has a `$patch` method, this applies the\n * deserialized state as a patch. Otherwise, the state is ignored.\n *\n * @param storeId - The store ID to hydrate\n * @param state - The plain state object to apply\n *\n * @example\n * ```ts\n * import { hydrateStore, deserializeStoreState } from '@bquery/bquery/ssr';\n * import { createStore } from '@bquery/bquery/store';\n *\n * // 1. Deserialize state from SSR script tag\n * const ssrState = deserializeStoreState();\n *\n * // 2. Create store (gets initial values from factory)\n * const store = createStore({\n * id: 'counter',\n * state: () => ({ count: 0 }),\n * });\n *\n * // 3. Apply SSR state\n * if (ssrState.counter) {\n * hydrateStore('counter', ssrState.counter);\n * }\n * // store.count is now 42 (from SSR)\n * ```\n */\nexport const hydrateStore = (storeId: string, state: Record<string, unknown>): void => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const store = getStore<{ $patch?: (partial: any) => void }>(storeId);\n if (store && typeof store.$patch === 'function') {\n store.$patch(sanitizeHydrationState(state));\n }\n};\n\n/**\n * Hydrates all stores at once from a deserialized state map.\n *\n * Convenience wrapper that calls `hydrateStore` for each entry in the state map.\n *\n * @param stateMap - Map of store IDs to their state objects\n *\n * @example\n * ```ts\n * import { hydrateStores, deserializeStoreState } from '@bquery/bquery/ssr';\n *\n * const ssrState = deserializeStoreState();\n * hydrateStores(ssrState);\n * ```\n */\nexport const hydrateStores = (stateMap: DeserializedStoreState): void => {\n for (const [storeId, state] of Object.entries(stateMap)) {\n hydrateStore(storeId, state);\n }\n};\n","/**\n * SSR rendering utilities.\n *\n * Server-side renders bQuery templates to HTML strings by evaluating\n * directive attributes against a plain data context. Uses a lightweight\n * DOM implementation to process templates without a browser.\n *\n * @module bquery/ssr\n */\n\nimport { isComputed, isSignal, type Signal } from '../reactive/index';\nimport { DANGEROUS_PROTOCOLS } from '../security/constants';\nimport type { BindingContext } from '../view/types';\nimport { getDOMParserImpl, resolveBackend } from './config';\nimport { cheapHash, collectDirectiveSignatureFromElement, HYDRATION_HASH_ATTR } from './hash';\nimport { renderTemplatePure, sanitizeHtmlForSSR } from './renderer';\nimport type { RenderOptions, SSRResult } from './types';\nimport { serializeStoreState } from './serialize';\n\nconst VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n\nconst TEXT_NODE_TYPE = 3;\nconst ELEMENT_NODE_TYPE = 1;\n\nconst escapeHtmlText = (value: string): string =>\n value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n\nconst escapeHtmlAttribute = (value: string): string =>\n escapeHtmlText(value).replace(/\"/g, '"');\n\nconst isUnsafeUrlAttribute = (name: string): boolean => {\n const normalized = name.toLowerCase();\n return (\n normalized === 'href' ||\n normalized === 'src' ||\n normalized === 'xlink:href' ||\n normalized === 'formaction' ||\n normalized === 'action' ||\n normalized === 'poster' ||\n normalized === 'background' ||\n normalized === 'cite' ||\n normalized === 'data'\n );\n};\n\nconst sanitizeUrlForProtocolCheck = (value: string): string =>\n value\n .trim()\n .replace(/[\\u0000-\\u001F\\u007F]+/g, '')\n .replace(/[\\u200B-\\u200D\\uFEFF\\u2028\\u2029]+/g, '')\n .replace(/\\\\u[\\da-fA-F]{4}/g, '')\n .replace(/\\s+/g, '')\n .toLowerCase();\n\nconst isUnsafeUrlValue = (value: string): boolean => {\n const normalized = sanitizeUrlForProtocolCheck(value);\n return DANGEROUS_PROTOCOLS.some((protocol) => normalized.startsWith(protocol));\n};\n\nconst serializeSSRNode = (node: Node): string => {\n if (node.nodeType === TEXT_NODE_TYPE) {\n return escapeHtmlText(node.textContent ?? '');\n }\n\n if (node.nodeType !== ELEMENT_NODE_TYPE) {\n return '';\n }\n\n const el = node as Element;\n const tagName = el.tagName.toLowerCase();\n\n if (tagName === 'script') {\n return '';\n }\n\n let attrs = '';\n for (const attr of el.attributes) {\n const attrName = attr.name.toLowerCase();\n if (attrName.startsWith('on')) {\n continue;\n }\n if (isUnsafeUrlAttribute(attrName) && isUnsafeUrlValue(attr.value)) {\n continue;\n }\n attrs += ` ${attr.name}=\"${escapeHtmlAttribute(attr.value)}\"`;\n }\n\n if (VOID_ELEMENTS.has(tagName)) {\n return `<${tagName}${attrs}>`;\n }\n\n let childrenHtml = '';\n for (const child of el.childNodes) {\n childrenHtml += serializeSSRNode(child);\n }\n\n return `<${tagName}${attrs}>${childrenHtml}</${tagName}>`;\n};\n\n/**\n * Unwraps a value — if it's a signal/computed, returns `.value`, otherwise returns as-is.\n * @internal\n */\nconst unwrap = (value: unknown): unknown => {\n if (isSignal(value) || isComputed(value)) {\n return (value as Signal<unknown>).value;\n }\n return value;\n};\n\n/**\n * Evaluates a simple expression against a context.\n * Supports dot-notation property access, negation, ternary, and basic comparisons.\n * Unlike the view module's `evaluate()`, this does NOT use `new Function()` —\n * it uses a safe subset for SSR to avoid `unsafe-eval` in server environments.\n *\n * Falls back to `new Function()` for complex expressions.\n *\n * @internal\n */\nconst evaluateSSR = <T = unknown>(expression: string, context: BindingContext): T => {\n const trimmed = expression.trim();\n\n // Handle negation: !expr\n if (trimmed.startsWith('!')) {\n return !evaluateSSR(trimmed.slice(1).trim(), context) as T;\n }\n\n // Handle string literals\n if (\n (trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\")) ||\n (trimmed.startsWith('\"') && trimmed.endsWith('\"'))\n ) {\n return trimmed.slice(1, -1) as T;\n }\n\n // Handle numeric literals\n if (/^-?\\d+(\\.\\d+)?$/.test(trimmed)) {\n return Number(trimmed) as T;\n }\n\n // Handle boolean literals\n if (trimmed === 'true') return true as T;\n if (trimmed === 'false') return false as T;\n if (trimmed === 'null') return null as T;\n if (trimmed === 'undefined') return undefined as T;\n\n // Handle dot-notation property access: a.b.c\n if (/^[\\w$]+(?:\\.[\\w$]+)*$/.test(trimmed)) {\n const parts = trimmed.split('.');\n let current: unknown = context;\n for (const part of parts) {\n if (current == null) return undefined as T;\n // First level: unwrap signals\n if (current === context) {\n current = unwrap((current as Record<string, unknown>)[part]);\n } else {\n current = (current as Record<string, unknown>)[part];\n }\n }\n return current as T;\n }\n\n // For complex expressions, fall back to Function-based evaluation\n try {\n const keys = Object.keys(context);\n const values = keys.map((k) => unwrap(context[k]));\n const fn = new Function(...keys, `return (${trimmed});`);\n return fn(...values) as T;\n } catch {\n return undefined as T;\n }\n};\n\n/**\n * Parses a `bq-for` expression like `item in items` or `(item, index) in items`.\n * @internal\n */\nconst parseForExpression = (\n expression: string\n): { itemName: string; indexName?: string; listExpr: string } | null => {\n const match = expression.match(/^\\(?(\\w+)(?:\\s*,\\s*(\\w+))?\\)?\\s+in\\s+(\\S.*)$/);\n if (!match) return null;\n return {\n itemName: match[1],\n indexName: match[2] || undefined,\n listExpr: match[3].trim(),\n };\n};\n\n/**\n * Processes an element's SSR directives, modifying it in place.\n * Returns `false` if the element should be removed from output (bq-if = false).\n * @internal\n */\nconst processSSRElement = (\n el: Element,\n context: BindingContext,\n prefix: string,\n annotateHydration = false\n): boolean => {\n // Handle bq-for before other directives so each clone gets an item-scoped context.\n const forExpr = el.getAttribute(`${prefix}-for`);\n const parsedFor = forExpr !== null ? parseForExpression(forExpr) : null;\n if (forExpr !== null && !parsedFor) {\n // Remove invalid directives before signature capture so hydration hashes\n // match the DOM-free renderer's normalized output.\n el.removeAttribute(`${prefix}-for`);\n }\n\n // Capture directive signature after normalizing invalid directives, but\n // before mutating any still-effective directive attributes.\n const signature = annotateHydration ? collectDirectiveSignatureFromElement(el, prefix) : '';\n\n if (forExpr !== null) {\n if (parsedFor) {\n const list = evaluateSSR<unknown[]>(parsedFor.listExpr, context);\n if (el.parentNode) {\n const parent = el.parentNode;\n if (!Array.isArray(list)) {\n parent.removeChild(el);\n return true;\n }\n\n for (let i = 0; i < list.length; i++) {\n const item = list[i];\n const clone = el.cloneNode(true) as Element;\n\n // Remove the bq-for attribute from clones\n clone.removeAttribute(`${prefix}-for`);\n clone.removeAttribute(':key');\n clone.removeAttribute(`${prefix}-key`);\n\n // Create item context\n const itemContext: BindingContext = {\n ...context,\n [parsedFor.itemName]: item,\n };\n if (parsedFor.indexName) {\n itemContext[parsedFor.indexName] = i;\n }\n\n // Recursively process the clone\n const shouldRenderClone = processSSRElement(\n clone,\n itemContext,\n prefix,\n annotateHydration\n );\n if (!shouldRenderClone) {\n continue;\n }\n processSSRChildren(clone, itemContext, prefix, annotateHydration);\n\n parent.insertBefore(clone, el);\n }\n\n // Remove the original template element\n parent.removeChild(el);\n return true; // Already handled children\n }\n }\n }\n\n // Handle bq-if: remove element if condition is falsy\n const ifExpr = el.getAttribute(`${prefix}-if`);\n if (ifExpr !== null) {\n const condition = evaluateSSR<boolean>(ifExpr, context);\n if (!condition) {\n return false; // Signal to remove this element\n }\n }\n\n // Handle bq-show: set display:none if falsy\n const showExpr = el.getAttribute(`${prefix}-show`);\n if (showExpr !== null) {\n const condition = evaluateSSR<boolean>(showExpr, context);\n if (!condition) {\n const htmlEl = el as unknown as { style?: { display?: string } };\n if (htmlEl.style) {\n htmlEl.style.display = 'none';\n } else {\n el.setAttribute('style', 'display: none;');\n }\n }\n }\n\n // Handle bq-text: set text content\n const textExpr = el.getAttribute(`${prefix}-text`);\n if (textExpr !== null) {\n const value = evaluateSSR(textExpr, context);\n el.textContent = String(value ?? '');\n }\n\n // Handle bq-html: sanitize to match client-side default behavior\n const htmlExpr = el.getAttribute(`${prefix}-html`);\n if (htmlExpr !== null) {\n const value = evaluateSSR(htmlExpr, context);\n el.innerHTML = sanitizeHtmlForSSR(String(value ?? ''));\n }\n\n // Handle bq-class: add classes\n const classExpr = el.getAttribute(`${prefix}-class`);\n if (classExpr !== null) {\n const trimmedClass = classExpr.trim();\n if (trimmedClass.startsWith('{')) {\n // Object syntax: { active: isActive, disabled: !enabled }\n const inner = trimmedClass.slice(1, -1).trim();\n const pairs = inner.split(',');\n for (const pair of pairs) {\n const colonIdx = pair.indexOf(':');\n if (colonIdx > -1) {\n const className = pair\n .slice(0, colonIdx)\n .trim()\n .replace(/^['\"]|['\"]$/g, '');\n const condExpr = pair.slice(colonIdx + 1).trim();\n const condition = evaluateSSR<boolean>(condExpr, context);\n if (condition) {\n el.classList.add(className);\n }\n }\n }\n } else {\n const result = evaluateSSR<string | string[]>(classExpr, context);\n if (typeof result === 'string') {\n result\n .split(/\\s+/)\n .filter(Boolean)\n .forEach((cls) => el.classList.add(cls));\n } else if (Array.isArray(result)) {\n result.filter(Boolean).forEach((cls) => el.classList.add(cls));\n }\n }\n }\n\n // Handle bq-style: set inline styles\n const styleExpr = el.getAttribute(`${prefix}-style`);\n if (styleExpr !== null) {\n const result = evaluateSSR<Record<string, string>>(styleExpr, context);\n if (result && typeof result === 'object') {\n const htmlEl = el as HTMLElement;\n for (const [prop, val] of Object.entries(result)) {\n // Convert camelCase to kebab-case\n const cssProp = prop.replace(/([A-Z])/g, '-$1').toLowerCase();\n htmlEl.style.setProperty(cssProp, String(val));\n }\n }\n }\n\n // Handle bq-bind:attr — set arbitrary attributes\n const attrs = Array.from(el.attributes);\n for (const attr of attrs) {\n if (attr.name.startsWith(`${prefix}-bind:`)) {\n const attrName = attr.name.slice(`${prefix}-bind:`.length);\n const value = evaluateSSR(attr.value, context);\n if (value === false || value === null || value === undefined) {\n el.removeAttribute(attrName);\n } else if (value === true) {\n el.setAttribute(attrName, '');\n } else {\n el.setAttribute(attrName, String(value));\n }\n }\n }\n\n if (signature) {\n el.setAttribute(HYDRATION_HASH_ATTR, cheapHash(signature));\n }\n\n return true;\n};\n\n/**\n * Recursively processes children of an element for SSR.\n * @internal\n */\nconst processSSRChildren = (\n parent: Element,\n context: BindingContext,\n prefix: string,\n annotateHydration = false\n): void => {\n // Process a snapshotted child list so removals do not affect iteration\n const children = Array.from(parent.children);\n for (const child of children) {\n let processedForDirective = false;\n\n // Handle elements that start with bq-for before the normal per-element pass.\n if (child.hasAttribute(`${prefix}-for`)) {\n const keep = processSSRElement(child, context, prefix, annotateHydration);\n processedForDirective = true;\n if (!keep) {\n child.remove();\n continue;\n }\n\n // Valid bq-for handling removes/replaces the original template node. If the\n // original child is no longer attached here, recursion has already been\n // handled by the bq-for expansion path.\n if (child.parentNode !== parent) {\n continue;\n }\n }\n\n if (!processedForDirective) {\n const keep = processSSRElement(child, context, prefix, annotateHydration);\n if (!keep) {\n child.remove();\n continue;\n }\n }\n\n // Recurse into children\n processSSRChildren(child, context, prefix, annotateHydration);\n }\n};\n\n/**\n * Strips all directive attributes (bq-*) from an element and its descendants.\n * @internal\n */\nconst stripDirectiveAttributes = (el: Element, prefix: string): void => {\n // Remove directive attributes from this element\n const attrs = Array.from(el.attributes);\n for (const attr of attrs) {\n if (attr.name.startsWith(`${prefix}-`) || attr.name.startsWith(':') || attr.name === ':key') {\n el.removeAttribute(attr.name);\n }\n }\n\n // Recurse into children\n for (const child of Array.from(el.children)) {\n stripDirectiveAttributes(child, prefix);\n }\n};\n\n/**\n * Server-side renders a bQuery template to an HTML string.\n *\n * Takes an HTML template with bQuery directives (bq-text, bq-if, bq-for, etc.)\n * and a data context, then evaluates the directives to produce a static HTML string.\n * This HTML can be sent to the client and later hydrated with `mount()` using\n * `{ hydrate: true }`.\n *\n * Supported directives:\n * - `bq-text` — Sets text content\n * - `bq-html` — Sets innerHTML\n * - `bq-if` — Conditional rendering (removes element if falsy)\n * - `bq-show` — Toggle visibility via `display: none`\n * - `bq-class` — Dynamic class binding (object or expression syntax)\n * - `bq-style` — Dynamic inline styles\n * - `bq-for` — List rendering\n * - `bq-bind:attr` — Dynamic attribute binding\n *\n * @param template - HTML template string with bq-* directives\n * @param data - Plain data object (signals will be unwrapped automatically)\n * @param options - Rendering options\n * @returns SSR result with HTML string and optional store state\n *\n * @example\n * ```ts\n * import { renderToString } from '@bquery/bquery/ssr';\n * import { signal } from '@bquery/bquery/reactive';\n *\n * const result = renderToString(\n * '<div><h1 bq-text=\"title\"></h1><p bq-if=\"showBody\">Hello!</p></div>',\n * { title: 'Welcome', showBody: true }\n * );\n *\n * console.log(result.html);\n * // '<div><h1>Welcome</h1><p>Hello!</p></div>'\n * ```\n *\n * @example\n * ```ts\n * // With bq-for list rendering\n * const result = renderToString(\n * '<ul><li bq-for=\"item in items\" bq-text=\"item.name\"></li></ul>',\n * { items: [{ name: 'Alice' }, { name: 'Bob' }] }\n * );\n *\n * console.log(result.html);\n * // '<ul><li>Alice</li><li>Bob</li></ul>'\n * ```\n */\nexport const renderToString = (\n template: string,\n data: BindingContext,\n options: RenderOptions = {}\n): SSRResult => {\n const {\n prefix = 'bq',\n stripDirectives = false,\n includeStoreState = false,\n annotateHydration = false,\n } = options;\n\n if (!template || typeof template !== 'string') {\n throw new Error('bQuery SSR: template must be a non-empty string.');\n }\n\n const normalizedTemplate = template.trim();\n\n // Resolve the renderer backend. Defaults to the legacy DOM-based path when\n // a `DOMParser` is available (browser/happy-dom in tests); otherwise the\n // pure DOM-free renderer kicks in automatically — this is what makes\n // `renderToString()` work seamlessly on Bun, Deno and Node ≥ 24.\n const backend = resolveBackend();\n\n if (backend === 'pure') {\n const html = renderTemplatePure(normalizedTemplate, data, {\n prefix,\n stripDirectives,\n annotateHydration,\n });\n let storeState: string | undefined;\n if (includeStoreState) {\n const storeIds = Array.isArray(includeStoreState) ? includeStoreState : undefined;\n storeState = serializeStoreState({ storeIds }).stateJson;\n }\n return { html, storeState };\n }\n\n const DOMParserImpl = getDOMParserImpl();\n if (!DOMParserImpl) {\n throw new Error(\n 'bQuery SSR: DOMParser is not available in this environment. Provide a DOMParser-compatible implementation before calling renderToString().'\n );\n }\n\n // Create a DOM document for processing\n const parser = new DOMParserImpl();\n const doc = parser.parseFromString(normalizedTemplate, 'text/html');\n const body = doc.body || doc.documentElement;\n\n if (!body) {\n throw new Error('bQuery SSR: Failed to parse template.');\n }\n\n // Process all children of the body\n processSSRChildren(body, data, prefix, annotateHydration);\n\n // Strip directive attributes if requested\n if (stripDirectives) {\n for (const child of Array.from(body.children)) {\n stripDirectiveAttributes(child, prefix);\n }\n }\n\n let html = '';\n for (const child of body.childNodes) {\n html += serializeSSRNode(child);\n }\n\n // Handle store state serialization\n let storeState: string | undefined;\n if (includeStoreState) {\n const storeIds = Array.isArray(includeStoreState) ? includeStoreState : undefined;\n storeState = serializeStoreState({ storeIds }).stateJson;\n }\n\n return { html, storeState };\n};\n","/**\n * Runtime detection helpers for the SSR module.\n *\n * Detects whether the current runtime is Bun, Deno, Node.js, a browser,\n * or a Web-Worker / edge runtime (Cloudflare Workers / `workerd`).\n * Detection is feature-based and never throws; calling these helpers is\n * safe in any environment that provides `globalThis`.\n *\n * @module bquery/ssr\n */\n\n/**\n * Identifier for a recognised JavaScript runtime.\n */\nexport type SSRRuntime = 'bun' | 'deno' | 'node' | 'browser' | 'workerd' | 'unknown';\n\ninterface BunGlobal {\n version?: string;\n}\n\ninterface DenoGlobal {\n version?: { deno?: string };\n}\n\ninterface NodeProcess {\n versions?: { node?: string };\n}\n\nconst safeGlobal = (): Record<string, unknown> => {\n return (typeof globalThis !== 'undefined' ? globalThis : {}) as Record<string, unknown>;\n};\n\n/**\n * Detects the current runtime via feature checks on `globalThis`.\n * Order matters: Bun and Deno expose Node compatibility shims, so they are\n * checked first.\n *\n * @returns The detected runtime identifier, or `'unknown'` if none match.\n *\n * @example\n * ```ts\n * import { detectRuntime } from '@bquery/bquery/ssr';\n *\n * if (detectRuntime() === 'deno') {\n * // Deno-specific behaviour\n * }\n * ```\n */\nexport const detectRuntime = (): SSRRuntime => {\n const g = safeGlobal();\n\n if (typeof (g.Bun as BunGlobal | undefined)?.version === 'string') {\n return 'bun';\n }\n\n if (typeof (g.Deno as DenoGlobal | undefined)?.version?.deno === 'string') {\n return 'deno';\n }\n\n // workerd / Cloudflare Workers expose `navigator.userAgent === 'Cloudflare-Workers'`\n // and lack `process.versions.node`.\n const navigator = g.navigator as { userAgent?: string } | undefined;\n if (\n typeof navigator?.userAgent === 'string' &&\n navigator.userAgent.toLowerCase().includes('cloudflare-workers')\n ) {\n return 'workerd';\n }\n\n if (typeof (g.process as NodeProcess | undefined)?.versions?.node === 'string') {\n return 'node';\n }\n\n if (typeof g.window !== 'undefined' && typeof g.document !== 'undefined') {\n return 'browser';\n }\n\n return 'unknown';\n};\n\n/**\n * Returns `true` when called inside a server-side runtime (Bun, Deno, Node,\n * Cloudflare Workers / `workerd`).\n */\nexport const isServerRuntime = (): boolean => {\n const rt = detectRuntime();\n return rt === 'bun' || rt === 'deno' || rt === 'node' || rt === 'workerd';\n};\n\n/**\n * Returns `true` when called inside a browser-like runtime (full DOM available).\n */\nexport const isBrowserRuntime = (): boolean => detectRuntime() === 'browser';\n\n/**\n * Lightweight feature-detection report for runtime capabilities relevant to SSR.\n */\nexport interface SSRRuntimeFeatures {\n /** Whether `Request`/`Response`/`fetch` are available on `globalThis`. */\n fetchApi: boolean;\n /** Whether `ReadableStream` is available on `globalThis`. */\n webStreams: boolean;\n /** Whether `TextEncoder` is available on `globalThis`. */\n textEncoder: boolean;\n /** Whether `crypto.subtle` is available (used for ETag hashing). */\n subtleCrypto: boolean;\n /** Whether `crypto.randomUUID()` is available. */\n randomUuid: boolean;\n /** Whether the global `DOMParser` is available. */\n domParser: boolean;\n}\n\n/**\n * Returns a feature-detection report for the current runtime. All checks are\n * non-throwing; missing globals yield `false`.\n */\nexport const getSSRRuntimeFeatures = (): SSRRuntimeFeatures => {\n const g = safeGlobal();\n const crypto = g.crypto as { subtle?: unknown; randomUUID?: () => string } | undefined;\n return {\n fetchApi:\n typeof g.Request === 'function' &&\n typeof g.Response === 'function' &&\n typeof g.fetch === 'function',\n webStreams: typeof g.ReadableStream === 'function',\n textEncoder: typeof g.TextEncoder === 'function',\n subtleCrypto: typeof crypto?.subtle === 'object' && crypto?.subtle !== null,\n randomUuid: typeof crypto?.randomUUID === 'function',\n domParser: typeof g.DOMParser === 'function',\n };\n};\n","/** Shared internal brand for SSR deferred values and tagged loaders. */\ndeclare const _deferBrandSymbol: unique symbol;\nexport const DEFER_BRAND = Symbol.for('bquery.ssr.defer') as typeof _deferBrandSymbol;\n","/**\n * Async data helpers for SSR.\n *\n * These tiny utilities let `renderToStringAsync()`/`renderToStream()` await\n * `Promise`-shaped values inside the binding context before the templates are\n * evaluated, without coupling the synchronous renderer to async semantics.\n *\n * @module bquery/ssr\n */\n\nimport { isComputed, isSignal, type Signal } from '../reactive/index';\nimport type { BindingContext } from '../view/types';\nimport { isPrototypePollutionKey } from '../core/utils/object';\nimport type { SSRContext } from './context';\nimport { DEFER_BRAND } from './defer-brand';\n\n/** A loader function executed before render. */\nexport type SSRLoader<T = unknown> = (ctx: SSRContext) => T | Promise<T>;\n\n/**\n * Wraps a loader so it can be invoked or stored uniformly. The wrapper is\n * tagged with the internal defer brand so `resolveContext()` recognises it\n * and calls the loader with the active `SSRContext`.\n */\nexport const defineLoader = <T>(loader: SSRLoader<T>): SSRLoader<T> => {\n Object.defineProperty(loader, DEFER_BRAND, {\n value: true,\n enumerable: false,\n configurable: true,\n });\n return loader;\n};\n\ninterface DeferredValue<T> {\n [DEFER_BRAND]: true;\n promise: Promise<T>;\n fallback?: unknown;\n}\n\n/**\n * Marks a promise as \"may resolve in parallel\". When `renderToStringAsync()`\n * sees a deferred value in the context, it awaits the underlying promise.\n * Streaming renderers can flush a fallback first and patch the resolved value\n * later (see `renderToStreamSuspense()`).\n */\nexport const defer = <T>(promise: Promise<T> | T, fallback?: unknown): DeferredValue<T> => {\n const p = promise instanceof Promise ? promise : Promise.resolve(promise);\n return {\n [DEFER_BRAND]: true,\n promise: p,\n fallback,\n };\n};\n\nconst isDeferred = (value: unknown): value is DeferredValue<unknown> =>\n typeof value === 'object' &&\n value !== null &&\n (value as Record<symbol, unknown>)[DEFER_BRAND] === true;\n\n/**\n * Walks the binding context, awaits all promises and deferred values, and\n * returns a new context with the resolved values. Signals/computeds are kept\n * as-is so the renderer can still unwrap them lazily.\n *\n * @internal\n */\nexport const resolveContext = async (\n context: BindingContext,\n ctx: SSRContext\n): Promise<BindingContext> => {\n const out = Object.create(null) as BindingContext;\n const entries = Object.entries(context);\n await Promise.all(\n entries.map(async ([key, value]) => {\n if (isPrototypePollutionKey(key)) return;\n if (isSignal(value) || isComputed(value)) {\n out[key] = value;\n return;\n }\n if (isDeferred(value)) {\n try {\n out[key] = await value.promise;\n } catch (error) {\n ctx.reportError(error);\n out[key] = value.fallback;\n }\n return;\n }\n if (value && typeof (value as Promise<unknown>).then === 'function') {\n try {\n out[key] = await (value as Promise<unknown>);\n } catch (error) {\n ctx.reportError(error);\n out[key] = undefined;\n }\n return;\n }\n if (\n typeof value === 'function' &&\n (value as unknown as { [DEFER_BRAND]?: unknown })[DEFER_BRAND]\n ) {\n // Allow loader-style functions tagged via defineLoader to opt in.\n try {\n out[key] = await Promise.resolve((value as SSRLoader)(ctx));\n } catch (error) {\n ctx.reportError(error);\n out[key] = undefined;\n }\n return;\n }\n out[key] = value;\n })\n );\n // Carry forward signals untouched so unwrap() in the evaluator still works.\n for (const [key, value] of Object.entries(context)) {\n if (\n !isPrototypePollutionKey(key) &&\n !Object.prototype.hasOwnProperty.call(out, key) &&\n (isSignal(value) || isComputed(value))\n ) {\n out[key] = value as Signal<unknown>;\n }\n }\n return out;\n};\n","/**\n * Head manager for SSR.\n *\n * Collects `<title>`, `<meta>`, `<link>` and inline `<script>` directives that\n * a render path wants to inject into the document head, then serialises them\n * as a single HTML string. The same descriptor shape is reused by the\n * server-side head manager methods across SSR entry points.\n *\n * @module bquery/ssr\n */\n\nimport { isPrototypePollutionKey } from '../core/utils/object';\n\nconst escapeAttr = (value: string): string =>\n value.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<').replace(/>/g, '>');\n\nconst escapeText = (value: string): string =>\n value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n\nconst escapeScriptBody = (value: string): string =>\n value\n .replace(/<\\/(script)/gi, '<\\\\/$1')\n .replace(/<!--/g, '<\\\\!--')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029');\n\n/** A `<meta>` tag descriptor. */\nexport interface SSRMeta {\n name?: string;\n property?: string;\n httpEquiv?: string;\n charset?: string;\n content?: string;\n}\n\n/** A `<link>` tag descriptor. */\nexport interface SSRLink {\n rel: string;\n href: string;\n as?: string;\n type?: string;\n crossorigin?: string;\n media?: string;\n integrity?: string;\n nonce?: string;\n}\n\n/** An inline or external `<script>` tag descriptor. */\nexport interface SSRScript {\n src?: string;\n type?: string;\n body?: string;\n defer?: boolean;\n async?: boolean;\n nonce?: string;\n crossorigin?: string;\n integrity?: string;\n module?: boolean;\n}\n\n/** Options accepted by `HeadManager.add()`. */\nexport interface UseHeadOptions {\n title?: string;\n titleTemplate?: string;\n meta?: SSRMeta[];\n link?: SSRLink[];\n script?: SSRScript[];\n}\n\n/** Aggregated head state collected during a render. */\nexport interface SSRHeadState {\n title: string | null;\n titleTemplate: string | null;\n meta: SSRMeta[];\n link: SSRLink[];\n script: SSRScript[];\n}\n\n/** Public head manager handle. */\nexport interface HeadManager {\n /** Add or replace head entries. */\n add(options: UseHeadOptions): void;\n /** Returns the current state snapshot. */\n state(): SSRHeadState;\n /** Renders the collected head into HTML. */\n render(options?: { nonce?: string }): string;\n /** Resets the manager to an empty state. */\n reset(): void;\n}\n\n/**\n * Creates an isolated head manager. Each SSR context owns one instance.\n */\nexport const createHeadManager = (): HeadManager => {\n const state: SSRHeadState = {\n title: null,\n titleTemplate: null,\n meta: [],\n link: [],\n script: [],\n };\n\n const add: HeadManager['add'] = (options) => {\n if (typeof options.title === 'string') state.title = options.title;\n if (typeof options.titleTemplate === 'string') state.titleTemplate = options.titleTemplate;\n if (Array.isArray(options.meta)) state.meta.push(...options.meta);\n if (Array.isArray(options.link)) state.link.push(...options.link);\n if (Array.isArray(options.script)) state.script.push(...options.script);\n };\n\n const render: HeadManager['render'] = (renderOpts = {}) => {\n let html = '';\n if (state.title !== null) {\n const formatted = state.titleTemplate\n ? state.titleTemplate.replace(/%s/g, state.title)\n : state.title;\n html += `<title>${escapeText(formatted)}</title>`;\n }\n for (const m of state.meta) {\n let attrs = '';\n for (const [k, v] of Object.entries(m)) {\n if (v === undefined || v === null) continue;\n if (isPrototypePollutionKey(k)) continue;\n const attrName = k === 'httpEquiv' ? 'http-equiv' : k;\n attrs += ` ${attrName}=\"${escapeAttr(String(v))}\"`;\n }\n html += `<meta${attrs}>`;\n }\n for (const l of state.link) {\n let attrs = ` rel=\"${escapeAttr(l.rel)}\" href=\"${escapeAttr(l.href)}\"`;\n if (l.as) attrs += ` as=\"${escapeAttr(l.as)}\"`;\n if (l.type) attrs += ` type=\"${escapeAttr(l.type)}\"`;\n if (l.crossorigin) attrs += ` crossorigin=\"${escapeAttr(l.crossorigin)}\"`;\n if (l.media) attrs += ` media=\"${escapeAttr(l.media)}\"`;\n if (l.integrity) attrs += ` integrity=\"${escapeAttr(l.integrity)}\"`;\n if (l.nonce ?? renderOpts.nonce) {\n attrs += ` nonce=\"${escapeAttr(l.nonce ?? renderOpts.nonce!)}\"`;\n }\n html += `<link${attrs}>`;\n }\n for (const sc of state.script) {\n let attrs = '';\n if (sc.src) attrs += ` src=\"${escapeAttr(sc.src)}\"`;\n if (sc.type) attrs += ` type=\"${escapeAttr(sc.type)}\"`;\n else if (sc.module) attrs += ' type=\"module\"';\n if (sc.defer) attrs += ' defer';\n if (sc.async) attrs += ' async';\n if (sc.crossorigin) attrs += ` crossorigin=\"${escapeAttr(sc.crossorigin)}\"`;\n if (sc.integrity) attrs += ` integrity=\"${escapeAttr(sc.integrity)}\"`;\n const nonce = sc.nonce ?? renderOpts.nonce;\n if (nonce) attrs += ` nonce=\"${escapeAttr(nonce)}\"`;\n html += `<script${attrs}>${sc.body ? escapeScriptBody(sc.body) : ''}</script>`;\n }\n return html;\n };\n\n const reset: HeadManager['reset'] = () => {\n state.title = null;\n state.titleTemplate = null;\n state.meta = [];\n state.link = [];\n state.script = [];\n };\n\n return {\n add,\n state: () =>\n ({\n ...state,\n meta: [...state.meta],\n link: [...state.link],\n script: [...state.script],\n }) as SSRHeadState,\n render,\n reset,\n };\n};\n\n/* ---------------------------------------------------------------------------\n * Asset manifest\n * ------------------------------------------------------------------------- */\n\n/** Asset preload entry. */\nexport interface SSRAsset {\n href: string;\n rel: 'preload' | 'modulepreload' | 'stylesheet';\n as?: string;\n type?: string;\n crossorigin?: string;\n integrity?: string;\n}\n\n/** Public asset manager handle. */\nexport interface AssetManager {\n /** Add a generic preload (`<link rel=\"preload\">`). */\n preload(href: string, opts?: Omit<SSRAsset, 'href' | 'rel'>): void;\n /** Add a JS module preload (`<link rel=\"modulepreload\">`). */\n module(href: string, opts?: Omit<SSRAsset, 'href' | 'rel' | 'as'>): void;\n /** Add a stylesheet link (`<link rel=\"stylesheet\">`). */\n style(href: string, opts?: Omit<SSRAsset, 'href' | 'rel' | 'as'>): void;\n /** Returns the current asset list snapshot. */\n list(): SSRAsset[];\n /** Renders all assets to a series of `<link>` tags. */\n render(options?: { nonce?: string }): string;\n /** Resets the manifest. */\n reset(): void;\n}\n\nexport const createAssetManager = (): AssetManager => {\n const assets: SSRAsset[] = [];\n\n return {\n preload(href, opts = {}) {\n assets.push({ href, rel: 'preload', ...opts });\n },\n module(href, opts = {}) {\n assets.push({ href, rel: 'modulepreload', ...opts });\n },\n style(href, opts = {}) {\n assets.push({ href, rel: 'stylesheet', ...opts });\n },\n list: () => [...assets],\n render(renderOpts = {}) {\n let html = '';\n for (const a of assets) {\n let attrs = ` rel=\"${escapeAttr(a.rel)}\" href=\"${escapeAttr(a.href)}\"`;\n if (a.as) attrs += ` as=\"${escapeAttr(a.as)}\"`;\n if (a.type) attrs += ` type=\"${escapeAttr(a.type)}\"`;\n if (a.crossorigin) attrs += ` crossorigin=\"${escapeAttr(a.crossorigin)}\"`;\n if (a.integrity) attrs += ` integrity=\"${escapeAttr(a.integrity)}\"`;\n if (renderOpts.nonce) attrs += ` nonce=\"${escapeAttr(renderOpts.nonce)}\"`;\n html += `<link${attrs}>`;\n }\n return html;\n },\n reset() {\n assets.length = 0;\n },\n };\n};\n","/**\n * Server-side rendering context.\n *\n * Encapsulates everything a render path may need to know about the incoming\n * request and to produce response-side metadata (head tags, asset hints,\n * nonces, etc.). The context is propagated explicitly through the public\n * async APIs (`renderToStringAsync`, `renderToStream`, `renderToResponse`)\n * and is available to template loaders.\n *\n * @module bquery/ssr\n */\n\nimport { generateNonce } from '../security/csp';\nimport { isPrototypePollutionKey } from '../core/utils/object';\nimport { createAssetManager, createHeadManager, type AssetManager, type HeadManager } from './head';\n\n/** Options for `createSSRContext()`. */\nexport interface CreateSSRContextOptions {\n /** Pre-built request to use as the source of URL/headers/cookies/etc. */\n request?: Request;\n /** Override the URL (defaults to `request.url` or `'http://localhost/'`). */\n url?: string | URL;\n /** Override the user agent string. */\n userAgent?: string;\n /** Override the request locale; defaults to `Accept-Language` parsing. */\n locale?: string;\n /** Provide an `AbortSignal` for cancellation. Default: `request.signal`. */\n signal?: AbortSignal;\n /** Pre-computed CSP nonce. If omitted and `crypto.getRandomValues` exists, a fresh nonce is generated. */\n nonce?: string;\n /** Render mode hint — used by streaming/string renderers for diagnostics. */\n mode?: 'string' | 'stream';\n /** Optional error sink invoked for non-fatal render errors. */\n onError?: (error: unknown) => void;\n}\n\n/** Public SSR context shape. */\nexport interface SSRContext {\n /** The originating `Request` (may be a synthetic one if none was provided). */\n request: Request;\n /** Parsed URL of the request. */\n url: URL;\n /** Request headers (via `Request.headers`). */\n headers: Headers;\n /** Resolved cookie map from `Cookie` header. */\n cookies: Record<string, string>;\n /** Best-effort user agent string. */\n userAgent: string;\n /** Best-effort locale parsed from `Accept-Language`. */\n locale: string;\n /** Cancellation signal — render paths must respect it. */\n signal: AbortSignal;\n /** CSP nonce applied to all generated `<script>` tags. */\n nonce: string;\n /** Render mode hint. */\n mode: 'string' | 'stream';\n /** Head manager — call `head.add(...)`, `head.render()`, or read `head.state()`. */\n head: HeadManager;\n /** Asset manifest — call `assets.preload()`/`module()`/`style()`. */\n assets: AssetManager;\n /** Status code suggested by render paths (loaders, error boundaries). */\n status: number;\n /** Outgoing response headers (used by `renderToResponse()`). */\n responseHeaders: Headers;\n /** Reports a non-fatal error. */\n reportError(error: unknown): void;\n}\n\nconst parseCookies = (header: string): Record<string, string> => {\n const out = Object.create(null) as Record<string, string>;\n if (!header) return out;\n for (const pair of header.split(/;\\s*/)) {\n const idx = pair.indexOf('=');\n if (idx === -1) continue;\n const name = pair.slice(0, idx).trim();\n const value = pair.slice(idx + 1).trim();\n if (!name || isPrototypePollutionKey(name)) continue;\n try {\n out[name] = decodeURIComponent(value);\n } catch {\n out[name] = value;\n }\n }\n return out;\n};\n\nconst parseLocale = (acceptLanguage: string | null): string => {\n if (!acceptLanguage) return 'en';\n // Pick the highest-quality entry. Header parsing is intentionally minimal.\n const entries = acceptLanguage\n .split(',')\n .map((entry) => {\n const [tag, ...params] = entry.trim().split(';');\n const qParam = params.find((p) => p.trim().startsWith('q='));\n const q = qParam ? Number.parseFloat(qParam.split('=')[1]) : 1;\n return { tag: tag.trim(), q: Number.isFinite(q) ? q : 0 };\n })\n .filter((e) => e.tag);\n if (!entries.length) return 'en';\n entries.sort((a, b) => b.q - a.q);\n return entries[0].tag;\n};\n\nconst safeNonce = (): string => {\n try {\n return generateNonce();\n } catch {\n // Runtime lacks `crypto.getRandomValues` / `btoa` — fall back to empty.\n return '';\n }\n};\n\nconst createHeadersFallback = (): Headers => {\n const store = new Map<string, string[]>();\n const api = {\n append(name: string, value: string): void {\n const key = String(name).toLowerCase();\n const existing = store.get(key);\n if (existing) existing.push(String(value));\n else store.set(key, [String(value)]);\n },\n delete(name: string): void {\n store.delete(String(name).toLowerCase());\n },\n get(name: string): string | null {\n const values = store.get(String(name).toLowerCase());\n return values ? values.join(', ') : null;\n },\n has(name: string): boolean {\n return store.has(String(name).toLowerCase());\n },\n set(name: string, value: string): void {\n store.set(String(name).toLowerCase(), [String(value)]);\n },\n forEach(\n callback: (value: string, key: string, parent: Headers) => void,\n thisArg?: unknown\n ): void {\n for (const [key, values] of store) {\n callback.call(thisArg, values.join(', '), key, api as unknown as Headers);\n }\n },\n *entries(): IterableIterator<[string, string]> {\n for (const [key, values] of store) {\n yield [key, values.join(', ')];\n }\n },\n [Symbol.iterator](): IterableIterator<[string, string]> {\n return api.entries();\n },\n };\n return api as unknown as Headers;\n};\n\nconst createAbortSignalFallback = (): AbortSignal =>\n ({\n aborted: false,\n onabort: null,\n reason: undefined,\n addEventListener() {\n /* no-op */\n },\n removeEventListener() {\n /* no-op */\n },\n dispatchEvent() {\n return false;\n },\n throwIfAborted() {\n /* no-op */\n },\n }) as unknown as AbortSignal;\n\nconst hasHeadersApi = (value: unknown): value is Headers =>\n typeof value === 'object' && value !== null && typeof (value as Headers).get === 'function';\n\nconst hasAbortSignalApi = (value: unknown): value is AbortSignal =>\n typeof value === 'object' &&\n value !== null &&\n typeof (value as AbortSignal).aborted === 'boolean';\n\nconst createHeadersLike = (): Headers =>\n typeof Headers === 'function' ? new Headers() : createHeadersFallback();\n\n/**\n * Creates a fully populated SSR context.\n *\n * @example\n * ```ts\n * const ctx = createSSRContext({ request });\n * const { html } = await renderToStringAsync(template, data, { context: ctx });\n * ```\n */\nexport const createSSRContext = (options: CreateSSRContextOptions = {}): SSRContext => {\n // SSRContext relies on Web `Request`/`Headers`/`AbortSignal`. All target\n // runtimes (Node ≥ 24, Deno, Bun, browsers) provide these natively. The\n // structural fallback below only exists so the helper does not throw in\n // exotic embedded runtimes; downstream code that expects real `Request`\n // methods should ensure the runtime ships them.\n const fallbackRequestUrl =\n options.url instanceof URL\n ? options.url.toString()\n : typeof options.url === 'string'\n ? new URL(options.url, 'http://localhost/').toString()\n : 'http://localhost/';\n const request =\n options.request ??\n (typeof Request === 'function'\n ? new Request(fallbackRequestUrl)\n : ({\n url: fallbackRequestUrl,\n headers: createHeadersFallback(),\n signal: createAbortSignalFallback(),\n } as unknown as Request));\n\n const urlSource = options.url ?? request.url;\n const url =\n urlSource instanceof URL ? urlSource : new URL(String(urlSource), 'http://localhost/');\n\n const headers = hasHeadersApi(request.headers) ? request.headers : createHeadersLike();\n const cookies = parseCookies(headers.get('cookie') ?? '');\n const userAgent = options.userAgent ?? headers.get('user-agent') ?? '';\n const locale = options.locale ?? parseLocale(headers.get('accept-language'));\n const signal =\n options.signal ??\n (hasAbortSignalApi(request.signal) ? request.signal : createAbortSignalFallback());\n const nonce = options.nonce ?? safeNonce();\n\n const ctx: SSRContext = {\n request,\n url,\n headers,\n cookies,\n userAgent,\n locale,\n signal,\n nonce,\n mode: options.mode ?? 'string',\n head: createHeadManager(),\n assets: createAssetManager(),\n status: 200,\n responseHeaders: createHeadersLike(),\n reportError(error) {\n options.onError?.(error);\n },\n };\n\n return ctx;\n};\n","/**\n * Async / streaming render entry points.\n *\n * Builds on top of the synchronous `renderToString()` and adds:\n * - `renderToStringAsync()` — awaits Promise/`defer()` values in the context.\n * - `renderToStream()` — emits the HTML as a Web `ReadableStream<Uint8Array>`.\n * - `renderToResponse()` — wraps the stream in a `Response` with sensible\n * defaults (`Content-Type`, `Cache-Control`, ETag, head injection, store\n * state injection).\n *\n * All three run on Bun, Deno and Node ≥ 24 without external dependencies.\n *\n * @module bquery/ssr\n */\n\nimport type { BindingContext } from '../view/types';\nimport { resolveContext } from './async';\nimport { createSSRContext, type SSRContext } from './context';\nimport { renderToString } from './render';\nimport { serializeStoreState } from './serialize';\nimport type { RenderOptions, SSRResult } from './types';\n\nconst escapeAttr = (value: string): string =>\n value.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<').replace(/>/g, '>');\n\n/**\n * HTML ASCII whitespace used between tag names and attributes. Includes form\n * feed (`\\f`) because the HTML tokenizer treats it as whitespace alongside\n * spaces, tabs, CR and LF.\n */\nconst isHtmlWhitespace = (ch: string | undefined): boolean =>\n ch === ' ' || ch === '\\n' || ch === '\\t' || ch === '\\r' || ch === '\\f';\n\nconst injectScriptNonce = (scriptTag: string, nonce: string): string => {\n const scriptPrefix = '<script';\n if (scriptTag.slice(0, scriptPrefix.length).toLowerCase() !== scriptPrefix) {\n return scriptTag;\n }\n\n const next = scriptTag[scriptPrefix.length];\n if (next !== '>' && !isHtmlWhitespace(next)) {\n return scriptTag;\n }\n\n return `<script nonce=\"${escapeAttr(nonce)}\"${scriptTag.slice(scriptPrefix.length)}`;\n};\n\n/**\n * Options accepted by the async render APIs. Extends the base `RenderOptions`\n * with response-shaping switches.\n */\nexport interface AsyncRenderOptions extends RenderOptions {\n /** Pre-built SSR context. Created automatically if omitted. */\n context?: SSRContext;\n /**\n * Whether to inject the head manager output, asset manifest and store-state\n * `<script>` tag into the output HTML when the template contains\n * `</head>`/`</body>` markers. Default: `true`.\n */\n injectHead?: boolean;\n /**\n * Custom store-state script ID/global key forwarded to `serializeStoreState()`.\n */\n storeScriptId?: string;\n storeGlobalKey?: string;\n}\n\n/** Result of an async render call. */\nexport interface AsyncSSRResult extends SSRResult {\n /** SSR context that produced this result. */\n context: SSRContext;\n /** Aggregated head HTML (already injected when `injectHead` is true). */\n headHtml: string;\n /** Aggregated asset preload HTML (already injected when `injectHead` is true). */\n assetsHtml: string;\n /** `<script>` tag with serialized store state, if any. */\n storeScriptTag: string;\n}\n\nconst injectIntoHead = (html: string, fragment: string): string => {\n if (!fragment) return html;\n const idx = html.toLowerCase().indexOf('</head>');\n if (idx === -1) return html;\n return html.slice(0, idx) + fragment + html.slice(idx);\n};\n\nconst injectBeforeBodyEnd = (html: string, fragment: string): string => {\n if (!fragment) return html;\n const idx = html.toLowerCase().lastIndexOf('</body>');\n if (idx === -1) return html;\n return html.slice(0, idx) + fragment + html.slice(idx);\n};\n\n/**\n * Async-aware render. Resolves all `Promise`/`defer()` values in the context,\n * then delegates to `renderToString()` and applies head/asset/store-state\n * injection based on the SSR context.\n */\nexport const renderToStringAsync = async (\n template: string,\n data: BindingContext,\n options: AsyncRenderOptions = {}\n): Promise<AsyncSSRResult> => {\n const context = options.context ?? createSSRContext({ mode: 'string' });\n\n if (context.signal.aborted) {\n throw new DOMException('SSR render aborted', 'AbortError');\n }\n\n const resolvedData = await resolveContext(data, context);\n\n if (context.signal.aborted) {\n throw new DOMException('SSR render aborted', 'AbortError');\n }\n\n const baseOptions: RenderOptions = {\n prefix: options.prefix,\n stripDirectives: options.stripDirectives,\n includeStoreState: false,\n annotateHydration: options.annotateHydration,\n };\n\n let { html, storeState } = renderToString(template, resolvedData, baseOptions);\n\n const headHtml = context.head.render({ nonce: context.nonce });\n const assetsHtml = context.assets.render({ nonce: context.nonce });\n\n let storeScriptTag = '';\n if (options.includeStoreState) {\n const storeIds = Array.isArray(options.includeStoreState)\n ? options.includeStoreState\n : undefined;\n const result = serializeStoreState({\n storeIds,\n scriptId: options.storeScriptId,\n globalKey: options.storeGlobalKey,\n });\n storeState = result.stateJson;\n storeScriptTag = result.scriptTag;\n if (context.nonce) {\n // Inject nonce into the script tag.\n storeScriptTag = injectScriptNonce(storeScriptTag, context.nonce);\n }\n }\n\n if (options.injectHead !== false) {\n html = injectIntoHead(html, headHtml + assetsHtml);\n html = injectBeforeBodyEnd(html, storeScriptTag);\n }\n\n return {\n html,\n storeState,\n context,\n headHtml,\n assetsHtml,\n storeScriptTag,\n };\n};\n\nconst getEncoder = (): TextEncoder => {\n if (typeof TextEncoder === 'undefined') {\n throw new Error('bQuery SSR: TextEncoder is not available in this runtime.');\n }\n return new TextEncoder();\n};\n\n/**\n * Renders a template into a Web `ReadableStream<Uint8Array>`. The stream is\n * single-chunk for now (the HTML is fully resolved before flushing) but is\n * exposed as a stream so adapters can pipe it directly into Bun/Deno/Node\n * responses without buffering into memory twice.\n *\n * Future Suspense-style streaming patches will reuse the same return type.\n */\nexport const renderToStream = (\n template: string,\n data: BindingContext,\n options: AsyncRenderOptions = {}\n): ReadableStream<Uint8Array> => {\n if (typeof ReadableStream === 'undefined') {\n throw new Error('bQuery SSR: ReadableStream is not available in this runtime.');\n }\n\n const encoder = getEncoder();\n const ctx = options.context ?? createSSRContext({ ...options, mode: 'stream' });\n const merged: AsyncRenderOptions = { ...options, context: ctx };\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const onAbort = () => {\n try {\n controller.error(new DOMException('SSR stream aborted', 'AbortError'));\n } catch {\n /* already closed */\n }\n };\n if (ctx.signal.aborted) {\n onAbort();\n return;\n }\n ctx.signal.addEventListener('abort', onAbort, { once: true });\n\n try {\n const result = await renderToStringAsync(template, data, merged);\n controller.enqueue(encoder.encode(result.html));\n controller.close();\n } catch (error) {\n ctx.signal.removeEventListener('abort', onAbort);\n try {\n controller.error(error);\n } catch {\n /* already errored */\n }\n } finally {\n ctx.signal.removeEventListener('abort', onAbort);\n }\n },\n });\n};\n\nconst computeWeakEtag = async (text: string): Promise<string | null> => {\n const subtle = (globalThis as { crypto?: { subtle?: SubtleCrypto } }).crypto?.subtle;\n if (!subtle) return null;\n try {\n const digest = await subtle.digest('SHA-1', getEncoder().encode(text));\n const bytes = new Uint8Array(digest);\n let hex = '';\n for (const b of bytes) hex += b.toString(16).padStart(2, '0');\n return `W/\"${hex.slice(0, 27)}\"`;\n } catch {\n return null;\n }\n};\n\n/** Options for `renderToResponse()`. */\nexport interface RenderToResponseOptions extends AsyncRenderOptions {\n /** Override the response status code. */\n status?: number;\n /** Override the `Content-Type` header. Default: `text/html; charset=utf-8`. */\n contentType?: string;\n /** Set a `Cache-Control` header value. */\n cacheControl?: string;\n /** Whether to compute a weak ETag from the rendered HTML. Default: `false`. */\n etag?: boolean;\n /** Extra headers merged into the response. */\n headers?: HeadersInit;\n}\n\n/**\n * Renders a template and returns a `Response` ready to be returned from a\n * `fetch`-style handler (`Bun.serve`, `Deno.serve`, Hono, Elysia, etc.).\n *\n * Honours `SSRContext.signal` for cancellation and `SSRContext.responseHeaders`\n * for headers added during the render path.\n */\nexport const renderToResponse = async (\n template: string,\n data: BindingContext,\n options: RenderToResponseOptions = {}\n): Promise<Response> => {\n const ctx = options.context ?? createSSRContext({ ...options, mode: 'string' });\n const merged: AsyncRenderOptions = { ...options, context: ctx };\n const result = await renderToStringAsync(template, data, merged);\n const status = options.status ?? ctx.status ?? 200;\n\n const headers = new Headers(options.headers);\n for (const [k, v] of ctx.responseHeaders) headers.append(k, v);\n if (!headers.has('content-type')) {\n headers.set('content-type', options.contentType ?? 'text/html; charset=utf-8');\n }\n if (options.cacheControl) headers.set('cache-control', options.cacheControl);\n\n if (options.etag) {\n const etag = await computeWeakEtag(result.html);\n if (etag) {\n headers.set('etag', etag);\n const ifNoneMatch = ctx.headers.get('if-none-match');\n if (ifNoneMatch && ifNoneMatch === etag) {\n return new Response(null, { status: 304, headers });\n }\n }\n }\n\n return new Response(result.html, { status, headers });\n};\n","/**\n * Progressive hydration strategies.\n *\n * Provide thin wrappers around `hydrateMount()` that defer the hydration\n * pass until a chosen trigger fires. They are runtime-safe: in non-browser\n * environments they fall back to immediate hydration (or a no-op) so the\n * same code path can run in tests.\n *\n * @module bquery/ssr\n */\n\nimport type { BindingContext, View } from '../view/types';\nimport { hydrateMount, type HydrateMountOptions } from './hydrate';\n\nconst resolveElement = (selector: string | Element): Element | null => {\n if (typeof selector !== 'string') return selector;\n if (typeof document === 'undefined') return null;\n try {\n return document.querySelector(selector);\n } catch {\n return null;\n }\n};\n\nconst hydrateResolved = (\n selector: string | Element,\n context: BindingContext,\n options: HydrateMountOptions\n): View | null => {\n const el = resolveElement(selector);\n if (!el) return null;\n return hydrateMount(el, context, options);\n};\n\nconst noop = (): void => {};\n\ntype LegacyMediaQueryList = MediaQueryList & {\n addListener?: (listener: (event: MediaQueryListEvent | MediaQueryList) => void) => void;\n removeListener?: (listener: (event: MediaQueryListEvent | MediaQueryList) => void) => void;\n};\n\nconst defer = (cb: () => void): (() => void) => {\n if (typeof window === 'undefined') {\n cb();\n return noop;\n }\n const ric = (window as unknown as { requestIdleCallback?: (cb: () => void) => number })\n .requestIdleCallback;\n if (typeof ric === 'function') {\n const id = ric(cb);\n return () => {\n const cic = (window as unknown as { cancelIdleCallback?: (id: number) => void })\n .cancelIdleCallback;\n if (typeof cic === 'function') cic(id);\n };\n }\n const id = setTimeout(cb, 1);\n return () => clearTimeout(id);\n};\n\n/** Common return shape for progressive hydration. */\nexport interface HydrationHandle {\n /** Cancels pending hydration (no-op if it has already run). */\n cancel(): void;\n /** Resolves with the View once hydration runs, or `null` if cancelled. */\n ready: Promise<View | null>;\n}\n\nconst buildHandle = (\n trigger: (resolve: () => void) => () => void\n): { handle: HydrationHandle; arm: (run: () => View | null) => void } => {\n let cancelled = false;\n let resolveReady: (v: View | null) => void = noop;\n let rejectReady: (e: unknown) => void = noop;\n const ready = new Promise<View | null>((res, rej) => {\n resolveReady = res;\n rejectReady = rej;\n });\n let cleanupTrigger: () => void = noop;\n\n const arm = (run: () => View | null): void => {\n cleanupTrigger = trigger(() => {\n if (cancelled) return;\n try {\n const view = run();\n resolveReady(view);\n } catch (error) {\n rejectReady(error);\n }\n });\n };\n\n return {\n handle: {\n ready,\n cancel() {\n if (cancelled) return;\n cancelled = true;\n cleanupTrigger();\n resolveReady(null);\n },\n },\n arm,\n };\n};\n\n/**\n * Hydrates the target only once it scrolls into view.\n *\n * Falls back to immediate hydration if `IntersectionObserver` is unavailable.\n */\nexport const hydrateOnVisible = (\n selector: string | Element,\n context: BindingContext,\n options: HydrateMountOptions & { rootMargin?: string; threshold?: number } = {}\n): HydrationHandle => {\n const { rootMargin, threshold, ...mountOptions } = options;\n const { handle, arm } = buildHandle((resolve) => {\n const el = resolveElement(selector);\n if (!el) {\n resolve();\n return noop;\n }\n if (typeof IntersectionObserver === 'undefined') {\n resolve();\n return noop;\n }\n const observer = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.isIntersecting) {\n observer.disconnect();\n resolve();\n return;\n }\n }\n },\n { rootMargin: rootMargin ?? '0px', threshold: threshold ?? 0 }\n );\n observer.observe(el);\n return () => observer.disconnect();\n });\n\n arm(() => hydrateResolved(selector, context, mountOptions));\n return handle;\n};\n\n/** Hydrates when the browser is idle. */\nexport const hydrateOnIdle = (\n selector: string | Element,\n context: BindingContext,\n options: HydrateMountOptions = {}\n): HydrationHandle => {\n const { handle, arm } = buildHandle((resolve) => defer(resolve));\n arm(() => hydrateResolved(selector, context, options));\n return handle;\n};\n\n/** Hydrates on first user interaction (click/keydown/pointerdown/touchstart). */\nexport const hydrateOnInteraction = (\n selector: string | Element,\n context: BindingContext,\n options: HydrateMountOptions & { events?: string[] } = {}\n): HydrationHandle => {\n const events = options.events ?? ['pointerdown', 'click', 'keydown', 'touchstart', 'focusin'];\n const { events: _events, ...mountOptions } = options;\n const { handle, arm } = buildHandle((resolve) => {\n const el = resolveElement(selector);\n if (!el) {\n resolve();\n return noop;\n }\n const listener = () => {\n cleanup();\n resolve();\n };\n const cleanup = (): void => {\n for (const evt of events) {\n el.removeEventListener(evt, listener, true);\n }\n };\n for (const evt of events) {\n el.addEventListener(evt, listener, { once: true, capture: true });\n }\n return cleanup;\n });\n arm(() => hydrateResolved(selector, context, mountOptions));\n return handle;\n};\n\n/** Hydrates only when a media query matches. */\nexport const hydrateOnMedia = (\n selector: string | Element,\n context: BindingContext,\n query: string,\n options: HydrateMountOptions = {}\n): HydrationHandle => {\n const { handle, arm } = buildHandle((resolve) => {\n if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {\n resolve();\n return noop;\n }\n const mql = window.matchMedia(query);\n if (mql.matches) {\n resolve();\n return noop;\n }\n let cleanup: () => void = noop;\n const listener = (event: MediaQueryListEvent | MediaQueryList): void => {\n if (event.matches) {\n cleanup();\n resolve();\n }\n };\n if (typeof mql.addEventListener === 'function') {\n mql.addEventListener('change', listener);\n cleanup = () => mql.removeEventListener('change', listener);\n return cleanup;\n }\n const legacyMql = mql as LegacyMediaQueryList;\n if (\n typeof legacyMql.addListener === 'function' &&\n typeof legacyMql.removeListener === 'function'\n ) {\n legacyMql.addListener(listener);\n cleanup = () => legacyMql.removeListener(listener);\n return cleanup;\n }\n resolve();\n return noop;\n });\n arm(() => hydrateResolved(selector, context, options));\n return handle;\n};\n\n/**\n * Hydrates a single SSR island using the same runtime-safe target resolution\n * as the other progressive hydration helpers. Returns `null` when the DOM is\n * unavailable or the target cannot be resolved.\n */\nexport const hydrateIsland = (\n selector: string | Element,\n context: BindingContext,\n options: HydrateMountOptions = {}\n): View | null => hydrateResolved(selector, context, options);\n","/**\n * Hydration mismatch detection.\n *\n * The DOM-free SSR renderer can annotate every element that carries a `bq-*`\n * directive with a small `data-bq-h` hash (see `RenderOptions.annotateHydration`).\n * On the client, `verifyHydration()` walks the live DOM, recomputes the same\n * hash for each annotated element and reports any divergence.\n *\n * The check is intentionally cheap and safe: collisions only result in false\n * negatives (a mismatch slips through), never in false positives (a stable\n * tree never reports a mismatch).\n *\n * @module bquery/ssr\n */\n\nimport { cheapHash, collectDirectiveSignatureFromElement, HYDRATION_HASH_ATTR } from './hash';\nimport { detectDevEnvironment } from '../core/env';\n\n/** A single hydration mismatch entry returned by `verifyHydration()`. */\nexport interface HydrationMismatch {\n /** The DOM element whose annotation diverged. */\n element: Element;\n /** The hash that the server emitted (`data-bq-h` value). */\n expected: string;\n /** The hash recomputed from the live element. */\n actual: string;\n /** The directive signature that was hashed (useful for diagnostics). */\n signature: string;\n}\n\n/** Options for `verifyHydration`. */\nexport interface VerifyHydrationOptions {\n /** Directive prefix to match. Default: `'bq'`. */\n prefix?: string;\n /**\n * Whether to log a `console.warn` for each mismatch. Defaults to `true` in\n * non-production environments and `false` otherwise. Pass an explicit\n * boolean to override.\n */\n warn?: boolean;\n /** Optional callback invoked once per mismatch. */\n onMismatch?: (mismatch: HydrationMismatch) => void;\n}\n\n/**\n * Walks `[data-bq-h]` elements within `root`, recomputes the directive hash\n * and reports mismatches. Returns the list of mismatches; callers can react\n * however they want (throw in tests, log in dev, ignore in production).\n *\n * Safe to call in any environment. When the runtime has no DOM (server-side)\n * or `root` has no `querySelectorAll`, the function returns an empty array\n * without throwing.\n *\n * @example\n * ```ts\n * import { detectDevEnvironment } from '@bquery/bquery';\n * import { hydrateMount, verifyHydration } from '@bquery/bquery/ssr';\n *\n * const view = hydrateMount('#app', context);\n * if (detectDevEnvironment()) {\n * verifyHydration(document.getElementById('app')!);\n * }\n * ```\n */\nexport const verifyHydration = (\n root: Element | Document,\n options: VerifyHydrationOptions = {}\n): HydrationMismatch[] => {\n const prefix = options.prefix ?? 'bq';\n const warn = options.warn ?? detectDevEnvironment();\n const onMismatch = options.onMismatch;\n\n const mismatches: HydrationMismatch[] = [];\n\n if (!root || typeof (root as Element).querySelectorAll !== 'function') {\n return mismatches;\n }\n\n // Include the root itself if it carries the annotation.\n const annotated: Element[] = [];\n if (\n typeof (root as Element).getAttribute === 'function' &&\n (root as Element).getAttribute(HYDRATION_HASH_ATTR) !== null\n ) {\n annotated.push(root as Element);\n }\n for (const el of Array.from(root.querySelectorAll(`[${HYDRATION_HASH_ATTR}]`))) {\n annotated.push(el);\n }\n\n for (const el of annotated) {\n const expected = el.getAttribute(HYDRATION_HASH_ATTR) ?? '';\n const signature = collectDirectiveSignatureFromElement(el, prefix);\n const actual = cheapHash(signature);\n if (actual !== expected) {\n const mismatch: HydrationMismatch = { element: el, expected, actual, signature };\n mismatches.push(mismatch);\n onMismatch?.(mismatch);\n if (warn) {\n console.warn(\n `[bQuery SSR] Hydration mismatch on <${el.tagName.toLowerCase()}>: ` +\n `server=\"${expected}\" client=\"${actual}\" signature=\"${signature}\".`,\n el\n );\n }\n }\n }\n\n return mismatches;\n};\n","/**\n * Suspense-style out-of-order streaming for SSR.\n *\n * Renders the synchronous shell with `defer(...)` placeholders wrapped in\n * `<bq-slot id=\"bq-s-N\">…</bq-slot>` markers, flushes that initial chunk,\n * then streams a `<template id=\"bq-r-N\">…</template>` plus a tiny inline\n * patch script for every resolved promise. The patch script swaps the\n * template content into the placeholder and removes both.\n *\n * Honours `SSRContext.signal` for cancellation and propagates the context\n * nonce onto every emitted `<script>` tag for CSP-strict environments.\n *\n * @module bquery/ssr\n */\n\nimport { isComputed, isSignal, type Signal } from '../reactive/index';\nimport type { BindingContext } from '../view/types';\nimport { createSSRContext, type SSRContext } from './context';\nimport { DEFER_BRAND } from './defer-brand';\nimport { parseTemplate, serializeTree, type SSRElement, type SSRNode } from './html-parser';\nimport { renderToString } from './render';\nimport type { AsyncRenderOptions } from './render-async';\n\ninterface DeferredLike<T = unknown> {\n [DEFER_BRAND]: true;\n promise: Promise<T>;\n fallback?: unknown;\n}\n\nconst isDeferredLike = (value: unknown): value is DeferredLike =>\n typeof value === 'object' &&\n value !== null &&\n (value as Record<symbol, unknown>)[DEFER_BRAND] === true;\n\nconst isReactive = (value: unknown): boolean => isSignal(value) || isComputed(value);\n\n/** A single slot collected by `renderToStreamSuspense`. */\ninterface SuspenseSlot {\n id: string;\n key: string;\n promise: Promise<unknown>;\n}\n\ntype SettledSuspenseSlot =\n | { index: number; slot: SuspenseSlot; ok: true; value: unknown }\n | { index: number; slot: SuspenseSlot; ok: false; error: unknown };\n\n/**\n * Whitelist regex for slot/template IDs. The IDs end up inside an inline\n * `<script>` patch, and while `escapeScriptBody()` already protects against\n * `</script>` injection, validating the prefix at the boundary is defense in\n * depth. Allows ASCII letters, digits, `-` and `_`.\n */\nconst SAFE_ID_RE = /^[A-Za-z][\\w-]*$/;\n/** Enforces a lowercase custom-element-style tag name with a required hyphen. */\nconst SAFE_SLOT_TAG_RE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)+$/;\n\nconst sanitizeSlotPrefix = (prefix: string, fallback: string): string => {\n if (typeof prefix !== 'string' || !SAFE_ID_RE.test(prefix)) return fallback;\n return prefix;\n};\n\nconst sanitizeSlotTag = (tag: string | undefined, fallback: string): string => {\n if (typeof tag !== 'string' || !SAFE_SLOT_TAG_RE.test(tag)) return fallback;\n return tag;\n};\n\n/**\n * Derives a template ID prefix that cannot collide with placeholder slot IDs.\n * The default `bq-s` becomes `bq-r`; custom prefixes without that suffix get\n * `-r` appended, so `slot` produces `slot-r` instead of a duplicate `slot`.\n * Prefixes already ending in `-r` get `-template` to avoid `-r-r`.\n */\nconst getResolvedIdPrefix = (slotIdPrefix: string): string => {\n const candidate = slotIdPrefix.replace(/-s$/, '-r');\n if (candidate === slotIdPrefix && slotIdPrefix.endsWith('-r')) {\n return `${slotIdPrefix}-template`;\n }\n return candidate === slotIdPrefix ? `${slotIdPrefix}-r` : candidate;\n};\n\n/**\n * Build a synchronous rendering context where every `defer(...)` value is\n * replaced by a placeholder string and every other Promise/loader is\n * replaced by its fallback (`undefined`). The deferred values are recorded\n * so the streaming loop can resolve them after the shell flushes.\n */\nconst splitDeferred = (\n context: BindingContext,\n prefix: string\n): { syncContext: BindingContext; slots: SuspenseSlot[] } => {\n const syncContext: BindingContext = {};\n const slots: SuspenseSlot[] = [];\n let counter = 0;\n for (const [key, value] of Object.entries(context)) {\n if (isReactive(value)) {\n syncContext[key] = value as Signal<unknown>;\n continue;\n }\n if (isDeferredLike(value)) {\n const id = `${prefix}-${counter++}`;\n slots.push({ id, key, promise: value.promise });\n // Render with the fallback so the synchronous shell has *something*.\n syncContext[key] = value.fallback;\n continue;\n }\n if (value && typeof (value as Promise<unknown>).then === 'function') {\n // Bare promises become deferred slots without a fallback.\n const id = `${prefix}-${counter++}`;\n slots.push({ id, key, promise: value as Promise<unknown> });\n syncContext[key] = undefined;\n continue;\n }\n syncContext[key] = value;\n }\n return { syncContext, slots };\n};\n\nconst escapeHtml = (s: string): string =>\n s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n\nconst escapeAttr = (s: string): string => escapeHtml(s).replace(/\"/g, '"');\n\nconst escapeScriptBody = (s: string): string =>\n s\n .replace(/<\\/(script)/gi, '<\\\\/$1')\n .replace(/<!--/g, '<\\\\!--')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029');\n\n/**\n * Options for `renderToStreamSuspense`.\n *\n * Only `context`, `prefix`, `stripDirectives`, and `annotateHydration` are\n * inherited from the base async render options. Head/store injection and other\n * response-shaping options are intentionally unsupported here.\n */\nexport interface SuspenseStreamOptions extends Pick<\n AsyncRenderOptions,\n 'context' | 'prefix' | 'stripDirectives' | 'annotateHydration'\n> {\n /**\n * Prefix used for slot/template IDs. Default: `'bq-s'` for placeholders\n * and `'bq-r'` for resolved templates.\n */\n slotIdPrefix?: string;\n /**\n * Tag name used for the placeholder element. Default: `'bq-slot'`.\n * Must be a valid custom-element tag (contain a `-`) so the browser keeps\n * inner content intact.\n */\n slotTag?: string;\n}\n\n/**\n * Static patch script for streamed Suspense fragments.\n *\n * The server passes the variable slot/template IDs through escaped\n * `data-bq-slot` / `data-bq-template` attributes on the `<script>` tag, and\n * the script reads them from `document.currentScript`. This keeps the emitted\n * code body constant while still letting each streamed patch target a\n * different placeholder/template pair.\n */\nconst PATCH_SCRIPT_BODY = escapeScriptBody(\n '(()=>{var c=document.currentScript;if(!c)return;var slotId=c.getAttribute(\"data-bq-slot\");var templateId=c.getAttribute(\"data-bq-template\");if(!slotId||!templateId)return;var s=document.getElementById(slotId);var t=document.getElementById(templateId);if(!s||!t)return;var f=t.content?t.content.cloneNode(true):t;while(s.firstChild)s.removeChild(s.firstChild);s.appendChild(f);t.parentNode&&t.parentNode.removeChild(t);s.parentNode&&s.replaceWith(...s.childNodes);})();'\n);\n\nconst buildPatchScript = (slotId: string, resolvedId: string, nonce?: string): string => {\n const nonceAttr = nonce ? ` nonce=\"${escapeAttr(nonce)}\"` : '';\n return `<script${nonceAttr} data-bq-slot=\"${escapeAttr(slotId)}\" data-bq-template=\"${escapeAttr(resolvedId)}\">${PATCH_SCRIPT_BODY}</script>`;\n};\n\nconst renderResolvedFragment = (\n _template: string,\n fullContext: BindingContext,\n syncContext: BindingContext,\n key: string,\n resolved: unknown,\n options: SuspenseStreamOptions\n): string => {\n // Re-render only the wrapping placeholder content. We use the original\n // template if the user provided a slot template via context (`__suspense_<key>`)\n // or fall back to a stringification of the resolved value.\n const slotTemplateKey = `__suspense_${key}`;\n const slotTemplate = (fullContext as Record<string, unknown>)[slotTemplateKey];\n if (typeof slotTemplate === 'string') {\n return renderToString(\n slotTemplate,\n { ...syncContext, [key]: resolved },\n {\n prefix: options.prefix,\n stripDirectives: options.stripDirectives,\n annotateHydration: options.annotateHydration,\n }\n ).html;\n }\n // Default: stringify the resolved value (with HTML escaping).\n if (resolved === null || resolved === undefined) return '';\n if (typeof resolved === 'string') return escapeHtml(resolved);\n return escapeHtml(String(resolved));\n // NOTE: the simple template path also serves as a hint for `bq-text`-style\n // bindings; rich nested rendering can be done by passing a slot template.\n};\n\nconst removeAttr = (el: SSRElement, name: string): void => {\n if (!(name in el.attributes)) return;\n delete el.attributes[name];\n const index = el.attributeOrder.indexOf(name);\n if (index !== -1) el.attributeOrder.splice(index, 1);\n};\n\nconst createSlotWrapper = (\n slotTag: string,\n slotId: string,\n children: SSRNode[] = []\n): SSRElement => ({\n type: 'element',\n tag: slotTag,\n attributes: { id: slotId },\n attributeOrder: ['id'],\n children,\n void: false,\n raw: false,\n});\n\nconst visitElements = (nodes: SSRNode[], visit: (element: SSRElement) => void): void => {\n for (const node of nodes) {\n if (node.type !== 'element') continue;\n visit(node);\n visitElements(node.children, visit);\n }\n};\n\nconst findElementByTag = (nodes: SSRNode[], tag: string): SSRElement | null => {\n for (const node of nodes) {\n if (node.type !== 'element') continue;\n if (node.tag === tag) return node;\n const nested = findElementByTag(node.children, tag);\n if (nested) return nested;\n }\n return null;\n};\n\nconst replaceSlotsInShell = (\n html: string,\n context: BindingContext,\n slots: SuspenseSlot[],\n options: SuspenseStreamOptions\n): string => {\n // Wrap the original placeholder text within a `<slotTag>` element so we can\n // patch it on the client. Only the parts that *come from* a deferred value\n // need wrapping; the synchronous renderer already produced them as text\n // (the fallback). We surround the *entire* fallback text in the slot tag.\n // To keep the renderer agnostic, we wrap the resolved value's fallback\n // wherever the renderer placed it. We rely on a marker attribute set by the\n // user (`bq-defer=\"key\"`) to mark where the slot wrapper goes.\n // Without such a marker, the slot fallback is already inlined and we\n // append the resolved templates at the end of <body>.\n const slotTag = sanitizeSlotTag(options.slotTag, 'bq-slot');\n const root = parseTemplate(html);\n const slotsByKey = new Map(slots.map((slot) => [slot.key, slot]));\n const placed = new Set<string>();\n\n visitElements(root.children, (element) => {\n const marker = element.attributes['data-bq-defer'];\n if (!marker) return;\n removeAttr(element, 'data-bq-defer');\n const slot = slotsByKey.get(marker);\n if (!slot || placed.has(slot.id)) return;\n const wrappedChildren = element.children;\n element.children = [createSlotWrapper(slotTag, slot.id, wrappedChildren)];\n placed.add(slot.id);\n });\n\n // If we didn't find any markers but slots exist, append placeholders at the\n // end of <body> (or the end of html) so the user can still see updates.\n const body = findElementByTag(root.children, 'body');\n const appendTarget = body?.children ?? root.children;\n for (const slot of slots) {\n if (placed.has(slot.id)) continue;\n appendTarget.push(createSlotWrapper(slotTag, slot.id));\n }\n // `context` reference suppressed to keep the function side-effect free\n // for the static analysis; the render uses syncContext where needed.\n void context;\n return serializeTree(root);\n};\n\n/** Returns true for characters that can appear immediately before an attribute name. */\nconst canPrecedeAttributeName = (ch: string | undefined): boolean =>\n ch !== undefined && /\\s/.test(ch);\n\n/** Returns true for characters that can terminate an attribute name in a start tag. */\nconst canFollowAttributeName = (ch: string | undefined): boolean =>\n ch === undefined || ch === '=' || ch === '>' || ch === '/' || /\\s/.test(ch);\n\n/**\n * Converts author-facing `bq-defer` markers to an internal data attribute\n * before rendering so `stripDirectives` can remove regular `bq-*` directives\n * without losing Suspense slot placement. This is a linear scanner instead of\n * a regex because templates are caller-provided strings.\n */\nconst protectDeferMarkers = (template: string): string => {\n let out = '';\n let i = 0;\n let inTag = false;\n let quote: '\"' | \"'\" | '' = '';\n let tagNameEnded = false;\n let tagLeadSeen = false;\n let allowAttributeRewrite = true;\n const marker = 'bq-defer';\n\n while (i < template.length) {\n const ch = template[i];\n\n if (!inTag) {\n if (ch === '<') {\n inTag = true;\n tagNameEnded = false;\n tagLeadSeen = false;\n allowAttributeRewrite = true;\n }\n out += ch;\n i++;\n continue;\n }\n\n if (quote) {\n out += ch;\n if (ch === quote) quote = '';\n i++;\n continue;\n }\n\n if (ch === '\"' || ch === \"'\") {\n quote = ch;\n out += ch;\n i++;\n continue;\n }\n\n if (ch === '>') {\n inTag = false;\n out += ch;\n i++;\n continue;\n }\n\n if (!tagNameEnded) {\n out += ch;\n i++;\n\n if (!tagLeadSeen) {\n if (/\\s/.test(ch)) continue;\n tagLeadSeen = true;\n if (ch === '/' || ch === '!' || ch === '?') {\n allowAttributeRewrite = false;\n }\n continue;\n }\n\n if (allowAttributeRewrite && /\\s/.test(ch)) {\n tagNameEnded = true;\n }\n continue;\n }\n\n if (\n allowAttributeRewrite &&\n template.startsWith(marker, i) &&\n canPrecedeAttributeName(template[i - 1]) &&\n canFollowAttributeName(template[i + marker.length])\n ) {\n out += 'data-bq-defer';\n i += marker.length;\n continue;\n }\n\n out += ch;\n i++;\n }\n\n return out;\n};\n\nconst getEncoder = (): TextEncoder => {\n if (typeof TextEncoder === 'undefined') {\n throw new Error('bQuery SSR: TextEncoder is not available in this runtime.');\n }\n return new TextEncoder();\n};\n\n/**\n * Renders a template into a Web `ReadableStream<Uint8Array>` with\n * Suspense-style out-of-order streaming. The synchronous shell is flushed\n * first; deferred slots stream in as their promises resolve.\n *\n * Use `bq-defer=\"key\"` on an element whose content depends on a `defer()`\n * value to mark where the placeholder wrapping should happen. Without the\n * marker, resolved fragments are appended at the end of `<body>`.\n */\nexport const renderToStreamSuspense = (\n template: string,\n data: BindingContext,\n options: SuspenseStreamOptions = {}\n): ReadableStream<Uint8Array> => {\n if (typeof ReadableStream === 'undefined') {\n throw new Error('bQuery SSR: ReadableStream is not available in this runtime.');\n }\n const encoder = getEncoder();\n const ctx: SSRContext = options.context ?? createSSRContext({ ...options, mode: 'stream' });\n const slotIdPrefix = sanitizeSlotPrefix(options.slotIdPrefix ?? 'bq-s', 'bq-s');\n const resolvedIdPrefix = sanitizeSlotPrefix(getResolvedIdPrefix(slotIdPrefix), 'bq-r');\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const onAbort = () => {\n try {\n controller.error(new DOMException('SSR stream aborted', 'AbortError'));\n } catch {\n /* already closed */\n }\n };\n if (ctx.signal.aborted) {\n onAbort();\n return;\n }\n ctx.signal.addEventListener('abort', onAbort, { once: true });\n\n try {\n const { syncContext, slots } = splitDeferred(data, slotIdPrefix);\n const shellTemplate = protectDeferMarkers(template);\n // Render the synchronous shell with fallbacks.\n const shell = renderToString(shellTemplate, syncContext, {\n prefix: options.prefix,\n stripDirectives: options.stripDirectives,\n annotateHydration: options.annotateHydration,\n }).html;\n\n const wrapped = replaceSlotsInShell(shell, syncContext, slots, options);\n controller.enqueue(encoder.encode(wrapped));\n\n // Resolve slots in arrival order so the network can flush as soon as\n // each promise settles. Track entries by array position because\n // multiple slots may intentionally share the same promise instance.\n const settledQueue: SettledSuspenseSlot[] = [];\n const waiters: Array<(settled: SettledSuspenseSlot) => void> = [];\n let remaining = slots.length;\n const enqueueSettled = (settled: SettledSuspenseSlot): void => {\n const waiter = waiters.shift();\n if (waiter) {\n waiter(settled);\n return;\n }\n settledQueue.push(settled);\n };\n\n for (const [index, slot] of slots.entries()) {\n slot.promise\n .then<SettledSuspenseSlot, SettledSuspenseSlot>(\n (value) => ({ index, slot, ok: true, value }),\n (error) => ({ index, slot, ok: false, error })\n )\n .then(enqueueSettled);\n }\n\n const nextSettled = async (): Promise<SettledSuspenseSlot> => {\n const queued = settledQueue.shift();\n if (queued) return queued;\n return new Promise<SettledSuspenseSlot>((resolve) => {\n waiters.push(resolve);\n });\n };\n\n while (remaining > 0) {\n if (ctx.signal.aborted) {\n return;\n }\n const settled = await nextSettled();\n remaining--;\n const { slot } = settled;\n const resolvedId = `${resolvedIdPrefix}-${slot.id.split('-').pop()}`;\n let resolvedHtml: string;\n if (!settled.ok) {\n ctx.reportError(settled.error);\n resolvedHtml = '';\n } else {\n resolvedHtml = renderResolvedFragment(\n template,\n data,\n syncContext,\n slot.key,\n settled.value,\n options\n );\n }\n const tpl = `<template id=\"${escapeAttr(resolvedId)}\">${resolvedHtml}</template>`;\n const patch = buildPatchScript(slot.id, resolvedId, ctx.nonce);\n controller.enqueue(encoder.encode(tpl + patch));\n }\n controller.close();\n } catch (error) {\n try {\n controller.error(error);\n } catch {\n /* already errored */\n }\n } finally {\n ctx.signal.removeEventListener('abort', onAbort);\n }\n },\n });\n};\n","/**\n * Router ↔ SSR bridge.\n *\n * On the server you typically need to:\n * 1. Match the incoming URL against your router's route table.\n * 2. Run any data loaders attached to the matched route.\n * 3. Inject the resolved route + loader data into the SSR binding context.\n *\n * `resolveSSRRoute()` and `runRouteLoaders()` perform steps 1 and 2 without\n * coupling the SSR module to the actual `createRouter()` runtime — only the\n * pure `matchRoute()` helper from `@bquery/bquery/router` is used. Loaders\n * live on `RouteDefinition.meta.loader` (additive, no existing field changes).\n *\n * @module bquery/ssr\n */\n\nimport { matchRoute } from '../router/match';\nimport { parseQuery } from '../router/query';\nimport type { Route, RouteDefinition } from '../router/types';\nimport type { SSRContext } from './context';\n\n/**\n * Loader signature for SSR routes. Attach as `meta.loader` on a\n * `RouteDefinition` and `runRouteLoaders()` will invoke it with the matched\n * route + the active SSR context.\n */\nexport type SSRRouteLoader<T = unknown> = (args: {\n route: Route;\n ctx: SSRContext;\n}) => T | Promise<T>;\n\nconst getLoader = (route: RouteDefinition | null): SSRRouteLoader | undefined => {\n if (!route || !route.meta) return undefined;\n const loader = (route.meta as { loader?: unknown }).loader;\n return typeof loader === 'function' ? (loader as SSRRouteLoader) : undefined;\n};\n\n/** Result of `resolveSSRRoute()`. */\nexport interface ResolvedSSRRoute {\n /** Route-like snapshot for the requested URL, with `matched` set when found. */\n route: Route;\n /** Whether a route definition was actually matched. */\n matched: boolean;\n /** Whether the matched route has a `redirectTo` target. */\n isRedirect: boolean;\n /** Redirect target, if any. */\n redirectTo?: string;\n}\n\n/**\n * Matches a URL against a route table without instantiating a full router.\n *\n * Designed to be called on the server before the SSR render so userland can\n * branch on `matched`/`isRedirect` (e.g. issue a 302 instead of rendering).\n *\n * @example\n * ```ts\n * import { resolveSSRRoute } from '@bquery/bquery/ssr';\n *\n * const { route, matched, isRedirect, redirectTo } = resolveSSRRoute({\n * url: new URL(request.url),\n * routes,\n * });\n *\n * if (isRedirect) return Response.redirect(redirectTo!, 302);\n * if (!matched) return new Response('Not Found', { status: 404 });\n * ```\n */\nexport const resolveSSRRoute = (options: {\n url: string | URL;\n routes: RouteDefinition[];\n /** Strip a base path before matching. Default: `''`. */\n base?: string;\n}): ResolvedSSRRoute => {\n const url =\n typeof options.url === 'string' ? new URL(options.url, 'http://localhost/') : options.url;\n const base = options.base ?? '';\n let pathname = url.pathname;\n if (base) {\n if (pathname === base) {\n pathname = '/';\n } else if (pathname.startsWith(`${base}/`)) {\n pathname = pathname.slice(base.length) || '/';\n }\n }\n\n const result = matchRoute(pathname, options.routes);\n const route: Route = {\n path: pathname,\n params: result?.params ?? {},\n query: parseQuery(url.search),\n matched: result?.matched ?? null,\n hash: url.hash.replace(/^#/, ''),\n };\n const matched = result !== null;\n const matchedDef = result?.matched ?? null;\n const isRedirect =\n !!matchedDef && 'redirectTo' in matchedDef && typeof matchedDef.redirectTo === 'string';\n return {\n route,\n matched,\n isRedirect,\n redirectTo: isRedirect ? (matchedDef as { redirectTo: string }).redirectTo : undefined,\n };\n};\n\n/**\n * Runs the loader attached to the matched route (`meta.loader`), if any.\n * Returns the resolved data, or `undefined` if no loader is configured.\n */\nexport const runRouteLoaders = async <T = unknown>(\n route: Route,\n ctx: SSRContext\n): Promise<T | undefined> => {\n const loader = getLoader(route.matched);\n if (!loader) return undefined;\n try {\n return (await loader({ route, ctx })) as T;\n } catch (error) {\n ctx.reportError(error);\n return undefined;\n }\n};\n\n/**\n * Convenience wrapper that resolves a route, runs its loader, and returns a\n * binding-context fragment ready to be merged into the data passed to\n * `renderToStringAsync()` / `renderToResponse()`.\n *\n * @example\n * ```ts\n * import {\n * createSSRContext,\n * createSSRRouterContext,\n * renderToResponse,\n * } from '@bquery/bquery/ssr';\n *\n * const ctx = createSSRContext();\n * const router = await createSSRRouterContext({ url: request.url, routes, ctx });\n * if (router.isRedirect) return Response.redirect(router.redirectTo!, 302);\n *\n * return renderToResponse(template, { ...router.bindings }, { context: ctx });\n * ```\n */\nexport const createSSRRouterContext = async (options: {\n url: string | URL;\n routes: RouteDefinition[];\n base?: string;\n ctx: SSRContext;\n}): Promise<{\n route: Route;\n matched: boolean;\n isRedirect: boolean;\n redirectTo?: string;\n data: unknown;\n bindings: Record<string, unknown>;\n}> => {\n const resolved = resolveSSRRoute({\n url: options.url,\n routes: options.routes,\n base: options.base,\n });\n const data = resolved.matched ? await runRouteLoaders(resolved.route, options.ctx) : undefined;\n return {\n route: resolved.route,\n matched: resolved.matched,\n isRedirect: resolved.isRedirect,\n redirectTo: resolved.redirectTo,\n data,\n bindings: {\n route: resolved.route,\n params: resolved.route.params,\n query: resolved.route.query,\n data,\n },\n };\n};\n","/**\n * Versioned store snapshots and strict drift-checking hydration.\n *\n * Sits *on top of* the simple `serializeStoreState()` / `hydrateStore()` pair\n * to give applications a way to:\n * - tag the snapshot with a schema version so a stale client can refuse to\n * apply server data that no longer matches its store shape;\n * - opt into strict mode where unknown keys cause a warning;\n * - selectively serialize / hydrate a subset of stores.\n *\n * Backwards compatible: the existing helpers stay untouched and remain the\n * primary entry-point for simple use cases.\n *\n * @module bquery/ssr\n */\n\nimport { getStore, listStores } from '../store/index';\nimport { isPrototypePollutionKey } from '../core/utils/object';\nimport { escapeForHtmlAttribute, escapeForScript } from './escape';\n\nconst isStateObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst sanitize = (value: Record<string, unknown>): Record<string, unknown> => {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n if (isPrototypePollutionKey(k)) continue;\n out[k] = v;\n }\n return out;\n};\n\n/** Versioned store snapshot. */\nexport interface SSRStoreSnapshot {\n /** Application-defined version string. Stable per schema. */\n version: string;\n /** Map of store ID → sanitized state. */\n state: Record<string, Record<string, unknown>>;\n}\n\n/** Result of `serializeStoreSnapshot()`. */\nexport interface SerializeSnapshotResult {\n snapshot: SSRStoreSnapshot;\n /** JSON-serialized snapshot. */\n json: string;\n /** `<script>` tag ready to embed (CSP-nonce-aware via `options.nonce`). */\n scriptTag: string;\n}\n\n/** Options for `serializeStoreSnapshot()`. */\nexport interface SerializeSnapshotOptions {\n /** Schema version. Required: hydration only succeeds when versions match. */\n version: string;\n /** Subset of store IDs to serialize. Defaults to all registered stores. */\n storeIds?: string[];\n /** Element ID for the generated `<script>` tag. */\n scriptId?: string;\n /** Global window key where the snapshot is assigned. */\n globalKey?: string;\n /** CSP nonce applied to the generated `<script>`. */\n nonce?: string;\n}\n\n/**\n * Captures every registered store's state into a versioned snapshot and\n * returns both the JSON payload and a ready-to-embed `<script>` tag.\n */\nexport const serializeStoreSnapshot = (\n options: SerializeSnapshotOptions\n): SerializeSnapshotResult => {\n const {\n version,\n storeIds,\n scriptId = '__BQUERY_STORE_SNAPSHOT__',\n globalKey = '__BQUERY_STORE_SNAPSHOT__',\n nonce,\n } = options;\n\n if (typeof version !== 'string' || version.length === 0) {\n throw new Error(\n 'serializeStoreSnapshot: `version` is required and must be a non-empty string.'\n );\n }\n if (isPrototypePollutionKey(scriptId) || isPrototypePollutionKey(globalKey)) {\n throw new Error('serializeStoreSnapshot: invalid scriptId/globalKey.');\n }\n\n const ids = storeIds ?? listStores();\n const state = Object.create(null) as Record<string, Record<string, unknown>>;\n for (const id of ids) {\n if (isPrototypePollutionKey(id)) continue;\n const store = getStore<{ $state: Record<string, unknown> }>(id);\n if (store) state[id] = sanitize(store.$state);\n }\n const snapshot: SSRStoreSnapshot = { version, state };\n const json = JSON.stringify(snapshot);\n\n const escapedJson = escapeForScript(json);\n const escapedKey = escapeForScript(JSON.stringify(globalKey));\n const escapedId = escapeForHtmlAttribute(scriptId);\n const nonceAttr = nonce ? ` nonce=\"${escapeForHtmlAttribute(nonce)}\"` : '';\n const scriptTag = `<script id=\"${escapedId}\"${nonceAttr}>window[${escapedKey}]=${escapedJson}</script>`;\n return { snapshot, json, scriptTag };\n};\n\n/** Options for `hydrateStoreSnapshot()`. */\nexport interface HydrateSnapshotOptions {\n /**\n * If set, the snapshot's `version` must match this value. Otherwise the\n * function returns early (and warns when `strict` is true).\n */\n expectedVersion?: string;\n /**\n * Strict mode: warn on version mismatch + warn on unknown store IDs (i.e.\n * the snapshot has IDs that aren't currently registered). Default: `false`.\n */\n strict?: boolean;\n}\n\n/** Result of `hydrateStoreSnapshot()`. */\nexport interface HydrateSnapshotResult {\n /** Whether the snapshot was applied. */\n applied: boolean;\n /** Reason when not applied (`'version-mismatch' | 'invalid-shape'`). */\n reason?: 'version-mismatch' | 'invalid-shape';\n /** IDs that were applied. */\n appliedIds: string[];\n /** IDs in the snapshot that no store exists for. */\n unknownIds: string[];\n}\n\nconst isStoreSnapshot = (value: unknown): value is SSRStoreSnapshot => {\n if (!isStateObject(value)) return false;\n const v = (value as { version: unknown }).version;\n const s = (value as { state: unknown }).state;\n return typeof v === 'string' && isStateObject(s);\n};\n\n/**\n * Applies a previously-serialized `SSRStoreSnapshot` to the registered stores.\n *\n * Returns a structured result; never throws on drift unless an explicit error\n * is thrown by a store's `$patch()` implementation.\n */\nexport const hydrateStoreSnapshot = (\n snapshot: unknown,\n options: HydrateSnapshotOptions = {}\n): HydrateSnapshotResult => {\n if (!isStoreSnapshot(snapshot)) {\n if (options.strict) {\n console.warn('[bQuery SSR] hydrateStoreSnapshot: snapshot has invalid shape.');\n }\n return { applied: false, reason: 'invalid-shape', appliedIds: [], unknownIds: [] };\n }\n\n if (typeof options.expectedVersion === 'string' && options.expectedVersion !== snapshot.version) {\n if (options.strict) {\n console.warn(\n `[bQuery SSR] hydrateStoreSnapshot: version mismatch — server=\"${snapshot.version}\" client=\"${options.expectedVersion}\". Skipping.`\n );\n }\n return { applied: false, reason: 'version-mismatch', appliedIds: [], unknownIds: [] };\n }\n\n const appliedIds: string[] = [];\n const unknownIds: string[] = [];\n for (const [id, state] of Object.entries(snapshot.state)) {\n if (isPrototypePollutionKey(id) || !isStateObject(state)) continue;\n const store = getStore<{ $patch?: (partial: Record<string, unknown>) => void }>(id);\n if (!store || typeof store.$patch !== 'function') {\n unknownIds.push(id);\n if (options.strict) {\n console.warn(\n `[bQuery SSR] hydrateStoreSnapshot: store \"${id}\" is not registered; skipping.`\n );\n }\n continue;\n }\n store.$patch(sanitize(state));\n appliedIds.push(id);\n }\n return { applied: appliedIds.length > 0, appliedIds, unknownIds };\n};\n\n/**\n * Reads the snapshot emitted by `serializeStoreSnapshot()` from `window`,\n * cleans up the global, and returns the parsed `SSRStoreSnapshot`.\n *\n * Returns `null` when no snapshot was found or when it has the wrong shape.\n */\nexport const readStoreSnapshot = (\n globalKey = '__BQUERY_STORE_SNAPSHOT__',\n scriptId = '__BQUERY_STORE_SNAPSHOT__'\n): SSRStoreSnapshot | null => {\n if (isPrototypePollutionKey(globalKey) || isPrototypePollutionKey(scriptId)) return null;\n if (typeof window === 'undefined') return null;\n const raw = (window as unknown as Record<string, unknown>)[globalKey];\n try {\n delete (window as unknown as Record<string, unknown>)[globalKey];\n } catch {\n (window as unknown as Record<string, unknown>)[globalKey] = undefined;\n }\n if (typeof document !== 'undefined' && typeof document.getElementById === 'function') {\n const el = document.getElementById(scriptId);\n if (el) el.remove();\n }\n if (!isStoreSnapshot(raw)) return null;\n return raw;\n};\n","/**\n * Resumability hooks.\n *\n * A *very* small primitive that lets the server publish JSON-serializable\n * values which the client can read back without re-running the producer.\n * Think of it as a typed key/value store that survives the serialization\n * boundary.\n *\n * It is intentionally not a full Qwik-style resumability system — bQuery's\n * reactive graph is rebuilt on the client. Instead, this primitive helps\n * applications avoid double-fetching loader-style data by parking it on\n * `window.__BQUERY_RESUME__` (or a custom global) inside a CSP-nonce-aware\n * `<script>` tag.\n *\n * @module bquery/ssr\n */\n\nimport { isPrototypePollutionKey } from '../core/utils/object';\nimport { escapeForHtmlAttribute, escapeForScript } from './escape';\n\n/** Server-side resumable state collector. */\nexport interface ResumableState {\n /** Stash a JSON-serializable value under `key`. */\n set: (key: string, value: unknown) => void;\n /** Read a value back (server-side, useful for tests). */\n get: <T = unknown>(key: string) => T | undefined;\n /** All collected entries. */\n entries: () => Record<string, unknown>;\n /** Build the `<script>` tag to embed in HTML. */\n render: (options?: { nonce?: string; scriptId?: string; globalKey?: string }) => string;\n}\n\n/** Options for `createResumableState()`. */\nexport interface CreateResumableStateOptions {\n /** Initial entries. */\n initial?: Record<string, unknown>;\n}\n\nconst cloneResumableEntries = (data: Record<string, unknown>): Record<string, unknown> => {\n const out = Object.create(null) as Record<string, unknown>;\n for (const [key, value] of Object.entries(data)) {\n if (isPrototypePollutionKey(key)) continue;\n out[key] = value;\n }\n return out;\n};\n\n/**\n * Creates a server-side resumable state collector.\n *\n * @example\n * ```ts\n * const resume = createResumableState();\n * resume.set('user', { id: 1, name: 'Ada' });\n *\n * // Inject into HTML:\n * const tag = resume.render({ nonce: ctx.nonce });\n * ```\n */\nexport const createResumableState = (options: CreateResumableStateOptions = {}): ResumableState => {\n const data: Record<string, unknown> = Object.create(null);\n if (options.initial) {\n for (const [k, v] of Object.entries(options.initial)) {\n if (!isPrototypePollutionKey(k)) data[k] = v;\n }\n }\n return {\n set(key, value) {\n if (isPrototypePollutionKey(key)) return;\n data[key] = value;\n },\n get<T = unknown>(key: string): T | undefined {\n return data[key] as T | undefined;\n },\n entries() {\n return cloneResumableEntries(data);\n },\n render(opts = {}) {\n const scriptId = opts.scriptId ?? '__BQUERY_RESUME__';\n const globalKey = opts.globalKey ?? '__BQUERY_RESUME__';\n if (isPrototypePollutionKey(scriptId) || isPrototypePollutionKey(globalKey)) {\n return '';\n }\n const json = JSON.stringify(data);\n const escapedJson = escapeForScript(json);\n const escapedKey = escapeForScript(JSON.stringify(globalKey));\n const escapedId = escapeForHtmlAttribute(scriptId);\n const nonceAttr = opts.nonce ? ` nonce=\"${escapeForHtmlAttribute(opts.nonce)}\"` : '';\n return `<script id=\"${escapedId}\"${nonceAttr}>window[${escapedKey}]=${escapedJson}</script>`;\n },\n };\n};\n\n/** Reader returned by `resumeState()`. */\nexport interface ResumeReader {\n /** Get a typed value from the resumable snapshot. */\n get: <T = unknown>(key: string) => T | undefined;\n /** Whether the snapshot was found. */\n hasSnapshot: boolean;\n /** All entries (read-only). */\n entries: () => Record<string, unknown>;\n}\n\n/**\n * Reads a previously-emitted resumable snapshot from `window` and cleans it\n * up. Safe to call in any environment; returns an empty reader when no\n * snapshot is present (server, tests, etc.).\n */\nexport const resumeState = (\n globalKey = '__BQUERY_RESUME__',\n scriptId = '__BQUERY_RESUME__'\n): ResumeReader => {\n const empty: ResumeReader = {\n get: () => undefined,\n hasSnapshot: false,\n entries: () => ({}),\n };\n if (isPrototypePollutionKey(globalKey) || isPrototypePollutionKey(scriptId)) return empty;\n if (typeof window === 'undefined') return empty;\n const raw = (window as unknown as Record<string, unknown>)[globalKey];\n try {\n delete (window as unknown as Record<string, unknown>)[globalKey];\n } catch {\n (window as unknown as Record<string, unknown>)[globalKey] = undefined;\n }\n if (typeof document !== 'undefined' && typeof document.getElementById === 'function') {\n const el = document.getElementById(scriptId);\n if (el) el.remove();\n }\n if (!raw || typeof raw !== 'object') return empty;\n const data = raw as Record<string, unknown>;\n return {\n hasSnapshot: true,\n get<T = unknown>(key: string): T | undefined {\n if (isPrototypePollutionKey(key)) return undefined;\n return data[key] as T | undefined;\n },\n entries() {\n return cloneResumableEntries(data);\n },\n };\n};\n","/**\n * Runtime adapters for SSR.\n *\n * Provide thin glue functions that turn a bQuery render handler into a\n * runtime-native server callback. They share a common signature so the same\n * application can be served by Bun, Deno, Node and any Web-`fetch` host.\n *\n * @module bquery/ssr\n */\n\nimport type { SSRContext } from './context';\nimport { detectRuntime } from './runtime';\n\n/** A handler that turns a request into a Response (Web-fetch style). */\nexport type SSRRequestHandler = (\n request: Request,\n context?: SSRContext\n) => Promise<Response> | Response;\n\n/* ---------------------------------------------------------------------------\n * Web (generic fetch) adapter\n * ------------------------------------------------------------------------- */\n\n/**\n * Identity adapter for Web-`fetch` style hosts (Hono, Elysia, Workerd, edge\n * runtimes). Exists for symmetry and future logging hooks.\n */\nexport const createWebHandler = (handler: SSRRequestHandler): SSRRequestHandler => handler;\n\n/* ---------------------------------------------------------------------------\n * Bun adapter\n * ------------------------------------------------------------------------- */\n\n/**\n * Wraps a handler for `Bun.serve()`. Returns a function with Bun's expected\n * signature `(request, server) => Response | Promise<Response>`.\n */\nexport const createBunHandler = (\n handler: SSRRequestHandler\n): ((request: Request) => Promise<Response>) => {\n return async (request) => Promise.resolve(handler(request));\n};\n\n/* ---------------------------------------------------------------------------\n * Deno adapter\n * ------------------------------------------------------------------------- */\n\n/**\n * Wraps a handler for `Deno.serve()`. Returns a function with Deno's expected\n * signature `(request, info?) => Response | Promise<Response>`.\n */\nexport const createDenoHandler = (\n handler: SSRRequestHandler\n): ((request: Request) => Promise<Response>) => {\n return async (request) => Promise.resolve(handler(request));\n};\n\n/* ---------------------------------------------------------------------------\n * Node adapter (`node:http`)\n * ------------------------------------------------------------------------- */\n\n/** Minimal subset of `node:http` IncomingMessage we rely on. */\nexport interface NodeIncomingMessage {\n url?: string;\n method?: string;\n headers: Record<string, string | string[] | undefined>;\n on(event: 'data', listener: (chunk: Uint8Array | string) => void): void;\n on(event: 'end', listener: () => void): void;\n on(event: 'error', listener: (err: unknown) => void): void;\n destroy?(error?: Error): void;\n}\n\n/** Minimal subset of `node:http` ServerResponse we rely on. */\nexport interface NodeServerResponse {\n statusCode: number;\n setHeader(name: string, value: string | number | readonly string[]): void;\n write(chunk: Uint8Array | string): boolean;\n end(chunk?: Uint8Array | string): void;\n once?(event: 'drain' | 'error', listener: (error?: unknown) => void): void;\n on?(event: 'drain' | 'error', listener: (error?: unknown) => void): void;\n}\n\n/** Optional hardening settings for the `node:http` adapter. */\nexport interface NodeHandlerOptions {\n /** Reject request bodies that exceed this many bytes. Default: unlimited. */\n maxBodyBytes?: number;\n}\n\nconst shouldReadNodeBody = (method: string): boolean => method !== 'GET' && method !== 'HEAD';\n\nclass NodeRequestLimitError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'NodeRequestLimitError';\n }\n}\n\nconst getSingleHeader = (\n headers: NodeIncomingMessage['headers'],\n name: string\n): string | undefined => {\n const value = headers[name];\n if (Array.isArray(value)) return value[0];\n return value;\n};\n\nconst getContentLength = (req: NodeIncomingMessage): number | null => {\n const header = getSingleHeader(req.headers, 'content-length');\n if (!header) return null;\n const value = Number.parseInt(header, 10);\n return Number.isSafeInteger(value) && value >= 0 ? value : null;\n};\n\nconst readNodeBody = (req: NodeIncomingMessage, maxBodyBytes?: number): Promise<ArrayBuffer> =>\n new Promise((resolve, reject) => {\n const chunks: Uint8Array[] = [];\n let total = 0;\n let done = false;\n const fail = (error: unknown): void => {\n if (done) return;\n done = true;\n chunks.length = 0;\n total = 0;\n req.destroy?.(error instanceof Error ? error : undefined);\n reject(error);\n };\n\n const declaredLength = getContentLength(req);\n if (maxBodyBytes !== undefined && declaredLength !== null && declaredLength > maxBodyBytes) {\n fail(new NodeRequestLimitError(`Request body exceeds ${maxBodyBytes} bytes.`));\n return;\n }\n\n req.on('data', (chunk) => {\n if (done) return;\n const bytes = typeof chunk === 'string' ? new TextEncoder().encode(chunk) : chunk;\n total += bytes.byteLength;\n if (maxBodyBytes !== undefined && total > maxBodyBytes) {\n fail(new NodeRequestLimitError(`Request body exceeds ${maxBodyBytes} bytes.`));\n return;\n }\n chunks.push(bytes);\n });\n req.on('end', () => {\n if (done) return;\n done = true;\n const buffer = new ArrayBuffer(total);\n const body = new Uint8Array(buffer);\n let offset = 0;\n for (const chunk of chunks) {\n body.set(chunk, offset);\n offset += chunk.byteLength;\n }\n resolve(buffer);\n });\n req.on('error', fail);\n });\n\nconst buildNodeUrl = (req: NodeIncomingMessage, protocol: string): URL => {\n const fallbackOrigin = `${protocol}://localhost`;\n const host = getSingleHeader(req.headers, 'host') || 'localhost';\n try {\n return new URL(req.url ?? '/', `${protocol}://${host}`);\n } catch {\n try {\n return new URL(req.url ?? '/', fallbackOrigin);\n } catch {\n return new URL('/', fallbackOrigin);\n }\n }\n};\n\nconst buildRequestFromNode = async (\n req: NodeIncomingMessage,\n options: NodeHandlerOptions = {}\n): Promise<Request> => {\n // Only honour `x-forwarded-proto` when it advertises a known protocol.\n // This adapter assumes deployment behind a trusted reverse proxy; callers\n // exposing `node:http` directly to the public internet should strip\n // `x-forwarded-*` headers in their proxy layer.\n const forwardedProto =\n typeof getSingleHeader(req.headers, 'x-forwarded-proto') === 'string'\n ? (getSingleHeader(req.headers, 'x-forwarded-proto') as string)\n .split(',')[0]\n .trim()\n .toLowerCase()\n : '';\n const protocol =\n forwardedProto === 'http' || forwardedProto === 'https' ? forwardedProto : 'http';\n const url = buildNodeUrl(req, protocol);\n\n const headers = new Headers();\n for (const [name, value] of Object.entries(req.headers)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) {\n for (const v of value) headers.append(name, v);\n } else {\n headers.append(name, value);\n }\n }\n\n const upperMethod = (req.method ?? 'GET').toUpperCase();\n const init: RequestInit = {\n method: upperMethod,\n headers,\n };\n\n if (shouldReadNodeBody(upperMethod)) {\n init.body = await readNodeBody(req, options.maxBodyBytes);\n }\n\n return new Request(url.toString(), init);\n};\n\ntype HeadersWithSetCookie = Headers & {\n getSetCookie?: () => string[];\n};\n\nconst getSetCookieHeaderValues = (headers: Headers): string[] => {\n const setCookies = (headers as HeadersWithSetCookie).getSetCookie?.();\n if (Array.isArray(setCookies) && setCookies.length > 0) {\n return setCookies;\n }\n const fallback = headers.get('set-cookie');\n return fallback ? [fallback] : [];\n};\n\nconst waitForNodeDrain = (res: NodeServerResponse): Promise<void> =>\n new Promise((resolve, reject) => {\n const once = typeof res.once === 'function' ? res.once.bind(res) : undefined;\n const on = typeof res.on === 'function' ? res.on.bind(res) : undefined;\n const subscribe = once ?? on;\n if (!subscribe) {\n resolve();\n return;\n }\n subscribe('drain', () => resolve());\n subscribe('error', (error?: unknown) => {\n reject(\n error instanceof Error ? error : new Error('Node response stream errored while draining.')\n );\n });\n });\n\nconst writeResponseToNode = async (response: Response, res: NodeServerResponse): Promise<void> => {\n res.statusCode = response.status;\n const setCookies = getSetCookieHeaderValues(response.headers);\n if (setCookies.length > 0) {\n res.setHeader('set-cookie', setCookies.length === 1 ? setCookies[0] : setCookies);\n }\n response.headers.forEach((value, name) => {\n if (name.toLowerCase() === 'set-cookie') return;\n res.setHeader(name, value);\n });\n\n if (!response.body) {\n res.end();\n return;\n }\n\n const reader = response.body.getReader();\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n if (value && !res.write(value)) {\n await waitForNodeDrain(res);\n }\n }\n res.end();\n};\n\n/**\n * Wraps a handler so it can be passed directly to a `node:http` server.\n *\n * @example\n * ```ts\n * import { createServer } from 'node:http';\n * import { createNodeHandler, renderToResponse } from '@bquery/bquery/ssr';\n *\n * const handler = createNodeHandler(async (request) => {\n * return renderToResponse('<div bq-text=\"msg\"></div>', { msg: 'Hello' });\n * });\n *\n * createServer(handler).listen(3000);\n * ```\n */\nexport const createNodeHandler = (\n handler: SSRRequestHandler,\n options: NodeHandlerOptions = {}\n): ((req: NodeIncomingMessage, res: NodeServerResponse) => Promise<void>) => {\n return async (req, res) => {\n let request: Request;\n try {\n request = await buildRequestFromNode(req, options);\n } catch (error) {\n if (error instanceof NodeRequestLimitError) {\n await writeResponseToNode(new Response(error.message, { status: 413 }), res);\n return;\n }\n throw error;\n }\n const response = await Promise.resolve(handler(request));\n await writeResponseToNode(response, res);\n };\n};\n\n/* ---------------------------------------------------------------------------\n * Auto-detection\n * ------------------------------------------------------------------------- */\n\n/**\n * Convenience helper that picks the right adapter based on the current\n * runtime. Returns the same handler unchanged for Web/Bun/Deno (they share a\n * fetch-style signature). On Node it returns the `node:http` adapter.\n */\nexport const createSSRHandler = (\n handler: SSRRequestHandler\n): SSRRequestHandler | ((req: NodeIncomingMessage, res: NodeServerResponse) => Promise<void>) => {\n const runtime = detectRuntime();\n switch (runtime) {\n case 'node':\n return createNodeHandler(handler);\n case 'bun':\n return createBunHandler(handler);\n case 'deno':\n return createDenoHandler(handler);\n default:\n return createWebHandler(handler);\n }\n};\n"],"mappings":";;;;;;;AAmEA,IAAa,KAAA,CACX,GACA,GACA,IAA+B,CAAC,MACvB;AACT,QAAM,EAAE,SAAA,IAAU,IAAM,GAAG,EAAA,IAAiB;AAE5C,MAAI,CAAC,EACH,OAAM,IAAI,MACR,kFACF;AAKF,SAAO,GAAM,GAAU,GAAS,CAAY;AAC9C,GCrDM,IAAoB;AAAA,EACxB,SAAS;AAAA,EACT,cAAc;AAChB,GAca,KAAA,CACX,MACS;AACT,EAAI,EAAQ,YAAY,WAAW,EAAO,UAAU,EAAQ,UACxD,EAAQ,iBAAiB,WAAW,EAAO,eAAe,EAAQ;AACxE,GAKa,KAAA,OAA2C;AAAA,EACtD,SAAS,EAAO;AAAA,EAChB,cAAc,EAAO;AACvB,IAQa,KAAA,MACP,EAAO,YAAY,SAAe,SAClC,EAAO,YAAY,SAEnB,EAAO,gBACP,OAAO,WAAW,aAAc,aAAmB,QAChD,QAOI,KAAA,MACP,EAAO,eAAqB,EAAO,aAAa,YAChD,OAAO,WAAW,aAAc,aAAmB,WAAW,YAC3D,MCjEI,KAAA,CAAa,MAA0B;AAClD,MAAI,IAAI;AACR,WAAS,IAAI,GAAG,IAAI,EAAM,QAAQ,IAChC,CAAA,KAAM,KAAK,KAAK,IAAI,EAAM,WAAW,CAAC,IAAK;AAE7C,UAAQ,MAAM,GAAG,SAAS,EAAE;AAC9B,GAMa,KAAsB,aAQtB,KAAA,CACX,GACA,GACA,MACW;AACX,QAAM,IAAkB,CAAC;AACzB,aAAW,KAAQ;AACjB,IAAI,MAAA,gBACA,EAAK,WAAW,GAAG,CAAA,GAAS,KAAK,EAAK,WAAW,GAAG,MACtD,EAAM,KAAK,GAAG,CAAA,IAAQ,EAAW,CAAA,KAAS,EAAA,EAAI;AAGlD,SAAO,EAAM,KAAK,GAAG;AACvB,GAQa,KAAA,CAAwC,GAAa,MAA2B;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