@askrjs/askr 0.0.44 → 0.0.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/benchmark.js +2 -2
  2. package/dist/bin/askr-ssg.js.map +1 -1
  3. package/dist/boot/index.js.map +1 -1
  4. package/dist/common/env.js.map +1 -1
  5. package/dist/common/route-activity.js.map +1 -1
  6. package/dist/control/case.js.map +1 -1
  7. package/dist/control/show.js.map +1 -1
  8. package/dist/data/index.js.map +1 -1
  9. package/dist/foundations/icon/icon.js.map +1 -1
  10. package/dist/foundations/structures/layer.js.map +1 -1
  11. package/dist/foundations/structures/portal.js.map +1 -1
  12. package/dist/fx/fx.js.map +1 -1
  13. package/dist/fx/timing.js.map +1 -1
  14. package/dist/renderer/children.js.map +1 -1
  15. package/dist/renderer/cleanup.js.map +1 -1
  16. package/dist/renderer/dom.js.map +1 -1
  17. package/dist/renderer/evaluate.js.map +1 -1
  18. package/dist/renderer/fastpath.js.map +1 -1
  19. package/dist/renderer/for-commit.js.map +1 -1
  20. package/dist/renderer/keyed.js.map +1 -1
  21. package/dist/renderer/reconcile.js.map +1 -1
  22. package/dist/renderer/utils.js.map +1 -1
  23. package/dist/router/match.js.map +1 -1
  24. package/dist/router/navigate.js.map +1 -1
  25. package/dist/router/policy.js.map +1 -1
  26. package/dist/router/route.js.map +1 -1
  27. package/dist/runtime/component.d.ts +1 -0
  28. package/dist/runtime/component.d.ts.map +1 -1
  29. package/dist/runtime/component.js +16 -8
  30. package/dist/runtime/component.js.map +1 -1
  31. package/dist/runtime/context.js.map +1 -1
  32. package/dist/runtime/derive.js.map +1 -1
  33. package/dist/runtime/dev-namespace.js.map +1 -1
  34. package/dist/runtime/effect.js.map +1 -1
  35. package/dist/runtime/events.js.map +1 -1
  36. package/dist/runtime/fastlane.js.map +1 -1
  37. package/dist/runtime/for.js.map +1 -1
  38. package/dist/runtime/operations.js.map +1 -1
  39. package/dist/runtime/readable.d.ts +2 -1
  40. package/dist/runtime/readable.d.ts.map +1 -1
  41. package/dist/runtime/readable.js +41 -10
  42. package/dist/runtime/readable.js.map +1 -1
  43. package/dist/runtime/resource-cell.js.map +1 -1
  44. package/dist/runtime/scheduler.js.map +1 -1
  45. package/dist/runtime/selector.js.map +1 -1
  46. package/dist/ssg/batch-render.js.map +1 -1
  47. package/dist/ssg/create-static-gen.js.map +1 -1
  48. package/dist/ssg/generate-metadata.js.map +1 -1
  49. package/dist/ssg/incremental-manifest.js.map +1 -1
  50. package/dist/ssg/resolve-ssg-data.js.map +1 -1
  51. package/dist/ssg/write-static-files.js.map +1 -1
  52. package/dist/ssr/context.js.map +1 -1
  53. package/dist/ssr/escape.js.map +1 -1
  54. package/dist/ssr/index.js.map +1 -1
  55. package/dist/ssr/render-keys.js.map +1 -1
  56. package/dist/testing/index.js.map +1 -1
  57. package/package.json +3 -2
@@ -1 +1 @@
1
- {"version":3,"file":"component.js","names":[],"sources":["../../src/runtime/component.ts"],"sourcesContent":["/**\n * Component instance lifecycle management\n * Internal only — users never see this\n */\n\nimport { type State } from './state';\nimport { globalScheduler } from './scheduler';\nimport type { Props } from '../common/props';\nimport type { ComponentFunction } from '../common/component';\nimport {\n // withContext is the sole primitive for context restoration\n withContext,\n type ContextFrame,\n} from './context';\nimport {\n type ReadableSource,\n finalizeReadableSubscriptions,\n finalizeReadableSubscriptionsFromSnapshot,\n cleanupReadableSubscriptions,\n} from './readable';\nimport {\n isDevelopmentEnvironment,\n isProductionEnvironment,\n} from '../common/env';\nimport { logger } from '../dev/logger';\nimport { incDevCounter, setDevValue } from './dev-namespace';\nimport { isPromiseLike } from '../common/promise';\n\nexport type { ComponentFunction } from '../common/component';\n\nexport interface ComponentInstance {\n id: string;\n fn: ComponentFunction;\n props: Props;\n target: Element | null;\n parentInstance: ComponentInstance | null;\n portalScope: object | null;\n mounted: boolean;\n abortController: AbortController | null; // Lazily created per-component abort lifecycle\n ssr?: boolean; // Set to true for SSR temporary instances\n // Opt-in strict cleanup mode: when true cleanup errors are aggregated and re-thrown\n cleanupStrict?: boolean;\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 render-scoped hook indices (frozen after first render)\n firstRenderComplete: boolean; // Flag to detect transition from first to subsequent renders\n mountOperations: Array<\n () => void | (() => void) | PromiseLike<void | (() => void)>\n >; // Operations to run when component mounts\n commitOperations: Array<\n () => void | (() => void) | PromiseLike<void | (() => void)>\n >; // Operations to run after a successful committed render\n cleanupFns: Array<() => void>; // Cleanup functions to run on unmount\n lifecycleSlots: unknown[]; // Render-scoped lifecycle primitive storage\n lifecycleGeneration: number; // Invalidates async mount-operation settlement after disposal\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 _pendingReadSources?: Set<ReadableSource<unknown>>; // Readables read during the in-progress render\n _lastReadSources?: Set<ReadableSource<unknown>>; // Readables read during the last committed render\n devWarningsEmitted?: Set<string>; // Dev-only warning dedupe for this instance\n\n // Placeholder for null-returning components. When a component initially returns\n // null, we create a comment placeholder so updates can replace it with content.\n _placeholder?: Comment;\n _ownedChildScopes?: Set<{\n key: string | number;\n dispose(): void;\n }>;\n errorBoundaryState?: {\n error: unknown | null;\n resetKey: unknown;\n notified: boolean;\n };\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 parentInstance: currentInstance,\n portalScope: currentInstance?.portalScope ?? currentPortalScope ?? null,\n mounted: false,\n abortController: null,\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 commitOperations: [],\n cleanupFns: [],\n lifecycleSlots: [],\n lifecycleGeneration: 0,\n hasPendingUpdate: false,\n ownerFrame: null, // Will be set by renderer when vnode is marked\n ssr: false,\n cleanupStrict: false,\n isRoot: false,\n\n // Render-tracking (for precise state subscriptions)\n _currentRenderToken: undefined,\n lastRenderToken: 0,\n _pendingReadSources: undefined,\n _lastReadSources: undefined,\n devWarningsEmitted: undefined,\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 if (instance.notifyUpdate === null) {\n return;\n }\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 // Default state-driven updates enqueue the run task directly. Specialized\n // runtimes (for example `For` item instances) can still override this hook.\n instance._pendingFlushTask = instance._pendingRunTask;\n\n return instance;\n}\n\nlet currentInstance: ComponentInstance | null = null;\nlet currentPortalScope: object | null = null;\nlet stateIndex = 0;\n\ntype OwnedChildScope = {\n key: string | number;\n dispose(): void;\n};\n\nfunction ensureAbortController(instance: ComponentInstance): AbortController {\n let controller = instance.abortController;\n if (!controller || controller.signal.aborted) {\n controller = new AbortController();\n instance.abortController = controller;\n }\n return controller;\n}\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 currentPortalScope = instance?.portalScope ?? null;\n}\n\nexport function getCurrentPortalScope(): object | null {\n return currentInstance?.portalScope ?? currentPortalScope;\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';\nimport { evaluate, cleanupInstancesUnder } from '../renderer';\n\ntype LifecycleOperation = () =>\n | void\n | (() => void)\n | PromiseLike<void | (() => void)>;\n\ntype LifecycleCommitBatchEntry = {\n instance: ComponentInstance;\n wasFirstMount: boolean;\n};\n\ntype ReadSubscriptionCommit = {\n instance: ComponentInstance;\n token: number;\n pendingReadSources: Set<ReadableSource<unknown>> | undefined;\n};\n\ntype InlineRenderSnapshot = {\n instance: ComponentInstance;\n props: Props;\n ownerFrame: ContextFrame | null;\n portalScope: object | null;\n parentInstance: ComponentInstance | null;\n isRoot: boolean | undefined;\n};\n\ntype LifecycleCommitBatch = {\n parent: LifecycleCommitBatch | null;\n entries: LifecycleCommitBatchEntry[];\n entriesByInstance: Map<ComponentInstance, LifecycleCommitBatchEntry>;\n readCommits: ReadSubscriptionCommit[];\n readCommitsByInstance: Map<ComponentInstance, ReadSubscriptionCommit>;\n renderSnapshots: InlineRenderSnapshot[];\n renderSnapshotsByInstance: Map<ComponentInstance, InlineRenderSnapshot>;\n active: boolean;\n};\n\nlet currentLifecycleCommitBatch: LifecycleCommitBatch | null = null;\n\nfunction beginLifecycleCommitBatch(): LifecycleCommitBatch {\n const batch: LifecycleCommitBatch = {\n parent: currentLifecycleCommitBatch,\n entries: [],\n entriesByInstance: new Map(),\n readCommits: [],\n readCommitsByInstance: new Map(),\n renderSnapshots: [],\n renderSnapshotsByInstance: new Map(),\n active: true,\n };\n currentLifecycleCommitBatch = batch;\n return batch;\n}\n\nfunction closeLifecycleCommitBatch(batch: LifecycleCommitBatch): boolean {\n if (!batch.active) {\n return false;\n }\n\n batch.active = false;\n currentLifecycleCommitBatch = batch.parent;\n return true;\n}\n\nfunction enqueueLifecycleCommit(\n batch: LifecycleCommitBatch,\n instance: ComponentInstance,\n wasFirstMount: boolean\n): void {\n const existing = batch.entriesByInstance.get(instance);\n if (existing) {\n existing.wasFirstMount = existing.wasFirstMount || wasFirstMount;\n return;\n }\n\n const entry = { instance, wasFirstMount };\n batch.entriesByInstance.set(instance, entry);\n batch.entries.push(entry);\n}\n\nfunction enqueueReadSubscriptionCommit(\n batch: LifecycleCommitBatch,\n instance: ComponentInstance,\n token: number,\n pendingReadSources: Set<ReadableSource<unknown>> | undefined\n): void {\n const existing = batch.readCommitsByInstance.get(instance);\n const commit = existing ?? {\n instance,\n token,\n pendingReadSources,\n };\n\n commit.token = token;\n commit.pendingReadSources = pendingReadSources\n ? new Set(pendingReadSources)\n : undefined;\n\n if (!existing) {\n batch.readCommitsByInstance.set(instance, commit);\n batch.readCommits.push(commit);\n }\n}\n\nfunction enqueueInlineRenderSnapshot(\n batch: LifecycleCommitBatch,\n snapshot: InlineRenderSnapshot\n): void {\n if (batch.renderSnapshotsByInstance.has(snapshot.instance)) {\n return;\n }\n\n batch.renderSnapshotsByInstance.set(snapshot.instance, snapshot);\n batch.renderSnapshots.push(snapshot);\n}\n\nexport function captureInlineRenderSnapshot(instance: ComponentInstance): void {\n if (!currentLifecycleCommitBatch?.active) {\n return;\n }\n\n enqueueInlineRenderSnapshot(currentLifecycleCommitBatch, {\n instance,\n props: instance.props,\n ownerFrame: instance.ownerFrame,\n portalScope: instance.portalScope,\n parentInstance: instance.parentInstance,\n isRoot: instance.isRoot,\n });\n}\n\nfunction finalizeInlineReadSubscriptions(\n instance: ComponentInstance,\n token: number,\n pendingReadSources: Set<ReadableSource<unknown>> | undefined\n): void {\n if (currentLifecycleCommitBatch?.active) {\n enqueueReadSubscriptionCommit(\n currentLifecycleCommitBatch,\n instance,\n token,\n pendingReadSources\n );\n return;\n }\n\n finalizeReadableSubscriptionsFromSnapshot(\n instance,\n token,\n pendingReadSources\n );\n}\n\nfunction flushLifecycleCommitBatch(batch: LifecycleCommitBatch): void {\n if (!closeLifecycleCommitBatch(batch)) {\n return;\n }\n\n if (batch.parent?.active) {\n for (const snapshot of batch.renderSnapshots) {\n enqueueInlineRenderSnapshot(batch.parent, snapshot);\n }\n for (const commit of batch.readCommits) {\n enqueueReadSubscriptionCommit(\n batch.parent,\n commit.instance,\n commit.token,\n commit.pendingReadSources\n );\n }\n for (const entry of batch.entries) {\n enqueueLifecycleCommit(batch.parent, entry.instance, entry.wasFirstMount);\n }\n return;\n }\n\n for (const commit of batch.readCommits) {\n finalizeReadableSubscriptionsFromSnapshot(\n commit.instance,\n commit.token,\n commit.pendingReadSources\n );\n }\n\n for (const entry of batch.entries) {\n executeCommittedLifecycleOperations(entry.instance, entry.wasFirstMount);\n }\n}\n\nfunction discardLifecycleCommitBatch(batch: LifecycleCommitBatch): void {\n if (!closeLifecycleCommitBatch(batch)) {\n return;\n }\n\n for (let index = batch.renderSnapshots.length - 1; index >= 0; index -= 1) {\n const snapshot = batch.renderSnapshots[index]!;\n snapshot.instance.props = snapshot.props;\n snapshot.instance.ownerFrame = snapshot.ownerFrame;\n snapshot.instance.portalScope = snapshot.portalScope;\n snapshot.instance.parentInstance = snapshot.parentInstance;\n snapshot.instance.isRoot = snapshot.isRoot;\n }\n\n for (const entry of batch.entries) {\n if (entry.wasFirstMount) {\n entry.instance.mountOperations = [];\n }\n discardCommitOperations(entry.instance);\n }\n}\n\nexport function registerMountOperation(operation: LifecycleOperation): 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 (isDevelopmentEnvironment()) {\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\nexport function registerCommitOperation(operation: LifecycleOperation): void {\n const instance = getCurrentComponentInstance();\n if (instance) {\n if (isBulkCommitActive()) {\n if (isDevelopmentEnvironment()) {\n throw new Error(\n 'registerCommitOperation called during bulk commit fast-lane'\n );\n }\n return;\n }\n instance.commitOperations.push(operation);\n }\n}\n\nfunction settleLifecycleOperationResult(\n instance: ComponentInstance,\n lifecycleGeneration: number,\n result: void | (() => void) | PromiseLike<void | (() => void)>\n): void {\n if (isPromiseLike(result)) {\n Promise.resolve(result).then(\n (cleanup) => {\n if (typeof cleanup === 'function') {\n if (\n instance.lifecycleGeneration === lifecycleGeneration &&\n instance.mounted\n ) {\n instance.cleanupFns.push(cleanup);\n return;\n }\n\n try {\n cleanup();\n } catch (err) {\n logger.error('[Askr] async mount cleanup failed:', err);\n }\n }\n },\n (err) => {\n logger.error('[Askr] async mount operation failed:', err);\n }\n );\n } else if (typeof result === 'function') {\n instance.cleanupFns.push(result);\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 const mountOperations = instance.mountOperations;\n if (mountOperations.length === 0) {\n return;\n }\n\n const lifecycleGeneration = instance.lifecycleGeneration;\n\n for (const operation of mountOperations) {\n settleLifecycleOperationResult(instance, lifecycleGeneration, operation());\n }\n // Clear the operations array so they don't run again on subsequent renders\n instance.mountOperations = [];\n}\n\nfunction executeCommitOperations(instance: ComponentInstance): void {\n const commitOperations = instance.commitOperations;\n if (commitOperations.length === 0) {\n return;\n }\n\n instance.commitOperations = [];\n const lifecycleGeneration = instance.lifecycleGeneration;\n\n for (const operation of commitOperations) {\n settleLifecycleOperationResult(instance, lifecycleGeneration, operation());\n }\n}\n\nfunction discardCommitOperations(instance: ComponentInstance): void {\n instance.commitOperations = [];\n}\n\nfunction executeCommittedLifecycleOperations(\n instance: ComponentInstance,\n wasFirstMount: boolean\n): void {\n if (wasFirstMount && instance.mountOperations.length > 0) {\n executeMountOperations(instance);\n }\n if (instance.commitOperations.length > 0) {\n executeCommitOperations(instance);\n }\n}\n\nfunction commitLifecycleForInstance(\n instance: ComponentInstance,\n wasFirstMount: boolean\n): void {\n if (currentLifecycleCommitBatch) {\n enqueueLifecycleCommit(\n currentLifecycleCommitBatch,\n instance,\n wasFirstMount\n );\n return;\n }\n\n executeCommittedLifecycleOperations(instance, wasFirstMount);\n}\n\nexport function commitRenderedComponent(instance: ComponentInstance): void {\n if (instance.mounted && instance.commitOperations.length > 0) {\n commitLifecycleForInstance(instance, false);\n }\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 const host = target as Element & {\n __ASKR_INSTANCE?: ComponentInstance;\n __ASKR_INSTANCES?: ComponentInstance[];\n };\n const instances = host.__ASKR_INSTANCES ?? [];\n const nextInstances = instances.filter((entry) => entry !== instance);\n nextInstances.push(instance);\n host.__ASKR_INSTANCES = nextInstances;\n host.__ASKR_INSTANCE = nextInstances[0] ?? instance;\n }\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 commitLifecycleForInstance(instance, wasFirstMount);\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 resetRenderState(instance: ComponentInstance): void {\n instance.stateIndexCheck = -1;\n\n for (const state of instance.stateValues) {\n if (state) {\n state._hasBeenRead = false;\n }\n }\n\n instance._pendingReadSources = undefined;\n}\n\nfunction nextRenderToken(): number {\n return ++_globalRenderCounter;\n}\n\nexport function renderScopedComponent<T>(\n instance: ComponentInstance,\n startStateIndex: number,\n render: () => T\n): T {\n const savedInstance = currentInstance;\n const savedPortalScope = currentPortalScope;\n const savedStateIndex = stateIndex;\n\n instance.notifyUpdate = instance._enqueueRun!;\n resetRenderState(instance);\n instance._currentRenderToken = nextRenderToken();\n\n currentInstance = instance;\n currentPortalScope = instance.portalScope ?? savedPortalScope;\n stateIndex = startStateIndex;\n\n let didComplete = false;\n\n try {\n const executionFrame: ContextFrame = {\n parent: instance.ownerFrame,\n values: null,\n };\n const result = withContext(executionFrame, render);\n didComplete = true;\n return result;\n } finally {\n if (!didComplete) {\n instance._pendingReadSources = undefined;\n instance._currentRenderToken = undefined;\n }\n currentInstance = savedInstance;\n currentPortalScope = savedPortalScope;\n stateIndex = savedStateIndex;\n }\n}\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 = nextRenderToken();\n instance._pendingReadSources = undefined;\n const domSnapshot = instance.target ? instance.target.innerHTML : '';\n\n let result: unknown | Promise<unknown>;\n try {\n result = executeComponentSync(instance);\n } catch (err) {\n discardCommitOperations(instance);\n throw err;\n }\n if (isPromiseLike(result)) {\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 {\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) {\n warnUnusedStateReads(instance);\n return;\n }\n } catch (err) {\n // If invariant check failed in dev, surface the error; otherwise fall back\n if (isDevelopmentEnvironment()) throw err;\n }\n\n // Fallback: enqueue the render/commit normally\n globalScheduler.enqueue(() => {\n // Handle placeholder-based updates: when a component initially returned null,\n // we created a comment placeholder. If it now has content, we need to create\n // a host element and replace the placeholder.\n if (!instance.target && instance._placeholder) {\n // Component previously returned null (has placeholder), check if now has content\n if (result === null || result === undefined) {\n // Still null - nothing to do, keep placeholder\n finalizeReadSubscriptions(instance);\n warnUnusedStateReads(instance);\n commitRenderedComponent(instance);\n return;\n }\n\n // Has content now - need to create DOM and replace placeholder\n const placeholder = instance._placeholder;\n const parent = placeholder.parentNode;\n if (!parent) {\n // Placeholder was removed from DOM - can't render\n logger.warn(\n '[Askr] placeholder no longer in DOM, cannot render component'\n );\n return;\n }\n\n // Create a new host element for the content\n const host = document.createElement('div');\n const executionFrame: ContextFrame = {\n parent: instance.ownerFrame,\n values: null,\n };\n\n // Set up instance for normal updates\n const oldInstance = currentInstance;\n currentInstance = instance;\n const lifecycleBatch = beginLifecycleCommitBatch();\n try {\n try {\n withContext(executionFrame, () => {\n evaluate(result, host);\n });\n\n // Replace placeholder with host\n parent.replaceChild(host, placeholder);\n } catch (err) {\n discardLifecycleCommitBatch(lifecycleBatch);\n throw err;\n }\n\n // Set up instance for future updates\n instance.target = host;\n instance._placeholder = undefined;\n (\n host as Element & { __ASKR_INSTANCE?: ComponentInstance }\n ).__ASKR_INSTANCE = instance;\n\n flushLifecycleCommitBatch(lifecycleBatch);\n finalizeReadSubscriptions(instance);\n warnUnusedStateReads(instance);\n commitRenderedComponent(instance);\n } finally {\n currentInstance = oldInstance;\n }\n return;\n }\n\n if (instance.target) {\n let oldChildren: Node[] = [];\n let restoredOldChildren = false;\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 const executionFrame: ContextFrame = {\n parent: instance.ownerFrame,\n values: null,\n };\n // Capture snapshot of current children (by reference) so we can\n // restore them on render failure without losing event listeners or\n // instance attachments.\n oldChildren = Array.from(instance.target.childNodes);\n\n const lifecycleBatch = beginLifecycleCommitBatch();\n try {\n try {\n withContext(executionFrame, () => {\n evaluate(result, instance.target, undefined, instance);\n });\n } catch (e) {\n discardLifecycleCommitBatch(lifecycleBatch);\n throw e;\n }\n } catch (e) {\n // If evaluation failed, attempt to cleanup any partially-added nodes\n // and restore the old children to preserve listeners and instances.\n try {\n const newChildren = Array.from(instance.target.childNodes);\n const preservedChildren = new Set(oldChildren);\n for (const n of newChildren) {\n if (preservedChildren.has(n)) {\n continue;\n }\n try {\n cleanupInstancesUnder(n);\n } catch (err) {\n logger.warn(\n '[Askr] error cleaning up failed commit children:',\n err\n );\n }\n }\n } catch (_err) {\n void _err;\n }\n\n // Restore original children by re-inserting the old node references\n // this preserves attached listeners and instance backrefs.\n try {\n incDevCounter('__DOM_REPLACE_COUNT');\n setDevValue(\n '__LAST_DOM_REPLACE_STACK_COMPONENT_RESTORE',\n new Error().stack\n );\n } catch (e) {\n void e;\n }\n instance.target.replaceChildren(...oldChildren);\n restoredOldChildren = true;\n throw e;\n } finally {\n currentInstance = oldInstance;\n }\n\n flushLifecycleCommitBatch(lifecycleBatch);\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 warnUnusedStateReads(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 executeCommittedLifecycleOperations(instance, wasFirstMount);\n } catch (renderError) {\n discardCommitOperations(instance);\n // Atomic rendering: rollback on render error. Attempt non-lossy restore of\n // original child node references to preserve listeners/instances.\n try {\n const currentChildren = Array.from(instance.target.childNodes);\n const preservedChildren = restoredOldChildren\n ? new Set(oldChildren)\n : null;\n for (const n of currentChildren) {\n if (preservedChildren?.has(n)) {\n continue;\n }\n try {\n cleanupInstancesUnder(n);\n } catch (err) {\n logger.warn(\n '[Askr] error cleaning up partial children during rollback:',\n err\n );\n }\n }\n } catch (_err) {\n void _err;\n }\n\n try {\n incDevCounter('__DOM_REPLACE_COUNT');\n setDevValue(\n '__LAST_DOM_REPLACE_STACK_COMPONENT_ROLLBACK',\n new Error().stack\n );\n instance.target.replaceChildren(...oldChildren);\n } catch {\n // Fallback to innerHTML restore if replaceChildren fails for some reason.\n instance.target.innerHTML = domSnapshot;\n }\n\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 // Reused inline instances can cross renderer cleanup boundaries while their\n // host node is retained. Make sure state writes still enqueue this instance.\n instance.notifyUpdate = instance._enqueueRun!;\n\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 const prevToken = instance._currentRenderToken;\n const prevPendingReads = instance._pendingReadSources;\n const savedInstance = currentInstance;\n const savedPortalScope = currentPortalScope;\n if (!hadToken) {\n instance._currentRenderToken = nextRenderToken();\n instance._pendingReadSources = undefined;\n }\n\n try {\n const result = executeComponentSync(instance);\n // If we set the token for inline execution, finalize subscriptions now\n // unless the parent DOM commit is still provisional. Renderer commit\n // batches flush these reads only after DOM evaluation succeeds.\n if (!hadToken) {\n finalizeInlineReadSubscriptions(\n instance,\n instance._currentRenderToken!,\n instance._pendingReadSources\n );\n }\n commitRenderedComponent(instance);\n return result;\n } finally {\n // Restore previous token/read states for nested inline render scenarios\n instance._currentRenderToken = prevToken;\n instance._pendingReadSources = prevPendingReads;\n currentInstance = savedInstance;\n currentPortalScope = savedPortalScope;\n }\n}\n\nexport function warnUnusedStateReads(instance: ComponentInstance): void {\n for (let i = 0; i < instance.stateValues.length; i++) {\n const state = instance.stateValues[i];\n const hasCommittedUsage =\n (state?._readers?.size ?? 0) > 0 ||\n ((state as { _derivedSubscribers?: Set<unknown> } | undefined)\n ?._derivedSubscribers?.size ?? 0) > 0;\n\n if (\n state &&\n !state._hasBeenRead &&\n !state._hasEverBeenRead &&\n !hasCommittedUsage\n ) {\n try {\n const name = instance.fn?.name || '<anonymous>';\n warnInstanceOnce(\n instance,\n `unused-state:${i}`,\n `[askr] Unused state variable detected in ${name} at index ${i}. State should be read during render or removed.`\n );\n } catch {\n warnInstanceOnce(\n instance,\n `unused-state:${i}`,\n `[askr] Unused state variable detected. State should be read during render or removed.`\n );\n }\n }\n }\n}\n\nfunction executeComponentSync(\n instance: ComponentInstance\n): unknown | Promise<unknown> {\n resetRenderState(instance);\n incDevCounter('componentRuns');\n incDevCounter('componentReruns');\n\n const savedPortalScope = currentPortalScope;\n currentInstance = instance;\n currentPortalScope = instance.portalScope ?? savedPortalScope;\n stateIndex = 0;\n\n let didComplete = false;\n\n try {\n // Track render time in dev mode\n const renderStartTime = isDevelopmentEnvironment() ? Date.now() : 0;\n\n // Create context object with abort signal\n const context = {\n get signal(): AbortSignal {\n return ensureAbortController(instance).signal;\n },\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\n const renderTime = Date.now() - renderStartTime;\n if (renderTime > 5) {\n warnInstanceOnce(\n instance,\n 'slow-render',\n `[askr] Slow render detected: ${renderTime}ms. Consider optimizing component performance.`\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 didComplete = true;\n return result;\n } finally {\n if (!didComplete) {\n discardCommitOperations(instance);\n }\n // Synchronous path: we did not push a fresh frame, so nothing to pop here.\n currentInstance = null;\n currentPortalScope = savedPortalScope;\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 // Lazily recreate abort controller only when signal is actually requested.\n instance.abortController = null;\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(instance._pendingRunTask!);\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 ensureAbortController(currentInstance).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 finalizeReadableSubscriptions(instance);\n}\n\nexport function getNextStateIndex(): number {\n return stateIndex++;\n}\n\nexport function claimHookIndex(\n instance: ComponentInstance,\n hookName: string\n): number {\n const index = getNextStateIndex();\n\n if (index < instance.stateIndexCheck) {\n throw new Error(\n `Hook index violation: ${hookName}() call at index ${index}, ` +\n `but previously saw index ${instance.stateIndexCheck}. ` +\n `This happens when render-scoped hooks are called conditionally (inside if/for/etc). ` +\n `Move all ${hookName}() calls to the top level of your component function, ` +\n `before any conditionals.`\n );\n }\n\n instance.stateIndexCheck = index;\n\n if (instance.firstRenderComplete) {\n if (instance.expectedStateIndices[index] !== index) {\n throw new Error(\n `Hook order violation: ${hookName}() called at index ${index}, ` +\n `but this index was not in the first render's sequence [${instance.expectedStateIndices.join(', ')}]. ` +\n `This usually means ${hookName}() is inside a conditional or loop. ` +\n `Move all render-scoped hooks to the top level of your component function.`\n );\n }\n } else {\n instance.expectedStateIndices.push(index);\n }\n\n return index;\n}\n\nexport function getCurrentStateIndex(): number {\n return stateIndex;\n}\n\nexport function resetStateIndex(): void {\n stateIndex = 0;\n}\n\nexport function setStateIndex(value: number): void {\n stateIndex = value;\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 const savedInstance = currentInstance;\n const savedPortalScope = currentPortalScope;\n currentInstance = null;\n currentPortalScope = null;\n\n try {\n const cleanupErrors: unknown[] = [];\n const recordCleanupError = (message: string, err: unknown): void => {\n if (instance.cleanupStrict) {\n cleanupErrors.push(err);\n } else if (isDevelopmentEnvironment()) {\n logger.warn(message, err);\n }\n };\n\n const ownedChildScopes = instance._ownedChildScopes;\n if (ownedChildScopes && ownedChildScopes.size > 0) {\n instance._ownedChildScopes = new Set();\n for (const scope of ownedChildScopes) {\n try {\n scope.dispose();\n } catch (err) {\n recordCleanupError('[Askr] child scope cleanup threw:', err);\n }\n }\n }\n\n // Execute cleanup functions (from mount effects)\n const cleanupFns = instance.cleanupFns;\n instance.cleanupFns = [];\n for (const cleanup of cleanupFns) {\n try {\n cleanup();\n } catch (err) {\n recordCleanupError('[Askr] cleanup function threw:', err);\n }\n }\n\n // Remove deterministic state subscriptions for this instance\n try {\n cleanupReadableSubscriptions(instance);\n } catch (err) {\n recordCleanupError('[Askr] readable subscription cleanup threw:', err);\n }\n\n // Abort all pending operations\n try {\n if (\n instance.abortController &&\n !instance.abortController.signal.aborted\n ) {\n instance.abortController.abort();\n }\n } catch (err) {\n recordCleanupError('[Askr] abort controller cleanup threw:', err);\n }\n instance.abortController = null;\n\n // Clear update callback to prevent dangling references and stale updates\n instance.lifecycleGeneration++;\n instance.evaluationGeneration++;\n instance.mountOperations = [];\n instance.commitOperations = [];\n instance.lifecycleSlots = [];\n instance.hasPendingUpdate = false;\n instance.notifyUpdate = null;\n instance._placeholder = undefined;\n\n // Mark instance as unmounted so external tracking (e.g., portal host lists)\n // can deterministically prune stale instances. Not marking this leads to\n // retained \"mounted\" flags across cleanup boundaries which breaks\n // owner selection in the portal fallback.\n instance.mounted = false;\n\n if (cleanupErrors.length > 0) {\n throw new AggregateError(\n cleanupErrors,\n `Cleanup failed for component ${instance.id}`\n );\n }\n } finally {\n currentInstance = savedInstance;\n currentPortalScope = savedPortalScope;\n }\n}\n\nexport function registerOwnedChildScope(\n instance: ComponentInstance,\n scope: OwnedChildScope\n): void {\n const scopes = (instance._ownedChildScopes ??= new Set());\n scopes.add(scope);\n}\n\nexport function unregisterOwnedChildScope(\n instance: ComponentInstance,\n scope: OwnedChildScope\n): void {\n instance._ownedChildScopes?.delete(scope);\n}\n\nfunction warnInstanceOnce(\n instance: ComponentInstance,\n key: string,\n message: string\n): void {\n if (isProductionEnvironment()) return;\n const warnings = (instance.devWarningsEmitted ??= new Set());\n if (warnings.has(key)) return;\n warnings.add(key);\n logger.warn(message);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAsFA,SAAgB,wBACd,IACA,IACA,OACA,QACmB;CACnB,MAAM,WAA8B;EAClC;EACA;EACA;EACA;EACA,gBAAgB;EAChB,aAAa,iBAAiB,eAAe,sBAAsB;EACnE,SAAS;EACT,iBAAiB;EACjB,aAAa,CAAC;EACd,sBAAsB;EACtB,cAAc;EAEd,mBAAmB;EACnB,iBAAiB;EACjB,aAAa;EACb,iBAAiB;EACjB,sBAAsB,CAAC;EACvB,qBAAqB;EACrB,iBAAiB,CAAC;EAClB,kBAAkB,CAAC;EACnB,YAAY,CAAC;EACb,gBAAgB,CAAC;EACjB,qBAAqB;EACrB,kBAAkB;EAClB,YAAY;EACZ,KAAK;EACL,eAAe;EACf,QAAQ;EAGR,qBAAqB;EACrB,iBAAiB;EACjB,qBAAqB;EACrB,kBAAkB;EAClB,oBAAoB;CACtB;CAGA,SAAS,wBAAwB;EAE/B,SAAS,mBAAmB;EAC5B,IAAI,SAAS,iBAAiB,MAC5B;EAGF,aAAa,QAAQ;CACvB;CAEA,SAAS,oBAAoB;EAC3B,IAAI,CAAC,SAAS,kBAAkB;GAC9B,SAAS,mBAAmB;GAE5B,gBAAgB,QAAQ,SAAS,eAAgB;EACnD;CACF;CAIA,SAAS,oBAAoB,SAAS;CAEtC,OAAO;AACT;AAEA,IAAI,kBAA4C;AAChD,IAAI,qBAAoC;AACxC,IAAI,aAAa;AAOjB,SAAS,sBAAsB,UAA8C;CAC3E,IAAI,aAAa,SAAS;CAC1B,IA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;IACF,MAAM,QAAQ;GAChB,SAAS,KAAK;IACZ,mBAAmB,qCAAqC,GAAG;GAC7D;EAEJ;EAGA,MAAM,aAAa,SAAS;EAC5B,SAAS,aAAa,CAAC;EACvB,KAAK,MAAM,WAAW,YACpB,IAAI;GACF,QAAQ;EACV,SAAS,KAAK;GACZ,mBAAmB,kCAAkC,GAAG;EAC1D;EAIF,IAAI;GACF,6BAA6B,QAAQ;EACvC,SAAS,KAAK;GACZ,mBAAmB,+CAA+C,GAAG;EACvE;EAGA,IAAI;GACF,IACE,SAAS,mBACT,CAAC,SAAS,gBAAgB,OAAO,SAEjC,SAAS,gBAAgB,MAAM;EAEnC,SAAS,KAAK;GACZ,mBAAmB,0CAA0C,GAAG;EAClE;EACA,SAAS,kBAAkB;EAG3B,SAAS;EACT,SAAS;EACT,SAAS,kBAAkB,CAAC;EAC5B,SAAS,mBAAmB,CAAC;EAC7B,SAAS,iBAAiB,CAAC;EAC3B,SAAS,mBAAmB;EAC5B,SAAS,eAAe;EACxB,SAAS,eAAe;EAMxB,SAAS,UAAU;EAEnB,IAAI,cAAc,SAAS,GACzB,MAAM,IAAI,eACR,eACA,gCAAgC,SAAS,IAC3C;CAEJ,UAAU;EACR,kBAAkB;EAClB,qBAAqB;CACvB;AACF;AAEA,SAAgB,wBACd,UACA,OACM;CAEN,CADgB,SAAS,sCAAsB,IAAI,IAAI,GAChD,IAAI,KAAK;AAClB;AAEA,SAAgB,0BACd,UACA,OACM;CACN,SAAS,mBAAmB,OAAO,KAAK;AAC1C;AAEA,SAAS,iBACP,UACA,KACA,SACM;CACN,IAAI,wBAAwB,GAAG;CAC/B,MAAM,WAAY,SAAS,uCAAuB,IAAI,IAAI;CAC1D,IAAI,SAAS,IAAI,GAAG,GAAG;CACvB,SAAS,IAAI,GAAG;CAChB,OAAO,KAAK,OAAO;AACrB"}
1
+ {"version":3,"file":"component.js","names":[],"sources":["../../src/runtime/component.ts"],"sourcesContent":["/**\n * Component instance lifecycle management\n * Internal only — users never see this\n */\n\nimport { type State } from './state';\nimport { globalScheduler } from './scheduler';\nimport type { Props } from '../common/props';\nimport type { ComponentFunction } from '../common/component';\nimport {\n // withContext is the sole primitive for context restoration\n withContext,\n type ContextFrame,\n} from './context';\nimport {\n type ReadableSource,\n finalizeReadableSubscriptions,\n finalizeReadableSubscriptionsFromSnapshot,\n cleanupReadableSubscriptions,\n} from './readable';\nimport {\n isDevelopmentEnvironment,\n isProductionEnvironment,\n} from '../common/env';\nimport { logger } from '../dev/logger';\nimport { incDevCounter, setDevValue } from './dev-namespace';\nimport { isPromiseLike } from '../common/promise';\n\nexport type { ComponentFunction } from '../common/component';\n\nexport interface ComponentInstance {\n id: string;\n fn: ComponentFunction;\n props: Props;\n target: Element | null;\n parentInstance: ComponentInstance | null;\n portalScope: object | null;\n mounted: boolean;\n abortController: AbortController | null; // Lazily created per-component abort lifecycle\n ssr?: boolean; // Set to true for SSR temporary instances\n // Opt-in strict cleanup mode: when true cleanup errors are aggregated and re-thrown\n cleanupStrict?: boolean;\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 render-scoped hook indices (frozen after first render)\n firstRenderComplete: boolean; // Flag to detect transition from first to subsequent renders\n mountOperations: Array<\n () => void | (() => void) | PromiseLike<void | (() => void)>\n >; // Operations to run when component mounts\n commitOperations: Array<\n () => void | (() => void) | PromiseLike<void | (() => void)>\n >; // Operations to run after a successful committed render\n cleanupFns: Array<() => void>; // Cleanup functions to run on unmount\n lifecycleSlots: unknown[]; // Render-scoped lifecycle primitive storage\n lifecycleGeneration: number; // Invalidates async mount-operation settlement after disposal\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 _pendingReadSources?: Set<ReadableSource<unknown>>; // Readables read during the in-progress render\n _pendingReadSourceVersions?: Map<ReadableSource<unknown>, number>; // Source versions captured during the in-progress render\n _lastReadSources?: Set<ReadableSource<unknown>>; // Readables read during the last committed render\n devWarningsEmitted?: Set<string>; // Dev-only warning dedupe for this instance\n\n // Placeholder for null-returning components. When a component initially returns\n // null, we create a comment placeholder so updates can replace it with content.\n _placeholder?: Comment;\n _ownedChildScopes?: Set<{\n key: string | number;\n dispose(): void;\n }>;\n errorBoundaryState?: {\n error: unknown | null;\n resetKey: unknown;\n notified: boolean;\n };\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 parentInstance: currentInstance,\n portalScope: currentInstance?.portalScope ?? currentPortalScope ?? null,\n mounted: false,\n abortController: null,\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 commitOperations: [],\n cleanupFns: [],\n lifecycleSlots: [],\n lifecycleGeneration: 0,\n hasPendingUpdate: false,\n ownerFrame: null, // Will be set by renderer when vnode is marked\n ssr: false,\n cleanupStrict: false,\n isRoot: false,\n\n // Render-tracking (for precise state subscriptions)\n _currentRenderToken: undefined,\n lastRenderToken: 0,\n _pendingReadSources: undefined,\n _pendingReadSourceVersions: undefined,\n _lastReadSources: undefined,\n devWarningsEmitted: undefined,\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 if (instance.notifyUpdate === null) {\n return;\n }\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 // Default state-driven updates enqueue the run task directly. Specialized\n // runtimes (for example `For` item instances) can still override this hook.\n instance._pendingFlushTask = instance._pendingRunTask;\n\n return instance;\n}\n\nlet currentInstance: ComponentInstance | null = null;\nlet currentPortalScope: object | null = null;\nlet stateIndex = 0;\n\ntype OwnedChildScope = {\n key: string | number;\n dispose(): void;\n};\n\nfunction ensureAbortController(instance: ComponentInstance): AbortController {\n let controller = instance.abortController;\n if (!controller || controller.signal.aborted) {\n controller = new AbortController();\n instance.abortController = controller;\n }\n return controller;\n}\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 currentPortalScope = instance?.portalScope ?? null;\n}\n\nexport function getCurrentPortalScope(): object | null {\n return currentInstance?.portalScope ?? currentPortalScope;\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';\nimport { evaluate, cleanupInstancesUnder } from '../renderer';\n\ntype LifecycleOperation = () =>\n | void\n | (() => void)\n | PromiseLike<void | (() => void)>;\n\ntype LifecycleCommitBatchEntry = {\n instance: ComponentInstance;\n wasFirstMount: boolean;\n};\n\ntype ReadSubscriptionCommit = {\n instance: ComponentInstance;\n token: number;\n pendingReadSources: Set<ReadableSource<unknown>> | undefined;\n pendingReadSourceVersions: Map<ReadableSource<unknown>, number> | undefined;\n};\n\ntype InlineRenderSnapshot = {\n instance: ComponentInstance;\n props: Props;\n ownerFrame: ContextFrame | null;\n portalScope: object | null;\n parentInstance: ComponentInstance | null;\n isRoot: boolean | undefined;\n};\n\ntype LifecycleCommitBatch = {\n parent: LifecycleCommitBatch | null;\n entries: LifecycleCommitBatchEntry[];\n entriesByInstance: Map<ComponentInstance, LifecycleCommitBatchEntry>;\n readCommits: ReadSubscriptionCommit[];\n readCommitsByInstance: Map<ComponentInstance, ReadSubscriptionCommit>;\n renderSnapshots: InlineRenderSnapshot[];\n renderSnapshotsByInstance: Map<ComponentInstance, InlineRenderSnapshot>;\n active: boolean;\n};\n\nlet currentLifecycleCommitBatch: LifecycleCommitBatch | null = null;\n\nfunction beginLifecycleCommitBatch(): LifecycleCommitBatch {\n const batch: LifecycleCommitBatch = {\n parent: currentLifecycleCommitBatch,\n entries: [],\n entriesByInstance: new Map(),\n readCommits: [],\n readCommitsByInstance: new Map(),\n renderSnapshots: [],\n renderSnapshotsByInstance: new Map(),\n active: true,\n };\n currentLifecycleCommitBatch = batch;\n return batch;\n}\n\nfunction closeLifecycleCommitBatch(batch: LifecycleCommitBatch): boolean {\n if (!batch.active) {\n return false;\n }\n\n batch.active = false;\n currentLifecycleCommitBatch = batch.parent;\n return true;\n}\n\nfunction enqueueLifecycleCommit(\n batch: LifecycleCommitBatch,\n instance: ComponentInstance,\n wasFirstMount: boolean\n): void {\n const existing = batch.entriesByInstance.get(instance);\n if (existing) {\n existing.wasFirstMount = existing.wasFirstMount || wasFirstMount;\n return;\n }\n\n const entry = { instance, wasFirstMount };\n batch.entriesByInstance.set(instance, entry);\n batch.entries.push(entry);\n}\n\nfunction enqueueReadSubscriptionCommit(\n batch: LifecycleCommitBatch,\n instance: ComponentInstance,\n token: number,\n pendingReadSources: Set<ReadableSource<unknown>> | undefined,\n pendingReadSourceVersions: Map<ReadableSource<unknown>, number> | undefined\n): void {\n const existing = batch.readCommitsByInstance.get(instance);\n const commit = existing ?? {\n instance,\n token,\n pendingReadSources,\n pendingReadSourceVersions,\n };\n\n commit.token = token;\n commit.pendingReadSources = pendingReadSources\n ? new Set(pendingReadSources)\n : undefined;\n commit.pendingReadSourceVersions = pendingReadSourceVersions\n ? new Map(pendingReadSourceVersions)\n : undefined;\n\n if (!existing) {\n batch.readCommitsByInstance.set(instance, commit);\n batch.readCommits.push(commit);\n }\n}\n\nfunction enqueueInlineRenderSnapshot(\n batch: LifecycleCommitBatch,\n snapshot: InlineRenderSnapshot\n): void {\n if (batch.renderSnapshotsByInstance.has(snapshot.instance)) {\n return;\n }\n\n batch.renderSnapshotsByInstance.set(snapshot.instance, snapshot);\n batch.renderSnapshots.push(snapshot);\n}\n\nexport function captureInlineRenderSnapshot(instance: ComponentInstance): void {\n if (!currentLifecycleCommitBatch?.active) {\n return;\n }\n\n enqueueInlineRenderSnapshot(currentLifecycleCommitBatch, {\n instance,\n props: instance.props,\n ownerFrame: instance.ownerFrame,\n portalScope: instance.portalScope,\n parentInstance: instance.parentInstance,\n isRoot: instance.isRoot,\n });\n}\n\nfunction finalizeInlineReadSubscriptions(\n instance: ComponentInstance,\n token: number,\n pendingReadSources: Set<ReadableSource<unknown>> | undefined,\n pendingReadSourceVersions: Map<ReadableSource<unknown>, number> | undefined\n): void {\n if (currentLifecycleCommitBatch?.active) {\n enqueueReadSubscriptionCommit(\n currentLifecycleCommitBatch,\n instance,\n token,\n pendingReadSources,\n pendingReadSourceVersions\n );\n return;\n }\n\n finalizeReadableSubscriptionsFromSnapshot(\n instance,\n token,\n pendingReadSources,\n pendingReadSourceVersions\n );\n}\n\nfunction flushLifecycleCommitBatch(batch: LifecycleCommitBatch): void {\n if (!closeLifecycleCommitBatch(batch)) {\n return;\n }\n\n if (batch.parent?.active) {\n for (const snapshot of batch.renderSnapshots) {\n enqueueInlineRenderSnapshot(batch.parent, snapshot);\n }\n for (const commit of batch.readCommits) {\n enqueueReadSubscriptionCommit(\n batch.parent,\n commit.instance,\n commit.token,\n commit.pendingReadSources,\n commit.pendingReadSourceVersions\n );\n }\n for (const entry of batch.entries) {\n enqueueLifecycleCommit(batch.parent, entry.instance, entry.wasFirstMount);\n }\n return;\n }\n\n for (const commit of batch.readCommits) {\n finalizeReadableSubscriptionsFromSnapshot(\n commit.instance,\n commit.token,\n commit.pendingReadSources,\n commit.pendingReadSourceVersions\n );\n }\n\n for (const entry of batch.entries) {\n executeCommittedLifecycleOperations(entry.instance, entry.wasFirstMount);\n }\n}\n\nfunction discardLifecycleCommitBatch(batch: LifecycleCommitBatch): void {\n if (!closeLifecycleCommitBatch(batch)) {\n return;\n }\n\n for (let index = batch.renderSnapshots.length - 1; index >= 0; index -= 1) {\n const snapshot = batch.renderSnapshots[index]!;\n snapshot.instance.props = snapshot.props;\n snapshot.instance.ownerFrame = snapshot.ownerFrame;\n snapshot.instance.portalScope = snapshot.portalScope;\n snapshot.instance.parentInstance = snapshot.parentInstance;\n snapshot.instance.isRoot = snapshot.isRoot;\n }\n\n for (const entry of batch.entries) {\n if (entry.wasFirstMount) {\n entry.instance.mountOperations = [];\n }\n discardCommitOperations(entry.instance);\n }\n}\n\nexport function registerMountOperation(operation: LifecycleOperation): 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 (isDevelopmentEnvironment()) {\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\nexport function registerCommitOperation(operation: LifecycleOperation): void {\n const instance = getCurrentComponentInstance();\n if (instance) {\n if (isBulkCommitActive()) {\n if (isDevelopmentEnvironment()) {\n throw new Error(\n 'registerCommitOperation called during bulk commit fast-lane'\n );\n }\n return;\n }\n instance.commitOperations.push(operation);\n }\n}\n\nfunction settleLifecycleOperationResult(\n instance: ComponentInstance,\n lifecycleGeneration: number,\n result: void | (() => void) | PromiseLike<void | (() => void)>\n): void {\n if (isPromiseLike(result)) {\n Promise.resolve(result).then(\n (cleanup) => {\n if (typeof cleanup === 'function') {\n if (\n instance.lifecycleGeneration === lifecycleGeneration &&\n instance.mounted\n ) {\n instance.cleanupFns.push(cleanup);\n return;\n }\n\n try {\n cleanup();\n } catch (err) {\n logger.error('[Askr] async mount cleanup failed:', err);\n }\n }\n },\n (err) => {\n logger.error('[Askr] async mount operation failed:', err);\n }\n );\n } else if (typeof result === 'function') {\n instance.cleanupFns.push(result);\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 const mountOperations = instance.mountOperations;\n if (mountOperations.length === 0) {\n return;\n }\n\n const lifecycleGeneration = instance.lifecycleGeneration;\n\n for (const operation of mountOperations) {\n settleLifecycleOperationResult(instance, lifecycleGeneration, operation());\n }\n // Clear the operations array so they don't run again on subsequent renders\n instance.mountOperations = [];\n}\n\nfunction executeCommitOperations(instance: ComponentInstance): void {\n const commitOperations = instance.commitOperations;\n if (commitOperations.length === 0) {\n return;\n }\n\n instance.commitOperations = [];\n const lifecycleGeneration = instance.lifecycleGeneration;\n\n for (const operation of commitOperations) {\n settleLifecycleOperationResult(instance, lifecycleGeneration, operation());\n }\n}\n\nfunction discardCommitOperations(instance: ComponentInstance): void {\n instance.commitOperations = [];\n}\n\nfunction executeCommittedLifecycleOperations(\n instance: ComponentInstance,\n wasFirstMount: boolean\n): void {\n if (wasFirstMount && instance.mountOperations.length > 0) {\n executeMountOperations(instance);\n }\n if (instance.commitOperations.length > 0) {\n executeCommitOperations(instance);\n }\n}\n\nfunction commitLifecycleForInstance(\n instance: ComponentInstance,\n wasFirstMount: boolean\n): void {\n if (currentLifecycleCommitBatch) {\n enqueueLifecycleCommit(\n currentLifecycleCommitBatch,\n instance,\n wasFirstMount\n );\n return;\n }\n\n executeCommittedLifecycleOperations(instance, wasFirstMount);\n}\n\nexport function commitRenderedComponent(instance: ComponentInstance): void {\n if (instance.mounted && instance.commitOperations.length > 0) {\n commitLifecycleForInstance(instance, false);\n }\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 const host = target as Element & {\n __ASKR_INSTANCE?: ComponentInstance;\n __ASKR_INSTANCES?: ComponentInstance[];\n };\n const instances = host.__ASKR_INSTANCES ?? [];\n const nextInstances = instances.filter((entry) => entry !== instance);\n nextInstances.push(instance);\n host.__ASKR_INSTANCES = nextInstances;\n host.__ASKR_INSTANCE = nextInstances[0] ?? instance;\n }\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 commitLifecycleForInstance(instance, wasFirstMount);\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 resetRenderState(instance: ComponentInstance): void {\n instance.stateIndexCheck = -1;\n\n for (const state of instance.stateValues) {\n if (state) {\n state._hasBeenRead = false;\n }\n }\n\n instance._pendingReadSources = undefined;\n instance._pendingReadSourceVersions = undefined;\n}\n\nfunction nextRenderToken(): number {\n return ++_globalRenderCounter;\n}\n\nexport function renderScopedComponent<T>(\n instance: ComponentInstance,\n startStateIndex: number,\n render: () => T\n): T {\n const savedInstance = currentInstance;\n const savedPortalScope = currentPortalScope;\n const savedStateIndex = stateIndex;\n\n instance.notifyUpdate = instance._enqueueRun!;\n resetRenderState(instance);\n instance._currentRenderToken = nextRenderToken();\n\n currentInstance = instance;\n currentPortalScope = instance.portalScope ?? savedPortalScope;\n stateIndex = startStateIndex;\n\n let didComplete = false;\n\n try {\n const executionFrame: ContextFrame = {\n parent: instance.ownerFrame,\n values: null,\n };\n const result = withContext(executionFrame, render);\n didComplete = true;\n return result;\n } finally {\n if (!didComplete) {\n instance._pendingReadSources = undefined;\n instance._pendingReadSourceVersions = undefined;\n instance._currentRenderToken = undefined;\n }\n currentInstance = savedInstance;\n currentPortalScope = savedPortalScope;\n stateIndex = savedStateIndex;\n }\n}\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 = nextRenderToken();\n instance._pendingReadSources = undefined;\n const domSnapshot = instance.target ? instance.target.innerHTML : '';\n\n let result: unknown | Promise<unknown>;\n try {\n result = executeComponentSync(instance);\n } catch (err) {\n discardCommitOperations(instance);\n throw err;\n }\n if (isPromiseLike(result)) {\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 {\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) {\n warnUnusedStateReads(instance);\n return;\n }\n } catch (err) {\n // If invariant check failed in dev, surface the error; otherwise fall back\n if (isDevelopmentEnvironment()) throw err;\n }\n\n // Fallback: enqueue the render/commit normally\n globalScheduler.enqueue(() => {\n // Handle placeholder-based updates: when a component initially returned null,\n // we created a comment placeholder. If it now has content, we need to create\n // a host element and replace the placeholder.\n if (!instance.target && instance._placeholder) {\n // Component previously returned null (has placeholder), check if now has content\n if (result === null || result === undefined) {\n // Still null - nothing to do, keep placeholder\n finalizeReadSubscriptions(instance);\n warnUnusedStateReads(instance);\n commitRenderedComponent(instance);\n return;\n }\n\n // Has content now - need to create DOM and replace placeholder\n const placeholder = instance._placeholder;\n const parent = placeholder.parentNode;\n if (!parent) {\n // Placeholder was removed from DOM - can't render\n logger.warn(\n '[Askr] placeholder no longer in DOM, cannot render component'\n );\n return;\n }\n\n // Create a new host element for the content\n const host = document.createElement('div');\n const executionFrame: ContextFrame = {\n parent: instance.ownerFrame,\n values: null,\n };\n\n // Set up instance for normal updates\n const oldInstance = currentInstance;\n currentInstance = instance;\n const lifecycleBatch = beginLifecycleCommitBatch();\n try {\n try {\n withContext(executionFrame, () => {\n evaluate(result, host);\n });\n\n // Replace placeholder with host\n parent.replaceChild(host, placeholder);\n } catch (err) {\n discardLifecycleCommitBatch(lifecycleBatch);\n throw err;\n }\n\n // Set up instance for future updates\n instance.target = host;\n instance._placeholder = undefined;\n (\n host as Element & { __ASKR_INSTANCE?: ComponentInstance }\n ).__ASKR_INSTANCE = instance;\n\n flushLifecycleCommitBatch(lifecycleBatch);\n finalizeReadSubscriptions(instance);\n warnUnusedStateReads(instance);\n commitRenderedComponent(instance);\n } finally {\n currentInstance = oldInstance;\n }\n return;\n }\n\n if (instance.target) {\n let oldChildren: Node[] = [];\n let restoredOldChildren = false;\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 const executionFrame: ContextFrame = {\n parent: instance.ownerFrame,\n values: null,\n };\n // Capture snapshot of current children (by reference) so we can\n // restore them on render failure without losing event listeners or\n // instance attachments.\n oldChildren = Array.from(instance.target.childNodes);\n\n const lifecycleBatch = beginLifecycleCommitBatch();\n try {\n try {\n withContext(executionFrame, () => {\n evaluate(result, instance.target, undefined, instance);\n });\n } catch (e) {\n discardLifecycleCommitBatch(lifecycleBatch);\n throw e;\n }\n } catch (e) {\n // If evaluation failed, attempt to cleanup any partially-added nodes\n // and restore the old children to preserve listeners and instances.\n try {\n const newChildren = Array.from(instance.target.childNodes);\n const preservedChildren = new Set(oldChildren);\n for (const n of newChildren) {\n if (preservedChildren.has(n)) {\n continue;\n }\n try {\n cleanupInstancesUnder(n);\n } catch (err) {\n logger.warn(\n '[Askr] error cleaning up failed commit children:',\n err\n );\n }\n }\n } catch (_err) {\n void _err;\n }\n\n // Restore original children by re-inserting the old node references\n // this preserves attached listeners and instance backrefs.\n try {\n incDevCounter('__DOM_REPLACE_COUNT');\n setDevValue(\n '__LAST_DOM_REPLACE_STACK_COMPONENT_RESTORE',\n new Error().stack\n );\n } catch (e) {\n void e;\n }\n instance.target.replaceChildren(...oldChildren);\n restoredOldChildren = true;\n throw e;\n } finally {\n currentInstance = oldInstance;\n }\n\n flushLifecycleCommitBatch(lifecycleBatch);\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 warnUnusedStateReads(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 executeCommittedLifecycleOperations(instance, wasFirstMount);\n } catch (renderError) {\n discardCommitOperations(instance);\n // Atomic rendering: rollback on render error. Attempt non-lossy restore of\n // original child node references to preserve listeners/instances.\n try {\n const currentChildren = Array.from(instance.target.childNodes);\n const preservedChildren = restoredOldChildren\n ? new Set(oldChildren)\n : null;\n for (const n of currentChildren) {\n if (preservedChildren?.has(n)) {\n continue;\n }\n try {\n cleanupInstancesUnder(n);\n } catch (err) {\n logger.warn(\n '[Askr] error cleaning up partial children during rollback:',\n err\n );\n }\n }\n } catch (_err) {\n void _err;\n }\n\n try {\n incDevCounter('__DOM_REPLACE_COUNT');\n setDevValue(\n '__LAST_DOM_REPLACE_STACK_COMPONENT_ROLLBACK',\n new Error().stack\n );\n instance.target.replaceChildren(...oldChildren);\n } catch {\n // Fallback to innerHTML restore if replaceChildren fails for some reason.\n instance.target.innerHTML = domSnapshot;\n }\n\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 // Reused inline instances can cross renderer cleanup boundaries while their\n // host node is retained. Make sure state writes still enqueue this instance.\n instance.notifyUpdate = instance._enqueueRun!;\n\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 const prevToken = instance._currentRenderToken;\n const prevPendingReads = instance._pendingReadSources;\n const prevPendingReadVersions = instance._pendingReadSourceVersions;\n const savedInstance = currentInstance;\n const savedPortalScope = currentPortalScope;\n\n if (!hadToken) {\n instance._currentRenderToken = nextRenderToken();\n instance._pendingReadSources = undefined;\n instance._pendingReadSourceVersions = undefined;\n }\n\n try {\n const result = executeComponentSync(instance);\n // If we set the token for inline execution, finalize subscriptions now\n // unless the parent DOM commit is still provisional. Renderer commit\n // batches flush these reads only after DOM evaluation succeeds.\n if (!hadToken) {\n finalizeInlineReadSubscriptions(\n instance,\n instance._currentRenderToken!,\n instance._pendingReadSources,\n instance._pendingReadSourceVersions\n );\n }\n commitRenderedComponent(instance);\n return result;\n } finally {\n // Restore previous token/read states for nested inline render scenarios\n instance._currentRenderToken = prevToken;\n instance._pendingReadSources = prevPendingReads;\n instance._pendingReadSourceVersions = prevPendingReadVersions;\n currentInstance = savedInstance;\n currentPortalScope = savedPortalScope;\n }\n}\n\nexport function warnUnusedStateReads(instance: ComponentInstance): void {\n for (let i = 0; i < instance.stateValues.length; i++) {\n const state = instance.stateValues[i];\n const hasCommittedUsage =\n (state?._readers?.size ?? 0) > 0 ||\n ((state as { _derivedSubscribers?: Set<unknown> } | undefined)\n ?._derivedSubscribers?.size ?? 0) > 0;\n\n if (\n state &&\n !state._hasBeenRead &&\n !state._hasEverBeenRead &&\n !hasCommittedUsage\n ) {\n try {\n const name = instance.fn?.name || '<anonymous>';\n warnInstanceOnce(\n instance,\n `unused-state:${i}`,\n `[askr] Unused state variable detected in ${name} at index ${i}. State should be read during render or removed.`\n );\n } catch {\n warnInstanceOnce(\n instance,\n `unused-state:${i}`,\n `[askr] Unused state variable detected. State should be read during render or removed.`\n );\n }\n }\n }\n}\n\nfunction executeComponentSync(\n instance: ComponentInstance\n): unknown | Promise<unknown> {\n resetRenderState(instance);\n incDevCounter('componentRuns');\n incDevCounter('componentReruns');\n\n const savedPortalScope = currentPortalScope;\n currentInstance = instance;\n currentPortalScope = instance.portalScope ?? savedPortalScope;\n stateIndex = 0;\n\n let didComplete = false;\n\n try {\n // Track render time in dev mode\n const renderStartTime = isDevelopmentEnvironment() ? Date.now() : 0;\n\n // Create context object with abort signal\n const context = {\n get signal(): AbortSignal {\n return ensureAbortController(instance).signal;\n },\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\n const renderTime = Date.now() - renderStartTime;\n if (renderTime > 5) {\n warnInstanceOnce(\n instance,\n 'slow-render',\n `[askr] Slow render detected: ${renderTime}ms. Consider optimizing component performance.`\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 didComplete = true;\n return result;\n } finally {\n if (!didComplete) {\n discardCommitOperations(instance);\n }\n // Synchronous path: we did not push a fresh frame, so nothing to pop here.\n currentInstance = null;\n currentPortalScope = savedPortalScope;\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 // Lazily recreate abort controller only when signal is actually requested.\n instance.abortController = null;\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(instance._pendingRunTask!);\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 ensureAbortController(currentInstance).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 finalizeReadableSubscriptions(instance);\n}\n\nexport function getNextStateIndex(): number {\n return stateIndex++;\n}\n\nexport function claimHookIndex(\n instance: ComponentInstance,\n hookName: string\n): number {\n const index = getNextStateIndex();\n\n if (index < instance.stateIndexCheck) {\n throw new Error(\n `Hook index violation: ${hookName}() call at index ${index}, ` +\n `but previously saw index ${instance.stateIndexCheck}. ` +\n `This happens when render-scoped hooks are called conditionally (inside if/for/etc). ` +\n `Move all ${hookName}() calls to the top level of your component function, ` +\n `before any conditionals.`\n );\n }\n\n instance.stateIndexCheck = index;\n\n if (instance.firstRenderComplete) {\n if (instance.expectedStateIndices[index] !== index) {\n throw new Error(\n `Hook order violation: ${hookName}() called at index ${index}, ` +\n `but this index was not in the first render's sequence [${instance.expectedStateIndices.join(', ')}]. ` +\n `This usually means ${hookName}() is inside a conditional or loop. ` +\n `Move all render-scoped hooks to the top level of your component function.`\n );\n }\n } else {\n instance.expectedStateIndices.push(index);\n }\n\n return index;\n}\n\nexport function getCurrentStateIndex(): number {\n return stateIndex;\n}\n\nexport function resetStateIndex(): void {\n stateIndex = 0;\n}\n\nexport function setStateIndex(value: number): void {\n stateIndex = value;\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 const savedInstance = currentInstance;\n const savedPortalScope = currentPortalScope;\n currentInstance = null;\n currentPortalScope = null;\n\n try {\n const cleanupErrors: unknown[] = [];\n const recordCleanupError = (message: string, err: unknown): void => {\n if (instance.cleanupStrict) {\n cleanupErrors.push(err);\n } else if (isDevelopmentEnvironment()) {\n logger.warn(message, err);\n }\n };\n\n const ownedChildScopes = instance._ownedChildScopes;\n if (ownedChildScopes && ownedChildScopes.size > 0) {\n instance._ownedChildScopes = new Set();\n for (const scope of ownedChildScopes) {\n try {\n scope.dispose();\n } catch (err) {\n recordCleanupError('[Askr] child scope cleanup threw:', err);\n }\n }\n }\n\n // Execute cleanup functions (from mount effects)\n const cleanupFns = instance.cleanupFns;\n instance.cleanupFns = [];\n for (const cleanup of cleanupFns) {\n try {\n cleanup();\n } catch (err) {\n recordCleanupError('[Askr] cleanup function threw:', err);\n }\n }\n\n // Remove deterministic state subscriptions for this instance\n try {\n cleanupReadableSubscriptions(instance);\n } catch (err) {\n recordCleanupError('[Askr] readable subscription cleanup threw:', err);\n }\n\n // Abort all pending operations\n try {\n if (\n instance.abortController &&\n !instance.abortController.signal.aborted\n ) {\n instance.abortController.abort();\n }\n } catch (err) {\n recordCleanupError('[Askr] abort controller cleanup threw:', err);\n }\n instance.abortController = null;\n\n // Clear update callback to prevent dangling references and stale updates\n instance.lifecycleGeneration++;\n instance.evaluationGeneration++;\n instance.mountOperations = [];\n instance.commitOperations = [];\n instance.lifecycleSlots = [];\n instance.hasPendingUpdate = false;\n instance.notifyUpdate = null;\n instance._placeholder = undefined;\n\n // Mark instance as unmounted so external tracking (e.g., portal host lists)\n // can deterministically prune stale instances. Not marking this leads to\n // retained \"mounted\" flags across cleanup boundaries which breaks\n // owner selection in the portal fallback.\n instance.mounted = false;\n\n if (cleanupErrors.length > 0) {\n throw new AggregateError(\n cleanupErrors,\n `Cleanup failed for component ${instance.id}`\n );\n }\n } finally {\n currentInstance = savedInstance;\n currentPortalScope = savedPortalScope;\n }\n}\n\nexport function registerOwnedChildScope(\n instance: ComponentInstance,\n scope: OwnedChildScope\n): void {\n const scopes = (instance._ownedChildScopes ??= new Set());\n scopes.add(scope);\n}\n\nexport function unregisterOwnedChildScope(\n instance: ComponentInstance,\n scope: OwnedChildScope\n): void {\n instance._ownedChildScopes?.delete(scope);\n}\n\nfunction warnInstanceOnce(\n instance: ComponentInstance,\n key: string,\n message: string\n): void {\n if (isProductionEnvironment()) return;\n const warnings = (instance.devWarningsEmitted ??= new Set());\n if (warnings.has(key)) return;\n warnings.add(key);\n logger.warn(message);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAuFA,SAAgB,wBACd,IACA,IACA,OACA,QACmB;CACnB,MAAM,WAA8B;EAClC;EACA;EACA;EACA;EACA,gBAAgB;EAChB,aAAa,iBAAiB,eAAe,sBAAsB;EACnE,SAAS;EACT,iBAAiB;EACjB,aAAa,CAAC;EACd,sBAAsB;EACtB,cAAc;EAEd,mBAAmB;EACnB,iBAAiB;EACjB,aAAa;EACb,iBAAiB;EACjB,sBAAsB,CAAC;EACvB,qBAAqB;EACrB,iBAAiB,CAAC;EAClB,kBAAkB,CAAC;EACnB,YAAY,CAAC;EACb,gBAAgB,CAAC;EACjB,qBAAqB;EACrB,kBAAkB;EAClB,YAAY;EACZ,KAAK;EACL,eAAe;EACf,QAAQ;EAGR,qBAAqB;EACrB,iBAAiB;EACjB,qBAAqB;EACrB,4BAA4B;EAC5B,kBAAkB;EAClB,oBAAoB;CACtB;CAGA,SAAS,wBAAwB;EAE/B,SAAS,mBAAmB;EAC5B,IAAI,SAAS,iBAAiB,MAC5B;EAGF,aAAa,QAAQ;CACvB;CAEA,SAAS,oBAAoB;EAC3B,IAAI,CAAC,SAAS,kBAAkB;GAC9B,SAAS,mBAAmB;GAE5B,gBAAgB,QAAQ,SAAS,eAAgB;EACnD;CACF;CAIA,SAAS,oBAAoB,SAAS;CAEtC,OAAO;AACT;AAEA,IAAI,kBAA4C;AAChD,IAAI,qBAAoC;AACxC,IAAI,aAAa;AAOjB,SAAS,sBAAsB,UAA8C;CAC3E,IAAI,aAAa,SAAS;CAC1B,IAAI,CAAC,cAAc,WAAW,OAAO,SAAS;EAC5C,aAAa,IAAI,gBAAgB;EACjC,SAAS,kBAAkB;CAC7B;CACA,OAAO;AACT;A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AAS,IAAI,GAAG,GAAG;CACvB,SAAS,IAAI,GAAG;CAChB,OAAO,KAAK,OAAO;AACrB"}
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","names":[],"sources":["../../src/runtime/context.ts"],"sourcesContent":["/**\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 '../common/jsx';\nimport { ELEMENT_TYPE, STATIC_CHILDREN } from '../common/jsx';\nimport type { Props } from '../common/props';\nimport type { RenderableChild } from '../common/vnode';\nimport { getCurrentComponentInstance } from './component';\nimport type { ComponentInstance } from './component';\n\nexport type ContextKey = symbol;\n\ntype Renderable = RenderableChild;\ntype ContextScopeChildren = Renderable | (() => Renderable);\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: {\n value: T;\n children?: ContextScopeChildren;\n }) => 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\ntype ContextFrameCarrier = {\n [CONTEXT_FRAME_SYMBOL]?: ContextFrame;\n};\n\nconst vnodeContextFrames = new WeakMap<object, ContextFrame>();\n\nexport function getVNodeContextFrame(node: unknown): ContextFrame | undefined {\n if (typeof node !== 'object' || node === null) {\n return undefined;\n }\n\n const objectNode = node as ContextFrameCarrier;\n return vnodeContextFrames.get(node) ?? objectNode[CONTEXT_FRAME_SYMBOL];\n}\n\nexport function markVNodeWithContextFrame(\n node: unknown,\n frame: ContextFrame,\n overwrite = false\n): void {\n if (typeof node !== 'object' || node === null) {\n return;\n }\n\n if (!overwrite && getVNodeContextFrame(node)) {\n return;\n }\n\n const objectNode = node as ContextFrameCarrier;\n if (Object.prototype.hasOwnProperty.call(node, CONTEXT_FRAME_SYMBOL)) {\n try {\n objectNode[CONTEXT_FRAME_SYMBOL] = frame;\n return;\n } catch {\n // Fall through to WeakMap metadata when the symbol slot is readonly.\n }\n }\n\n if (Object.isExtensible(node)) {\n try {\n Object.defineProperty(node, CONTEXT_FRAME_SYMBOL, {\n value: frame,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n return;\n } catch {\n // Fall through to WeakMap metadata for exotic objects/proxies.\n }\n }\n\n vnodeContextFrames.set(node, frame);\n}\n\nfunction isVNodeLike(value: unknown): boolean {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n\n const objectValue = value as Record<string | symbol, unknown>;\n if (objectValue.$$typeof === ELEMENT_TYPE) {\n return true;\n }\n\n return (\n 'type' in objectValue &&\n ('props' in objectValue || 'children' in objectValue)\n );\n}\n\nfunction markContextPropValue(\n value: unknown,\n frame: ContextFrame,\n overwrite: boolean\n): void {\n if (Array.isArray(value)) {\n for (const item of value) {\n markContextPropValue(item, frame, overwrite);\n }\n return;\n }\n\n if (isVNodeLike(value)) {\n markVNodeTreeWithContextFrame(value, frame, overwrite);\n }\n}\n\nexport function markVNodeTreeWithContextFrame(\n node: unknown,\n frame: ContextFrame | null,\n overwrite = false\n): unknown {\n if (!frame) return node;\n\n if (Array.isArray(node)) {\n for (const child of node) {\n markVNodeTreeWithContextFrame(child, frame, overwrite);\n }\n return node;\n }\n\n if (typeof node !== 'object' || node === null) {\n return node;\n }\n\n markVNodeWithContextFrame(node, frame, overwrite);\n\n const objectNode = node as Record<string | symbol, unknown>;\n const props =\n typeof objectNode.props === 'object' && objectNode.props !== null\n ? (objectNode.props as Record<string, unknown>)\n : null;\n const children = (props?.children ?? objectNode.children) as unknown;\n\n if (Array.isArray(children)) {\n for (const child of children) {\n markVNodeTreeWithContextFrame(child, frame, overwrite);\n }\n } else if (children) {\n markVNodeTreeWithContextFrame(children, frame, overwrite);\n }\n\n if (props) {\n for (const key in props) {\n if (key !== 'children') {\n markContextPropValue(props[key], frame, overwrite);\n }\n }\n }\n\n return node;\n}\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: {\n value: T;\n children?: ContextScopeChildren;\n }): JSXElement => {\n const value = props.value;\n // Scope component: creates a new frame and renders children within it\n return {\n $$typeof: ELEMENT_TYPE,\n type: ContextScopeComponent,\n props: { key, value, children: props.children },\n key: null,\n } as JSXElement;\n },\n };\n}\n\nfunction preserveStaticChildrenMarker(\n source: readonly unknown[],\n target: unknown[]\n): unknown[] {\n if (\n (\n source as {\n [STATIC_CHILDREN]?: boolean;\n }\n )[STATIC_CHILDREN] === true\n ) {\n Object.defineProperty(target, STATIC_CHILDREN, {\n value: true,\n enumerable: false,\n configurable: true,\n });\n }\n\n return target;\n}\n\nfunction isPresentRenderable(\n value: Renderable | null | undefined\n): value is Renderable {\n return value !== null && value !== undefined && value !== false;\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 ContextScopeChildren;\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 // Helper: create a function-child invoker node (centralized cast)\n function createFunctionChildInvoker(\n fn: () => Renderable,\n frame: ContextFrame,\n owner: ComponentInstance | null\n ): Renderable {\n return {\n type: ContextFunctionChildInvoker,\n props: { fn, __frame: frame, __owner: owner },\n } as unknown as Renderable;\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 preserveStaticChildrenMarker(\n children,\n children.map((child) => {\n if (typeof child === 'function') {\n return createFunctionChildInvoker(\n child as () => Renderable,\n newFrame,\n getCurrentComponentInstance()\n );\n }\n return markWithFrame(child, newFrame);\n })\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 createFunctionChildInvoker(\n children as () => Renderable,\n newFrame,\n getCurrentComponentInstance()\n );\n } else if (isPresentRenderable(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 return markVNodeTreeWithContextFrame(node, frame, true) as Renderable;\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 __owner?: ComponentInstance | null;\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 (isPresentRenderable(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"],"mappings":";;;AAmDA,MAAa,uBAAuB,OAAO,uBAAuB;AAMlE,MAAM,qCAAqB,IAAI,QAA8B;AAE7D,SAAgB,qBAAqB,MAAyC;CAC5E,IAAI,OAAO,SAAS,YAAY,SAAS,MACvC;CAGF,MAAM,aAAa;CACnB,OAAO,mBAAmB,IAAI,IAAI,KAAK,WAAW;AACpD;AAEA,SAAgB,0BACd,MACA,OACA,YAAY,OACN;CACN,IAAI,OAAO,SAAS,YAAY,SAAS,MACvC;CAGF,IAAI,CAAC,aAAa,qBAAqB,IAAI,GACzC;CAGF,MAAM,aAAa;CACnB,IAAI,OAAO,UAAU,eAAe,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AM;CACpB,MAAM,WAAW,MAAM;CAGvB,MAAM,WAAW,4BAA4B;CAiB7C,MAAM,WAAyB;EAC7B,eAjB8C;GAK9C,IAAI,qBAAqB,OAAO;GAIhC,IAAI,YAAY,SAAS,YAAY,OAAO,SAAS;GAIrD,OAAO;EACT,GAGU;EACR,QAAQ,IAAI,IAAI,CAAC,CAAC,KAAK,KAAK,CAAC,CAAC;CAChC;CAGA,SAAS,2BACP,IACA,OACA,OACY;EACZ,OAAO;GACL,MAAM;GACN,OAAO;IAAE;IAAI,SAAS;IAAO,SAAS;GAAM;EAC9C;CACF;CAIA,IAAI,MAAM,QAAQ,QAAQ,GAGxB,OAAO,6BACL,UACA,SAAS,KAAK,UAAU;EACtB,IAAI,OAAO,UAAU,YACnB,OAAO,2BACL,OACA,UACA,4BAA4B,CAC9B;EAEF,OAAO,cAAc,OAAO,QAAQ;CACtC,CAAC,CACH;MACK,IAAI,OAAO,aAAa,YAM7B,OAAO,2BACL,UACA,UACA,4BAA4B,CAC9B;MACK,IAAI,oBAAoB,QAAQ,GACrC,OAAO,cAAc,UAAU,QAAQ;CAGzC,OAAO;AACT;;;;;AAMA,SAAS,cAAc,MAAkB,OAAiC;CACxE,OAAO,8BAA8B,MAAM,OAAO,IAAI;AACxD;;;;;;;;;;AAWA,SAAS,4BAA4B,OAItB;CACb,MAAM,EAAE,IAAI,YAAY;CAMxB,MAAM,MAAM,YAAY,eAAe,GAAG,CAAC;CAG3C,IAAI,oBAAoB,GAAG,GAAG,OAAO,cAAc,KAAK,OAAO;CAC/D,OAAO;AACT;;;;AA+BA,SAAgB,yBAA8C;CAC5D,OAAO;AACT"}
1
+ {"version":3,"file":"context.js","names":[],"sources":["../../src/runtime/context.ts"],"sourcesContent":["/**\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 '../common/jsx';\nimport { ELEMENT_TYPE, STATIC_CHILDREN } from '../common/jsx';\nimport type { Props } from '../common/props';\nimport type { RenderableChild } from '../common/vnode';\nimport { getCurrentComponentInstance } from './component';\nimport type { ComponentInstance } from './component';\n\nexport type ContextKey = symbol;\n\ntype Renderable = RenderableChild;\ntype ContextScopeChildren = Renderable | (() => Renderable);\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: {\n value: T;\n children?: ContextScopeChildren;\n }) => 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\ntype ContextFrameCarrier = {\n [CONTEXT_FRAME_SYMBOL]?: ContextFrame;\n};\n\nconst vnodeContextFrames = new WeakMap<object, ContextFrame>();\n\nexport function getVNodeContextFrame(node: unknown): ContextFrame | undefined {\n if (typeof node !== 'object' || node === null) {\n return undefined;\n }\n\n const objectNode = node as ContextFrameCarrier;\n return vnodeContextFrames.get(node) ?? objectNode[CONTEXT_FRAME_SYMBOL];\n}\n\nexport function markVNodeWithContextFrame(\n node: unknown,\n frame: ContextFrame,\n overwrite = false\n): void {\n if (typeof node !== 'object' || node === null) {\n return;\n }\n\n if (!overwrite && getVNodeContextFrame(node)) {\n return;\n }\n\n const objectNode = node as ContextFrameCarrier;\n if (Object.prototype.hasOwnProperty.call(node, CONTEXT_FRAME_SYMBOL)) {\n try {\n objectNode[CONTEXT_FRAME_SYMBOL] = frame;\n return;\n } catch {\n // Fall through to WeakMap metadata when the symbol slot is readonly.\n }\n }\n\n if (Object.isExtensible(node)) {\n try {\n Object.defineProperty(node, CONTEXT_FRAME_SYMBOL, {\n value: frame,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n return;\n } catch {\n // Fall through to WeakMap metadata for exotic objects/proxies.\n }\n }\n\n vnodeContextFrames.set(node, frame);\n}\n\nfunction isVNodeLike(value: unknown): boolean {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n\n const objectValue = value as Record<string | symbol, unknown>;\n if (objectValue.$$typeof === ELEMENT_TYPE) {\n return true;\n }\n\n return (\n 'type' in objectValue &&\n ('props' in objectValue || 'children' in objectValue)\n );\n}\n\nfunction markContextPropValue(\n value: unknown,\n frame: ContextFrame,\n overwrite: boolean\n): void {\n if (Array.isArray(value)) {\n for (const item of value) {\n markContextPropValue(item, frame, overwrite);\n }\n return;\n }\n\n if (isVNodeLike(value)) {\n markVNodeTreeWithContextFrame(value, frame, overwrite);\n }\n}\n\nexport function markVNodeTreeWithContextFrame(\n node: unknown,\n frame: ContextFrame | null,\n overwrite = false\n): unknown {\n if (!frame) return node;\n\n if (Array.isArray(node)) {\n for (const child of node) {\n markVNodeTreeWithContextFrame(child, frame, overwrite);\n }\n return node;\n }\n\n if (typeof node !== 'object' || node === null) {\n return node;\n }\n\n markVNodeWithContextFrame(node, frame, overwrite);\n\n const objectNode = node as Record<string | symbol, unknown>;\n const props =\n typeof objectNode.props === 'object' && objectNode.props !== null\n ? (objectNode.props as Record<string, unknown>)\n : null;\n const children = (props?.children ?? objectNode.children) as unknown;\n\n if (Array.isArray(children)) {\n for (const child of children) {\n markVNodeTreeWithContextFrame(child, frame, overwrite);\n }\n } else if (children) {\n markVNodeTreeWithContextFrame(children, frame, overwrite);\n }\n\n if (props) {\n for (const key in props) {\n if (key !== 'children') {\n markContextPropValue(props[key], frame, overwrite);\n }\n }\n }\n\n return node;\n}\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: {\n value: T;\n children?: ContextScopeChildren;\n }): JSXElement => {\n const value = props.value;\n // Scope component: creates a new frame and renders children within it\n return {\n $$typeof: ELEMENT_TYPE,\n type: ContextScopeComponent,\n props: { key, value, children: props.children },\n key: null,\n } as JSXElement;\n },\n };\n}\n\nfunction preserveStaticChildrenMarker(\n source: readonly unknown[],\n target: unknown[]\n): unknown[] {\n if (\n (\n source as {\n [STATIC_CHILDREN]?: boolean;\n }\n )[STATIC_CHILDREN] === true\n ) {\n Object.defineProperty(target, STATIC_CHILDREN, {\n value: true,\n enumerable: false,\n configurable: true,\n });\n }\n\n return target;\n}\n\nfunction isPresentRenderable(\n value: Renderable | null | undefined\n): value is Renderable {\n return value !== null && value !== undefined && value !== false;\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 ContextScopeChildren;\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 // Helper: create a function-child invoker node (centralized cast)\n function createFunctionChildInvoker(\n fn: () => Renderable,\n frame: ContextFrame,\n owner: ComponentInstance | null\n ): Renderable {\n return {\n type: ContextFunctionChildInvoker,\n props: { fn, __frame: frame, __owner: owner },\n } as unknown as Renderable;\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 preserveStaticChildrenMarker(\n children,\n children.map((child) => {\n if (typeof child === 'function') {\n return createFunctionChildInvoker(\n child as () => Renderable,\n newFrame,\n getCurrentComponentInstance()\n );\n }\n return markWithFrame(child, newFrame);\n })\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 createFunctionChildInvoker(\n children as () => Renderable,\n newFrame,\n getCurrentComponentInstance()\n );\n } else if (isPresentRenderable(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 return markVNodeTreeWithContextFrame(node, frame, true) as Renderable;\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 __owner?: ComponentInstance | null;\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 (isPresentRenderable(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"],"mappings":";;;AAmDA,MAAa,uBAAuB,OAAO,uBAAuB;AAMlE,MAAM,qCAAqB,IAAI,QAA8B;AAE7D,SAAgB,qBAAqB,MAAyC;CAC5E,IAAI,OAAO,SAAS,YAAY,SAAS,MACvC;CAGF,MAAM,aAAa;CACnB,OAAO,mBAAmB,IAAI,IAAI,KAAK,WAAW;AACpD;AAEA,SAAgB,0BACd,MACA,OACA,YAAY,OACN;CACN,IAAI,OAAO,SAAS,YAAY,SAAS,MACvC;CAGF,IAAI,CAAC,aAAa,qBAAqB,IAAI,GACzC;CAGF,MAAM,aAAa;CACnB,IAAI,OAAO,UAAU,eAAe,KAAK,MAAM,oBAAoB,GACjE,IAAI;EACF,WAAW,wBAAwB;EACnC;CACF,QAAQ,CAER;CAGF,IAAI,OAAO,aAAa,IAAI,GAC1B,IAAI;EACF,OAAO,eAAe,MAAM,sBAAsB;GAChD,OAAO;GACP,UAAU;GACV,YAAY;GACZ,cAAc;EAChB,CAAC;EACD;CACF,QAAQ,CAER;CAGF,mBAAmB,IAAI,MAAM,KAAK;AACpC;AAEA,SAAS,YAAY,OAAyB;CAC5C,IAAI,OAA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MAAM;GACN,OAAO;IAAE;IAAI,SAAS;IAAO,SAAS;GAAM;EAC9C;CACF;CAIA,IAAI,MAAM,QAAQ,QAAQ,GAGxB,OAAO,6BACL,UACA,SAAS,KAAK,UAAU;EACtB,IAAI,OAAO,UAAU,YACnB,OAAO,2BACL,OACA,UACA,4BAA4B,CAC9B;EAEF,OAAO,cAAc,OAAO,QAAQ;CACtC,CAAC,CACH;MACK,IAAI,OAAO,aAAa,YAM7B,OAAO,2BACL,UACA,UACA,4BAA4B,CAC9B;MACK,IAAI,oBAAoB,QAAQ,GACrC,OAAO,cAAc,UAAU,QAAQ;CAGzC,OAAO;AACT;;;;;AAMA,SAAS,cAAc,MAAkB,OAAiC;CACxE,OAAO,8BAA8B,MAAM,OAAO,IAAI;AACxD;;;;;;;;;;AAWA,SAAS,4BAA4B,OAItB;CACb,MAAM,EAAE,IAAI,YAAY;CAMxB,MAAM,MAAM,YAAY,eAAe,GAAG,CAAC;CAG3C,IAAI,oBAAoB,GAAG,GAAG,OAAO,cAAc,KAAK,OAAO;CAC/D,OAAO;AACT;;;;AA+BA,SAAgB,yBAA8C;CAC5D,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"derive.js","names":[],"sources":["../../src/runtime/derive.ts"],"sourcesContent":["import {\n claimHookIndex,\n getCurrentInstance,\n type ComponentInstance,\n} from './component';\nimport { globalScheduler } from './scheduler';\nimport {\n clearDerivedDependencySubscriptions,\n markReadableDerivedSubscribersDirty,\n markReactivePropsDirtySource,\n notifyReadableReaders,\n recordReadableRead,\n syncDerivedDependencySubscriptions,\n type DerivedSubscriber,\n type ReadableSource,\n withDerivedReadTracking,\n} from './readable';\nimport { isSnapshotSource, type SnapshotSourceBrand } from './snapshot-source';\n\nexport interface Derived<T> extends ReadableSource<T> {\n (): T;\n}\n\ninterface DerivedCell<T> extends Derived<T>, DerivedSubscriber {\n _owner: ComponentInstance;\n _hookIndex: number;\n _compute: () => T;\n _value: T;\n _hasValue: boolean;\n _dirty: boolean;\n _scheduled: boolean;\n _evaluating: boolean;\n _lastRecomputeFlushVersion: number;\n _sources: Set<ReadableSource<unknown>>;\n _pendingDependencySources?: Set<ReadableSource<unknown>>;\n _cleanup(): void;\n}\n\ntype SnapshotSource<T> = {\n value: T | null;\n pending?: boolean;\n error?: Error | null;\n} & SnapshotSourceBrand;\n\nconst deriveCells = new WeakMap<\n ComponentInstance,\n Map<number, DerivedCell<unknown>>\n>();\nconst dirtyDerivedCells = new Set<DerivedCell<unknown>>();\nlet hasPendingDerivedFlush = false;\n\nfunction getDeriveStore(\n instance: ComponentInstance\n): Map<number, DerivedCell<unknown>> {\n let store = deriveCells.get(instance);\n if (!store) {\n store = new Map();\n deriveCells.set(instance, store);\n }\n return store;\n}\n\nfunction markDerivedCellDirty(cell: DerivedCell<unknown>): void {\n cell._dirty = true;\n if (cell._scheduled) {\n return;\n }\n\n cell._scheduled = true;\n dirtyDerivedCells.add(cell);\n\n if (!hasPendingDerivedFlush) {\n hasPendingDerivedFlush = true;\n globalScheduler.enqueueInLane('derived', flushDirtyDerivedCells);\n }\n}\n\nfunction flushDirtyDerivedCells(): void {\n hasPendingDerivedFlush = false;\n\n if (dirtyDerivedCells.size === 0) {\n return;\n }\n\n const pending = dirtyDerivedCells.values();\n let next = pending.next();\n\n while (!next.done) {\n const cell = next.value as DerivedCell<unknown>;\n dirtyDerivedCells.delete(cell);\n cell._scheduled = false;\n if (!cell._dirty) {\n next = pending.next();\n continue;\n }\n recomputeDerivedCell(cell, true);\n next = pending.next();\n }\n}\n\nfunction recomputeDerivedCell<T>(\n cell: DerivedCell<T>,\n notifyDownstream: boolean\n): T {\n if (!cell._dirty && cell._hasValue) {\n return cell._value;\n }\n\n if (cell._evaluating) {\n throw new Error('derive() cannot read itself recursively');\n }\n\n cell._evaluating = true;\n cell._dirty = false;\n cell._pendingDependencySources = new Set();\n\n const prevSources = cell._sources;\n let nextValue: T;\n\n try {\n nextValue = withDerivedReadTracking(cell, cell._compute);\n } catch (error) {\n cell._dirty = true;\n cell._pendingDependencySources = undefined;\n throw error;\n } finally {\n cell._evaluating = false;\n }\n\n const nextSources = cell._pendingDependencySources ?? new Set();\n cell._pendingDependencySources = undefined;\n syncDerivedDependencySubscriptions(cell, prevSources, nextSources);\n cell._sources = nextSources;\n\n const valueChanged = !cell._hasValue || !Object.is(cell._value, nextValue);\n cell._hasValue = true;\n cell._value = nextValue;\n cell._lastRecomputeFlushVersion = globalScheduler.getFlushVersion();\n\n if (valueChanged && notifyDownstream) {\n markReadableDerivedSubscribersDirty(cell);\n markReactivePropsDirtySource(cell);\n notifyReadableReaders(cell);\n }\n\n return cell._value;\n}\n\nfunction createDerivedCell<T>(\n instance: ComponentInstance,\n hookIndex: number,\n compute: () => T\n): DerivedCell<T> {\n const cell = function derivedGetter(): T {\n recordReadableRead(cell as DerivedCell<T>);\n return recomputeDerivedCell(\n cell as DerivedCell<T>,\n (cell as DerivedCell<T>)._scheduled\n );\n } as DerivedCell<T>;\n\n cell._owner = instance;\n cell._hookIndex = hookIndex;\n cell._compute = compute;\n cell._value = undefined as T;\n cell._hasValue = false;\n cell._dirty = true;\n cell._scheduled = false;\n cell._evaluating = false;\n cell._lastRecomputeFlushVersion = -1;\n cell._sources = new Set();\n cell._markDirty = () => {\n markDerivedCellDirty(cell);\n };\n cell._cleanup = () => {\n cell._scheduled = false;\n cell._dirty = false;\n cell._hasValue = false;\n dirtyDerivedCells.delete(cell);\n clearDerivedDependencySubscriptions(cell, cell._sources);\n cell._derivedSubscribers?.clear();\n cell._readers?.clear();\n };\n\n (instance.cleanupFns ??= []).push(() => {\n cell._cleanup();\n deriveCells.get(instance)?.delete(hookIndex);\n });\n\n return cell;\n}\n\nfunction getOrCreateDerivedCell<T>(\n instance: ComponentInstance,\n hookIndex: number,\n compute: () => T\n): DerivedCell<T> {\n const store = getDeriveStore(instance);\n const existing = store.get(hookIndex) as DerivedCell<T> | undefined;\n if (existing) {\n existing._compute = compute;\n if (\n existing._lastRecomputeFlushVersion !== globalScheduler.getFlushVersion()\n ) {\n existing._dirty = true;\n }\n return existing;\n }\n\n const created = createDerivedCell(instance, hookIndex, compute);\n store.set(hookIndex, created as DerivedCell<unknown>);\n return created;\n}\n\nfunction createMappedSelector<TIn, TOut>(\n source: SnapshotSource<TIn> | TIn | (() => TIn),\n map: (value: TIn) => TOut\n): () => TOut | null {\n return () => {\n let value: TIn;\n if (typeof source === 'function') {\n value = (source as () => TIn)();\n } else if (isSnapshotSource(source)) {\n value = (source as SnapshotSource<TIn>).value ?? (source as TIn);\n } else {\n value = source as TIn;\n }\n\n if (value == null) {\n return null;\n }\n\n return map(value);\n };\n}\n\nexport function derive<TOut>(fn: () => TOut): Derived<TOut>;\n\nexport function derive<TIn, TOut>(\n source: SnapshotSource<TIn> | TIn | (() => TIn),\n map: (value: TIn) => TOut\n): Derived<TOut | null>;\n\nexport function derive<TIn, TOut>(\n source: SnapshotSource<TIn> | TIn | (() => TIn),\n map?: (value: TIn) => TOut\n): Derived<TOut | null> | Derived<TIn> {\n const instance = getCurrentInstance();\n if (!instance) {\n throw new Error(\n 'derive() can only be called during component render execution. ' +\n 'Move derive() calls to the top level of your component function.'\n );\n }\n\n const hookIndex = claimHookIndex(instance, 'derive');\n const compute =\n map === undefined\n ? () => (source as () => TIn)()\n : createMappedSelector(source, map);\n\n const cell = getOrCreateDerivedCell(\n instance,\n hookIndex,\n compute as () => TOut | null | TIn\n );\n recomputeDerivedCell(cell, false);\n return cell as Derived<TOut | null> | Derived<TIn>;\n}\n"],"mappings":";;;;;AA4CA,MAAM,8BAAc,IAAI,QAGtB;AACF,MAAM,oCAAoB,IAAI,IAA0B;AACxD,IAAI,yBAAyB;AAE7B,SAAS,eACP,UACmC;CACnC,IAAI,QAAQ,YAAY,IAAI,QAAQ;CACpC,IAAI,CAAC,OAAO;EACV,wBAAQ,IAAI,IAAI;EAChB,YAAY,IAAI,UAAU,KAAK;CACjC;CACA,OAAO;AACT;AAEA,SAAS,qBAAqB,MAAkC;CAC9D,KAA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GV,IAAI,SAAS,MACX,OAAO;EAGT,OAAO,IAAI,KAAK;CAClB;AACF;AASA,SAAgB,OACd,QACA,KACqC;CACrC,MAAM,WAAW,mBAAmB;CACpC,IAAI,CAAC,UACH,MAAM,IAAI,MACR,iIAEF;CASF,MAAM,OAAO,uBACX,UAPgB,eAAe,UAAU,QAQzC,GANA,QAAQ,eACG,OAAqB,IAC5B,qBAAqB,QAAQ,GAAG,CAMtC;CACA,qBAAqB,MAAM,KAAK;CAChC,OAAO;AACT"}
1
+ {"version":3,"file":"derive.js","names":[],"sources":["../../src/runtime/derive.ts"],"sourcesContent":["import {\n claimHookIndex,\n getCurrentInstance,\n type ComponentInstance,\n} from './component';\nimport { globalScheduler } from './scheduler';\nimport {\n clearDerivedDependencySubscriptions,\n markReadableDerivedSubscribersDirty,\n markReactivePropsDirtySource,\n notifyReadableReaders,\n recordReadableRead,\n syncDerivedDependencySubscriptions,\n type DerivedSubscriber,\n type ReadableSource,\n withDerivedReadTracking,\n} from './readable';\nimport { isSnapshotSource, type SnapshotSourceBrand } from './snapshot-source';\n\nexport interface Derived<T> extends ReadableSource<T> {\n (): T;\n}\n\ninterface DerivedCell<T> extends Derived<T>, DerivedSubscriber {\n _owner: ComponentInstance;\n _hookIndex: number;\n _compute: () => T;\n _value: T;\n _hasValue: boolean;\n _dirty: boolean;\n _scheduled: boolean;\n _evaluating: boolean;\n _lastRecomputeFlushVersion: number;\n _sources: Set<ReadableSource<unknown>>;\n _pendingDependencySources?: Set<ReadableSource<unknown>>;\n _cleanup(): void;\n}\n\ntype SnapshotSource<T> = {\n value: T | null;\n pending?: boolean;\n error?: Error | null;\n} & SnapshotSourceBrand;\n\nconst deriveCells = new WeakMap<\n ComponentInstance,\n Map<number, DerivedCell<unknown>>\n>();\nconst dirtyDerivedCells = new Set<DerivedCell<unknown>>();\nlet hasPendingDerivedFlush = false;\n\nfunction getDeriveStore(\n instance: ComponentInstance\n): Map<number, DerivedCell<unknown>> {\n let store = deriveCells.get(instance);\n if (!store) {\n store = new Map();\n deriveCells.set(instance, store);\n }\n return store;\n}\n\nfunction markDerivedCellDirty(cell: DerivedCell<unknown>): void {\n cell._dirty = true;\n if (cell._scheduled) {\n return;\n }\n\n cell._scheduled = true;\n dirtyDerivedCells.add(cell);\n\n if (!hasPendingDerivedFlush) {\n hasPendingDerivedFlush = true;\n globalScheduler.enqueueInLane('derived', flushDirtyDerivedCells);\n }\n}\n\nfunction flushDirtyDerivedCells(): void {\n hasPendingDerivedFlush = false;\n\n if (dirtyDerivedCells.size === 0) {\n return;\n }\n\n const pending = dirtyDerivedCells.values();\n let next = pending.next();\n\n while (!next.done) {\n const cell = next.value as DerivedCell<unknown>;\n dirtyDerivedCells.delete(cell);\n cell._scheduled = false;\n if (!cell._dirty) {\n next = pending.next();\n continue;\n }\n recomputeDerivedCell(cell, true);\n next = pending.next();\n }\n}\n\nfunction recomputeDerivedCell<T>(\n cell: DerivedCell<T>,\n notifyDownstream: boolean\n): T {\n if (!cell._dirty && cell._hasValue) {\n return cell._value;\n }\n\n if (cell._evaluating) {\n throw new Error('derive() cannot read itself recursively');\n }\n\n cell._evaluating = true;\n cell._dirty = false;\n cell._pendingDependencySources = new Set();\n\n const prevSources = cell._sources;\n let nextValue: T;\n\n try {\n nextValue = withDerivedReadTracking(cell, cell._compute);\n } catch (error) {\n cell._dirty = true;\n cell._pendingDependencySources = undefined;\n throw error;\n } finally {\n cell._evaluating = false;\n }\n\n const nextSources = cell._pendingDependencySources ?? new Set();\n cell._pendingDependencySources = undefined;\n syncDerivedDependencySubscriptions(cell, prevSources, nextSources);\n cell._sources = nextSources;\n\n const valueChanged = !cell._hasValue || !Object.is(cell._value, nextValue);\n cell._hasValue = true;\n cell._value = nextValue;\n cell._lastRecomputeFlushVersion = globalScheduler.getFlushVersion();\n\n if (valueChanged && notifyDownstream) {\n markReadableDerivedSubscribersDirty(cell);\n markReactivePropsDirtySource(cell);\n notifyReadableReaders(cell);\n }\n\n return cell._value;\n}\n\nfunction createDerivedCell<T>(\n instance: ComponentInstance,\n hookIndex: number,\n compute: () => T\n): DerivedCell<T> {\n const cell = function derivedGetter(): T {\n recordReadableRead(cell as DerivedCell<T>);\n return recomputeDerivedCell(\n cell as DerivedCell<T>,\n (cell as DerivedCell<T>)._scheduled\n );\n } as DerivedCell<T>;\n\n cell._owner = instance;\n cell._hookIndex = hookIndex;\n cell._compute = compute;\n cell._value = undefined as T;\n cell._hasValue = false;\n cell._dirty = true;\n cell._scheduled = false;\n cell._evaluating = false;\n cell._lastRecomputeFlushVersion = -1;\n cell._sources = new Set();\n cell._markDirty = () => {\n markDerivedCellDirty(cell);\n };\n cell._cleanup = () => {\n cell._scheduled = false;\n cell._dirty = false;\n cell._hasValue = false;\n dirtyDerivedCells.delete(cell);\n clearDerivedDependencySubscriptions(cell, cell._sources);\n cell._derivedSubscribers?.clear();\n cell._readers?.clear();\n };\n\n (instance.cleanupFns ??= []).push(() => {\n cell._cleanup();\n deriveCells.get(instance)?.delete(hookIndex);\n });\n\n return cell;\n}\n\nfunction getOrCreateDerivedCell<T>(\n instance: ComponentInstance,\n hookIndex: number,\n compute: () => T\n): DerivedCell<T> {\n const store = getDeriveStore(instance);\n const existing = store.get(hookIndex) as DerivedCell<T> | undefined;\n if (existing) {\n existing._compute = compute;\n if (\n existing._lastRecomputeFlushVersion !== globalScheduler.getFlushVersion()\n ) {\n existing._dirty = true;\n }\n return existing;\n }\n\n const created = createDerivedCell(instance, hookIndex, compute);\n store.set(hookIndex, created as DerivedCell<unknown>);\n return created;\n}\n\nfunction createMappedSelector<TIn, TOut>(\n source: SnapshotSource<TIn> | TIn | (() => TIn),\n map: (value: TIn) => TOut\n): () => TOut | null {\n return () => {\n let value: TIn;\n if (typeof source === 'function') {\n value = (source as () => TIn)();\n } else if (isSnapshotSource(source)) {\n value = (source as SnapshotSource<TIn>).value ?? (source as TIn);\n } else {\n value = source as TIn;\n }\n\n if (value == null) {\n return null;\n }\n\n return map(value);\n };\n}\n\nexport function derive<TOut>(fn: () => TOut): Derived<TOut>;\n\nexport function derive<TIn, TOut>(\n source: SnapshotSource<TIn> | TIn | (() => TIn),\n map: (value: TIn) => TOut\n): Derived<TOut | null>;\n\nexport function derive<TIn, TOut>(\n source: SnapshotSource<TIn> | TIn | (() => TIn),\n map?: (value: TIn) => TOut\n): Derived<TOut | null> | Derived<TIn> {\n const instance = getCurrentInstance();\n if (!instance) {\n throw new Error(\n 'derive() can only be called during component render execution. ' +\n 'Move derive() calls to the top level of your component function.'\n );\n }\n\n const hookIndex = claimHookIndex(instance, 'derive');\n const compute =\n map === undefined\n ? () => (source as () => TIn)()\n : createMappedSelector(source, map);\n\n const cell = getOrCreateDerivedCell(\n instance,\n hookIndex,\n compute as () => TOut | null | TIn\n );\n recomputeDerivedCell(cell, false);\n return cell as Derived<TOut | null> | Derived<TIn>;\n}\n"],"mappings":";;;;;AA4CA,MAAM,8BAAc,IAAI,QAGtB;AACF,MAAM,oCAAoB,IAAI,IAA0B;AACxD,IAAI,yBAAyB;AAE7B,SAAS,eACP,UACmC;CACnC,IAAI,QAAQ,YAAY,IAAI,QAAQ;CACpC,IAAI,CAAC,OAAO;EACV,wBAAQ,IAAI,IAAI;EAChB,YAAY,IAAI,UAAU,KAAK;CACjC;CACA,OAAO;AACT;AAEA,SAAS,qBAAqB,MAAkC;CAC9D,KAAK,SAAS;CACd,IAAI,KAAK,YACP;CAGF,KAAK,aAAa;CAClB,kBAAkB,IAAI,IAAI;CAE1B,IAAI,CAAC,wBAAwB;EAC3B,yBAAyB;EACzB,gBAAgB,cAAc,WAAW,sBAAsB;CACjE;AACF;AAEA,SAAS,yBAA+B;CACtC,yBAAyB;CAEzB,IAAI,kBAAkB,SAAS,GAC7B;CAGF,MAAM,UAAU,kBAAkB,OAAO;CACzC,IAAI,OAAO,QAAQ,KAAK;CAExB,OAAO,CAAC,KAAK,MAAM;EACjB,MAAM,OAAO,KAAK;EAClB,kBAAkB,OAAO,IAAI;EAC7B,KAAK,aAAa;EAClB,IAAI,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Content":["/**\n * Dev-only namespace helpers for diagnostics\n *\n * Centralizes the repetitive globalThis.__ASKR__ access pattern\n * used throughout runtime for dev-mode diagnostics.\n */\n\nimport { isProductionEnvironment } from '../common/env';\n\ntype DevNamespace = Record<string, unknown>;\n\n/**\n * Get or create the __ASKR__ dev namespace on globalThis.\n * Returns empty object in production to avoid allocations.\n */\nexport function getDevNamespace(): DevNamespace {\n if (isProductionEnvironment()) return {};\n try {\n const g = globalThis as unknown as Record<string, DevNamespace>;\n if (!g.__ASKR__) g.__ASKR__ = {};\n return g.__ASKR__;\n } catch {\n return {};\n }\n}\n\n/**\n * Set a value in the dev namespace (no-op in production).\n */\nexport function setDevValue(key: string, value: unknown): void {\n if (isProductionEnvironment()) return;\n try {\n getDevNamespace()[key] = value;\n } catch {\n // ignore\n }\n}\n\n/**\n * Get a value from the dev namespace (returns undefined in production).\n */\nexport function getDevValue<T>(key: string): T | undefined {\n if (isProductionEnvironment()) return undefined;\n try {\n return getDevNamespace()[key] as T | undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Delete a value from the dev namespace (no-op in production).\n */\nexport function deleteDevValue(key: string): void {\n if (isProductionEnvironment()) return;\n try {\n delete getDevNamespace()[key];\n } catch {\n // ignore\n }\n}\n\n/**\n * Increment a counter in the dev namespace (no-op in production).\n * Safely handles non-number values by resetting to 1.\n */\nexport function incDevCounter(key: string): void {\n if (isProductionEnvironment()) return;\n try {\n const ns = getDevNamespace();\n const prev = typeof ns[key] === 'number' ? (ns[key] as number) : 0;\n ns[key] = prev + 1;\n } catch {\n // ignore\n }\n}\n"],"mappings":";;;;;;;;;;;;AAeA,SAAgB,kBAAgC;CAC9C,IAAI,wBAAwB,GAAG,OAAO,CAAC;CACvC,IAAI;EACF,MAAM,IAAI;EACV,IAAI,CAAC,EAAE,UAAU,EAAE,WAAW,CAAC;EAC/B,OAAO,EAAE;CACX,QAAQ;EACN,OAAO,CAAC;CACV;AACF;;;;AAKA,SAAgB,YAAY,KAAa,OAAsB;CAC7D,IAAI,wBAAwB,GAAG;CAC/B,IAAI;EACF,gBAAgB,EAAE,OAAO;CAC3B,QAAQ,CAER;AACF;;;;AAKA,SAAgB,YAAe,KAA4B;CACzD,IAAI,wBAAwB,GAAG,OAAO;CACtC,IAAI;EACF,OAAO,gBAAgB,EAAE;CAC3B,QAAQ;EACN;CACF;AACF;;;;;AAkBA,SAAgB,cAAc,KAAmB;CAC/C,IAAI,wBAAwB,GAAG;CAC/B,IAAI;EACF,MAAM,KAAK,gBAAgB;EAE3B,GAAG,QADU,OAAO,GAAG,SAAS,WAAY,GAAG,OAAkB,KAChD;CACnB,QAAQ,CAER;AACF"}
1
+ {"version":3,"file":"dev-namespace.js","names":[],"sources":["../../src/runtime/dev-namespace.ts"],"sourcesContent":["/**\n * Dev-only namespace helpers for diagnostics\n *\n * Centralizes the repetitive globalThis.__ASKR__ access pattern\n * used throughout runtime for dev-mode diagnostics.\n */\n\nimport { isProductionEnvironment } from '../common/env';\n\ntype DevNamespace = Record<string, unknown>;\n\n/**\n * Get or create the __ASKR__ dev namespace on globalThis.\n * Returns empty object in production to avoid allocations.\n */\nexport function getDevNamespace(): DevNamespace {\n if (isProductionEnvironment()) return {};\n try {\n const g = globalThis as unknown as Record<string, DevNamespace>;\n if (!g.__ASKR__) g.__ASKR__ = {};\n return g.__ASKR__;\n } catch {\n return {};\n }\n}\n\n/**\n * Set a value in the dev namespace (no-op in production).\n */\nexport function setDevValue(key: string, value: unknown): void {\n if (isProductionEnvironment()) return;\n try {\n getDevNamespace()[key] = value;\n } catch {\n // ignore\n }\n}\n\n/**\n * Get a value from the dev namespace (returns undefined in production).\n */\nexport function getDevValue<T>(key: string): T | undefined {\n if (isProductionEnvironment()) return undefined;\n try {\n return getDevNamespace()[key] as T | undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Delete a value from the dev namespace (no-op in production).\n */\nexport function deleteDevValue(key: string): void {\n if (isProductionEnvironment()) return;\n try {\n delete getDevNamespace()[key];\n } catch {\n // ignore\n }\n}\n\n/**\n * Increment a counter in the dev namespace (no-op in production).\n * Safely handles non-number values by resetting to 1.\n */\nexport function incDevCounter(key: string): void {\n if (isProductionEnvironment()) return;\n try {\n const ns = getDevNamespace();\n const prev = typeof ns[key] === 'number' ? (ns[key] as number) : 0;\n ns[key] = prev + 1;\n } catch {\n // ignore\n }\n}\n"],"mappings":";;;;;;;;;;;;AAeA,SAAgB,kBAAgC;CAC9C,IAAI,wBAAwB,GAAG,OAAO,CAAC;CACvC,IAAI;EACF,MAAM,IAAI;EACV,IAAI,CAAC,EAAE,UAAU,EAAE,WAAW,CAAC;EAC/B,OAAO,EAAE;CACX,QAAQ;EACN,OAAO,CAAC;CACV;AACF;;;;AAKA,SAAgB,YAAY,KAAa,OAAsB;CAC7D,IAAI,wBAAwB,GAAG;CAC/B,IAAI;EACF,gBAAgB,CAAC,CAAC,OAAO;CAC3B,QAAQ,CAER;AACF;;;;AAKA,SAAgB,YAAe,KAA4B;CACzD,IAAI,wBAAwB,GAAG,OAAO;CACtC,IAAI;EACF,OAAO,gBAAgB,CAAC,CAAC;CAC3B,QAAQ;EACN;CACF;AACF;;;;;AAkBA,SAAgB,cAAc,KAAmB;CAC/C,IAAI,wBAAwB,GAAG;CAC/B,IAAI;EACF,MAAM,KAAK,gBAAgB;EAE3B,GAAG,QADU,OAAO,GAAG,SAAS,WAAY,GAAG,OAAkB,KAChD;CACnB,QAAQ,CAER;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"effect.js","names":[],"sources":["../../src/runtime/effect.ts"],"sourcesContent":["import { incDevCounter } from './dev-namespace';\nimport { type ReadableSource, withFineGrainedReadTracking } from './readable';\nimport { globalScheduler, type SchedulerLane } from './scheduler';\n\ntype EffectRegistry = WeakMap<\n ReadableSource<unknown>,\n Set<FineGrainedEffect<unknown>>\n>;\n\ntype EffectFlushSets = Record<SchedulerLane, Set<FineGrainedEffect<unknown>>>;\n\ntype EffectPendingFlushState = Record<SchedulerLane, boolean>;\ntype EffectLaneDirtyState = Record<SchedulerLane, boolean>;\n\nconst effectSources: EffectRegistry = new WeakMap();\nconst dirtyEffectsByLane: EffectFlushSets = {\n derived: new Set(),\n component: new Set(),\n reactive: new Set(),\n post: new Set(),\n};\nconst hasPendingLaneFlush: EffectPendingFlushState = {\n derived: false,\n component: false,\n reactive: false,\n post: false,\n};\n\nconst dirtyLaneState: EffectLaneDirtyState = {\n derived: false,\n component: false,\n reactive: false,\n post: false,\n};\n\nconst MAX_EFFECT_RUNS_PER_FLUSH = 50;\nconst LANE_FLUSH_TASKS: Record<SchedulerLane, () => void> = {\n derived: () => flushLaneEffects('derived'),\n component: () => flushLaneEffects('component'),\n reactive: () => flushLaneEffects('reactive'),\n post: () => flushLaneEffects('post'),\n};\n\nexport interface FineGrainedEffect<T> {\n lane: SchedulerLane;\n compute(): T;\n commit(value: T, previousValue: T | undefined): void;\n equals(previousValue: T, nextValue: T): boolean;\n readSources: Set<ReadableSource<unknown>>;\n isActive: boolean;\n hasValue: boolean;\n lastValue: T | undefined;\n onError?(error: unknown): void;\n}\n\nexport interface FineGrainedEffectHandle<T> {\n cleanup(): void;\n updateCompute(nextCompute: () => T): void;\n flush(): void;\n}\n\nexport interface CreateFineGrainedEffectOptions<T> {\n lane: SchedulerLane;\n compute: () => T;\n commit: (value: T, previousValue: T | undefined) => void;\n equals?: (previousValue: T, nextValue: T) => boolean;\n onError?: (error: unknown) => void;\n}\n\nfunction registerEffectSource(\n source: ReadableSource<unknown>,\n effect: FineGrainedEffect<unknown>\n): void {\n let effects = effectSources.get(source);\n if (!effects) {\n effects = new Set();\n effectSources.set(source, effects);\n }\n effects.add(effect);\n}\n\nfunction unregisterEffectSource(\n source: ReadableSource<unknown>,\n effect: FineGrainedEffect<unknown>\n): void {\n effectSources.get(source)?.delete(effect);\n}\n\nfunction clearEffectSubscriptions(effect: FineGrainedEffect<unknown>): void {\n for (const source of effect.readSources) {\n unregisterEffectSource(source, effect);\n }\n effect.readSources.clear();\n}\n\nfunction normalizeNextSources(\n previousSources: Set<ReadableSource<unknown>>,\n pendingSources: Set<ReadableSource<unknown>>\n): Set<ReadableSource<unknown>> {\n if (previousSources.size === pendingSources.size) {\n let same = true;\n for (const source of previousSources) {\n if (!pendingSources.has(source)) {\n same = false;\n break;\n }\n }\n\n if (same) {\n return previousSources;\n }\n }\n\n return new Set(pendingSources);\n}\n\nfunction evaluateEffect<T>(effect: FineGrainedEffect<T>): {\n value: T;\n nextSources: Set<ReadableSource<unknown>>;\n} {\n const pendingSources = new Set<ReadableSource<unknown>>();\n\n incDevCounter('effectRuns');\n const value = withFineGrainedReadTracking(pendingSources, () =>\n effect.compute()\n );\n const nextSources = normalizeNextSources(effect.readSources, pendingSources);\n return { value, nextSources };\n}\n\nfunction commitEffectSubscriptions(\n effect: FineGrainedEffect<unknown>,\n nextSources: Set<ReadableSource<unknown>>\n): void {\n const previousSources = effect.readSources;\n\n if (previousSources === nextSources) {\n return;\n }\n\n for (const source of previousSources) {\n if (!nextSources.has(source)) {\n unregisterEffectSource(source, effect);\n }\n }\n\n for (const source of nextSources) {\n if (!previousSources.has(source)) {\n registerEffectSource(source, effect);\n }\n }\n\n effect.readSources = nextSources;\n}\n\nfunction commitEffectResult<T>(\n effect: FineGrainedEffect<T>,\n value: T,\n nextSources: Set<ReadableSource<unknown>>\n): void {\n const previousValue = effect.lastValue;\n const shouldCommit =\n !effect.hasValue || !effect.equals(previousValue as T, value);\n\n if (shouldCommit) {\n effect.commit(value, effect.hasValue ? previousValue : undefined);\n }\n\n commitEffectSubscriptions(effect, nextSources);\n effect.lastValue = value;\n effect.hasValue = true;\n}\n\nfunction flushLaneEffects(lane: SchedulerLane): void {\n hasPendingLaneFlush[lane] = false;\n\n const effects = dirtyEffectsByLane[lane];\n if (effects.size === 0) {\n return;\n }\n\n const pending = effects.values();\n const effectRuns = new Map<FineGrainedEffect<unknown>, number>();\n let next = pending.next();\n\n while (!next.done) {\n const effect = next.value as FineGrainedEffect<unknown>;\n effects.delete(effect);\n if (!effect.isActive) {\n next = pending.next();\n continue;\n }\n\n const runCount = (effectRuns.get(effect) ?? 0) + 1;\n effectRuns.set(effect, runCount);\n if (runCount > MAX_EFFECT_RUNS_PER_FLUSH) {\n const error = new Error(\n `[Askr] fine-grained effect exceeded ${MAX_EFFECT_RUNS_PER_FLUSH} runs in one flush. Likely reactive cycle.`\n );\n if (effect.onError) {\n effect.onError(error);\n } else {\n throw error;\n }\n next = pending.next();\n continue;\n }\n\n try {\n const { value, nextSources } = evaluateEffect(effect);\n commitEffectResult(effect, value, nextSources);\n } catch (error) {\n effect.onError?.(error);\n }\n\n next = pending.next();\n }\n}\n\nfunction scheduleLaneFlush(lane: SchedulerLane): void {\n if (hasPendingLaneFlush[lane]) {\n return;\n }\n\n hasPendingLaneFlush[lane] = true;\n globalScheduler.enqueueInLane(lane, LANE_FLUSH_TASKS[lane]);\n}\n\nfunction unscheduleEffect(effect: FineGrainedEffect<unknown>): void {\n dirtyEffectsByLane[effect.lane].delete(effect);\n}\n\nfunction recomputeEffectNow<T>(effect: FineGrainedEffect<T>): void {\n const { value, nextSources } = evaluateEffect(effect);\n commitEffectResult(effect, value, nextSources);\n}\n\nexport function markFineGrainedEffectsDirtySource(\n source: ReadableSource<unknown>\n): void {\n const effects = effectSources.get(source);\n if (!effects || effects.size === 0) {\n return;\n }\n\n dirtyLaneState.derived = false;\n dirtyLaneState.component = false;\n dirtyLaneState.reactive = false;\n dirtyLaneState.post = false;\n\n for (const effect of effects) {\n if (!effect.isActive) {\n continue;\n }\n const lane = effect.lane;\n dirtyEffectsByLane[lane].add(effect);\n dirtyLaneState[lane] = true;\n }\n\n if (dirtyLaneState.derived) {\n scheduleLaneFlush('derived');\n }\n if (dirtyLaneState.component) {\n scheduleLaneFlush('component');\n }\n if (dirtyLaneState.reactive) {\n scheduleLaneFlush('reactive');\n }\n if (dirtyLaneState.post) {\n scheduleLaneFlush('post');\n }\n}\n\nexport function createFineGrainedEffect<T>(\n options: CreateFineGrainedEffectOptions<T>\n): FineGrainedEffectHandle<T> {\n const effect: FineGrainedEffect<T> = {\n lane: options.lane,\n compute: options.compute,\n commit: options.commit,\n equals: options.equals ?? Object.is,\n readSources: new Set(),\n isActive: true,\n hasValue: false,\n lastValue: undefined,\n onError: options.onError,\n };\n\n recomputeEffectNow(effect);\n\n return {\n cleanup(): void {\n if (!effect.isActive) {\n return;\n }\n\n effect.isActive = false;\n unscheduleEffect(effect);\n clearEffectSubscriptions(effect);\n },\n\n updateCompute(nextCompute: () => T): void {\n if (!effect.isActive) {\n return;\n }\n\n effect.compute = nextCompute;\n unscheduleEffect(effect);\n recomputeEffectNow(effect);\n },\n\n flush(): void {\n if (!effect.isActive) {\n return;\n }\n\n unscheduleEffect(effect);\n recomputeEffectNow(effect);\n },\n };\n}\n"],"mappings":";;;;AAcA,MAAM,gCAAgC,IAAI,QAAQ;AAClD,MAAM,qBAAsC;CAC1C,yBAAS,IAAI,IAAI;CACjB,2BAAW,IAAI,IAAI;CACnB,0BAAU,IAAI,IAAI;CAClB,sBAAM,IAAI,IAAI;AAChB;AACA,MAAM,sBAA+C;CACnD,SAAS;CACT,WAAW;CACX,UAAU;CACV,MAAM;AACR;AAEA,MAAM,iBAAuC;CAC3C,SAAS;CACT,WAAW;CACX,UAAU;CACV,MAAM;AACR;AAEA,MAAM,4BAA4B;AAClC,MAAM,mBAAsD;CAC1D,eAAe,iBAAiB,SAAS;CACzC,iBAAiB,iBAAiB,WAAW;CAC7C,gBAAgB,iBAAiB,UAAU;CAC3C,YAAY,iBAAiB,MAAM;AACrC;AA4BA,SAAS,qBACP,QACA,QACM;CACN,IAAI,UAAU,cAAc,IAAI,MAAM;CACtC,IAAI,CAAC,SAAS;EACZ,0BAAU,IAAI,IAAI;EAClB,cAAc,IAAI,QAAQ,OAAO;CACnC;CACA,QAAQ,IAAI,MAAM;AACpB;AAEA,SAAS,uBACP,QACA,QACM;CACN,cAAc,IAAI,MAAM,GAAG,OAAO,MAAM;AAC1C;AAEA,SAAS,yBAAyB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,QAAQ;CACzB;CAEA,IAAI,eAAe,SACjB,kBAAkB,SAAS;CAE7B,IAAI,eAAe,WACjB,kBAAkB,WAAW;CAE/B,IAAI,eAAe,UACjB,kBAAkB,UAAU;CAE9B,IAAI,eAAe,MACjB,kBAAkB,MAAM;AAE5B;AAEA,SAAgB,wBACd,SAC4B;CAC5B,MAAM,SAA+B;EACnC,MAAM,QAAQ;EACd,SAAS,QAAQ;EACjB,QAAQ,QAAQ;EAChB,QAAQ,QAAQ,UAAU,OAAO;EACjC,6BAAa,IAAI,IAAI;EACrB,UAAU;EACV,UAAU;EACV,WAAW;EACX,SAAS,QAAQ;CACnB;CAEA,mBAAmB,MAAM;CAEzB,OAAO;EACL,UAAgB;GACd,IAAI,CAAC,OAAO,UACV;GAGF,OAAO,WAAW;GAClB,iBAAiB,MAAM;GACvB,yBAAyB,MAAM;EACjC;EAEA,cAAc,aAA4B;GACxC,IAAI,CAAC,OAAO,UACV;GAGF,OAAO,UAAU;GACjB,iBAAiB,MAAM;GACvB,mBAAmB,MAAM;EAC3B;EAEA,QAAc;GACZ,IAAI,CAAC,OAAO,UACV;GAGF,iBAAiB,MAAM;GACvB,mBAAmB,MAAM;EAC3B;CACF;AACF"}
1
+ {"version":3,"file":"effect.js","names":[],"sources":["../../src/runtime/effect.ts"],"sourcesContent":["import { incDevCounter } from './dev-namespace';\nimport { type ReadableSource, withFineGrainedReadTracking } from './readable';\nimport { globalScheduler, type SchedulerLane } from './scheduler';\n\ntype EffectRegistry = WeakMap<\n ReadableSource<unknown>,\n Set<FineGrainedEffect<unknown>>\n>;\n\ntype EffectFlushSets = Record<SchedulerLane, Set<FineGrainedEffect<unknown>>>;\n\ntype EffectPendingFlushState = Record<SchedulerLane, boolean>;\ntype EffectLaneDirtyState = Record<SchedulerLane, boolean>;\n\nconst effectSources: EffectRegistry = new WeakMap();\nconst dirtyEffectsByLane: EffectFlushSets = {\n derived: new Set(),\n component: new Set(),\n reactive: new Set(),\n post: new Set(),\n};\nconst hasPendingLaneFlush: EffectPendingFlushState = {\n derived: false,\n component: false,\n reactive: false,\n post: false,\n};\n\nconst dirtyLaneState: EffectLaneDirtyState = {\n derived: false,\n component: false,\n reactive: false,\n post: false,\n};\n\nconst MAX_EFFECT_RUNS_PER_FLUSH = 50;\nconst LANE_FLUSH_TASKS: Record<SchedulerLane, () => void> = {\n derived: () => flushLaneEffects('derived'),\n component: () => flushLaneEffects('component'),\n reactive: () => flushLaneEffects('reactive'),\n post: () => flushLaneEffects('post'),\n};\n\nexport interface FineGrainedEffect<T> {\n lane: SchedulerLane;\n compute(): T;\n commit(value: T, previousValue: T | undefined): void;\n equals(previousValue: T, nextValue: T): boolean;\n readSources: Set<ReadableSource<unknown>>;\n isActive: boolean;\n hasValue: boolean;\n lastValue: T | undefined;\n onError?(error: unknown): void;\n}\n\nexport interface FineGrainedEffectHandle<T> {\n cleanup(): void;\n updateCompute(nextCompute: () => T): void;\n flush(): void;\n}\n\nexport interface CreateFineGrainedEffectOptions<T> {\n lane: SchedulerLane;\n compute: () => T;\n commit: (value: T, previousValue: T | undefined) => void;\n equals?: (previousValue: T, nextValue: T) => boolean;\n onError?: (error: unknown) => void;\n}\n\nfunction registerEffectSource(\n source: ReadableSource<unknown>,\n effect: FineGrainedEffect<unknown>\n): void {\n let effects = effectSources.get(source);\n if (!effects) {\n effects = new Set();\n effectSources.set(source, effects);\n }\n effects.add(effect);\n}\n\nfunction unregisterEffectSource(\n source: ReadableSource<unknown>,\n effect: FineGrainedEffect<unknown>\n): void {\n effectSources.get(source)?.delete(effect);\n}\n\nfunction clearEffectSubscriptions(effect: FineGrainedEffect<unknown>): void {\n for (const source of effect.readSources) {\n unregisterEffectSource(source, effect);\n }\n effect.readSources.clear();\n}\n\nfunction normalizeNextSources(\n previousSources: Set<ReadableSource<unknown>>,\n pendingSources: Set<ReadableSource<unknown>>\n): Set<ReadableSource<unknown>> {\n if (previousSources.size === pendingSources.size) {\n let same = true;\n for (const source of previousSources) {\n if (!pendingSources.has(source)) {\n same = false;\n break;\n }\n }\n\n if (same) {\n return previousSources;\n }\n }\n\n return new Set(pendingSources);\n}\n\nfunction evaluateEffect<T>(effect: FineGrainedEffect<T>): {\n value: T;\n nextSources: Set<ReadableSource<unknown>>;\n} {\n const pendingSources = new Set<ReadableSource<unknown>>();\n\n incDevCounter('effectRuns');\n const value = withFineGrainedReadTracking(pendingSources, () =>\n effect.compute()\n );\n const nextSources = normalizeNextSources(effect.readSources, pendingSources);\n return { value, nextSources };\n}\n\nfunction commitEffectSubscriptions(\n effect: FineGrainedEffect<unknown>,\n nextSources: Set<ReadableSource<unknown>>\n): void {\n const previousSources = effect.readSources;\n\n if (previousSources === nextSources) {\n return;\n }\n\n for (const source of previousSources) {\n if (!nextSources.has(source)) {\n unregisterEffectSource(source, effect);\n }\n }\n\n for (const source of nextSources) {\n if (!previousSources.has(source)) {\n registerEffectSource(source, effect);\n }\n }\n\n effect.readSources = nextSources;\n}\n\nfunction commitEffectResult<T>(\n effect: FineGrainedEffect<T>,\n value: T,\n nextSources: Set<ReadableSource<unknown>>\n): void {\n const previousValue = effect.lastValue;\n const shouldCommit =\n !effect.hasValue || !effect.equals(previousValue as T, value);\n\n if (shouldCommit) {\n effect.commit(value, effect.hasValue ? previousValue : undefined);\n }\n\n commitEffectSubscriptions(effect, nextSources);\n effect.lastValue = value;\n effect.hasValue = true;\n}\n\nfunction flushLaneEffects(lane: SchedulerLane): void {\n hasPendingLaneFlush[lane] = false;\n\n const effects = dirtyEffectsByLane[lane];\n if (effects.size === 0) {\n return;\n }\n\n const pending = effects.values();\n const effectRuns = new Map<FineGrainedEffect<unknown>, number>();\n let next = pending.next();\n\n while (!next.done) {\n const effect = next.value as FineGrainedEffect<unknown>;\n effects.delete(effect);\n if (!effect.isActive) {\n next = pending.next();\n continue;\n }\n\n const runCount = (effectRuns.get(effect) ?? 0) + 1;\n effectRuns.set(effect, runCount);\n if (runCount > MAX_EFFECT_RUNS_PER_FLUSH) {\n const error = new Error(\n `[Askr] fine-grained effect exceeded ${MAX_EFFECT_RUNS_PER_FLUSH} runs in one flush. Likely reactive cycle.`\n );\n if (effect.onError) {\n effect.onError(error);\n } else {\n throw error;\n }\n next = pending.next();\n continue;\n }\n\n try {\n const { value, nextSources } = evaluateEffect(effect);\n commitEffectResult(effect, value, nextSources);\n } catch (error) {\n effect.onError?.(error);\n }\n\n next = pending.next();\n }\n}\n\nfunction scheduleLaneFlush(lane: SchedulerLane): void {\n if (hasPendingLaneFlush[lane]) {\n return;\n }\n\n hasPendingLaneFlush[lane] = true;\n globalScheduler.enqueueInLane(lane, LANE_FLUSH_TASKS[lane]);\n}\n\nfunction unscheduleEffect(effect: FineGrainedEffect<unknown>): void {\n dirtyEffectsByLane[effect.lane].delete(effect);\n}\n\nfunction recomputeEffectNow<T>(effect: FineGrainedEffect<T>): void {\n const { value, nextSources } = evaluateEffect(effect);\n commitEffectResult(effect, value, nextSources);\n}\n\nexport function markFineGrainedEffectsDirtySource(\n source: ReadableSource<unknown>\n): void {\n const effects = effectSources.get(source);\n if (!effects || effects.size === 0) {\n return;\n }\n\n dirtyLaneState.derived = false;\n dirtyLaneState.component = false;\n dirtyLaneState.reactive = false;\n dirtyLaneState.post = false;\n\n for (const effect of effects) {\n if (!effect.isActive) {\n continue;\n }\n const lane = effect.lane;\n dirtyEffectsByLane[lane].add(effect);\n dirtyLaneState[lane] = true;\n }\n\n if (dirtyLaneState.derived) {\n scheduleLaneFlush('derived');\n }\n if (dirtyLaneState.component) {\n scheduleLaneFlush('component');\n }\n if (dirtyLaneState.reactive) {\n scheduleLaneFlush('reactive');\n }\n if (dirtyLaneState.post) {\n scheduleLaneFlush('post');\n }\n}\n\nexport function createFineGrainedEffect<T>(\n options: CreateFineGrainedEffectOptions<T>\n): FineGrainedEffectHandle<T> {\n const effect: FineGrainedEffect<T> = {\n lane: options.lane,\n compute: options.compute,\n commit: options.commit,\n equals: options.equals ?? Object.is,\n readSources: new Set(),\n isActive: true,\n hasValue: false,\n lastValue: undefined,\n onError: options.onError,\n };\n\n recomputeEffectNow(effect);\n\n return {\n cleanup(): void {\n if (!effect.isActive) {\n return;\n }\n\n effect.isActive = false;\n unscheduleEffect(effect);\n clearEffectSubscriptions(effect);\n },\n\n updateCompute(nextCompute: () => T): void {\n if (!effect.isActive) {\n return;\n }\n\n effect.compute = nextCompute;\n unscheduleEffect(effect);\n recomputeEffectNow(effect);\n },\n\n flush(): void {\n if (!effect.isActive) {\n return;\n }\n\n unscheduleEffect(effect);\n recomputeEffectNow(effect);\n },\n };\n}\n"],"mappings":";;;;AAcA,MAAM,gCAAgC,IAAI,QAAQ;AAClD,MAAM,qBAAsC;CAC1C,yBAAS,IAAI,IAAI;CACjB,2BAAW,IAAI,IAAI;CACnB,0BAAU,IAAI,IAAI;CAClB,sBAAM,IAAI,IAAI;AAChB;AACA,MAAM,sBAA+C;CACnD,SAAS;CACT,WAAW;CACX,UAAU;CACV,MAAM;AACR;AAEA,MAAM,iBAAuC;CAC3C,SAAS;CACT,WAAW;CACX,UAAU;CACV,MAAM;AACR;AAEA,MAAM,4BAA4B;AAClC,MAAM,mBAAsD;CAC1D,eAAe,iBAAiB,SAAS;CACzC,iBAAiB,iBAAiB,WAAW;CAC7C,gBAAgB,iBAAiB,UAAU;CAC3C,YAAY,iBAAiB,MAAM;AACrC;AA4BA,SAAS,qBACP,QACA,QACM;CACN,IAAI,UAAU,cAAc,IAAI,MAAM;CACtC,IAAI,CAAC,SAAS;EACZ,0BAAU,IAAI,IAAI;EAClB,cAAc,IAAI,QAAQ,OAAO;CACnC;CACA,QAAQ,IAAI,MAAM;AACpB;AAEA,SAAS,uBACP,QACA,QACM;CACN,cAAc,IAAI,MAAM,CAAC,EAAE,OAAO,MAAM;AAC1C;AAEA,SAAS,yBAAyB,QAA0C;CAC1E,KAAK,MAAM,UAAU,OAAO,aAC1B,uBAAuB,QAAQ,MAAM;CAEvC,OAAO,YAAY,MAAM;AAC3B;AAEA,SAAS,qBACP,iBACA,gBAC8B;CAC9B,IAA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CAE9B,IAAI,eAAe,MACjB,kBAAkB,MAAM;AAE5B;AAEA,SAAgB,wBACd,SAC4B;CAC5B,MAAM,SAA+B;EACnC,MAAM,QAAQ;EACd,SAAS,QAAQ;EACjB,QAAQ,QAAQ;EAChB,QAAQ,QAAQ,UAAU,OAAO;EACjC,6BAAa,IAAI,IAAI;EACrB,UAAU;EACV,UAAU;EACV,WAAW;EACX,SAAS,QAAQ;CACnB;CAEA,mBAAmB,MAAM;CAEzB,OAAO;EACL,UAAgB;GACd,IAAI,CAAC,OAAO,UACV;GAGF,OAAO,WAAW;GAClB,iBAAiB,MAAM;GACvB,yBAAyB,MAAM;EACjC;EAEA,cAAc,aAA4B;GACxC,IAAI,CAAC,OAAO,UACV;GAGF,OAAO,UAAU;GACjB,iBAAiB,MAAM;GACvB,mBAAmB,MAAM;EAC3B;EAEA,QAAc;GACZ,IAAI,CAAC,OAAO,UACV;GAGF,iBAAiB,MAAM;GACvB,mBAAmB,MAAM;EAC3B;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"events.js","names":[],"sources":["../../src/runtime/events.ts"],"sourcesContent":["/**\n * Event delegation system for Askr\n *\n * Provides efficient event handling by attaching listeners to a container\n * instead of individual elements. This significantly reduces memory usage\n * and improves performance when many elements have the same event type.\n *\n * Delegated handling is enabled by default. Tests and internal runtime code\n * can still disable or re-enable it when they need to exercise both modes.\n */\n\nimport { globalScheduler } from './scheduler';\nimport { logger } from '../dev/logger';\nimport { incrementPerfMetric } from './perf-metrics';\nimport { incDevCounter } from './dev-namespace';\n\nexport interface DelegatedEventMap {\n click: MouseEvent;\n dblclick: MouseEvent;\n mousedown: MouseEvent;\n mouseup: MouseEvent;\n mouseover: MouseEvent;\n mouseout: MouseEvent;\n mousemove: MouseEvent;\n focus: FocusEvent;\n blur: FocusEvent;\n input: InputEvent;\n change: Event;\n keydown: KeyboardEvent;\n keyup: KeyboardEvent;\n keypress: KeyboardEvent;\n submit: Event;\n scroll: Event;\n wheel: WheelEvent;\n touchstart: TouchEvent;\n touchend: TouchEvent;\n touchmove: TouchEvent;\n touchcancel: TouchEvent;\n}\n\nconst DELEGATED_EVENTS: (keyof DelegatedEventMap)[] = [\n 'click',\n 'dblclick',\n 'mousedown',\n 'mouseup',\n 'mouseover',\n 'mouseout',\n 'mousemove',\n 'focus',\n 'blur',\n 'input',\n 'change',\n 'keydown',\n 'keyup',\n 'keypress',\n 'submit',\n 'scroll',\n 'wheel',\n 'touchstart',\n 'touchend',\n 'touchmove',\n 'touchcancel',\n];\n\ninterface DelegatedHandler {\n handler: EventListener;\n original: EventListener;\n element: Element;\n container: Element;\n eventName: string;\n options?: AddEventListenerOptions;\n}\n\ntype DelegatedHandlerStore = DelegatedHandler | Map<string, DelegatedHandler>;\n\nconst delegatedHandlers = new WeakMap<Element, DelegatedHandlerStore>();\n\nlet eventDelegationEnabled = true;\nlet defaultContainer: Element | null = null;\nlet globalDelegationContainer: Element | null = null;\nconst containerDelegatedListeners = new Map<\n Element,\n Map<string, EventListener>\n>();\nconst containerDelegatedListenerUsage = new Map<Element, Map<string, number>>();\n\nexport function isEventDelegationEnabled(): boolean {\n return eventDelegationEnabled;\n}\n\nexport function disableEventDelegation(): void {\n eventDelegationEnabled = false;\n cleanupAllDelegatedListeners();\n}\n\nexport function enableEventDelegation(container?: Element): void {\n eventDelegationEnabled = true;\n if (container) {\n defaultContainer = container;\n }\n}\n\nexport function setGlobalDelegationContainer(container: Element): void {\n globalDelegationContainer = container;\n}\n\nfunction cleanupAllDelegatedListeners(): void {\n for (const [container, listeners] of containerDelegatedListeners) {\n for (const [eventName, handler] of listeners) {\n container.removeEventListener(eventName, handler);\n }\n }\n containerDelegatedListeners.clear();\n containerDelegatedListenerUsage.clear();\n}\n\nfunction incrementContainerListenerUsage(\n container: Element,\n eventName: string\n): void {\n let usage = containerDelegatedListenerUsage.get(container);\n if (!usage) {\n usage = new Map();\n containerDelegatedListenerUsage.set(container, usage);\n }\n usage.set(eventName, (usage.get(eventName) ?? 0) + 1);\n}\n\nfunction decrementContainerListenerUsage(entry: DelegatedHandler): void {\n const usage = containerDelegatedListenerUsage.get(entry.container);\n if (!usage) {\n return;\n }\n\n const nextCount = (usage.get(entry.eventName) ?? 0) - 1;\n if (nextCount > 0) {\n usage.set(entry.eventName, nextCount);\n return;\n }\n\n usage.delete(entry.eventName);\n const listeners = containerDelegatedListeners.get(entry.container);\n const listener = listeners?.get(entry.eventName);\n if (listener) {\n entry.container.removeEventListener(entry.eventName, listener);\n listeners?.delete(entry.eventName);\n }\n\n if (listeners?.size === 0) {\n containerDelegatedListeners.delete(entry.container);\n }\n if (usage.size === 0) {\n containerDelegatedListenerUsage.delete(entry.container);\n }\n}\n\nfunction getDelegationContainer(): Element | null {\n if (globalDelegationContainer) return globalDelegationContainer;\n if (defaultContainer) return defaultContainer;\n if (typeof document !== 'undefined') return document.body;\n return null;\n}\n\nfunction attachDelegatedListener(\n container: Element,\n element: Element,\n eventName: string,\n handler: EventListener,\n originalHandler: EventListener,\n options?: AddEventListenerOptions\n): void {\n const hadHandler = !!getDelegatedHandlerForElement(element, eventName);\n\n if (!containerDelegatedListeners.has(container)) {\n containerDelegatedListeners.set(container, new Map());\n }\n const containerListeners = containerDelegatedListeners.get(container)!;\n\n if (!containerListeners.has(eventName)) {\n const delegatedHandler = (e: Event) => {\n const target = e.target as Element;\n if (!target) return;\n\n globalScheduler.runInHandlerScope(() => {\n let current: Element | null = target;\n while (current && current !== container) {\n incrementPerfMetric('delegatedAncestorHops');\n const store = delegatedHandlers.get(current);\n const entry = !store\n ? undefined\n : store instanceof Map\n ? store.get(eventName)\n : store.eventName === eventName\n ? store\n : undefined;\n if (entry) {\n try {\n entry.handler(e);\n } catch (error) {\n logger.error('[Askr] Delegated event error:', error);\n }\n }\n\n if (e.cancelBubble) {\n break;\n }\n\n current = current.parentElement;\n }\n }, 'sync');\n };\n\n const passiveOptions = getPassiveOptions(eventName);\n const listenerOptions = passiveOptions ?? options;\n\n container.addEventListener(eventName, delegatedHandler, listenerOptions);\n containerListeners.set(eventName, delegatedHandler);\n }\n\n setDelegatedHandlerForElement(element, {\n handler,\n original: originalHandler,\n element,\n container,\n eventName,\n options,\n });\n if (!hadHandler) {\n incrementContainerListenerUsage(container, eventName);\n }\n}\n\nfunction setDelegatedHandlerForElement(\n element: Element,\n entry: DelegatedHandler\n): void {\n const existing = delegatedHandlers.get(element);\n if (!existing) {\n delegatedHandlers.set(element, entry);\n return;\n }\n\n if (existing instanceof Map) {\n existing.set(entry.eventName, entry);\n return;\n }\n\n if (existing.eventName === entry.eventName) {\n delegatedHandlers.set(element, entry);\n return;\n }\n\n const next = new Map<string, DelegatedHandler>();\n next.set(existing.eventName, existing);\n next.set(entry.eventName, entry);\n delegatedHandlers.set(element, next);\n}\n\nfunction getPassiveOptions(\n eventName: string\n): AddEventListenerOptions | undefined {\n if (\n eventName === 'wheel' ||\n eventName === 'scroll' ||\n eventName.startsWith('touch')\n ) {\n return { passive: true };\n }\n return undefined;\n}\n\nexport function addDelegatedListener(\n element: Element,\n eventName: string,\n handler: EventListener,\n originalHandler: EventListener,\n options?: AddEventListenerOptions\n): void {\n if (!eventDelegationEnabled) return;\n\n const container = getDelegationContainer();\n if (!container) return;\n\n incDevCounter('listenerAdds');\n\n attachDelegatedListener(\n container,\n element,\n eventName,\n handler,\n originalHandler,\n options\n );\n}\n\nexport function updateDelegatedListener(\n element: Element,\n eventName: string,\n handler: EventListener,\n originalHandler: EventListener,\n options?: AddEventListenerOptions\n): boolean {\n const existing = getDelegatedHandlerForElement(element, eventName);\n if (!existing) {\n return false;\n }\n\n const container = getDelegationContainer();\n if (\n !container ||\n existing.container !== container ||\n !containerDelegatedListeners.get(existing.container)?.has(eventName)\n ) {\n removeDelegatedListener(element, eventName);\n return false;\n }\n\n existing.handler = handler;\n existing.original = originalHandler;\n existing.options = options;\n return true;\n}\n\nexport function removeDelegatedListener(\n element: Element,\n eventName: string\n): void {\n const existing = delegatedHandlers.get(element);\n if (!existing) {\n return;\n }\n\n if (existing instanceof Map) {\n if (existing.has(eventName)) {\n incDevCounter('listenerRemoves');\n decrementContainerListenerUsage(existing.get(eventName)!);\n }\n existing.delete(eventName);\n if (existing.size === 0) {\n delegatedHandlers.delete(element);\n return;\n }\n if (existing.size === 1) {\n const only = existing.values().next().value as DelegatedHandler;\n delegatedHandlers.set(element, only);\n }\n return;\n }\n\n if (existing.eventName === eventName) {\n incDevCounter('listenerRemoves');\n decrementContainerListenerUsage(existing);\n delegatedHandlers.delete(element);\n }\n}\n\nexport function getDelegatedHandlerForElement(\n element: Element,\n eventName: string\n): DelegatedHandler | undefined {\n const store = delegatedHandlers.get(element);\n if (!store) return undefined;\n if (store instanceof Map) return store.get(eventName);\n return store.eventName === eventName ? store : undefined;\n}\n\nexport function getDelegatedHandlersForElement(\n element: Element\n): Map<string, DelegatedHandler> | undefined {\n const store = delegatedHandlers.get(element);\n if (!store) return undefined;\n if (store instanceof Map) return store;\n return new Map([[store.eventName, store]]);\n}\n\nexport function hasDelegatedHandler(\n element: Element,\n eventName: string\n): boolean {\n return getDelegatedHandlerForElement(element, eventName) !== undefined;\n}\n\nexport function clearDelegatedHandlersForElement(element: Element): void {\n const existing = delegatedHandlers.get(element);\n if (existing instanceof Map) {\n for (const entry of existing.values()) {\n decrementContainerListenerUsage(entry);\n }\n } else if (existing) {\n decrementContainerListenerUsage(existing);\n }\n delegatedHandlers.delete(element);\n}\n\nexport function getDelegatedEventNames(): readonly (keyof DelegatedEventMap)[] {\n return DELEGATED_EVENTS;\n}\n\nexport function isDelegatedEvent(eventName: string): boolean {\n return DELEGATED_EVENTS.includes(eventName as keyof DelegatedEventMap);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwCA,MAAM,mBAAgD;CACpD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAaA,MAAM,oCAAoB,IAAI,QAAwC;AAEtE,IAAI,yBAAyB;AAG7B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O,MAAM,IAAI,SAAS;CACpD,OAAO,MAAM,cAAc,YAAY,QAAQ;AACjD;AAEA,SAAgB,+BACd,SAC2C;CAC3C,MAAM,QAAQ,kBAAkB,IAAI,OAAO;CAC3C,IAAI,CAAC,OAAO,OAAO;CACnB,IAAI,iBAAiB,KAAK,OAAO;CACjC,OAAO,IAAI,IAAI,CAAC,CAAC,MAAM,WAAW,KAAK,CAAC,CAAC;AAC3C;AASA,SAAgB,iCAAiC,SAAwB;CACvE,MAAM,WAAW,kBAAkB,IAAI,OAAO;CAC9C,IAAI,oBAAoB,KACtB,KAAK,MAAM,SAAS,SAAS,OAAO,GAClC,gCAAgC,KAAK;MAElC,IAAI,UACT,gCAAgC,QAAQ;CAE1C,kBAAkB,OAAO,OAAO;AAClC;AAMA,SAAgB,iBAAiB,WAA4B;CAC3D,OAAO,iBAAiB,SAAS,SAAoC;AACvE"}
1
+ {"version":3,"file":"events.js","names":[],"sources":["../../src/runtime/events.ts"],"sourcesContent":["/**\n * Event delegation system for Askr\n *\n * Provides efficient event handling by attaching listeners to a container\n * instead of individual elements. This significantly reduces memory usage\n * and improves performance when many elements have the same event type.\n *\n * Delegated handling is enabled by default. Tests and internal runtime code\n * can still disable or re-enable it when they need to exercise both modes.\n */\n\nimport { globalScheduler } from './scheduler';\nimport { logger } from '../dev/logger';\nimport { incrementPerfMetric } from './perf-metrics';\nimport { incDevCounter } from './dev-namespace';\n\nexport interface DelegatedEventMap {\n click: MouseEvent;\n dblclick: MouseEvent;\n mousedown: MouseEvent;\n mouseup: MouseEvent;\n mouseover: MouseEvent;\n mouseout: MouseEvent;\n mousemove: MouseEvent;\n focus: FocusEvent;\n blur: FocusEvent;\n input: InputEvent;\n change: Event;\n keydown: KeyboardEvent;\n keyup: KeyboardEvent;\n keypress: KeyboardEvent;\n submit: Event;\n scroll: Event;\n wheel: WheelEvent;\n touchstart: TouchEvent;\n touchend: TouchEvent;\n touchmove: TouchEvent;\n touchcancel: TouchEvent;\n}\n\nconst DELEGATED_EVENTS: (keyof DelegatedEventMap)[] = [\n 'click',\n 'dblclick',\n 'mousedown',\n 'mouseup',\n 'mouseover',\n 'mouseout',\n 'mousemove',\n 'focus',\n 'blur',\n 'input',\n 'change',\n 'keydown',\n 'keyup',\n 'keypress',\n 'submit',\n 'scroll',\n 'wheel',\n 'touchstart',\n 'touchend',\n 'touchmove',\n 'touchcancel',\n];\n\ninterface DelegatedHandler {\n handler: EventListener;\n original: EventListener;\n element: Element;\n container: Element;\n eventName: string;\n options?: AddEventListenerOptions;\n}\n\ntype DelegatedHandlerStore = DelegatedHandler | Map<string, DelegatedHandler>;\n\nconst delegatedHandlers = new WeakMap<Element, DelegatedHandlerStore>();\n\nlet eventDelegationEnabled = true;\nlet defaultContainer: Element | null = null;\nlet globalDelegationContainer: Element | null = null;\nconst containerDelegatedListeners = new Map<\n Element,\n Map<string, EventListener>\n>();\nconst containerDelegatedListenerUsage = new Map<Element, Map<string, number>>();\n\nexport function isEventDelegationEnabled(): boolean {\n return eventDelegationEnabled;\n}\n\nexport function disableEventDelegation(): void {\n eventDelegationEnabled = false;\n cleanupAllDelegatedListeners();\n}\n\nexport function enableEventDelegation(container?: Element): void {\n eventDelegationEnabled = true;\n if (container) {\n defaultContainer = container;\n }\n}\n\nexport function setGlobalDelegationContainer(container: Element): void {\n globalDelegationContainer = container;\n}\n\nfunction cleanupAllDelegatedListeners(): void {\n for (const [container, listeners] of containerDelegatedListeners) {\n for (const [eventName, handler] of listeners) {\n container.removeEventListener(eventName, handler);\n }\n }\n containerDelegatedListeners.clear();\n containerDelegatedListenerUsage.clear();\n}\n\nfunction incrementContainerListenerUsage(\n container: Element,\n eventName: string\n): void {\n let usage = containerDelegatedListenerUsage.get(container);\n if (!usage) {\n usage = new Map();\n containerDelegatedListenerUsage.set(container, usage);\n }\n usage.set(eventName, (usage.get(eventName) ?? 0) + 1);\n}\n\nfunction decrementContainerListenerUsage(entry: DelegatedHandler): void {\n const usage = containerDelegatedListenerUsage.get(entry.container);\n if (!usage) {\n return;\n }\n\n const nextCount = (usage.get(entry.eventName) ?? 0) - 1;\n if (nextCount > 0) {\n usage.set(entry.eventName, nextCount);\n return;\n }\n\n usage.delete(entry.eventName);\n const listeners = containerDelegatedListeners.get(entry.container);\n const listener = listeners?.get(entry.eventName);\n if (listener) {\n entry.container.removeEventListener(entry.eventName, listener);\n listeners?.delete(entry.eventName);\n }\n\n if (listeners?.size === 0) {\n containerDelegatedListeners.delete(entry.container);\n }\n if (usage.size === 0) {\n containerDelegatedListenerUsage.delete(entry.container);\n }\n}\n\nfunction getDelegationContainer(): Element | null {\n if (globalDelegationContainer) return globalDelegationContainer;\n if (defaultContainer) return defaultContainer;\n if (typeof document !== 'undefined') return document.body;\n return null;\n}\n\nfunction attachDelegatedListener(\n container: Element,\n element: Element,\n eventName: string,\n handler: EventListener,\n originalHandler: EventListener,\n options?: AddEventListenerOptions\n): void {\n const hadHandler = !!getDelegatedHandlerForElement(element, eventName);\n\n if (!containerDelegatedListeners.has(container)) {\n containerDelegatedListeners.set(container, new Map());\n }\n const containerListeners = containerDelegatedListeners.get(container)!;\n\n if (!containerListeners.has(eventName)) {\n const delegatedHandler = (e: Event) => {\n const target = e.target as Element;\n if (!target) return;\n\n globalScheduler.runInHandlerScope(() => {\n let current: Element | null = target;\n while (current && current !== container) {\n incrementPerfMetric('delegatedAncestorHops');\n const store = delegatedHandlers.get(current);\n const entry = !store\n ? undefined\n : store instanceof Map\n ? store.get(eventName)\n : store.eventName === eventName\n ? store\n : undefined;\n if (entry) {\n try {\n entry.handler(e);\n } catch (error) {\n logger.error('[Askr] Delegated event error:', error);\n }\n }\n\n if (e.cancelBubble) {\n break;\n }\n\n current = current.parentElement;\n }\n }, 'sync');\n };\n\n const passiveOptions = getPassiveOptions(eventName);\n const listenerOptions = passiveOptions ?? options;\n\n container.addEventListener(eventName, delegatedHandler, listenerOptions);\n containerListeners.set(eventName, delegatedHandler);\n }\n\n setDelegatedHandlerForElement(element, {\n handler,\n original: originalHandler,\n element,\n container,\n eventName,\n options,\n });\n if (!hadHandler) {\n incrementContainerListenerUsage(container, eventName);\n }\n}\n\nfunction setDelegatedHandlerForElement(\n element: Element,\n entry: DelegatedHandler\n): void {\n const existing = delegatedHandlers.get(element);\n if (!existing) {\n delegatedHandlers.set(element, entry);\n return;\n }\n\n if (existing instanceof Map) {\n existing.set(entry.eventName, entry);\n return;\n }\n\n if (existing.eventName === entry.eventName) {\n delegatedHandlers.set(element, entry);\n return;\n }\n\n const next = new Map<string, DelegatedHandler>();\n next.set(existing.eventName, existing);\n next.set(entry.eventName, entry);\n delegatedHandlers.set(element, next);\n}\n\nfunction getPassiveOptions(\n eventName: string\n): AddEventListenerOptions | undefined {\n if (\n eventName === 'wheel' ||\n eventName === 'scroll' ||\n eventName.startsWith('touch')\n ) {\n return { passive: true };\n }\n return undefined;\n}\n\nexport function addDelegatedListener(\n element: Element,\n eventName: string,\n handler: EventListener,\n originalHandler: EventListener,\n options?: AddEventListenerOptions\n): void {\n if (!eventDelegationEnabled) return;\n\n const container = getDelegationContainer();\n if (!container) return;\n\n incDevCounter('listenerAdds');\n\n attachDelegatedListener(\n container,\n element,\n eventName,\n handler,\n originalHandler,\n options\n );\n}\n\nexport function updateDelegatedListener(\n element: Element,\n eventName: string,\n handler: EventListener,\n originalHandler: EventListener,\n options?: AddEventListenerOptions\n): boolean {\n const existing = getDelegatedHandlerForElement(element, eventName);\n if (!existing) {\n return false;\n }\n\n const container = getDelegationContainer();\n if (\n !container ||\n existing.container !== container ||\n !containerDelegatedListeners.get(existing.container)?.has(eventName)\n ) {\n removeDelegatedListener(element, eventName);\n return false;\n }\n\n existing.handler = handler;\n existing.original = originalHandler;\n existing.options = options;\n return true;\n}\n\nexport function removeDelegatedListener(\n element: Element,\n eventName: string\n): void {\n const existing = delegatedHandlers.get(element);\n if (!existing) {\n return;\n }\n\n if (existing instanceof Map) {\n if (existing.has(eventName)) {\n incDevCounter('listenerRemoves');\n decrementContainerListenerUsage(existing.get(eventName)!);\n }\n existing.delete(eventName);\n if (existing.size === 0) {\n delegatedHandlers.delete(element);\n return;\n }\n if (existing.size === 1) {\n const only = existing.values().next().value as DelegatedHandler;\n delegatedHandlers.set(element, only);\n }\n return;\n }\n\n if (existing.eventName === eventName) {\n incDevCounter('listenerRemoves');\n decrementContainerListenerUsage(existing);\n delegatedHandlers.delete(element);\n }\n}\n\nexport function getDelegatedHandlerForElement(\n element: Element,\n eventName: string\n): DelegatedHandler | undefined {\n const store = delegatedHandlers.get(element);\n if (!store) return undefined;\n if (store instanceof Map) return store.get(eventName);\n return store.eventName === eventName ? store : undefined;\n}\n\nexport function getDelegatedHandlersForElement(\n element: Element\n): Map<string, DelegatedHandler> | undefined {\n const store = delegatedHandlers.get(element);\n if (!store) return undefined;\n if (store instanceof Map) return store;\n return new Map([[store.eventName, store]]);\n}\n\nexport function hasDelegatedHandler(\n element: Element,\n eventName: string\n): boolean {\n return getDelegatedHandlerForElement(element, eventName) !== undefined;\n}\n\nexport function clearDelegatedHandlersForElement(element: Element): void {\n const existing = delegatedHandlers.get(element);\n if (existing instanceof Map) {\n for (const entry of existing.values()) {\n decrementContainerListenerUsage(entry);\n }\n } else if (existing) {\n decrementContainerListenerUsage(existing);\n }\n delegatedHandlers.delete(element);\n}\n\nexport function getDelegatedEventNames(): readonly (keyof DelegatedEventMap)[] {\n return DELEGATED_EVENTS;\n}\n\nexport function isDelegatedEvent(eventName: string): boolean {\n return DELEGATED_EVENTS.includes(eventName as keyof DelegatedEventMap);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwCA,MAAM,mBAAgD;CACpD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAaA,MAAM,oCAAoB,IAAI,QAAwC;AAEtE,IAAI,yBAAyB;AAG7B,MAAM,8CAA8B,IAAI,IAGtC;AACF,MAAM,kDAAkC,IAAI,IAAkC;AAE9E,SAAgB,2BAAoC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