@askrjs/askr 0.0.30 → 0.0.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -3
- package/dist/benchmark.js +2 -2
- package/dist/common/vnode.d.ts +1 -0
- package/dist/common/vnode.d.ts.map +1 -1
- package/dist/common/vnode.js +2 -1
- package/dist/common/vnode.js.map +1 -1
- package/dist/components/error-boundary.d.ts +25 -0
- package/dist/components/error-boundary.d.ts.map +1 -0
- package/dist/components/error-boundary.js +114 -0
- package/dist/components/error-boundary.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/renderer/dom.js +23 -1
- package/dist/renderer/dom.js.map +1 -1
- package/dist/runtime/component.d.ts +5 -0
- package/dist/runtime/component.d.ts.map +1 -1
- package/dist/runtime/component.js.map +1 -1
- package/dist/ssr/index.d.ts.map +1 -1
- package/dist/ssr/index.js +166 -0
- package/dist/ssr/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -38,6 +38,11 @@ interface ComponentInstance {
|
|
|
38
38
|
key: string | number;
|
|
39
39
|
dispose(): void;
|
|
40
40
|
}>;
|
|
41
|
+
errorBoundaryState?: {
|
|
42
|
+
error: unknown | null;
|
|
43
|
+
resetKey: unknown;
|
|
44
|
+
notified: boolean;
|
|
45
|
+
};
|
|
41
46
|
}
|
|
42
47
|
declare function createComponentInstance(id: string, fn: ComponentFunction, props: Props, target: Element | null): ComponentInstance;
|
|
43
48
|
type OwnedChildScope = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"component.d.ts","names":[],"sources":["../../src/runtime/component.ts"],"mappings":";;;;;;;UA4BiB,iBAAA;EACf,EAAA;EACA,EAAA,EAAI,iBAAA;EACJ,KAAA,EAAO,KAAA;EACP,MAAA,EAAQ,OAAA;EACR,OAAA;EACA,eAAA,EAAiB,eAAA;EACjB,GAAA;EAEA,aAAA;EACA,WAAA,EAAa,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;;AA/kBtC;;;;;;;;;;;;;;;;;;;AA4DC;;;;;AAoBD;;;;;AAKA;;;;iBAuiBgB,SAAA,CAAA,GAAa,WAAA;AA1hB7B;;;;;AAmDA;;;AAnDA,iBA4iBgB,yBAAA,CAA0B,QAAA,EAAU,iBAAA;AAAA,iBAIpC,iBAAA,CAAA;AAAA,iBAIA,cAAA,CACd,QAAA,EAAU,iBAAA,EACV,QAAA;AAAA,iBAgCc,oBAAA,CAAA;AAAA,iBAIA,eAAA,CAAA;AAAA,iBAIA,aAAA,CAAc,KAAA;;AA/e9B;;;;iBAwfgB,cAAA,CAAe,QAAA,EAAU,iBAAA;;;;;iBAQzB,gBAAA,CAAiB,QAAA,EAAU,iBAAA;AAAA,iBAuD3B,uBAAA,CACd,QAAA,EAAU,iBAAA,EACV,KAAA,EAAO,eAAA;AAAA,iBAMO,yBAAA,CACd,QAAA,EAAU,iBAAA,EACV,KAAA,EAAO,eAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"component.js","names":[],"sources":["../../src/runtime/component.ts"],"sourcesContent":["/**\n * Component instance lifecycle management\n * Internal only — users never see this\n */\n\nimport { type State } from './state';\nimport { globalScheduler } from './scheduler';\nimport type { Props } from '../common/props';\nimport type { ComponentFunction } from '../common/component';\nimport {\n // withContext is the sole primitive for context restoration\n withContext,\n type ContextFrame,\n} from './context';\nimport {\n type ReadableSource,\n finalizeReadableSubscriptions,\n cleanupReadableSubscriptions,\n} from './readable';\nimport {\n isDevelopmentEnvironment,\n isProductionEnvironment,\n} from '../common/env';\nimport { logger } from '../dev/logger';\nimport { incDevCounter, setDevValue } from './dev-namespace';\n\nexport type { ComponentFunction } from '../common/component';\n\nexport interface ComponentInstance {\n id: string;\n fn: ComponentFunction;\n props: Props;\n target: Element | null;\n mounted: boolean;\n abortController: AbortController | null; // Lazily created per-component abort lifecycle\n ssr?: boolean; // Set to true for SSR temporary instances\n // Opt-in strict cleanup mode: when true cleanup errors are aggregated and re-thrown\n cleanupStrict?: boolean;\n stateValues: State<unknown>[]; // Persistent state storage across renders\n evaluationGeneration: number; // Prevents stale async evaluation completions\n notifyUpdate: (() => void) | null; // Callback for state updates (persisted on instance)\n // Internal: prebound helpers to avoid per-update closures (allocation hot-path)\n _pendingFlushTask?: () => void; // Clears hasPendingUpdate and triggers notifyUpdate\n _pendingRunTask?: () => void; // Clears hasPendingUpdate and runs component\n _enqueueRun?: () => void; // Batches run requests and enqueues _pendingRunTask\n stateIndexCheck: number; // Track state indices to catch conditional calls\n expectedStateIndices: number[]; // Expected sequence of render-scoped hook indices (frozen after first render)\n firstRenderComplete: boolean; // Flag to detect transition from first to subsequent renders\n mountOperations: Array<\n () => void | (() => void) | Promise<void | (() => void)>\n >; // Operations to run when component mounts\n cleanupFns: Array<() => void>; // Cleanup functions to run on unmount\n hasPendingUpdate: boolean; // Flag to batch state updates (coalescing)\n ownerFrame: ContextFrame | null; // Provider chain for this component (set by Scope, never overwritten)\n isRoot?: boolean;\n\n // Render-tracking for precise subscriptions (internal)\n _currentRenderToken?: number; // Token for the in-progress render (set before render)\n lastRenderToken?: number; // Token of the last *committed* render\n _pendingReadSources?: Set<ReadableSource<unknown>>; // Readables read during the in-progress render\n _lastReadSources?: Set<ReadableSource<unknown>>; // Readables read during the last committed render\n devWarningsEmitted?: Set<string>; // Dev-only warning dedupe for this instance\n\n // Placeholder for null-returning components. When a component initially returns\n // null, we create a comment placeholder so updates can replace it with content.\n _placeholder?: Comment;\n _ownedChildScopes?: Set<{\n key: string | number;\n dispose(): void;\n }>;\n}\n\nexport function createComponentInstance(\n id: string,\n fn: ComponentFunction,\n props: Props,\n target: Element | null\n): ComponentInstance {\n const instance: ComponentInstance = {\n id,\n fn,\n props,\n target,\n mounted: false,\n abortController: null,\n stateValues: [],\n evaluationGeneration: 0,\n notifyUpdate: null,\n // Prebound helpers (initialized below) to avoid per-update allocations\n _pendingFlushTask: undefined,\n _pendingRunTask: undefined,\n _enqueueRun: undefined,\n stateIndexCheck: -1,\n expectedStateIndices: [],\n firstRenderComplete: false,\n mountOperations: [],\n cleanupFns: [],\n hasPendingUpdate: false,\n ownerFrame: null, // Will be set by renderer when vnode is marked\n ssr: false,\n cleanupStrict: false,\n isRoot: false,\n\n // Render-tracking (for precise state subscriptions)\n _currentRenderToken: undefined,\n lastRenderToken: 0,\n _pendingReadSources: undefined,\n _lastReadSources: undefined,\n devWarningsEmitted: undefined,\n };\n\n // Initialize prebound helper tasks once per instance to avoid allocations\n instance._pendingRunTask = () => {\n // Clear pending flag when the run task executes\n instance.hasPendingUpdate = false;\n // Execute component run (will set up notifyUpdate before render)\n runComponent(instance);\n };\n\n instance._enqueueRun = () => {\n if (!instance.hasPendingUpdate) {\n instance.hasPendingUpdate = true;\n // Enqueue single run task (coalesces multiple writes)\n globalScheduler.enqueue(instance._pendingRunTask!);\n }\n };\n\n // Default state-driven updates enqueue the run task directly. Specialized\n // runtimes (for example `For` item instances) can still override this hook.\n instance._pendingFlushTask = instance._pendingRunTask;\n\n return instance;\n}\n\nlet currentInstance: ComponentInstance | null = null;\nlet stateIndex = 0;\n\ntype OwnedChildScope = {\n key: string | number;\n dispose(): void;\n};\n\nfunction ensureAbortController(instance: ComponentInstance): AbortController {\n let controller = instance.abortController;\n if (!controller || controller.signal.aborted) {\n controller = new AbortController();\n instance.abortController = controller;\n }\n return controller;\n}\n\n// Export for state.ts to access\nexport function getCurrentComponentInstance(): ComponentInstance | null {\n return currentInstance;\n}\n\n// Export for SSR to set temporary instance\nexport function setCurrentComponentInstance(\n instance: ComponentInstance | null\n): void {\n currentInstance = instance;\n}\n\n/**\n * Register a mount operation that will run after the component is mounted\n * Used by operations (task, on, timer, etc) to execute after render completes\n */\nimport { isBulkCommitActive } from './fastlane';\nimport { evaluate, cleanupInstancesUnder } from '../renderer';\n\nexport function registerMountOperation(\n operation: () => void | (() => void) | Promise<void | (() => void)>\n): void {\n const instance = getCurrentComponentInstance();\n if (instance) {\n // If we're in bulk-commit fast lane, registering mount operations is a\n // violation of the fast-lane preconditions. Throw in dev, otherwise ignore\n // silently in production (we must avoid scheduling work during bulk commit).\n if (isBulkCommitActive()) {\n if (isDevelopmentEnvironment()) {\n throw new Error(\n 'registerMountOperation called during bulk commit fast-lane'\n );\n }\n return;\n }\n instance.mountOperations.push(operation);\n }\n}\n\n/**\n * Execute all mount operations for a component\n * These run after the component is rendered and mounted to the DOM\n */\nfunction executeMountOperations(instance: ComponentInstance): void {\n // Only execute mount operations for root app instance. Child component\n // operations are currently registered but should not be executed (per\n // contract tests). They remain registered for cleanup purposes.\n if (!instance.isRoot) return;\n\n const mountOperations = instance.mountOperations;\n if (mountOperations.length === 0) {\n return;\n }\n\n for (const operation of mountOperations) {\n const result = operation();\n if (result instanceof Promise) {\n result.then((cleanup) => {\n if (typeof cleanup === 'function') {\n instance.cleanupFns.push(cleanup);\n }\n });\n } else if (typeof result === 'function') {\n instance.cleanupFns.push(result);\n }\n }\n // Clear the operations array so they don't run again on subsequent renders\n instance.mountOperations = [];\n}\n\nexport function mountInstanceInline(\n instance: ComponentInstance,\n target: Element | null\n): void {\n instance.target = target;\n // Record backref on host element so renderer can clean up when the\n // node is removed. Avoids leaks if the node is detached or replaced.\n try {\n if (target instanceof Element) {\n const host = target as Element & {\n __ASKR_INSTANCE?: ComponentInstance;\n __ASKR_INSTANCES?: ComponentInstance[];\n };\n const instances = host.__ASKR_INSTANCES ?? [];\n const nextInstances = instances.filter((entry) => entry !== instance);\n nextInstances.push(instance);\n host.__ASKR_INSTANCES = nextInstances;\n host.__ASKR_INSTANCE = nextInstances[0] ?? instance;\n }\n } catch (err) {\n void err;\n }\n\n // Ensure notifyUpdate is available for async resource completions that may\n // try to trigger re-render. This mirrors the setup in executeComponent().\n // Use prebound enqueue helper to avoid allocating a new closure\n instance.notifyUpdate = instance._enqueueRun!;\n\n const wasFirstMount = !instance.mounted;\n instance.mounted = true;\n if (wasFirstMount && instance.mountOperations.length > 0) {\n executeMountOperations(instance);\n }\n}\n\n/**\n * Run a component synchronously: execute function, handle result\n * This is the internal workhorse that manages async continuations and generation tracking.\n * Must always be called through the scheduler.\n *\n * ACTOR INVARIANT: This function is enqueued as a task, never called directly.\n */\nlet _globalRenderCounter = 0;\n\nfunction resetRenderState(instance: ComponentInstance): void {\n instance.stateIndexCheck = -1;\n\n for (const state of instance.stateValues) {\n if (state) {\n state._hasBeenRead = false;\n }\n }\n\n instance._pendingReadSources = undefined;\n}\n\nfunction nextRenderToken(): number {\n return ++_globalRenderCounter;\n}\n\nexport function renderScopedComponent<T>(\n instance: ComponentInstance,\n startStateIndex: number,\n render: () => T\n): T {\n const savedInstance = currentInstance;\n const savedStateIndex = stateIndex;\n\n instance.notifyUpdate = instance._enqueueRun!;\n resetRenderState(instance);\n instance._currentRenderToken = nextRenderToken();\n\n currentInstance = instance;\n stateIndex = startStateIndex;\n\n let didComplete = false;\n\n try {\n const executionFrame: ContextFrame = {\n parent: instance.ownerFrame,\n values: null,\n };\n const result = withContext(executionFrame, render);\n didComplete = true;\n return result;\n } finally {\n if (!didComplete) {\n instance._pendingReadSources = undefined;\n instance._currentRenderToken = undefined;\n }\n currentInstance = savedInstance;\n stateIndex = savedStateIndex;\n }\n}\n\nfunction runComponent(instance: ComponentInstance): void {\n // CRITICAL: Ensure notifyUpdate is available for state.set() calls during this render.\n // This must be set before executeComponentSync() runs, not after.\n // Use prebound enqueue helper to avoid allocating per-render closures\n instance.notifyUpdate = instance._enqueueRun!;\n\n // Assign a token for this in-progress render and start a fresh pending-read set\n instance._currentRenderToken = nextRenderToken();\n instance._pendingReadSources = undefined;\n const domSnapshot = instance.target ? instance.target.innerHTML : '';\n\n const result = executeComponentSync(instance);\n if (result instanceof Promise) {\n // Async components are not supported. Components must be synchronous and\n // must not return a Promise from their render function.\n throw new Error(\n 'Async components are not supported. Components must be synchronous.'\n );\n } else {\n // Try runtime fast-lane synchronously; if it activates we do not enqueue\n // follow-up work and the commit happens atomically in this task.\n // (Runtime fast-lane has conservative preconditions.)\n const fastlaneBridge = (\n globalThis as {\n __ASKR_FASTLANE?: {\n tryRuntimeFastLaneSync?: (\n instance: unknown,\n result: unknown\n ) => boolean;\n };\n }\n ).__ASKR_FASTLANE;\n try {\n const used = fastlaneBridge?.tryRuntimeFastLaneSync?.(instance, result);\n if (used) {\n warnUnusedStateReads(instance);\n return;\n }\n } catch (err) {\n // If invariant check failed in dev, surface the error; otherwise fall back\n if (isDevelopmentEnvironment()) throw err;\n }\n\n // Fallback: enqueue the render/commit normally\n globalScheduler.enqueue(() => {\n // Handle placeholder-based updates: when a component initially returned null,\n // we created a comment placeholder. If it now has content, we need to create\n // a host element and replace the placeholder.\n if (!instance.target && instance._placeholder) {\n // Component previously returned null (has placeholder), check if now has content\n if (result === null || result === undefined) {\n // Still null - nothing to do, keep placeholder\n finalizeReadSubscriptions(instance);\n warnUnusedStateReads(instance);\n return;\n }\n\n // Has content now - need to create DOM and replace placeholder\n const placeholder = instance._placeholder;\n const parent = placeholder.parentNode;\n if (!parent) {\n // Placeholder was removed from DOM - can't render\n logger.warn(\n '[Askr] placeholder no longer in DOM, cannot render component'\n );\n return;\n }\n\n // Create a new host element for the content\n const host = document.createElement('div');\n const executionFrame: ContextFrame = {\n parent: instance.ownerFrame,\n values: null,\n };\n\n // Set up instance for normal updates\n const oldInstance = currentInstance;\n currentInstance = instance;\n try {\n withContext(executionFrame, () => {\n evaluate(result, host);\n });\n\n // Replace placeholder with host\n parent.replaceChild(host, placeholder);\n\n // Set up instance for future updates\n instance.target = host;\n instance._placeholder = undefined;\n (\n host as Element & { __ASKR_INSTANCE?: ComponentInstance }\n ).__ASKR_INSTANCE = instance;\n\n finalizeReadSubscriptions(instance);\n warnUnusedStateReads(instance);\n } finally {\n currentInstance = oldInstance;\n }\n return;\n }\n\n if (instance.target) {\n let oldChildren: Node[] = [];\n try {\n const wasFirstMount = !instance.mounted;\n // Ensure nested component executions during evaluation have access to\n // the current component instance. This allows nested components to\n // call `state()`, `resource()`, and other runtime helpers which\n // rely on `getCurrentComponentInstance()` being available.\n const oldInstance = currentInstance;\n currentInstance = instance;\n const executionFrame: ContextFrame = {\n parent: instance.ownerFrame,\n values: null,\n };\n // Capture snapshot of current children (by reference) so we can\n // restore them on render failure without losing event listeners or\n // instance attachments.\n oldChildren = Array.from(instance.target.childNodes);\n\n try {\n withContext(executionFrame, () => {\n evaluate(result, instance.target);\n });\n } catch (e) {\n // If evaluation failed, attempt to cleanup any partially-added nodes\n // and restore the old children to preserve listeners and instances.\n try {\n const newChildren = Array.from(instance.target.childNodes);\n for (const n of newChildren) {\n try {\n cleanupInstancesUnder(n);\n } catch (err) {\n logger.warn(\n '[Askr] error cleaning up failed commit children:',\n err\n );\n }\n }\n } catch (_err) {\n void _err;\n }\n\n // Restore original children by re-inserting the old node references\n // this preserves attached listeners and instance backrefs.\n try {\n incDevCounter('__DOM_REPLACE_COUNT');\n setDevValue(\n '__LAST_DOM_REPLACE_STACK_COMPONENT_RESTORE',\n new Error().stack\n );\n } catch (e) {\n void e;\n }\n instance.target.replaceChildren(...oldChildren);\n throw e;\n } finally {\n currentInstance = oldInstance;\n }\n\n // Commit succeeded — finalize recorded state reads so subscriptions reflect\n // the last *committed* render. This updates per-state reader maps\n // deterministically and synchronously with the commit.\n finalizeReadSubscriptions(instance);\n warnUnusedStateReads(instance);\n\n instance.mounted = true;\n // Execute mount operations after first mount (do NOT run these with\n // currentInstance set - they may perform state mutations/registrations)\n if (wasFirstMount && instance.mountOperations.length > 0) {\n executeMountOperations(instance);\n }\n } catch (renderError) {\n // Atomic rendering: rollback on render error. Attempt non-lossy restore of\n // original child node references to preserve listeners/instances.\n try {\n const currentChildren = Array.from(instance.target.childNodes);\n for (const n of currentChildren) {\n try {\n cleanupInstancesUnder(n);\n } catch (err) {\n logger.warn(\n '[Askr] error cleaning up partial children during rollback:',\n err\n );\n }\n }\n } catch (_err) {\n void _err;\n }\n\n try {\n incDevCounter('__DOM_REPLACE_COUNT');\n setDevValue(\n '__LAST_DOM_REPLACE_STACK_COMPONENT_ROLLBACK',\n new Error().stack\n );\n instance.target.replaceChildren(...oldChildren);\n } catch {\n // Fallback to innerHTML restore if replaceChildren fails for some reason.\n instance.target.innerHTML = domSnapshot;\n }\n\n throw renderError;\n }\n }\n });\n }\n}\n\n/**\n * Execute a component's render function synchronously.\n * Returns either a vnode/promise immediately (does NOT render).\n * Rendering happens separately through runComponent.\n */\nexport function renderComponentInline(\n instance: ComponentInstance\n): unknown | Promise<unknown> {\n // Ensure inline executions (rendered during parent's evaluate) still\n // receive a render token and have their state reads finalized so\n // subscriptions are correctly recorded. If this function is called\n // as part of a scheduled run, the token will already be set by\n // runComponent and we should not overwrite it.\n const hadToken = instance._currentRenderToken !== undefined;\n const prevToken = instance._currentRenderToken;\n const prevPendingReads = instance._pendingReadSources;\n if (!hadToken) {\n instance._currentRenderToken = nextRenderToken();\n instance._pendingReadSources = undefined;\n }\n\n try {\n const result = executeComponentSync(instance);\n // If we set the token for inline execution, finalize subscriptions now\n // because the component is effectively committed as part of the parent's\n // synchronous evaluation.\n if (!hadToken) {\n finalizeReadSubscriptions(instance);\n }\n return result;\n } finally {\n // Restore previous token/read states for nested inline render scenarios\n instance._currentRenderToken = prevToken;\n instance._pendingReadSources = prevPendingReads;\n }\n}\n\nexport function warnUnusedStateReads(instance: ComponentInstance): void {\n for (let i = 0; i < instance.stateValues.length; i++) {\n const state = instance.stateValues[i];\n const hasCommittedUsage =\n (state?._readers?.size ?? 0) > 0 ||\n ((state as { _derivedSubscribers?: Set<unknown> } | undefined)\n ?._derivedSubscribers?.size ?? 0) > 0;\n\n if (state && !state._hasBeenRead && !hasCommittedUsage) {\n try {\n const name = instance.fn?.name || '<anonymous>';\n warnInstanceOnce(\n instance,\n `unused-state:${i}`,\n `[askr] Unused state variable detected in ${name} at index ${i}. State should be read during render or removed.`\n );\n } catch {\n warnInstanceOnce(\n instance,\n `unused-state:${i}`,\n `[askr] Unused state variable detected. State should be read during render or removed.`\n );\n }\n }\n }\n}\n\nfunction executeComponentSync(\n instance: ComponentInstance\n): unknown | Promise<unknown> {\n resetRenderState(instance);\n incDevCounter('componentRuns');\n incDevCounter('componentReruns');\n\n currentInstance = instance;\n stateIndex = 0;\n\n try {\n // Track render time in dev mode\n const renderStartTime = isDevelopmentEnvironment() ? Date.now() : 0;\n\n // Create context object with abort signal\n const context = {\n get signal(): AbortSignal {\n return ensureAbortController(instance).signal;\n },\n };\n\n // Execute component within its owner frame (provider chain).\n // This ensures all context reads see the correct provider values.\n // We create a new execution frame whose parent is the ownerFrame. The\n // `values` map is lazily allocated to avoid per-render Map allocations\n // for components that do not use context.\n const executionFrame: ContextFrame = {\n parent: instance.ownerFrame,\n values: null,\n };\n const result = withContext(executionFrame, () =>\n instance.fn(instance.props, context)\n );\n\n // Check render time\n const renderTime = Date.now() - renderStartTime;\n if (renderTime > 5) {\n warnInstanceOnce(\n instance,\n 'slow-render',\n `[askr] Slow render detected: ${renderTime}ms. Consider optimizing component performance.`\n );\n }\n\n // Mark first render complete after successful execution\n // This enables hook order validation on subsequent renders\n if (!instance.firstRenderComplete) {\n instance.firstRenderComplete = true;\n }\n\n return result;\n } finally {\n // Synchronous path: we did not push a fresh frame, so nothing to pop here.\n currentInstance = null;\n }\n}\n\n/**\n * Public entry point: Execute component with full lifecycle (execute + render)\n * Handles both initial mount and re-execution. Always enqueues through scheduler.\n * Single entry point to avoid lifecycle divergence.\n */\nexport function executeComponent(instance: ComponentInstance): void {\n // Lazily recreate abort controller only when signal is actually requested.\n instance.abortController = null;\n\n // Setup notifyUpdate callback using prebound helper to avoid per-call closures\n instance.notifyUpdate = instance._enqueueRun!;\n\n // Enqueue the initial component run\n globalScheduler.enqueue(instance._pendingRunTask!);\n}\n\nexport function getCurrentInstance(): ComponentInstance | null {\n return currentInstance;\n}\n\n/**\n * Get the abort signal for the current component\n * Used to cancel async operations on unmount/navigation\n *\n * The signal is guaranteed to be aborted when:\n * - Component unmounts\n * - Navigation occurs (different route)\n * - Parent is destroyed\n *\n * IMPORTANT: getSignal() must be called during component render execution.\n * It captures the current component instance from context.\n *\n * @returns AbortSignal that will be aborted when component unmounts\n * @throws Error if called outside component execution\n *\n * @example\n * ```ts\n * // ✅ Correct: called during render, used in async operation\n * export async function UserPage({ id }: { id: string }) {\n * const signal = getSignal();\n * const user = await fetch(`/api/users/${id}`, { signal });\n * return <div>{user.name}</div>;\n * }\n *\n * // ✅ Correct: passed to event handler\n * export function Button() {\n * const signal = getSignal();\n * return {\n * type: 'button',\n * props: {\n * onClick: async () => {\n * const data = await fetch(url, { signal });\n * }\n * }\n * };\n * }\n *\n * // ❌ Wrong: called outside component context\n * const signal = getSignal(); // Error: not in component\n * ```\n */\nexport function getSignal(): AbortSignal {\n if (!currentInstance) {\n throw new Error(\n 'getSignal() can only be called during component render execution. ' +\n 'Ensure you are calling this from inside your component function.'\n );\n }\n return ensureAbortController(currentInstance).signal;\n}\n\n/**\n * Finalize read subscriptions for an instance after a successful commit.\n * - Update per-state readers map to point to this instance's last committed token\n * - Remove this instance from states it no longer reads\n * This is deterministic and runs synchronously with commit to ensure\n * subscribers are only notified when they actually read a state in their\n * last committed render.\n */\nexport function finalizeReadSubscriptions(instance: ComponentInstance): void {\n finalizeReadableSubscriptions(instance);\n}\n\nexport function getNextStateIndex(): number {\n return stateIndex++;\n}\n\nexport function claimHookIndex(\n instance: ComponentInstance,\n hookName: string\n): number {\n const index = getNextStateIndex();\n\n if (index < instance.stateIndexCheck) {\n throw new Error(\n `Hook index violation: ${hookName}() call at index ${index}, ` +\n `but previously saw index ${instance.stateIndexCheck}. ` +\n `This happens when render-scoped hooks are called conditionally (inside if/for/etc). ` +\n `Move all ${hookName}() calls to the top level of your component function, ` +\n `before any conditionals.`\n );\n }\n\n instance.stateIndexCheck = index;\n\n if (instance.firstRenderComplete) {\n if (!instance.expectedStateIndices.includes(index)) {\n throw new Error(\n `Hook order violation: ${hookName}() called at index ${index}, ` +\n `but this index was not in the first render's sequence [${instance.expectedStateIndices.join(', ')}]. ` +\n `This usually means ${hookName}() is inside a conditional or loop. ` +\n `Move all render-scoped hooks to the top level of your component function.`\n );\n }\n } else {\n instance.expectedStateIndices.push(index);\n }\n\n return index;\n}\n\nexport function getCurrentStateIndex(): number {\n return stateIndex;\n}\n\nexport function resetStateIndex(): void {\n stateIndex = 0;\n}\n\nexport function setStateIndex(value: number): void {\n stateIndex = value;\n}\n\n/**\n * Mount a component instance.\n * This is just an alias to executeComponent() to maintain API compatibility.\n * All lifecycle logic is unified in executeComponent().\n */\nexport function mountComponent(instance: ComponentInstance): void {\n executeComponent(instance);\n}\n\n/**\n * Clean up component — abort pending operations\n * Called on unmount or route change\n */\nexport function cleanupComponent(instance: ComponentInstance): void {\n const ownedChildScopes = instance._ownedChildScopes;\n if (ownedChildScopes && ownedChildScopes.size > 0) {\n instance._ownedChildScopes = new Set();\n for (const scope of ownedChildScopes) {\n scope.dispose();\n }\n }\n\n // Execute cleanup functions (from mount effects)\n const cleanupErrors: unknown[] = [];\n const cleanupFns = instance.cleanupFns;\n for (const cleanup of cleanupFns) {\n try {\n cleanup();\n } catch (err) {\n if (instance.cleanupStrict) {\n cleanupErrors.push(err);\n } else {\n // Preserve previous behavior: log warnings in dev and continue\n if (isDevelopmentEnvironment()) {\n logger.warn('[Askr] cleanup function threw:', err);\n }\n }\n }\n }\n instance.cleanupFns = [];\n if (cleanupErrors.length > 0) {\n // If strict mode, surface all cleanup errors as an AggregateError after attempting all cleanups\n throw new AggregateError(\n cleanupErrors,\n `Cleanup failed for component ${instance.id}`\n );\n }\n\n // Remove deterministic state subscriptions for this instance\n cleanupReadableSubscriptions(instance);\n\n // Abort all pending operations\n if (instance.abortController && !instance.abortController.signal.aborted) {\n instance.abortController.abort();\n }\n instance.abortController = null;\n\n // Clear update callback to prevent dangling references and stale updates\n instance.notifyUpdate = null;\n instance._placeholder = undefined;\n\n // Mark instance as unmounted so external tracking (e.g., portal host lists)\n // can deterministically prune stale instances. Not marking this leads to\n // retained \"mounted\" flags across cleanup boundaries which breaks\n // owner selection in the portal fallback.\n instance.mounted = false;\n}\n\nexport function registerOwnedChildScope(\n instance: ComponentInstance,\n scope: OwnedChildScope\n): void {\n const scopes = (instance._ownedChildScopes ??= new Set());\n scopes.add(scope);\n}\n\nexport function unregisterOwnedChildScope(\n instance: ComponentInstance,\n scope: OwnedChildScope\n): void {\n instance._ownedChildScopes?.delete(scope);\n}\n\nfunction warnInstanceOnce(\n instance: ComponentInstance,\n key: string,\n message: string\n): void {\n if (isProductionEnvironment()) return;\n const warnings = (instance.devWarningsEmitted ??= new Set());\n if (warnings.has(key)) return;\n warnings.add(key);\n logger.warn(message);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwEA,SAAgB,wBACd,IACA,IACA,OACA,QACmB;CACnB,MAAM,WAA8B;EAClC;EACA;EACA;EACA;EACA,SAAS;EACT,iBAAiB;EACjB,aAAa,EAAE;EACf,sBAAsB;EACtB,cAAc;EAEd,mBAAmB;EACnB,iBAAiB;EACjB,aAAa;EACb,iBAAiB;EACjB,sBAAsB,EAAE;EACxB,qBAAqB;EACrB,iBAAiB,EAAE;EACnB,YAAY,EAAE;EACd,kBAAkB;EAClB,YAAY;EACZ,KAAK;EACL,eAAe;EACf,QAAQ;EAGR,qBAAqB;EACrB,iBAAiB;EACjB,qBAAqB;EACrB,kBAAkB;EAClB,oBAAoB;EACrB;AAGD,UAAS,wBAAwB;AAE/B,WAAS,mBAAmB;AAE5B,eAAa,SAAS;;AAGxB,UAAS,oBAAoB;AAC3B,MAAI,CAAC,SAAS,kBAAkB;AAC9B,YAAS,mBAAmB;AAE5B,mBAAgB,QAAQ,SAAS,gBAAiB;;;AAMtD,UAAS,oBAAoB,SAAS;AAEtC,QAAO;;AAGT,IAAI,kBAA4C;AAChD,IAAI,aAAa;AAOjB,SAAS,sBAAsB,UAA8C;CAC3E,IAAI,aAAa,SAAS;AAC1B,KAAI,CAAC,cAAc,WAAW,OAAO,SAAS;AAC5C,eAAa,IAAI,iBAAiB;AAClC,WAAS,kBAAkB;;AAE7B,QAAO;;AAIT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,MAAM,gBAA2B,EAAE;CACnC,MAAM,aAAa,SAAS;AAC5B,MAAK,MAAM,WAAW,WACpB,KAAI;AACF,WAAS;UACF,KAAK;AACZ,MAAI,SAAS,cACX,eAAc,KAAK,IAAI;WAGnB,0BAA0B,CAC5B,QAAO,KAAK,kCAAkC,IAAI;;AAK1D,UAAS,aAAa,EAAE;AACxB,KAAI,cAAc,SAAS,EAEzB,OAAM,IAAI,eACR,eACA,gCAAgC,SAAS,KAC1C;AAIH,8BAA6B,SAAS;AAGtC,KAAI,SAAS,mBAAmB,CAAC,SAAS,gBAAgB,OAAO,QAC/D,UAAS,gBAAgB,OAAO;AAElC,UAAS,kBAAkB;AAG3B,UAAS,eAAe;AACxB,UAAS,eAAe;AAMxB,UAAS,UAAU;;AAGrB,SAAgB,wBACd,UACA,OACM;AAEN,EADgB,SAAS,sCAAsB,IAAI,KAAK,EACjD,IAAI,MAAM;;AAGnB,SAAgB,0BACd,UACA,OACM;AACN,UAAS,mBAAmB,OAAO,MAAM;;AAG3C,SAAS,iBACP,UACA,KACA,SACM;AACN,KAAI,yBAAyB,CAAE;CAC/B,MAAM,WAAY,SAAS,uCAAuB,IAAI,KAAK;AAC3D,KAAI,SAAS,IAAI,IAAI,CAAE;AACvB,UAAS,IAAI,IAAI;AACjB,QAAO,KAAK,QAAQ"}
|
|
1
|
+
{"version":3,"file":"component.js","names":[],"sources":["../../src/runtime/component.ts"],"sourcesContent":["/**\n * Component instance lifecycle management\n * Internal only — users never see this\n */\n\nimport { type State } from './state';\nimport { globalScheduler } from './scheduler';\nimport type { Props } from '../common/props';\nimport type { ComponentFunction } from '../common/component';\nimport {\n // withContext is the sole primitive for context restoration\n withContext,\n type ContextFrame,\n} from './context';\nimport {\n type ReadableSource,\n finalizeReadableSubscriptions,\n cleanupReadableSubscriptions,\n} from './readable';\nimport {\n isDevelopmentEnvironment,\n isProductionEnvironment,\n} from '../common/env';\nimport { logger } from '../dev/logger';\nimport { incDevCounter, setDevValue } from './dev-namespace';\n\nexport type { ComponentFunction } from '../common/component';\n\nexport interface ComponentInstance {\n id: string;\n fn: ComponentFunction;\n props: Props;\n target: Element | null;\n mounted: boolean;\n abortController: AbortController | null; // Lazily created per-component abort lifecycle\n ssr?: boolean; // Set to true for SSR temporary instances\n // Opt-in strict cleanup mode: when true cleanup errors are aggregated and re-thrown\n cleanupStrict?: boolean;\n stateValues: State<unknown>[]; // Persistent state storage across renders\n evaluationGeneration: number; // Prevents stale async evaluation completions\n notifyUpdate: (() => void) | null; // Callback for state updates (persisted on instance)\n // Internal: prebound helpers to avoid per-update closures (allocation hot-path)\n _pendingFlushTask?: () => void; // Clears hasPendingUpdate and triggers notifyUpdate\n _pendingRunTask?: () => void; // Clears hasPendingUpdate and runs component\n _enqueueRun?: () => void; // Batches run requests and enqueues _pendingRunTask\n stateIndexCheck: number; // Track state indices to catch conditional calls\n expectedStateIndices: number[]; // Expected sequence of render-scoped hook indices (frozen after first render)\n firstRenderComplete: boolean; // Flag to detect transition from first to subsequent renders\n mountOperations: Array<\n () => void | (() => void) | Promise<void | (() => void)>\n >; // Operations to run when component mounts\n cleanupFns: Array<() => void>; // Cleanup functions to run on unmount\n hasPendingUpdate: boolean; // Flag to batch state updates (coalescing)\n ownerFrame: ContextFrame | null; // Provider chain for this component (set by Scope, never overwritten)\n isRoot?: boolean;\n\n // Render-tracking for precise subscriptions (internal)\n _currentRenderToken?: number; // Token for the in-progress render (set before render)\n lastRenderToken?: number; // Token of the last *committed* render\n _pendingReadSources?: Set<ReadableSource<unknown>>; // Readables read during the in-progress render\n _lastReadSources?: Set<ReadableSource<unknown>>; // Readables read during the last committed render\n devWarningsEmitted?: Set<string>; // Dev-only warning dedupe for this instance\n\n // Placeholder for null-returning components. When a component initially returns\n // null, we create a comment placeholder so updates can replace it with content.\n _placeholder?: Comment;\n _ownedChildScopes?: Set<{\n key: string | number;\n dispose(): void;\n }>;\n errorBoundaryState?: {\n error: unknown | null;\n resetKey: unknown;\n notified: boolean;\n };\n}\n\nexport function createComponentInstance(\n id: string,\n fn: ComponentFunction,\n props: Props,\n target: Element | null\n): ComponentInstance {\n const instance: ComponentInstance = {\n id,\n fn,\n props,\n target,\n mounted: false,\n abortController: null,\n stateValues: [],\n evaluationGeneration: 0,\n notifyUpdate: null,\n // Prebound helpers (initialized below) to avoid per-update allocations\n _pendingFlushTask: undefined,\n _pendingRunTask: undefined,\n _enqueueRun: undefined,\n stateIndexCheck: -1,\n expectedStateIndices: [],\n firstRenderComplete: false,\n mountOperations: [],\n cleanupFns: [],\n hasPendingUpdate: false,\n ownerFrame: null, // Will be set by renderer when vnode is marked\n ssr: false,\n cleanupStrict: false,\n isRoot: false,\n\n // Render-tracking (for precise state subscriptions)\n _currentRenderToken: undefined,\n lastRenderToken: 0,\n _pendingReadSources: undefined,\n _lastReadSources: undefined,\n devWarningsEmitted: undefined,\n };\n\n // Initialize prebound helper tasks once per instance to avoid allocations\n instance._pendingRunTask = () => {\n // Clear pending flag when the run task executes\n instance.hasPendingUpdate = false;\n // Execute component run (will set up notifyUpdate before render)\n runComponent(instance);\n };\n\n instance._enqueueRun = () => {\n if (!instance.hasPendingUpdate) {\n instance.hasPendingUpdate = true;\n // Enqueue single run task (coalesces multiple writes)\n globalScheduler.enqueue(instance._pendingRunTask!);\n }\n };\n\n // Default state-driven updates enqueue the run task directly. Specialized\n // runtimes (for example `For` item instances) can still override this hook.\n instance._pendingFlushTask = instance._pendingRunTask;\n\n return instance;\n}\n\nlet currentInstance: ComponentInstance | null = null;\nlet stateIndex = 0;\n\ntype OwnedChildScope = {\n key: string | number;\n dispose(): void;\n};\n\nfunction ensureAbortController(instance: ComponentInstance): AbortController {\n let controller = instance.abortController;\n if (!controller || controller.signal.aborted) {\n controller = new AbortController();\n instance.abortController = controller;\n }\n return controller;\n}\n\n// Export for state.ts to access\nexport function getCurrentComponentInstance(): ComponentInstance | null {\n return currentInstance;\n}\n\n// Export for SSR to set temporary instance\nexport function setCurrentComponentInstance(\n instance: ComponentInstance | null\n): void {\n currentInstance = instance;\n}\n\n/**\n * Register a mount operation that will run after the component is mounted\n * Used by operations (task, on, timer, etc) to execute after render completes\n */\nimport { isBulkCommitActive } from './fastlane';\nimport { evaluate, cleanupInstancesUnder } from '../renderer';\n\nexport function registerMountOperation(\n operation: () => void | (() => void) | Promise<void | (() => void)>\n): void {\n const instance = getCurrentComponentInstance();\n if (instance) {\n // If we're in bulk-commit fast lane, registering mount operations is a\n // violation of the fast-lane preconditions. Throw in dev, otherwise ignore\n // silently in production (we must avoid scheduling work during bulk commit).\n if (isBulkCommitActive()) {\n if (isDevelopmentEnvironment()) {\n throw new Error(\n 'registerMountOperation called during bulk commit fast-lane'\n );\n }\n return;\n }\n instance.mountOperations.push(operation);\n }\n}\n\n/**\n * Execute all mount operations for a component\n * These run after the component is rendered and mounted to the DOM\n */\nfunction executeMountOperations(instance: ComponentInstance): void {\n // Only execute mount operations for root app instance. Child component\n // operations are currently registered but should not be executed (per\n // contract tests). They remain registered for cleanup purposes.\n if (!instance.isRoot) return;\n\n const mountOperations = instance.mountOperations;\n if (mountOperations.length === 0) {\n return;\n }\n\n for (const operation of mountOperations) {\n const result = operation();\n if (result instanceof Promise) {\n result.then((cleanup) => {\n if (typeof cleanup === 'function') {\n instance.cleanupFns.push(cleanup);\n }\n });\n } else if (typeof result === 'function') {\n instance.cleanupFns.push(result);\n }\n }\n // Clear the operations array so they don't run again on subsequent renders\n instance.mountOperations = [];\n}\n\nexport function mountInstanceInline(\n instance: ComponentInstance,\n target: Element | null\n): void {\n instance.target = target;\n // Record backref on host element so renderer can clean up when the\n // node is removed. Avoids leaks if the node is detached or replaced.\n try {\n if (target instanceof Element) {\n const host = target as Element & {\n __ASKR_INSTANCE?: ComponentInstance;\n __ASKR_INSTANCES?: ComponentInstance[];\n };\n const instances = host.__ASKR_INSTANCES ?? [];\n const nextInstances = instances.filter((entry) => entry !== instance);\n nextInstances.push(instance);\n host.__ASKR_INSTANCES = nextInstances;\n host.__ASKR_INSTANCE = nextInstances[0] ?? instance;\n }\n } catch (err) {\n void err;\n }\n\n // Ensure notifyUpdate is available for async resource completions that may\n // try to trigger re-render. This mirrors the setup in executeComponent().\n // Use prebound enqueue helper to avoid allocating a new closure\n instance.notifyUpdate = instance._enqueueRun!;\n\n const wasFirstMount = !instance.mounted;\n instance.mounted = true;\n if (wasFirstMount && instance.mountOperations.length > 0) {\n executeMountOperations(instance);\n }\n}\n\n/**\n * Run a component synchronously: execute function, handle result\n * This is the internal workhorse that manages async continuations and generation tracking.\n * Must always be called through the scheduler.\n *\n * ACTOR INVARIANT: This function is enqueued as a task, never called directly.\n */\nlet _globalRenderCounter = 0;\n\nfunction resetRenderState(instance: ComponentInstance): void {\n instance.stateIndexCheck = -1;\n\n for (const state of instance.stateValues) {\n if (state) {\n state._hasBeenRead = false;\n }\n }\n\n instance._pendingReadSources = undefined;\n}\n\nfunction nextRenderToken(): number {\n return ++_globalRenderCounter;\n}\n\nexport function renderScopedComponent<T>(\n instance: ComponentInstance,\n startStateIndex: number,\n render: () => T\n): T {\n const savedInstance = currentInstance;\n const savedStateIndex = stateIndex;\n\n instance.notifyUpdate = instance._enqueueRun!;\n resetRenderState(instance);\n instance._currentRenderToken = nextRenderToken();\n\n currentInstance = instance;\n stateIndex = startStateIndex;\n\n let didComplete = false;\n\n try {\n const executionFrame: ContextFrame = {\n parent: instance.ownerFrame,\n values: null,\n };\n const result = withContext(executionFrame, render);\n didComplete = true;\n return result;\n } finally {\n if (!didComplete) {\n instance._pendingReadSources = undefined;\n instance._currentRenderToken = undefined;\n }\n currentInstance = savedInstance;\n stateIndex = savedStateIndex;\n }\n}\n\nfunction runComponent(instance: ComponentInstance): void {\n // CRITICAL: Ensure notifyUpdate is available for state.set() calls during this render.\n // This must be set before executeComponentSync() runs, not after.\n // Use prebound enqueue helper to avoid allocating per-render closures\n instance.notifyUpdate = instance._enqueueRun!;\n\n // Assign a token for this in-progress render and start a fresh pending-read set\n instance._currentRenderToken = nextRenderToken();\n instance._pendingReadSources = undefined;\n const domSnapshot = instance.target ? instance.target.innerHTML : '';\n\n const result = executeComponentSync(instance);\n if (result instanceof Promise) {\n // Async components are not supported. Components must be synchronous and\n // must not return a Promise from their render function.\n throw new Error(\n 'Async components are not supported. Components must be synchronous.'\n );\n } else {\n // Try runtime fast-lane synchronously; if it activates we do not enqueue\n // follow-up work and the commit happens atomically in this task.\n // (Runtime fast-lane has conservative preconditions.)\n const fastlaneBridge = (\n globalThis as {\n __ASKR_FASTLANE?: {\n tryRuntimeFastLaneSync?: (\n instance: unknown,\n result: unknown\n ) => boolean;\n };\n }\n ).__ASKR_FASTLANE;\n try {\n const used = fastlaneBridge?.tryRuntimeFastLaneSync?.(instance, result);\n if (used) {\n warnUnusedStateReads(instance);\n return;\n }\n } catch (err) {\n // If invariant check failed in dev, surface the error; otherwise fall back\n if (isDevelopmentEnvironment()) throw err;\n }\n\n // Fallback: enqueue the render/commit normally\n globalScheduler.enqueue(() => {\n // Handle placeholder-based updates: when a component initially returned null,\n // we created a comment placeholder. If it now has content, we need to create\n // a host element and replace the placeholder.\n if (!instance.target && instance._placeholder) {\n // Component previously returned null (has placeholder), check if now has content\n if (result === null || result === undefined) {\n // Still null - nothing to do, keep placeholder\n finalizeReadSubscriptions(instance);\n warnUnusedStateReads(instance);\n return;\n }\n\n // Has content now - need to create DOM and replace placeholder\n const placeholder = instance._placeholder;\n const parent = placeholder.parentNode;\n if (!parent) {\n // Placeholder was removed from DOM - can't render\n logger.warn(\n '[Askr] placeholder no longer in DOM, cannot render component'\n );\n return;\n }\n\n // Create a new host element for the content\n const host = document.createElement('div');\n const executionFrame: ContextFrame = {\n parent: instance.ownerFrame,\n values: null,\n };\n\n // Set up instance for normal updates\n const oldInstance = currentInstance;\n currentInstance = instance;\n try {\n withContext(executionFrame, () => {\n evaluate(result, host);\n });\n\n // Replace placeholder with host\n parent.replaceChild(host, placeholder);\n\n // Set up instance for future updates\n instance.target = host;\n instance._placeholder = undefined;\n (\n host as Element & { __ASKR_INSTANCE?: ComponentInstance }\n ).__ASKR_INSTANCE = instance;\n\n finalizeReadSubscriptions(instance);\n warnUnusedStateReads(instance);\n } finally {\n currentInstance = oldInstance;\n }\n return;\n }\n\n if (instance.target) {\n let oldChildren: Node[] = [];\n try {\n const wasFirstMount = !instance.mounted;\n // Ensure nested component executions during evaluation have access to\n // the current component instance. This allows nested components to\n // call `state()`, `resource()`, and other runtime helpers which\n // rely on `getCurrentComponentInstance()` being available.\n const oldInstance = currentInstance;\n currentInstance = instance;\n const executionFrame: ContextFrame = {\n parent: instance.ownerFrame,\n values: null,\n };\n // Capture snapshot of current children (by reference) so we can\n // restore them on render failure without losing event listeners or\n // instance attachments.\n oldChildren = Array.from(instance.target.childNodes);\n\n try {\n withContext(executionFrame, () => {\n evaluate(result, instance.target);\n });\n } catch (e) {\n // If evaluation failed, attempt to cleanup any partially-added nodes\n // and restore the old children to preserve listeners and instances.\n try {\n const newChildren = Array.from(instance.target.childNodes);\n for (const n of newChildren) {\n try {\n cleanupInstancesUnder(n);\n } catch (err) {\n logger.warn(\n '[Askr] error cleaning up failed commit children:',\n err\n );\n }\n }\n } catch (_err) {\n void _err;\n }\n\n // Restore original children by re-inserting the old node references\n // this preserves attached listeners and instance backrefs.\n try {\n incDevCounter('__DOM_REPLACE_COUNT');\n setDevValue(\n '__LAST_DOM_REPLACE_STACK_COMPONENT_RESTORE',\n new Error().stack\n );\n } catch (e) {\n void e;\n }\n instance.target.replaceChildren(...oldChildren);\n throw e;\n } finally {\n currentInstance = oldInstance;\n }\n\n // Commit succeeded — finalize recorded state reads so subscriptions reflect\n // the last *committed* render. This updates per-state reader maps\n // deterministically and synchronously with the commit.\n finalizeReadSubscriptions(instance);\n warnUnusedStateReads(instance);\n\n instance.mounted = true;\n // Execute mount operations after first mount (do NOT run these with\n // currentInstance set - they may perform state mutations/registrations)\n if (wasFirstMount && instance.mountOperations.length > 0) {\n executeMountOperations(instance);\n }\n } catch (renderError) {\n // Atomic rendering: rollback on render error. Attempt non-lossy restore of\n // original child node references to preserve listeners/instances.\n try {\n const currentChildren = Array.from(instance.target.childNodes);\n for (const n of currentChildren) {\n try {\n cleanupInstancesUnder(n);\n } catch (err) {\n logger.warn(\n '[Askr] error cleaning up partial children during rollback:',\n err\n );\n }\n }\n } catch (_err) {\n void _err;\n }\n\n try {\n incDevCounter('__DOM_REPLACE_COUNT');\n setDevValue(\n '__LAST_DOM_REPLACE_STACK_COMPONENT_ROLLBACK',\n new Error().stack\n );\n instance.target.replaceChildren(...oldChildren);\n } catch {\n // Fallback to innerHTML restore if replaceChildren fails for some reason.\n instance.target.innerHTML = domSnapshot;\n }\n\n throw renderError;\n }\n }\n });\n }\n}\n\n/**\n * Execute a component's render function synchronously.\n * Returns either a vnode/promise immediately (does NOT render).\n * Rendering happens separately through runComponent.\n */\nexport function renderComponentInline(\n instance: ComponentInstance\n): unknown | Promise<unknown> {\n // Ensure inline executions (rendered during parent's evaluate) still\n // receive a render token and have their state reads finalized so\n // subscriptions are correctly recorded. If this function is called\n // as part of a scheduled run, the token will already be set by\n // runComponent and we should not overwrite it.\n const hadToken = instance._currentRenderToken !== undefined;\n const prevToken = instance._currentRenderToken;\n const prevPendingReads = instance._pendingReadSources;\n if (!hadToken) {\n instance._currentRenderToken = nextRenderToken();\n instance._pendingReadSources = undefined;\n }\n\n try {\n const result = executeComponentSync(instance);\n // If we set the token for inline execution, finalize subscriptions now\n // because the component is effectively committed as part of the parent's\n // synchronous evaluation.\n if (!hadToken) {\n finalizeReadSubscriptions(instance);\n }\n return result;\n } finally {\n // Restore previous token/read states for nested inline render scenarios\n instance._currentRenderToken = prevToken;\n instance._pendingReadSources = prevPendingReads;\n }\n}\n\nexport function warnUnusedStateReads(instance: ComponentInstance): void {\n for (let i = 0; i < instance.stateValues.length; i++) {\n const state = instance.stateValues[i];\n const hasCommittedUsage =\n (state?._readers?.size ?? 0) > 0 ||\n ((state as { _derivedSubscribers?: Set<unknown> } | undefined)\n ?._derivedSubscribers?.size ?? 0) > 0;\n\n if (state && !state._hasBeenRead && !hasCommittedUsage) {\n try {\n const name = instance.fn?.name || '<anonymous>';\n warnInstanceOnce(\n instance,\n `unused-state:${i}`,\n `[askr] Unused state variable detected in ${name} at index ${i}. State should be read during render or removed.`\n );\n } catch {\n warnInstanceOnce(\n instance,\n `unused-state:${i}`,\n `[askr] Unused state variable detected. State should be read during render or removed.`\n );\n }\n }\n }\n}\n\nfunction executeComponentSync(\n instance: ComponentInstance\n): unknown | Promise<unknown> {\n resetRenderState(instance);\n incDevCounter('componentRuns');\n incDevCounter('componentReruns');\n\n currentInstance = instance;\n stateIndex = 0;\n\n try {\n // Track render time in dev mode\n const renderStartTime = isDevelopmentEnvironment() ? Date.now() : 0;\n\n // Create context object with abort signal\n const context = {\n get signal(): AbortSignal {\n return ensureAbortController(instance).signal;\n },\n };\n\n // Execute component within its owner frame (provider chain).\n // This ensures all context reads see the correct provider values.\n // We create a new execution frame whose parent is the ownerFrame. The\n // `values` map is lazily allocated to avoid per-render Map allocations\n // for components that do not use context.\n const executionFrame: ContextFrame = {\n parent: instance.ownerFrame,\n values: null,\n };\n const result = withContext(executionFrame, () =>\n instance.fn(instance.props, context)\n );\n\n // Check render time\n const renderTime = Date.now() - renderStartTime;\n if (renderTime > 5) {\n warnInstanceOnce(\n instance,\n 'slow-render',\n `[askr] Slow render detected: ${renderTime}ms. Consider optimizing component performance.`\n );\n }\n\n // Mark first render complete after successful execution\n // This enables hook order validation on subsequent renders\n if (!instance.firstRenderComplete) {\n instance.firstRenderComplete = true;\n }\n\n return result;\n } finally {\n // Synchronous path: we did not push a fresh frame, so nothing to pop here.\n currentInstance = null;\n }\n}\n\n/**\n * Public entry point: Execute component with full lifecycle (execute + render)\n * Handles both initial mount and re-execution. Always enqueues through scheduler.\n * Single entry point to avoid lifecycle divergence.\n */\nexport function executeComponent(instance: ComponentInstance): void {\n // Lazily recreate abort controller only when signal is actually requested.\n instance.abortController = null;\n\n // Setup notifyUpdate callback using prebound helper to avoid per-call closures\n instance.notifyUpdate = instance._enqueueRun!;\n\n // Enqueue the initial component run\n globalScheduler.enqueue(instance._pendingRunTask!);\n}\n\nexport function getCurrentInstance(): ComponentInstance | null {\n return currentInstance;\n}\n\n/**\n * Get the abort signal for the current component\n * Used to cancel async operations on unmount/navigation\n *\n * The signal is guaranteed to be aborted when:\n * - Component unmounts\n * - Navigation occurs (different route)\n * - Parent is destroyed\n *\n * IMPORTANT: getSignal() must be called during component render execution.\n * It captures the current component instance from context.\n *\n * @returns AbortSignal that will be aborted when component unmounts\n * @throws Error if called outside component execution\n *\n * @example\n * ```ts\n * // ✅ Correct: called during render, used in async operation\n * export async function UserPage({ id }: { id: string }) {\n * const signal = getSignal();\n * const user = await fetch(`/api/users/${id}`, { signal });\n * return <div>{user.name}</div>;\n * }\n *\n * // ✅ Correct: passed to event handler\n * export function Button() {\n * const signal = getSignal();\n * return {\n * type: 'button',\n * props: {\n * onClick: async () => {\n * const data = await fetch(url, { signal });\n * }\n * }\n * };\n * }\n *\n * // ❌ Wrong: called outside component context\n * const signal = getSignal(); // Error: not in component\n * ```\n */\nexport function getSignal(): AbortSignal {\n if (!currentInstance) {\n throw new Error(\n 'getSignal() can only be called during component render execution. ' +\n 'Ensure you are calling this from inside your component function.'\n );\n }\n return ensureAbortController(currentInstance).signal;\n}\n\n/**\n * Finalize read subscriptions for an instance after a successful commit.\n * - Update per-state readers map to point to this instance's last committed token\n * - Remove this instance from states it no longer reads\n * This is deterministic and runs synchronously with commit to ensure\n * subscribers are only notified when they actually read a state in their\n * last committed render.\n */\nexport function finalizeReadSubscriptions(instance: ComponentInstance): void {\n finalizeReadableSubscriptions(instance);\n}\n\nexport function getNextStateIndex(): number {\n return stateIndex++;\n}\n\nexport function claimHookIndex(\n instance: ComponentInstance,\n hookName: string\n): number {\n const index = getNextStateIndex();\n\n if (index < instance.stateIndexCheck) {\n throw new Error(\n `Hook index violation: ${hookName}() call at index ${index}, ` +\n `but previously saw index ${instance.stateIndexCheck}. ` +\n `This happens when render-scoped hooks are called conditionally (inside if/for/etc). ` +\n `Move all ${hookName}() calls to the top level of your component function, ` +\n `before any conditionals.`\n );\n }\n\n instance.stateIndexCheck = index;\n\n if (instance.firstRenderComplete) {\n if (!instance.expectedStateIndices.includes(index)) {\n throw new Error(\n `Hook order violation: ${hookName}() called at index ${index}, ` +\n `but this index was not in the first render's sequence [${instance.expectedStateIndices.join(', ')}]. ` +\n `This usually means ${hookName}() is inside a conditional or loop. ` +\n `Move all render-scoped hooks to the top level of your component function.`\n );\n }\n } else {\n instance.expectedStateIndices.push(index);\n }\n\n return index;\n}\n\nexport function getCurrentStateIndex(): number {\n return stateIndex;\n}\n\nexport function resetStateIndex(): void {\n stateIndex = 0;\n}\n\nexport function setStateIndex(value: number): void {\n stateIndex = value;\n}\n\n/**\n * Mount a component instance.\n * This is just an alias to executeComponent() to maintain API compatibility.\n * All lifecycle logic is unified in executeComponent().\n */\nexport function mountComponent(instance: ComponentInstance): void {\n executeComponent(instance);\n}\n\n/**\n * Clean up component — abort pending operations\n * Called on unmount or route change\n */\nexport function cleanupComponent(instance: ComponentInstance): void {\n const ownedChildScopes = instance._ownedChildScopes;\n if (ownedChildScopes && ownedChildScopes.size > 0) {\n instance._ownedChildScopes = new Set();\n for (const scope of ownedChildScopes) {\n scope.dispose();\n }\n }\n\n // Execute cleanup functions (from mount effects)\n const cleanupErrors: unknown[] = [];\n const cleanupFns = instance.cleanupFns;\n for (const cleanup of cleanupFns) {\n try {\n cleanup();\n } catch (err) {\n if (instance.cleanupStrict) {\n cleanupErrors.push(err);\n } else {\n // Preserve previous behavior: log warnings in dev and continue\n if (isDevelopmentEnvironment()) {\n logger.warn('[Askr] cleanup function threw:', err);\n }\n }\n }\n }\n instance.cleanupFns = [];\n if (cleanupErrors.length > 0) {\n // If strict mode, surface all cleanup errors as an AggregateError after attempting all cleanups\n throw new AggregateError(\n cleanupErrors,\n `Cleanup failed for component ${instance.id}`\n );\n }\n\n // Remove deterministic state subscriptions for this instance\n cleanupReadableSubscriptions(instance);\n\n // Abort all pending operations\n if (instance.abortController && !instance.abortController.signal.aborted) {\n instance.abortController.abort();\n }\n instance.abortController = null;\n\n // Clear update callback to prevent dangling references and stale updates\n instance.notifyUpdate = null;\n instance._placeholder = undefined;\n\n // Mark instance as unmounted so external tracking (e.g., portal host lists)\n // can deterministically prune stale instances. Not marking this leads to\n // retained \"mounted\" flags across cleanup boundaries which breaks\n // owner selection in the portal fallback.\n instance.mounted = false;\n}\n\nexport function registerOwnedChildScope(\n instance: ComponentInstance,\n scope: OwnedChildScope\n): void {\n const scopes = (instance._ownedChildScopes ??= new Set());\n scopes.add(scope);\n}\n\nexport function unregisterOwnedChildScope(\n instance: ComponentInstance,\n scope: OwnedChildScope\n): void {\n instance._ownedChildScopes?.delete(scope);\n}\n\nfunction warnInstanceOnce(\n instance: ComponentInstance,\n key: string,\n message: string\n): void {\n if (isProductionEnvironment()) return;\n const warnings = (instance.devWarningsEmitted ??= new Set());\n if (warnings.has(key)) return;\n warnings.add(key);\n logger.warn(message);\n}\n"],"mappings":";;;;;;;;;;;;;;;AA6EA,SAAgB,wBACd,IACA,IACA,OACA,QACmB;CACnB,MAAM,WAA8B;EAClC;EACA;EACA;EACA;EACA,SAAS;EACT,iBAAiB;EACjB,aAAa,EAAE;EACf,sBAAsB;EACtB,cAAc;EAEd,mBAAmB;EACnB,iBAAiB;EACjB,aAAa;EACb,iBAAiB;EACjB,sBAAsB,EAAE;EACxB,qBAAqB;EACrB,iBAAiB,EAAE;EACnB,YAAY,EAAE;EACd,kBAAkB;EAClB,YAAY;EACZ,KAAK;EACL,eAAe;EACf,QAAQ;EAGR,qBAAqB;EACrB,iBAAiB;EACjB,qBAAqB;EACrB,kBAAkB;EAClB,oBAAoB;EACrB;AAGD,UAAS,wBAAwB;AAE/B,WAAS,mBAAmB;AAE5B,eAAa,SAAS;;AAGxB,UAAS,oBAAoB;AAC3B,MAAI,CAAC,SAAS,kBAAkB;AAC9B,YAAS,mBAAmB;AAE5B,mBAAgB,Q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AAAA;AAAA,iBAGc,cAAA,CACd,SAAA,GACE,KAAA,GAAQ,MAAA,sBACL,KAAA,GAAQ,UAAA;AAAA,iBAEC,cAAA,CAAe,IAAA;EAC7B,GAAA;EACA,MAAA,EAAQ,QAAA;EACR,IAAA;EACA,IAAA,GAAO,OAAA;AAAA;AAAA,iBAuBO,cAAA,CAAe,IAAA;EAC7B,GAAA;EACA,MAAA,EAAQ,QAAA;EACR,IAAA;EACA,IAAA,GAAO,OAAA;EACP,OAAA,CAAQ,IAAA;EACR,UAAA;AAAA"}
|
package/dist/ssr/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { __CONTROL_BOUNDARY__ } from "../common/control.js";
|
|
2
|
+
import { __ERROR_BOUNDARY__ } from "../common/vnode.js";
|
|
2
3
|
import { logger } from "../dev/logger.js";
|
|
3
4
|
import { ELEMENT_TYPE, Fragment } from "../common/jsx.js";
|
|
4
5
|
import { createComponentInstance, getCurrentComponentInstance, setCurrentComponentInstance } from "../runtime/component.js";
|
|
@@ -78,6 +79,88 @@ function renderChildrenSync(children, ctx) {
|
|
|
78
79
|
}
|
|
79
80
|
return Array.from({ length: children.length }, (_, index) => renderChildSync(children[index], ctx)).join("");
|
|
80
81
|
}
|
|
82
|
+
function normalizeRenderableChildren(value) {
|
|
83
|
+
if (value === null || value === void 0 || value === false) return [];
|
|
84
|
+
return Array.isArray(value) ? value : [value];
|
|
85
|
+
}
|
|
86
|
+
function getErrorBoundaryState(node) {
|
|
87
|
+
return node.__instance?.errorBoundaryState ?? null;
|
|
88
|
+
}
|
|
89
|
+
function createDefaultErrorBoundaryFallbackVNode(error) {
|
|
90
|
+
const message = error instanceof Error ? error.stack || error.message || error.name : typeof error === "string" ? error : (() => {
|
|
91
|
+
try {
|
|
92
|
+
return JSON.stringify(error);
|
|
93
|
+
} catch {
|
|
94
|
+
return String(error);
|
|
95
|
+
}
|
|
96
|
+
})();
|
|
97
|
+
return {
|
|
98
|
+
$$typeof: ELEMENT_TYPE,
|
|
99
|
+
type: "div",
|
|
100
|
+
props: {
|
|
101
|
+
role: "alert",
|
|
102
|
+
"data-askr-error-boundary": "true",
|
|
103
|
+
style: {
|
|
104
|
+
boxSizing: "border-box",
|
|
105
|
+
padding: "1rem",
|
|
106
|
+
border: "1px solid currentColor",
|
|
107
|
+
borderRadius: "0.75rem",
|
|
108
|
+
display: "grid",
|
|
109
|
+
gap: "0.75rem",
|
|
110
|
+
maxWidth: "100%"
|
|
111
|
+
},
|
|
112
|
+
children: [
|
|
113
|
+
{
|
|
114
|
+
$$typeof: ELEMENT_TYPE,
|
|
115
|
+
type: "strong",
|
|
116
|
+
props: { children: ["Something went wrong while rendering this view."] }
|
|
117
|
+
},
|
|
118
|
+
{
|
|
119
|
+
$$typeof: ELEMENT_TYPE,
|
|
120
|
+
type: "p",
|
|
121
|
+
props: {
|
|
122
|
+
style: { margin: "0" },
|
|
123
|
+
children: ["The app recovered into a visible fallback so the error is not hidden in the console."]
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
$$typeof: ELEMENT_TYPE,
|
|
128
|
+
type: "details",
|
|
129
|
+
props: {
|
|
130
|
+
open: true,
|
|
131
|
+
children: [{
|
|
132
|
+
$$typeof: ELEMENT_TYPE,
|
|
133
|
+
type: "summary",
|
|
134
|
+
props: { children: ["Error details"] }
|
|
135
|
+
}, {
|
|
136
|
+
$$typeof: ELEMENT_TYPE,
|
|
137
|
+
type: "pre",
|
|
138
|
+
props: {
|
|
139
|
+
style: {
|
|
140
|
+
margin: "0",
|
|
141
|
+
whiteSpace: "pre-wrap",
|
|
142
|
+
wordBreak: "break-word"
|
|
143
|
+
},
|
|
144
|
+
children: [message]
|
|
145
|
+
}
|
|
146
|
+
}]
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
]
|
|
150
|
+
},
|
|
151
|
+
key: null
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
function resolveErrorBoundaryFallbackNode(fallback, error, reset) {
|
|
155
|
+
return typeof fallback === "function" ? fallback(error, reset) : fallback !== void 0 ? fallback : createDefaultErrorBoundaryFallbackVNode(error);
|
|
156
|
+
}
|
|
157
|
+
function renderErrorBoundaryFallbackValue(fallback, error, reset, ctx) {
|
|
158
|
+
const nextValue = resolveErrorBoundaryFallbackNode(fallback, error, reset);
|
|
159
|
+
return Array.isArray(nextValue) ? renderChildrenSync(normalizeRenderableChildren(nextValue), ctx) : renderChildSync(nextValue, ctx);
|
|
160
|
+
}
|
|
161
|
+
function renderErrorBoundaryFallbackValueToSink(fallback, error, reset, sink, ctx) {
|
|
162
|
+
sink.write(renderErrorBoundaryFallbackValue(fallback, error, reset, ctx));
|
|
163
|
+
}
|
|
81
164
|
function getControlBoundaryState(node) {
|
|
82
165
|
const boundaryNode = node;
|
|
83
166
|
return boundaryNode._controlState ?? boundaryNode._forState ?? null;
|
|
@@ -151,6 +234,28 @@ function renderNodeSync(node, ctx) {
|
|
|
151
234
|
return renderChildrenSync(childrenArr, ctx);
|
|
152
235
|
}
|
|
153
236
|
if (type === __CONTROL_BOUNDARY__) return renderChildrenSync(evaluateControlBoundaryChildren(node), ctx);
|
|
237
|
+
if (type === __ERROR_BOUNDARY__) {
|
|
238
|
+
const boundaryState = getErrorBoundaryState(node);
|
|
239
|
+
const fallback = props?.fallback;
|
|
240
|
+
const reset = () => {
|
|
241
|
+
const state = node.__instance?.errorBoundaryState;
|
|
242
|
+
if (state) {
|
|
243
|
+
state.error = null;
|
|
244
|
+
state.notified = false;
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
if (boundaryState?.error != null) return renderErrorBoundaryFallbackValue(fallback, boundaryState.error, reset, ctx);
|
|
248
|
+
try {
|
|
249
|
+
return renderChildrenSync(normalizeRenderableChildren(props?.children), ctx);
|
|
250
|
+
} catch (error) {
|
|
251
|
+
if (boundaryState) {
|
|
252
|
+
boundaryState.error = error;
|
|
253
|
+
boundaryState.notified = true;
|
|
254
|
+
}
|
|
255
|
+
logger.error("[Askr] ErrorBoundary caught render error:", error);
|
|
256
|
+
return renderErrorBoundaryFallbackValue(fallback, error, reset, ctx);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
154
259
|
throw new Error(`renderNodeSync: unsupported VNode symbol type: ${String(type)}`);
|
|
155
260
|
}
|
|
156
261
|
const typeStr = type;
|
|
@@ -178,6 +283,32 @@ function renderNodeSyncToSink(node, sink, ctx) {
|
|
|
178
283
|
renderChildrenSyncToSink(evaluateControlBoundaryChildren(node), sink, ctx);
|
|
179
284
|
return;
|
|
180
285
|
}
|
|
286
|
+
if (type === __ERROR_BOUNDARY__) {
|
|
287
|
+
const boundaryState = getErrorBoundaryState(node);
|
|
288
|
+
const fallback = props?.fallback;
|
|
289
|
+
const reset = () => {
|
|
290
|
+
const state = node.__instance?.errorBoundaryState;
|
|
291
|
+
if (state) {
|
|
292
|
+
state.error = null;
|
|
293
|
+
state.notified = false;
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
if (boundaryState?.error != null) {
|
|
297
|
+
renderErrorBoundaryFallbackValueToSink(fallback, boundaryState.error, reset, sink, ctx);
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
try {
|
|
301
|
+
renderChildrenSyncToSink(normalizeRenderableChildren(props?.children), sink, ctx);
|
|
302
|
+
} catch (error) {
|
|
303
|
+
if (boundaryState) {
|
|
304
|
+
boundaryState.error = error;
|
|
305
|
+
boundaryState.notified = true;
|
|
306
|
+
}
|
|
307
|
+
logger.error("[Askr] ErrorBoundary caught render error:", error);
|
|
308
|
+
renderErrorBoundaryFallbackValueToSink(fallback, error, reset, sink, ctx);
|
|
309
|
+
}
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
181
312
|
throw new Error(`renderNodeSyncToSink: unsupported VNode symbol type: ${String(type)}`);
|
|
182
313
|
}
|
|
183
314
|
const typeStr = type;
|
|
@@ -364,6 +495,33 @@ function verifyExpectedNode(node, state, ctx) {
|
|
|
364
495
|
for (let index = 0; index < children.length; index += 1) if (!verifyExpectedNode(children[index], state, ctx)) return false;
|
|
365
496
|
return true;
|
|
366
497
|
}
|
|
498
|
+
if (type === __ERROR_BOUNDARY__) {
|
|
499
|
+
const boundaryState = getErrorBoundaryState(vnode);
|
|
500
|
+
const fallback = props?.fallback;
|
|
501
|
+
const reset = () => {
|
|
502
|
+
const stateRef = vnode.__instance?.errorBoundaryState;
|
|
503
|
+
if (stateRef) {
|
|
504
|
+
stateRef.error = null;
|
|
505
|
+
stateRef.notified = false;
|
|
506
|
+
}
|
|
507
|
+
};
|
|
508
|
+
const snapshot = {
|
|
509
|
+
current: state.current,
|
|
510
|
+
pendingText: state.pendingText
|
|
511
|
+
};
|
|
512
|
+
if (boundaryState?.error != null) return verifyRenderableNode(resolveErrorBoundaryFallbackNode(fallback, boundaryState.error, reset), state, ctx);
|
|
513
|
+
try {
|
|
514
|
+
if (verifyExpectedChildren(normalizeRenderableChildren(props?.children), state, ctx)) return true;
|
|
515
|
+
} catch (error) {
|
|
516
|
+
if (boundaryState) {
|
|
517
|
+
boundaryState.error = error;
|
|
518
|
+
boundaryState.notified = true;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
state.current = snapshot.current;
|
|
522
|
+
state.pendingText = snapshot.pendingText;
|
|
523
|
+
return verifyRenderableNode(resolveErrorBoundaryFallbackNode(fallback, boundaryState?.error ?? /* @__PURE__ */ new Error("ErrorBoundary render failed"), reset), state, ctx);
|
|
524
|
+
}
|
|
367
525
|
if (type !== Fragment) throw new Error(`verifyHydrationSyncForUrl: unsupported VNode symbol type: ${String(type)}`);
|
|
368
526
|
const children = getRenderableChildren(vnode);
|
|
369
527
|
if (!children || children.length === 0) return true;
|
|
@@ -406,6 +564,14 @@ function verifyHydrationRoot(root, node, ctx) {
|
|
|
406
564
|
if (!verifyExpectedNode(node, state, ctx)) return false;
|
|
407
565
|
return flushPendingText(state) && state.current === null;
|
|
408
566
|
}
|
|
567
|
+
function verifyExpectedChildren(children, state, ctx) {
|
|
568
|
+
if (!children || children.length === 0) return true;
|
|
569
|
+
for (let index = 0; index < children.length; index += 1) if (!verifyExpectedNode(children[index], state, ctx)) return false;
|
|
570
|
+
return true;
|
|
571
|
+
}
|
|
572
|
+
function verifyRenderableNode(value, state, ctx) {
|
|
573
|
+
return Array.isArray(value) ? verifyExpectedChildren(normalizeRenderableChildren(value), state, ctx) : verifyExpectedNode(value, state, ctx);
|
|
574
|
+
}
|
|
409
575
|
/**
|
|
410
576
|
* Single synchronous SSR entrypoint: render a component to an HTML string.
|
|
411
577
|
* This is strictly synchronous and deterministic. Optionally provide a seed
|