@askrjs/askr 0.0.35 → 0.0.36

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 (146) hide show
  1. package/dist/bench/components/benchmark-row.js.map +1 -1
  2. package/dist/bench/components/benchmark-table.js.map +1 -1
  3. package/dist/benchmark.js +2 -2
  4. package/dist/benchmark.js.map +1 -1
  5. package/dist/bin/askr-ssg.js.map +1 -1
  6. package/dist/boot/index.d.ts.map +1 -1
  7. package/dist/boot/index.js +9 -29
  8. package/dist/boot/index.js.map +1 -1
  9. package/dist/common/control.js.map +1 -1
  10. package/dist/common/env.js.map +1 -1
  11. package/dist/common/ssr-errors.js.map +1 -1
  12. package/dist/common/vnode.js.map +1 -1
  13. package/dist/components/error-boundary.js.map +1 -1
  14. package/dist/components/link.js.map +1 -1
  15. package/dist/control/case.js.map +1 -1
  16. package/dist/control/for.js.map +1 -1
  17. package/dist/control/shared.js.map +1 -1
  18. package/dist/control/show.js.map +1 -1
  19. package/dist/data/index.d.ts.map +1 -1
  20. package/dist/data/index.js +165 -23
  21. package/dist/data/index.js.map +1 -1
  22. package/dist/dev/invariant.js.map +1 -1
  23. package/dist/dev/logger.js.map +1 -1
  24. package/dist/foundations/icon/icon.js.map +1 -1
  25. package/dist/foundations/interactions/dismissable.js.map +1 -1
  26. package/dist/foundations/interactions/focusable.js.map +1 -1
  27. package/dist/foundations/interactions/hoverable.js.map +1 -1
  28. package/dist/foundations/interactions/interaction-policy.js.map +1 -1
  29. package/dist/foundations/interactions/pressable.js.map +1 -1
  30. package/dist/foundations/interactions/roving-focus.js.map +1 -1
  31. package/dist/foundations/state/controllable.js.map +1 -1
  32. package/dist/foundations/structures/collection.js.map +1 -1
  33. package/dist/foundations/structures/layer.js.map +1 -1
  34. package/dist/foundations/structures/layout.js.map +1 -1
  35. package/dist/foundations/structures/portal.js.map +1 -1
  36. package/dist/foundations/structures/presence.js.map +1 -1
  37. package/dist/foundations/structures/slot.js.map +1 -1
  38. package/dist/foundations/utilities/aria.js.map +1 -1
  39. package/dist/foundations/utilities/compose-handlers.js.map +1 -1
  40. package/dist/foundations/utilities/compose-ref.js.map +1 -1
  41. package/dist/foundations/utilities/merge-props.js.map +1 -1
  42. package/dist/foundations/utilities/use-id.js.map +1 -1
  43. package/dist/fx/fx.js.map +1 -1
  44. package/dist/fx/timing.js.map +1 -1
  45. package/dist/index.d.ts +2 -2
  46. package/dist/index.js +2 -2
  47. package/dist/index.js.map +1 -1
  48. package/dist/jsx/utils.js.map +1 -1
  49. package/dist/jsx-dev-runtime.js.map +1 -1
  50. package/dist/jsx-runtime.js.map +1 -1
  51. package/dist/renderer/children.js.map +1 -1
  52. package/dist/renderer/cleanup.js.map +1 -1
  53. package/dist/renderer/dom.js +128 -53
  54. package/dist/renderer/dom.js.map +1 -1
  55. package/dist/renderer/evaluate.js +7 -0
  56. package/dist/renderer/evaluate.js.map +1 -1
  57. package/dist/renderer/fastpath.js.map +1 -1
  58. package/dist/renderer/index.js.map +1 -1
  59. package/dist/renderer/keyed.js +1 -1
  60. package/dist/renderer/keyed.js.map +1 -1
  61. package/dist/renderer/reconcile.js.map +1 -1
  62. package/dist/renderer/utils.js.map +1 -1
  63. package/dist/router/index.d.ts +2 -2
  64. package/dist/router/index.js +2 -2
  65. package/dist/router/match.js.map +1 -1
  66. package/dist/router/navigate.d.ts.map +1 -1
  67. package/dist/router/navigate.js +4 -2
  68. package/dist/router/navigate.js.map +1 -1
  69. package/dist/router/policy.js.map +1 -1
  70. package/dist/router/route-context.js.map +1 -1
  71. package/dist/router/route.d.ts +1 -1
  72. package/dist/router/route.d.ts.map +1 -1
  73. package/dist/router/route.js +3 -34
  74. package/dist/router/route.js.map +1 -1
  75. package/dist/runtime/child-scope.d.ts +1 -0
  76. package/dist/runtime/child-scope.d.ts.map +1 -1
  77. package/dist/runtime/child-scope.js +2 -0
  78. package/dist/runtime/child-scope.js.map +1 -1
  79. package/dist/runtime/component.js +1 -1
  80. package/dist/runtime/component.js.map +1 -1
  81. package/dist/runtime/context.js.map +1 -1
  82. package/dist/runtime/control.js.map +1 -1
  83. package/dist/runtime/derive.d.ts +2 -1
  84. package/dist/runtime/derive.d.ts.map +1 -1
  85. package/dist/runtime/derive.js +15 -10
  86. package/dist/runtime/derive.js.map +1 -1
  87. package/dist/runtime/dev-namespace.js.map +1 -1
  88. package/dist/runtime/effect.d.ts.map +1 -1
  89. package/dist/runtime/effect.js +34 -9
  90. package/dist/runtime/effect.js.map +1 -1
  91. package/dist/runtime/events.js.map +1 -1
  92. package/dist/runtime/execution-model.js.map +1 -1
  93. package/dist/runtime/fastlane.js.map +1 -1
  94. package/dist/runtime/for-bench.d.ts +1 -1
  95. package/dist/runtime/for-bench.d.ts.map +1 -1
  96. package/dist/runtime/for-bench.js +15 -14
  97. package/dist/runtime/for-bench.js.map +1 -1
  98. package/dist/runtime/for.d.ts +1 -0
  99. package/dist/runtime/for.d.ts.map +1 -1
  100. package/dist/runtime/for.js +63 -16
  101. package/dist/runtime/for.js.map +1 -1
  102. package/dist/runtime/operations.d.ts.map +1 -1
  103. package/dist/runtime/operations.js +9 -7
  104. package/dist/runtime/operations.js.map +1 -1
  105. package/dist/runtime/perf-metrics.js +8 -2
  106. package/dist/runtime/perf-metrics.js.map +1 -1
  107. package/dist/runtime/readable.js.map +1 -1
  108. package/dist/runtime/resource-cell.js +3 -2
  109. package/dist/runtime/resource-cell.js.map +1 -1
  110. package/dist/runtime/scheduler.d.ts +0 -1
  111. package/dist/runtime/scheduler.d.ts.map +1 -1
  112. package/dist/runtime/scheduler.js +6 -19
  113. package/dist/runtime/scheduler.js.map +1 -1
  114. package/dist/runtime/selector.d.ts.map +1 -1
  115. package/dist/runtime/selector.js +6 -4
  116. package/dist/runtime/selector.js.map +1 -1
  117. package/dist/runtime/snapshot-source.d.ts +10 -0
  118. package/dist/runtime/snapshot-source.d.ts.map +1 -0
  119. package/dist/runtime/snapshot-source.js +17 -0
  120. package/dist/runtime/snapshot-source.js.map +1 -0
  121. package/dist/runtime/ssr-bridge.js.map +1 -1
  122. package/dist/runtime/state.d.ts.map +1 -1
  123. package/dist/runtime/state.js +1 -5
  124. package/dist/runtime/state.js.map +1 -1
  125. package/dist/ssg/batch-render.js.map +1 -1
  126. package/dist/ssg/create-static-gen.js.map +1 -1
  127. package/dist/ssg/generate-metadata.js.map +1 -1
  128. package/dist/ssg/incremental-manifest.js.map +1 -1
  129. package/dist/ssg/resolve-ssg-data.js.map +1 -1
  130. package/dist/ssg/route-utils.js.map +1 -1
  131. package/dist/ssg/write-static-files.js.map +1 -1
  132. package/dist/ssr/attrs.js.map +1 -1
  133. package/dist/ssr/context.d.ts +1 -0
  134. package/dist/ssr/context.d.ts.map +1 -1
  135. package/dist/ssr/context.js +3 -0
  136. package/dist/ssr/context.js.map +1 -1
  137. package/dist/ssr/escape.js +56 -16
  138. package/dist/ssr/escape.js.map +1 -1
  139. package/dist/ssr/index.d.ts.map +1 -1
  140. package/dist/ssr/index.js +15 -3
  141. package/dist/ssr/index.js.map +1 -1
  142. package/dist/ssr/render-keys.js.map +1 -1
  143. package/dist/ssr/sink.js.map +1 -1
  144. package/dist/ssr/stream-render.js +14 -2
  145. package/dist/ssr/stream-render.js.map +1 -1
  146. package/package.json +8 -6
@@ -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 { getCurrentComponentInstance } from './component';\nimport type { ComponentInstance } from './component';\n\nexport type ContextKey = symbol;\n\n// Lightweight VNode definition used for JSX typing in this module\ntype VNode = {\n type: string;\n props?: Record<string, unknown>;\n children?: (string | VNode | null | undefined | false)[];\n};\n\n// Union of allowed render return values (text, vnode, JSX element, etc.)\ntype Renderable =\n | JSXElement\n | VNode\n | string\n | number\n | null\n | undefined\n | false;\n\nexport interface Context<T> {\n readonly key: ContextKey;\n readonly defaultValue: T;\n // A Scope is a JSX-style element factory returning a JSXElement (component invocation)\n readonly Scope: (props: { value: unknown; children?: unknown }) => JSXElement;\n}\n\nexport interface ContextFrame {\n parent: ContextFrame | null;\n // Lazily allocate `values` Map only when a provider sets values or a read occurs.\n values: Map<ContextKey, unknown> | null;\n}\n\n// Symbol to mark vnodes that need frame restoration\nexport const CONTEXT_FRAME_SYMBOL = Symbol('__tempoContextFrame__');\n\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: { value: unknown; children?: unknown }): JSXElement => {\n // Scope component: accepts an unknown value (tests often pass loosely typed values)\n // Cast to the expected T at the call site to preserve runtime behavior.\n const value = props.value as T;\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\nexport function readContext<T>(context: Context<T>): T {\n // Check render frame first (components), then async resource frame (resources)\n const frame = currentContextFrame || currentAsyncResourceFrame;\n\n if (!frame) {\n throw new Error(\n 'readContext() can only be called during component render or async resource execution. ' +\n 'Ensure you are calling this from inside your component or resource function.'\n );\n }\n\n let current: ContextFrame | null = frame;\n while (current) {\n // `values` may be null when no provider has created it yet — treat as empty\n const values = current.values;\n if (values && values.has(context.key)) {\n return values.get(context.key) as T;\n }\n current = current.parent;\n }\n return context.defaultValue;\n}\n\n/**\n * Internal component that manages context frame\n * Used by Context.Scope to provide shadowed value to children\n */\nfunction ContextScopeComponent(props: Props): Renderable {\n // Extract expected properties (we accept a loose shape so this can be used as a component type)\n const key = props['key'] as ContextKey;\n const value = props['value'];\n const children = props['children'] as Renderable;\n\n // Create a new frame with this value\n const instance = getCurrentComponentInstance();\n const parentFrame: ContextFrame | null = (() => {\n // Prefer the live render frame.\n // Note: the runtime executes component functions inside an empty \"render frame\"\n // whose parent points at the nearest provider chain. Even if this frame has no\n // values, it must still be used to preserve the parent linkage.\n if (currentContextFrame) return currentContextFrame;\n\n // If there is no live render frame (should be rare), fall back to the\n // instance's owner frame.\n if (instance && instance.ownerFrame) return instance.ownerFrame;\n\n // Do NOT fall back to the async snapshot stack here: that stack represents\n // unrelated async continuations and must not affect lexical provider chaining.\n return null;\n })();\n\n const newFrame: ContextFrame = {\n parent: parentFrame,\n values: new Map([[key, value]]),\n };\n\n // 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 (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 (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":";;;AA6DA,MAAa,uBAAuB,OAAO,wBAAwB;AAMnE,MAAM,qCAAqB,IAAI,SAA+B;AAE9D,SAAgB,qBAAqB,MAAyC;AAC5E,KAAI,OAAO,SAAS,YAAY,SAAS,KACvC;CAGF,MAAM,aAAa;AACnB,QAAO,mBAAmB,IAAI,KAAK,IAAI,WAAW;;AAGpD,SAAgB,0BACd,MACA,OACA,YAAY,OACN;AACN,KAAI,OAAO,SAAS,YAAY,SAAS,KACvC;AAGF,KAAI,CAAC,aAAa,qBAAqB,KAAK,CAC1C;CAGF,MAAM,aAAa;AACnB,KAAI,OAAO,UAAU,eAAe,KAAK,MAAM,qBAAqB,CAClE,KAAI;AACF,aAAW,wBAAwB;AACnC;SACM;AAKV,KAAI,OAAO,aAAa,KAAK,CAC3B,KAAI;AACF,SAAO,eAAe,MAAM,sBAAsB;GAChD,OAAO;GACP,UAAU;GACV,YAAY;GACZ,cAAc;GACf,CAAC;AACF;SACM;AAKV,oBAAmB,IAAI,MAAM,MAAM;;AAGrC,SAAS,YAAY,OAAyB;AAC5C,KAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,MAAM,CACrE,QAAO;CAGT,MAAM,cAAc;AACpB,KAAI,YAAY,aAAa,aAC3B,QAAO;AAGT,QACE,UAAU,gBACT,WAAW,eAAe,cAAc;;AAI7C,SAAS,qBACP,OACA,OACA,WACM;AACN,KAAI,MAAM,QAA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cAAc,MAAkB,OAAiC;AACxE,QAAO,8BAA8B,MAAM,OAAO,KAAK;;;;;;;;;;;AAYzD,SAAS,4BAA4B,OAItB;CACb,MAAM,EAAE,IAAI,YAAY;CAMxB,MAAM,MAAM,YAAY,eAAe,IAAI,CAAC;AAG5C,KAAI,IAAK,QAAO,cAAc,KAAK,QAAQ;AAC3C,QAAO;;;;;AAgCT,SAAgB,yBAA8C;AAC5D,QAAO"}
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 { getCurrentComponentInstance } from './component';\nimport type { ComponentInstance } from './component';\n\nexport type ContextKey = symbol;\n\n// Lightweight VNode definition used for JSX typing in this module\ntype VNode = {\n type: string;\n props?: Record<string, unknown>;\n children?: (string | VNode | null | undefined | false)[];\n};\n\n// Union of allowed render return values (text, vnode, JSX element, etc.)\ntype Renderable =\n | JSXElement\n | VNode\n | string\n | number\n | null\n | undefined\n | false;\n\nexport interface Context<T> {\n readonly key: ContextKey;\n readonly defaultValue: T;\n // A Scope is a JSX-style element factory returning a JSXElement (component invocation)\n readonly Scope: (props: { value: unknown; children?: unknown }) => JSXElement;\n}\n\nexport interface ContextFrame {\n parent: ContextFrame | null;\n // Lazily allocate `values` Map only when a provider sets values or a read occurs.\n values: Map<ContextKey, unknown> | null;\n}\n\n// Symbol to mark vnodes that need frame restoration\nexport const CONTEXT_FRAME_SYMBOL = Symbol('__tempoContextFrame__');\n\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: { value: unknown; children?: unknown }): JSXElement => {\n // Scope component: accepts an unknown value (tests often pass loosely typed values)\n // Cast to the expected T at the call site to preserve runtime behavior.\n const value = props.value as T;\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\nexport function readContext<T>(context: Context<T>): T {\n // Check render frame first (components), then async resource frame (resources)\n const frame = currentContextFrame || currentAsyncResourceFrame;\n\n if (!frame) {\n throw new Error(\n 'readContext() can only be called during component render or async resource execution. ' +\n 'Ensure you are calling this from inside your component or resource function.'\n );\n }\n\n let current: ContextFrame | null = frame;\n while (current) {\n // `values` may be null when no provider has created it yet — treat as empty\n const values = current.values;\n if (values && values.has(context.key)) {\n return values.get(context.key) as T;\n }\n current = current.parent;\n }\n return context.defaultValue;\n}\n\n/**\n * Internal component that manages context frame\n * Used by Context.Scope to provide shadowed value to children\n */\nfunction ContextScopeComponent(props: Props): Renderable {\n // Extract expected properties (we accept a loose shape so this can be used as a component type)\n const key = props['key'] as ContextKey;\n const value = props['value'];\n const children = props['children'] as Renderable;\n\n // Create a new frame with this value\n const instance = getCurrentComponentInstance();\n const parentFrame: ContextFrame | null = (() => {\n // Prefer the live render frame.\n // Note: the runtime executes component functions inside an empty \"render frame\"\n // whose parent points at the nearest provider chain. Even if this frame has no\n // values, it must still be used to preserve the parent linkage.\n if (currentContextFrame) return currentContextFrame;\n\n // If there is no live render frame (should be rare), fall back to the\n // instance's owner frame.\n if (instance && instance.ownerFrame) return instance.ownerFrame;\n\n // Do NOT fall back to the async snapshot stack here: that stack represents\n // unrelated async continuations and must not affect lexical provider chaining.\n return null;\n })();\n\n const newFrame: ContextFrame = {\n parent: parentFrame,\n values: new Map([[key, value]]),\n };\n\n // 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 (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 (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":";;;AA6DA,MAAa,uBAAuB,OAAO,wBAAwB;AAMnE,MAAM,qCAAqB,IAAI,SAA+B;AAE9D,SAAgB,qBAAqB,MAAyC;CAC5E,IAAI,OAAO,SAAS,YAAY,SAAS,MACvC;CAGF,MAAM,aAAa;C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CAEvD,MAAM,MAAM,MAAM;CAClB,MAAM,QAAQ,MAAM;CACpB,MAAM,WAAW,MAAM;CAGvB,MAAM,WAAW,6BAA6B;CAiB9C,MAAM,WAAyB;EAC7B,eAjB8C;GAK9C,IAAI,qBAAqB,OAAO;GAIhC,IAAI,YAAY,SAAS,YAAY,OAAO,SAAS;GAIrD,OAAO;MAIC;EACR,QAAQ,IAAI,IAAI,CAAC,CAAC,KAAK,MAAM,CAAC,CAAC;EAChC;CAGD,SAAS,2BACP,IACA,OACA,OACY;EACZ,OAAO;GACL,MAAM;GACN,OAAO;IAAE;IAAI,SAAS;IAAO,SAAS;IAAO;GAC9C;;CAKH,IAAI,MAAM,QAAQ,SAAS,EAGzB,OAAO,6BACL,UACA,SAAS,KAAK,UAAU;EACtB,IAAI,OAAO,UAAU,YACnB,OAAO,2BACL,OACA,UACA,6BAA6B,CAC9B;EAEH,OAAO,cAAc,OAAO,SAAS;GACrC,CACH;MACI,IAAI,OAAO,aAAa,YAM7B,OAAO,2BACL,UACA,UACA,6BAA6B,CAC9B;MACI,IAAI,UACT,OAAO,cAAc,UAAU,SAAS;CAG1C,OAAO;;;;;;AAOT,SAAS,cAAc,MAAkB,OAAiC;CACxE,OAAO,8BAA8B,MAAM,OAAO,KAAK;;;;;;;;;;;AAYzD,SAAS,4BAA4B,OAItB;CACb,MAAM,EAAE,IAAI,YAAY;CAMxB,MAAM,MAAM,YAAY,eAAe,IAAI,CAAC;CAG5C,IAAI,KAAK,OAAO,cAAc,KAAK,QAAQ;CAC3C,OAAO;;;;;AAgCT,SAAgB,yBAA8C;CAC5D,OAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"control.js","names":[],"sources":["../../src/runtime/control.ts"],"sourcesContent":["import type { VNode } from '../common/vnode';\nimport {\n createChildScope,\n disposeChildScope,\n type ChildScope,\n} from './child-scope';\nimport { getCurrentInstance, type ComponentInstance } from './component';\nimport type { ForState } from './for';\n\nexport interface MatchBranch {\n key: string | number;\n render: () => VNode;\n when: unknown;\n}\n\ninterface BranchControlStateBase {\n activeKey: string | number | null;\n activeScope: ChildScope | null;\n activeVNodes: VNode[];\n lastRemovedNodes: Node[];\n parentInstance: ComponentInstance | null;\n _enqueueBoundaryCommit?: (() => void) | null;\n _hasPendingBoundaryCommit?: boolean;\n}\n\nexport interface ShowState extends BranchControlStateBase {\n kind: 'show';\n fallbackScope: ChildScope | null;\n renderFallback: (() => VNode) | null;\n renderTruthy: ((value: unknown) => VNode) | (() => VNode);\n selectedValue: unknown;\n truthyScope: ChildScope | null;\n}\n\nexport interface CaseState extends BranchControlStateBase {\n kind: 'case';\n fallback: (() => VNode) | null;\n matches: MatchBranch[];\n}\n\nexport type ControlBoundaryState = ForState<unknown> | ShowState | CaseState;\n\nconst SHOW_TRUTHY_KEY = '__show-truthy__';\nconst SHOW_FALLBACK_KEY = '__show-fallback__';\nconst CASE_FALLBACK_KEY = '__case-fallback__';\n\nfunction disposeBranchScope(\n state: BranchControlStateBase,\n scope: ChildScope | null\n): void {\n if (!scope) {\n return;\n }\n const removedDom = scope.dom;\n disposeChildScope(scope);\n if (removedDom) {\n state.lastRemovedNodes.push(removedDom);\n }\n}\n\nfunction createBranchScope(\n state: BranchControlStateBase,\n key: string | number\n): ChildScope {\n return createChildScope(state.parentInstance, key, () => {\n if (state._enqueueBoundaryCommit) {\n state._enqueueBoundaryCommit();\n return;\n }\n\n state.parentInstance?._enqueueRun?.();\n });\n}\n\nexport function createShowState(\n value: unknown,\n renderTruthy: ShowState['renderTruthy'],\n renderFallback: ShowState['renderFallback']\n): ShowState {\n return {\n kind: 'show',\n activeKey: null,\n activeScope: null,\n activeVNodes: [],\n fallbackScope: null,\n lastRemovedNodes: [],\n parentInstance: getCurrentInstance(),\n _enqueueBoundaryCommit: null,\n _hasPendingBoundaryCommit: false,\n renderFallback,\n renderTruthy,\n selectedValue: value,\n truthyScope: null,\n };\n}\n\nexport function evaluateShowState(state: ShowState): VNode[] {\n state.lastRemovedNodes = [];\n\n if (state.selectedValue) {\n if (state.fallbackScope) {\n disposeBranchScope(state, state.fallbackScope);\n state.fallbackScope = null;\n }\n\n const truthyScope =\n state.truthyScope ?? createBranchScope(state, SHOW_TRUTHY_KEY);\n state.truthyScope = truthyScope;\n state.activeScope = truthyScope;\n state.activeKey = SHOW_TRUTHY_KEY;\n\n const vnode = truthyScope.render(() =>\n state.renderTruthy(state.selectedValue)\n );\n state.activeVNodes = vnode == null || vnode === false ? [] : [vnode];\n return state.activeVNodes;\n }\n\n if (state.truthyScope) {\n disposeBranchScope(state, state.truthyScope);\n state.truthyScope = null;\n }\n\n if (!state.renderFallback) {\n if (state.fallbackScope) {\n disposeBranchScope(state, state.fallbackScope);\n state.fallbackScope = null;\n }\n state.activeKey = null;\n state.activeScope = null;\n state.activeVNodes = [];\n return state.activeVNodes;\n }\n\n const fallbackScope =\n state.fallbackScope ?? createBranchScope(state, SHOW_FALLBACK_KEY);\n state.fallbackScope = fallbackScope;\n state.activeScope = fallbackScope;\n state.activeKey = SHOW_FALLBACK_KEY;\n\n const vnode = fallbackScope.render(state.renderFallback);\n state.activeVNodes = vnode == null || vnode === false ? [] : [vnode];\n return state.activeVNodes;\n}\n\nexport function clearShowDomUpdateState(state: ShowState): void {\n if (state.truthyScope) {\n state.truthyScope.needsDomUpdate = false;\n }\n if (state.fallbackScope) {\n state.fallbackScope.needsDomUpdate = false;\n }\n state.lastRemovedNodes = [];\n}\n\nexport function createCaseState(\n matches: MatchBranch[],\n fallback: (() => VNode) | null\n): CaseState {\n return {\n kind: 'case',\n activeKey: null,\n activeScope: null,\n activeVNodes: [],\n fallback,\n lastRemovedNodes: [],\n matches,\n parentInstance: getCurrentInstance(),\n _enqueueBoundaryCommit: null,\n _hasPendingBoundaryCommit: false,\n };\n}\n\nexport function evaluateCaseState(state: CaseState): VNode[] {\n state.lastRemovedNodes = [];\n\n const selectedMatch =\n state.matches.find((candidate) => Boolean(candidate.when)) ?? null;\n const nextKey =\n selectedMatch?.key ?? (state.fallback ? CASE_FALLBACK_KEY : null);\n\n if (nextKey === null) {\n if (state.activeScope) {\n disposeBranchScope(state, state.activeScope);\n }\n state.activeKey = null;\n state.activeScope = null;\n state.activeVNodes = [];\n return state.activeVNodes;\n }\n\n if (state.activeScope && state.activeKey !== nextKey) {\n disposeBranchScope(state, state.activeScope);\n state.activeScope = null;\n }\n\n const activeScope = state.activeScope ?? createBranchScope(state, nextKey);\n state.activeKey = nextKey;\n state.activeScope = activeScope;\n\n const renderBranch = selectedMatch?.render ?? state.fallback;\n const vnode = renderBranch ? activeScope.render(renderBranch) : null;\n state.activeVNodes = vnode == null || vnode === false ? [] : [vnode];\n return state.activeVNodes;\n}\n\nexport function clearCaseDomUpdateState(state: CaseState): void {\n if (state.activeScope) {\n state.activeScope.needsDomUpdate = false;\n }\n state.lastRemovedNodes = [];\n}\n"],"mappings":";;;AA0CA,MAAM,kBAAkB;AACxB,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAE1B,SAAS,mBACP,OACA,OACM;AACN,KAAI,CAAC,MACH;CAEF,MAAM,aAAa,MAAM;AACzB,mBAAkB,MAAM;AACxB,KAAI,WACF,OAAM,iBAAiB,KAAK,WAAW;;AAI3C,SAAS,kBACP,OACA,KACY;AACZ,QAAO,iBAAiB,MAAM,gBAAgB,WAAW;AACvD,MAAI,MAAM,wBAAwB;AAChC,SAAM,wBAAwB;AAC9B;;AAGF,QAAM,gBAAgB,eAAe;GACrC;;AAGJ,SAAgB,gBACd,OACA,cACA,gBACW;AACX,QAAO;EACL,MAAM;EACN,WAAW;EACX,aAAa;EACb,cAAc,EAAE;EAChB,eAAe;EACf,kBAAkB,EAAE;EACpB,gBAAgB,oBAAoB;EACpC,wBAAwB;EACxB,2BAA2B;EAC3B;EACA;EACA,eAAe;EACf,aAAa;EACd;;AAGH,SAAgB,kBAAkB,OAA2B;AAC3D,OAAM,mBAAmB,EAAE;AAE3B,KAAI,MAAM,eAAe;AACvB,MAAI,MAAM,eAAe;AACvB,sBAAmB,OAAO,MA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AAQ,UAAU,KAAK,CAAC,IAAI;CAChE,MAAM,UACJ,eAAe,QAAQ,MAAM,WAAW,oBAAoB;AAE9D,KAAI,YAAY,MAAM;AACpB,MAAI,MAAM,YACR,oBAAmB,OAAO,MAAM,YAAY;AAE9C,QAAM,YAAY;AAClB,QAAM,cAAc;AACpB,QAAM,eAAe,EAAE;AACvB,SAAO,MAAM;;AAGf,KAAI,MAAM,eAAe,MAAM,cAAc,SAAS;AACpD,qBAAmB,OAAO,MAAM,YAAY;AAC5C,QAAM,cAAc;;CAGtB,MAAM,cAAc,MAAM,eAAe,kBAAkB,OAAO,QAAQ;AAC1E,OAAM,YAAY;AAClB,OAAM,cAAc;CAEpB,MAAM,eAAe,eAAe,UAAU,MAAM;CACpD,MAAM,QAAQ,eAAe,YAAY,OAAO,aAAa,GAAG;AAChE,OAAM,eAAe,SAAS,QAAQ,UAAU,QAAQ,EAAE,GAAG,CAAC,MAAM;AACpE,QAAO,MAAM;;AAGf,SAAgB,wBAAwB,OAAwB;AAC9D,KAAI,MAAM,YACR,OAAM,YAAY,iBAAiB;AAErC,OAAM,mBAAmB,EAAE"}
1
+ {"version":3,"file":"control.js","names":[],"sources":["../../src/runtime/control.ts"],"sourcesContent":["import type { VNode } from '../common/vnode';\nimport {\n createChildScope,\n disposeChildScope,\n type ChildScope,\n} from './child-scope';\nimport { getCurrentInstance, type ComponentInstance } from './component';\nimport type { ForState } from './for';\n\nexport interface MatchBranch {\n key: string | number;\n render: () => VNode;\n when: unknown;\n}\n\ninterface BranchControlStateBase {\n activeKey: string | number | null;\n activeScope: ChildScope | null;\n activeVNodes: VNode[];\n lastRemovedNodes: Node[];\n parentInstance: ComponentInstance | null;\n _enqueueBoundaryCommit?: (() => void) | null;\n _hasPendingBoundaryCommit?: boolean;\n}\n\nexport interface ShowState extends BranchControlStateBase {\n kind: 'show';\n fallbackScope: ChildScope | null;\n renderFallback: (() => VNode) | null;\n renderTruthy: ((value: unknown) => VNode) | (() => VNode);\n selectedValue: unknown;\n truthyScope: ChildScope | null;\n}\n\nexport interface CaseState extends BranchControlStateBase {\n kind: 'case';\n fallback: (() => VNode) | null;\n matches: MatchBranch[];\n}\n\nexport type ControlBoundaryState = ForState<unknown> | ShowState | CaseState;\n\nconst SHOW_TRUTHY_KEY = '__show-truthy__';\nconst SHOW_FALLBACK_KEY = '__show-fallback__';\nconst CASE_FALLBACK_KEY = '__case-fallback__';\n\nfunction disposeBranchScope(\n state: BranchControlStateBase,\n scope: ChildScope | null\n): void {\n if (!scope) {\n return;\n }\n const removedDom = scope.dom;\n disposeChildScope(scope);\n if (removedDom) {\n state.lastRemovedNodes.push(removedDom);\n }\n}\n\nfunction createBranchScope(\n state: BranchControlStateBase,\n key: string | number\n): ChildScope {\n return createChildScope(state.parentInstance, key, () => {\n if (state._enqueueBoundaryCommit) {\n state._enqueueBoundaryCommit();\n return;\n }\n\n state.parentInstance?._enqueueRun?.();\n });\n}\n\nexport function createShowState(\n value: unknown,\n renderTruthy: ShowState['renderTruthy'],\n renderFallback: ShowState['renderFallback']\n): ShowState {\n return {\n kind: 'show',\n activeKey: null,\n activeScope: null,\n activeVNodes: [],\n fallbackScope: null,\n lastRemovedNodes: [],\n parentInstance: getCurrentInstance(),\n _enqueueBoundaryCommit: null,\n _hasPendingBoundaryCommit: false,\n renderFallback,\n renderTruthy,\n selectedValue: value,\n truthyScope: null,\n };\n}\n\nexport function evaluateShowState(state: ShowState): VNode[] {\n state.lastRemovedNodes = [];\n\n if (state.selectedValue) {\n if (state.fallbackScope) {\n disposeBranchScope(state, state.fallbackScope);\n state.fallbackScope = null;\n }\n\n const truthyScope =\n state.truthyScope ?? createBranchScope(state, SHOW_TRUTHY_KEY);\n state.truthyScope = truthyScope;\n state.activeScope = truthyScope;\n state.activeKey = SHOW_TRUTHY_KEY;\n\n const vnode = truthyScope.render(() =>\n state.renderTruthy(state.selectedValue)\n );\n state.activeVNodes = vnode == null || vnode === false ? [] : [vnode];\n return state.activeVNodes;\n }\n\n if (state.truthyScope) {\n disposeBranchScope(state, state.truthyScope);\n state.truthyScope = null;\n }\n\n if (!state.renderFallback) {\n if (state.fallbackScope) {\n disposeBranchScope(state, state.fallbackScope);\n state.fallbackScope = null;\n }\n state.activeKey = null;\n state.activeScope = null;\n state.activeVNodes = [];\n return state.activeVNodes;\n }\n\n const fallbackScope =\n state.fallbackScope ?? createBranchScope(state, SHOW_FALLBACK_KEY);\n state.fallbackScope = fallbackScope;\n state.activeScope = fallbackScope;\n state.activeKey = SHOW_FALLBACK_KEY;\n\n const vnode = fallbackScope.render(state.renderFallback);\n state.activeVNodes = vnode == null || vnode === false ? [] : [vnode];\n return state.activeVNodes;\n}\n\nexport function clearShowDomUpdateState(state: ShowState): void {\n if (state.truthyScope) {\n state.truthyScope.needsDomUpdate = false;\n }\n if (state.fallbackScope) {\n state.fallbackScope.needsDomUpdate = false;\n }\n state.lastRemovedNodes = [];\n}\n\nexport function createCaseState(\n matches: MatchBranch[],\n fallback: (() => VNode) | null\n): CaseState {\n return {\n kind: 'case',\n activeKey: null,\n activeScope: null,\n activeVNodes: [],\n fallback,\n lastRemovedNodes: [],\n matches,\n parentInstance: getCurrentInstance(),\n _enqueueBoundaryCommit: null,\n _hasPendingBoundaryCommit: false,\n };\n}\n\nexport function evaluateCaseState(state: CaseState): VNode[] {\n state.lastRemovedNodes = [];\n\n const selectedMatch =\n state.matches.find((candidate) => Boolean(candidate.when)) ?? null;\n const nextKey =\n selectedMatch?.key ?? (state.fallback ? CASE_FALLBACK_KEY : null);\n\n if (nextKey === null) {\n if (state.activeScope) {\n disposeBranchScope(state, state.activeScope);\n }\n state.activeKey = null;\n state.activeScope = null;\n state.activeVNodes = [];\n return state.activeVNodes;\n }\n\n if (state.activeScope && state.activeKey !== nextKey) {\n disposeBranchScope(state, state.activeScope);\n state.activeScope = null;\n }\n\n const activeScope = state.activeScope ?? createBranchScope(state, nextKey);\n state.activeKey = nextKey;\n state.activeScope = activeScope;\n\n const renderBranch = selectedMatch?.render ?? state.fallback;\n const vnode = renderBranch ? activeScope.render(renderBranch) : null;\n state.activeVNodes = vnode == null || vnode === false ? [] : [vnode];\n return state.activeVNodes;\n}\n\nexport function clearCaseDomUpdateState(state: CaseState): void {\n if (state.activeScope) {\n state.activeScope.needsDomUpdate = false;\n }\n state.lastRemovedNodes = [];\n}\n"],"mappings":";;;AA0CA,MAAM,kBAAkB;AACxB,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAE1B,SAAS,mBACP,OACA,OACM;CACN,IAAI,CAAC,OACH;CAEF,MAAM,aAAa,MAAM;CACzB,kBAAkB,MAAM;CACxB,IAAI,YACF,MAAM,iBAAiB,KAAK,WAAW;;AAI3C,SAAS,kBACP,OACA,KACY;CACZ,OAAO,iBAAiB,MAAM,gBAAgB,WAAW;EACvD,IAAI,MAAM,wBAAwB;GAChC,MAAM,wBAAwB;GAC9B;;EAGF,MAAM,gBAAgB,eAAe;GACrC;;AAGJ,SAAgB,gBACd,OACA,cACA,gBACW;CACX,OAAO;EACL,MAAM;EACN,WAAW;EACX,aAAa;EACb,cAAc,EAAE;EAChB,eAAe;EACf,kBAAkB,EAAE;EACpB,gBAAgB,oBAAoB;EACpC,wBAAwB;EACxB,2BAA2B;EAC3B;EACA;EACA,eAAe;EACf,aAAa;EACd;;AAGH,SAAgB,kBAAkB,OAA2B;CAC3D,MAAM,mBAAmB,EAAE;CAE3B,IAAI,MAAM,eAAe;EACvB,IAAI,MAAM,eAAe;GACvB,mBAAmB,OAAO,MAAM,cAAc;GAC9C,MAAM,gBAAgB;;EAGxB,MAAM,cACJ,MAAM,eAAe,kBAAkB,OAAO,gBAAgB;EAChE,MAAM,cAAc;EACpB,MAAM,cAAc;EACpB,MAAM,YAAY;EAElB,MAAM,QAAQ,YAAY,aACxB,MAAM,aAAa,MAAM,cAAc,CACxC;EACD,MAAM,eAAe,SAAS,QAAQ,UAAU,QAAQ,EAAE,GAAG,CAAC,MAAM;EACpE,OAAO,MAAM;;CAGf,IAAI,MAAM,aAAa;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AC5C,MAAM,cAAc;;CAGtB,MAAM,cAAc,MAAM,eAAe,kBAAkB,OAAO,QAAQ;CAC1E,MAAM,YAAY;CAClB,MAAM,cAAc;CAEpB,MAAM,eAAe,eAAe,UAAU,MAAM;CACpD,MAAM,QAAQ,eAAe,YAAY,OAAO,aAAa,GAAG;CAChE,MAAM,eAAe,SAAS,QAAQ,UAAU,QAAQ,EAAE,GAAG,CAAC,MAAM;CACpE,OAAO,MAAM;;AAGf,SAAgB,wBAAwB,OAAwB;CAC9D,IAAI,MAAM,aACR,MAAM,YAAY,iBAAiB;CAErC,MAAM,mBAAmB,EAAE"}
@@ -1,4 +1,5 @@
1
1
  import { ReadableSource } from "./readable.js";
2
+ import { SnapshotSourceBrand } from "./snapshot-source.js";
2
3
 
3
4
  //#region src/runtime/derive.d.ts
4
5
  interface Derived<T> extends ReadableSource<T> {
@@ -8,7 +9,7 @@ type SnapshotSource<T> = {
8
9
  value: T | null;
9
10
  pending?: boolean;
10
11
  error?: Error | null;
11
- };
12
+ } & SnapshotSourceBrand;
12
13
  declare function derive<TOut>(fn: () => TOut): Derived<TOut>;
13
14
  declare function derive<TIn, TOut>(source: SnapshotSource<TIn> | TIn | (() => TIn), map: (value: TIn) => TOut): Derived<TOut | null>;
14
15
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"derive.d.ts","names":[],"sources":["../../src/runtime/derive.ts"],"mappings":";;;UAkBiB,OAAA,YAAmB,cAAA,CAAe,CAAA;EAAA,IAC7C,CAAA;AAAA;AAAA,KAiBD,cAAA;EACH,KAAA,EAAO,CAAA;EACP,OAAA;EACA,KAAA,GAAQ,KAAA;AAAA;AAAA,iBA2LM,MAAA,MAAA,CAAa,EAAA,QAAU,IAAA,GAAO,OAAA,CAAQ,IAAA;AAAA,iBAEtC,MAAA,WAAA,CACd,MAAA,EAAQ,cAAA,CAAe,GAAA,IAAO,GAAA,UAAa,GAAA,GAC3C,GAAA,GAAM,KAAA,EAAO,GAAA,KAAQ,IAAA,GACpB,OAAA,CAAQ,IAAA"}
1
+ {"version":3,"file":"derive.d.ts","names":[],"sources":["../../src/runtime/derive.ts"],"mappings":";;;;UAmBiB,OAAA,YAAmB,cAAA,CAAe,CAAA;EAAA,IAC7C,CAAA;AAAA;AAAA,KAiBD,cAAA;EACH,KAAA,EAAO,CAAA;EACP,OAAA;EACA,KAAA,GAAQ,KAAA;AAAA,IACN,mBAAA;AAAA,iBA4LY,MAAA,MAAA,CAAa,EAAA,QAAU,IAAA,GAAO,OAAA,CAAQ,IAAA;AAAA,iBAEtC,MAAA,WAAA,CACd,MAAA,EAAQ,cAAA,CAAe,GAAA,IAAO,GAAA,UAAa,GAAA,GAC3C,GAAA,GAAM,KAAA,EAAO,GAAA,KAAQ,IAAA,GACpB,OAAA,CAAQ,IAAA"}
@@ -1,6 +1,7 @@
1
1
  import { globalScheduler } from "./scheduler.js";
2
2
  import { clearDerivedDependencySubscriptions, markReactivePropsDirtySource, markReadableDerivedSubscribersDirty, notifyReadableReaders, recordReadableRead, syncDerivedDependencySubscriptions, withDerivedReadTracking } from "./readable.js";
3
3
  import { claimHookIndex, getCurrentInstance } from "./component.js";
4
+ import { isSnapshotSource } from "./snapshot-source.js";
4
5
  //#region src/runtime/derive.ts
5
6
  const deriveCells = /* @__PURE__ */ new WeakMap();
6
7
  const dirtyDerivedCells = /* @__PURE__ */ new Set();
@@ -26,12 +27,18 @@ function markDerivedCellDirty(cell) {
26
27
  function flushDirtyDerivedCells() {
27
28
  hasPendingDerivedFlush = false;
28
29
  if (dirtyDerivedCells.size === 0) return;
29
- const pending = Array.from(dirtyDerivedCells);
30
- dirtyDerivedCells.clear();
31
- for (const cell of pending) {
30
+ const pending = dirtyDerivedCells.values();
31
+ let next = pending.next();
32
+ while (!next.done) {
33
+ const cell = next.value;
34
+ dirtyDerivedCells.delete(cell);
32
35
  cell._scheduled = false;
33
- if (!cell._dirty) continue;
36
+ if (!cell._dirty) {
37
+ next = pending.next();
38
+ continue;
39
+ }
34
40
  recomputeDerivedCell(cell, true);
41
+ next = pending.next();
35
42
  }
36
43
  }
37
44
  function recomputeDerivedCell(cell, notifyDownstream) {
@@ -109,14 +116,12 @@ function getOrCreateDerivedCell(instance, hookIndex, compute) {
109
116
  store.set(hookIndex, created);
110
117
  return created;
111
118
  }
112
- function createSelector(selector) {
113
- return selector;
114
- }
115
119
  function createMappedSelector(source, map) {
116
120
  return () => {
117
121
  let value;
118
- if (typeof source === "function" && !("value" in source)) value = source();
119
- else value = source?.value ?? source;
122
+ if (typeof source === "function") value = source();
123
+ else if (isSnapshotSource(source)) value = source.value ?? source;
124
+ else value = source;
120
125
  if (value == null) return null;
121
126
  return map(value);
122
127
  };
@@ -124,7 +129,7 @@ function createMappedSelector(source, map) {
124
129
  function derive(source, map) {
125
130
  const instance = getCurrentInstance();
126
131
  if (!instance) throw new Error("derive() can only be called during component render execution. Move derive() calls to the top level of your component function.");
127
- const cell = getOrCreateDerivedCell(instance, claimHookIndex(instance, "derive"), map === void 0 ? createSelector(source) : createMappedSelector(source, map));
132
+ const cell = getOrCreateDerivedCell(instance, claimHookIndex(instance, "derive"), map === void 0 ? () => source() : createMappedSelector(source, map));
128
133
  recomputeDerivedCell(cell, false);
129
134
  return cell;
130
135
  }
@@ -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';\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 _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};\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 = Array.from(dirtyDerivedCells);\n dirtyDerivedCells.clear();\n\n for (const cell of pending) {\n cell._scheduled = false;\n if (!cell._dirty) {\n continue;\n }\n recomputeDerivedCell(cell, true);\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\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._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 existing._dirty = true;\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 createSelector<TOut>(selector: () => TOut): () => TOut {\n return selector;\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' && !('value' in source)) {\n value = (source as () => TIn)();\n } else {\n value = (source as SnapshotSource<TIn>)?.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 ? createSelector(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":";;;;AA0CA,MAAM,8BAAc,IAAI,SAGrB;AACH,MAAM,oCAAoB,IAAI,KAA2B;AACzD,IAAI,yBAAyB;AAE7B,SAAS,eACP,UACmC;CACnC,IAAI,QAAQ,YAAY,IAAI,SAAS;AACrC,KAAI,CAAC,OAAO;AACV,0BAAQ,IAAI,KAAK;AACjB,cAAY,IAAI,UAAU,MAAM;;AAElC,QAAO;;AAGT,SAAS,qBAAqB,MAAkC;AAC9D,MAAK,SAAS;AACd,KAAI,KAAK,WACP;AAGF,MAAK,aAAa;AAClB,mBAAkB,IAAI,KAAK;AAE3B,KAAI,CAAC,wBAAwB;AAC3B,2BAAyB;AACzB,kBAAgB,cAAc,WAAW,uBAAuB;;;AAIpE,SAAS,yBAA+B;AACtC,0BAAyB;A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AmB;AACtB,uBAAqB,KAAK;;AAE5B,MAAK,iBAAiB;AACpB,OAAK,aAAa;AAClB,OAAK,SAAS;AACd,OAAK,YAAY;AACjB,oBAAkB,OAAO,KAAK;AAC9B,sCAAoC,MAAM,KAAK,SAAS;AACxD,OAAK,qBAAqB,OAAO;AACjC,OAAK,UAAU,OAAO;;AAGxB,EAAC,SAAS,eAAe,EAAE,EAAE,WAAW;AACtC,OAAK,UAAU;AACf,cAAY,IAAI,SAAS,EAAE,OAAO,UAAU;GAC5C;AAEF,QAAO;;AAGT,SAAS,uBACP,UACA,WACA,SACgB;CAChB,MAAM,QAAQ,eAAe,SAAS;CACtC,MAAM,WAAW,MAAM,IAAI,UAAU;AACrC,KAAI,UAAU;AACZ,WAAS,WAAW;AACpB,WAAS,SAAS;AAClB,SAAO;;CAGT,MAAM,UAAU,kBAAkB,UAAU,WAAW,QAAQ;AAC/D,OAAM,IAAI,WAAW,QAAgC;AACrD,QAAO;;AAGT,SAAS,eAAqB,UAAkC;AAC9D,QAAO;;AAGT,SAAS,qBACP,QACA,KACmB;AACnB,cAAa;EACX,IAAI;AACJ,MAAI,OAAO,WAAW,cAAc,EAAE,WAAW,QAC/C,SAAS,QAAsB;MAE/B,SAAS,QAAgC,SAAU;AAGrD,MAAI,SAAS,KACX,QAAO;AAGT,SAAO,IAAI,MAAM;;;AAWrB,SAAgB,OACd,QACA,KACqC;CACrC,MAAM,WAAW,oBAAoB;AACrC,KAAI,CAAC,SACH,OAAM,IAAI,MACR,kIAED;CASH,MAAM,OAAO,uBACX,UAPgB,eAAe,UAAU,SAQzC,EANA,QAAQ,SACJ,eAAe,OAAoB,GACnC,qBAAqB,QAAQ,IAAI,CAMtC;AACD,sBAAqB,MAAM,MAAM;AACjC,QAAO"}
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 _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\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._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 existing._dirty = true;\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":";;;;;AA2CA,MAAM,8BAAc,IAAI,SAGrB;AACH,MAAM,oCAAoB,IAAI,KAA2B;AACz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AAO,EACjC,QAAS,OAA+B,SAAU;OAElD,QAAQ;EAGV,IAAI,SAAS,MACX,OAAO;EAGT,OAAO,IAAI,MAAM;;;AAWrB,SAAgB,OACd,QACA,KACqC;CACrC,MAAM,WAAW,oBAAoB;CACrC,IAAI,CAAC,UACH,MAAM,IAAI,MACR,kIAED;CASH,MAAM,OAAO,uBACX,UAPgB,eAAe,UAAU,SAQzC,EANA,QAAQ,eACG,QAAsB,GAC7B,qBAAqB,QAAQ,IAAI,CAMtC;CACD,qBAAqB,MAAM,MAAM;CACjC,OAAO"}
@@ -1 +1 @@
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;AAC9C,KAAI,yBAAyB,CAAE,QAAO,EAAE;AACxC,KAAI;EACF,MAAM,IAAI;AACV,MAAI,CAAC,EAAE,SAAU,GAAE,WAAW,EAAE;AAChC,SAAO,EAAE;SACH;AACN,SAAO,EAAE;;;;;;AAOb,SAAgB,YAAY,KAAa,OAAsB;AAC7D,KAAI,yBAAyB,CAAE;AAC/B,KAAI;AACF,mBAAiB,CAAC,OAAO;SACnB;;;;;AAQV,SAAgB,YAAe,KAA4B;AACzD,KAAI,yBAAyB,CAAE,QAAO;AACtC,KAAI;AACF,SAAO,iBAAiB,CAAC;SACnB;AACN;;;;;;;AAoBJ,SAAgB,cAAc,KAAmB;AAC/C,KAAI,yBAAyB,CAAE;AAC/B,KAAI;EACF,MAAM,KAAK,iBAAiB;AAE5B,KAAG,QADU,OAAO,GAAG,SAAS,WAAY,GAAG,OAAkB,KAChD;SACX"}
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,yBAAyB,EAAE,OAAO,EAAE;CACxC,IAAI;EACF,MAAM,IAAI;EACV,IAAI,CAAC,EAAE,UAAU,EAAE,WAAW,EAAE;EAChC,OAAO,EAAE;SACH;EACN,OAAO,EAAE;;;;;;AAOb,SAAgB,YAAY,KAAa,OAAsB;CAC7D,IAAI,yBAAyB,EAAE;CAC/B,IAAI;EACF,iBAAiB,CAAC,OAAO;SACnB;;;;;AAQV,SAAgB,YAAe,KAA4B;CACzD,IAAI,yBAAyB,EAAE,OAAO;CACtC,IAAI;EACF,OAAO,iBAAiB,CAAC;SACnB;EACN;;;;;;;AAoBJ,SAAgB,cAAc,KAAmB;CAC/C,IAAI,yBAAyB,EAAE;CAC/B,IAAI;EACF,MAAM,KAAK,iBAAiB;EAE5B,GAAG,QADU,OAAO,GAAG,SAAS,WAAY,GAAG,OAAkB,KAChD;SACX"}
@@ -1 +1 @@
1
- {"version":3,"file":"effect.d.ts","names":[],"sources":["../../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,aAAA;EACN,OAAA,QAAe,CAAA;EACf,MAAA,GAAS,KAAA,EAAO,CAAA,EAAG,aAAA,EAAe,CAAA;EAClC,MAAA,IAAU,aAAA,EAAe,CAAA,EAAG,SAAA,EAAW,CAAA;EACvC,OAAA,IAAW,KAAA;AAAA;AAAA,iBAkKG,iCAAA,CACd,MAAA,EAAQ,cAAA;AAAA,iBAmCM,uBAAA,GAAA,CACd,OAAA,EAAS,8BAAA,CAA+B,CAAA,IACvC,uBAAA,CAAwB,CAAA"}
@@ -15,7 +15,19 @@ const hasPendingLaneFlush = {
15
15
  reactive: false,
16
16
  post: false
17
17
  };
18
+ const dirtyLaneState = {
19
+ derived: false,
20
+ component: false,
21
+ reactive: false,
22
+ post: false
23
+ };
18
24
  const _evalSourceBuffer = /* @__PURE__ */ new Set();
25
+ const LANE_FLUSH_TASKS = {
26
+ derived: () => flushLaneEffects("derived"),
27
+ component: () => flushLaneEffects("component"),
28
+ reactive: () => flushLaneEffects("reactive"),
29
+ post: () => flushLaneEffects("post")
30
+ };
19
31
  function registerEffectSource(source, effect) {
20
32
  let effects = effectSources.get(source);
21
33
  if (!effects) {
@@ -72,24 +84,28 @@ function flushLaneEffects(lane) {
72
84
  hasPendingLaneFlush[lane] = false;
73
85
  const effects = dirtyEffectsByLane[lane];
74
86
  if (effects.size === 0) return;
75
- const pending = Array.from(effects);
76
- effects.clear();
77
- for (const effect of pending) {
78
- if (!effect.isActive) continue;
87
+ const pending = effects.values();
88
+ let next = pending.next();
89
+ while (!next.done) {
90
+ const effect = next.value;
91
+ effects.delete(effect);
92
+ if (!effect.isActive) {
93
+ next = pending.next();
94
+ continue;
95
+ }
79
96
  try {
80
97
  const { value, nextSources } = evaluateEffect(effect);
81
98
  commitEffectResult(effect, value, nextSources);
82
99
  } catch (error) {
83
100
  effect.onError?.(error);
84
101
  }
102
+ next = pending.next();
85
103
  }
86
104
  }
87
105
  function scheduleLaneFlush(lane) {
88
106
  if (hasPendingLaneFlush[lane]) return;
89
107
  hasPendingLaneFlush[lane] = true;
90
- globalScheduler.enqueueInLane(lane, () => {
91
- flushLaneEffects(lane);
92
- });
108
+ globalScheduler.enqueueInLane(lane, LANE_FLUSH_TASKS[lane]);
93
109
  }
94
110
  function unscheduleEffect(effect) {
95
111
  dirtyEffectsByLane[effect.lane].delete(effect);
@@ -101,11 +117,20 @@ function recomputeEffectNow(effect) {
101
117
  function markFineGrainedEffectsDirtySource(source) {
102
118
  const effects = effectSources.get(source);
103
119
  if (!effects || effects.size === 0) return;
120
+ dirtyLaneState.derived = false;
121
+ dirtyLaneState.component = false;
122
+ dirtyLaneState.reactive = false;
123
+ dirtyLaneState.post = false;
104
124
  for (const effect of effects) {
105
125
  if (!effect.isActive) continue;
106
- dirtyEffectsByLane[effect.lane].add(effect);
126
+ const lane = effect.lane;
127
+ dirtyEffectsByLane[lane].add(effect);
128
+ dirtyLaneState[lane] = true;
107
129
  }
108
- for (const lane of Object.keys(hasPendingLaneFlush)) if (dirtyEffectsByLane[lane].size > 0) scheduleLaneFlush(lane);
130
+ if (dirtyLaneState.derived) scheduleLaneFlush("derived");
131
+ if (dirtyLaneState.component) scheduleLaneFlush("component");
132
+ if (dirtyLaneState.reactive) scheduleLaneFlush("reactive");
133
+ if (dirtyLaneState.post) scheduleLaneFlush("post");
109
134
  }
110
135
  function createFineGrainedEffect(options) {
111
136
  const effect = {
@@ -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>;\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 _evalSourceBuffer = new Set<ReadableSource<unknown>>();\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 _evalSourceBuffer.clear();\n\n try {\n incDevCounter('effectRuns');\n const value = withFineGrainedReadTracking(_evalSourceBuffer, () =>\n effect.compute()\n );\n const nextSources = normalizeNextSources(\n effect.readSources,\n _evalSourceBuffer\n );\n return { value, nextSources };\n } finally {\n _evalSourceBuffer.clear();\n }\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 = Array.from(effects);\n effects.clear();\n\n for (const effect of pending) {\n if (!effect.isActive) {\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}\n\nfunction scheduleLaneFlush(lane: SchedulerLane): void {\n if (hasPendingLaneFlush[lane]) {\n return;\n }\n\n hasPendingLaneFlush[lane] = true;\n globalScheduler.enqueueInLane(lane, () => {\n flushLaneEffects(lane);\n });\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 for (const effect of effects) {\n if (!effect.isActive) {\n continue;\n }\n dirtyEffectsByLane[effect.lane].add(effect);\n }\n\n for (const lane of Object.keys(hasPendingLaneFlush) as SchedulerLane[]) {\n if (dirtyEffectsByLane[lane].size > 0) {\n scheduleLaneFlush(lane);\n }\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":";;;;AAaA,MAAM,gCAAgC,IAAI,SAAS;AACnD,MAAM,qBAAsC;CAC1C,yBAAS,IAAI,KAAK;CAClB,2BAAW,IAAI,KAAK;CACpB,0BAAU,IAAI,KAAK;CACnB,sBAAM,IAAI,KAAK;CAChB;AACD,MAAM,sBAA+C;CACnD,SAAS;CACT,WAAW;CACX,UAAU;CACV,MAAM;CACP;AAED,MAAM,oCAAoB,IAAI,KAA8B;AA4B5D,SAAS,qBACP,QAC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ACV,WAAW;EACX,SAAS,QAAQ;EAClB;AAED,oBAAmB,OAAO;AAE1B,QAAO;EACL,UAAgB;AACd,OAAI,CAAC,OAAO,SACV;AAGF,UAAO,WAAW;AAClB,oBAAiB,OAAO;AACxB,4BAAyB,OAAO;;EAGlC,cAAc,aAA4B;AACxC,OAAI,CAAC,OAAO,SACV;AAGF,UAAO,UAAU;AACjB,oBAAiB,OAAO;AACxB,sBAAmB,OAAO;;EAG5B,QAAc;AACZ,OAAI,CAAC,OAAO,SACV;AAGF,oBAAiB,OAAO;AACxB,sBAAmB,OAAO;;EAE7B"}
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 _evalSourceBuffer = new Set<ReadableSource<unknown>>();\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 _evalSourceBuffer.clear();\n\n try {\n incDevCounter('effectRuns');\n const value = withFineGrainedReadTracking(_evalSourceBuffer, () =>\n effect.compute()\n );\n const nextSources = normalizeNextSources(\n effect.readSources,\n _evalSourceBuffer\n );\n return { value, nextSources };\n } finally {\n _evalSourceBuffer.clear();\n }\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 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 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,SAAS;AACnD,MAAM,qBAAsC;CAC1C,yBAAS,IAAI,KAAK;CAClB,2BAAW,IAAI,KAAK;CACpB,0BAAU,IAAI,KAAK;CACnB,sBAAM,IAAI,KAAK;CAChB;AACD,MAAM,sBAA+C;CACnD,SAAS;CACT,WAAW;CACX,UAAU;CACV,MAAM;CACP;AAED,MAAM,iBAAuC;CAC3C,SAAS;CACT,WAAW;CACX,UAAU;C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CAEtB,KAAK,MAAM,UAAU,SAAS;EAC5B,IAAI,CAAC,OAAO,UACV;EAEF,MAAM,OAAO,OAAO;EACpB,mBAAmB,MAAM,IAAI,OAAO;EACpC,eAAe,QAAQ;;CAGzB,IAAI,eAAe,SACjB,kBAAkB,UAAU;CAE9B,IAAI,eAAe,WACjB,kBAAkB,YAAY;CAEhC,IAAI,eAAe,UACjB,kBAAkB,WAAW;CAE/B,IAAI,eAAe,MACjB,kBAAkB,OAAO;;AAI7B,SAAgB,wBACd,SAC4B;CAC5B,MAAM,SAA+B;EACnC,MAAM,QAAQ;EACd,SAAS,QAAQ;EACjB,QAAQ,QAAQ;EAChB,QAAQ,QAAQ,UAAU,OAAO;EACjC,6BAAa,IAAI,KAAK;EACtB,UAAU;EACV,UAAU;EACV,WAAW;EACX,SAAS,QAAQ;EAClB;CAED,mBAAmB,OAAO;CAE1B,OAAO;EACL,UAAgB;GACd,IAAI,CAAC,OAAO,UACV;GAGF,OAAO,WAAW;GAClB,iBAAiB,OAAO;GACxB,yBAAyB,OAAO;;EAGlC,cAAc,aAA4B;GACxC,IAAI,CAAC,OAAO,UACV;GAGF,OAAO,UAAU;GACjB,iBAAiB,OAAO;GACxB,mBAAmB,OAAO;;EAG5B,QAAc;GACZ,IAAI,CAAC,OAAO,UACV;GAGF,iBAAiB,OAAO;GACxB,mBAAmB,OAAO;;EAE7B"}
@@ -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 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>();\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}\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 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 eventName,\n options,\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 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 }\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 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 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;CACD;AAYD,MAAM,oCAAoB,IAAI,SAAyC;AAEvE,IAAI,yBAAyB;AAG7B,MAAM,8CAA8B,IAAI,KAGrC;AAEH,SAAgB,2BAAoC;AAClD,QAAO;;AA4BT,SAAS,yBAAyC;AAGhD,KAAI,OAAO,aAAa,YAAa,QAAO,SAAS;AACrD,QAAO;;AAGT,SAAS,wBACP,WACA,SACA,WACA,SACA,iBACA,SACM;AACN,KAAI,CAAC,4BAA4B,IAAI,UAAU,CAC7C,6BAA4B,IAAI,2BAAW,IAAI,KAAK,CAAC;CAEvD,MAAM,qBAAqB,4BAA4B,IAAI,UAAU;AAErE,KAAI,CAAC,mBAAmB,IAAI,UAAU,EAAE;EACtC,MAAM,oBAAoB,MAAa;GACrC,MAAM,SAAS,EAAE;AACjB,OAAI,CAAC,OAAQ;AAEb,mBAAgB,wBAAwB;IACtC,IAAI,UAA0B;AAC9B,WAAO,WAAW,YAAY,WAAW;AACvC,yBAAoB,wBAAwB;KAC5C,MAAM,QAAQ,kBAAkB,IAAI,QAAQ;KAC5C,MAAM,QAAQ,CAAC,QACX,SACA,iBAAiB,MACf,MAAM,IAAI,UAAU,GACpB,MAAM,cAAc,YAClB,QACA;AACR,SAAI,MACF,KAAI;AACF,YAAM,QAAQ,EAAE;cACT,OAAO;AACd,aAAO,MAAM,iCAAiC,MAAM;;AAIxD,SAAI,EAAE,aACJ;AAGF,eAAU,QAAQ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,kBAAkB;AAElC,WAAS,OAAO,UAAU;AAC1B,MAAI,SAAS,SAAS,GAAG;AACvB,qBAAkB,OAAO,QAAQ;AACjC;;AAEF,MAAI,SAAS,SAAS,GAAG;GACvB,MAAM,OAAO,SAAS,QAAQ,CAAC,MAAM,CAAC;AACtC,qBAAkB,IAAI,SAAS,KAAK;;AAEtC;;AAGF,KAAI,SAAS,cAAc,WAAW;AACpC,gBAAc,kBAAkB;AAChC,oBAAkB,OAAO,QAAQ;;;AAIrC,SAAgB,8BACd,SACA,WAC8B;CAC9B,MAAM,QAAQ,kBAAkB,IAAI,QAAQ;AAC5C,KAAI,CAAC,MAAO,QAAO;AACnB,KAAI,iBAAiB,IAAK,QAAO,MAAM,IAAI,UAAU;AACrD,QAAO,MAAM,cAAc,YAAY,QAAQ;;AAGjD,SAAgB,+BACd,SAC2C;CAC3C,MAAM,QAAQ,kBAAkB,IAAI,QAAQ;AAC5C,KAAI,CAAC,MAAO,QAAO;AACnB,KAAI,iBAAiB,IAAK,QAAO;AACjC,QAAO,IAAI,IAAI,CAAC,CAAC,MAAM,WAAW,MAAM,CAAC,CAAC;;AAU5C,SAAgB,iCAAiC,SAAwB;AACvE,mBAAkB,OAAO,QAAQ;;AAOnC,SAAgB,iBAAiB,WAA4B;AAC3D,QAAO,iBAAiB,SAAS,UAAqC"}
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 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>();\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}\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 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 eventName,\n options,\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 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 }\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 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 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;CACD;AAYD,MAAM,oCAAoB,IAAI,SAAyC;AAEvE,IAAI,yBAAyB;AAG7B,MAAM,8CAA8B,IAAI,KAGrC;AAEH,SAAgB,2BAAoC;CAClD,OAAO;;AA4BT,SAAS,yBAAyC;CAGhD,IAAI,OAAO,aAAa,aAAa,OAAO,SAAS;CACrD,OAAO;;AAGT,SAAS,wBACP,WACA,SACA,WACA,SACA,iBACA,SACM;CACN,IAAI,CAAC,4BAA4B,IAAI,UAAU,EAC7C,4BAA4B,IAAI,2BAAW,IAAI,KAAK,CAAC;CAEvD,MAAM,qBAAqB,4BAA4B,IAAI,UAAU;CAErE,IAAI,CAAC,mBAAmB,IAAI,UAAU,EAAE;EACtC,MAAM,oBAAoB,MAAa;GACrC,MAAM,SAAS,EAAE;GACjB,IAAI,CAAC,QAAQ;GAEb,gBAAgB,wBAAwB;IACtC,IAAI,UAA0B;IAC9B,OAAO,WAAW,YAAY,WAAW;KACvC,oBAAoB,wBAAwB;KAC5C,MAAM,QAAQ,kBAAkB,IAAI,QAAQ;KAC5C,MAAM,QAAQ,CAAC,QACX,SACA,iBAAiB,MACf,MAAM,IAAI,UAAU,GACpB,MAAM,cAAc,YAClB,QACA;KACR,IAAI,OACF,IAAI;MACF,MAAM,QAAQ,EAAE;cACT,OAAO;MACd,OAAO,MAAM,iCAAiC,MAAM;;KAIxD,IAAI,EAAE,cACJ;KAGF,UAAU,QAAQ;;MAEnB,OAAO;;EAIZ,MAAM,kBADiB,kBAA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AI,SAAS,SAAS,GAAG;GACvB,kBAAkB,OAAO,QAAQ;GACjC;;EAEF,IAAI,SAAS,SAAS,GAAG;GACvB,MAAM,OAAO,SAAS,QAAQ,CAAC,MAAM,CAAC;GACtC,kBAAkB,IAAI,SAAS,KAAK;;EAEtC;;CAGF,IAAI,SAAS,cAAc,WAAW;EACpC,cAAc,kBAAkB;EAChC,kBAAkB,OAAO,QAAQ;;;AAIrC,SAAgB,8BACd,SACA,WAC8B;CAC9B,MAAM,QAAQ,kBAAkB,IAAI,QAAQ;CAC5C,IAAI,CAAC,OAAO,OAAO;CACnB,IAAI,iBAAiB,KAAK,OAAO,MAAM,IAAI,UAAU;CACrD,OAAO,MAAM,cAAc,YAAY,QAAQ;;AAGjD,SAAgB,+BACd,SAC2C;CAC3C,MAAM,QAAQ,kBAAkB,IAAI,QAAQ;CAC5C,IAAI,CAAC,OAAO,OAAO;CACnB,IAAI,iBAAiB,KAAK,OAAO;CACjC,OAAO,IAAI,IAAI,CAAC,CAAC,MAAM,WAAW,MAAM,CAAC,CAAC;;AAU5C,SAAgB,iCAAiC,SAAwB;CACvE,kBAAkB,OAAO,QAAQ;;AAOnC,SAAgB,iBAAiB,WAA4B;CAC3D,OAAO,iBAAiB,SAAS,UAAqC"}
@@ -1 +1 @@
1
- {"version":3,"file":"execution-model.js","names":[],"sources":["../../src/runtime/execution-model.ts"],"sourcesContent":["export type ExecutionModel = 'spa' | 'islands' | 'ssr';\n\nconst EXECUTION_MODEL_KEY = Symbol.for('__ASKR_EXECUTION_MODEL__');\n\nexport function getExecutionModel(): ExecutionModel | undefined {\n const g = globalThis as unknown as Record<string | symbol, unknown>;\n return g[EXECUTION_MODEL_KEY] as ExecutionModel | undefined;\n}\n\nexport function assertExecutionModel(model: ExecutionModel): void {\n // Mixing execution models is forbidden: once an app starts in one model,\n // attempting to start another is an invariant violation.\n const g = globalThis as unknown as Record<string | symbol, unknown>;\n const cur = g[EXECUTION_MODEL_KEY] as ExecutionModel | undefined;\n if (cur && cur !== model) {\n throw new Error(\n `[Askr] mixing execution models is not allowed (current: ${cur}, attempted: ${model}). ` +\n `Choose exactly one: createSPA, createSSR, or createIslands.`\n );\n }\n if (!cur) g[EXECUTION_MODEL_KEY] = model;\n}\n"],"mappings":";AAEA,MAAM,sBAAsB,OAAO,IAAI,2BAA2B;AAElE,SAAgB,oBAAgD;AAE9D,QAAO,WAAE;;AAGX,SAAgB,qBAAqB,OAA6B;CAGhE,MAAM,IAAI;CACV,MAAM,MAAM,EAAE;AACd,KAAI,OAAO,QAAQ,MACjB,OAAM,IAAI,MACR,2DAA2D,IAAI,eAAe,MAAM,gEAErF;AAEH,KAAI,CAAC,IAAK,GAAE,uBAAuB"}
1
+ {"version":3,"file":"execution-model.js","names":[],"sources":["../../src/runtime/execution-model.ts"],"sourcesContent":["export type ExecutionModel = 'spa' | 'islands' | 'ssr';\n\nconst EXECUTION_MODEL_KEY = Symbol.for('__ASKR_EXECUTION_MODEL__');\n\nexport function getExecutionModel(): ExecutionModel | undefined {\n const g = globalThis as unknown as Record<string | symbol, unknown>;\n return g[EXECUTION_MODEL_KEY] as ExecutionModel | undefined;\n}\n\nexport function assertExecutionModel(model: ExecutionModel): void {\n // Mixing execution models is forbidden: once an app starts in one model,\n // attempting to start another is an invariant violation.\n const g = globalThis as unknown as Record<string | symbol, unknown>;\n const cur = g[EXECUTION_MODEL_KEY] as ExecutionModel | undefined;\n if (cur && cur !== model) {\n throw new Error(\n `[Askr] mixing execution models is not allowed (current: ${cur}, attempted: ${model}). ` +\n `Choose exactly one: createSPA, createSSR, or createIslands.`\n );\n }\n if (!cur) g[EXECUTION_MODEL_KEY] = model;\n}\n"],"mappings":";AAEA,MAAM,sBAAsB,OAAO,IAAI,2BAA2B;AAElE,SAAgB,oBAAgD;CAE9D,OAAO,WAAE;;AAGX,SAAgB,qBAAqB,OAA6B;CAGhE,MAAM,IAAI;CACV,MAAM,MAAM,EAAE;CACd,IAAI,OAAO,QAAQ,OACjB,MAAM,IAAI,MACR,2DAA2D,IAAI,eAAe,MAAM,gEAErF;CAEH,IAAI,CAAC,KAAK,EAAE,uBAAuB"}
@@ -1 +1 @@
1
- {"version":3,"file":"fastlane.js","names":[],"sources":["../../src/runtime/fastlane.ts"],"sourcesContent":["import { isDevelopmentEnvironment } from '../common/env';\nimport { globalScheduler } from './scheduler';\nimport { logger } from '../dev/logger';\nimport type { ComponentInstance } from './component';\nimport { finalizeReadableSubscriptions } from './readable';\nimport {\n getKeyMapForElement,\n isKeyedReorderFastPathEligible,\n populateKeyMapForElement,\n} from '../renderer/keyed';\nimport { Fragment } from '../common/jsx';\nimport { setDevValue, getDevValue, getDevNamespace } from './dev-namespace';\n\nlet _bulkCommitActive = false;\nlet _appliedParents: WeakSet<Element> | null = null;\n\nexport function enterBulkCommit(): void {\n _bulkCommitActive = true;\n // Initialize registry of parents that had fast-path applied during this bulk commit\n _appliedParents = new WeakSet<Element>();\n\n // Clear any previously scheduled synchronous scheduler tasks so they don't\n // retrigger evaluations during the committed fast-path.\n try {\n const cleared = globalScheduler.clearPendingSyncTasks?.() ?? 0;\n setDevValue('__ASKR_FASTLANE_CLEARED_TASKS', cleared);\n } catch (err) {\n if (isDevelopmentEnvironment()) throw err;\n }\n}\n\nexport function exitBulkCommit(): void {\n _bulkCommitActive = false;\n // Clear registry to avoid leaking across commits\n _appliedParents = null;\n}\n\nexport function isBulkCommitActive(): boolean {\n return _bulkCommitActive;\n}\n\n// Mark that a fast-path was applied on a parent element during the active\n// bulk commit. No-op if there is no active bulk commit.\nexport function markFastPathApplied(parent: Element): void {\n if (!_appliedParents) return;\n try {\n _appliedParents.add(parent);\n } catch (e) {\n void e;\n }\n}\n\nexport function isFastPathApplied(parent: Element): boolean {\n return !!(_appliedParents && _appliedParents.has(parent));\n}\n\nfunction finalizeReadSubscriptions(instance: ComponentInstance): void {\n finalizeReadableSubscriptions(instance);\n}\n\n/**\n * Attempt to execute a runtime fast-lane for a single component's synchronous\n * render result. Returns true if the fast-lane was used and commit was done.\n *\n * Preconditions (checked conservatively):\n * - The render result is an intrinsic element root with keyed children\n * - The renderer's fast-path heuristics indicate to use the fast-path\n * - No mount operations are pending on the component instance\n * - No child vnodes are component functions (avoid async/component mounts)\n */\n\n// Helper to unwrap Fragment vnodes to get the first intrinsic element child\nfunction unwrapFragmentForFastPath(vnode: unknown): unknown {\n if (!vnode || typeof vnode !== 'object' || !('type' in vnode)) return vnode;\n const v = vnode as {\n type: unknown;\n children?: unknown;\n props?: { children?: unknown };\n };\n // Check if it's a Fragment\n if (\n typeof v.type === 'symbol' &&\n (v.type === Fragment || String(v.type) === 'Symbol(askr.fragment)')\n ) {\n const children = v.props?.children ?? v.children;\n if (Array.isArray(children) && children.length > 0) {\n // Return the first child that's an intrinsic element\n for (const child of children) {\n if (child && typeof child === 'object' && 'type' in child) {\n const c = child as { type: unknown };\n if (typeof c.type === 'string') {\n return child;\n }\n }\n }\n }\n }\n return vnode;\n}\n\nexport function classifyUpdate(instance: ComponentInstance, result: unknown) {\n // Returns a classification describing whether this update is eligible for\n // the reorder-only fast-lane. The classifier mirrors renderer-level\n // heuristics and performs runtime-level checks (mounts, effects, component\n // children) that the renderer cannot reason about.\n\n // Unwrap Fragment to get the actual element vnode for classification\n const unwrappedResult = unwrapFragmentForFastPath(result);\n\n if (\n !unwrappedResult ||\n typeof unwrappedResult !== 'object' ||\n !('type' in unwrappedResult)\n )\n return { useFastPath: false, reason: 'not-vnode' };\n\n const vnode = unwrappedResult as {\n type: unknown;\n children?: unknown;\n props?: { children?: unknown };\n };\n if (vnode == null || typeof vnode.type !== 'string')\n return { useFastPath: false, reason: 'not-intrinsic' };\n\n const parent = instance.target;\n if (!parent) return { useFastPath: false, reason: 'no-root' };\n\n const firstChild = parent.children[0] as Element | undefined;\n if (!firstChild) return { useFastPath: false, reason: 'no-first-child' };\n if (firstChild.tagName.toLowerCase() !== String(vnode.type).toLowerCase())\n return { useFastPath: false, reason: 'root-tag-mismatch' };\n\n const children = vnode.props?.children ?? vnode.children;\n if (!Array.isArray(children))\n return { useFastPath: false, reason: 'no-children-array' };\n\n // Avoid component child vnodes (they may mount/unmount or trigger async)\n for (const c of children) {\n if (\n typeof c === 'object' &&\n c !== null &&\n 'type' in c &&\n typeof (c as { type?: unknown }).type === 'function'\n ) {\n return { useFastPath: false, reason: 'component-child-present' };\n }\n }\n\n if ((instance.mountOperations?.length ?? 0) > 0)\n return { useFastPath: false, reason: 'pending-mounts' };\n\n // Ask renderer for keyed reorder eligibility (prop differences & heuristics)\n // Ensure a keyed map is available for the first child by populating it proactively.\n try {\n populateKeyMapForElement(firstChild);\n } catch {\n // ignore\n }\n\n const oldKeyMap = getKeyMapForElement(firstChild);\n const decision = isKeyedReorderFastPathEligible(\n firstChild,\n children,\n oldKeyMap\n );\n\n if (!decision.useFastPath || decision.totalKeyed < 128)\n return { ...decision, useFastPath: false, reason: 'renderer-declined' };\n\n return { ...decision, useFastPath: true } as const;\n}\n\nexport function commitReorderOnly(\n instance: ComponentInstance,\n result: unknown\n): boolean {\n // Performs the minimal, synchronous reorder-only commit.\n const evaluate = (\n globalThis as {\n __ASKR_RENDERER?: {\n evaluate?: (node: unknown, target: Element | null) => void;\n };\n }\n ).__ASKR_RENDERER?.evaluate;\n\n if (typeof evaluate !== 'function') {\n logger.warn(\n '[Tempo][FASTPATH][DEV] renderer.evaluate not available; declining fast-lane'\n );\n return false;\n }\n\n const schedBefore = isDevelopmentEnvironment()\n ? globalScheduler.getState()\n : null;\n\n enterBulkCommit();\n\n try {\n globalScheduler.runWithSyncProgress(() => {\n evaluate(result, instance.target);\n\n // Finalize runtime bookkeeping (read subscriptions / tokens)\n try {\n finalizeReadSubscriptions(instance);\n } catch (e) {\n if (isDevelopmentEnvironment()) throw e;\n }\n });\n\n // Clear any synchronous tasks scheduled during the commit\n const clearedAfter = globalScheduler.clearPendingSyncTasks?.() ?? 0;\n setDevValue('__FASTLANE_CLEARED_AFTER', clearedAfter);\n\n // Dev-only invariant checks\n if (isDevelopmentEnvironment()) {\n validateFastLaneInvariants(instance, schedBefore);\n }\n\n return true;\n } finally {\n // Clear bulk commit flag first\n exitBulkCommit();\n }\n // Note: The original code had a check here that was dead code because\n // exitBulkCommit() already ran in the finally block. This comment serves\n // as documentation that we've intentionally removed that unreachable code.\n}\n\n/**\n * Validates fast-lane invariants in dev mode.\n * Extracted to reduce complexity in commitReorderOnly.\n */\nfunction validateFastLaneInvariants(\n instance: ComponentInstance,\n schedBefore: ReturnType<typeof globalScheduler.getState> | null\n): void {\n const commitCount = getDevValue<number>('__LAST_FASTPATH_COMMIT_COUNT') ?? 0;\n const invariants = {\n commitCount,\n mountOps: instance.mountOperations?.length ?? 0,\n cleanupFns: instance.cleanupFns?.length ?? 0,\n };\n setDevValue('__LAST_FASTLANE_INVARIANTS', invariants);\n\n if (commitCount !== 1) {\n console.error(\n '[FASTLANE][INV] commitCount',\n commitCount,\n 'diag',\n getDevNamespace()\n );\n throw new Error(\n 'Fast-lane invariant violated: expected exactly one DOM commit during reorder-only commit'\n );\n }\n\n if (invariants.mountOps > 0) {\n throw new Error(\n 'Fast-lane invariant violated: mount operations were registered during bulk commit'\n );\n }\n\n if (invariants.cleanupFns > 0) {\n throw new Error(\n 'Fast-lane invariant violated: cleanup functions were added during bulk commit'\n );\n }\n\n const schedAfter = globalScheduler.getState();\n if (\n schedBefore &&\n schedAfter &&\n schedAfter.taskCount > schedBefore.taskCount\n ) {\n console.error(\n '[FASTLANE] schedBefore, schedAfter',\n schedBefore,\n schedAfter\n );\n console.error('[FASTLANE] enqueue logs', getDevValue('__ENQUEUE_LOGS'));\n throw new Error(\n 'Fast-lane invariant violated: scheduler enqueued leftover work during bulk commit'\n );\n }\n\n // Final quiescence assertion\n let finalState = globalScheduler.getState();\n const executing = globalScheduler.isExecuting();\n let outstandingAfter = Math.max(\n 0,\n finalState.taskCount - (executing ? 1 : 0)\n );\n\n if (outstandingAfter !== 0) {\n // Attempt to clear newly enqueued synchronous tasks\n let attempts = 0;\n while (attempts < 5) {\n const cleared = globalScheduler.clearPendingSyncTasks?.() ?? 0;\n if (cleared === 0) break;\n attempts++;\n }\n finalState = globalScheduler.getState();\n outstandingAfter = Math.max(\n 0,\n finalState.taskCount - (globalScheduler.isExecuting() ? 1 : 0)\n );\n if (outstandingAfter !== 0) {\n console.error(\n '[FASTLANE] Post-commit enqueue logs:',\n getDevValue('__ENQUEUE_LOGS')\n );\n console.error(\n '[FASTLANE] Cleared counts:',\n getDevValue('__FASTLANE_CLEARED_TASKS'),\n getDevValue('__FASTLANE_CLEARED_AFTER')\n );\n throw new Error(\n `Fast-lane invariant violated: scheduler has ${finalState.taskCount} pending task(s) after commit`\n );\n }\n }\n}\n\nexport function tryRuntimeFastLaneSync(\n instance: ComponentInstance,\n result: unknown\n): boolean {\n const cls = classifyUpdate(instance, result);\n if (!cls.useFastPath) {\n // Clear stale fast-path diagnostics\n setDevValue('__LAST_FASTPATH_STATS', undefined);\n setDevValue('__LAST_FASTPATH_COMMIT_COUNT', 0);\n return false;\n }\n\n try {\n return commitReorderOnly(instance, result);\n } catch (err) {\n // Surface dev-only invariant failures, otherwise decline silently\n if (isDevelopmentEnvironment()) throw err;\n return false;\n }\n}\n\n// Expose fastlane bridge on globalThis for environments/tests\nif (typeof globalThis !== 'undefined') {\n (globalThis as Record<string, unknown>).__ASKR_FASTLANE = {\n isBulkCommitActive,\n enterBulkCommit,\n exitBulkCommit,\n tryRuntimeFastLaneSync,\n markFastPathApplied,\n isFastPathApplied,\n };\n}\n"],"mappings":";;;;;;;;AAaA,IAAI,oBAAoB;AACxB,IAAI,kBAA2C;AAE/C,SAAgB,kBAAwB;AACtC,qBAAoB;AAEpB,mCAAkB,IAAI,SAAkB;AAIxC,KAAI;AAEF,cAAY,iCADI,gBAAgB,yBAAyB,IAAI,EACR;UAC9C,KAAK;AACZ,MAAI,0BAA0B,CAAE,OAAM;;;AAI1C,SAAgB,iBAAuB;AACrC,qBAAoB;AAEpB,mBAAkB;;AAGpB,SAAgB,qBAA8B;AAC5C,QA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tC,SAAO;;;AAKX,IAAI,OAAO,eAAe,YACvB,YAAuC,kBAAkB;CACxD;CACA;CACA;CACA;CACA;CACA;CACD"}
1
+ {"version":3,"file":"fastlane.js","names":[],"sources":["../../src/runtime/fastlane.ts"],"sourcesContent":["import { isDevelopmentEnvironment } from '../common/env';\nimport { globalScheduler } from './scheduler';\nimport { logger } from '../dev/logger';\nimport type { ComponentInstance } from './component';\nimport { finalizeReadableSubscriptions } from './readable';\nimport {\n getKeyMapForElement,\n isKeyedReorderFastPathEligible,\n populateKeyMapForElement,\n} from '../renderer/keyed';\nimport { Fragment } from '../common/jsx';\nimport { setDevValue, getDevValue, getDevNamespace } from './dev-namespace';\n\nlet _bulkCommitActive = false;\nlet _appliedParents: WeakSet<Element> | null = null;\n\nexport function enterBulkCommit(): void {\n _bulkCommitActive = true;\n // Initialize registry of parents that had fast-path applied during this bulk commit\n _appliedParents = new WeakSet<Element>();\n\n // Clear any previously scheduled synchronous scheduler tasks so they don't\n // retrigger evaluations during the committed fast-path.\n try {\n const cleared = globalScheduler.clearPendingSyncTasks?.() ?? 0;\n setDevValue('__ASKR_FASTLANE_CLEARED_TASKS', cleared);\n } catch (err) {\n if (isDevelopmentEnvironment()) throw err;\n }\n}\n\nexport function exitBulkCommit(): void {\n _bulkCommitActive = false;\n // Clear registry to avoid leaking across commits\n _appliedParents = null;\n}\n\nexport function isBulkCommitActive(): boolean {\n return _bulkCommitActive;\n}\n\n// Mark that a fast-path was applied on a parent element during the active\n// bulk commit. No-op if there is no active bulk commit.\nexport function markFastPathApplied(parent: Element): void {\n if (!_appliedParents) return;\n try {\n _appliedParents.add(parent);\n } catch (e) {\n void e;\n }\n}\n\nexport function isFastPathApplied(parent: Element): boolean {\n return !!(_appliedParents && _appliedParents.has(parent));\n}\n\nfunction finalizeReadSubscriptions(instance: ComponentInstance): void {\n finalizeReadableSubscriptions(instance);\n}\n\n/**\n * Attempt to execute a runtime fast-lane for a single component's synchronous\n * render result. Returns true if the fast-lane was used and commit was done.\n *\n * Preconditions (checked conservatively):\n * - The render result is an intrinsic element root with keyed children\n * - The renderer's fast-path heuristics indicate to use the fast-path\n * - No mount operations are pending on the component instance\n * - No child vnodes are component functions (avoid async/component mounts)\n */\n\n// Helper to unwrap Fragment vnodes to get the first intrinsic element child\nfunction unwrapFragmentForFastPath(vnode: unknown): unknown {\n if (!vnode || typeof vnode !== 'object' || !('type' in vnode)) return vnode;\n const v = vnode as {\n type: unknown;\n children?: unknown;\n props?: { children?: unknown };\n };\n // Check if it's a Fragment\n if (\n typeof v.type === 'symbol' &&\n (v.type === Fragment || String(v.type) === 'Symbol(askr.fragment)')\n ) {\n const children = v.props?.children ?? v.children;\n if (Array.isArray(children) && children.length > 0) {\n // Return the first child that's an intrinsic element\n for (const child of children) {\n if (child && typeof child === 'object' && 'type' in child) {\n const c = child as { type: unknown };\n if (typeof c.type === 'string') {\n return child;\n }\n }\n }\n }\n }\n return vnode;\n}\n\nexport function classifyUpdate(instance: ComponentInstance, result: unknown) {\n // Returns a classification describing whether this update is eligible for\n // the reorder-only fast-lane. The classifier mirrors renderer-level\n // heuristics and performs runtime-level checks (mounts, effects, component\n // children) that the renderer cannot reason about.\n\n // Unwrap Fragment to get the actual element vnode for classification\n const unwrappedResult = unwrapFragmentForFastPath(result);\n\n if (\n !unwrappedResult ||\n typeof unwrappedResult !== 'object' ||\n !('type' in unwrappedResult)\n )\n return { useFastPath: false, reason: 'not-vnode' };\n\n const vnode = unwrappedResult as {\n type: unknown;\n children?: unknown;\n props?: { children?: unknown };\n };\n if (vnode == null || typeof vnode.type !== 'string')\n return { useFastPath: false, reason: 'not-intrinsic' };\n\n const parent = instance.target;\n if (!parent) return { useFastPath: false, reason: 'no-root' };\n\n const firstChild = parent.children[0] as Element | undefined;\n if (!firstChild) return { useFastPath: false, reason: 'no-first-child' };\n if (firstChild.tagName.toLowerCase() !== String(vnode.type).toLowerCase())\n return { useFastPath: false, reason: 'root-tag-mismatch' };\n\n const children = vnode.props?.children ?? vnode.children;\n if (!Array.isArray(children))\n return { useFastPath: false, reason: 'no-children-array' };\n\n // Avoid component child vnodes (they may mount/unmount or trigger async)\n for (const c of children) {\n if (\n typeof c === 'object' &&\n c !== null &&\n 'type' in c &&\n typeof (c as { type?: unknown }).type === 'function'\n ) {\n return { useFastPath: false, reason: 'component-child-present' };\n }\n }\n\n if ((instance.mountOperations?.length ?? 0) > 0)\n return { useFastPath: false, reason: 'pending-mounts' };\n\n // Ask renderer for keyed reorder eligibility (prop differences & heuristics)\n // Ensure a keyed map is available for the first child by populating it proactively.\n try {\n populateKeyMapForElement(firstChild);\n } catch {\n // ignore\n }\n\n const oldKeyMap = getKeyMapForElement(firstChild);\n const decision = isKeyedReorderFastPathEligible(\n firstChild,\n children,\n oldKeyMap\n );\n\n if (!decision.useFastPath || decision.totalKeyed < 128)\n return { ...decision, useFastPath: false, reason: 'renderer-declined' };\n\n return { ...decision, useFastPath: true } as const;\n}\n\nexport function commitReorderOnly(\n instance: ComponentInstance,\n result: unknown\n): boolean {\n // Performs the minimal, synchronous reorder-only commit.\n const evaluate = (\n globalThis as {\n __ASKR_RENDERER?: {\n evaluate?: (node: unknown, target: Element | null) => void;\n };\n }\n ).__ASKR_RENDERER?.evaluate;\n\n if (typeof evaluate !== 'function') {\n logger.warn(\n '[Tempo][FASTPATH][DEV] renderer.evaluate not available; declining fast-lane'\n );\n return false;\n }\n\n const schedBefore = isDevelopmentEnvironment()\n ? globalScheduler.getState()\n : null;\n\n enterBulkCommit();\n\n try {\n globalScheduler.runWithSyncProgress(() => {\n evaluate(result, instance.target);\n\n // Finalize runtime bookkeeping (read subscriptions / tokens)\n try {\n finalizeReadSubscriptions(instance);\n } catch (e) {\n if (isDevelopmentEnvironment()) throw e;\n }\n });\n\n // Clear any synchronous tasks scheduled during the commit\n const clearedAfter = globalScheduler.clearPendingSyncTasks?.() ?? 0;\n setDevValue('__FASTLANE_CLEARED_AFTER', clearedAfter);\n\n // Dev-only invariant checks\n if (isDevelopmentEnvironment()) {\n validateFastLaneInvariants(instance, schedBefore);\n }\n\n return true;\n } finally {\n // Clear bulk commit flag first\n exitBulkCommit();\n }\n // Note: The original code had a check here that was dead code because\n // exitBulkCommit() already ran in the finally block. This comment serves\n // as documentation that we've intentionally removed that unreachable code.\n}\n\n/**\n * Validates fast-lane invariants in dev mode.\n * Extracted to reduce complexity in commitReorderOnly.\n */\nfunction validateFastLaneInvariants(\n instance: ComponentInstance,\n schedBefore: ReturnType<typeof globalScheduler.getState> | null\n): void {\n const commitCount = getDevValue<number>('__LAST_FASTPATH_COMMIT_COUNT') ?? 0;\n const invariants = {\n commitCount,\n mountOps: instance.mountOperations?.length ?? 0,\n cleanupFns: instance.cleanupFns?.length ?? 0,\n };\n setDevValue('__LAST_FASTLANE_INVARIANTS', invariants);\n\n if (commitCount !== 1) {\n console.error(\n '[FASTLANE][INV] commitCount',\n commitCount,\n 'diag',\n getDevNamespace()\n );\n throw new Error(\n 'Fast-lane invariant violated: expected exactly one DOM commit during reorder-only commit'\n );\n }\n\n if (invariants.mountOps > 0) {\n throw new Error(\n 'Fast-lane invariant violated: mount operations were registered during bulk commit'\n );\n }\n\n if (invariants.cleanupFns > 0) {\n throw new Error(\n 'Fast-lane invariant violated: cleanup functions were added during bulk commit'\n );\n }\n\n const schedAfter = globalScheduler.getState();\n if (\n schedBefore &&\n schedAfter &&\n schedAfter.taskCount > schedBefore.taskCount\n ) {\n console.error(\n '[FASTLANE] schedBefore, schedAfter',\n schedBefore,\n schedAfter\n );\n console.error('[FASTLANE] enqueue logs', getDevValue('__ENQUEUE_LOGS'));\n throw new Error(\n 'Fast-lane invariant violated: scheduler enqueued leftover work during bulk commit'\n );\n }\n\n // Final quiescence assertion\n let finalState = globalScheduler.getState();\n const executing = globalScheduler.isExecuting();\n let outstandingAfter = Math.max(\n 0,\n finalState.taskCount - (executing ? 1 : 0)\n );\n\n if (outstandingAfter !== 0) {\n // Attempt to clear newly enqueued synchronous tasks\n let attempts = 0;\n while (attempts < 5) {\n const cleared = globalScheduler.clearPendingSyncTasks?.() ?? 0;\n if (cleared === 0) break;\n attempts++;\n }\n finalState = globalScheduler.getState();\n outstandingAfter = Math.max(\n 0,\n finalState.taskCount - (globalScheduler.isExecuting() ? 1 : 0)\n );\n if (outstandingAfter !== 0) {\n console.error(\n '[FASTLANE] Post-commit enqueue logs:',\n getDevValue('__ENQUEUE_LOGS')\n );\n console.error(\n '[FASTLANE] Cleared counts:',\n getDevValue('__FASTLANE_CLEARED_TASKS'),\n getDevValue('__FASTLANE_CLEARED_AFTER')\n );\n throw new Error(\n `Fast-lane invariant violated: scheduler has ${finalState.taskCount} pending task(s) after commit`\n );\n }\n }\n}\n\nexport function tryRuntimeFastLaneSync(\n instance: ComponentInstance,\n result: unknown\n): boolean {\n const cls = classifyUpdate(instance, result);\n if (!cls.useFastPath) {\n // Clear stale fast-path diagnostics\n setDevValue('__LAST_FASTPATH_STATS', undefined);\n setDevValue('__LAST_FASTPATH_COMMIT_COUNT', 0);\n return false;\n }\n\n try {\n return commitReorderOnly(instance, result);\n } catch (err) {\n // Surface dev-only invariant failures, otherwise decline silently\n if (isDevelopmentEnvironment()) throw err;\n return false;\n }\n}\n\n// Expose fastlane bridge on globalThis for environments/tests\nif (typeof globalThis !== 'undefined') {\n (globalThis as Record<string, unknown>).__ASKR_FASTLANE = {\n isBulkCommitActive,\n enterBulkCommit,\n exitBulkCommit,\n tryRuntimeFastLaneSync,\n markFastPathApplied,\n isFastPathApplied,\n };\n}\n"],"mappings":";;;;;;;;AAaA,IAAI,oBAAoB;AACxB,IAAI,kBAA2C;AAE/C,SAAgB,kBAAwB;CACtC,oBAAoB;CAEpB,kCAAkB,IAAI,SAAkB;CAIxC,IAAI;EAEF,YAAY,iCADI,gBAAgB,yBAAyB,IAAI,EACR;UAC9C,KAAK;EACZ,IAAI,0BAA0B,EAAE,MAAM;;;AAI1C,SAAgB,iBAAuB;CACrC,oBAAoB;CAEpB,kBAAkB;;AAGpB,SAAgB,qBAA8B;CAC5C,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EACtC,OAAO;;;AAKX,IAAI,OAAO,eAAe,aACxB,WAAwC,kBAAkB;CACxD;CACA;CACA;CACA;CACA;CACA;CACD"}
@@ -27,7 +27,7 @@ type BenchMetricScope = 'coldCreate' | 'fullClear';
27
27
  type BenchCounter = 'domNodesCreated' | 'listenerBindings' | 'reactivePropsMounted' | 'replaceChildrenCommits' | 'bulkClearCommits';
28
28
  declare function withBenchMetricScopeLive<T>(scope: BenchMetricScope, run: () => T): T;
29
29
  declare const resetBenchMetrics: () => void;
30
- declare const recordBenchEvent: (event: BenchEvent) => void;
30
+ declare const recordBenchEvent: (event: BenchEvent, delta?: number) => void;
31
31
  declare const recordBenchFastLane: (name: string) => void;
32
32
  declare const recordBenchTiming: (phase: "reconcile" | "domCommit", ms: number) => void;
33
33
  declare const recordBenchCounter: (counter: BenchCounter, delta?: number) => void;
@@ -1 +1 @@
1
- {"version":3,"file":"for-bench.d.ts","names":[],"sources":["../../src/runtime/for-bench.ts"],"mappings":";UASiB,YAAA;EACf,YAAA;EACA,WAAA;EACA,YAAA;EACA,UAAA;EACA,qBAAA;EACA,UAAA;EACA,OAAA;EACA,SAAA;EACA,UAAA;EACA,UAAA;EACA,QAAA;EACA,WAAA;EACA,WAAA;EACA,eAAA;EACA,gBAAA;EACA,oBAAA;EACA,sBAAA;EACA,gBAAA;EACA,gBAAA;EACA,gBAAA;EACA,YAAA;AAAA;AAAA,KAGU,UAAA;AAAA,KA0CP,gBAAA;AAAA,KACA,YAAA;AAAA,iBA+II,wBAAA,GAAA,CAA4B,KAAA,EAAO,gBAAA,EAAkB,GAAA,QAAW,CAAA,GAAI,CAAA;AAAA,cAoChE,iBAAA;AAAA,cAUA,gBAAA,GAAgB,KAAA,EA9HQ,UAAA;AAAA,cAkIxB,mBAAA,GAAmB,IAAA;AAAA,cAInB,iBAAA,GAAiB,KAAA,6BAnCI,EAAA;AAAA,cAuCrB,kBAAA,GAAkB,OAAA,EAlFU,YAAA,EAAY,KAAA;AAAA,cAsFxC,o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