@askrjs/askr 0.0.1 → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -10
- package/dist/chunk-KR6HG7HF.js +38 -0
- package/dist/chunk-KR6HG7HF.js.map +1 -0
- package/dist/{chunk-L7RL4LYV.js → chunk-MIPES65F.js} +1486 -1905
- package/dist/chunk-MIPES65F.js.map +1 -0
- package/dist/{chunk-HIWJVOS4.js → chunk-PFOLLB6A.js} +38 -17
- package/dist/chunk-PFOLLB6A.js.map +1 -0
- package/dist/chunk-QECQ2TF6.js +28 -0
- package/dist/chunk-QECQ2TF6.js.map +1 -0
- package/dist/{chunk-UUM5W2RM.js → chunk-RJWOOUYV.js} +2 -2
- package/dist/chunk-RJWOOUYV.js.map +1 -0
- package/dist/index.cjs +1760 -1972
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +52 -40
- package/dist/index.d.ts +52 -40
- package/dist/index.js +226 -52
- package/dist/index.js.map +1 -1
- package/dist/jsx/jsx-dev-runtime.cjs +9 -3
- package/dist/jsx/jsx-dev-runtime.cjs.map +1 -1
- package/dist/jsx/jsx-dev-runtime.d.cts +4 -9
- package/dist/jsx/jsx-dev-runtime.d.ts +4 -9
- package/dist/jsx/jsx-dev-runtime.js +10 -4
- package/dist/jsx/jsx-dev-runtime.js.map +1 -1
- package/dist/jsx/jsx-runtime.cjs +14 -5
- package/dist/jsx/jsx-runtime.cjs.map +1 -1
- package/dist/jsx/jsx-runtime.d.cts +9 -6
- package/dist/jsx/jsx-runtime.d.ts +9 -6
- package/dist/jsx/jsx-runtime.js +6 -2
- package/dist/{navigate-NLQOZQGM.js → navigate-SDZNA2ZE.js} +5 -5
- package/dist/{route-TVYWYCEJ.js → route-P5YQBT4T.js} +4 -4
- package/dist/{ssr-4ELUFK65.js → ssr-65K3IJ6B.js} +9 -5
- package/dist/{types-DUDmnzD8.d.cts → types-DLTViI21.d.cts} +15 -3
- package/dist/{types-DUDmnzD8.d.ts → types-DLTViI21.d.ts} +15 -3
- package/package.json +5 -3
- package/src/jsx/index.ts +4 -0
- package/src/jsx/jsx-dev-runtime.ts +7 -10
- package/src/jsx/jsx-runtime.ts +23 -11
- package/src/jsx/types.ts +22 -3
- package/src/jsx/utils.ts +19 -0
- package/dist/chunk-4CV4JOE5.js +0 -27
- package/dist/chunk-HIWJVOS4.js.map +0 -1
- package/dist/chunk-L7RL4LYV.js.map +0 -1
- package/dist/chunk-UUM5W2RM.js.map +0 -1
- package/dist/chunk-YNH3D4KW.js +0 -29
- package/dist/chunk-YNH3D4KW.js.map +0 -1
- package/dist/ssr-4ELUFK65.js.map +0 -1
- package/src/jsx/react-jsx-runtime.d.ts +0 -0
- /package/dist/{chunk-4CV4JOE5.js.map → navigate-SDZNA2ZE.js.map} +0 -0
- /package/dist/{navigate-NLQOZQGM.js.map → route-P5YQBT4T.js.map} +0 -0
- /package/dist/{route-TVYWYCEJ.js.map → ssr-65K3IJ6B.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/dev/invariant.ts","../src/dev/logger.ts","../src/runtime/scheduler.ts","../src/runtime/fastlane.ts","../src/runtime/context.ts","../src/renderer/dom.ts","../src/runtime/component.ts","../src/router/route.ts","../src/router/match.ts"],"sourcesContent":["/**\n * Invariant assertion utilities for correctness checking\n * Production-safe: invariants are enforced at build-time or with minimal overhead\n *\n * Core principle: fail fast when invariants are violated\n * All functions throw descriptive errors for debugging\n */\n\n/**\n * Assert a condition; throw with context if false\n * @internal\n */\nexport function invariant(\n condition: boolean,\n message: string,\n context?: Record<string, unknown>\n): asserts condition {\n if (!condition) {\n const contextStr = context ? '\\n' + JSON.stringify(context, null, 2) : '';\n throw new Error(`[Askr Invariant] ${message}${contextStr}`);\n }\n}\n\n/**\n * Assert object property exists and has correct type\n * @internal\n */\nexport function assertProperty<T extends object, K extends keyof T>(\n obj: T,\n prop: K,\n expectedType?: string\n): asserts obj is T & Required<Pick<T, K>> {\n invariant(prop in obj, `Object missing required property '${String(prop)}'`, {\n object: obj,\n });\n\n if (expectedType) {\n const actualType = typeof obj[prop];\n invariant(\n actualType === expectedType,\n `Property '${String(prop)}' has type '${actualType}', expected '${expectedType}'`,\n { value: obj[prop], expectedType }\n );\n }\n}\n\n/**\n * Assert a reference is not null/undefined\n * @internal\n */\nexport function assertDefined<T>(\n value: T | null | undefined,\n message: string\n): asserts value is T {\n invariant(value !== null && value !== undefined, message, { value });\n}\n\n/**\n * Assert a task runs exactly once atomically\n * Useful for verifying lifecycle events fire precisely when expected\n * @internal\n */\nexport class Once {\n private called = false;\n private calledAt: number | null = null;\n readonly name: string;\n\n constructor(name: string) {\n this.name = name;\n }\n\n check(): boolean {\n return this.called;\n }\n\n mark(): void {\n invariant(\n !this.called,\n `${this.name} called multiple times (previously at ${this.calledAt}ms)`,\n { now: Date.now() }\n );\n this.called = true;\n this.calledAt = Date.now();\n }\n\n reset(): void {\n this.called = false;\n this.calledAt = null;\n }\n}\n\n/**\n * Assert a value falls in an enumerated set\n * @internal\n */\nexport function assertEnum<T extends readonly unknown[]>(\n value: unknown,\n allowedValues: T,\n fieldName: string\n): asserts value is T[number] {\n invariant(\n allowedValues.includes(value),\n `${fieldName} must be one of [${allowedValues.join(', ')}], got ${JSON.stringify(value)}`,\n { value, allowed: allowedValues }\n );\n}\n\n/**\n * Assert execution context (scheduler, component, etc)\n * @internal\n */\nexport function assertContext(\n actual: unknown,\n expected: unknown,\n contextName: string\n): asserts actual is typeof expected {\n invariant(\n actual === expected,\n `Invalid ${contextName} context. Expected ${expected}, got ${actual}`,\n { expected, actual }\n );\n}\n\n/**\n * Assert scheduling precondition (not reentering, not during render, etc)\n * @internal\n */\nexport function assertSchedulingPrecondition(\n condition: boolean,\n violationMessage: string\n): asserts condition {\n invariant(condition, `[Scheduler Precondition] ${violationMessage}`);\n}\n\n/**\n * Assert state precondition\n * @internal\n */\nexport function assertStatePrecondition(\n condition: boolean,\n violationMessage: string\n): asserts condition {\n invariant(condition, `[State Precondition] ${violationMessage}`);\n}\n\n/**\n * Verify AbortController lifecycle\n * @internal\n */\nexport function assertAbortControllerState(\n signal: AbortSignal,\n expectedAborted: boolean,\n context: string\n): void {\n invariant(\n signal.aborted === expectedAborted,\n `AbortSignal ${expectedAborted ? 'should be' : 'should not be'} aborted in ${context}`,\n { actual: signal.aborted, expected: expectedAborted }\n );\n}\n\n/**\n * Guard: throw if callback is null when it shouldn't be\n * Used for notifyUpdate, event handlers, etc.\n * @internal\n */\nexport function assertCallbackAvailable<\n T extends (...args: unknown[]) => unknown,\n>(callback: T | null | undefined, callbackName: string): asserts callback is T {\n invariant(\n callback !== null && callback !== undefined,\n `${callbackName} callback is required but not available`,\n { callback }\n );\n}\n\n/**\n * Verify evaluation generation prevents stale evaluations\n * @internal\n */\nexport function assertEvaluationGeneration(\n current: number,\n latest: number,\n context: string\n): void {\n invariant(\n current === latest,\n `Stale evaluation generation in ${context}: current ${current}, latest ${latest}`,\n { current, latest }\n );\n}\n\n/**\n * Verify mounted flag state\n * @internal\n */\nexport function assertMountedState(\n mounted: boolean,\n expectedMounted: boolean,\n context: string\n): void {\n invariant(\n mounted === expectedMounted,\n `Invalid mounted state in ${context}: expected ${expectedMounted}, got ${mounted}`,\n { mounted, expected: expectedMounted }\n );\n}\n\n/**\n * Verify no null target when rendering\n * @internal\n */\nexport function assertRenderTarget(\n target: Element | null,\n context: string\n): asserts target is Element {\n invariant(target !== null, `Cannot render in ${context}: target is null`, {\n target,\n });\n}\n","/**\n * Centralized logger interface\n * - Keeps production builds silent for debug/warn/info messages\n * - Ensures consistent behavior across the codebase\n * - Protects against missing `console` in some environments\n */\n\nfunction callConsole(method: string, args: unknown[]): void {\n const c = typeof console !== 'undefined' ? (console as unknown) : undefined;\n if (!c) return;\n const fn = (c as Record<string, unknown>)[method];\n if (typeof fn === 'function') {\n try {\n (fn as (...a: unknown[]) => unknown).apply(console, args as unknown[]);\n } catch {\n // ignore logging errors\n }\n }\n}\n\nexport const logger = {\n debug: (...args: unknown[]) => {\n if (process.env.NODE_ENV === 'production') return;\n callConsole('debug', args);\n },\n\n info: (...args: unknown[]) => {\n if (process.env.NODE_ENV === 'production') return;\n callConsole('info', args);\n },\n\n warn: (...args: unknown[]) => {\n if (process.env.NODE_ENV === 'production') return;\n callConsole('warn', args);\n },\n\n error: (...args: unknown[]) => {\n callConsole('error', args);\n },\n};\n","/**\n * Serialized update scheduler — safer design (no inline execution, explicit flush)\n *\n * Key ideas:\n * - Never execute a task inline from `enqueue`.\n * - `flush()` is explicit and non-reentrant.\n * - `runWithSyncProgress()` allows enqueues temporarily but does not run tasks\n * inline; it runs `fn` and then does an explicit `flush()`.\n * - `waitForFlush()` is race-free with a monotonic `flushVersion`.\n */\n\nimport { assertSchedulingPrecondition, invariant } from '../dev/invariant';\nimport { logger } from '../dev/logger';\n\nconst MAX_FLUSH_DEPTH = 50;\n\ntype Task = () => void;\n\nfunction isBulkCommitActive(): boolean {\n try {\n const fb = (\n globalThis as unknown as {\n __ASKR_FASTLANE?: { isBulkCommitActive?: () => boolean };\n }\n ).__ASKR_FASTLANE;\n return typeof fb?.isBulkCommitActive === 'function'\n ? !!fb.isBulkCommitActive()\n : false;\n } catch (e) {\n void e;\n return false;\n }\n}\n\nexport class Scheduler {\n private q: Task[] = [];\n private head = 0;\n\n private running = false;\n private inHandler = false;\n private depth = 0;\n private executionDepth = 0; // for compat with existing diagnostics\n\n // Monotonic flush version increments at end of each flush\n private flushVersion = 0;\n\n // Best-effort microtask kick scheduling\n private kickScheduled = false;\n\n // Escape hatch flag for runWithSyncProgress\n private allowSyncProgress = false;\n\n // Waiters waiting for flushVersion >= target\n private waiters: Array<{\n target: number;\n resolve: () => void;\n reject: (err: unknown) => void;\n timer?: ReturnType<typeof setTimeout>;\n }> = [];\n\n // Keep a lightweight taskCount for compatibility/diagnostics\n private taskCount = 0;\n\n enqueue(task: Task): void {\n assertSchedulingPrecondition(\n typeof task === 'function',\n 'enqueue() requires a function'\n );\n\n // Strict rule: during bulk commit, only allow enqueues if runWithSyncProgress enabled\n if (isBulkCommitActive() && !this.allowSyncProgress) {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(\n '[Scheduler] enqueue() during bulk commit (not allowed)'\n );\n }\n return;\n }\n\n // Enqueue task and account counts\n this.q.push(task);\n this.taskCount++;\n\n // Microtask kick: best-effort, but avoid if we are in handler or running or bulk commit\n if (\n !this.running &&\n !this.kickScheduled &&\n !this.inHandler &&\n !isBulkCommitActive()\n ) {\n this.kickScheduled = true;\n queueMicrotask(() => {\n this.kickScheduled = false;\n if (this.running) return;\n if (isBulkCommitActive()) return;\n try {\n this.flush();\n } catch (err) {\n setTimeout(() => {\n throw err;\n });\n }\n });\n }\n }\n\n flush(): void {\n invariant(\n !this.running,\n '[Scheduler] flush() called while already running'\n );\n\n // Dev-only guard: disallow flush during bulk commit unless allowed\n if (process.env.NODE_ENV !== 'production') {\n if (isBulkCommitActive() && !this.allowSyncProgress) {\n throw new Error(\n '[Scheduler] flush() started during bulk commit (not allowed)'\n );\n }\n }\n\n this.running = true;\n this.depth = 0;\n let fatal: unknown = null;\n\n try {\n while (this.head < this.q.length) {\n this.depth++;\n if (\n process.env.NODE_ENV !== 'production' &&\n this.depth > MAX_FLUSH_DEPTH\n ) {\n throw new Error(\n `[Scheduler] exceeded MAX_FLUSH_DEPTH (${MAX_FLUSH_DEPTH}). Likely infinite update loop.`\n );\n }\n\n const task = this.q[this.head++];\n try {\n this.executionDepth++;\n task();\n this.executionDepth--;\n } catch (err) {\n // ensure executionDepth stays balanced\n if (this.executionDepth > 0) this.executionDepth = 0;\n fatal = err;\n break;\n }\n\n // Account for executed task in taskCount\n if (this.taskCount > 0) this.taskCount--;\n }\n } finally {\n this.running = false;\n this.depth = 0;\n this.executionDepth = 0;\n\n // Compact queue\n if (this.head >= this.q.length) {\n this.q.length = 0;\n this.head = 0;\n } else if (this.head > 0) {\n const remaining = this.q.length - this.head;\n if (this.head > 1024 || this.head > remaining) {\n this.q = this.q.slice(this.head);\n } else {\n for (let i = 0; i < remaining; i++) {\n this.q[i] = this.q[this.head + i];\n }\n this.q.length = remaining;\n }\n this.head = 0;\n }\n\n // Advance flush epoch and resolve waiters\n this.flushVersion++;\n this.resolveWaiters();\n }\n\n if (fatal) throw fatal;\n }\n\n runWithSyncProgress<T>(fn: () => T): T {\n const prev = this.allowSyncProgress;\n this.allowSyncProgress = true;\n\n const g = globalThis as unknown as {\n queueMicrotask?: (...args: unknown[]) => void;\n setTimeout?: (...args: unknown[]) => unknown;\n };\n const origQueueMicrotask = g.queueMicrotask;\n const origSetTimeout = g.setTimeout;\n\n if (process.env.NODE_ENV !== 'production') {\n g.queueMicrotask = () => {\n throw new Error(\n '[Scheduler] queueMicrotask not allowed during runWithSyncProgress'\n );\n };\n g.setTimeout = () => {\n throw new Error(\n '[Scheduler] setTimeout not allowed during runWithSyncProgress'\n );\n };\n }\n\n // Snapshot flushVersion so we can ensure we always complete an epoch\n const startVersion = this.flushVersion;\n\n try {\n const res = fn();\n\n // Flush deterministically if tasks were enqueued (and we're not already running)\n if (!this.running && this.q.length - this.head > 0) {\n this.flush();\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (this.q.length - this.head > 0) {\n throw new Error(\n '[Scheduler] tasks remain after runWithSyncProgress flush'\n );\n }\n }\n\n return res;\n } finally {\n // Restore guarded globals\n if (process.env.NODE_ENV !== 'production') {\n g.queueMicrotask = origQueueMicrotask;\n g.setTimeout = origSetTimeout;\n }\n\n // If no flush happened during the protected window, complete an epoch so\n // observers (tests) see progress even when fast-lane did synchronous work\n // without enqueuing tasks.\n try {\n if (this.flushVersion === startVersion) {\n this.flushVersion++;\n this.resolveWaiters();\n }\n } catch (e) {\n void e;\n }\n\n this.allowSyncProgress = prev;\n }\n }\n\n waitForFlush(targetVersion?: number, timeoutMs = 2000): Promise<void> {\n const target =\n typeof targetVersion === 'number' ? targetVersion : this.flushVersion + 1;\n if (this.flushVersion >= target) return Promise.resolve();\n\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n const diag = {\n flushVersion: this.flushVersion,\n queueLen: this.q.length - this.head,\n running: this.running,\n inHandler: this.inHandler,\n bulk: isBulkCommitActive(),\n globals: {\n __ASKR_LAST_FASTPATH_STATS: (\n globalThis as unknown as Record<string, unknown>\n ).__ASKR_LAST_FASTPATH_STATS,\n __ASKR_LAST_BULK_TEXT_FASTPATH_STATS: (\n globalThis as unknown as Record<string, unknown>\n ).__ASKR_LAST_BULK_TEXT_FASTPATH_STATS,\n __ASKR_FASTPATH_COUNTERS: (\n globalThis as unknown as Record<string, unknown>\n ).__ASKR_FASTPATH_COUNTERS,\n },\n };\n reject(\n new Error(\n `waitForFlush timeout ${timeoutMs}ms: ${JSON.stringify(diag)}`\n )\n );\n }, timeoutMs);\n\n this.waiters.push({ target, resolve, reject, timer });\n });\n }\n\n getState() {\n // Provide the compatibility shape expected by diagnostics/tests\n return {\n queueLength: this.q.length - this.head,\n running: this.running,\n depth: this.depth,\n executionDepth: this.executionDepth,\n taskCount: this.taskCount,\n flushVersion: this.flushVersion,\n // New fields for optional inspection\n inHandler: this.inHandler,\n allowSyncProgress: this.allowSyncProgress,\n };\n }\n\n setInHandler(v: boolean) {\n this.inHandler = v;\n }\n\n isInHandler(): boolean {\n return this.inHandler;\n }\n\n isExecuting(): boolean {\n return this.running || this.executionDepth > 0;\n }\n\n // Clear pending synchronous tasks (used by fastlane enter/exit)\n clearPendingSyncTasks(): number {\n const remaining = this.q.length - this.head;\n if (remaining <= 0) return 0;\n\n if (this.running) {\n this.q.length = this.head;\n this.taskCount = Math.max(0, this.taskCount - remaining);\n queueMicrotask(() => {\n try {\n this.flushVersion++;\n this.resolveWaiters();\n } catch (e) {\n void e;\n }\n });\n return remaining;\n }\n\n this.q.length = 0;\n this.head = 0;\n this.taskCount = Math.max(0, this.taskCount - remaining);\n this.flushVersion++;\n this.resolveWaiters();\n return remaining;\n }\n\n private resolveWaiters() {\n if (this.waiters.length === 0) return;\n const ready: Array<() => void> = [];\n const remaining: typeof this.waiters = [];\n\n for (const w of this.waiters) {\n if (this.flushVersion >= w.target) {\n if (w.timer) clearTimeout(w.timer);\n ready.push(w.resolve);\n } else {\n remaining.push(w);\n }\n }\n\n this.waiters = remaining;\n for (const r of ready) r();\n }\n}\n\nexport const globalScheduler = new Scheduler();\n\nexport function isSchedulerExecuting(): boolean {\n return globalScheduler.isExecuting();\n}\n\nexport function scheduleEventHandler(handler: EventListener): EventListener {\n return (event: Event) => {\n globalScheduler.setInHandler(true);\n try {\n handler.call(null, event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n } finally {\n globalScheduler.setInHandler(false);\n // If the handler enqueued tasks while we disallowed microtask kicks,\n // ensure we schedule a microtask to flush them now that the handler\n // has completed. This avoids tests timing out waiting for flush.\n const state = globalScheduler.getState();\n if ((state.queueLength ?? 0) > 0 && !state.running) {\n queueMicrotask(() => {\n try {\n if (!globalScheduler.isExecuting()) globalScheduler.flush();\n } catch (err) {\n setTimeout(() => {\n throw err;\n });\n }\n });\n }\n }\n };\n}\n","import { globalScheduler } from './scheduler';\nimport { logger } from '../dev/logger';\nimport {\n getKeyMapForElement,\n isKeyedReorderFastPathEligible,\n} from '../renderer/dom';\nimport type { ComponentInstance } from './component';\n\nlet _bulkCommitActive = false;\nlet _appliedParents: WeakSet<Element> | null = null;\n\nexport function enterBulkCommit(): void {\n _bulkCommitActive = true;\n // Initialize registry of parents that had fast-path applied during this bulk commit\n _appliedParents = new WeakSet<Element>();\n\n // Clear any previously scheduled synchronous scheduler tasks so they don't\n // retrigger evaluations during the committed fast-path. This is a safety\n // barrier to enforce quiescence for bulk commits.\n try {\n const cleared = globalScheduler.clearPendingSyncTasks?.() ?? 0;\n if (process.env.NODE_ENV !== 'production') {\n const _g = globalThis as unknown as Record<string, unknown>;\n _g.__ASKR_FASTLANE_CLEARED_TASKS = cleared;\n }\n } catch (err) {\n // In the unlikely event clearing fails in production, ignore it; in dev rethrow\n if (process.env.NODE_ENV !== 'production') throw err;\n }\n}\n\nexport function exitBulkCommit(): void {\n _bulkCommitActive = false;\n // Clear registry to avoid leaking across commits\n _appliedParents = null;\n}\n\nexport function isBulkCommitActive(): boolean {\n return _bulkCommitActive;\n}\n\n// Mark that a fast-path was applied on a parent element during the active\n// bulk commit. No-op if there is no active bulk commit.\nexport function markFastPathApplied(parent: Element): void {\n if (!_appliedParents) return;\n try {\n _appliedParents.add(parent);\n } catch (e) {\n void e;\n }\n}\n\nexport function isFastPathApplied(parent: Element): boolean {\n return !!(_appliedParents && _appliedParents.has(parent));\n}\n\n/**\n * Attempt to execute a runtime fast-lane for a single component's synchronous\n * render result. Returns true if the fast-lane was used and commit was done.\n *\n * Preconditions (checked conservatively):\n * - The render result is an intrinsic element root with keyed children\n * - The renderer's fast-path heuristics indicate to use the fast-path\n * - No mount operations are pending on the component instance\n * - No child vnodes are component functions (avoid async/component mounts)\n */\nexport function classifyUpdate(instance: ComponentInstance, result: unknown) {\n // Returns a classification describing whether this update is eligible for\n // the reorder-only fast-lane. The classifier mirrors renderer-level\n // heuristics and performs runtime-level checks (mounts, effects, component\n // children) that the renderer cannot reason about.\n if (!result || typeof result !== 'object' || !('type' in result))\n return { useFastPath: false, reason: 'not-vnode' };\n const vnode = result as {\n type: unknown;\n children?: unknown;\n props?: { children?: unknown };\n };\n if (vnode == null || typeof vnode.type !== 'string')\n return { useFastPath: false, reason: 'not-intrinsic' };\n\n const parent = instance.target;\n if (!parent) return { useFastPath: false, reason: 'no-root' };\n\n const firstChild = parent.children[0] as Element | undefined;\n if (!firstChild) return { useFastPath: false, reason: 'no-first-child' };\n if (firstChild.tagName.toLowerCase() !== String(vnode.type).toLowerCase())\n return { useFastPath: false, reason: 'root-tag-mismatch' };\n\n const children =\n (vnode as { children?: unknown; props?: { children?: unknown } })\n .children ||\n (vnode as { props?: { children?: unknown } }).props?.children;\n if (!Array.isArray(children))\n return { useFastPath: false, reason: 'no-children-array' };\n\n // Avoid component child vnodes (they may mount/unmount or trigger async)\n for (let i = 0; i < children.length; i++) {\n const c = children[i];\n if (\n typeof c === 'object' &&\n c !== null &&\n 'type' in c &&\n typeof (c as { type?: unknown }).type === 'function'\n ) {\n return { useFastPath: false, reason: 'component-child-present' };\n }\n }\n\n if (instance.mountOperations.length > 0)\n return { useFastPath: false, reason: 'pending-mounts' };\n\n // Ask renderer for keyed reorder eligibility (prop differences & heuristics)\n const oldKeyMap = getKeyMapForElement(firstChild);\n const decision = isKeyedReorderFastPathEligible(\n firstChild,\n children,\n oldKeyMap\n );\n\n if (!decision.useFastPath || decision.totalKeyed < 128)\n return { ...decision, useFastPath: false, reason: 'renderer-declined' };\n\n return { ...decision, useFastPath: true } as const;\n}\n\nexport function commitReorderOnly(\n instance: ComponentInstance,\n result: unknown\n) {\n // Performs the minimal, synchronous reorder-only commit. Sets dev-only\n // diagnostic fields on globalThis for test assertions and verifies\n // invariants (no mounts, no effects, single DOM commit).\n const evaluate = (\n globalThis as unknown as {\n __ASKR_RENDERER?: {\n evaluate?: (node: unknown, target: Element | null) => void;\n };\n }\n ).__ASKR_RENDERER?.evaluate;\n if (typeof evaluate !== 'function') {\n logger.warn(\n '[Tempo][FASTPATH][DEV] renderer.evaluate not available; declining fast-lane'\n );\n return false;\n }\n\n const schedBefore =\n process.env.NODE_ENV !== 'production' ? globalScheduler.getState() : null;\n\n enterBulkCommit();\n\n try {\n // Execute the renderer synchronously inside a controlled scheduler\n // escape hatch that allows deterministic synchronous scheduler progress\n // while still preserving bulk-commit semantics (no async tasks, single DOM\n // mutation, and rollback safety).\n globalScheduler.runWithSyncProgress(() => {\n evaluate(result, instance.target);\n\n // Ensure runtime bookkeeping (read subscriptions / tokens) is finalized\n // even when we bypass the normal scheduler-driven commit path.\n try {\n // Import function dynamically to avoid circular import at module top-level\n // (component module defines finalizeReadSubscriptions).\n // eslint-disable-next-line @typescript-eslint/no-require-imports -- circular import; require used intentionally to perform a synchronous call\n const comp = require('./component') as typeof import('./component');\n if (typeof comp?.finalizeReadSubscriptions === 'function') {\n try {\n comp.finalizeReadSubscriptions(instance);\n } catch (e) {\n // Surface in dev, ignore in prod\n if (process.env.NODE_ENV !== 'production') throw e;\n }\n }\n } catch (e) {\n void e;\n }\n });\n\n // Safety: clear any synchronous tasks that were scheduled during the commit\n // but did not get executed due to flush reentrancy or microtask timing. This\n // ensures final quiescence for bulk commits.\n try {\n const clearedAfter = globalScheduler.clearPendingSyncTasks?.() ?? 0;\n if (process.env.NODE_ENV !== 'production') {\n const _g = globalThis as unknown as Record<string, unknown>;\n _g.__ASKR_FASTLANE_CLEARED_AFTER = clearedAfter;\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') throw err;\n }\n\n // Dev-only invariant checks and diagnostics\n if (process.env.NODE_ENV !== 'production') {\n // Commit count recorded by renderer (set by fast-path code)\n const _g = globalThis as unknown as Record<string, unknown>;\n const commitCount =\n (_g.__ASKR_LAST_FASTPATH_COMMIT_COUNT as number | undefined) ?? 0;\n const invariants = {\n commitCount,\n mountOps: instance.mountOperations.length,\n cleanupFns: instance.cleanupFns.length,\n } as const;\n _g.__ASKR_LAST_FASTLANE_INVARIANTS = invariants;\n\n if (commitCount !== 1) {\n throw new Error(\n 'Fast-lane invariant violated: expected exactly one DOM commit during reorder-only commit'\n );\n }\n if (invariants.mountOps > 0) {\n throw new Error(\n 'Fast-lane invariant violated: mount operations were registered during bulk commit'\n );\n }\n if (invariants.cleanupFns > 0) {\n throw new Error(\n 'Fast-lane invariant violated: cleanup functions were added during bulk commit'\n );\n }\n\n const schedAfter = globalScheduler.getState();\n if (\n schedBefore &&\n schedAfter &&\n // Only fail if outstanding tasks increased — consuming existing tasks is allowed\n schedAfter.taskCount > schedBefore.taskCount\n ) {\n try {\n console.error(\n '[FASTLANE] schedBefore, schedAfter',\n schedBefore,\n schedAfter\n );\n\n console.error(\n '[FASTLANE] enqueue logs',\n (globalThis as unknown as Record<string, unknown>)\n .__ASKR_ENQUEUE_LOGS\n );\n } catch (e) {\n void e;\n }\n throw new Error(\n 'Fast-lane invariant violated: scheduler enqueued leftover work during bulk commit'\n );\n }\n\n // Final quiescence assertion: ensure scheduler has no pending sync tasks\n let finalState = globalScheduler.getState();\n // Adjust expected task count by subtracting the currently executing task\n // (we're inside that task at the time of this check). The goal is to\n // ensure there are no *other* pending tasks beyond the active execution.\n const executing = globalScheduler.isExecuting();\n const outstandingAfter = Math.max(\n 0,\n finalState.taskCount - (executing ? 1 : 0)\n );\n\n if (outstandingAfter !== 0) {\n // Attempt to clear newly enqueued synchronous tasks that may have\n // been scheduled in microtasks or during remaining flush operations.\n // This loop is conservative and only runs in dev to help catch\n // flaky microtask timing windows; in prod we prefer to fail-safe by\n // dropping such tasks earlier.\n if (process.env.NODE_ENV !== 'production') {\n let attempts = 0;\n while (attempts < 5) {\n const cleared = globalScheduler.clearPendingSyncTasks?.() ?? 0;\n if (cleared === 0) break;\n attempts++;\n }\n finalState = globalScheduler.getState();\n const outstandingAfter2 = Math.max(\n 0,\n finalState.taskCount - (globalScheduler.isExecuting() ? 1 : 0)\n );\n if (outstandingAfter2 !== 0) {\n try {\n const _g = globalThis as unknown as Record<string, unknown>;\n\n console.error(\n '[FASTLANE] Post-commit enqueue logs:',\n _g.__ASKR_ENQUEUE_LOGS\n );\n\n console.error(\n '[FASTLANE] Cleared counts:',\n _g.__ASKR_FASTLANE_CLEARED_TASKS,\n _g.__ASKR_FASTLANE_CLEARED_AFTER\n );\n } catch (err) {\n void err;\n }\n throw new Error(\n `Fast-lane invariant violated: scheduler has ${finalState.taskCount} pending task(s) after commit`\n );\n }\n } else {\n // In production, silently drop remaining synchronous tasks to preserve\n // atomicity and avoid leaving the system in a non-quiescent state.\n globalScheduler.clearPendingSyncTasks?.();\n }\n }\n }\n\n return true;\n } finally {\n exitBulkCommit();\n\n // Dev-time: ensure the bulk commit flag was cleared by the end of the operation\n // NOTE: avoid throwing inside `finally` (no-unsafe-finally). Capture the\n // failure and rethrow after the finally block.\n // We set a flag on `globalThis` to check after the finally, which will be\n // handled below.\n if (process.env.NODE_ENV !== 'production') {\n try {\n const _g = globalThis as unknown as Record<string, unknown>;\n _g.__ASKR_FASTLANE_BULK_FLAG_CHECK = isBulkCommitActive();\n } catch (e) {\n void e;\n }\n }\n }\n\n // Re-check the captured assertion outside of finally and throw if needed\n if (process.env.NODE_ENV !== 'production') {\n const _g = globalThis as unknown as Record<string, unknown>;\n if (_g.__ASKR_FASTLANE_BULK_FLAG_CHECK) {\n delete _g.__ASKR_FASTLANE_BULK_FLAG_CHECK;\n throw new Error(\n 'Fast-lane invariant violated: bulk commit flag still set after commit'\n );\n }\n }\n}\n\nexport function tryRuntimeFastLaneSync(\n instance: ComponentInstance,\n result: unknown\n): boolean {\n const cls = classifyUpdate(instance, result);\n if (!cls.useFastPath) return false;\n\n try {\n return commitReorderOnly(instance, result);\n } catch (err) {\n // Surface dev-only invariant failures, otherwise decline silently\n if (process.env.NODE_ENV !== 'production') throw err;\n return false;\n }\n}\n\n// Expose fastlane bridge on globalThis for environments/tests that access it\n// synchronously without using ES module dynamic imports.\nif (typeof globalThis !== 'undefined') {\n const _g = globalThis as unknown as Record<string, unknown>;\n _g.__ASKR_FASTLANE = {\n isBulkCommitActive,\n enterBulkCommit,\n exitBulkCommit,\n tryRuntimeFastLaneSync,\n markFastPathApplied,\n isFastPathApplied,\n };\n}\n","/**\n * Context system: lexical scope + render-time snapshots\n *\n * CORE SEMANTIC (Option A — Snapshot-Based):\n * ============================================\n * An async resource observes the context of the render that created it.\n * Context changes only take effect via re-render, not magically mid-await.\n *\n * This ensures:\n * - Deterministic behavior\n * - Concurrency safety\n * - Replayable execution\n * - Debuggability\n *\n * INVARIANTS:\n * - readContext() only works during component render (has currentContextFrame)\n * - Each render captures a context snapshot\n * - Async continuations see the snapshot from render start (frozen)\n * - Provider (Scope) creates a new frame that shadows parent\n * - Context updates require re-render to take effect\n */\n\nimport type { JSXElement } from '../jsx/types';\nimport type { Props } from '../shared/types';\nimport { getCurrentComponentInstance } from './component';\n\nexport type ContextKey = symbol;\n\n// Lightweight VNode definition used for JSX typing in this module\ntype VNode = {\n type: string;\n props?: Record<string, unknown>;\n children?: (string | VNode | null | undefined | false)[];\n};\n\n// Union of allowed render return values (text, vnode, JSX element, etc.)\ntype Renderable =\n | JSXElement\n | VNode\n | string\n | number\n | null\n | undefined\n | false;\n\nexport interface Context<T> {\n readonly key: ContextKey;\n readonly defaultValue: T;\n // A Scope is a JSX-style element factory returning a JSXElement (component invocation)\n readonly Scope: (props: { value: T; children?: unknown }) => JSXElement;\n}\n\nexport interface ContextFrame {\n parent: ContextFrame | null;\n // Lazily allocate `values` Map only when a provider sets values or a read occurs.\n values: Map<ContextKey, unknown> | null;\n}\n\n// Symbol to mark vnodes that need frame restoration\nexport const CONTEXT_FRAME_SYMBOL = Symbol('__tempoContextFrame__');\n\n// Global context frame stack (maintained during render)\n// INVARIANT: Must NEVER be non-null across an await boundary\nlet currentContextFrame: ContextFrame | null = null;\n\n// Async resource frame (maintained during async resource execution)\n// INVARIANT: Set only for synchronous execution steps, cleared in finally\n// This allows async resources to access their frozen render-time snapshot\nlet currentAsyncResourceFrame: ContextFrame | null = null;\n\n/**\n * Execute a function within a specific context frame.\n *\n * CORE PRIMITIVE for context restoration:\n * - Saves the current context\n * - Sets the provided frame as current\n * - Executes the function\n * - Restores the previous context in finally\n *\n * This ensures no context frame remains globally active across await.\n */\nexport function withContext<T>(frame: ContextFrame | null, fn: () => T): T {\n const oldFrame = currentContextFrame;\n currentContextFrame = frame;\n try {\n return fn();\n } finally {\n currentContextFrame = oldFrame;\n }\n}\n\n/**\n * Execute an async resource step within its frozen context snapshot.\n *\n * CRITICAL: This wrapper is applied only to synchronous execution steps of\n * an async resource (the initial call). We intentionally DO NOT restore\n * the resource frame for post-await continuations — continuations must not\n * observe or rely on a live resource frame. This keeps semantics simple and\n * deterministic: async resources see only their creation-time snapshot.\n */\nexport function withAsyncResourceContext<T>(\n frame: ContextFrame | null,\n fn: () => T\n): T {\n const oldFrame = currentAsyncResourceFrame;\n // Only set the frame for the synchronous execution step\n currentAsyncResourceFrame = frame;\n try {\n return fn();\n } finally {\n // Clear the frame to avoid exposing it across await boundaries\n currentAsyncResourceFrame = oldFrame;\n }\n}\n\nexport function defineContext<T>(defaultValue: T): Context<T> {\n const key = Symbol('AskrContext');\n\n return {\n key,\n defaultValue,\n Scope: (props: { value: T; children?: unknown }): JSXElement => {\n // Scope component: creates a new frame and renders children within it\n return {\n type: ContextScopeComponent,\n props: { key, value: props.value, children: props.children },\n } as unknown as JSXElement;\n },\n };\n}\n\nexport function readContext<T>(context: Context<T>): T {\n // Check render frame first (components), then async resource frame (resources)\n const frame = currentContextFrame || currentAsyncResourceFrame;\n\n if (!frame) {\n throw new Error(\n 'readContext() can only be called during component render or async resource execution. ' +\n 'Ensure you are calling this from inside your component or resource function.'\n );\n }\n\n let current: ContextFrame | null = frame;\n while (current) {\n // `values` may be null when no provider has created it yet — treat as empty\n const values = current.values;\n if (values && values.has(context.key)) {\n return values.get(context.key) as T;\n }\n current = current.parent;\n }\n return context.defaultValue;\n}\n\n/**\n * Internal component that manages context frame\n * Used by Context.Scope to provide shadowed value to children\n */\nfunction ContextScopeComponent(props: Props): Renderable {\n // Extract expected properties (we accept a loose shape so this can be used as a component type)\n const key = props['key'] as ContextKey;\n const value = props['value'];\n const children = props['children'] as Renderable;\n\n // Create a new frame with this value\n const instance = getCurrentComponentInstance();\n const parentFrame: ContextFrame | null = (() => {\n // Prefer the live render frame.\n // Note: the runtime executes component functions inside an empty \"render frame\"\n // whose parent points at the nearest provider chain. Even if this frame has no\n // values, it must still be used to preserve the parent linkage.\n if (currentContextFrame) return currentContextFrame;\n\n // If there is no live render frame (should be rare), fall back to the\n // instance's owner frame.\n if (instance && instance.ownerFrame) return instance.ownerFrame;\n\n // Do NOT fall back to the async snapshot stack here: that stack represents\n // unrelated async continuations and must not affect lexical provider chaining.\n return null;\n })();\n\n const newFrame: ContextFrame = {\n parent: parentFrame,\n values: new Map([[key, value]]),\n };\n\n // The renderer will set ownerFrame on child component instances when they're created.\n // We mark vnodes with the frame so the renderer knows which frame to assign.\n if (Array.isArray(children)) {\n // Mark array elements with the frame. If an element is a function-child,\n // convert it into a lazy invoker so it's executed later inside the frame.\n return children.map((child) => {\n if (typeof child === 'function') {\n return {\n type: ContextFunctionChildInvoker,\n props: {\n fn: child as () => Renderable,\n __frame: newFrame,\n __owner: getCurrentComponentInstance(),\n },\n } as unknown as Renderable;\n }\n return markWithFrame(child, newFrame);\n }) as unknown as Renderable;\n } else if (typeof children === 'function') {\n // If children is a function (render callback), do NOT execute it eagerly\n // during the parent render. Instead, return a small internal component\n // that will execute the function later (when it itself is rendered) and\n // will execute it within the provider frame so any reads performed during\n // that execution observe the provider's frame.\n return {\n type: ContextFunctionChildInvoker,\n props: {\n fn: children as () => Renderable,\n __frame: newFrame,\n __owner: getCurrentComponentInstance(),\n },\n } as unknown as Renderable;\n } else if (children) {\n return markWithFrame(children, newFrame);\n }\n\n return null;\n}\n\n/**\n * Internal: Mark a vnode with a context frame\n * The renderer will restore this frame before executing component functions\n */\nfunction markWithFrame(node: Renderable, frame: ContextFrame): Renderable {\n // Recursively mark node and its subtree so nested provider/component\n // executions will restore the correct frame when they are rendered.\n if (typeof node === 'object' && node !== null) {\n const obj = node as Record<string | symbol, unknown>;\n obj[CONTEXT_FRAME_SYMBOL] = frame;\n\n // If the node is a VNode with children, recursively mark its children\n const children = obj.children as unknown;\n if (Array.isArray(children)) {\n for (let i = 0; i < children.length; i++) {\n const child = children[i] as Renderable;\n if (child) {\n children[i] = markWithFrame(child, frame) as Renderable;\n }\n }\n } else if (children) {\n obj.children = markWithFrame(children as Renderable, frame) as Renderable;\n }\n }\n return node;\n}\n\n/**\n * Internal helper component: executes a function-child lazily inside the\n * provided frame and marks the returned subtree with that frame so later\n * component executions will restore the correct context frame.\n *\n * SNAPSHOT SEMANTIC: The frame passed here is the snapshot captured at render\n * time. Any resources created during this execution will observe this frozen\n * snapshot, ensuring deterministic behavior.\n */\nfunction ContextFunctionChildInvoker(props: {\n fn: () => Renderable;\n __frame: ContextFrame;\n}): Renderable {\n const { fn, __frame } = props;\n\n // Execute the function-child within the provider frame.\n // The owner's ownerFrame is already set by the renderer when the component was created.\n // Any resources started during this execution will capture this frame as their\n // snapshot, ensuring they see the context values from this render, not future renders.\n const res = withContext(__frame, () => fn());\n\n // Mark the result so the renderer knows to set ownerFrame on child instances\n if (res) return markWithFrame(res, __frame);\n return null;\n}\n\n/**\n * Push a new context frame (for render entry)\n * Called by component runtime when render starts\n */\nexport function pushContextFrame(): ContextFrame {\n // Lazily allocate the `values` map to avoid per-render allocations when\n // components do not use context. The map will be created when a provider\n // sets a value or when a read discovers no map and needs to behave as empty.\n const frame: ContextFrame = {\n parent: currentContextFrame,\n values: null,\n };\n currentContextFrame = frame;\n return frame;\n}\n\n/**\n * Pop context frame (for render exit)\n * Called by component runtime when render ends\n */\nexport function popContextFrame(): void {\n if (currentContextFrame) {\n currentContextFrame = currentContextFrame.parent;\n }\n}\n\n/**\n * Get the current context frame for inspection (used by tests/diagnostics only)\n */\nexport function getCurrentContextFrame(): ContextFrame | null {\n return currentContextFrame;\n}\n\n/**\n * Get the top of the context snapshot stack (used by runtime when deciding\n * how to link snapshots for async continuations). Returns null if stack empty.\n */\nexport function getTopContextSnapshot(): ContextFrame | null {\n return currentContextFrame;\n}\n\n/**\n * Deprecated aliases for backward compatibility\n * These should not be used in new code\n */\nexport function executeWithinFrame<T>(\n frame: ContextFrame | null,\n fn: () => T\n): T {\n return withContext(frame, fn);\n}\n","/**\n * DOM mounting and updates\n * Direct DOM manipulation, no VDOM - heavily optimized for speed\n */\n\nimport { globalScheduler, isSchedulerExecuting } from '../runtime/scheduler';\nimport {\n isBulkCommitActive,\n markFastPathApplied,\n isFastPathApplied,\n} from '../runtime/fastlane';\nimport { logger } from '../dev/logger';\nimport type { Props } from '../shared/types';\nimport { Fragment } from '../jsx/jsx-runtime';\nimport {\n CONTEXT_FRAME_SYMBOL,\n type ContextFrame,\n withContext,\n getCurrentContextFrame,\n} from '../runtime/context';\nimport {\n createComponentInstance,\n renderComponentInline,\n mountInstanceInline,\n cleanupComponent,\n} from '../runtime/component';\nimport type {\n ComponentFunction,\n ComponentInstance,\n} from '../runtime/component';\n\ntype InstanceHost = Element & { __ASKR_INSTANCE?: ComponentInstance };\n\n// Helpers to clean up component instances when their host DOM nodes are removed\nfunction cleanupInstanceIfPresent(node: Node | null): void {\n if (!node) return;\n if (!(node instanceof Element)) return;\n try {\n const inst = (node as InstanceHost).__ASKR_INSTANCE;\n if (inst) {\n cleanupComponent(inst);\n try {\n delete (node as InstanceHost).__ASKR_INSTANCE;\n } catch (e) {\n void e;\n }\n }\n } catch (err) {\n // Swallow cleanup errors but keep a reference to avoid empty-block lint error\n void err;\n }\n\n // Also attempt to clean up any nested instances that may be attached\n // on descendants (defensive: some components may attach to deeper nodes)\n try {\n const descendants = node.querySelectorAll('*');\n for (const d of Array.from(descendants)) {\n try {\n const inst = (d as InstanceHost).__ASKR_INSTANCE;\n if (inst) {\n cleanupComponent(inst);\n try {\n delete (d as InstanceHost).__ASKR_INSTANCE;\n } catch (e) {\n void e;\n }\n }\n } catch (err) {\n void err;\n }\n }\n } catch (err) {\n void err;\n }\n}\n\ninterface DOMElement {\n type: string | ((props: Props) => unknown);\n props?: Props;\n children?: VNode[];\n key?: string | number;\n}\n\n// Type for virtual DOM nodes\nexport type VNode = DOMElement | string | number | boolean | null | undefined;\n\n// Type for elements that have context frames attached\ninterface ElementWithContext extends DOMElement {\n [CONTEXT_FRAME_SYMBOL]?: ContextFrame;\n}\n\nfunction _isDOMElement(node: unknown): node is DOMElement {\n return typeof node === 'object' && node !== null && 'type' in node;\n}\n\n/**\n * Internal marker for component-owned DOM ranges\n * Allows efficient partial DOM updates instead of clearing entire target\n */\ninterface DOMRange {\n start: Node; // Start marker (comment node)\n end: Node; // End marker (comment node)\n}\n\nconst domRanges = new WeakMap<object, DOMRange>();\n\n// Track listeners so we can remove them on cleanup\ninterface ListenerMapEntry {\n handler: EventListener;\n original: EventListener;\n}\nconst elementListeners = new WeakMap<Element, Map<string, ListenerMapEntry>>();\n\n// Track keyed elements for reconciliation\ninterface _KeyedChild {\n key: string | number;\n vnode: unknown;\n}\nconst keyedElements = new WeakMap<Element, Map<string | number, Element>>();\n\n// Exported for runtime use: retrieve existing keyed map for a parent element\nexport function getKeyMapForElement(el: Element) {\n return keyedElements.get(el);\n}\n\n// Track which parents had the reconciler record fast-path stats during the\n// current evaluation, so we can preserve diagnostics across additional\n// reconciliations within the same render pass without leaking between runs.\nconst _reconcilerRecordedParents = new WeakSet<Element>();\n\nexport function removeElementListeners(element: Element): void {\n const map = elementListeners.get(element);\n if (map) {\n for (const [eventName, entry] of map) {\n element.removeEventListener(eventName, entry.handler);\n }\n elementListeners.delete(element);\n }\n}\n\nexport function removeAllListeners(root: Element | null): void {\n if (!root) return;\n\n // Remove listeners from root\n removeElementListeners(root);\n\n // Recursively remove from all children\n const children = root.querySelectorAll('*');\n for (let i = 0; i < children.length; i++) {\n removeElementListeners(children[i]);\n }\n}\n\nexport function evaluate(\n node: unknown,\n target: Element | null,\n context?: object\n): void {\n if (!target) return;\n // Debug tracing to help understand why initial mounts sometimes don't\n // result in DOM mutations during tests.\n\n // If context provided, use component-owned DOM range (only replace that range)\n if (context && domRanges.has(context)) {\n const range = domRanges.get(context)!;\n // Remove all nodes between start and end markers\n let current = range.start.nextSibling;\n while (current && current !== range.end) {\n const next = current.nextSibling;\n current.remove();\n current = next;\n }\n // Append new DOM before end marker\n const dom = createDOMNode(node);\n if (dom) {\n target.insertBefore(dom, range.end);\n }\n } else if (context) {\n // First render with context: create range markers\n const start = document.createComment('component-start');\n const end = document.createComment('component-end');\n target.appendChild(start);\n target.appendChild(end);\n domRanges.set(context, { start, end });\n // Render into the range\n const dom = createDOMNode(node);\n if (dom) {\n target.insertBefore(dom, end);\n }\n } else {\n // Root render (no context): smart update strategy\n // If target has exactly one child of the same element type as the vnode,\n // reuse the element and just update its content.\n // This preserves the element reference and event handlers across renders.\n\n const vnode = node;\n const firstChild = target.children[0] as Element | undefined;\n\n if (\n firstChild &&\n _isDOMElement(vnode) &&\n typeof vnode.type === 'string' &&\n firstChild.tagName.toLowerCase() === vnode.type.toLowerCase()\n ) {\n // Reuse the existing element - it's the same type\n\n // Smart child update: if the only child is a single text node and vnode only has text children,\n // update the text node in place instead of replacing\n const vnodeChildren = vnode.children || vnode.props?.children;\n\n // Determine if this should be a simple text update\n let isSimpleTextVNode = false;\n let textContent: string | undefined;\n\n if (!Array.isArray(vnodeChildren)) {\n if (\n typeof vnodeChildren === 'string' ||\n typeof vnodeChildren === 'number'\n ) {\n isSimpleTextVNode = true;\n textContent = String(vnodeChildren);\n }\n } else if (vnodeChildren.length === 1) {\n // Array with single element - check if it's text\n const child = vnodeChildren[0];\n if (typeof child === 'string' || typeof child === 'number') {\n isSimpleTextVNode = true;\n textContent = String(child);\n }\n }\n\n if (\n isSimpleTextVNode &&\n firstChild.childNodes.length === 1 &&\n firstChild.firstChild?.nodeType === 3\n ) {\n // Update existing text node in place\n (firstChild.firstChild as Text).data = textContent!;\n } else {\n // Clear and repopulate children\n if (vnodeChildren) {\n if (Array.isArray(vnodeChildren)) {\n // Check if any children have keys - if so, use keyed reconciliation\n const hasKeys = vnodeChildren.some(\n (child) =>\n typeof child === 'object' && child !== null && 'key' in child\n );\n\n if (hasKeys) {\n // Get existing key map or create new one\n let oldKeyMap = keyedElements.get(firstChild);\n if (!oldKeyMap) {\n oldKeyMap = new Map();\n }\n\n // Optional forced positional bulk path for large keyed lists\n try {\n if (process.env.ASKR_FORCE_BULK_POSREUSE === '1') {\n try {\n const keyedVnodes: Array<{\n key: string | number;\n vnode: VNode;\n }> = [];\n for (\n let i = 0;\n i < (vnodeChildren as VNode[]).length;\n i++\n ) {\n const c = (vnodeChildren as VNode[])[i];\n if (\n _isDOMElement(c) &&\n (c as DOMElement).key !== undefined\n ) {\n keyedVnodes.push({\n key: (c as DOMElement).key as string | number,\n vnode: c,\n });\n }\n }\n // Only apply when all children are keyed and count matches\n if (\n keyedVnodes.length > 0 &&\n keyedVnodes.length === (vnodeChildren as VNode[]).length\n ) {\n logger.warn(\n '[Askr][FASTPATH] forced positional bulk keyed reuse (evaluate-level)'\n );\n const stats = performBulkPositionalKeyedTextUpdate(\n firstChild,\n keyedVnodes\n );\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const gl = globalThis as unknown as {\n __ASKR_LAST_FASTPATH_STATS?: unknown;\n __ASKR_LAST_FASTPATH_COMMIT_COUNT?:\n | number\n | undefined;\n __ASKR_FASTPATH_COUNTERS?: Record<string, number>;\n };\n (gl.__ASKR_LAST_FASTPATH_STATS as unknown) = stats;\n // Mark a single logical commit for dev diagnostics so\n // runtime fast-lane invariants can validate commit counts.\n gl.__ASKR_LAST_FASTPATH_COMMIT_COUNT = 1;\n const counters =\n (gl.__ASKR_FASTPATH_COUNTERS as Record<\n string,\n number\n >) || {};\n counters.bulkKeyedPositionalForced =\n (counters.bulkKeyedPositionalForced || 0) + 1;\n gl.__ASKR_FASTPATH_COUNTERS = counters;\n } catch (e) {\n void e;\n }\n }\n // Rebuild keyed map\n try {\n const map = new Map<string | number, Element>();\n const children = Array.from(firstChild.children);\n for (let i = 0; i < children.length; i++) {\n const el = children[i] as Element;\n const k = el.getAttribute('data-key');\n if (k !== null) {\n map.set(k, el);\n const n = Number(k);\n if (!Number.isNaN(n)) map.set(n, el);\n }\n }\n keyedElements.set(firstChild, map);\n } catch (e) {\n void e;\n }\n } else {\n // Fall back to normal reconciliation below\n const newKeyMap = reconcileKeyedChildren(\n firstChild,\n vnodeChildren,\n oldKeyMap\n );\n keyedElements.set(firstChild, newKeyMap);\n }\n } catch (err) {\n logger.warn(\n '[Askr][FASTPATH] forced bulk path failed, falling back',\n err\n );\n const newKeyMap = reconcileKeyedChildren(\n firstChild,\n vnodeChildren,\n oldKeyMap\n );\n keyedElements.set(firstChild, newKeyMap);\n }\n } else {\n // Do reconciliation - this will reuse existing keyed elements\n const newKeyMap = reconcileKeyedChildren(\n firstChild,\n vnodeChildren,\n oldKeyMap\n );\n keyedElements.set(firstChild, newKeyMap);\n }\n } catch (e) {\n void e; // suppress unused variable lint\n // Fall back to normal reconciliation on error\n const newKeyMap = reconcileKeyedChildren(\n firstChild,\n vnodeChildren,\n oldKeyMap\n );\n keyedElements.set(firstChild, newKeyMap);\n }\n } else {\n // Unkeyed - consider bulk text fast-path for large text-dominant updates\n if (isBulkTextFastPathEligible(firstChild, vnodeChildren)) {\n const stats = performBulkTextReplace(firstChild, vnodeChildren);\n // Dev-only instrumentation counters\n if (process.env.NODE_ENV !== 'production') {\n try {\n const gl = globalThis as unknown as {\n __ASKR_LAST_BULK_TEXT_FASTPATH_STATS?: unknown;\n __ASKR_FASTPATH_COUNTERS?: Record<string, number>;\n };\n (gl.__ASKR_LAST_BULK_TEXT_FASTPATH_STATS as unknown) =\n stats;\n const counters =\n (gl.__ASKR_FASTPATH_COUNTERS as Record<string, number>) ||\n {};\n counters.bulkTextHits = (counters.bulkTextHits || 0) + 1;\n gl.__ASKR_FASTPATH_COUNTERS = counters;\n } catch (e) {\n void e;\n }\n }\n } else {\n if (process.env.NODE_ENV !== 'production') {\n try {\n const gl = globalThis as unknown as {\n __ASKR_FASTPATH_COUNTERS?: Record<string, number>;\n };\n const counters =\n (gl.__ASKR_FASTPATH_COUNTERS as Record<string, number>) ||\n {};\n counters.bulkTextMisses =\n (counters.bulkTextMisses || 0) + 1;\n gl.__ASKR_FASTPATH_COUNTERS = counters;\n } catch (e) {\n void e;\n }\n }\n // Fall back to existing per-node updates\n updateUnkeyedChildren(firstChild, vnodeChildren);\n keyedElements.delete(firstChild);\n }\n }\n } else {\n // Non-array children\n firstChild.textContent = '';\n const dom = createDOMNode(vnodeChildren);\n if (dom) firstChild.appendChild(dom);\n keyedElements.delete(firstChild);\n }\n } else {\n // No children\n firstChild.textContent = '';\n keyedElements.delete(firstChild);\n }\n }\n\n // Update attributes and event listeners\n updateElementFromVnode(firstChild, vnode, false);\n } else {\n // Clear and rebuild (first render or structure changed)\n target.textContent = '';\n\n // Check if this is an element with keyed children even on first render\n if (_isDOMElement(vnode) && typeof vnode.type === 'string') {\n const children = vnode.children;\n if (\n Array.isArray(children) &&\n children.some(\n (child) =>\n typeof child === 'object' && child !== null && 'key' in child\n )\n ) {\n // Create the element first\n const el = document.createElement(vnode.type);\n target.appendChild(el);\n\n // Apply attributes\n const props = vnode.props || {};\n for (const [key, value] of Object.entries(props)) {\n if (key === 'children' || key === 'key') continue;\n if (value === undefined || value === null || value === false)\n continue;\n if (key.startsWith('on') && key.length > 2) {\n const eventName =\n key.slice(2).charAt(0).toLowerCase() +\n key.slice(3).toLowerCase();\n // Note: DOM event handlers run synchronously, but while in the\n // handler we mark the scheduler as \"in handler\" to defer any scheduled\n // flushes until the handler completes. This preserves synchronous\n // handler semantics (immediate reads observe state changes), while\n // keeping commits atomic and serialized.\n const wrappedHandler = (event: Event) => {\n globalScheduler.setInHandler(true);\n try {\n (value as EventListener)(event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n } finally {\n globalScheduler.setInHandler(false);\n }\n // After handler completes, flush any pending tasks\n // globalScheduler.flush(); // Defer flush to manual control for testing\n };\n\n el.addEventListener(eventName, wrappedHandler);\n if (!elementListeners.has(el)) {\n elementListeners.set(el, new Map());\n }\n elementListeners.get(el)!.set(eventName, {\n handler: wrappedHandler,\n original: value as EventListener,\n });\n continue;\n }\n if (key === 'class' || key === 'className') {\n el.className = String(value);\n } else if (key === 'value' || key === 'checked') {\n (el as HTMLElement & Props)[key] = value;\n } else {\n el.setAttribute(key, String(value));\n }\n }\n\n // Use keyed reconciliation for children\n const newKeyMap = reconcileKeyedChildren(el, children, undefined);\n keyedElements.set(el, newKeyMap);\n return;\n return;\n }\n }\n\n // Default: create whole tree\n const dom = createDOMNode(vnode);\n if (dom) {\n target.appendChild(dom);\n }\n }\n }\n}\n\nexport function clearDOMRange(context: object): void {\n domRanges.delete(context);\n}\n\n/**\n * Reconcile children with keys, efficiently reusing existing elements\n */\n\n// Helper exported so the runtime can decide whether to activate a higher-level\n// runtime fast-lane before doing full render bookkeeping. Returns detailed\n// decision metadata for dev-mode diagnostics.\nexport function isKeyedReorderFastPathEligible(\n parent: Element,\n newChildren: VNode[],\n oldKeyMap: Map<string | number, Element> | undefined\n) {\n const keyedVnodes: Array<{ key: string | number; vnode: VNode }> = [];\n for (let i = 0; i < newChildren.length; i++) {\n const child = newChildren[i];\n if (_isDOMElement(child) && child.key !== undefined) {\n keyedVnodes.push({ key: child.key, vnode: child });\n }\n }\n\n const totalKeyed = keyedVnodes.length;\n const newKeyOrder = keyedVnodes.map((kv) => kv.key);\n const oldKeyOrder = oldKeyMap ? Array.from(oldKeyMap.keys()) : [];\n\n let moveCount = 0;\n for (let i = 0; i < newKeyOrder.length; i++) {\n const k = newKeyOrder[i];\n if (i >= oldKeyOrder.length || oldKeyOrder[i] !== k || !oldKeyMap?.has(k)) {\n moveCount++;\n }\n }\n\n const FAST_MOVE_THRESHOLD_ABS = 64;\n const FAST_MOVE_THRESHOLD_REL = 0.1; // 10%\n const cheapMoveTrigger =\n totalKeyed >= 128 &&\n oldKeyOrder.length > 0 &&\n moveCount >\n Math.max(\n FAST_MOVE_THRESHOLD_ABS,\n Math.floor(totalKeyed * FAST_MOVE_THRESHOLD_REL)\n );\n\n let lisTrigger = false;\n let lisLen = 0;\n if (totalKeyed >= 128) {\n const parentChildren = Array.from(parent.children);\n const positions: number[] = new Array(keyedVnodes.length).fill(-1);\n for (let i = 0; i < keyedVnodes.length; i++) {\n const key = keyedVnodes[i].key;\n const el = oldKeyMap?.get(key);\n if (el && el.parentElement === parent) {\n positions[i] = parentChildren.indexOf(el);\n }\n }\n\n const tails: number[] = [];\n for (let i = 0; i < positions.length; i++) {\n const pos = positions[i];\n if (pos === -1) continue;\n let lo = 0;\n let hi = tails.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (tails[mid] < pos) lo = mid + 1;\n else hi = mid;\n }\n if (lo === tails.length) tails.push(pos);\n else tails[lo] = pos;\n }\n lisLen = tails.length;\n lisTrigger = lisLen < Math.floor(totalKeyed * 0.5);\n }\n\n // Conservative rule: if any keyed vnode declares non-trivial props\n // (excluding event handlers), decline the fast-path. This prevents edge\n // cases where props exist but match current DOM; the runtime fast-lane is\n // only for pure reorder-only updates.\n let hasPropsPresent = false;\n for (let i = 0; i < keyedVnodes.length; i++) {\n const vnode = keyedVnodes[i].vnode;\n if (!_isDOMElement(vnode)) continue;\n const props = vnode.props || {};\n for (const k of Object.keys(props)) {\n if (k === 'children' || k === 'key') continue;\n if (k.startsWith('on') && k.length > 2) continue; // ignore event handlers\n if (k.startsWith('data-')) continue; // allow data-* attrs (keys/materialization)\n hasPropsPresent = true;\n break;\n }\n if (hasPropsPresent) break;\n }\n\n // Check for conservative prop differences on existing elements\n let hasPropChanges = false;\n for (let i = 0; i < keyedVnodes.length; i++) {\n const { key, vnode } = keyedVnodes[i];\n const el = oldKeyMap?.get(key);\n if (!el || !_isDOMElement(vnode)) continue;\n const props = vnode.props || {};\n for (const k of Object.keys(props)) {\n if (k === 'children' || k === 'key') continue;\n if (k.startsWith('on') && k.length > 2) continue;\n if (k.startsWith('data-')) continue; // ignore data-* attrs (e.g. data-key)\n const v = (props as Record<string, unknown>)[k];\n try {\n if (k === 'class' || k === 'className') {\n if (el.className !== String(v)) {\n hasPropChanges = true;\n break;\n }\n } else if (k === 'value' || k === 'checked') {\n if ((el as HTMLElement & Record<string, unknown>)[k] !== v) {\n hasPropChanges = true;\n break;\n }\n } else {\n const attr = el.getAttribute(k);\n if (v === undefined || v === null || v === false) {\n if (attr !== null) {\n hasPropChanges = true;\n break;\n }\n } else if (String(v) !== attr) {\n hasPropChanges = true;\n break;\n }\n }\n } catch {\n hasPropChanges = true;\n break;\n }\n }\n if (hasPropChanges) break;\n }\n\n const useFastPath =\n (cheapMoveTrigger || lisTrigger) && !hasPropChanges && !hasPropsPresent;\n\n return {\n useFastPath,\n totalKeyed,\n moveCount,\n lisLen,\n hasPropChanges,\n } as const;\n}\n\nfunction reconcileKeyedChildren(\n parent: Element,\n newChildren: VNode[],\n oldKeyMap: Map<string | number, Element> | undefined\n): Map<string | number, Element> {\n const newKeyMap = new Map<string | number, Element>();\n\n // First pass: collect all keyed vnodes and match to existing elements\n const keyedVnodes: Array<{ key: string | number; vnode: VNode }> = [];\n const unkeyedVnodes: VNode[] = [];\n\n for (let i = 0; i < newChildren.length; i++) {\n const child = newChildren[i];\n if (_isDOMElement(child) && child.key !== undefined) {\n keyedVnodes.push({ key: child.key, vnode: child });\n } else {\n unkeyedVnodes.push(child);\n }\n }\n\n // Decide whether to use the fast-path. We use two heuristics:\n // - cheap move heuristic: positional mismatches in-memory (no DOM reads)\n // - LIS-based heuristic: compute Longest Increasing Subsequence on the\n // parent's current children order (requires reading current DOM order)\n // Additionally, the fast-path is only valid if there are NO prop/event\n // changes to existing keyed elements; it's strictly a bulk reorder escape.\n const totalKeyed = keyedVnodes.length;\n const newKeyOrder = keyedVnodes.map((kv) => kv.key);\n const oldKeyOrder = oldKeyMap ? Array.from(oldKeyMap.keys()) : [];\n\n // Conservative mismatch count: positional differences or new insertions\n // count as moves. This intentionally avoids any DOM traversal.\n let moveCount = 0;\n for (let i = 0; i < newKeyOrder.length; i++) {\n const k = newKeyOrder[i];\n if (i >= oldKeyOrder.length || oldKeyOrder[i] !== k || !oldKeyMap?.has(k)) {\n moveCount++;\n }\n }\n\n // Fast-path eligibility is computed by `isKeyedReorderFastPathEligible`.\n // We intentionally avoid duplicating the heuristic computation here to keep\n // the logic centralized and prevent unused-variable lint errors.\n // Check for prop / event-handler changes on existing nodes. If any keyed vnode\n // introduces attribute/event handler changes compared to the current element\n // state, decline the fast-path to preserve correctness (we will do fine-grained updates).\n let hasPropChanges = false;\n for (let i = 0; i < keyedVnodes.length; i++) {\n const { key, vnode } = keyedVnodes[i];\n const el = oldKeyMap?.get(key);\n if (!el || !_isDOMElement(vnode)) continue;\n const props = vnode.props || {};\n // If vnode declares event handlers, bail (we don't want to reattach handlers in bulk)\n for (const k of Object.keys(props)) {\n if (k === 'children' || k === 'key') continue;\n if (k.startsWith('on') && k.length > 2) {\n // Ignore event handlers for fast-path activation: the fast-path\n // preserves existing element listeners (we do not reattach on each\n // reorder). Treat presence of a handler as non-blocking for fast-path.\n continue;\n }\n // Check `class`, `value`, `checked`, attribute differences conservatively\n const v = (props as Record<string, unknown>)[k];\n try {\n if (k === 'class' || k === 'className') {\n if (el.className !== String(v)) {\n logger.warn('[Askr][FASTPATH][DEV] prop mismatch', {\n key,\n prop: k,\n expected: String(v),\n actual: el.className,\n });\n hasPropChanges = true;\n break;\n }\n } else if (k === 'value' || k === 'checked') {\n if ((el as HTMLElement & Record<string, unknown>)[k] !== v) {\n logger.warn('[Askr][FASTPATH][DEV] prop mismatch', {\n key,\n prop: k,\n expected: v,\n actual: (el as HTMLElement & Record<string, unknown>)[k],\n });\n hasPropChanges = true;\n break;\n }\n } else {\n // Attribute check: presence/absence or string difference\n const attr = el.getAttribute(k);\n if (v === undefined || v === null || v === false) {\n if (attr !== null) {\n logger.warn(\n '[Askr][FASTPATH][DEV] prop mismatch (missing attr)',\n {\n key,\n prop: k,\n expected: v,\n actual: attr,\n }\n );\n hasPropChanges = true;\n break;\n }\n } else if (String(v) !== attr) {\n logger.warn('[Askr][FASTPATH][DEV] prop mismatch (attr diff)', {\n key,\n prop: k,\n expected: String(v),\n actual: attr,\n });\n hasPropChanges = true;\n break;\n }\n }\n } catch {\n // If any DOM read fails, be conservative and disable the fast path\n hasPropChanges = true;\n break;\n }\n }\n if (hasPropChanges) break;\n }\n\n const decision = isKeyedReorderFastPathEligible(\n parent,\n newChildren,\n oldKeyMap\n );\n const useFastPath = decision.useFastPath;\n\n // Dev debug: explain why we chose (or declined) fast-path for this update\n logger.warn('[Askr][FASTPATH][DEV] decision', decision);\n\n // Aggressive fallback for huge keyed lists that are text-dominant.\n // If the renderer declined the keyed fast-path but the list is extremely\n // large and each vnode is a simple intrinsic element with a single\n // primitive child (text), apply a positional bulk update to avoid\n // per-node reconciliation overhead.\n try {\n const hugeThreshold = Number(process.env.ASKR_BULK_HUGE_THRESHOLD) || 2048;\n if (!useFastPath && keyedVnodes.length >= hugeThreshold) {\n let allSimple = true;\n for (let i = 0; i < keyedVnodes.length; i++) {\n const vnode = keyedVnodes[i].vnode;\n if (!_isDOMElement(vnode)) {\n allSimple = false;\n break;\n }\n const dv = vnode as DOMElement;\n if (typeof dv.type !== 'string') {\n allSimple = false;\n break;\n }\n const ch = dv.children || dv.props?.children;\n if (ch === undefined) continue;\n if (Array.isArray(ch)) {\n if (\n ch.length !== 1 ||\n (typeof ch[0] !== 'string' && typeof ch[0] !== 'number')\n ) {\n allSimple = false;\n break;\n }\n } else if (typeof ch !== 'string' && typeof ch !== 'number') {\n allSimple = false;\n break;\n }\n }\n\n if (allSimple) {\n logger.warn('[Askr][FASTPATH] applying huge-list positional fallback');\n try {\n if (isBulkCommitActive()) markFastPathApplied(parent);\n } catch (e) {\n void e;\n }\n const stats = performBulkPositionalKeyedTextUpdate(parent, keyedVnodes);\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const gl = globalThis as unknown as {\n __ASKR_LAST_FASTPATH_STATS?: unknown;\n __ASKR_FASTPATH_COUNTERS?: Record<string, number>;\n __ASKR_BULK_DIAG?: unknown;\n };\n (gl.__ASKR_LAST_FASTPATH_STATS as unknown) = stats;\n const counters =\n (gl.__ASKR_FASTPATH_COUNTERS as Record<string, number>) || {};\n counters.bulkKeyedHugeFallback =\n (counters.bulkKeyedHugeFallback || 0) + 1;\n gl.__ASKR_FASTPATH_COUNTERS = counters;\n (gl.__ASKR_BULK_DIAG as unknown) = {\n phase: 'bulk-keyed-huge-fallback',\n stats,\n };\n } catch (e) {\n void e;\n }\n }\n return newKeyMap;\n }\n }\n } catch (e) {\n void e;\n }\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const gl = globalThis as unknown as { __ASKR_BULK_DIAG?: unknown };\n (gl.__ASKR_BULK_DIAG as unknown) = {\n phase: 'keyed-decision',\n decision,\n totalKeyed,\n oldKeyMapSize: oldKeyMap?.size ?? 0,\n };\n } catch (e) {\n void e;\n }\n }\n\n // Heuristic: if many incoming keys are missing from the old key map (i.e.\n // keys changed en-masse) and all children are simple text, prefer the\n // positional bulk text fast-path rather than the keyed map fast-path which\n // would allocate many new elements.\n let allSimpleText = false;\n try {\n if (\n keyedVnodes.length >=\n (Number(process.env.ASKR_BULK_TEXT_THRESHOLD) || 1024)\n ) {\n let missing = 0;\n try {\n const present = new Set<string | number>();\n const parentChildren = Array.from(parent.children);\n for (let i = 0; i < parentChildren.length; i++) {\n const attr = parentChildren[i].getAttribute('data-key');\n if (attr !== null) {\n present.add(attr);\n const n = Number(attr);\n if (!Number.isNaN(n)) present.add(n);\n }\n }\n for (let i = 0; i < keyedVnodes.length; i++) {\n const k = keyedVnodes[i].key;\n if (!present.has(k)) missing++;\n }\n } catch {\n // If DOM reads fail, be conservative and set missing low\n missing = 0;\n }\n\n // Determine whether all keyed vnodes are \"simple text\" candidates.\n // Moved here to ensure the predicate is available where it's needed.\n // Declare variable in outer scope so it can be referenced later in file\n // (some heuristics need this predicate after this try block).\n allSimpleText =\n keyedVnodes.length > 0 &&\n keyedVnodes.every(({ vnode }) => {\n if (!_isDOMElement(vnode)) return false;\n const dv = vnode as DOMElement;\n if (typeof dv.type !== 'string') return false;\n const ch = dv.children || dv.props?.children;\n if (ch === undefined) return true;\n if (Array.isArray(ch)) {\n return (\n ch.length === 1 &&\n (typeof ch[0] === 'string' || typeof ch[0] === 'number')\n );\n }\n return typeof ch === 'string' || typeof ch === 'number';\n });\n\n // Conservative: do not apply positional bulk keyed fast-path when any\n // child vnode declares non-data props (class, value, etc). Such props\n // may require per-node updates and the bulk path assumes text-only\n // changes. Compute presence of non-data props here.\n let hasPropsPresent = false;\n for (let i = 0; i < keyedVnodes.length; i++) {\n const vnode = keyedVnodes[i].vnode;\n if (!_isDOMElement(vnode)) continue;\n const props = vnode.props || {};\n for (const k of Object.keys(props)) {\n if (k === 'children' || k === 'key') continue;\n if (k.startsWith('on') && k.length > 2) continue; // ignore event handlers\n if (k.startsWith('data-')) continue; // ignore data-* attributes\n hasPropsPresent = true;\n break;\n }\n if (hasPropsPresent) break;\n }\n\n const missingRatio = missing / Math.max(1, keyedVnodes.length);\n if (missingRatio > 0.5 && allSimpleText && !hasPropsPresent) {\n logger.warn(\n '[Askr][FASTPATH] switching to positional bulk keyed fast-path due to missing keys ratio',\n missingRatio\n );\n try {\n if (isBulkCommitActive()) markFastPathApplied(parent);\n } catch (e) {\n void e;\n }\n const stats = performBulkPositionalKeyedTextUpdate(parent, keyedVnodes);\n if (process.env.NODE_ENV !== 'production') {\n try {\n const gl = globalThis as unknown as {\n __ASKR_LAST_FASTPATH_STATS?: unknown;\n __ASKR_LAST_FASTPATH_COMMIT_COUNT?: number | undefined;\n __ASKR_FASTPATH_COUNTERS?: Record<string, number>;\n };\n (gl.__ASKR_LAST_FASTPATH_STATS as unknown) = stats;\n // Mark that reconciler recorded stats for this parent during this\n // render pass; this allows subsequent reconciliations in the same\n // pass to preserve the diagnostic fields instead of clearing them.\n try {\n _reconcilerRecordedParents.add(parent);\n } catch (e) {\n void e;\n }\n // Record a logical commit for diagnostics (even though the\n // reconciler performed in-place updates, treat it as a single\n // fast-path commit for runtime invariant checks).\n gl.__ASKR_LAST_FASTPATH_COMMIT_COUNT = 1;\n const counters =\n (gl.__ASKR_FASTPATH_COUNTERS as Record<string, number>) || {};\n counters.bulkKeyedPositionalHits =\n (counters.bulkKeyedPositionalHits || 0) + 1;\n gl.__ASKR_FASTPATH_COUNTERS = counters;\n } catch (e) {\n void e;\n }\n }\n return newKeyMap;\n }\n }\n } catch (e) {\n void e;\n }\n\n // Clear previous fast-path stats when we decline the fast-path to avoid\n // leaking prior run data across updates (tests rely on this behavior).\n // However, if a fast-path was applied synchronously for this parent in the\n // same render pass, preserve the recorded stats (they may be set by the\n // reconciler even when the runtime fast-lane was not taken).\n if (!useFastPath && typeof globalThis !== 'undefined') {\n try {\n let parentFastpathApplied = false;\n try {\n parentFastpathApplied = isFastPathApplied(parent);\n } catch {\n parentFastpathApplied = false;\n }\n if (!parentFastpathApplied) {\n const gl = globalThis as unknown as {\n __ASKR_LAST_FASTPATH_STATS?: unknown;\n __ASKR_LAST_FASTPATH_REUSED?: unknown;\n };\n // If the reconciler recorded stats for this parent in the current\n // render pass, preserve them and remove the transient marker so that\n // subsequent independent renders will not inherit the flag.\n try {\n if (_reconcilerRecordedParents.has(parent)) {\n _reconcilerRecordedParents.delete(parent);\n } else {\n delete gl.__ASKR_LAST_FASTPATH_STATS;\n delete gl.__ASKR_LAST_FASTPATH_REUSED;\n }\n } catch {\n // On any failure, clear diagnostics conservatively\n delete gl.__ASKR_LAST_FASTPATH_STATS;\n delete gl.__ASKR_LAST_FASTPATH_REUSED;\n }\n }\n } catch (e) {\n void e;\n }\n }\n\n // Heuristic: if keys changed but the new children are the same element tag\n // and only their text content differs, reuse existing elements by **position**\n // (positional reuse). This avoids allocating a new Element/Node per update\n // when the structure is stable and only textual content changes.\n // Conditions:\n // - oldKeyMap is missing or provides no matching keys\n // - parent has same number of children as keyed vnodes\n // - each keyed vnode is an intrinsic element (string type) whose children\n // are a single primitive (string/number)\n let _triedPositionalReuse = false;\n\n // New heuristic: bulk keyed text update fast-path\n // If there are many keyed elements (large lists) and **no moves** (stable key order)\n // and all keyed vnodes are simple intrinsic elements with a single primitive\n // child (text), we can build a DocumentFragment by reusing the existing\n // Element nodes and updating their text content in-memory, then perform a\n // single atomic `replaceChildren` to avoid per-node reconciliation overhead.\n // This preserves element identity and listeners while dramatically reducing\n // JS overhead for pure text churn.\n try {\n const bulkTextThreshold =\n Number(process.env.ASKR_BULK_TEXT_THRESHOLD) || 1024; // `allSimpleText` computed earlier near missing-ratio check\n\n if (\n !useFastPath &&\n keyedVnodes.length >= bulkTextThreshold &&\n allSimpleText &&\n !hasPropChanges\n ) {\n // If bulk fast-path was already applied synchronously on this parent in\n // this commit, avoid reapplying another structural fast-path which could\n // replace nodes again and inadvertently remove listeners. This marker\n // is cleared on the next tick.\n try {\n // Avoid reapplying a fast-path on the same parent during the same bulk\n // commit. Use runtime registry rather than DOM attributes to avoid\n // introducing async cleanup and to keep this logic synchronous.\n if (isFastPathApplied(parent)) {\n logger.warn(\n '[Askr][FASTPATH] fast-path already applied on parent; skipping'\n );\n return newKeyMap;\n }\n } catch (e) {\n void e;\n }\n // Two bulk behaviors:\n // 1) Stable keys & order: reuse elements from oldKeyMap by key and do an\n // atomic replaceChildren after updating text content (preserves identity).\n // 2) Keys changed en-masse but structure is stable: positional reuse - reuse\n // elements by position, update their text, and remap data-key attributes.\n let stable = true;\n try {\n const parentChildren = Array.from(parent.children);\n\n // If the parent and new children have identical length and all\n // keyed vnodes are simple text elements, we can apply the positional\n // bulk update. Allow a forced env var to bypass conservative checks\n // for benching/debugging scenarios where we know structure is stable.\n if (parentChildren.length === keyedVnodes.length) {\n const allSimple = keyedVnodes.every(({ vnode }) => {\n if (!_isDOMElement(vnode)) return false;\n const dv = vnode as DOMElement;\n if (typeof dv.type !== 'string') return false;\n const ch = dv.children || dv.props?.children;\n if (ch === undefined) return true;\n if (Array.isArray(ch)) {\n return (\n ch.length === 1 &&\n (typeof ch[0] === 'string' || typeof ch[0] === 'number')\n );\n }\n return typeof ch === 'string' || typeof ch === 'number';\n });\n\n if (allSimple || process.env.ASKR_FORCE_BULK_POSREUSE === '1') {\n logger.warn(\n '[Askr][FASTPATH] len-match heuristic triggered (positional bulk)'\n );\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const gl = globalThis as unknown as {\n __ASKR_BULK_DIAG?: unknown;\n };\n (gl.__ASKR_BULK_DIAG as unknown) = {\n phase: 'bulk-keyed-positional-trigger-lenmatch-early',\n totalKeyed: keyedVnodes.length,\n allSimple,\n forced: process.env.ASKR_FORCE_BULK_POSREUSE === '1',\n };\n } catch (e) {\n void e;\n }\n }\n try {\n if (isBulkCommitActive()) markFastPathApplied(parent);\n } catch (e) {\n void e;\n }\n\n const stats = performBulkPositionalKeyedTextUpdate(\n parent,\n keyedVnodes\n );\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const gl = globalThis as unknown as {\n __ASKR_LAST_FASTPATH_STATS?: unknown;\n __ASKR_BULK_DIAG?: unknown;\n __ASKR_FASTPATH_COUNTERS?: Record<string, number>;\n };\n (gl.__ASKR_LAST_FASTPATH_STATS as unknown) = stats;\n (gl.__ASKR_BULK_DIAG as unknown) = {\n phase: 'bulk-keyed-positional-applied',\n stats,\n };\n const counters =\n (gl.__ASKR_FASTPATH_COUNTERS as Record<string, number>) || {};\n counters.bulkKeyedPositionalHits =\n (counters.bulkKeyedPositionalHits || 0) + 1;\n if (process.env.ASKR_FORCE_BULK_POSREUSE === '1')\n counters.bulkKeyedPositionalForced =\n (counters.bulkKeyedPositionalForced || 0) + 1;\n gl.__ASKR_FASTPATH_COUNTERS = counters;\n } catch (e) {\n void e;\n }\n }\n return newKeyMap;\n }\n }\n\n if (parentChildren.length !== keyedVnodes.length) stable = false;\n else {\n // Check if keys match positions (stable-key case) and collect mismatch count\n let keyMismatches = 0;\n for (let i = 0; i < keyedVnodes.length; i++) {\n const k = keyedVnodes[i].key;\n const ch = parentChildren[i] as Element | undefined;\n if (!ch) {\n stable = false;\n break;\n }\n const attr = ch.getAttribute('data-key');\n if (attr === null) {\n stable = false;\n break;\n }\n if (String(k) !== attr && String(Number(attr)) !== String(k)) {\n keyMismatches++;\n }\n }\n\n if (stable) {\n if (keyMismatches === 0) {\n // Perfectly aligned - treat as stable keyed fast-path\n logger.warn(\n '[Askr][FASTPATH] applying bulk keyed text fast-path (stable keys)'\n );\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const gl = globalThis as unknown as {\n __ASKR_BULK_DIAG?: unknown;\n };\n (gl.__ASKR_BULK_DIAG as unknown) = {\n phase: 'bulk-keyed-stable-trigger',\n totalKeyed: keyedVnodes.length,\n hasPropChanges,\n };\n } catch (e) {\n void e;\n }\n }\n try {\n if (isBulkCommitActive()) markFastPathApplied(parent);\n } catch (e) {\n void e;\n }\n\n const stats = performBulkKeyedTextReplace(\n parent,\n keyedVnodes,\n oldKeyMap\n );\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const gl = globalThis as unknown as {\n __ASKR_LAST_FASTPATH_STATS?: unknown;\n __ASKR_BULK_DIAG?: unknown;\n __ASKR_FASTPATH_COUNTERS?: Record<string, number>;\n };\n (gl.__ASKR_LAST_FASTPATH_STATS as unknown) = stats;\n (gl.__ASKR_BULK_DIAG as unknown) = {\n phase: 'bulk-keyed-applied',\n stats,\n };\n const counters =\n (gl.__ASKR_FASTPATH_COUNTERS as Record<string, number>) ||\n {};\n counters.bulkKeyedTextHits =\n (counters.bulkKeyedTextHits || 0) + 1;\n gl.__ASKR_FASTPATH_COUNTERS = counters;\n } catch (e) {\n void e;\n }\n }\n return newKeyMap;\n }\n\n // If the parent shape (number of children) matches, prefer a\n // positional bulk update for large lists of simple text. This is a\n // conservative but practical heuristic: for very large lists the\n // per-node insert/move/update overhead dominates and a single\n // DocumentFragment-based positional update is much cheaper while\n // preserving identity and listeners.\n if (parentChildren.length === keyedVnodes.length) {\n logger.warn(\n '[Askr][FASTPATH] applying bulk keyed positional text fast-path (len-match)'\n );\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const gl = globalThis as unknown as {\n __ASKR_BULK_DIAG?: unknown;\n };\n (gl.__ASKR_BULK_DIAG as unknown) = {\n phase: 'bulk-keyed-positional-trigger-lenmatch',\n totalKeyed: keyedVnodes.length,\n keyMismatches: keyMismatches,\n };\n } catch (e) {\n void e;\n }\n }\n try {\n if (isBulkCommitActive()) markFastPathApplied(parent);\n } catch (e) {\n void e;\n }\n\n const stats = performBulkPositionalKeyedTextUpdate(\n parent,\n keyedVnodes\n );\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const gl = globalThis as unknown as {\n __ASKR_LAST_FASTPATH_STATS?: unknown;\n __ASKR_BULK_DIAG?: unknown;\n __ASKR_FASTPATH_COUNTERS?: Record<string, number>;\n };\n gl.__ASKR_LAST_FASTPATH_STATS = stats;\n gl.__ASKR_BULK_DIAG = {\n phase: 'bulk-keyed-positional-applied',\n stats,\n };\n const counters =\n (gl.__ASKR_FASTPATH_COUNTERS as Record<string, number>) ||\n {};\n counters.bulkKeyedPositionalHits =\n (counters.bulkKeyedPositionalHits || 0) + 1;\n gl.__ASKR_FASTPATH_COUNTERS = counters;\n } catch (e) {\n void e;\n }\n }\n return newKeyMap;\n }\n\n // If many mismatches but structural shape is identical and all children\n // are simple text, attempt positional bulk keyed replace to avoid\n // alloc/move churn. This reuses elements by position, updates text,\n // and remaps the `data-key` attribute to the new key.\n const mismatchRatio = keyMismatches / keyedVnodes.length;\n const POSITIONAL_THRESHOLD = 0.5; // if >50% mismatched, use positional path\n if (mismatchRatio > POSITIONAL_THRESHOLD) {\n logger.warn(\n '[Askr][FASTPATH] applying bulk keyed positional text fast-path'\n );\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n (\n globalThis as unknown as { __ASKR_BULK_DIAG?: unknown }\n ).__ASKR_BULK_DIAG = {\n phase: 'bulk-keyed-positional-trigger',\n totalKeyed: keyedVnodes.length,\n keyMismatches: keyMismatches,\n };\n } catch (e) {\n void e;\n }\n }\n try {\n if (isBulkCommitActive()) markFastPathApplied(parent);\n } catch (e) {\n void e;\n }\n\n const stats = performBulkPositionalKeyedTextUpdate(\n parent,\n keyedVnodes\n );\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const gl = globalThis as unknown as {\n __ASKR_LAST_FASTPATH_STATS?: unknown;\n __ASKR_BULK_DIAG?: unknown;\n __ASKR_FASTPATH_COUNTERS?: Record<string, number>;\n };\n gl.__ASKR_LAST_FASTPATH_STATS = stats;\n gl.__ASKR_BULK_DIAG = {\n phase: 'bulk-keyed-positional-applied',\n stats,\n };\n const counters =\n (gl.__ASKR_FASTPATH_COUNTERS as Record<string, number>) ||\n {};\n counters.bulkKeyedPositionalHits =\n (counters.bulkKeyedPositionalHits || 0) + 1;\n gl.__ASKR_FASTPATH_COUNTERS = counters;\n } catch (e) {\n void e;\n }\n }\n return newKeyMap;\n }\n }\n }\n } catch {\n stable = false;\n }\n }\n } catch (e) {\n void e;\n }\n if (!useFastPath) {\n const totalKeyed = keyedVnodes.length;\n // Aggressive positional reuse heuristic for small lists where all\n // keyed vnodes are simple intrinsic elements with a single primitive\n // child (text or number). This handles cases where keys change each\n // update but structure is stable (common in bulk text updates).\n // Evaluate candidates from the raw newChildren array (handles both keyed and unkeyed)\n const candidates = newChildren.filter(\n (c) => _isDOMElement(c) && typeof (c as DOMElement).type === 'string'\n ) as DOMElement[];\n const smallListPositionalReuseEligible =\n candidates.length > 0 &&\n candidates.length <= 64 &&\n parent.children.length === candidates.length &&\n candidates.every((vnode) => {\n const children =\n (vnode as DOMElement).children ||\n (vnode as DOMElement).props?.children;\n if (Array.isArray(children)) {\n return (\n children.length === 1 &&\n (typeof children[0] === 'string' || typeof children[0] === 'number')\n );\n }\n return (\n children === undefined ||\n typeof children === 'string' ||\n typeof children === 'number'\n );\n });\n\n try {\n if (smallListPositionalReuseEligible) {\n let eligible = true;\n for (let i = 0; i < totalKeyed; i++) {\n const vnode = keyedVnodes[i].vnode;\n if (\n !_isDOMElement(vnode) ||\n typeof (vnode as DOMElement).type !== 'string'\n ) {\n eligible = false;\n break;\n }\n const children =\n (vnode as DOMElement).children ||\n (vnode as DOMElement).props?.children;\n // Accept a single string/number child or no children\n if (Array.isArray(children)) {\n if (children.length !== 1) {\n eligible = false;\n break;\n }\n const c = children[0];\n if (typeof c !== 'string' && typeof c !== 'number') {\n eligible = false;\n break;\n }\n } else if (\n children !== undefined &&\n typeof children !== 'string' &&\n typeof children !== 'number'\n ) {\n eligible = false;\n break;\n }\n }\n\n // Safety guard: do not apply positional reuse when existing DOM keys match\n // incoming vnode keys. That indicates this is a keyed list reorder, and\n // identity must be preserved by key rather than by position.\n const anyKeyMatches =\n !!oldKeyMap && keyedVnodes.some((kv) => oldKeyMap!.has(kv.key));\n if (anyKeyMatches) {\n eligible = false;\n }\n\n if (eligible || process.env.ASKR_FORCE_POSREUSE === '1') {\n _triedPositionalReuse = true;\n if (process.env.ASKR_FORCE_POSREUSE === '1') {\n logger.warn(\n '[Askr][POSREUSE][FORCED] forcing positional reuse path for testing'\n );\n } else {\n logger.warn('[Askr][POSREUSE] positional reuse heuristic applied');\n }\n\n // Perform positional update in-place\n const existingChildren = parent.children;\n for (let i = 0; i < totalKeyed; i++) {\n const { key, vnode } = keyedVnodes[i];\n const current = existingChildren[i] as Element | undefined;\n if (current && _isDOMElement(vnode)) {\n const vnodeType = (vnode as DOMElement).type as string;\n if (current.tagName.toLowerCase() === vnodeType.toLowerCase()) {\n // Update attributes and children in-place\n updateElementFromVnode(current, vnode as VNode);\n newKeyMap.set(key, current);\n continue;\n }\n }\n // Fall back: create a new node and replace\n const newEl = createDOMNode(vnode);\n if (newEl instanceof Element) {\n if (current) {\n // Clean up any component instance that owned the existing node\n cleanupInstanceIfPresent(current);\n parent.replaceChild(newEl, current);\n } else parent.appendChild(newEl);\n newKeyMap.set(key, newEl);\n }\n }\n // Add unkeyed nodes (should be none in this heuristic)\n for (const vnode of unkeyedVnodes) {\n const newEl = createDOMNode(vnode);\n if (newEl) parent.appendChild(newEl as Node);\n }\n // Positional reuse done; return new key map\n return newKeyMap;\n }\n }\n } catch {\n // If any DOM read/write here fails, fall back to normal code path below\n }\n }\n\n if (useFastPath) {\n // Dev invariant: ensure we are executing inside the scheduler/commit flush\n if (!isSchedulerExecuting()) {\n logger.warn(\n '[Askr][FASTPATH][DEV] Fast-path reconciliation invoked outside scheduler execution'\n );\n }\n\n // Build either a small linear scan cache or a map depending on size.\n // For small keyed lists (<= 20) we prefer linear scans to avoid Map\n // allocations and HashTable churn — O(N^2) is acceptable for small N.\n let parentChildrenArr: Element[] | undefined;\n let localOldKeyMap: Map<string | number, Element> | undefined;\n\n if (totalKeyed <= 20) {\n try {\n const pc = parent.children;\n parentChildrenArr = new Array(pc.length);\n for (let i = 0; i < pc.length; i++)\n parentChildrenArr[i] = pc[i] as Element;\n } catch {\n parentChildrenArr = undefined;\n }\n } else {\n localOldKeyMap = new Map<string | number, Element>();\n try {\n const parentChildren = Array.from(parent.children);\n for (let i = 0; i < parentChildren.length; i++) {\n const ch = parentChildren[i] as Element;\n const k = ch.getAttribute('data-key');\n if (k !== null) {\n localOldKeyMap.set(k, ch);\n // also store numeric form for numeric keys\n const n = Number(k);\n if (!Number.isNaN(n)) localOldKeyMap.set(n, ch);\n }\n }\n } catch {\n // ignore DOM read failures; we'll fall back to creation\n localOldKeyMap = undefined;\n }\n }\n\n logger.warn(\n '[Askr][FASTPATH] oldKeyMap size:',\n oldKeyMap?.size ?? 0,\n 'localOldKeyMap size:',\n localOldKeyMap?.size\n );\n\n // Build the final node array WITHOUT touching the DOM. For existing\n // elements we reuse the `oldKeyMap` or `localOldKeyMap` references; for\n // new vnodes we create detached nodes via `createDOMNode`.\n const tLookupStart =\n typeof performance !== 'undefined' && performance.now\n ? performance.now()\n : Date.now();\n const finalNodes: Node[] = [];\n let mapLookups = 0;\n let createdNodes = 0;\n let reusedCount = 0;\n\n for (let i = 0; i < keyedVnodes.length; i++) {\n const { key, vnode } = keyedVnodes[i];\n mapLookups++;\n\n let el: Element | undefined;\n if (totalKeyed <= 20 && parentChildrenArr) {\n // Linear scan lookup for small lists (avoid Map allocation)\n const ks = String(key);\n for (let j = 0; j < parentChildrenArr.length; j++) {\n const ch = parentChildrenArr[j];\n const k = ch.getAttribute('data-key');\n if (k !== null && (k === ks || Number(k) === (key as number))) {\n el = ch;\n break;\n }\n }\n // Fallback to cached map if present\n if (!el) el = oldKeyMap?.get(key);\n } else {\n el = localOldKeyMap?.get(key as string | number) ?? oldKeyMap?.get(key);\n }\n\n if (el) {\n finalNodes.push(el);\n reusedCount++;\n } else {\n const newEl = createDOMNode(vnode);\n if (newEl) {\n finalNodes.push(newEl);\n createdNodes++;\n }\n }\n }\n\n // Add unkeyed nodes (detached as well)\n for (const vnode of unkeyedVnodes) {\n const newEl = createDOMNode(vnode);\n if (newEl) {\n finalNodes.push(newEl);\n createdNodes++;\n }\n }\n const t_lookup =\n typeof performance !== 'undefined' && performance.now\n ? performance.now() - tLookupStart\n : 0;\n\n // Dev-only guard disabled for minimal fast-path to avoid prototype\n // monkey-patching during the tight commit. The fast-path now performs a\n // single DocumentFragment-based commit and is validated via micro-bench\n // instrumentation instead of dynamic API wrapping.\n if (process.env.ASKR_FASTPATH_GUARD === '1') {\n const replaceChildrenCount = 0;\n const otherMutationCount = 0;\n\n const orig: Record<string, unknown> = {};\n // Only wrap methods that exist in the current environment\n const elProto = Element.prototype as unknown as Record<string, unknown>;\n const nodeProto = Node.prototype as unknown as Record<string, unknown>;\n // Detect existence of `remove()` on nodes without referencing the\n // `ChildNode` type (which is a TS-only interface in some lib targets).\n const removeFn = (() => {\n if (\n typeof document === 'undefined' ||\n typeof document.createElement !== 'function'\n )\n return undefined;\n try {\n const el = document.createElement('div') as unknown as {\n remove?: () => void;\n };\n return typeof el.remove === 'function' ? el.remove : undefined;\n } catch {\n return undefined;\n }\n })();\n\n if (elProto.replaceChildren)\n orig.replaceChildren = elProto.replaceChildren;\n if (nodeProto.appendChild) orig.appendChild = nodeProto.appendChild;\n if (nodeProto.insertBefore) orig.insertBefore = nodeProto.insertBefore;\n if (nodeProto.removeChild) orig.removeChild = nodeProto.removeChild;\n if (nodeProto.replaceChild) orig.replaceChild = nodeProto.replaceChild;\n if (removeFn) orig.remove = removeFn;\n\n let violation = false;\n try {\n const fragment = document.createDocumentFragment();\n for (let i = 0; i < finalNodes.length; i++)\n fragment.appendChild(finalNodes[i]);\n // Count commits explicitly in code (no prototype monkey-patching)\n let commitCount = 0;\n commitCount++;\n parent.replaceChildren(fragment);\n // Export commit count for dev diagnostics\n if (typeof globalThis !== 'undefined') {\n (globalThis as unknown as Record<string, unknown>)[\n '__ASKR_LAST_FASTPATH_COMMIT_COUNT'\n ] = commitCount;\n }\n } finally {\n // Restore parent's original\n\n // Restore originals (only those we replaced)\n\n // Assert invariants: no other structural mutation APIs were called\n // during the fast-path. We accept >=1 replaceChildren calls because\n // tests may install instance-level spies that wrap the call once.\n violation =\n (otherMutationCount as number) !== 0 ||\n (replaceChildrenCount as number) < 1;\n }\n if (violation) {\n logger.error(\n '[Askr][DEV] Fast-path structural mutation invariant violated:',\n {\n replaceChildrenCount,\n otherMutationCount,\n }\n );\n // Fail hard in dev so regressions are caught early\n throw new Error(\n 'Fast-path must perform a single structural replacement (replaceChildren) and no other structural mutations'\n );\n }\n } else {\n // Production: single atomic commit (measure phases if tracing)\n\n const tFragmentStart = Date.now();\n const fragment = document.createDocumentFragment();\n let fragmentAppendCount = 0;\n for (let i = 0; i < finalNodes.length; i++) {\n fragment.appendChild(finalNodes[i]);\n fragmentAppendCount++;\n }\n const t_fragment = Date.now() - tFragmentStart;\n\n // Dev: capture scheduler state so we can assert no tasks were enqueued\n // during the fast-path commit. This ensures we didn't accidentally\n // invoke per-node scheduling work.\n const schedBefore =\n process.env.NODE_ENV !== 'production'\n ? globalScheduler.getState()\n : null;\n const wasExecuting =\n process.env.NODE_ENV !== 'production' ? isSchedulerExecuting() : false;\n\n const tCommitStart = Date.now();\n if (process.env.NODE_ENV !== 'production') {\n // Extra debug to help tests detect the structural change and to aid\n // diagnosing spy/observer mismatches in test harnesses.\n }\n // Count commits explicitly in code (no prototype monkey-patching)\n let commitCount = 0;\n commitCount++;\n // Clean up any mounted component instances that will be removed by\n // the atomic replaceChildren commit to avoid leaking subscriptions.\n try {\n const existing = Array.from(parent.childNodes);\n for (const n of existing) cleanupInstanceIfPresent(n);\n } catch (e) {\n void e;\n }\n // Clean up any mounted component instances that will be removed by\n // the atomic replaceChildren commit to avoid leaking subscriptions.\n try {\n const existing = Array.from(parent.childNodes);\n for (const n of existing) cleanupInstanceIfPresent(n);\n } catch (e) {\n void e;\n }\n parent.replaceChildren(fragment);\n // Export commit count for dev diagnostics\n if (typeof globalThis !== 'undefined') {\n (globalThis as unknown as Record<string, unknown>)[\n '__ASKR_LAST_FASTPATH_COMMIT_COUNT'\n ] = commitCount;\n }\n const t_commit = Date.now() - tCommitStart;\n\n // Dev assertions: validate scheduler state and final DOM structure\n if (process.env.NODE_ENV !== 'production') {\n const schedAfter = globalScheduler.getState();\n if (!wasExecuting) {\n logger.warn(\n '[Askr][FASTPATH][DEV] Fast-path commit invoked outside scheduler execution'\n );\n }\n if (schedBefore && schedAfter) {\n if (schedBefore.taskCount !== schedAfter.taskCount) {\n logger.error(\n '[Askr][FASTPATH][DEV] Scheduler tasks were enqueued during fast-path commit',\n {\n before: schedBefore,\n after: schedAfter,\n }\n );\n throw new Error('Fast-path must not enqueue scheduler tasks');\n }\n }\n\n // Assert that the parent's children exactly match the final nodes\n // (single atomic replacement). If this fails, the fast-path violated\n // the single-commit invariant.\n const parentNodes = Array.from(parent.childNodes);\n if (parentNodes.length !== finalNodes.length) {\n logger.error('[Askr][FASTPATH][DEV] Parent child count mismatch', {\n parentCount: parentNodes.length,\n expected: finalNodes.length,\n });\n throw new Error(\n 'Fast-path must perform a single structural replacement'\n );\n }\n for (let i = 0; i < finalNodes.length; i++) {\n if (parentNodes[i] !== finalNodes[i]) {\n logger.error(\n '[Askr][FASTPATH][DEV] Final DOM order mismatch at index',\n i,\n {\n expected: finalNodes[i],\n found: parentNodes[i],\n }\n );\n throw new Error(\n 'Fast-path final DOM order does not match expected nodes'\n );\n }\n }\n }\n\n // Phase: minimal bookkeeping - populate newKeyMap\n const tBookkeepingStart = Date.now();\n for (let i = 0; i < keyedVnodes.length; i++) {\n const key = keyedVnodes[i].key;\n const node = finalNodes[i];\n if (node instanceof Element) newKeyMap.set(key, node as Element);\n }\n const t_bookkeeping = Date.now() - tBookkeepingStart;\n\n // Emit tracing stats in dev if requested\n if (\n process.env.ASKR_FASTPATH_TRACE === '1' ||\n process.env.NODE_ENV !== 'production'\n ) {\n const stats = {\n n: totalKeyed,\n moves: moveCount,\n lisLen: 0,\n t_lookup,\n t_fragment,\n t_commit,\n t_bookkeeping,\n fragmentAppendCount,\n mapLookups,\n createdNodes,\n reusedCount,\n } as const;\n if (typeof globalThis !== 'undefined') {\n const _g = globalThis as unknown as Record<string, unknown>;\n _g['__ASKR_LAST_FASTPATH_STATS'] = stats;\n _g['__ASKR_LAST_FASTPATH_REUSED'] = reusedCount > 0;\n // Maintain a simple history for tooling/tests so we can assert\n // that fast-path was used at least once during a series of updates\n // even if subsequent non-fast-path updates clear the most recent\n // diagnostic fields. Use a typed temporary for the history array to\n // avoid explicit `any` in typings.\n const historyKey = '__ASKR_LAST_FASTPATH_HISTORY';\n let hist = _g[historyKey] as unknown[] | undefined;\n if (!hist) {\n hist = [];\n _g[historyKey] = hist;\n }\n hist.push(stats as unknown);\n }\n logger.warn('[Askr][FASTPATH]', JSON.stringify(stats));\n }\n }\n\n return newKeyMap;\n }\n\n // Fallback: Rebuild with minimal moves: insert before `anchor` as we go\n // Compute indices of existing keyed elements in parent's current order\n const parentChildren = Array.from(parent.children);\n const positions: number[] = new Array(keyedVnodes.length).fill(-1);\n for (let i = 0; i < keyedVnodes.length; i++) {\n const key = keyedVnodes[i].key;\n const el = oldKeyMap?.get(key);\n if (el && el.parentElement === parent) {\n positions[i] = parentChildren.indexOf(el);\n }\n }\n\n // Compute Longest Increasing Subsequence (LIS) of positions to\n // determine which existing elements are already in correct order\n // and can be left in place (minimizes moves).\n const tailsStart =\n typeof performance !== 'undefined' && performance.now\n ? performance.now()\n : Date.now();\n const keepSet = new Set<number>();\n const tails: number[] = [];\n const tailsIdx: number[] = [];\n const prev: number[] = new Array(positions.length).fill(-1);\n\n for (let i = 0; i < positions.length; i++) {\n const pos = positions[i];\n if (pos === -1) continue;\n // binary search for insertion point\n let lo = 0;\n let hi = tails.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (tails[mid] < pos) lo = mid + 1;\n else hi = mid;\n }\n if (lo === tails.length) {\n tails.push(pos);\n tailsIdx.push(i);\n } else {\n tails[lo] = pos;\n tailsIdx[lo] = i;\n }\n prev[i] = lo > 0 ? tailsIdx[lo - 1] : -1;\n }\n\n // Reconstruct LIS indices into keepSet\n let k = tailsIdx.length ? tailsIdx[tailsIdx.length - 1] : -1;\n while (k !== -1) {\n keepSet.add(k);\n k = prev[k];\n }\n const tLIS =\n (typeof performance !== 'undefined' && performance.now\n ? performance.now()\n : Date.now()) - tailsStart;\n\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const prev = (\n globalThis as unknown as { __ASKR_BULK_DIAG?: { decision?: unknown } }\n ).__ASKR_BULK_DIAG;\n (\n globalThis as unknown as { __ASKR_BULK_DIAG?: unknown }\n ).__ASKR_BULK_DIAG = {\n phase: 'keyed-fallback-lis',\n positionsFound: positions.filter((p) => p !== -1).length,\n keepCount: keepSet.size,\n tLIS,\n previousDecision: prev?.decision,\n };\n } catch (e) {\n void e;\n }\n }\n\n let anchor: Node | null = parent.firstChild;\n\n for (let i = 0; i < keyedVnodes.length; i++) {\n const { key, vnode } = keyedVnodes[i];\n const el = oldKeyMap?.get(key);\n\n if (el && el.parentElement === parent) {\n if (keepSet.has(i)) {\n // This element can stay; ensure anchor advances past it\n if (anchor === el) {\n anchor = el.nextSibling;\n }\n updateElementFromVnode(el, vnode);\n newKeyMap.set(key, el);\n } else {\n // Move existing element into place before anchor\n parent.insertBefore(el, anchor);\n updateElementFromVnode(el, vnode);\n newKeyMap.set(key, el);\n anchor = el.nextSibling;\n }\n } else {\n // New element - insert before anchor\n const newEl = createDOMNode(vnode);\n if (newEl instanceof Element) {\n parent.insertBefore(newEl, anchor);\n newKeyMap.set(key, newEl);\n anchor = newEl.nextSibling;\n }\n }\n }\n\n // Add unkeyed children at the end\n for (const vnode of unkeyedVnodes) {\n const newEl = createDOMNode(vnode);\n if (newEl) {\n parent.appendChild(newEl);\n }\n }\n\n return newKeyMap;\n}\n\n/**\n * Variant of bulk replace specialized for keyed lists where elements are\n * intrinsic elements whose only child is a primitive (text/number).\n * Reuses existing Element nodes (preserves identity/listeners) and updates\n * their text content before assembling a DocumentFragment and doing a\n * single atomic replacement.\n */\nfunction performBulkKeyedTextReplace(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>,\n oldKeyMap?: Map<string | number, Element>\n) {\n const total = keyedVnodes.length;\n const finalNodes: Node[] = [];\n let reused = 0;\n let created = 0;\n const t0 =\n typeof performance !== 'undefined' && performance.now\n ? performance.now()\n : Date.now();\n\n for (let i = 0; i < total; i++) {\n const { key, vnode } = keyedVnodes[i];\n const el = oldKeyMap?.get(key);\n if (\n el &&\n _isDOMElement(vnode) &&\n typeof (vnode as DOMElement).type === 'string'\n ) {\n const children =\n (vnode as DOMElement).children || (vnode as DOMElement).props?.children;\n // Update text content in-place when possible\n if (typeof children === 'string' || typeof children === 'number') {\n if (el.childNodes.length === 1 && el.firstChild?.nodeType === 3) {\n (el.firstChild as Text).data = String(children);\n } else {\n el.textContent = String(children);\n }\n } else if (\n Array.isArray(children) &&\n children.length === 1 &&\n (typeof children[0] === 'string' || typeof children[0] === 'number')\n ) {\n if (el.childNodes.length === 1 && el.firstChild?.nodeType === 3) {\n (el.firstChild as Text).data = String(children[0]);\n } else {\n el.textContent = String(children[0]);\n }\n } else {\n // Fallback to normal element update\n updateElementFromVnode(el, vnode as VNode);\n }\n finalNodes.push(el);\n reused++;\n } else {\n const dom = createDOMNode(vnode);\n if (dom) {\n finalNodes.push(dom);\n created++;\n }\n }\n }\n\n // Remove instances that won't be in final set\n try {\n const toRemove = Array.from(parent.childNodes).filter(\n (n) => !finalNodes.includes(n)\n );\n for (const n of toRemove) cleanupInstanceIfPresent(n);\n } catch (e) {\n void e;\n }\n\n // Prepare to transfer listeners for positions where nodes are replaced\n const existingChildren = Array.from(parent.children);\n const listenerSnapshots: Array<Map<string, ListenerMapEntry> | undefined> =\n new Array(existingChildren.length).fill(undefined);\n try {\n for (let i = 0; i < existingChildren.length; i++) {\n const ch = existingChildren[i] as Element | undefined;\n if (ch) {\n const map = elementListeners.get(ch);\n if (map && map.size > 0) {\n // Clone the map entries to avoid mutation during transfer\n const clone = new Map<string, ListenerMapEntry>();\n for (const [k, v] of map) clone.set(k, v);\n listenerSnapshots[i] = clone;\n }\n }\n }\n } catch (e) {\n void e;\n }\n\n // Atomic replace using fragment\n const fragment = document.createDocumentFragment();\n for (let i = 0; i < finalNodes.length; i++)\n fragment.appendChild(finalNodes[i]);\n parent.replaceChildren(fragment);\n\n // Transfer listeners where nodes were replaced (preserve user handlers)\n try {\n for (let i = 0; i < finalNodes.length; i++) {\n const newNode = finalNodes[i];\n const snapshot = listenerSnapshots[i];\n if (snapshot && newNode instanceof Element) {\n // Reattach handlers to newNode\n for (const [eventName, entry] of snapshot) {\n // If newNode already has a listener with the same original, skip\n const existing = elementListeners.get(newNode)?.get(eventName);\n if (existing && existing.original === entry.original) continue;\n newNode.addEventListener(eventName, entry.handler);\n if (!elementListeners.has(newNode))\n elementListeners.set(newNode, new Map());\n elementListeners.get(newNode)!.set(eventName, entry);\n }\n }\n }\n } catch (e) {\n void e;\n }\n\n // Rebuild keyed map\n try {\n keyedElements.delete(parent);\n } catch (e) {\n void e;\n }\n\n const t =\n typeof performance !== 'undefined' && performance.now\n ? performance.now() - t0\n : 0;\n const stats = {\n n: total,\n reused,\n created,\n t,\n } as const;\n return stats;\n}\n\n/**\n * Positional update for keyed lists where keys changed en-masse but structure\n * (element tags and simple text children) remains identical. This updates\n * text content in-place and remaps the `data-key` attribute to the new key so\n * subsequent updates can find elements by their data-key.\n */\nfunction performBulkPositionalKeyedTextUpdate(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>\n) {\n const total = keyedVnodes.length;\n let reused = 0;\n let updatedKeys = 0;\n const t0 =\n typeof performance !== 'undefined' && performance.now\n ? performance.now()\n : Date.now();\n\n for (let i = 0; i < total; i++) {\n const { key, vnode } = keyedVnodes[i];\n const ch = parent.children[i] as Element | undefined;\n if (\n ch &&\n _isDOMElement(vnode) &&\n typeof (vnode as DOMElement).type === 'string'\n ) {\n const vnodeType = (vnode as DOMElement).type as string;\n if (ch.tagName.toLowerCase() === vnodeType.toLowerCase()) {\n const children =\n (vnode as DOMElement).children ||\n (vnode as DOMElement).props?.children;\n if (typeof children === 'string' || typeof children === 'number') {\n if (ch.childNodes.length === 1 && ch.firstChild?.nodeType === 3) {\n (ch.firstChild as Text).data = String(children);\n } else {\n ch.textContent = String(children);\n }\n } else if (\n Array.isArray(children) &&\n children.length === 1 &&\n (typeof children[0] === 'string' || typeof children[0] === 'number')\n ) {\n if (ch.childNodes.length === 1 && ch.firstChild?.nodeType === 3) {\n (ch.firstChild as Text).data = String(children[0]);\n } else {\n ch.textContent = String(children[0]);\n }\n } else {\n updateElementFromVnode(ch, vnode as VNode);\n }\n // Update data-key attribute to reflect new key mapping\n try {\n ch.setAttribute('data-key', String(key));\n updatedKeys++;\n } catch (e) {\n void e;\n }\n reused++;\n continue;\n }\n }\n // Fallback: replace the node at position i\n const dom = createDOMNode(vnode);\n if (dom) {\n const existing = parent.children[i];\n if (existing) {\n cleanupInstanceIfPresent(existing);\n parent.replaceChild(dom, existing);\n } else parent.appendChild(dom);\n }\n }\n\n const t =\n typeof performance !== 'undefined' && performance.now\n ? performance.now() - t0\n : 0;\n\n // Rebuild keyed map to reflect new keys -> element mapping\n try {\n const newKeyMap = new Map<string | number, Element>();\n for (let i = 0; i < total; i++) {\n const k = keyedVnodes[i].key;\n const ch = parent.children[i] as Element | undefined;\n if (ch) newKeyMap.set(k, ch);\n }\n keyedElements.set(parent, newKeyMap);\n } catch (e) {\n void e;\n }\n\n const stats = {\n n: total,\n reused,\n updatedKeys,\n t,\n } as const;\n return stats;\n}\n\n/**\n * Heuristic to detect large bulk text-dominant updates eligible for fast-path.\n * Conditions:\n * - total children >= threshold\n * - majority of children are simple text (string/number) or intrinsic elements\n * with a single primitive child\n * - conservative: avoid when component children or complex shapes present\n */\nfunction isBulkTextFastPathEligible(parent: Element, newChildren: VNode[]) {\n const threshold = Number(process.env.ASKR_BULK_TEXT_THRESHOLD) || 1024;\n const requiredFraction = 0.8; // 80% of children should be simple text\n\n const total = Array.isArray(newChildren) ? newChildren.length : 0;\n if (total < threshold) {\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n (\n globalThis as unknown as { __ASKR_BULK_DIAG?: unknown }\n ).__ASKR_BULK_DIAG = {\n phase: 'bulk-unkeyed-eligible',\n reason: 'too-small',\n total,\n threshold,\n };\n } catch (e) {\n void e;\n }\n }\n return false;\n }\n\n let simple = 0;\n for (let i = 0; i < newChildren.length; i++) {\n const c = newChildren[i];\n if (typeof c === 'string' || typeof c === 'number') {\n simple++;\n continue;\n }\n if (typeof c === 'object' && c !== null && 'type' in c) {\n const dv = c as DOMElement;\n if (typeof dv.type === 'function') {\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n (\n globalThis as unknown as { __ASKR_BULK_DIAG?: unknown }\n ).__ASKR_BULK_DIAG = {\n phase: 'bulk-unkeyed-eligible',\n reason: 'component-child',\n index: i,\n };\n } catch (e) {\n void e;\n }\n }\n return false; // component child - decline\n }\n if (typeof dv.type === 'string') {\n const children = dv.children || dv.props?.children;\n if (!children) {\n // empty element - treat as simple\n simple++;\n continue;\n }\n if (Array.isArray(children)) {\n if (\n children.length === 1 &&\n (typeof children[0] === 'string' || typeof children[0] === 'number')\n ) {\n simple++;\n continue;\n }\n } else if (\n typeof children === 'string' ||\n typeof children === 'number'\n ) {\n simple++;\n continue;\n }\n }\n }\n // complex child - not simple\n }\n\n const fraction = simple / total;\n const eligible =\n fraction >= requiredFraction && parent.childNodes.length >= total;\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n (\n globalThis as unknown as { __ASKR_BULK_DIAG?: unknown }\n ).__ASKR_BULK_DIAG = {\n phase: 'bulk-unkeyed-eligible',\n total,\n simple,\n fraction,\n requiredFraction,\n eligible,\n };\n } catch (e) {\n void e;\n }\n }\n\n return eligible;\n}\n\n/**\n * Perform a bulk replace using DocumentFragment while reusing existing nodes\n * where possible to preserve identity and listeners. We avoid per-node DOM\n * insert/remove churn and perform a single atomic replaceChildren.\n */\nfunction performBulkTextReplace(parent: Element, newChildren: VNode[]) {\n const t0 =\n typeof performance !== 'undefined' && performance.now\n ? performance.now()\n : Date.now();\n const existing = Array.from(parent.childNodes);\n const finalNodes: Node[] = [];\n let reused = 0;\n let created = 0;\n\n for (let i = 0; i < newChildren.length; i++) {\n const vnode = newChildren[i];\n const existingNode = existing[i];\n\n if (typeof vnode === 'string' || typeof vnode === 'number') {\n const text = String(vnode);\n if (existingNode && existingNode.nodeType === 3) {\n // Reuse existing text node\n (existingNode as Text).data = text;\n finalNodes.push(existingNode);\n reused++;\n } else {\n // Create detached text node\n finalNodes.push(document.createTextNode(text));\n created++;\n }\n continue;\n }\n\n if (typeof vnode === 'object' && vnode !== null && 'type' in vnode) {\n if (typeof (vnode as DOMElement).type === 'string') {\n const vtype = (vnode as DOMElement).type as string;\n if (\n existingNode &&\n existingNode.nodeType === 1 &&\n (existingNode as Element).tagName.toLowerCase() ===\n vtype.toLowerCase()\n ) {\n // Reuse existing element node and update its text content (simple case)\n const el = existingNode as Element;\n const children =\n (vnode as DOMElement).children ||\n (vnode as DOMElement).props?.children;\n if (typeof children === 'string' || typeof children === 'number') {\n if (el.childNodes.length === 1 && el.firstChild?.nodeType === 3) {\n (el.firstChild as Text).data = String(children);\n } else {\n el.textContent = String(children);\n }\n } else if (\n Array.isArray(children) &&\n children.length === 1 &&\n (typeof children[0] === 'string' || typeof children[0] === 'number')\n ) {\n if (el.childNodes.length === 1 && el.firstChild?.nodeType === 3) {\n (el.firstChild as Text).data = String(children[0]);\n } else {\n el.textContent = String(children[0]);\n }\n } else {\n // For slightly more complex children, fallback to existing update routine\n updateElementFromVnode(el, vnode as VNode);\n }\n finalNodes.push(el);\n reused++;\n continue;\n }\n\n // Not reusable - create detached DOM node\n const dom = createDOMNode(vnode);\n if (dom) {\n finalNodes.push(dom);\n created++;\n }\n continue;\n }\n }\n\n // Fallback for anything else: create node\n const dom = createDOMNode(vnode);\n if (dom) {\n finalNodes.push(dom);\n created++;\n }\n }\n\n const tBuild =\n typeof performance !== 'undefined' && performance.now\n ? performance.now() - t0\n : 0;\n\n // Clean up instances that will be removed\n try {\n const toRemove = Array.from(parent.childNodes).filter(\n (n) => !finalNodes.includes(n)\n );\n for (const n of toRemove) cleanupInstanceIfPresent(n);\n } catch (e) {\n void e;\n }\n\n const fragStart = Date.now();\n const fragment = document.createDocumentFragment();\n for (let i = 0; i < finalNodes.length; i++)\n fragment.appendChild(finalNodes[i]);\n // Atomic replacement\n parent.replaceChildren(fragment);\n const tCommit = Date.now() - fragStart;\n\n // Clear keyed map for unkeyed path\n keyedElements.delete(parent);\n\n const stats = {\n n: newChildren.length,\n reused,\n created,\n tBuild,\n tCommit,\n } as const;\n\n return stats;\n}\n\n/**\n * Update an existing element's attributes and children from vnode\n */\nfunction updateElementFromVnode(\n el: Element,\n vnode: VNode,\n updateChildren = true\n): void {\n if (!_isDOMElement(vnode)) {\n return;\n }\n\n const props = vnode.props || {};\n\n // Ensure key is materialized on existing elements so DOM-based scans succeed\n if ((vnode as DOMElement).key !== undefined) {\n el.setAttribute('data-key', String((vnode as DOMElement).key));\n }\n\n // Diff and update event listeners and other attributes\n const existingListeners = elementListeners.get(el);\n const desiredEventNames = new Set<string>();\n\n for (const key in props) {\n const value = (props as Record<string, unknown>)[key];\n if (key === 'children' || key === 'key') continue;\n\n // Handle removal cases\n if (value === undefined || value === null || value === false) {\n if (key === 'class' || key === 'className') {\n el.className = '';\n } else if (key.startsWith('on') && key.length > 2) {\n const eventName =\n key.slice(2).charAt(0).toLowerCase() + key.slice(3).toLowerCase();\n if (existingListeners && existingListeners.has(eventName)) {\n const entry = existingListeners.get(eventName)!;\n el.removeEventListener(eventName, entry.handler);\n existingListeners.delete(eventName);\n }\n continue;\n } else {\n el.removeAttribute(key);\n }\n continue;\n }\n\n if (key === 'class' || key === 'className') {\n el.className = String(value);\n } else if (key === 'value' || key === 'checked') {\n (el as HTMLElement & Record<string, unknown>)[key] = value;\n } else if (key.startsWith('on') && key.length > 2) {\n const eventName =\n key.slice(2).charAt(0).toLowerCase() + key.slice(3).toLowerCase();\n\n desiredEventNames.add(eventName);\n\n const existing = existingListeners?.get(eventName);\n // If the handler reference is unchanged, keep existing wrapped handler\n if (existing && existing.original === value) {\n continue;\n }\n\n // Remove old handler if present\n if (existing) {\n el.removeEventListener(eventName, existing.handler);\n }\n\n const wrappedHandler = (event: Event) => {\n globalScheduler.setInHandler(true);\n try {\n (value as EventListener)(event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n } finally {\n globalScheduler.setInHandler(false);\n }\n };\n\n el.addEventListener(eventName, wrappedHandler);\n if (!elementListeners.has(el)) {\n elementListeners.set(el, new Map());\n }\n elementListeners.get(el)!.set(eventName, {\n handler: wrappedHandler,\n original: value as EventListener,\n });\n } else {\n el.setAttribute(key, String(value));\n }\n }\n\n // Remove any remaining listeners not desired by current props\n if (existingListeners) {\n // Iterate over keys to avoid allocating a transient array via Array.from\n for (const eventName of existingListeners.keys()) {\n const entry = existingListeners.get(eventName)!;\n if (!desiredEventNames.has(eventName)) {\n el.removeEventListener(eventName, entry.handler);\n existingListeners.delete(eventName);\n }\n }\n if (existingListeners.size === 0) elementListeners.delete(el);\n }\n\n // Update children\n if (updateChildren) {\n const children =\n vnode.children || (props.children as VNode | VNode[] | undefined);\n updateElementChildren(el, children);\n }\n}\n\n/**\n * Update an existing element's children\n */\nfunction updateElementChildren(\n el: Element,\n children: VNode | VNode[] | undefined\n): void {\n if (!children) {\n el.textContent = '';\n return;\n }\n\n // Handle simple text case\n if (\n !Array.isArray(children) &&\n (typeof children === 'string' || typeof children === 'number')\n ) {\n if (el.childNodes.length === 1 && el.firstChild?.nodeType === 3) {\n // Update existing text node\n (el.firstChild as Text).data = String(children);\n } else {\n el.textContent = String(children);\n }\n return;\n }\n\n // For array children, update in-place to preserve positional identity\n if (Array.isArray(children)) {\n updateUnkeyedChildren(el, children);\n return;\n }\n\n // Fallback: clear and rebuild\n el.textContent = '';\n const dom = createDOMNode(children);\n if (dom) el.appendChild(dom);\n}\n\n/**\n * Update unkeyed children by position, preserving element identity when tags match.\n */\nfunction updateUnkeyedChildren(parent: Element, newChildren: unknown[]): void {\n const existing = Array.from(parent.children);\n // If there are only text nodes (no element children), clear before updating\n if (existing.length === 0 && parent.childNodes.length > 0) {\n parent.textContent = '';\n }\n const max = Math.max(existing.length, newChildren.length);\n\n for (let i = 0; i < max; i++) {\n const current = existing[i];\n const next = newChildren[i];\n\n // Remove extra existing children\n if (next === undefined && current) {\n // Clean up any component instance mounted on this node\n cleanupInstanceIfPresent(current);\n current.remove();\n continue;\n }\n\n // Append new children beyond existing length\n if (!current && next !== undefined) {\n const dom = createDOMNode(next);\n if (dom) parent.appendChild(dom);\n continue;\n }\n\n if (!current || next === undefined) continue;\n\n // Update existing element based on next vnode/primitive\n if (typeof next === 'string' || typeof next === 'number') {\n current.textContent = String(next);\n } else if (_isDOMElement(next)) {\n if (typeof next.type === 'string') {\n // If element type matches, update in place; otherwise replace\n if (current.tagName.toLowerCase() === next.type.toLowerCase()) {\n updateElementFromVnode(current, next);\n } else {\n const dom = createDOMNode(next);\n if (dom) {\n cleanupInstanceIfPresent(current);\n parent.replaceChild(dom, current);\n }\n }\n } else {\n // Non-string types: replace conservatively\n const dom = createDOMNode(next);\n if (dom) {\n cleanupInstanceIfPresent(current);\n parent.replaceChild(dom, current);\n }\n }\n } else {\n // Fallback for other types: replace\n const dom = createDOMNode(next);\n if (dom) {\n cleanupInstanceIfPresent(current);\n parent.replaceChild(dom, current);\n }\n }\n }\n}\n\nexport function createDOMNode(node: unknown): Node | null {\n // Fast paths for primitives (most common)\n if (typeof node === 'string') {\n return document.createTextNode(node);\n }\n if (typeof node === 'number') {\n return document.createTextNode(String(node));\n }\n\n // Null/undefined/false\n if (!node) {\n return null;\n }\n\n // Array (fragment) - batch all at once\n if (Array.isArray(node)) {\n const fragment = document.createDocumentFragment();\n for (let i = 0; i < node.length; i++) {\n const dom = createDOMNode(node[i]);\n if (dom) fragment.appendChild(dom);\n }\n return fragment;\n }\n\n // Element or Component\n if (typeof node === 'object' && node !== null && 'type' in node) {\n const type = (node as DOMElement).type;\n const props = (node as DOMElement).props || {};\n\n // Intrinsic element (string type)\n if (typeof type === 'string') {\n const el = document.createElement(type);\n\n // Set attributes and event handlers in single pass (allocation-free)\n for (const key in props) {\n const value = (props as Record<string, unknown>)[key];\n // Skip special keys\n if (key === 'children' || key === 'key') continue;\n if (value === undefined || value === null || value === false) continue;\n\n if (key.startsWith('on') && key.length > 2) {\n const eventName =\n key.slice(2).charAt(0).toLowerCase() + key.slice(3).toLowerCase();\n const wrappedHandler = (event: Event) => {\n globalScheduler.setInHandler(true);\n try {\n (value as EventListener)(event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n } finally {\n globalScheduler.setInHandler(false);\n // If the handler enqueued tasks while we disallowed microtask kicks,\n // ensure we schedule a microtask to flush them now that the handler\n // has completed. This mirrors the behavior in scheduleEventHandler.\n const state = globalScheduler.getState();\n if ((state.queueLength ?? 0) > 0 && !state.running) {\n queueMicrotask(() => {\n try {\n if (!globalScheduler.isExecuting()) globalScheduler.flush();\n } catch (err) {\n setTimeout(() => {\n throw err;\n });\n }\n });\n }\n }\n };\n\n el.addEventListener(eventName, wrappedHandler);\n if (!elementListeners.has(el)) {\n elementListeners.set(el, new Map());\n }\n elementListeners.get(el)!.set(eventName, {\n handler: wrappedHandler,\n original: value as EventListener,\n });\n } else if (key === 'class' || key === 'className') {\n el.className = String(value);\n } else if (key === 'value' || key === 'checked') {\n (el as HTMLElement & Props)[key] = value;\n el.setAttribute(key, String(value));\n } else {\n el.setAttribute(key, String(value));\n }\n }\n\n // Materialize key on created element so DOM-based fast-path can find it\n const vnodeKey = (node as DOMElement).key;\n if (vnodeKey !== undefined) {\n el.setAttribute('data-key', String(vnodeKey));\n }\n\n // Add children - batch append\n const children = props.children || (node as DOMElement).children;\n if (children) {\n if (Array.isArray(children)) {\n // Check for missing keys on dynamic lists in dev mode\n if (process.env.NODE_ENV !== 'production') {\n let hasElements = false;\n let hasKeys = false;\n for (let i = 0; i < children.length; i++) {\n const item = children[i];\n if (typeof item === 'object' && item !== null && 'type' in item) {\n hasElements = true;\n const itemProps = (item as DOMElement).props || {};\n if ('key' in itemProps) {\n hasKeys = true;\n break;\n }\n }\n }\n if (hasElements && !hasKeys) {\n if (typeof console !== 'undefined') {\n logger.warn(\n 'Missing keys on dynamic lists. Each child in a list should have a unique \"key\" prop.'\n );\n }\n }\n }\n\n for (let i = 0; i < children.length; i++) {\n const dom = createDOMNode(children[i]);\n if (dom) el.appendChild(dom);\n }\n } else {\n const dom = createDOMNode(children);\n if (dom) el.appendChild(dom);\n }\n }\n\n return el;\n }\n\n // Component (function type) - inline execution\n if (typeof type === 'function') {\n // Check if this vnode has a marked context frame\n const frame = (node as ElementWithContext)[CONTEXT_FRAME_SYMBOL];\n\n // Capture context snapshot for this component's render\n // If the vnode was not explicitly marked, fall back to the current\n // ambient frame so the component's returned subtree inherits lexical\n // provider context.\n const snapshot = frame || getCurrentContextFrame();\n\n // Components must be synchronous. Async components are not supported.\n // Use `resource()` for async work — it provides explicit pending/value/error\n // semantics, generation-based staleness, and lifecycle-bound cancellation.\n const componentFn = type as (props: Props) => unknown;\n const isAsync = componentFn.constructor.name === 'AsyncFunction';\n\n if (isAsync) {\n throw new Error(\n 'Async components are not supported. Use resource() for async work.'\n );\n }\n\n // Ensure there is a persistent instance object attached to this vnode\n const vnodeAny = node as ElementWithContext & {\n __instance?: ComponentInstance;\n };\n let childInstance = vnodeAny.__instance;\n if (!childInstance) {\n // Create a new instance for this component so it can own hooks and mount ops\n childInstance = createComponentInstance(\n `comp-${Math.random().toString(36).slice(2, 7)}`,\n componentFn as ComponentFunction,\n props || {},\n null\n );\n vnodeAny.__instance = childInstance;\n }\n\n // If this vnode was marked with a context frame, record it on the\n // instance as its incoming provider frame so future re-renders and\n // async operations (resources) can reference the correct provider chain.\n if (snapshot) {\n childInstance.ownerFrame = snapshot;\n }\n\n // Render the component inline using the instance so hooks register correctly.\n // IMPORTANT: also keep the snapshot active while materializing the returned\n // subtree so nested providers can chain to the correct parent frame.\n const result = withContext(snapshot, () =>\n renderComponentInline(childInstance)\n );\n\n if (result instanceof Promise) {\n // Defensive: disallow components that return a Promise\n throw new Error(\n 'Async components are not supported. Components must return synchronously.'\n );\n }\n\n // Create DOM subtree for the component result (under the same snapshot)\n const dom = withContext(snapshot, () => createDOMNode(result));\n\n // Mount the instance inline now that its DOM is materialized\n if (dom instanceof Element) {\n mountInstanceInline(childInstance, dom);\n } else {\n // For non-element results (fragments or text nodes) create a host\n // element to serve as the instance target. This host is not attached\n // to the document; it only provides a stable element for mount ops.\n const host = document.createElement('div');\n mountInstanceInline(childInstance, host);\n }\n\n return dom;\n }\n\n // Fragment support: render children without wrapper element\n // Uses Askr's Fragment symbol\n if (\n typeof type === 'symbol' &&\n (type === Fragment || String(type) === 'Symbol(Fragment)')\n ) {\n const fragment = document.createDocumentFragment();\n const children = props.children || (node as DOMElement).children;\n if (children) {\n if (Array.isArray(children)) {\n for (let i = 0; i < children.length; i++) {\n const dom = createDOMNode(children[i]);\n if (dom) fragment.appendChild(dom);\n }\n } else {\n const dom = createDOMNode(children);\n if (dom) fragment.appendChild(dom);\n }\n }\n return fragment;\n }\n }\n\n return null;\n}\n\n// Expose minimal renderer bridge for runtime fast-lane to call `evaluate`\nif (typeof globalThis !== 'undefined') {\n const _g = globalThis as unknown as Record<string, unknown>;\n _g.__ASKR_RENDERER = {\n evaluate,\n isKeyedReorderFastPathEligible,\n getKeyMapForElement,\n };\n}\n","/**\n * Component instance lifecycle management\n * Internal only — users never see this\n */\n\nimport { type State } from './state';\nimport { evaluate } from '../renderer/dom';\nimport { globalScheduler } from './scheduler';\nimport type { JSXElement } from '../jsx/types';\nimport type { Props } from '../shared/types';\nimport {\n // withContext is the sole primitive for context restoration\n withContext,\n type ContextFrame,\n} from './context';\nimport { logger } from '../dev/logger';\n\nexport type ComponentFunction = (\n props: Props,\n context?: { signal: AbortSignal }\n) => JSXElement | VNode | string | number | null;\n\ntype VNode = {\n type: string;\n props?: Props;\n children?: (string | VNode | null | undefined | false)[];\n};\n\nexport interface ComponentInstance {\n id: string;\n fn: ComponentFunction;\n props: Props;\n target: Element | null;\n mounted: boolean;\n abortController: AbortController; // Per-component abort lifecycle\n ssr?: boolean; // Set to true for SSR temporary instances\n stateValues: State<unknown>[]; // Persistent state storage across renders\n evaluationGeneration: number; // Prevents stale async evaluation completions\n notifyUpdate: (() => void) | null; // Callback for state updates (persisted on instance)\n // Internal: prebound helpers to avoid per-update closures (allocation hot-path)\n _pendingFlushTask?: () => void; // Clears hasPendingUpdate and triggers notifyUpdate\n _pendingRunTask?: () => void; // Clears hasPendingUpdate and runs component\n _enqueueRun?: () => void; // Batches run requests and enqueues _pendingRunTask\n stateIndexCheck: number; // Track state indices to catch conditional calls\n expectedStateIndices: number[]; // Expected sequence of state indices (frozen after first render)\n firstRenderComplete: boolean; // Flag to detect transition from first to subsequent renders\n mountOperations: Array<\n () => void | (() => void) | Promise<void | (() => void)>\n >; // Operations to run when component mounts\n cleanupFns: Array<() => void>; // Cleanup functions to run on unmount\n hasPendingUpdate: boolean; // Flag to batch state updates (coalescing)\n ownerFrame: ContextFrame | null; // Provider chain for this component (set by Scope, never overwritten)\n isRoot?: boolean;\n\n // Render-tracking for precise subscriptions (internal)\n _currentRenderToken?: number; // Token for the in-progress render (set before render)\n lastRenderToken?: number; // Token of the last *committed* render\n _pendingReadStates?: Set<State<unknown>>; // States read during the in-progress render\n _lastReadStates?: Set<State<unknown>>; // States read during the last committed render\n}\n\nexport function createComponentInstance(\n id: string,\n fn: ComponentFunction,\n props: Props,\n target: Element | null\n): ComponentInstance {\n const instance: ComponentInstance = {\n id,\n fn,\n props,\n target,\n mounted: false,\n abortController: new AbortController(), // Create per-component\n stateValues: [],\n evaluationGeneration: 0,\n notifyUpdate: null,\n // Prebound helpers (initialized below) to avoid per-update allocations\n _pendingFlushTask: undefined,\n _pendingRunTask: undefined,\n _enqueueRun: undefined,\n stateIndexCheck: -1,\n expectedStateIndices: [],\n firstRenderComplete: false,\n mountOperations: [],\n cleanupFns: [],\n hasPendingUpdate: false,\n ownerFrame: null, // Will be set by renderer when vnode is marked\n ssr: false,\n isRoot: false,\n\n // Render-tracking (for precise state subscriptions)\n _currentRenderToken: undefined,\n lastRenderToken: 0,\n _pendingReadStates: new Set(),\n _lastReadStates: new Set(),\n };\n\n // Initialize prebound helper tasks once per instance to avoid allocations\n instance._pendingRunTask = () => {\n // Clear pending flag when the run task executes\n instance.hasPendingUpdate = false;\n // Execute component run (will set up notifyUpdate before render)\n runComponent(instance);\n };\n\n instance._enqueueRun = () => {\n if (!instance.hasPendingUpdate) {\n instance.hasPendingUpdate = true;\n // Enqueue single run task (coalesces multiple writes)\n globalScheduler.enqueue(instance._pendingRunTask!);\n }\n };\n\n instance._pendingFlushTask = () => {\n // Called by state.set() when we want to flush a pending update\n instance.hasPendingUpdate = false;\n // Trigger a run via enqueue helper — this will schedule the component run\n instance._enqueueRun?.();\n };\n\n return instance;\n}\n\nlet currentInstance: ComponentInstance | null = null;\nlet stateIndex = 0;\n\n// Export for state.ts to access\nexport function getCurrentComponentInstance(): ComponentInstance | null {\n return currentInstance;\n}\n\n// Export for SSR to set temporary instance\nexport function setCurrentComponentInstance(\n instance: ComponentInstance | null\n): void {\n currentInstance = instance;\n}\n\n/**\n * Register a mount operation that will run after the component is mounted\n * Used by operations (task, on, timer, etc) to execute after render completes\n */\nimport { isBulkCommitActive } from './fastlane';\n\nexport function registerMountOperation(\n operation: () => void | (() => void) | Promise<void | (() => void)>\n): void {\n const instance = getCurrentComponentInstance();\n if (instance) {\n // If we're in bulk-commit fast lane, registering mount operations is a\n // violation of the fast-lane preconditions. Throw in dev, otherwise ignore\n // silently in production (we must avoid scheduling work during bulk commit).\n if (isBulkCommitActive()) {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(\n 'registerMountOperation called during bulk commit fast-lane'\n );\n }\n return;\n }\n instance.mountOperations.push(operation);\n }\n}\n\n/**\n * Execute all mount operations for a component\n * These run after the component is rendered and mounted to the DOM\n */\nfunction executeMountOperations(instance: ComponentInstance): void {\n // Only execute mount operations for root app instance. Child component\n // operations are currently registered but should not be executed (per\n // contract tests). They remain registered for cleanup purposes.\n if (!instance.isRoot) return;\n\n for (const operation of instance.mountOperations) {\n const result = operation();\n if (result instanceof Promise) {\n result.then((cleanup) => {\n if (typeof cleanup === 'function') {\n instance.cleanupFns.push(cleanup);\n }\n });\n } else if (typeof result === 'function') {\n instance.cleanupFns.push(result);\n }\n }\n // Clear the operations array so they don't run again on subsequent renders\n instance.mountOperations = [];\n}\n\nexport function mountInstanceInline(\n instance: ComponentInstance,\n target: Element | null\n): void {\n instance.target = target;\n // Record backref on host element so renderer can clean up when the\n // node is removed. Avoids leaks if the node is detached or replaced.\n try {\n if (target instanceof Element)\n (\n target as Element & { __ASKR_INSTANCE?: ComponentInstance }\n ).__ASKR_INSTANCE = instance;\n } catch (err) {\n void err;\n }\n\n // Ensure notifyUpdate is available for async resource completions that may\n // try to trigger re-render. This mirrors the setup in executeComponent().\n // Use prebound enqueue helper to avoid allocating a new closure\n instance.notifyUpdate = instance._enqueueRun!;\n\n const wasFirstMount = !instance.mounted;\n instance.mounted = true;\n if (wasFirstMount && instance.mountOperations.length > 0) {\n executeMountOperations(instance);\n }\n}\n\n/**\n * Run a component synchronously: execute function, handle result\n * This is the internal workhorse that manages async continuations and generation tracking.\n * Must always be called through the scheduler.\n *\n * ACTOR INVARIANT: This function is enqueued as a task, never called directly.\n */\nlet _globalRenderCounter = 0;\n\nfunction runComponent(instance: ComponentInstance): void {\n // CRITICAL: Ensure notifyUpdate is available for state.set() calls during this render.\n // This must be set before executeComponentSync() runs, not after.\n // Use prebound enqueue helper to avoid allocating per-render closures\n instance.notifyUpdate = instance._enqueueRun!;\n\n // Assign a token for this in-progress render and start a fresh pending-read set\n instance._currentRenderToken = ++_globalRenderCounter;\n instance._pendingReadStates = new Set();\n\n // Atomic rendering: capture DOM state for rollback on error\n const domSnapshot = instance.target ? instance.target.innerHTML : '';\n\n const result = executeComponentSync(instance);\n if (result instanceof Promise) {\n // Async components are not supported. Components must be synchronous and\n // must not return a Promise from their render function.\n throw new Error(\n 'Async components are not supported. Components must be synchronous.'\n );\n } else {\n // Try runtime fast-lane synchronously; if it activates we do not enqueue\n // follow-up work and the commit happens atomically in this task.\n // (Runtime fast-lane has conservative preconditions.)\n const fastlaneBridge = (\n globalThis as unknown as {\n __ASKR_FASTLANE?: {\n tryRuntimeFastLaneSync?: (\n instance: unknown,\n result: unknown\n ) => boolean;\n };\n }\n ).__ASKR_FASTLANE;\n try {\n const used = fastlaneBridge?.tryRuntimeFastLaneSync?.(instance, result);\n if (used) return;\n } catch (err) {\n // If invariant check failed in dev, surface the error; otherwise fall back\n if (process.env.NODE_ENV !== 'production') throw err;\n }\n\n // Fallback: enqueue the render/commit normally\n globalScheduler.enqueue(() => {\n if (instance.target) {\n try {\n const wasFirstMount = !instance.mounted;\n // Ensure nested component executions during evaluation have access to\n // the current component instance. This allows nested components to\n // call `state()`, `resource()`, and other runtime helpers which\n // rely on `getCurrentComponentInstance()` being available.\n const oldInstance = currentInstance;\n currentInstance = instance;\n try {\n evaluate(result, instance.target);\n } finally {\n currentInstance = oldInstance;\n }\n\n // Commit succeeded — finalize recorded state reads so subscriptions reflect\n // the last *committed* render. This updates per-state reader maps\n // deterministically and synchronously with the commit.\n finalizeReadSubscriptions(instance);\n\n instance.mounted = true;\n // Execute mount operations after first mount (do NOT run these with\n // currentInstance set - they may perform state mutations/registrations)\n if (wasFirstMount && instance.mountOperations.length > 0) {\n executeMountOperations(instance);\n }\n } catch (renderError) {\n // Atomic rendering: rollback on render error\n instance.target.innerHTML = domSnapshot;\n throw renderError;\n }\n }\n });\n }\n}\n\n/**\n * Execute a component's render function synchronously.\n * Returns either a vnode/promise immediately (does NOT render).\n * Rendering happens separately through runComponent.\n */\nexport function renderComponentInline(\n instance: ComponentInstance\n): unknown | Promise<unknown> {\n // Ensure inline executions (rendered during parent's evaluate) still\n // receive a render token and have their state reads finalized so\n // subscriptions are correctly recorded. If this function is called\n // as part of a scheduled run, the token will already be set by\n // runComponent and we should not overwrite it.\n const hadToken = instance._currentRenderToken !== undefined;\n if (!hadToken) {\n instance._currentRenderToken = ++_globalRenderCounter;\n instance._pendingReadStates = new Set();\n }\n\n try {\n const result = executeComponentSync(instance);\n // If we set the token for inline execution, finalize subscriptions now\n // because the component is effectively committed as part of the parent's\n // synchronous evaluation.\n if (!hadToken) {\n finalizeReadSubscriptions(instance);\n }\n return result;\n } finally {\n if (!hadToken) {\n instance._pendingReadStates = new Set();\n instance._currentRenderToken = undefined;\n }\n }\n}\n\nfunction executeComponentSync(\n instance: ComponentInstance\n): unknown | Promise<unknown> {\n // Reset state index tracking for this render\n instance.stateIndexCheck = -1;\n\n // Reset read tracking for all existing state\n for (const state of instance.stateValues) {\n if (state) {\n state._hasBeenRead = false;\n }\n }\n\n // Prepare pending read set for this render (reads will be finalized on commit)\n instance._pendingReadStates = new Set();\n\n currentInstance = instance;\n stateIndex = 0;\n\n try {\n // Track render time in dev mode\n const renderStartTime =\n process.env.NODE_ENV !== 'production' ? Date.now() : 0;\n\n // Create context object with abort signal\n const context = {\n signal: instance.abortController.signal,\n };\n\n // Execute component within its owner frame (provider chain).\n // This ensures all context reads see the correct provider values.\n // We create a new execution frame whose parent is the ownerFrame. The\n // `values` map is lazily allocated to avoid per-render Map allocations\n // for components that do not use context.\n const executionFrame: ContextFrame = {\n parent: instance.ownerFrame,\n values: null,\n };\n const result = withContext(executionFrame, () =>\n instance.fn(instance.props, context)\n );\n\n // Check render time in dev mode\n if (process.env.NODE_ENV !== 'production') {\n const renderTime = Date.now() - renderStartTime;\n if (renderTime > 5) {\n // Warn if render takes more than 5ms\n logger.warn(\n `[askr] Slow render detected: ${renderTime}ms. Consider optimizing component performance.`\n );\n }\n }\n\n // Mark first render complete after successful execution\n // This enables hook order validation on subsequent renders\n if (!instance.firstRenderComplete) {\n instance.firstRenderComplete = true;\n }\n\n // Check for unused state in dev mode\n if (process.env.NODE_ENV !== 'production') {\n for (let i = 0; i < instance.stateValues.length; i++) {\n const state = instance.stateValues[i];\n if (state && !state._hasBeenRead) {\n logger.warn(\n `[askr] Unused state variable detected. State should be read during render or removed.`\n );\n }\n }\n }\n\n return result;\n } finally {\n // Synchronous path: we did not push a fresh frame, so nothing to pop here.\n currentInstance = null;\n }\n}\n\n/**\n * Public entry point: Execute component with full lifecycle (execute + render)\n * Handles both initial mount and re-execution. Always enqueues through scheduler.\n * Single entry point to avoid lifecycle divergence.\n */\nexport function executeComponent(instance: ComponentInstance): void {\n // Create a fresh abort controller on mount to allow remounting\n // (old one may have been aborted during previous cleanup)\n instance.abortController = new AbortController();\n\n // Setup notifyUpdate callback using prebound helper to avoid per-call closures\n instance.notifyUpdate = instance._enqueueRun!;\n\n // Enqueue the initial component run\n globalScheduler.enqueue(() => runComponent(instance));\n}\n\nexport function getCurrentInstance(): ComponentInstance | null {\n return currentInstance;\n}\n\n/**\n * Get the abort signal for the current component\n * Used to cancel async operations on unmount/navigation\n *\n * The signal is guaranteed to be aborted when:\n * - Component unmounts\n * - Navigation occurs (different route)\n * - Parent is destroyed\n *\n * IMPORTANT: getSignal() must be called during component render execution.\n * It captures the current component instance from context.\n *\n * @returns AbortSignal that will be aborted when component unmounts\n * @throws Error if called outside component execution\n *\n * @example\n * ```ts\n * // ✅ Correct: called during render, used in async operation\n * export async function UserPage({ id }: { id: string }) {\n * const signal = getSignal();\n * const user = await fetch(`/api/users/${id}`, { signal });\n * return <div>{user.name}</div>;\n * }\n *\n * // ✅ Correct: passed to event handler\n * export function Button() {\n * const signal = getSignal();\n * return {\n * type: 'button',\n * props: {\n * onClick: async () => {\n * const data = await fetch(url, { signal });\n * }\n * }\n * };\n * }\n *\n * // ❌ Wrong: called outside component context\n * const signal = getSignal(); // Error: not in component\n * ```\n */\nexport function getSignal(): AbortSignal {\n if (!currentInstance) {\n throw new Error(\n 'getSignal() can only be called during component render execution. ' +\n 'Ensure you are calling this from inside your component function.'\n );\n }\n return currentInstance.abortController.signal;\n}\n\n/**\n * Finalize read subscriptions for an instance after a successful commit.\n * - Update per-state readers map to point to this instance's last committed token\n * - Remove this instance from states it no longer reads\n * This is deterministic and runs synchronously with commit to ensure\n * subscribers are only notified when they actually read a state in their\n * last committed render.\n */\nexport function finalizeReadSubscriptions(instance: ComponentInstance): void {\n const newSet = instance._pendingReadStates ?? new Set();\n const oldSet = instance._lastReadStates ?? new Set();\n const token = instance._currentRenderToken;\n\n if (token === undefined) return;\n\n // Remove subscriptions for states that were read previously but not in this render\n for (const s of oldSet) {\n if (!newSet.has(s)) {\n const readers = (\n s as unknown as { _readers?: Map<ComponentInstance, number> }\n )?._readers;\n if (readers) readers.delete(instance);\n }\n }\n\n // Commit token becomes the authoritative token for this instance's last render\n instance.lastRenderToken = token;\n\n // Record subscriptions for states read during this render\n for (const s of newSet) {\n let readers = (\n s as unknown as { _readers?: Map<ComponentInstance, number> }\n )?._readers;\n if (!readers) {\n readers = new Map();\n // s is a State object; assign its _readers map\n (s as State<unknown>)._readers = readers;\n }\n readers.set(instance, instance.lastRenderToken ?? 0);\n }\n\n instance._lastReadStates = newSet;\n instance._pendingReadStates = new Set();\n instance._currentRenderToken = undefined;\n}\n\nexport function getNextStateIndex(): number {\n return stateIndex++;\n}\n\n/**\n * Mount a component instance.\n * This is just an alias to executeComponent() to maintain API compatibility.\n * All lifecycle logic is unified in executeComponent().\n */\nexport function mountComponent(instance: ComponentInstance): void {\n executeComponent(instance);\n}\n\n/**\n * Clean up component — abort pending operations\n * Called on unmount or route change\n */\nexport function cleanupComponent(instance: ComponentInstance): void {\n // Execute cleanup functions (from mount effects)\n for (const cleanup of instance.cleanupFns) {\n cleanup();\n }\n instance.cleanupFns = [];\n\n // Remove deterministic state subscriptions for this instance\n if (instance._lastReadStates) {\n for (const s of instance._lastReadStates) {\n const readers = (\n s as unknown as { _readers?: Map<ComponentInstance, number> }\n )?._readers;\n if (readers) readers.delete(instance);\n }\n instance._lastReadStates = new Set();\n }\n\n // Abort all pending operations\n instance.abortController.abort();\n}\n","/**\n * Route definition and matching\n * Supports dynamic route registration for micro frontends\n *\n * Optimization: Index by depth but maintain insertion order within each depth\n */\n\nimport { match as matchPath } from './match';\nimport { getCurrentComponentInstance } from '../runtime/component';\n\nexport interface RouteHandler {\n (params: Record<string, string>, context?: { signal: AbortSignal }): unknown;\n}\n\nexport interface Route {\n path: string;\n handler: RouteHandler;\n namespace?: string;\n}\n\nexport interface ResolvedRoute {\n handler: RouteHandler;\n params: Record<string, string>;\n}\n\nconst routes: Route[] = [];\nconst namespaces = new Set<string>();\n\n// Route index by depth - maintains insertion order\nconst routesByDepth = new Map<number, Route[]>();\n\n/**\n * Parse route path depth\n */\nfunction getDepth(path: string): number {\n const normalized =\n path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;\n return normalized === '/' ? 0 : normalized.split('/').filter(Boolean).length;\n}\n\n/**\n * Calculate route specificity for priority matching\n * Higher score = more specific\n * - Literal segments: 3 points each\n * - Parameter segments ({id}): 2 points each\n * - Wildcard segments (*): 1 point each\n * - Catch-all (/*): 0 points\n */\nfunction getSpecificity(path: string): number {\n const normalized =\n path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;\n\n // Special case: catch-all pattern\n if (normalized === '/*') {\n return 0;\n }\n\n const segments = normalized.split('/').filter(Boolean);\n let score = 0;\n\n for (const segment of segments) {\n if (segment.startsWith('{') && segment.endsWith('}')) {\n score += 2; // Parameter\n } else if (segment === '*') {\n score += 1; // Wildcard\n } else {\n score += 3; // Literal\n }\n }\n\n return score;\n}\n\n/**\n * RouteMatch, RouteQuery, RouteSnapshot\n * These describe the read-only snapshot returned by the render-time route() accessor\n */\nexport interface RouteMatch {\n path: string;\n params: Readonly<Record<string, string>>;\n name?: string;\n namespace?: string;\n}\n\nexport interface RouteQuery {\n get(key: string): string | null;\n getAll(key: string): string[];\n has(key: string): boolean;\n toJSON(): Record<string, string | string[]>;\n}\n\nexport interface RouteSnapshot {\n path: string;\n params: Readonly<Record<string, string>>;\n query: Readonly<RouteQuery>;\n hash: string | null;\n\n name?: string;\n namespace?: string;\n matches: readonly RouteMatch[];\n}\n\n// SSR helper: when rendering on the server, callers may set a location so that\n// render-time route() returns deterministic server values that match client\n// hydration. This is deliberately an opt-in escape for SSR and tests.\nlet serverLocation: string | null = null;\n\nexport function setServerLocation(url: string | null): void {\n serverLocation = url;\n}\n\n// Helper: parse a URL string into components\nfunction parseLocation(url: string) {\n try {\n const u = new URL(url, 'http://localhost');\n return { pathname: u.pathname, search: u.search, hash: u.hash };\n } catch {\n return { pathname: '/', search: '', hash: '' };\n }\n}\n\n// Deep freeze utility for small objects\nfunction deepFreeze<T>(obj: T): T {\n if (obj && typeof obj === 'object' && !Object.isFrozen(obj)) {\n Object.freeze(obj as unknown as Record<string, unknown>);\n for (const key of Object.keys(obj as Record<string, unknown>)) {\n const value = (obj as unknown as Record<string, unknown>)[key];\n if (value && typeof value === 'object') deepFreeze(value);\n }\n }\n return obj;\n}\n\n// Build an immutable query helper from a search string\nfunction makeQuery(search: string): RouteQuery {\n const usp = new URLSearchParams(search || '');\n const mapping = new Map<string, string[]>();\n for (const [k, v] of usp.entries()) {\n const existing = mapping.get(k);\n if (existing) existing.push(v);\n else mapping.set(k, [v]);\n }\n\n const obj: RouteQuery = {\n get(key: string) {\n const arr = mapping.get(key);\n return arr ? arr[0] : null;\n },\n getAll(key: string) {\n const arr = mapping.get(key);\n return arr ? [...arr] : [];\n },\n has(key: string) {\n return mapping.has(key);\n },\n toJSON() {\n const out: Record<string, string | string[]> = {};\n for (const [k, arr] of mapping.entries()) {\n out[k] = arr.length > 1 ? [...arr] : arr[0];\n }\n return out;\n },\n };\n\n return deepFreeze(obj);\n}\n\n// Compute matches by scanning registered routes (public API: getRoutes)\nfunction computeMatches(pathname: string): RouteMatch[] {\n const routesList = getRoutes();\n const matches: Array<{\n pattern: string;\n params: Record<string, string>;\n name?: string;\n namespace?: string;\n specificity: number;\n }> = [];\n\n function getSpecificity(path: string) {\n // Reuse same heuristic as above\n const normalized =\n path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;\n if (normalized === '/*') return 0;\n const segments = normalized.split('/').filter(Boolean);\n let score = 0;\n for (const segment of segments) {\n if (segment.startsWith('{') && segment.endsWith('}')) score += 2;\n else if (segment === '*') score += 1;\n else score += 3;\n }\n return score;\n }\n\n for (const r of routesList) {\n const result = matchPath(pathname, r.path);\n if (result.matched) {\n matches.push({\n pattern: r.path,\n params: result.params,\n name: (r as { name?: string }).name,\n namespace: r.namespace,\n specificity: getSpecificity(r.path),\n });\n }\n }\n\n matches.sort((a, b) => b.specificity - a.specificity);\n\n return matches.map((m) => ({\n path: m.pattern,\n params: deepFreeze({ ...m.params }),\n name: m.name,\n namespace: m.namespace,\n }));\n}\n\n/**\n * Dual-purpose `route` function:\n * - route() → returns a read-only, deeply frozen RouteSnapshot (render-time)\n * - route(path, handler, namespace?) → registers a route handler (existing semantics)\n */\n// Prevent runtime registrations after the app has started\nlet registrationLocked = false;\n\nexport function lockRouteRegistration(): void {\n registrationLocked = true;\n}\n\n// Internal test helpers\nexport function _lockRouteRegistrationForTests(): void {\n registrationLocked = true;\n}\n\nexport function _unlockRouteRegistrationForTests(): void {\n registrationLocked = false;\n}\n\nexport function route(\n path?: string,\n handler?: RouteHandler,\n namespace?: string\n): void | RouteSnapshot {\n // If called with no args, act as render-time accessor\n if (typeof path === 'undefined') {\n // Access the current component instance to ensure route() is only\n // called during render.\n const instance = getCurrentComponentInstance();\n if (!instance) {\n throw new Error(\n 'route() can only be called during component render execution. ' +\n 'Call route() from inside your component function.'\n );\n }\n\n // Determine location source: client window if present; otherwise SSR override\n let pathname = '/';\n let search = '';\n let hash = '';\n\n if (typeof window !== 'undefined' && window.location) {\n pathname = window.location.pathname || '/';\n search = window.location.search || '';\n hash = window.location.hash || '';\n } else if (serverLocation) {\n const parsed = parseLocation(serverLocation);\n pathname = parsed.pathname;\n search = parsed.search;\n hash = parsed.hash;\n }\n\n const params = deepFreeze({\n ...((instance.props as Record<string, string>) || {}),\n });\n const query = makeQuery(search);\n const matches = computeMatches(pathname);\n\n const snapshot: RouteSnapshot = Object.freeze({\n path: pathname,\n params,\n query,\n hash: hash || null,\n matches: Object.freeze(matches),\n });\n\n return snapshot;\n }\n\n // Disallow route registration during SSR render\n const currentInst = getCurrentComponentInstance();\n if (currentInst && currentInst.ssr) {\n throw new Error(\n 'route() cannot be called during SSR rendering. Register routes at module load time instead.'\n );\n }\n\n // Disallow registrations after app startup\n if (registrationLocked) {\n throw new Error(\n 'Route registration is locked after app startup. Register routes at module load time before calling createApp().'\n );\n }\n\n // Otherwise register a route (backwards compatible behavior)\n if (typeof handler !== 'function') {\n throw new Error(\n 'route(path, handler) requires a function handler that returns a VNode (e.g. () => <Page />). ' +\n 'Passing JSX elements or VNodes directly is not supported.'\n );\n }\n\n const routeObj: Route = { path, handler: handler as RouteHandler, namespace };\n routes.push(routeObj);\n\n // Index by depth (maintains insertion order within depth)\n const depth = getDepth(path);\n\n let depthRoutes = routesByDepth.get(depth);\n if (!depthRoutes) {\n depthRoutes = [];\n routesByDepth.set(depth, depthRoutes);\n }\n\n depthRoutes.push(routeObj);\n\n if (namespace) {\n namespaces.add(namespace);\n }\n}\n\n/**\n * Get all registered routes\n */\nexport function getRoutes(): Route[] {\n return [...routes];\n}\n\n/**\n * Get routes for a specific namespace\n */\nexport function getNamespaceRoutes(namespace: string): Route[] {\n return routes.filter((r) => r.namespace === namespace);\n}\n\n/**\n * Unload all routes from a namespace (for MFE unmounting)\n */\nexport function unloadNamespace(namespace: string): number {\n const before = routes.length;\n\n // Remove from main array\n for (let i = routes.length - 1; i >= 0; i--) {\n if (routes[i].namespace === namespace) {\n const removed = routes[i];\n routes.splice(i, 1);\n\n // Remove from depth index\n const depth = getDepth(removed.path);\n const depthRoutes = routesByDepth.get(depth);\n if (depthRoutes) {\n const idx = depthRoutes.indexOf(removed);\n if (idx >= 0) {\n depthRoutes.splice(idx, 1);\n }\n }\n }\n }\n\n namespaces.delete(namespace);\n return before - routes.length;\n}\n\n/**\n * Clear all registered routes (mainly for testing)\n */\nexport function clearRoutes(): void {\n routes.length = 0;\n namespaces.clear();\n routesByDepth.clear();\n}\n\n/**\n * RouteDescriptor type — used by `registerRoute` for nested descriptors.\n *\n * Note: `registerRouteTree` helper was removed; prefer explicit `route()` registrations.\n */\nexport type RouteDescriptor = {\n path: string;\n handler?: RouteHandler | unknown;\n children?: RouteDescriptor[];\n _isDescriptor?: true;\n};\n\n// `registerRouteTree` was removed — register explicit absolute paths with `route(path, handler)` instead.\n// If you need a helper to register descriptor trees, add a small wrapper in userland that\n// calls `route()` recursively.\n\n// Helper: normalize common handler shapes\n// NOTE: Only function handlers are accepted — passing raw JSX/VNodes at register\n// time is not allowed. This keeps registration data-only and avoids surprising\n// semantics between module-load-time and render-time.\nfunction normalizeHandler(handler: unknown): RouteHandler | undefined {\n if (handler == null) return undefined;\n if (typeof handler === 'function') {\n // Accept both (params) => ... handlers and component functions that take no args / props\n return (params: Record<string, string>, ctx?: { signal?: AbortSignal }) => {\n // Call with params and ctx; component functions can ignore them\n // Allow handler to return JSX element, VNode, Promise, etc.\n // If the function expects only props, passing params is safe (extra args ignored)\n try {\n return handler(params, ctx);\n } catch {\n return handler(params);\n }\n };\n }\n return undefined;\n}\n\n// Register route with flexible handler shapes and optional nested descriptors.\n// Usage patterns supported:\n// - Absolute flat registration: registerRoute('/pages', () => List())\n// - Nested descriptors: registerRoute('/', () => Home(), registerRoute('pages', () => List(), registerRoute('{id}', () => Detail())))\n// Note: child descriptors should use relative paths (no leading '/').\nexport function registerRoute(\n path: string,\n handler?: unknown,\n ...children: Array<RouteDescriptor | undefined>\n): RouteDescriptor {\n const isRelative = !path.startsWith('/');\n\n // Build descriptor that can be used for nesting\n const descriptor: RouteDescriptor = {\n path,\n handler,\n children: children.filter(Boolean) as RouteDescriptor[],\n _isDescriptor: true,\n };\n\n // If path is absolute, perform registration immediately and recurse into children\n if (!isRelative) {\n const normalized = normalizeHandler(handler);\n if (handler != null && !normalized) {\n throw new Error(\n 'registerRoute(path, handler) requires a function handler. Passing JSX elements or VNodes directly is not supported.'\n );\n }\n if (normalized) route(path, normalized);\n\n for (const child of descriptor.children || []) {\n // Compute child full path\n const base = path === '/' ? '' : path.replace(/\\/$/, '');\n const childPath = `${base}/${child.path.replace(/^\\//, '')}`.replace(\n /\\/\\//g,\n '/'\n );\n // Recurse: if child.handler is provided, register it\n if (child.handler) {\n const childNormalized = normalizeHandler(child.handler);\n if (!childNormalized) {\n throw new Error(\n 'registerRoute child handler must be a function. Passing JSX elements directly is not supported.'\n );\n }\n if (childNormalized) route(childPath, childNormalized);\n }\n // Recurse into grandchildren\n if (child.children && child.children.length) {\n // Convert child.children into descriptors and register them\n // Use registerRoute recursively with absolute childPath\n registerRoute(\n childPath,\n null,\n ...(child.children as RouteDescriptor[])\n );\n }\n }\n\n return descriptor;\n }\n\n // If relative, return descriptor for nesting (do not register yet)\n return descriptor;\n}\n\n/**\n * Get all loaded namespaces (MFE identifiers)\n */\nexport function getLoadedNamespaces(): string[] {\n return Array.from(namespaces);\n}\n\n/**\n * Resolve a path to a route handler with optimized lookup\n * Routes are matched by specificity: literals > parameters > wildcards > catch-all\n */\nexport function resolveRoute(pathname: string): ResolvedRoute | null {\n const normalized =\n pathname.endsWith('/') && pathname !== '/'\n ? pathname.slice(0, -1)\n : pathname;\n const depth =\n normalized === '/' ? 0 : normalized.split('/').filter(Boolean).length;\n\n // Collect all matching routes with their specificity\n const candidates: Array<{\n route: Route;\n specificity: number;\n params: Record<string, string>;\n }> = [];\n\n // Try routes at this depth first (most likely match)\n const depthRoutes = routesByDepth.get(depth);\n if (depthRoutes) {\n for (const r of depthRoutes) {\n const result = matchPath(pathname, r.path);\n if (result.matched) {\n candidates.push({\n route: r,\n specificity: getSpecificity(r.path),\n params: result.params,\n });\n }\n }\n }\n\n // Fallback: scan all routes for different depths\n // (handles edge cases like wildcard routes)\n for (const r of routes) {\n // Skip if already checked in depth routes\n if (depthRoutes?.includes(r)) continue;\n\n const result = matchPath(pathname, r.path);\n if (result.matched) {\n candidates.push({\n route: r,\n specificity: getSpecificity(r.path),\n params: result.params,\n });\n }\n }\n\n // Sort by specificity (highest first)\n candidates.sort((a, b) => b.specificity - a.specificity);\n\n // Return most specific match\n if (candidates.length > 0) {\n const best = candidates[0];\n return { handler: best.route.handler, params: best.params };\n }\n\n return null;\n}\n","/**\n * Path matching and parameter extraction\n */\n\nexport interface MatchResult {\n matched: boolean;\n params: Record<string, string>;\n}\n\n/**\n * Match a path against a route pattern and extract params\n *\n * @example\n * match('/users/123', '/users/{id}')\n * // → { matched: true, params: { id: '123' } }\n *\n * match('/posts/hello-world/edit', '/posts/{slug}/{action}')\n * // → { matched: true, params: { slug: 'hello-world', action: 'edit' } }\n *\n * match('/users', '/posts/{id}')\n * // → { matched: false, params: {} }\n */\nexport function match(path: string, pattern: string): MatchResult {\n // Normalize trailing slashes\n const normalizedPath =\n path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;\n const normalizedPattern =\n pattern.endsWith('/') && pattern !== '/' ? pattern.slice(0, -1) : pattern;\n\n // Split into segments\n const pathSegments = normalizedPath.split('/').filter(Boolean);\n const patternSegments = normalizedPattern.split('/').filter(Boolean);\n\n // Support catch-all route: /* matches any path at any depth\n if (patternSegments.length === 1 && patternSegments[0] === '*') {\n // For multi-segment paths, preserve the leading slash\n // For single-segment paths, return just the segment\n return {\n matched: true,\n params: {\n '*': pathSegments.length > 1 ? normalizedPath : pathSegments[0],\n },\n };\n }\n\n // Check if lengths match (wildcard segments still need to match one segment)\n if (pathSegments.length !== patternSegments.length) {\n return { matched: false, params: {} };\n }\n\n const params: Record<string, string> = {};\n\n // Match each segment\n for (let i = 0; i < patternSegments.length; i++) {\n const patternSegment = patternSegments[i];\n const pathSegment = pathSegments[i];\n\n // Parameter: {paramName}\n if (patternSegment.startsWith('{') && patternSegment.endsWith('}')) {\n const paramName = patternSegment.slice(1, -1);\n params[paramName] = decodeURIComponent(pathSegment);\n } else if (patternSegment === '*') {\n // Wildcard: match single segment\n params['*'] = pathSegment;\n } else if (patternSegment !== pathSegment) {\n // Literal segment mismatch\n return { matched: false, params: {} };\n }\n }\n\n return { matched: true, params };\n}\n"],"mappings":";;;;;;;;;;;AAYO,SAAS,UACd,WACA,SACA,SACmB;AACnB,MAAI,CAAC,WAAW;AACd,UAAM,aAAa,UAAU,OAAO,KAAK,UAAU,SAAS,MAAM,CAAC,IAAI;AACvE,UAAM,IAAI,MAAM,oBAAoB,OAAO,GAAG,UAAU,EAAE;AAAA,EAC5D;AACF;AA0GO,SAAS,6BACd,WACA,kBACmB;AACnB,YAAU,WAAW,4BAA4B,gBAAgB,EAAE;AACrE;AApIA;AAAA;AAAA;A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P,aAAa,eAAe,EAAE,IAAI;AAAA,UAClC,QAAQ,OAAO;AAAA,QACjB,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAIA,aAAW,KAAK,QAAQ;AAEtB,QAAI,aAAa,SAAS,CAAC,EAAG;AAE9B,UAAM,SAAS,MAAU,UAAU,EAAE,IAAI;AACzC,QAAI,OAAO,SAAS;AAClB,iBAAW,KAAK;AAAA,QACd,OAAO;AAAA,QACP,aAAa,eAAe,EAAE,IAAI;AAAA,QAClC,QAAQ,OAAO;AAAA,MACjB,CAAC;AAAA,IACH;AAAA,EACF;AAGA,aAAW,KAAK,CAAC,GAAG,MAAM,EAAE,cAAc,EAAE,WAAW;AAGvD,MAAI,WAAW,SAAS,GAAG;AACzB,UAAM,OAAO,WAAW,CAAC;AACzB,WAAO,EAAE,SAAS,KAAK,MAAM,SAAS,QAAQ,KAAK,OAAO;AAAA,EAC5D;AAEA,SAAO;AACT;","names":["isBulkCommitActive","evaluate","_g","k","isBulkCommitActive","parentChildren","totalKeyed","prev","dom","isBulkCommitActive","getSpecificity"]}
|