@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.
- package/dist/bench/components/benchmark-row.js.map +1 -1
- package/dist/bench/components/benchmark-table.js.map +1 -1
- package/dist/benchmark.js +2 -2
- package/dist/benchmark.js.map +1 -1
- package/dist/bin/askr-ssg.js.map +1 -1
- package/dist/boot/index.d.ts.map +1 -1
- package/dist/boot/index.js +9 -29
- package/dist/boot/index.js.map +1 -1
- package/dist/common/control.js.map +1 -1
- package/dist/common/env.js.map +1 -1
- package/dist/common/ssr-errors.js.map +1 -1
- package/dist/common/vnode.js.map +1 -1
- package/dist/components/error-boundary.js.map +1 -1
- package/dist/components/link.js.map +1 -1
- package/dist/control/case.js.map +1 -1
- package/dist/control/for.js.map +1 -1
- package/dist/control/shared.js.map +1 -1
- package/dist/control/show.js.map +1 -1
- package/dist/data/index.d.ts.map +1 -1
- package/dist/data/index.js +165 -23
- package/dist/data/index.js.map +1 -1
- package/dist/dev/invariant.js.map +1 -1
- package/dist/dev/logger.js.map +1 -1
- package/dist/foundations/icon/icon.js.map +1 -1
- package/dist/foundations/interactions/dismissable.js.map +1 -1
- package/dist/foundations/interactions/focusable.js.map +1 -1
- package/dist/foundations/interactions/hoverable.js.map +1 -1
- package/dist/foundations/interactions/interaction-policy.js.map +1 -1
- package/dist/foundations/interactions/pressable.js.map +1 -1
- package/dist/foundations/interactions/roving-focus.js.map +1 -1
- package/dist/foundations/state/controllable.js.map +1 -1
- package/dist/foundations/structures/collection.js.map +1 -1
- package/dist/foundations/structures/layer.js.map +1 -1
- package/dist/foundations/structures/layout.js.map +1 -1
- package/dist/foundations/structures/portal.js.map +1 -1
- package/dist/foundations/structures/presence.js.map +1 -1
- package/dist/foundations/structures/slot.js.map +1 -1
- package/dist/foundations/utilities/aria.js.map +1 -1
- package/dist/foundations/utilities/compose-handlers.js.map +1 -1
- package/dist/foundations/utilities/compose-ref.js.map +1 -1
- package/dist/foundations/utilities/merge-props.js.map +1 -1
- package/dist/foundations/utilities/use-id.js.map +1 -1
- package/dist/fx/fx.js.map +1 -1
- package/dist/fx/timing.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/jsx/utils.js.map +1 -1
- package/dist/jsx-dev-runtime.js.map +1 -1
- package/dist/jsx-runtime.js.map +1 -1
- package/dist/renderer/children.js.map +1 -1
- package/dist/renderer/cleanup.js.map +1 -1
- package/dist/renderer/dom.js +128 -53
- package/dist/renderer/dom.js.map +1 -1
- package/dist/renderer/evaluate.js +7 -0
- package/dist/renderer/evaluate.js.map +1 -1
- package/dist/renderer/fastpath.js.map +1 -1
- package/dist/renderer/index.js.map +1 -1
- package/dist/renderer/keyed.js +1 -1
- package/dist/renderer/keyed.js.map +1 -1
- package/dist/renderer/reconcile.js.map +1 -1
- package/dist/renderer/utils.js.map +1 -1
- package/dist/router/index.d.ts +2 -2
- package/dist/router/index.js +2 -2
- package/dist/router/match.js.map +1 -1
- package/dist/router/navigate.d.ts.map +1 -1
- package/dist/router/navigate.js +4 -2
- package/dist/router/navigate.js.map +1 -1
- package/dist/router/policy.js.map +1 -1
- package/dist/router/route-context.js.map +1 -1
- package/dist/router/route.d.ts +1 -1
- package/dist/router/route.d.ts.map +1 -1
- package/dist/router/route.js +3 -34
- package/dist/router/route.js.map +1 -1
- package/dist/runtime/child-scope.d.ts +1 -0
- package/dist/runtime/child-scope.d.ts.map +1 -1
- package/dist/runtime/child-scope.js +2 -0
- package/dist/runtime/child-scope.js.map +1 -1
- package/dist/runtime/component.js +1 -1
- package/dist/runtime/component.js.map +1 -1
- package/dist/runtime/context.js.map +1 -1
- package/dist/runtime/control.js.map +1 -1
- package/dist/runtime/derive.d.ts +2 -1
- package/dist/runtime/derive.d.ts.map +1 -1
- package/dist/runtime/derive.js +15 -10
- package/dist/runtime/derive.js.map +1 -1
- package/dist/runtime/dev-namespace.js.map +1 -1
- package/dist/runtime/effect.d.ts.map +1 -1
- package/dist/runtime/effect.js +34 -9
- package/dist/runtime/effect.js.map +1 -1
- package/dist/runtime/events.js.map +1 -1
- package/dist/runtime/execution-model.js.map +1 -1
- package/dist/runtime/fastlane.js.map +1 -1
- package/dist/runtime/for-bench.d.ts +1 -1
- package/dist/runtime/for-bench.d.ts.map +1 -1
- package/dist/runtime/for-bench.js +15 -14
- package/dist/runtime/for-bench.js.map +1 -1
- package/dist/runtime/for.d.ts +1 -0
- package/dist/runtime/for.d.ts.map +1 -1
- package/dist/runtime/for.js +63 -16
- package/dist/runtime/for.js.map +1 -1
- package/dist/runtime/operations.d.ts.map +1 -1
- package/dist/runtime/operations.js +9 -7
- package/dist/runtime/operations.js.map +1 -1
- package/dist/runtime/perf-metrics.js +8 -2
- package/dist/runtime/perf-metrics.js.map +1 -1
- package/dist/runtime/readable.js.map +1 -1
- package/dist/runtime/resource-cell.js +3 -2
- package/dist/runtime/resource-cell.js.map +1 -1
- package/dist/runtime/scheduler.d.ts +0 -1
- package/dist/runtime/scheduler.d.ts.map +1 -1
- package/dist/runtime/scheduler.js +6 -19
- package/dist/runtime/scheduler.js.map +1 -1
- package/dist/runtime/selector.d.ts.map +1 -1
- package/dist/runtime/selector.js +6 -4
- package/dist/runtime/selector.js.map +1 -1
- package/dist/runtime/snapshot-source.d.ts +10 -0
- package/dist/runtime/snapshot-source.d.ts.map +1 -0
- package/dist/runtime/snapshot-source.js +17 -0
- package/dist/runtime/snapshot-source.js.map +1 -0
- package/dist/runtime/ssr-bridge.js.map +1 -1
- package/dist/runtime/state.d.ts.map +1 -1
- package/dist/runtime/state.js +1 -5
- package/dist/runtime/state.js.map +1 -1
- package/dist/ssg/batch-render.js.map +1 -1
- package/dist/ssg/create-static-gen.js.map +1 -1
- package/dist/ssg/generate-metadata.js.map +1 -1
- package/dist/ssg/incremental-manifest.js.map +1 -1
- package/dist/ssg/resolve-ssg-data.js.map +1 -1
- package/dist/ssg/route-utils.js.map +1 -1
- package/dist/ssg/write-static-files.js.map +1 -1
- package/dist/ssr/attrs.js.map +1 -1
- package/dist/ssr/context.d.ts +1 -0
- package/dist/ssr/context.d.ts.map +1 -1
- package/dist/ssr/context.js +3 -0
- package/dist/ssr/context.js.map +1 -1
- package/dist/ssr/escape.js +56 -16
- package/dist/ssr/escape.js.map +1 -1
- package/dist/ssr/index.d.ts.map +1 -1
- package/dist/ssr/index.js +15 -3
- package/dist/ssr/index.js.map +1 -1
- package/dist/ssr/render-keys.js.map +1 -1
- package/dist/ssr/sink.js.map +1 -1
- package/dist/ssr/stream-render.js +14 -2
- package/dist/ssr/stream-render.js.map +1 -1
- package/package.json +8 -6
package/dist/router/route.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route.js","names":[],"sources":["../../src/router/route.ts"],"sourcesContent":["/**\n * Route definition, registration, and matching.\n *\n * Primary public authoring:\n * - `registerRoutes(() => { ... }, options?)`\n * - `group(options, () => { ... })`\n * - `page(path, Component, () => { ... })`\n * - `index(Component, options?)`\n * - `route(path, Component, options?)`\n * - `fallback(Component)`\n * - `Outlet()` for page child rendering\n * - `currentRoute()` for render-time access\n *\n */\n\nimport { matchSegments, parseSegments, computeRank } from './match';\nimport {\n buildRouteContext,\n buildRouteContextBase,\n deepFreeze,\n makeQuery,\n parseLocation,\n} from './route-context';\nimport { defineContext, readContext } from '../runtime/context';\nimport { getCurrentComponentInstance } from '../runtime/component';\nimport { getExecutionModel } from '../runtime/execution-model';\nimport {\n markReadableDerivedSubscribersDirty,\n markReactivePropsDirtySource,\n notifyReadableReaders,\n recordReadableRead,\n type ReadableSource,\n} from '../runtime/readable';\nimport { getRenderContext } from '../ssr/context';\nimport {\n requireAuth,\n requireGuest,\n requirePermission,\n requireRole,\n} from './policy';\n\nexport type {\n AccessDecision,\n AccessDenyDecision,\n AccessRedirectDecision,\n GroupHelperOptions,\n PageHelperOptions,\n RegisterRoutesOptions,\n RouteDefinition,\n RouteAuthOptions,\n RouteHandler,\n Route,\n RouteContext,\n RoutePolicy,\n RouteRenderResult,\n RouteRequestOptions,\n RouteRequestResult,\n ResolvedRoute,\n RouteMatch,\n RouteQuery,\n RouteSnapshot,\n RouteComponent,\n RouteOptions,\n ParsedSegment,\n LayoutScopeRecord,\n PageScopeRecord,\n RouteRecord,\n RouteManifest,\n} from '../common/router';\n\nimport type {\n AccessDecision,\n AccessDenyDecision,\n AccessRedirectDecision,\n GroupHelperOptions,\n PageHelperOptions,\n RegisterRoutesOptions,\n RouteDefinition,\n RouteAuthOptions,\n RouteHandler,\n Route,\n RouteContext,\n RoutePolicy,\n RouteRenderResult,\n RouteRequestOptions,\n RouteRequestResult,\n ResolvedRoute,\n RouteMatch,\n RouteQuery,\n RouteSnapshot,\n RouteComponent,\n RouteOptions,\n LayoutScopeRecord,\n PageScopeRecord,\n RouteRecord,\n RouteManifest,\n} from '../common/router';\n\n// ---------------------------------------------------------------------------\n// Module-level stores\n// ---------------------------------------------------------------------------\n\n/** Legacy flat route array — kept for resolver and route() accessor backward compat. */\ntype InternalRoute = Route & {\n fallbackPrefix?: string;\n};\n\ntype InternalRouteRecord = RouteRecord & {\n fallbackPrefix?: string;\n};\n\nconst routes: InternalRoute[] = [];\n\n/** Normalized route records built by the declarative registration API. */\nconst records: InternalRouteRecord[] = [];\n\ntype RegistrationScope = {\n kind: 'group' | 'page';\n pathPrefix: string;\n layout?: LayoutScopeRecord['component'];\n page?: PageScopeRecord['component'];\n policies: readonly RoutePolicy[];\n state: AccessScopeState;\n};\n\ntype RegistrationSession = {\n authConfigured: boolean;\n};\n\n/** Active registration scope stack during module-load-time registration. */\nconst registrationScopeStack: RegistrationScope[] = [];\nconst registrationSessionStack: RegistrationSession[] = [];\n\nconst namespaces = new Set<string>();\nlet registrationLocked = false;\n\ntype AccessScopeState = {\n guestOnly: boolean;\n authenticated: boolean;\n};\n\nlet defaultRouteAuthOptions: RouteAuthOptions | undefined;\nlet activeClientRouteAuthOptions: RouteAuthOptions | undefined;\n\nconst HAS_ROUTES_KEY = Symbol.for('__ASKR_HAS_ROUTES__');\n\nfunction setHasRoutes(value: boolean): void {\n try {\n const g = globalThis as unknown as Record<string | symbol, unknown>;\n g[HAS_ROUTES_KEY] = value;\n } catch {\n // ignore\n }\n}\n\n// Initialize to false at module load.\nsetHasRoutes(false);\n\n// Route index by depth - maintains insertion order\nconst routesByDepth = new Map<number, Route[]>();\n\n/**\n * Parse route path depth\n */\nfunction getDepth(path: string): number {\n const normalized =\n path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;\n return normalized === '/' ? 0 : normalized.split('/').filter(Boolean).length;\n}\n\n// ---------------------------------------------------------------------------\n// WeakMap caches for external Route[] objects (e.g. SSR per-request tables)\n// Amortises parseSegments / computeRank across repeated resolveRouteFromRoutes\n// calls on the same route list (same object reference).\n// ---------------------------------------------------------------------------\n\n/** Pre-parsed segments for an externally supplied Route object. */\nconst routeSegsCache = new WeakMap<Route, ReturnType<typeof parseSegments>>();\n/** Pre-computed rank for an externally supplied Route object. */\nconst routeRankCache = new WeakMap<Route, number>();\n/** A rank-descending sorted copy of an external readonly Route array. */\nconst sortedListCache = new WeakMap<\n ReadonlyArray<Route>,\n ReadonlyArray<Route>\n>();\n\nfunction cachedSegs(r: Route): ReturnType<typeof parseSegments> {\n let s = routeSegsCache.get(r);\n if (!s) {\n s = parseSegments(r.path);\n routeSegsCache.set(r, s);\n }\n return s;\n}\n\nfunction cachedRank(r: Route): number {\n let n = routeRankCache.get(r);\n if (n === undefined) {\n n = computeRank(cachedSegs(r));\n routeRankCache.set(r, n);\n }\n return n;\n}\n\nfunction cachedSortedList(\n routeList: ReadonlyArray<Route>\n): ReadonlyArray<Route> {\n let sorted = sortedListCache.get(routeList);\n if (!sorted) {\n sorted = [...routeList].sort((a, b) => cachedRank(b) - cachedRank(a));\n sortedListCache.set(routeList, sorted);\n }\n return sorted;\n}\n\nlet currentRouteSnapshot = buildRouteSnapshot('/', '', '');\n\nconst currentRouteSource = (() =>\n currentRouteSnapshot) as ReadableSource<RouteSnapshot> &\n (() => RouteSnapshot);\n\ncurrentRouteSource._readers = new Map();\n\n// SSR helper: when rendering on the server, callers may set a location so that\n// render-time route() returns deterministic server values that match client\n// hydration. This is deliberately an opt-in escape for SSR and tests.\nlet serverLocation: string | null = null;\n\nexport function setServerLocation(url: string | null): void {\n serverLocation = url;\n}\n\nfunction isPromise<T>(value: T | Promise<T>): value is Promise<T> {\n return value instanceof Promise;\n}\n\nfunction buildRouteSnapshot(\n pathname: string,\n search: string,\n hash: string\n): RouteSnapshot {\n const query = makeQuery(search);\n const matches = computeMatchesFromRoutes(pathname, getActiveRoutes());\n\n return Object.freeze({\n path: pathname,\n params: deepFreeze({ ...matches[0]?.params }),\n query,\n hash: hash || null,\n matches: Object.freeze(matches),\n });\n}\n\nfunction setCurrentRouteSnapshot(\n pathname: string,\n search: string,\n hash: string\n): void {\n currentRouteSnapshot = buildRouteSnapshot(pathname, search, hash);\n\n const instance = getCurrentComponentInstance();\n markReadableDerivedSubscribersDirty(currentRouteSource);\n markReactivePropsDirtySource(currentRouteSource);\n notifyReadableReaders(currentRouteSource, instance);\n}\n\n// Compute matches for a specific route list.\nfunction matchFallbackPrefix(\n pathname: string,\n fallbackPrefix: string\n): Record<string, string> | null {\n const normalizedPath =\n pathname.endsWith('/') && pathname !== '/'\n ? pathname.slice(0, -1)\n : pathname;\n const normalizedPrefix =\n fallbackPrefix.endsWith('/') && fallbackPrefix !== '/'\n ? fallbackPrefix.slice(0, -1)\n : fallbackPrefix;\n\n if (normalizedPrefix === '/') {\n const urlParts =\n normalizedPath === '/' ? [] : normalizedPath.split('/').filter(Boolean);\n return {\n '*':\n urlParts.length === 0\n ? '/'\n : urlParts.length === 1\n ? urlParts[0]\n : '/' + urlParts.join('/'),\n };\n }\n\n if (\n normalizedPath !== normalizedPrefix &&\n !normalizedPath.startsWith(`${normalizedPrefix}/`)\n ) {\n return null;\n }\n\n const remainder =\n normalizedPath === normalizedPrefix\n ? '/'\n : normalizedPath.slice(normalizedPrefix.length + 1);\n const remainderParts =\n remainder === '/' ? [] : remainder.split('/').filter(Boolean);\n\n return {\n '*':\n remainderParts.length === 0\n ? '/'\n : remainderParts.length === 1\n ? remainderParts[0]\n : '/' + remainderParts.join('/'),\n };\n}\n\nfunction computeMatchesFromRoutes(\n pathname: string,\n routesList: readonly Route[]\n): RouteMatch[] {\n const bestMatch =\n routesList === routes\n ? getMatchingRecord(pathname, records)\n : findBestResolvedRouteFromRoutes(pathname, routesList);\n\n if (!bestMatch) {\n return [];\n }\n\n return [\n {\n path: 'route' in bestMatch ? bestMatch.route.path : bestMatch.record.path,\n params: deepFreeze({ ...bestMatch.params }),\n name:\n 'route' in bestMatch\n ? (bestMatch.route as { name?: string }).name\n : undefined,\n namespace:\n 'route' in bestMatch\n ? bestMatch.route.namespace\n : bestMatch.record.options.namespace,\n },\n ];\n}\n\nfunction findBestResolvedRouteFromRoutes(\n pathname: string,\n routeList: readonly Route[]\n): { route: Route; params: Record<string, string> } | null {\n const normalized =\n pathname.endsWith('/') && pathname !== '/'\n ? pathname.slice(0, -1)\n : pathname;\n const urlParts =\n normalized === '/' ? [] : normalized.split('/').filter(Boolean);\n\n const sorted = cachedSortedList(routeList);\n let bestRoute: Route | null = null;\n let bestParams: Record<string, string> = {};\n let bestRank = -Infinity;\n\n for (const route of sorted) {\n const internalRoute = route as InternalRoute;\n if (internalRoute.fallbackPrefix) {\n continue;\n }\n\n const rank = cachedRank(route);\n if (rank < bestRank) break;\n if (bestRoute !== null && rank === bestRank) continue;\n\n const params = matchSegments(urlParts, cachedSegs(route));\n if (params !== null) {\n bestRoute = route;\n bestParams = params;\n bestRank = rank;\n }\n }\n\n if (bestRoute !== null) {\n return { route: bestRoute, params: bestParams };\n }\n\n let bestFallback: InternalRoute | null = null;\n let bestFallbackParams: Record<string, string> | null = null;\n let bestPrefixLength = -1;\n\n for (const route of routeList) {\n const internalRoute = route as InternalRoute;\n if (!internalRoute.fallbackPrefix) {\n continue;\n }\n\n const params = matchFallbackPrefix(\n normalized,\n internalRoute.fallbackPrefix\n );\n if (params === null) {\n continue;\n }\n\n if (internalRoute.fallbackPrefix.length > bestPrefixLength) {\n bestFallback = internalRoute;\n bestFallbackParams = params;\n bestPrefixLength = internalRoute.fallbackPrefix.length;\n }\n }\n\n return bestFallback && bestFallbackParams\n ? { route: bestFallback, params: bestFallbackParams }\n : null;\n}\n\nfunction getActiveRoutes(): readonly Route[] {\n const renderContext = getRenderContext();\n return renderContext?.routes ?? routes;\n}\n\nfunction getActiveRouteAuthOptions(\n override?: RouteAuthOptions\n): RouteAuthOptions | undefined {\n if (override) {\n return override;\n }\n\n const renderContext = getRenderContext();\n return (\n renderContext?.routeAuth ??\n activeClientRouteAuthOptions ??\n defaultRouteAuthOptions\n );\n}\n\nexport function _setActiveRouteAuthOptions(\n auth: RouteAuthOptions | undefined\n): void {\n activeClientRouteAuthOptions = auth;\n}\n\nfunction getCurrentRegistrationSession(): RegistrationSession {\n return (\n registrationSessionStack[registrationSessionStack.length - 1] ?? {\n authConfigured: !!defaultRouteAuthOptions?.resolve,\n }\n );\n}\n\nfunction getCurrentAccessScopeState(): AccessScopeState {\n return (\n registrationScopeStack[registrationScopeStack.length - 1]?.state ?? {\n guestOnly: false,\n authenticated: false,\n }\n );\n}\n\nfunction getCurrentLayoutChain(): LayoutScopeRecord[] {\n const layoutChain: LayoutScopeRecord[] = [];\n\n for (const scope of registrationScopeStack) {\n if (scope.layout) {\n layoutChain.push({ component: scope.layout });\n }\n }\n\n return layoutChain;\n}\n\nfunction getCurrentPageChain(): PageScopeRecord[] {\n const pageChain: PageScopeRecord[] = [];\n\n for (const scope of registrationScopeStack) {\n if (scope.page) {\n pageChain.push({ component: scope.page });\n }\n }\n\n return pageChain;\n}\n\nfunction hasActivePageScope(): boolean {\n return registrationScopeStack.some((scope) => !!scope.page);\n}\n\nfunction getCurrentScopeKind(): RegistrationScope['kind'] | null {\n return (\n registrationScopeStack[registrationScopeStack.length - 1]?.kind ?? null\n );\n}\n\nfunction getCurrentPathPrefix(): string {\n return (\n registrationScopeStack[registrationScopeStack.length - 1]?.pathPrefix ?? ''\n );\n}\n\nfunction getCurrentInheritedPolicies(): RoutePolicy[] {\n const policies: RoutePolicy[] = [];\n\n for (const scope of registrationScopeStack) {\n if (scope.policies.length > 0) {\n policies.push(...scope.policies);\n }\n }\n\n return policies;\n}\n\n// ---------------------------------------------------------------------------\n// Registration lock\n// ---------------------------------------------------------------------------\n\n/**\n * Prevent route registrations after the app has started.\n * Enforced in production; tests may unlock explicitly.\n */\n\nexport function lockRouteRegistration(): void {\n registrationLocked = true;\n}\n\nexport function _lockRouteRegistrationForTests(): void {\n registrationLocked = true;\n}\n\nexport function _unlockRouteRegistrationForTests(): void {\n registrationLocked = false;\n}\n\n// ---------------------------------------------------------------------------\n// Path validation\n// ---------------------------------------------------------------------------\n\nfunction validateRoutePath(path: string): void {\n if (!path.startsWith('/')) {\n throw new Error(`Route path must begin with \"/\". Got: \"${path}\"`);\n }\n // Reject Express-style :param syntax — Askr uses {param} interpolation\n if (/:([^/{}]+)/.test(path)) {\n const suggested = path.replace(/:([^/{}]+)/g, '{$1}');\n throw new Error(\n `Route parameter syntax uses {name} interpolation, not :name. ` +\n `Use \"${suggested}\" instead of \"${path}\".`\n );\n }\n}\n\nfunction normalizeAbsoluteRoutePath(path: string): string {\n if (!path || path === '/') {\n return '/';\n }\n\n const normalized = path.endsWith('/') ? path.slice(0, -1) : path;\n return normalized || '/';\n}\n\nfunction joinRoutePaths(prefix: string, path: string): string {\n const normalizedPrefix = normalizeAbsoluteRoutePath(prefix || '/');\n const normalizedPath = path.replace(/^\\/+|\\/+$/g, '');\n\n if (!normalizedPath) {\n return normalizedPrefix;\n }\n\n return normalizedPrefix === '/'\n ? `/${normalizedPath}`\n : `${normalizedPrefix}/${normalizedPath}`;\n}\n\nfunction resolvePageScopePath(path: string): string {\n if (!path) {\n throw new Error('page(path, Component, fn) requires a non-empty path.');\n }\n\n if (path.startsWith('/')) {\n validateRoutePath(path);\n return normalizeAbsoluteRoutePath(path);\n }\n\n return joinRoutePaths(getCurrentPathPrefix(), path);\n}\n\nfunction resolveIndexPath(): string {\n return normalizeAbsoluteRoutePath(getCurrentPathPrefix() || '/');\n}\n\nfunction resolveRouteRegistrationPath(path: string): string {\n if (path.startsWith('/')) {\n if (hasActivePageScope()) {\n throw new Error(\n 'Child route paths inside page() must be relative. ' +\n `Use \"${path.slice(1)}\" instead of \"${path}\".`\n );\n }\n\n validateRoutePath(path);\n return normalizeAbsoluteRoutePath(path);\n }\n\n const prefix = getCurrentPathPrefix();\n\n if (!prefix) {\n throw new Error(`Route path must begin with \"/\". Got: \"${path}\"`);\n }\n\n return joinRoutePaths(prefix, path);\n}\n\n// ---------------------------------------------------------------------------\n// Internal helper: insert a RouteRecord in rank-descending order\n// so that resolveRoute can use first-match-wins without sorting.\n// Ties preserve declaration order (stable binary-search insertion).\n// ---------------------------------------------------------------------------\n\nfunction insertRecordSorted(record: RouteRecord): void {\n let lo = 0;\n let hi = records.length;\n // Find the insertion point: after all existing records with rank >= this one\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (records[mid].rank >= record.rank) lo = mid + 1;\n else hi = mid;\n }\n records.splice(lo, 0, record);\n}\n\n// ---------------------------------------------------------------------------\n// Internal helper: add a single pre-built Route object to the runtime stores\n// ---------------------------------------------------------------------------\n\nfunction addRouteToStores(routeObj: Route): void {\n routes.push(routeObj);\n setHasRoutes(true);\n\n const depth = getDepth(routeObj.path);\n let depthRoutes = routesByDepth.get(depth);\n if (!depthRoutes) {\n depthRoutes = [];\n routesByDepth.set(depth, depthRoutes);\n }\n depthRoutes.push(routeObj);\n\n if (routeObj.namespace) {\n namespaces.add(routeObj.namespace);\n }\n}\n\n// ---------------------------------------------------------------------------\n// lazy() — eager-prefetch code-split component wrapper\n// ---------------------------------------------------------------------------\n\n/** Promises from in-flight lazy() imports, drained by createSPA / hydrateSPA. */\nconst pendingLazy = new Set<Promise<unknown>>();\n\nconst outletContext = defineContext<unknown>(null);\n\nexport function Outlet(): unknown {\n return readContext(outletContext);\n}\n\n/**\n * Snapshot the current in-flight lazy() imports.\n * Boot uses this before clearing route state so manifest-based startup can\n * still await chunks that were kicked off during route module evaluation.\n */\nexport function _snapshotLazy(): Promise<unknown>[] {\n return [...pendingLazy];\n}\n\n/**\n * Declare a code-split route component. The `import()` fires immediately at\n * module evaluation time (creating a bundler split point), and the resolved\n * chunk is guaranteed to be available before the app mounts — so the renderer\n * always receives a plain synchronous function.\n *\n * ```ts\n * registerRoutes(() => {\n * group({ layout: AppLayout }, () => {\n * route('/', lazy(() => import('./pages/landing')));\n * route('/dashboard', lazy(() => import('./pages/dashboard')));\n * });\n * });\n * ```\n *\n * The module must export the component as its **default** export:\n * ```ts\n * // pages/dashboard.tsx\n * export default function DashboardPage() { … }\n * ```\n */\nexport function lazy(\n factory: () => Promise<{ default: RouteComponent } | RouteComponent>\n): RouteComponent {\n let resolved: RouteComponent | null = null;\n let loadError: unknown = null;\n\n const promise = factory().then(\n (mod) => {\n resolved =\n typeof mod === 'function'\n ? mod\n : (mod as { default: RouteComponent }).default;\n pendingLazy.delete(promise);\n },\n (err: unknown) => {\n loadError = err;\n pendingLazy.delete(promise);\n }\n );\n pendingLazy.add(promise);\n\n return (params) => {\n if (loadError) throw loadError as Error;\n if (!resolved) {\n throw new Error(\n 'lazy() component used before it was resolved. ' +\n 'Await createSPA() / hydrateSPA() to ensure all chunks load first.'\n );\n }\n return resolved(params);\n };\n}\n\n/**\n * Wait for all pending `lazy()` imports to settle.\n * Called automatically by `createSPA` / `hydrateSPA` before mounting.\n */\nexport function _drainLazy(\n additionalPending: Iterable<Promise<unknown>> = []\n): Promise<void> {\n const combined = new Set<Promise<unknown>>([\n ...additionalPending,\n ...pendingLazy,\n ]);\n if (combined.size === 0) return Promise.resolve();\n return Promise.allSettled(combined).then(() => undefined);\n}\n\nexport function group(options: GroupHelperOptions, fn: RouteDefinition): void;\nexport function group(options: GroupHelperOptions, fn: RouteDefinition): void {\n pushGroupScope(options, fn);\n}\n\nexport function page(\n path: string,\n Component: RouteComponent,\n fn: RouteDefinition\n): void;\nexport function page(\n path: string,\n Component: RouteComponent,\n options: PageHelperOptions,\n fn: RouteDefinition\n): void;\nexport function page(\n path: string,\n Component: RouteComponent,\n optionsOrFn: PageHelperOptions | RouteDefinition,\n maybeFn?: RouteDefinition\n): void {\n const options =\n typeof optionsOrFn === 'function' ? ({} as PageHelperOptions) : optionsOrFn;\n const fn = typeof optionsOrFn === 'function' ? optionsOrFn : maybeFn;\n\n if (typeof Component !== 'function') {\n throw new Error(\n 'page(path, Component, fn) requires a component function as the second argument.'\n );\n }\n\n if (typeof fn !== 'function') {\n throw new Error(\n 'page(path, Component, fn) requires a route definition callback as the final argument.'\n );\n }\n\n pushPageScope(path, Component, options, fn);\n}\n\nexport function index(Component: RouteComponent, options?: RouteOptions): void {\n registerRouteAtResolvedPath(resolveIndexPath(), Component, options);\n}\n\nexport function fallback(Component: RouteComponent): void {\n if (hasActivePageScope()) {\n if (getCurrentScopeKind() !== 'page') {\n throw new Error(\n 'fallback() inside page() must be declared directly in the page scope, not inside nested group().'\n );\n }\n\n registerRouteAtResolvedPath(\n `${getCurrentPathPrefix()}/*`,\n Component,\n undefined,\n { isFallback: true, fallbackPrefix: getCurrentPathPrefix() }\n );\n return;\n }\n\n const allowsRootFallback = registrationScopeStack.every(\n (scope) =>\n scope.policies.length === 0 &&\n !scope.state.guestOnly &&\n !scope.state.authenticated\n );\n\n if (!allowsRootFallback) {\n throw new Error(\n 'fallback() can only be registered at the root scope. ' +\n 'Use route(\"/*\", Component) if you need compatibility behavior.'\n );\n }\n\n registerRouteAtResolvedPath('/*', Component, undefined, {\n isFallback: true,\n fallbackPrefix: '/',\n });\n}\n\nfunction pushRegistrationScope(\n scope: RegistrationScope,\n fn: RouteDefinition\n): void {\n registrationScopeStack.push(scope);\n try {\n fn();\n } finally {\n registrationScopeStack.pop();\n }\n}\n\nfunction pushGroupScope(\n options: GroupHelperOptions,\n fn: RouteDefinition\n): void {\n const session = getCurrentRegistrationSession();\n validateAccessMetadata(options, {\n authConfigured: session.authConfigured,\n state: getCurrentAccessScopeState(),\n });\n const policies = compileNodePolicies(options);\n\n pushRegistrationScope(\n {\n kind: 'group',\n pathPrefix: getCurrentPathPrefix(),\n layout: options.layout,\n policies,\n state: nextAccessScopeState(options, getCurrentAccessScopeState()),\n },\n fn\n );\n}\n\nfunction pushPageScope(\n path: string,\n Component: RouteComponent,\n options: PageHelperOptions,\n fn: RouteDefinition\n): void {\n if (hasActivePageScope()) {\n throw new Error(\n 'page() cannot be nested inside another page(). ' +\n 'Use route() for child leaves or group() for inherited behavior inside the existing page scope.'\n );\n }\n\n const session = getCurrentRegistrationSession();\n validateAccessMetadata(options, {\n authConfigured: session.authConfigured,\n state: getCurrentAccessScopeState(),\n });\n\n const policies = compileNodePolicies(options);\n\n pushRegistrationScope(\n {\n kind: 'page',\n pathPrefix: resolvePageScopePath(path),\n page: Component,\n policies,\n state: nextAccessScopeState(options, getCurrentAccessScopeState()),\n },\n fn\n );\n}\n\nfunction hasBuiltInAuthMetadata(\n node: Pick<GroupHelperOptions | RouteOptions, 'auth' | 'role' | 'permission'>\n): boolean {\n return node.auth !== undefined || !!node.role || !!node.permission;\n}\n\nfunction validateSameNodeAccessMetadata(\n node: Pick<GroupHelperOptions | RouteOptions, 'auth' | 'role' | 'permission'>\n): void {\n if (node.auth === 'guest' && (!!node.role || !!node.permission)) {\n throw new Error(\n 'Guest-only routes cannot be combined with role or permission requirements.'\n );\n }\n}\n\nfunction validateAccessMetadata(\n node: Pick<GroupHelperOptions | RouteOptions, 'auth' | 'role' | 'permission'>,\n context: {\n authConfigured: boolean;\n state: AccessScopeState;\n }\n): void {\n validateSameNodeAccessMetadata(node);\n\n const requiresAuthenticated =\n node.auth === true || !!node.role || !!node.permission;\n\n if (\n node.auth === 'guest' &&\n (context.state.authenticated || !!node.role || !!node.permission)\n ) {\n throw new Error(\n 'Guest-only routes cannot be combined with authenticated access requirements.'\n );\n }\n\n if (context.state.guestOnly && requiresAuthenticated) {\n throw new Error(\n 'Child routes cannot weaken a guest-only access scope with authenticated requirements.'\n );\n }\n\n if (hasBuiltInAuthMetadata(node) && !context.authConfigured) {\n throw new Error(\n 'Routes using `auth`, `role`, or `permission` require `auth.resolve` in registerRoutes(...).'\n );\n }\n}\n\nfunction nextAccessScopeState(\n node: Pick<GroupHelperOptions | RouteOptions, 'auth' | 'role' | 'permission'>,\n state: AccessScopeState\n): AccessScopeState {\n const requiresAuthenticated =\n node.auth === true || !!node.role || !!node.permission;\n\n return {\n guestOnly: state.guestOnly || node.auth === 'guest',\n authenticated: state.authenticated || requiresAuthenticated,\n };\n}\n\nfunction compileNodePolicies(\n node: Pick<\n RouteOptions | GroupHelperOptions,\n 'auth' | 'role' | 'permission' | 'policies'\n >\n): RoutePolicy[] {\n validateSameNodeAccessMetadata(node);\n\n const compiled: RoutePolicy[] = [];\n\n if (node.auth === true) {\n compiled.push(requireAuth());\n } else if (node.auth === 'guest') {\n compiled.push(requireGuest());\n }\n\n if (node.role) {\n compiled.push(requireRole(node.role));\n }\n\n if (node.permission) {\n compiled.push(requirePermission(node.permission));\n }\n\n if (node.policies?.length) {\n compiled.push(...node.policies);\n }\n\n return compiled;\n}\n\nfunction normalizeRouteOptions(\n options: RouteOptions | undefined\n): RouteOptions | undefined {\n if (!options) {\n return undefined;\n }\n\n const loader = options.loader;\n const policies = compileNodePolicies(options);\n\n if (\n !loader &&\n !options.entries &&\n policies.length === 0 &&\n !options.title &&\n !options.namespace &&\n options.auth === undefined &&\n !options.role &&\n !options.permission\n ) {\n return undefined;\n }\n\n return {\n ...(loader ? { loader } : {}),\n ...(options.entries ? { entries: options.entries } : {}),\n ...(options.auth !== undefined ? { auth: options.auth } : {}),\n ...(options.role ? { role: options.role } : {}),\n ...(options.permission ? { permission: options.permission } : {}),\n ...(policies.length > 0 ? { policies } : {}),\n ...(options.title ? { title: options.title } : {}),\n ...(options.namespace ? { namespace: options.namespace } : {}),\n };\n}\n\nfunction applyPageChain(\n pageChain: readonly PageScopeRecord[],\n params: Record<string, string>,\n content: unknown\n): unknown {\n let nextContent = content;\n\n for (let i = pageChain.length - 1; i >= 0; i--) {\n nextContent = outletContext.Scope({\n value: nextContent,\n children: pageChain[i].component(params),\n });\n }\n\n return nextContent;\n}\n\nfunction registerRouteAtResolvedPath(\n path: string,\n Component: RouteComponent,\n options?: RouteOptions,\n metadata?: {\n isFallback?: boolean;\n fallbackPrefix?: string;\n }\n): void {\n validateAccessMetadata(options ?? {}, {\n authConfigured: getCurrentRegistrationSession().authConfigured,\n state: getCurrentAccessScopeState(),\n });\n\n const chain = getCurrentLayoutChain();\n const pageChain = getCurrentPageChain();\n const segments = parseSegments(path);\n const rank = computeRank(segments);\n const isFallback = metadata?.isFallback ?? path === '/*';\n const comp = Component;\n const normalizedOptions = normalizeRouteOptions(options);\n const policies = [\n ...getCurrentInheritedPolicies(),\n ...(normalizedOptions?.policies ?? []),\n ];\n\n const handler: RouteHandler = (params) => {\n let content = comp(params);\n\n content = applyPageChain(pageChain, params, content);\n\n for (let i = chain.length - 1; i >= 0; i--) {\n content = chain[i].component({ children: content });\n }\n\n return content;\n };\n\n const record: InternalRouteRecord = {\n path,\n component: comp,\n segments,\n rank,\n layoutChain: chain,\n pageChain,\n options: normalizedOptions\n ? {\n ...normalizedOptions,\n ...(policies.length > 0 ? { policies } : {}),\n }\n : policies.length > 0\n ? { policies }\n : {},\n isFallback,\n handler,\n ...(metadata?.fallbackPrefix\n ? { fallbackPrefix: metadata.fallbackPrefix }\n : {}),\n };\n\n insertRecordSorted(record);\n addRouteToStores({\n path,\n handler,\n namespace: normalizedOptions?.namespace ?? options?.namespace,\n ...(metadata?.fallbackPrefix\n ? { fallbackPrefix: metadata.fallbackPrefix }\n : {}),\n });\n}\n\nexport function registerRoutes(\n definition: RouteDefinition,\n options: RegisterRoutesOptions = {}\n): void {\n defaultRouteAuthOptions = options.auth;\n\n registrationSessionStack.push({\n authConfigured: !!options.auth?.resolve,\n });\n try {\n definition();\n } finally {\n registrationSessionStack.pop();\n }\n}\n\n// ---------------------------------------------------------------------------\n// route() — dual-purpose: registration (module load) + accessor (render time)\n// ---------------------------------------------------------------------------\n\nfunction readCurrentRouteSnapshot(): RouteSnapshot {\n const instance = getCurrentComponentInstance();\n if (!instance) {\n throw new Error(\n 'currentRoute() can only be called during component render execution. ' +\n 'Call currentRoute() from inside your component function.'\n );\n }\n\n let pathname = '/';\n let search = '';\n let hash = '';\n const renderContext = getRenderContext();\n\n if (instance.ssr && renderContext?.url) {\n const parsed = parseLocation(renderContext.url);\n pathname = parsed.pathname;\n search = parsed.search;\n hash = parsed.hash;\n } else if (typeof window !== 'undefined' && window.location) {\n pathname = window.location.pathname || '/';\n search = window.location.search || '';\n hash = window.location.hash || '';\n } else if (serverLocation) {\n const parsed = parseLocation(serverLocation);\n pathname = parsed.pathname;\n search = parsed.search;\n hash = parsed.hash;\n }\n\n const query = makeQuery(search);\n const matches = computeMatchesFromRoutes(pathname, getActiveRoutes());\n const instanceParams = instance.props as Record<string, string>;\n const routeParams =\n Object.keys(instanceParams).length > 0\n ? instanceParams\n : (matches[0]?.params ?? {});\n const params = deepFreeze({\n ...routeParams,\n });\n\n return Object.freeze({\n path: pathname,\n params,\n query,\n hash: hash || null,\n matches: Object.freeze(matches),\n });\n}\n\nexport function currentRoute(): RouteSnapshot {\n const instance = getCurrentComponentInstance();\n if (!instance) {\n throw new Error(\n 'currentRoute() can only be called during component render execution. ' +\n 'Call currentRoute() from inside your component function.'\n );\n }\n\n if (typeof window === 'undefined' || instance.ssr) {\n return readCurrentRouteSnapshot();\n }\n\n if (currentRouteSnapshot.path !== (window.location.pathname || '/')) {\n recordReadableRead(currentRouteSource);\n return readCurrentRouteSnapshot();\n }\n\n recordReadableRead(currentRouteSource);\n return readCurrentRouteSnapshot();\n}\n\nexport function syncCurrentRouteSnapshot(\n pathname: string,\n search: string,\n hash: string\n): void {\n setCurrentRouteSnapshot(pathname, search, hash);\n}\n\n/**\n * Register a route.\n *\n * ```ts\n * route('/posts/{slug}', PostPage, {\n * loader: ({ params }) => getPost(params.slug),\n * entries: async () => getPosts().map(p => ({ slug: p.slug })),\n * title: 'Post',\n * policies:[requireAuth()],\n * });\n * ```\n */\nexport function route(\n path: string,\n Component: RouteComponent,\n options?: RouteOptions\n): void;\nexport function route(\n path: string,\n Component: RouteComponent,\n options?: RouteOptions\n): void {\n if (getExecutionModel() === 'islands') {\n throw new Error(\n 'Routes are not supported with islands. Use createSPA (client) or createSSR (server) instead.'\n );\n }\n\n // ── Render-time accessor (no arguments) ─────────────────────────────────\n if (typeof path === 'undefined') {\n throw new Error(\n 'route() is only for route registration. Use currentRoute() inside components.'\n );\n }\n\n // ── Registration mode ────────────────────────────────────────────────────\n\n // Disallow registration during SSR render\n const currentInst = getCurrentComponentInstance();\n if (currentInst && currentInst.ssr) {\n throw new Error(\n 'route() cannot be called during SSR rendering. Register routes at module load time instead.'\n );\n }\n\n if (registrationLocked) {\n throw new Error(\n 'Route registration is locked after app startup. ' +\n 'Register routes at module load time before calling createSPA or createSSR.'\n );\n }\n\n if (typeof Component !== 'function') {\n throw new Error(\n 'route(path, Component) requires a component function as the second argument. ' +\n 'Passing JSX elements or VNodes directly is not supported.'\n );\n }\n\n registerRouteAtResolvedPath(\n resolveRouteRegistrationPath(path),\n Component,\n options\n );\n}\n\n// ---------------------------------------------------------------------------\n// Manifest access\n// ---------------------------------------------------------------------------\n\n/**\n * Return the normalized route manifest built from registered route definitions.\n *\n * Pass this to `createSPA`, `hydrateSPA`, or `renderToString` as the\n * authoritative routing input:\n *\n * ```ts\n * import { getManifest } from '@askrjs/askr/router';\n * await createSPA({ root: '#app', manifest: getManifest() });\n * ```\n */\nexport function getManifest(): RouteManifest {\n return {\n records: [...records],\n ...(defaultRouteAuthOptions ? { auth: defaultRouteAuthOptions } : {}),\n };\n}\n\n/**\n * Internal: apply a pre-built manifest to the runtime stores without running\n * route() again. Called by createSPA / hydrateSPA when a manifest is passed.\n */\nexport function _applyManifest(manifest: RouteManifest): void {\n defaultRouteAuthOptions = manifest.auth;\n for (const record of manifest.records) {\n insertRecordSorted(record as InternalRouteRecord);\n addRouteToStores({\n path: record.path,\n handler: record.handler,\n namespace: record.options.namespace,\n ...('fallbackPrefix' in record &&\n typeof (record as InternalRouteRecord).fallbackPrefix === 'string'\n ? {\n fallbackPrefix: (record as InternalRouteRecord).fallbackPrefix,\n }\n : {}),\n });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Route collection helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Get all registered routes (flat list, insertion order).\n * Prefer `getManifest()` when metadata (loader, policies, entries) is needed.\n */\nexport function getRoutes(): Route[] {\n return [...routes];\n}\n\n/** Get routes for a specific namespace. */\nexport function getNamespaceRoutes(namespace: string): Route[] {\n return routes.filter((r) => r.namespace === namespace);\n}\n\n/** Unload all routes from a namespace (for MFE unmounting). */\nexport function unloadNamespace(namespace: string): number {\n const before = routes.length;\n\n for (let i = routes.length - 1; i >= 0; i--) {\n if (routes[i].namespace === namespace) {\n const removed = routes[i];\n routes.splice(i, 1);\n\n const depth = getDepth(removed.path);\n const depthRoutes = routesByDepth.get(depth);\n if (depthRoutes) {\n const idx = depthRoutes.indexOf(removed);\n if (idx >= 0) depthRoutes.splice(idx, 1);\n }\n }\n }\n\n // Remove matching records too\n for (let i = records.length - 1; i >= 0; i--) {\n if (records[i].options.namespace === namespace) {\n records.splice(i, 1);\n }\n }\n\n namespaces.delete(namespace);\n return before - routes.length;\n}\n\n/** Clear all registered routes and records (testing / boot reset). */\nexport function clearRoutes(): void {\n routes.length = 0;\n records.length = 0;\n namespaces.clear();\n routesByDepth.clear();\n registrationScopeStack.length = 0;\n registrationSessionStack.length = 0;\n registrationLocked = false;\n defaultRouteAuthOptions = undefined;\n activeClientRouteAuthOptions = undefined;\n setHasRoutes(false);\n pendingLazy.clear();\n}\n\n/**\n * Get all loaded namespaces (MFE identifiers)\n */\nexport function getLoadedNamespaces(): string[] {\n return Array.from(namespaces);\n}\n\nfunction findBestScopedFallbackRecord(\n pathname: string,\n routeRecords: readonly RouteRecord[]\n): { record: InternalRouteRecord; params: Record<string, string> } | null {\n let bestRecord: InternalRouteRecord | null = null;\n let bestParams: Record<string, string> | null = null;\n let bestPrefixLength = -1;\n\n for (const routeRecord of routeRecords) {\n const record = routeRecord as InternalRouteRecord;\n if (!record.fallbackPrefix) {\n continue;\n }\n\n const params = matchFallbackPrefix(pathname, record.fallbackPrefix);\n if (params === null) {\n continue;\n }\n\n if (record.fallbackPrefix.length > bestPrefixLength) {\n bestRecord = record;\n bestParams = params;\n bestPrefixLength = record.fallbackPrefix.length;\n }\n }\n\n return bestRecord && bestParams\n ? { record: bestRecord, params: bestParams }\n : null;\n}\n\n/**\n * Resolve a path to a route handler.\n *\n * Hot path: walks the module-level `records[]` array which is kept sorted by\n * rank descending at registration time — so the first `matchSegments` hit is\n * always the most specific match. No per-call allocations for the common\n * case of purely-static routes.\n */\nexport function resolveRoute(pathname: string): ResolvedRoute | null {\n const normalized =\n pathname.endsWith('/') && pathname !== '/'\n ? pathname.slice(0, -1)\n : pathname;\n const urlParts =\n normalized === '/' ? [] : normalized.split('/').filter(Boolean);\n\n for (const record of records) {\n if (record.fallbackPrefix) {\n continue;\n }\n\n const params = matchSegments(urlParts, record.segments);\n if (params !== null) {\n return { handler: record.handler, params };\n }\n }\n\n const fallbackMatch = findBestScopedFallbackRecord(normalized, records);\n return fallbackMatch\n ? { handler: fallbackMatch.record.handler, params: fallbackMatch.params }\n : null;\n}\n\nfunction getMatchingRecord(\n target: string,\n routeRecords: readonly RouteRecord[]\n): { record: RouteRecord; params: Record<string, string> } | null {\n const location = parseLocation(target);\n const normalized =\n location.pathname.endsWith('/') && location.pathname !== '/'\n ? location.pathname.slice(0, -1)\n : location.pathname;\n const urlParts =\n normalized === '/' ? [] : normalized.split('/').filter(Boolean);\n\n for (const record of routeRecords) {\n const internalRecord = record as InternalRouteRecord;\n if (internalRecord.fallbackPrefix) {\n continue;\n }\n\n const params = matchSegments(urlParts, record.segments);\n if (params !== null) {\n return { record, params };\n }\n }\n\n return findBestScopedFallbackRecord(normalized, routeRecords);\n}\n\nfunction getRoutePolicies(\n options: RouteOptions | undefined\n): readonly RoutePolicy[] {\n if (!options) {\n return [];\n }\n\n if (options.policies?.length) {\n return options.policies;\n }\n\n return compileNodePolicies(options);\n}\n\nfunction getDefaultRouteMode(): RouteContext['mode'] {\n if (typeof window !== 'undefined') {\n return 'spa';\n }\n\n return 'ssr';\n}\n\nfunction buildRenderResult(\n record: RouteRecord,\n params: Record<string, string>\n): RouteRenderResult {\n return {\n kind: 'render',\n handler: record.handler,\n params,\n };\n}\n\nfunction continueRoutePolicies(\n policies: readonly RoutePolicy[],\n context: RouteContext,\n record: RouteRecord,\n params: Record<string, string>,\n startIndex = 0\n): RouteRequestResult | Promise<RouteRequestResult> {\n for (let index = startIndex; index < policies.length; index += 1) {\n const policyResult = policies[index](context);\n\n if (isPromise(policyResult)) {\n return policyResult.then((next) => {\n if (next.kind !== 'allow') {\n return next;\n }\n\n return continueRoutePolicies(\n policies,\n context,\n record,\n params,\n index + 1\n );\n });\n }\n\n if (policyResult.kind !== 'allow') {\n return policyResult;\n }\n }\n\n return buildRenderResult(record, params);\n}\n\nexport function resolveRouteRequest(\n target: string,\n options: RouteRequestOptions = {}\n): RouteRequestResult | Promise<RouteRequestResult> {\n const routeRecords = options.manifest?.records ?? records;\n const match = getMatchingRecord(target, routeRecords);\n\n if (!match) {\n return null;\n }\n\n const { record, params } = match;\n const policies = getRoutePolicies(record.options);\n\n if (policies.length === 0) {\n return buildRenderResult(record, params);\n }\n\n const signal =\n options.signal ??\n getRenderContext()?.signal ??\n new AbortController().signal;\n const mode = options.mode ?? getDefaultRouteMode();\n const auth = getActiveRouteAuthOptions(\n options.auth ?? options.manifest?.auth\n );\n const baseContext = buildRouteContextBase(target, params, {\n mode,\n signal,\n });\n\n const finalize = (authState: { session: unknown; user: unknown }) =>\n continueRoutePolicies(\n policies,\n buildRouteContext(target, params, {\n mode,\n signal,\n auth,\n session: authState.session,\n user: authState.user,\n }),\n record,\n params\n );\n\n if (!auth?.resolve) {\n return finalize({ session: null, user: null });\n }\n\n const authState = auth.resolve(baseContext);\n if (isPromise(authState)) {\n return authState.then((next) => finalize(next));\n }\n\n return finalize(authState);\n}\n\n/**\n * Resolve a path against an explicit route list (e.g. an SSR per-render\n * context). When called with the global `routes` array this delegates to\n * the faster `resolveRoute` which uses pre-sorted `records[]`.\n *\n * For externally supplied lists the function:\n * 1. Builds a rank-sorted copy of the list on first call and caches it\n * in a WeakMap so subsequent resolutions against the same list pay\n * zero sort cost.\n * 2. Uses pre-parsed `ParsedSegment[]` from a WeakMap cache so no string\n * splitting or segment parsing occurs on the hot path.\n * 3. Uses a running-best with an early-exit once the sorted list reaches\n * a rank that cannot beat the current best match.\n */\nexport function resolveRouteFromRoutes(\n pathname: string,\n routeList: readonly Route[]\n): ResolvedRoute | null {\n if (routeList === routes) return resolveRoute(pathname);\n\n const match = findBestResolvedRouteFromRoutes(pathname, routeList);\n return match ? { handler: match.route.handler, params: match.params } : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+GA,MAAM,SAA0B,EAAE;;AAGlC,MAAM,UAAiC,EAAE;;AAgBzC,MAAM,yBAA8C,EAAE;AACtD,MAAM,2BAAkD,EAAE;AAE1D,MAAM,6BAAa,IAAI,KAAa;AACpC,IAAI,qBAAqB;AAOzB,IAAI;AACJ,IAAI;AAEJ,MAAM,iBAAiB,OAAO,IAAI,sBAAsB;AAExD,SAAS,aAAa,OAAsB;AAC1C,KAAI;EACF,MAAM,IAAI;AACV,IAAE,kBAAkB;SACd;;AAMV,aAAa,MAAM;AAGnB,MAAM,gCAAgB,IAAI,KAAsB;;;;AAKhD,SAAS,SAAS,MAAsB;CACtC,MAAM,aACJ,KAAK,SAAS,IAAI,IAAI,SAAS,MAAM,KAAK,MAAM,G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D,KAAI,SAAS,WAAW,EACtB,QAAO,kBAAkB,QAAQ,OAAO;CAG1C,MAAM,SACJ,QAAQ,UACR,kBAAkB,EAAE,UACpB,IAAI,iBAAiB,CAAC;CACxB,MAAM,OAAO,QAAQ,QAAQ,qBAAqB;CAClD,MAAM,OAAO,0BACX,QAAQ,QAAQ,QAAQ,UAAU,KACnC;CACD,MAAM,cAAc,sBAAsB,QAAQ,QAAQ;EACxD;EACA;EACD,CAAC;CAEF,MAAM,YAAY,cAChB,sBACE,UACA,kBAAkB,QAAQ,QAAQ;EAChC;EACA;EACA;EACA,SAAS,UAAU;EACnB,MAAM,UAAU;EACjB,CAAC,EACF,QACA,OACD;AAEH,KAAI,CAAC,MAAM,QACT,QAAO,SAAS;EAAE,SAAS;EAAM,MAAM;EAAM,CAAC;CAGhD,MAAM,YAAY,KAAK,QAAQ,YAAY;AAC3C,KAAI,UAAU,UAAU,CACtB,QAAO,UAAU,MAAM,SAAS,SAAS,KAAK,CAAC;AAGjD,QAAO,SAAS,UAAU;;;;;;;;;;;;;;;;AAiB5B,SAAgB,uBACd,UACA,WACsB;AACtB,KAAI,cAAc,OAAQ,QAAO,aAAa,SAAS;CAEvD,MAAM,QAAQ,gCAAgC,UAAU,UAAU;AAClE,QAAO,QAAQ;EAAE,SAAS,MAAM,MAAM;EAAS,QAAQ,MAAM;EAAQ,GAAG"}
|
|
1
|
+
{"version":3,"file":"route.js","names":[],"sources":["../../src/router/route.ts"],"sourcesContent":["/**\n * Route definition, registration, and matching.\n *\n * Primary public authoring:\n * - `registerRoutes(() => { ... }, options?)`\n * - `group(options, () => { ... })`\n * - `page(path, Component, () => { ... })`\n * - `index(Component, options?)`\n * - `route(path, Component, options?)`\n * - `fallback(Component)`\n * - `Outlet()` for page child rendering\n * - `currentRoute()` for render-time access\n *\n */\n\nimport { matchSegments, parseSegments, computeRank } from './match';\nimport {\n buildRouteContext,\n buildRouteContextBase,\n deepFreeze,\n makeQuery,\n parseLocation,\n} from './route-context';\nimport { defineContext, readContext } from '../runtime/context';\nimport { getCurrentComponentInstance } from '../runtime/component';\nimport { getExecutionModel } from '../runtime/execution-model';\nimport {\n markReadableDerivedSubscribersDirty,\n markReactivePropsDirtySource,\n notifyReadableReaders,\n recordReadableRead,\n type ReadableSource,\n} from '../runtime/readable';\nimport { getRenderContext } from '../ssr/context';\nimport {\n requireAuth,\n requireGuest,\n requirePermission,\n requireRole,\n} from './policy';\n\nexport type {\n AccessDecision,\n AccessDenyDecision,\n AccessRedirectDecision,\n GroupHelperOptions,\n PageHelperOptions,\n RegisterRoutesOptions,\n RouteDefinition,\n RouteAuthOptions,\n RouteHandler,\n Route,\n RouteContext,\n RoutePolicy,\n RouteRenderResult,\n RouteRequestOptions,\n RouteRequestResult,\n ResolvedRoute,\n RouteMatch,\n RouteQuery,\n RouteSnapshot,\n RouteComponent,\n RouteOptions,\n ParsedSegment,\n LayoutScopeRecord,\n PageScopeRecord,\n RouteRecord,\n RouteManifest,\n} from '../common/router';\n\nimport type {\n GroupHelperOptions,\n PageHelperOptions,\n RegisterRoutesOptions,\n RouteDefinition,\n RouteAuthOptions,\n RouteHandler,\n Route,\n RouteContext,\n RoutePolicy,\n RouteRenderResult,\n RouteRequestOptions,\n RouteRequestResult,\n ResolvedRoute,\n RouteMatch,\n RouteSnapshot,\n RouteComponent,\n RouteOptions,\n LayoutScopeRecord,\n PageScopeRecord,\n RouteRecord,\n RouteManifest,\n} from '../common/router';\n\n// ---------------------------------------------------------------------------\n// Module-level stores\n// ---------------------------------------------------------------------------\n\n/** Legacy flat route array — kept for resolver and route() accessor backward compat. */\ntype InternalRoute = Route & {\n fallbackPrefix?: string;\n};\n\ntype InternalRouteRecord = RouteRecord & {\n fallbackPrefix?: string;\n};\n\nconst routes: InternalRoute[] = [];\n\n/** Normalized route records built by the declarative registration API. */\nconst records: InternalRouteRecord[] = [];\n\ntype RegistrationScope = {\n kind: 'group' | 'page';\n pathPrefix: string;\n layout?: LayoutScopeRecord['component'];\n page?: PageScopeRecord['component'];\n policies: readonly RoutePolicy[];\n state: AccessScopeState;\n};\n\ntype RegistrationSession = {\n authConfigured: boolean;\n};\n\n/** Active registration scope stack during module-load-time registration. */\nconst registrationScopeStack: RegistrationScope[] = [];\nconst registrationSessionStack: RegistrationSession[] = [];\n\nconst namespaces = new Set<string>();\nlet registrationLocked = false;\n\ntype AccessScopeState = {\n guestOnly: boolean;\n authenticated: boolean;\n};\n\nlet defaultRouteAuthOptions: RouteAuthOptions | undefined;\nlet activeClientRouteAuthOptions: RouteAuthOptions | undefined;\n\nconst HAS_ROUTES_KEY = Symbol.for('__ASKR_HAS_ROUTES__');\n\nfunction setHasRoutes(value: boolean): void {\n try {\n const g = globalThis as unknown as Record<string | symbol, unknown>;\n g[HAS_ROUTES_KEY] = value;\n } catch {\n // ignore\n }\n}\n\n// Initialize to false at module load.\nsetHasRoutes(false);\n\n// Route index by depth - maintains insertion order\nconst routesByDepth = new Map<number, Route[]>();\n\n/**\n * Parse route path depth\n */\nfunction getDepth(path: string): number {\n const normalized =\n path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;\n return normalized === '/' ? 0 : normalized.split('/').filter(Boolean).length;\n}\n\n// ---------------------------------------------------------------------------\n// WeakMap caches for external Route[] objects (e.g. SSR per-request tables)\n// Amortises parseSegments / computeRank across repeated resolveRouteFromRoutes\n// calls on the same route list (same object reference).\n// ---------------------------------------------------------------------------\n\n/** Pre-parsed segments for an externally supplied Route object. */\nconst routeSegsCache = new WeakMap<Route, ReturnType<typeof parseSegments>>();\n/** Pre-computed rank for an externally supplied Route object. */\nconst routeRankCache = new WeakMap<Route, number>();\n/** A rank-descending sorted copy of an external readonly Route array. */\nconst sortedListCache = new WeakMap<\n ReadonlyArray<Route>,\n ReadonlyArray<Route>\n>();\n\nfunction cachedSegs(r: Route): ReturnType<typeof parseSegments> {\n let s = routeSegsCache.get(r);\n if (!s) {\n s = parseSegments(r.path);\n routeSegsCache.set(r, s);\n }\n return s;\n}\n\nfunction cachedRank(r: Route): number {\n let n = routeRankCache.get(r);\n if (n === undefined) {\n n = computeRank(cachedSegs(r));\n routeRankCache.set(r, n);\n }\n return n;\n}\n\nfunction cachedSortedList(\n routeList: ReadonlyArray<Route>\n): ReadonlyArray<Route> {\n let sorted = sortedListCache.get(routeList);\n if (!sorted) {\n sorted = [...routeList].sort((a, b) => cachedRank(b) - cachedRank(a));\n sortedListCache.set(routeList, sorted);\n }\n return sorted;\n}\n\nlet currentRouteSnapshot = buildRouteSnapshot('/', '', '');\n\nconst currentRouteSource = (() =>\n currentRouteSnapshot) as ReadableSource<RouteSnapshot> &\n (() => RouteSnapshot);\n\ncurrentRouteSource._readers = new Map();\n\n// SSR helper: when rendering on the server, callers may set a location so that\n// render-time route() returns deterministic server values that match client\n// hydration. This is deliberately an opt-in escape for SSR and tests.\nlet serverLocation: string | null = null;\n\nexport function setServerLocation(url: string | null): void {\n serverLocation = url;\n}\n\nfunction isPromise<T>(value: T | Promise<T>): value is Promise<T> {\n return value instanceof Promise;\n}\n\nfunction buildRouteSnapshot(\n pathname: string,\n search: string,\n hash: string\n): RouteSnapshot {\n const query = makeQuery(search);\n const matches = computeMatchesFromRoutes(pathname, getActiveRoutes());\n\n return Object.freeze({\n path: pathname,\n params: deepFreeze({ ...matches[0]?.params }),\n query,\n hash: hash || null,\n matches: Object.freeze(matches),\n });\n}\n\nfunction setCurrentRouteSnapshot(\n pathname: string,\n search: string,\n hash: string\n): void {\n currentRouteSnapshot = buildRouteSnapshot(pathname, search, hash);\n\n const instance = getCurrentComponentInstance();\n markReadableDerivedSubscribersDirty(currentRouteSource);\n markReactivePropsDirtySource(currentRouteSource);\n notifyReadableReaders(currentRouteSource, instance);\n}\n\n// Compute matches for a specific route list.\nfunction matchFallbackPrefix(\n pathname: string,\n fallbackPrefix: string\n): Record<string, string> | null {\n const normalizedPath =\n pathname.endsWith('/') && pathname !== '/'\n ? pathname.slice(0, -1)\n : pathname;\n const normalizedPrefix =\n fallbackPrefix.endsWith('/') && fallbackPrefix !== '/'\n ? fallbackPrefix.slice(0, -1)\n : fallbackPrefix;\n\n if (normalizedPrefix === '/') {\n const urlParts =\n normalizedPath === '/' ? [] : normalizedPath.split('/').filter(Boolean);\n return {\n '*':\n urlParts.length === 0\n ? '/'\n : urlParts.length === 1\n ? urlParts[0]\n : '/' + urlParts.join('/'),\n };\n }\n\n if (\n normalizedPath !== normalizedPrefix &&\n !normalizedPath.startsWith(`${normalizedPrefix}/`)\n ) {\n return null;\n }\n\n const remainder =\n normalizedPath === normalizedPrefix\n ? '/'\n : normalizedPath.slice(normalizedPrefix.length + 1);\n const remainderParts =\n remainder === '/' ? [] : remainder.split('/').filter(Boolean);\n\n return {\n '*':\n remainderParts.length === 0\n ? '/'\n : remainderParts.length === 1\n ? remainderParts[0]\n : '/' + remainderParts.join('/'),\n };\n}\n\nfunction computeMatchesFromRoutes(\n pathname: string,\n routesList: readonly Route[]\n): RouteMatch[] {\n const bestMatch =\n routesList === routes\n ? getMatchingRecord(pathname, records)\n : findBestResolvedRouteFromRoutes(pathname, routesList);\n\n if (!bestMatch) {\n return [];\n }\n\n return [\n {\n path: 'route' in bestMatch ? bestMatch.route.path : bestMatch.record.path,\n params: deepFreeze({ ...bestMatch.params }),\n name:\n 'route' in bestMatch\n ? (bestMatch.route as { name?: string }).name\n : undefined,\n namespace:\n 'route' in bestMatch\n ? bestMatch.route.namespace\n : bestMatch.record.options.namespace,\n },\n ];\n}\n\nfunction findBestResolvedRouteFromRoutes(\n pathname: string,\n routeList: readonly Route[]\n): { route: Route; params: Record<string, string> } | null {\n const normalized =\n pathname.endsWith('/') && pathname !== '/'\n ? pathname.slice(0, -1)\n : pathname;\n const urlParts =\n normalized === '/' ? [] : normalized.split('/').filter(Boolean);\n\n const sorted = cachedSortedList(routeList);\n let bestRoute: Route | null = null;\n let bestParams: Record<string, string> = {};\n let bestRank = -Infinity;\n\n for (const route of sorted) {\n const internalRoute = route as InternalRoute;\n if (internalRoute.fallbackPrefix) {\n continue;\n }\n\n const rank = cachedRank(route);\n if (rank < bestRank) break;\n if (bestRoute !== null && rank === bestRank) continue;\n\n const params = matchSegments(urlParts, cachedSegs(route));\n if (params !== null) {\n bestRoute = route;\n bestParams = params;\n bestRank = rank;\n }\n }\n\n if (bestRoute !== null) {\n return { route: bestRoute, params: bestParams };\n }\n\n let bestFallback: InternalRoute | null = null;\n let bestFallbackParams: Record<string, string> | null = null;\n let bestPrefixLength = -1;\n\n for (const route of routeList) {\n const internalRoute = route as InternalRoute;\n if (!internalRoute.fallbackPrefix) {\n continue;\n }\n\n const params = matchFallbackPrefix(\n normalized,\n internalRoute.fallbackPrefix\n );\n if (params === null) {\n continue;\n }\n\n if (internalRoute.fallbackPrefix.length > bestPrefixLength) {\n bestFallback = internalRoute;\n bestFallbackParams = params;\n bestPrefixLength = internalRoute.fallbackPrefix.length;\n }\n }\n\n return bestFallback && bestFallbackParams\n ? { route: bestFallback, params: bestFallbackParams }\n : null;\n}\n\nfunction getActiveRoutes(): readonly Route[] {\n const renderContext = getRenderContext();\n return renderContext?.routes ?? routes;\n}\n\nfunction getActiveRouteAuthOptions(\n override?: RouteAuthOptions\n): RouteAuthOptions | undefined {\n if (override) {\n return override;\n }\n\n const renderContext = getRenderContext();\n return (\n renderContext?.routeAuth ??\n activeClientRouteAuthOptions ??\n defaultRouteAuthOptions\n );\n}\n\nexport function _setActiveRouteAuthOptions(\n auth: RouteAuthOptions | undefined\n): void {\n activeClientRouteAuthOptions = auth;\n}\n\nfunction getCurrentRegistrationSession(): RegistrationSession {\n return (\n registrationSessionStack[registrationSessionStack.length - 1] ?? {\n authConfigured: !!defaultRouteAuthOptions?.resolve,\n }\n );\n}\n\nfunction getCurrentAccessScopeState(): AccessScopeState {\n return (\n registrationScopeStack[registrationScopeStack.length - 1]?.state ?? {\n guestOnly: false,\n authenticated: false,\n }\n );\n}\n\nfunction getCurrentLayoutChain(): LayoutScopeRecord[] {\n const layoutChain: LayoutScopeRecord[] = [];\n\n for (const scope of registrationScopeStack) {\n if (scope.layout) {\n layoutChain.push({ component: scope.layout });\n }\n }\n\n return layoutChain;\n}\n\nfunction getCurrentPageChain(): PageScopeRecord[] {\n const pageChain: PageScopeRecord[] = [];\n\n for (const scope of registrationScopeStack) {\n if (scope.page) {\n pageChain.push({ component: scope.page });\n }\n }\n\n return pageChain;\n}\n\nfunction hasActivePageScope(): boolean {\n return registrationScopeStack.some((scope) => !!scope.page);\n}\n\nfunction getCurrentScopeKind(): RegistrationScope['kind'] | null {\n return (\n registrationScopeStack[registrationScopeStack.length - 1]?.kind ?? null\n );\n}\n\nfunction getCurrentPathPrefix(): string {\n return (\n registrationScopeStack[registrationScopeStack.length - 1]?.pathPrefix ?? ''\n );\n}\n\nfunction getCurrentInheritedPolicies(): RoutePolicy[] {\n const policies: RoutePolicy[] = [];\n\n for (const scope of registrationScopeStack) {\n if (scope.policies.length > 0) {\n policies.push(...scope.policies);\n }\n }\n\n return policies;\n}\n\n// ---------------------------------------------------------------------------\n// Registration lock\n// ---------------------------------------------------------------------------\n\n/**\n * Prevent route registrations after the app has started.\n * Enforced in production; tests may unlock explicitly.\n */\n\nexport function lockRouteRegistration(): void {\n registrationLocked = true;\n}\n\nexport function _lockRouteRegistrationForTests(): void {\n registrationLocked = true;\n}\n\nexport function _unlockRouteRegistrationForTests(): void {\n registrationLocked = false;\n}\n\n// ---------------------------------------------------------------------------\n// Path validation\n// ---------------------------------------------------------------------------\n\nfunction validateRoutePath(path: string): void {\n if (!path.startsWith('/')) {\n throw new Error(`Route path must begin with \"/\". Got: \"${path}\"`);\n }\n // Reject Express-style :param syntax — Askr uses {param} interpolation\n if (/:([^/{}]+)/.test(path)) {\n const suggested = path.replace(/:([^/{}]+)/g, '{$1}');\n throw new Error(\n `Route parameter syntax uses {name} interpolation, not :name. ` +\n `Use \"${suggested}\" instead of \"${path}\".`\n );\n }\n}\n\nfunction normalizeAbsoluteRoutePath(path: string): string {\n if (!path || path === '/') {\n return '/';\n }\n\n const normalized = path.endsWith('/') ? path.slice(0, -1) : path;\n return normalized || '/';\n}\n\nfunction joinRoutePaths(prefix: string, path: string): string {\n const normalizedPrefix = normalizeAbsoluteRoutePath(prefix || '/');\n const normalizedPath = path.replace(/^\\/+|\\/+$/g, '');\n\n if (!normalizedPath) {\n return normalizedPrefix;\n }\n\n return normalizedPrefix === '/'\n ? `/${normalizedPath}`\n : `${normalizedPrefix}/${normalizedPath}`;\n}\n\nfunction resolvePageScopePath(path: string): string {\n if (!path) {\n throw new Error('page(path, Component, fn) requires a non-empty path.');\n }\n\n if (path.startsWith('/')) {\n validateRoutePath(path);\n return normalizeAbsoluteRoutePath(path);\n }\n\n return joinRoutePaths(getCurrentPathPrefix(), path);\n}\n\nfunction resolveIndexPath(): string {\n return normalizeAbsoluteRoutePath(getCurrentPathPrefix() || '/');\n}\n\nfunction resolveRouteRegistrationPath(path: string): string {\n if (path.startsWith('/')) {\n if (hasActivePageScope()) {\n throw new Error(\n 'Child route paths inside page() must be relative. ' +\n `Use \"${path.slice(1)}\" instead of \"${path}\".`\n );\n }\n\n validateRoutePath(path);\n return normalizeAbsoluteRoutePath(path);\n }\n\n const prefix = getCurrentPathPrefix();\n\n if (!prefix) {\n throw new Error(`Route path must begin with \"/\". Got: \"${path}\"`);\n }\n\n return joinRoutePaths(prefix, path);\n}\n\n// ---------------------------------------------------------------------------\n// Internal helper: insert a RouteRecord in rank-descending order\n// so that resolveRoute can use first-match-wins without sorting.\n// Ties preserve declaration order (stable binary-search insertion).\n// ---------------------------------------------------------------------------\n\nfunction insertRecordSorted(record: RouteRecord): void {\n let lo = 0;\n let hi = records.length;\n // Find the insertion point: after all existing records with rank >= this one\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (records[mid].rank >= record.rank) lo = mid + 1;\n else hi = mid;\n }\n records.splice(lo, 0, record);\n}\n\n// ---------------------------------------------------------------------------\n// Internal helper: add a single pre-built Route object to the runtime stores\n// ---------------------------------------------------------------------------\n\nfunction addRouteToStores(routeObj: Route): void {\n routes.push(routeObj);\n setHasRoutes(true);\n\n const depth = getDepth(routeObj.path);\n let depthRoutes = routesByDepth.get(depth);\n if (!depthRoutes) {\n depthRoutes = [];\n routesByDepth.set(depth, depthRoutes);\n }\n depthRoutes.push(routeObj);\n\n if (routeObj.namespace) {\n namespaces.add(routeObj.namespace);\n }\n}\n\n// ---------------------------------------------------------------------------\n// lazy() — eager-prefetch code-split component wrapper\n// ---------------------------------------------------------------------------\n\n/** Promises from in-flight lazy() imports, drained by createSPA / hydrateSPA. */\nconst pendingLazy = new Set<Promise<unknown>>();\n\nconst outletContext = defineContext<unknown>(null);\n\nexport function Outlet(): unknown {\n return readContext(outletContext);\n}\n\n/**\n * Snapshot the current in-flight lazy() imports.\n * Boot uses this before clearing route state so manifest-based startup can\n * still await chunks that were kicked off during route module evaluation.\n */\nexport function _snapshotLazy(): Promise<unknown>[] {\n return [...pendingLazy];\n}\n\n/**\n * Declare a code-split route component. The `import()` fires immediately at\n * module evaluation time (creating a bundler split point), and the resolved\n * chunk is guaranteed to be available before the app mounts — so the renderer\n * always receives a plain synchronous function.\n *\n * ```ts\n * registerRoutes(() => {\n * group({ layout: AppLayout }, () => {\n * route('/', lazy(() => import('./pages/landing')));\n * route('/dashboard', lazy(() => import('./pages/dashboard')));\n * });\n * });\n * ```\n *\n * The module must export the component as its **default** export:\n * ```ts\n * // pages/dashboard.tsx\n * export default function DashboardPage() { … }\n * ```\n */\nexport function lazy(\n factory: () => Promise<{ default: RouteComponent } | RouteComponent>\n): RouteComponent {\n let resolved: RouteComponent | null = null;\n let loadError: unknown = null;\n\n const promise = factory().then(\n (mod) => {\n resolved =\n typeof mod === 'function'\n ? mod\n : (mod as { default: RouteComponent }).default;\n pendingLazy.delete(promise);\n },\n (err: unknown) => {\n loadError = err;\n pendingLazy.delete(promise);\n }\n );\n pendingLazy.add(promise);\n\n return (params) => {\n if (loadError) throw loadError as Error;\n if (!resolved) {\n throw new Error(\n 'lazy() component used before it was resolved. ' +\n 'Await createSPA() / hydrateSPA() to ensure all chunks load first.'\n );\n }\n return resolved(params);\n };\n}\n\n/**\n * Wait for all pending `lazy()` imports to settle.\n * Called automatically by `createSPA` / `hydrateSPA` before mounting.\n */\nexport function _drainLazy(\n additionalPending: Iterable<Promise<unknown>> = []\n): Promise<void> {\n const combined = new Set<Promise<unknown>>([\n ...additionalPending,\n ...pendingLazy,\n ]);\n if (combined.size === 0) return Promise.resolve();\n return Promise.allSettled(combined).then(() => undefined);\n}\n\nexport function group(options: GroupHelperOptions, fn: RouteDefinition): void;\nexport function group(options: GroupHelperOptions, fn: RouteDefinition): void {\n pushGroupScope(options, fn);\n}\n\nexport function page(\n path: string,\n Component: RouteComponent,\n fn: RouteDefinition\n): void;\nexport function page(\n path: string,\n Component: RouteComponent,\n options: PageHelperOptions,\n fn: RouteDefinition\n): void;\nexport function page(\n path: string,\n Component: RouteComponent,\n optionsOrFn: PageHelperOptions | RouteDefinition,\n maybeFn?: RouteDefinition\n): void {\n const options =\n typeof optionsOrFn === 'function' ? ({} as PageHelperOptions) : optionsOrFn;\n const fn = typeof optionsOrFn === 'function' ? optionsOrFn : maybeFn;\n\n if (typeof Component !== 'function') {\n throw new Error(\n 'page(path, Component, fn) requires a component function as the second argument.'\n );\n }\n\n if (typeof fn !== 'function') {\n throw new Error(\n 'page(path, Component, fn) requires a route definition callback as the final argument.'\n );\n }\n\n pushPageScope(path, Component, options, fn);\n}\n\nexport function index(Component: RouteComponent, options?: RouteOptions): void {\n registerRouteAtResolvedPath(resolveIndexPath(), Component, options);\n}\n\nexport function fallback(Component: RouteComponent): void {\n if (hasActivePageScope()) {\n if (getCurrentScopeKind() !== 'page') {\n throw new Error(\n 'fallback() inside page() must be declared directly in the page scope, not inside nested group().'\n );\n }\n\n registerRouteAtResolvedPath(\n `${getCurrentPathPrefix()}/*`,\n Component,\n undefined,\n { isFallback: true, fallbackPrefix: getCurrentPathPrefix() }\n );\n return;\n }\n\n const allowsRootFallback = registrationScopeStack.every(\n (scope) =>\n scope.policies.length === 0 &&\n !scope.state.guestOnly &&\n !scope.state.authenticated\n );\n\n if (!allowsRootFallback) {\n throw new Error(\n 'fallback() can only be registered at the root scope. ' +\n 'Use route(\"/*\", Component) if you need compatibility behavior.'\n );\n }\n\n registerRouteAtResolvedPath('/*', Component, undefined, {\n isFallback: true,\n fallbackPrefix: '/',\n });\n}\n\nfunction pushRegistrationScope(\n scope: RegistrationScope,\n fn: RouteDefinition\n): void {\n registrationScopeStack.push(scope);\n try {\n fn();\n } finally {\n registrationScopeStack.pop();\n }\n}\n\nfunction pushGroupScope(\n options: GroupHelperOptions,\n fn: RouteDefinition\n): void {\n const session = getCurrentRegistrationSession();\n validateAccessMetadata(options, {\n authConfigured: session.authConfigured,\n state: getCurrentAccessScopeState(),\n });\n const policies = compileNodePolicies(options);\n\n pushRegistrationScope(\n {\n kind: 'group',\n pathPrefix: getCurrentPathPrefix(),\n layout: options.layout,\n policies,\n state: nextAccessScopeState(options, getCurrentAccessScopeState()),\n },\n fn\n );\n}\n\nfunction pushPageScope(\n path: string,\n Component: RouteComponent,\n options: PageHelperOptions,\n fn: RouteDefinition\n): void {\n if (hasActivePageScope()) {\n throw new Error(\n 'page() cannot be nested inside another page(). ' +\n 'Use route() for child leaves or group() for inherited behavior inside the existing page scope.'\n );\n }\n\n const session = getCurrentRegistrationSession();\n validateAccessMetadata(options, {\n authConfigured: session.authConfigured,\n state: getCurrentAccessScopeState(),\n });\n\n const policies = compileNodePolicies(options);\n\n pushRegistrationScope(\n {\n kind: 'page',\n pathPrefix: resolvePageScopePath(path),\n page: Component,\n policies,\n state: nextAccessScopeState(options, getCurrentAccessScopeState()),\n },\n fn\n );\n}\n\nfunction hasBuiltInAuthMetadata(\n node: Pick<GroupHelperOptions | RouteOptions, 'auth' | 'role' | 'permission'>\n): boolean {\n return node.auth !== undefined || !!node.role || !!node.permission;\n}\n\nfunction validateSameNodeAccessMetadata(\n node: Pick<GroupHelperOptions | RouteOptions, 'auth' | 'role' | 'permission'>\n): void {\n if (node.auth === 'guest' && (!!node.role || !!node.permission)) {\n throw new Error(\n 'Guest-only routes cannot be combined with role or permission requirements.'\n );\n }\n}\n\nfunction validateAccessMetadata(\n node: Pick<GroupHelperOptions | RouteOptions, 'auth' | 'role' | 'permission'>,\n context: {\n authConfigured: boolean;\n state: AccessScopeState;\n }\n): void {\n validateSameNodeAccessMetadata(node);\n\n const requiresAuthenticated =\n node.auth === true || !!node.role || !!node.permission;\n\n if (\n node.auth === 'guest' &&\n (context.state.authenticated || !!node.role || !!node.permission)\n ) {\n throw new Error(\n 'Guest-only routes cannot be combined with authenticated access requirements.'\n );\n }\n\n if (context.state.guestOnly && requiresAuthenticated) {\n throw new Error(\n 'Child routes cannot weaken a guest-only access scope with authenticated requirements.'\n );\n }\n\n if (hasBuiltInAuthMetadata(node) && !context.authConfigured) {\n throw new Error(\n 'Routes using `auth`, `role`, or `permission` require `auth.resolve` in registerRoutes(...).'\n );\n }\n}\n\nfunction nextAccessScopeState(\n node: Pick<GroupHelperOptions | RouteOptions, 'auth' | 'role' | 'permission'>,\n state: AccessScopeState\n): AccessScopeState {\n const requiresAuthenticated =\n node.auth === true || !!node.role || !!node.permission;\n\n return {\n guestOnly: state.guestOnly || node.auth === 'guest',\n authenticated: state.authenticated || requiresAuthenticated,\n };\n}\n\nfunction compileNodePolicies(\n node: Pick<\n RouteOptions | GroupHelperOptions,\n 'auth' | 'role' | 'permission' | 'policies'\n >\n): RoutePolicy[] {\n validateSameNodeAccessMetadata(node);\n\n const compiled: RoutePolicy[] = [];\n\n if (node.auth === true) {\n compiled.push(requireAuth());\n } else if (node.auth === 'guest') {\n compiled.push(requireGuest());\n }\n\n if (node.role) {\n compiled.push(requireRole(node.role));\n }\n\n if (node.permission) {\n compiled.push(requirePermission(node.permission));\n }\n\n if (node.policies?.length) {\n compiled.push(...node.policies);\n }\n\n return compiled;\n}\n\nfunction normalizeRouteOptions(\n options: RouteOptions | undefined\n): RouteOptions | undefined {\n if (!options) {\n return undefined;\n }\n\n const loader = options.loader;\n const policies = compileNodePolicies(options);\n\n if (\n !loader &&\n !options.entries &&\n policies.length === 0 &&\n !options.title &&\n !options.namespace &&\n options.auth === undefined &&\n !options.role &&\n !options.permission\n ) {\n return undefined;\n }\n\n return {\n ...(loader ? { loader } : {}),\n ...(options.entries ? { entries: options.entries } : {}),\n ...(options.auth !== undefined ? { auth: options.auth } : {}),\n ...(options.role ? { role: options.role } : {}),\n ...(options.permission ? { permission: options.permission } : {}),\n ...(policies.length > 0 ? { policies } : {}),\n ...(options.title ? { title: options.title } : {}),\n ...(options.namespace ? { namespace: options.namespace } : {}),\n };\n}\n\nfunction applyPageChain(\n pageChain: readonly PageScopeRecord[],\n params: Record<string, string>,\n content: unknown\n): unknown {\n let nextContent = content;\n\n for (let i = pageChain.length - 1; i >= 0; i--) {\n nextContent = outletContext.Scope({\n value: nextContent,\n children: pageChain[i].component(params),\n });\n }\n\n return nextContent;\n}\n\nfunction registerRouteAtResolvedPath(\n path: string,\n Component: RouteComponent,\n options?: RouteOptions,\n metadata?: {\n isFallback?: boolean;\n fallbackPrefix?: string;\n }\n): void {\n validateAccessMetadata(options ?? {}, {\n authConfigured: getCurrentRegistrationSession().authConfigured,\n state: getCurrentAccessScopeState(),\n });\n\n const chain = getCurrentLayoutChain();\n const pageChain = getCurrentPageChain();\n const segments = parseSegments(path);\n const rank = computeRank(segments);\n const isFallback = metadata?.isFallback ?? path === '/*';\n const comp = Component;\n const normalizedOptions = normalizeRouteOptions(options);\n const policies = [\n ...getCurrentInheritedPolicies(),\n ...(normalizedOptions?.policies ?? []),\n ];\n\n const handler: RouteHandler = (params) => {\n let content = comp(params);\n\n content = applyPageChain(pageChain, params, content);\n\n for (let i = chain.length - 1; i >= 0; i--) {\n content = chain[i].component({ children: content });\n }\n\n return content;\n };\n\n const record: InternalRouteRecord = {\n path,\n component: comp,\n segments,\n rank,\n layoutChain: chain,\n pageChain,\n options: normalizedOptions\n ? {\n ...normalizedOptions,\n ...(policies.length > 0 ? { policies } : {}),\n }\n : policies.length > 0\n ? { policies }\n : {},\n isFallback,\n handler,\n ...(metadata?.fallbackPrefix\n ? { fallbackPrefix: metadata.fallbackPrefix }\n : {}),\n };\n\n insertRecordSorted(record);\n addRouteToStores({\n path,\n handler,\n namespace: normalizedOptions?.namespace ?? options?.namespace,\n ...(metadata?.fallbackPrefix\n ? { fallbackPrefix: metadata.fallbackPrefix }\n : {}),\n });\n}\n\nexport function registerRoutes(\n definition: RouteDefinition,\n options: RegisterRoutesOptions = {}\n): void {\n defaultRouteAuthOptions = options.auth;\n\n registrationSessionStack.push({\n authConfigured: !!options.auth?.resolve,\n });\n try {\n definition();\n } finally {\n registrationSessionStack.pop();\n }\n}\n\n// ---------------------------------------------------------------------------\n// route() — dual-purpose: registration (module load) + accessor (render time)\n// ---------------------------------------------------------------------------\n\nfunction readCurrentRouteSnapshot(): RouteSnapshot {\n const instance = getCurrentComponentInstance();\n if (!instance) {\n throw new Error(\n 'currentRoute() can only be called during component render execution. ' +\n 'Call currentRoute() from inside your component function.'\n );\n }\n\n let pathname = '/';\n let search = '';\n let hash = '';\n const renderContext = getRenderContext();\n\n if (instance.ssr && renderContext?.url) {\n const parsed = parseLocation(renderContext.url);\n pathname = parsed.pathname;\n search = parsed.search;\n hash = parsed.hash;\n } else if (typeof window !== 'undefined' && window.location) {\n pathname = window.location.pathname || '/';\n search = window.location.search || '';\n hash = window.location.hash || '';\n } else if (serverLocation) {\n const parsed = parseLocation(serverLocation);\n pathname = parsed.pathname;\n search = parsed.search;\n hash = parsed.hash;\n }\n\n const query = makeQuery(search);\n const matches = computeMatchesFromRoutes(pathname, getActiveRoutes());\n const instanceParams = instance.props as Record<string, string>;\n const routeParams =\n Object.keys(instanceParams).length > 0\n ? instanceParams\n : (matches[0]?.params ?? {});\n const params = deepFreeze({\n ...routeParams,\n });\n\n return Object.freeze({\n path: pathname,\n params,\n query,\n hash: hash || null,\n matches: Object.freeze(matches),\n });\n}\n\nexport function currentRoute(): RouteSnapshot {\n const instance = getCurrentComponentInstance();\n if (!instance) {\n throw new Error(\n 'currentRoute() can only be called during component render execution. ' +\n 'Call currentRoute() from inside your component function.'\n );\n }\n\n if (typeof window === 'undefined' || instance.ssr) {\n return readCurrentRouteSnapshot();\n }\n\n recordReadableRead(currentRouteSource);\n return readCurrentRouteSnapshot();\n}\n\nexport function syncCurrentRouteSnapshot(\n pathname: string,\n search: string,\n hash: string\n): void {\n setCurrentRouteSnapshot(pathname, search, hash);\n}\n\n/**\n * Register a route.\n *\n * ```ts\n * route('/posts/{slug}', PostPage, {\n * loader: ({ params }) => getPost(params.slug),\n * entries: async () => getPosts().map(p => ({ slug: p.slug })),\n * title: 'Post',\n * policies:[requireAuth()],\n * });\n * ```\n */\nexport function route(\n path: string,\n Component: RouteComponent,\n options?: RouteOptions\n): void;\nexport function route(\n path: string,\n Component: RouteComponent,\n options?: RouteOptions\n): void {\n if (typeof path === 'undefined') {\n throw new Error(\n 'route() is only for route registration. Use currentRoute() inside components.'\n );\n }\n\n if (getExecutionModel() === 'islands') {\n throw new Error(\n 'Routes are not supported with islands. Use createSPA (client) or createSSR (server) instead.'\n );\n }\n\n // ── Registration mode ────────────────────────────────────────────────────\n\n // Disallow registration during SSR render\n const currentInst = getCurrentComponentInstance();\n if (currentInst && currentInst.ssr) {\n throw new Error(\n 'route() cannot be called during SSR rendering. Register routes at module load time instead.'\n );\n }\n\n if (registrationLocked) {\n throw new Error(\n 'Route registration is locked after app startup. ' +\n 'Register routes at module load time before calling createSPA or createSSR.'\n );\n }\n\n if (typeof Component !== 'function') {\n throw new Error(\n 'route(path, Component) requires a component function as the second argument. ' +\n 'Passing JSX elements or VNodes directly is not supported.'\n );\n }\n\n registerRouteAtResolvedPath(\n resolveRouteRegistrationPath(path),\n Component,\n options\n );\n}\n\n// ---------------------------------------------------------------------------\n// Manifest access\n// ---------------------------------------------------------------------------\n\n/**\n * Return the normalized route manifest built from registered route definitions.\n *\n * Pass this to `createSPA`, `hydrateSPA`, or `renderToString` as the\n * authoritative routing input:\n *\n * ```ts\n * import { getManifest } from '@askrjs/askr/router';\n * await createSPA({ root: '#app', manifest: getManifest() });\n * ```\n */\nexport function getManifest(): RouteManifest {\n return {\n records: [...records],\n ...(defaultRouteAuthOptions ? { auth: defaultRouteAuthOptions } : {}),\n };\n}\n\n/**\n * Internal: apply a pre-built manifest to the runtime stores without running\n * route() again. Called by createSPA / hydrateSPA when a manifest is passed.\n */\nexport function _applyManifest(manifest: RouteManifest): void {\n defaultRouteAuthOptions = manifest.auth;\n for (const record of manifest.records) {\n insertRecordSorted(record as InternalRouteRecord);\n addRouteToStores({\n path: record.path,\n handler: record.handler,\n namespace: record.options.namespace,\n ...('fallbackPrefix' in record &&\n typeof (record as InternalRouteRecord).fallbackPrefix === 'string'\n ? {\n fallbackPrefix: (record as InternalRouteRecord).fallbackPrefix,\n }\n : {}),\n });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Route collection helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Get all registered routes (flat list, insertion order).\n * Prefer `getManifest()` when metadata (loader, policies, entries) is needed.\n */\nexport function getRoutes(): Route[] {\n return [...routes];\n}\n\n/** Get routes for a specific namespace. */\nexport function getNamespaceRoutes(namespace: string): Route[] {\n return routes.filter((r) => r.namespace === namespace);\n}\n\n/** Unload all routes from a namespace (for MFE unmounting). */\nexport function unloadNamespace(namespace: string): number {\n const before = routes.length;\n\n for (let i = routes.length - 1; i >= 0; i--) {\n if (routes[i].namespace === namespace) {\n const removed = routes[i];\n routes.splice(i, 1);\n\n const depth = getDepth(removed.path);\n const depthRoutes = routesByDepth.get(depth);\n if (depthRoutes) {\n const idx = depthRoutes.indexOf(removed);\n if (idx >= 0) depthRoutes.splice(idx, 1);\n }\n }\n }\n\n // Remove matching records too\n for (let i = records.length - 1; i >= 0; i--) {\n if (records[i].options.namespace === namespace) {\n records.splice(i, 1);\n }\n }\n\n namespaces.delete(namespace);\n return before - routes.length;\n}\n\n/** Clear all registered routes and records (testing / boot reset). */\nexport function clearRoutes(): void {\n routes.length = 0;\n records.length = 0;\n namespaces.clear();\n routesByDepth.clear();\n registrationScopeStack.length = 0;\n registrationSessionStack.length = 0;\n registrationLocked = false;\n defaultRouteAuthOptions = undefined;\n activeClientRouteAuthOptions = undefined;\n setHasRoutes(false);\n pendingLazy.clear();\n}\n\n/**\n * Get all loaded namespaces (MFE identifiers)\n */\nexport function getLoadedNamespaces(): string[] {\n return Array.from(namespaces);\n}\n\nfunction findBestScopedFallbackRecord(\n pathname: string,\n routeRecords: readonly RouteRecord[]\n): { record: InternalRouteRecord; params: Record<string, string> } | null {\n let bestRecord: InternalRouteRecord | null = null;\n let bestParams: Record<string, string> | null = null;\n let bestPrefixLength = -1;\n\n for (const routeRecord of routeRecords) {\n const record = routeRecord as InternalRouteRecord;\n if (!record.fallbackPrefix) {\n continue;\n }\n\n const params = matchFallbackPrefix(pathname, record.fallbackPrefix);\n if (params === null) {\n continue;\n }\n\n if (record.fallbackPrefix.length > bestPrefixLength) {\n bestRecord = record;\n bestParams = params;\n bestPrefixLength = record.fallbackPrefix.length;\n }\n }\n\n return bestRecord && bestParams\n ? { record: bestRecord, params: bestParams }\n : null;\n}\n\n/**\n * Resolve a path to a route handler.\n *\n * Hot path: walks the module-level `records[]` array which is kept sorted by\n * rank descending at registration time — so the first `matchSegments` hit is\n * always the most specific match. No per-call allocations for the common\n * case of purely-static routes.\n */\nexport function resolveRoute(pathname: string): ResolvedRoute | null {\n const normalized =\n pathname.endsWith('/') && pathname !== '/'\n ? pathname.slice(0, -1)\n : pathname;\n const urlParts =\n normalized === '/' ? [] : normalized.split('/').filter(Boolean);\n\n for (const record of records) {\n if (record.fallbackPrefix) {\n continue;\n }\n\n const params = matchSegments(urlParts, record.segments);\n if (params !== null) {\n return { handler: record.handler, params };\n }\n }\n\n const fallbackMatch = findBestScopedFallbackRecord(normalized, records);\n return fallbackMatch\n ? { handler: fallbackMatch.record.handler, params: fallbackMatch.params }\n : null;\n}\n\nfunction getMatchingRecord(\n target: string,\n routeRecords: readonly RouteRecord[]\n): { record: RouteRecord; params: Record<string, string> } | null {\n const location = parseLocation(target);\n const normalized =\n location.pathname.endsWith('/') && location.pathname !== '/'\n ? location.pathname.slice(0, -1)\n : location.pathname;\n const urlParts =\n normalized === '/' ? [] : normalized.split('/').filter(Boolean);\n\n for (const record of routeRecords) {\n const internalRecord = record as InternalRouteRecord;\n if (internalRecord.fallbackPrefix) {\n continue;\n }\n\n const params = matchSegments(urlParts, record.segments);\n if (params !== null) {\n return { record, params };\n }\n }\n\n return findBestScopedFallbackRecord(normalized, routeRecords);\n}\n\nfunction getRoutePolicies(\n options: RouteOptions | undefined\n): readonly RoutePolicy[] {\n if (!options) {\n return [];\n }\n\n if (options.policies?.length) {\n return options.policies;\n }\n\n return compileNodePolicies(options);\n}\n\nfunction getDefaultRouteMode(): RouteContext['mode'] {\n if (typeof window !== 'undefined') {\n return 'spa';\n }\n\n return 'ssr';\n}\n\nfunction buildRenderResult(\n record: RouteRecord,\n params: Record<string, string>\n): RouteRenderResult {\n return {\n kind: 'render',\n handler: record.handler,\n params,\n };\n}\n\nfunction continueRoutePolicies(\n policies: readonly RoutePolicy[],\n context: RouteContext,\n record: RouteRecord,\n params: Record<string, string>,\n startIndex = 0\n): RouteRequestResult | Promise<RouteRequestResult> {\n for (let index = startIndex; index < policies.length; index += 1) {\n const policyResult = policies[index](context);\n\n if (isPromise(policyResult)) {\n return policyResult.then((next) => {\n if (next.kind !== 'allow') {\n return next;\n }\n\n return continueRoutePolicies(\n policies,\n context,\n record,\n params,\n index + 1\n );\n });\n }\n\n if (policyResult.kind !== 'allow') {\n return policyResult;\n }\n }\n\n return buildRenderResult(record, params);\n}\n\nexport function resolveRouteRequest(\n target: string,\n options: RouteRequestOptions = {}\n): RouteRequestResult | Promise<RouteRequestResult> {\n const routeRecords = options.manifest?.records ?? records;\n const match = getMatchingRecord(target, routeRecords);\n\n if (!match) {\n return null;\n }\n\n const { record, params } = match;\n const policies = getRoutePolicies(record.options);\n\n if (policies.length === 0) {\n return buildRenderResult(record, params);\n }\n\n const signal =\n options.signal ??\n getRenderContext()?.signal ??\n new AbortController().signal;\n const mode = options.mode ?? getDefaultRouteMode();\n const auth = getActiveRouteAuthOptions(\n options.auth ?? options.manifest?.auth\n );\n const baseContext = buildRouteContextBase(target, params, {\n mode,\n signal,\n });\n\n const finalize = (authState: { session: unknown; user: unknown }) =>\n continueRoutePolicies(\n policies,\n buildRouteContext(target, params, {\n mode,\n signal,\n auth,\n session: authState.session,\n user: authState.user,\n }),\n record,\n params\n );\n\n if (!auth?.resolve) {\n return finalize({ session: null, user: null });\n }\n\n const authState = auth.resolve(baseContext);\n if (isPromise(authState)) {\n return authState.then((next) => finalize(next));\n }\n\n return finalize(authState);\n}\n\n/**\n * Resolve a path against an explicit route list (e.g. an SSR per-render\n * context). When called with the global `routes` array this delegates to\n * the faster `resolveRoute` which uses pre-sorted `records[]`.\n *\n * For externally supplied lists the function:\n * 1. Builds a rank-sorted copy of the list on first call and caches it\n * in a WeakMap so subsequent resolutions against the same list pay\n * zero sort cost.\n * 2. Uses pre-parsed `ParsedSegment[]` from a WeakMap cache so no string\n * splitting or segment parsing occurs on the hot path.\n * 3. Uses a running-best with an early-exit once the sorted list reaches\n * a rank that cannot beat the current best match.\n */\nexport function resolveRouteFromRoutes(\n pathname: string,\n routeList: readonly Route[]\n): ResolvedRoute | null {\n if (routeList === routes) return resolveRoute(pathname);\n\n const match = findBestResolvedRouteFromRoutes(pathname, routeList);\n return match ? { handler: match.route.handler, params: match.params } : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA2GA,MAAM,SAA0B,EAAE;;AAGlC,MAAM,UAAiC,EAAE;;AAgBzC,MAAM,yBAA8C,EAAE;AACtD,MAAM,2BAAkD,EAAE;AAE1D,MAAM,6BAAa,IAAI,KAAa;AACpC,IAAI,qBAAqB;AAOzB,IAAI;AACJ,IAAI;AAEJ,MAAM,iBAAiB,OAAO,IAAI,sBAAsB;AAExD,SAAS,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ACtB,OAAO,UAAU,MAAM,SAAS,SAAS,KAAK,CAAC;CAGjD,OAAO,SAAS,UAAU;;;;;;;;;;;;;;;;AAiB5B,SAAgB,uBACd,UACA,WACsB;CACtB,IAAI,cAAc,QAAQ,OAAO,aAAa,SAAS;CAEvD,MAAM,QAAQ,gCAAgC,UAAU,UAAU;CAClE,OAAO,QAAQ;EAAE,SAAS,MAAM,MAAM;EAAS,QAAQ,MAAM;EAAQ,GAAG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"child-scope.d.ts","names":[],"sources":["../../src/runtime/child-scope.ts"],"mappings":";;;;UAciB,UAAA;EACf,GAAA;EACA,iBAAA,EAAmB,iBAAA;EACnB,aAAA,EAAe,KAAA;EACf,KAAA,EAAO,KAAA;EACP,GAAA,GAAM,IAAA;EACN,cAAA;EACA,MAAA,CAAO,QAAA,QAAgB,KAAA,GAAQ,KAAA;EAC/B,SAAA;EACA,OAAA;AAAA;AAAA,iBAiEc,kBAAA,CAAmB,KAAA,EAAO,UAAA,GAAa,KAAA;AAAA,iBAIvC,iBAAA,CAAkB,KAAA,EAAO,UAAA;AAAA,iBAIzB,gBAAA,CACd,MAAA,EAAQ,iBAAA,SACR,GAAA,mBACA,OAAA,gBACC,UAAA"}
|
|
1
|
+
{"version":3,"file":"child-scope.d.ts","names":[],"sources":["../../src/runtime/child-scope.ts"],"mappings":";;;;UAciB,UAAA;EACf,GAAA;EACA,iBAAA,EAAmB,iBAAA;EACnB,aAAA,EAAe,KAAA;EACf,KAAA,EAAO,KAAA;EACP,GAAA,GAAM,IAAA;EACN,cAAA;EACA,gBAAA;EACA,MAAA,CAAO,QAAA,QAAgB,KAAA,GAAQ,KAAA;EAC/B,SAAA;EACA,OAAA;AAAA;AAAA,iBAiEc,kBAAA,CAAmB,KAAA,EAAO,UAAA,GAAa,KAAA;AAAA,iBAIvC,iBAAA,CAAkB,KAAA,EAAO,UAAA;AAAA,iBAIzB,gBAAA,CACd,MAAA,EAAQ,iBAAA,SACR,GAAA,mBACA,OAAA,gBACC,UAAA"}
|
|
@@ -39,6 +39,7 @@ function createChildScope(parent, key, onDirty) {
|
|
|
39
39
|
scope.vnode = void 0;
|
|
40
40
|
scope.dom = void 0;
|
|
41
41
|
scope.needsDomUpdate = true;
|
|
42
|
+
scope.hydrationPending = true;
|
|
42
43
|
scope._startStateIndex = getCurrentStateIndex();
|
|
43
44
|
scope._renderFn = void 0;
|
|
44
45
|
scope._onDirty = onDirty;
|
|
@@ -61,6 +62,7 @@ function createChildScope(parent, key, onDirty) {
|
|
|
61
62
|
scope.vnode = void 0;
|
|
62
63
|
scope.dom = void 0;
|
|
63
64
|
scope.needsDomUpdate = false;
|
|
65
|
+
scope.hydrationPending = false;
|
|
64
66
|
componentInstance.hasPendingUpdate = false;
|
|
65
67
|
};
|
|
66
68
|
componentInstance._pendingFlushTask = () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"child-scope.js","names":[],"sources":["../../src/runtime/child-scope.ts"],"sourcesContent":["import type { VNode } from '../common/vnode';\nimport { _isDOMElement } from '../common/vnode';\nimport {\n cleanupComponent,\n createComponentInstance,\n finalizeReadSubscriptions,\n getCurrentStateIndex,\n registerOwnedChildScope,\n renderScopedComponent,\n unregisterOwnedChildScope,\n type ComponentInstance,\n} from './component';\nimport { isDevelopmentEnvironment } from '../common/env';\n\nexport interface ChildScope {\n key: string | number;\n componentInstance: ComponentInstance;\n previousVnode: VNode | undefined;\n vnode: VNode | undefined;\n dom?: Node;\n needsDomUpdate: boolean;\n render(renderFn: () => VNode): VNode;\n markDirty(): void;\n dispose(): void;\n}\n\ninterface MutableChildScope extends ChildScope {\n _startStateIndex: number;\n _renderFn?: (() => VNode) | undefined;\n _onDirty?: (() => void) | undefined;\n _parent?: ComponentInstance | null;\n _disposed: boolean;\n}\n\nfunction renderScope(scope: MutableChildScope): VNode | undefined {\n if (scope._disposed) {\n if (isDevelopmentEnvironment()) {\n throw new Error(\n `[askr] Attempted to render disposed child scope ${String(scope.key)}.`\n );\n }\n return scope.vnode;\n }\n\n if (!scope._renderFn) {\n return scope.vnode;\n }\n\n const { componentInstance } = scope;\n const previousVNode = scope.vnode;\n\n try {\n const nextVNode = renderScopedComponent(\n componentInstance,\n scope._startStateIndex,\n scope._renderFn\n );\n if (\n previousVNode &&\n nextVNode &&\n _isDOMElement(previousVNode) &&\n _isDOMElement(nextVNode) &&\n typeof previousVNode.type === 'function' &&\n previousVNode.type === nextVNode.type &&\n '__instance' in previousVNode &&\n !('__instance' in nextVNode)\n ) {\n (\n nextVNode as VNode & {\n __instance?: ComponentInstance;\n }\n ).__instance = (\n previousVNode as VNode & {\n __instance?: ComponentInstance;\n }\n ).__instance;\n }\n scope.previousVnode = previousVNode;\n scope.vnode = nextVNode;\n scope.markDirty();\n finalizeReadSubscriptions(componentInstance);\n return scope.vnode;\n } catch (error) {\n componentInstance.hasPendingUpdate = false;\n throw error;\n }\n}\n\nexport function rerenderChildScope(scope: ChildScope): VNode | undefined {\n return renderScope(scope as MutableChildScope);\n}\n\nexport function disposeChildScope(scope: ChildScope): void {\n scope.dispose();\n}\n\nexport function createChildScope(\n parent: ComponentInstance | null,\n key: string | number,\n onDirty?: () => void\n): ChildScope {\n const scope = {} as MutableChildScope;\n\n const componentInstance = createComponentInstance(\n `child-scope-${String(key)}`,\n () => scope._renderFn?.() ?? null,\n {},\n null\n );\n\n if (parent) {\n componentInstance.ownerFrame = parent.ownerFrame;\n }\n\n scope.key = key;\n scope.componentInstance = componentInstance;\n scope.previousVnode = undefined;\n scope.vnode = undefined;\n scope.dom = undefined;\n scope.needsDomUpdate = true;\n scope._startStateIndex = getCurrentStateIndex();\n scope._renderFn = undefined;\n scope._onDirty = onDirty;\n scope._parent = parent;\n scope._disposed = false;\n scope.markDirty = () => {\n scope.needsDomUpdate = true;\n };\n scope.render = (renderFn: () => VNode) => {\n scope._renderFn = renderFn;\n return renderScope(scope) as VNode;\n };\n scope.dispose = () => {\n if (scope._disposed) {\n return;\n }\n scope._disposed = true;\n if (scope._parent) {\n unregisterOwnedChildScope(scope._parent, scope);\n }\n cleanupComponent(componentInstance);\n scope._renderFn = undefined;\n scope.previousVnode = undefined;\n scope.vnode = undefined;\n scope.dom = undefined;\n scope.needsDomUpdate = false;\n componentInstance.hasPendingUpdate = false;\n };\n\n componentInstance._pendingFlushTask = () => {\n componentInstance.hasPendingUpdate = false;\n renderScope(scope);\n scope._onDirty?.();\n };\n\n if (parent) {\n registerOwnedChildScope(parent, scope);\n }\n\n return scope;\n}\n"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"child-scope.js","names":[],"sources":["../../src/runtime/child-scope.ts"],"sourcesContent":["import type { VNode } from '../common/vnode';\nimport { _isDOMElement } from '../common/vnode';\nimport {\n cleanupComponent,\n createComponentInstance,\n finalizeReadSubscriptions,\n getCurrentStateIndex,\n registerOwnedChildScope,\n renderScopedComponent,\n unregisterOwnedChildScope,\n type ComponentInstance,\n} from './component';\nimport { isDevelopmentEnvironment } from '../common/env';\n\nexport interface ChildScope {\n key: string | number;\n componentInstance: ComponentInstance;\n previousVnode: VNode | undefined;\n vnode: VNode | undefined;\n dom?: Node;\n needsDomUpdate: boolean;\n hydrationPending: boolean;\n render(renderFn: () => VNode): VNode;\n markDirty(): void;\n dispose(): void;\n}\n\ninterface MutableChildScope extends ChildScope {\n _startStateIndex: number;\n _renderFn?: (() => VNode) | undefined;\n _onDirty?: (() => void) | undefined;\n _parent?: ComponentInstance | null;\n _disposed: boolean;\n}\n\nfunction renderScope(scope: MutableChildScope): VNode | undefined {\n if (scope._disposed) {\n if (isDevelopmentEnvironment()) {\n throw new Error(\n `[askr] Attempted to render disposed child scope ${String(scope.key)}.`\n );\n }\n return scope.vnode;\n }\n\n if (!scope._renderFn) {\n return scope.vnode;\n }\n\n const { componentInstance } = scope;\n const previousVNode = scope.vnode;\n\n try {\n const nextVNode = renderScopedComponent(\n componentInstance,\n scope._startStateIndex,\n scope._renderFn\n );\n if (\n previousVNode &&\n nextVNode &&\n _isDOMElement(previousVNode) &&\n _isDOMElement(nextVNode) &&\n typeof previousVNode.type === 'function' &&\n previousVNode.type === nextVNode.type &&\n '__instance' in previousVNode &&\n !('__instance' in nextVNode)\n ) {\n (\n nextVNode as VNode & {\n __instance?: ComponentInstance;\n }\n ).__instance = (\n previousVNode as VNode & {\n __instance?: ComponentInstance;\n }\n ).__instance;\n }\n scope.previousVnode = previousVNode;\n scope.vnode = nextVNode;\n scope.markDirty();\n finalizeReadSubscriptions(componentInstance);\n return scope.vnode;\n } catch (error) {\n componentInstance.hasPendingUpdate = false;\n throw error;\n }\n}\n\nexport function rerenderChildScope(scope: ChildScope): VNode | undefined {\n return renderScope(scope as MutableChildScope);\n}\n\nexport function disposeChildScope(scope: ChildScope): void {\n scope.dispose();\n}\n\nexport function createChildScope(\n parent: ComponentInstance | null,\n key: string | number,\n onDirty?: () => void\n): ChildScope {\n const scope = {} as MutableChildScope;\n\n const componentInstance = createComponentInstance(\n `child-scope-${String(key)}`,\n () => scope._renderFn?.() ?? null,\n {},\n null\n );\n\n if (parent) {\n componentInstance.ownerFrame = parent.ownerFrame;\n }\n\n scope.key = key;\n scope.componentInstance = componentInstance;\n scope.previousVnode = undefined;\n scope.vnode = undefined;\n scope.dom = undefined;\n scope.needsDomUpdate = true;\n scope.hydrationPending = true;\n scope._startStateIndex = getCurrentStateIndex();\n scope._renderFn = undefined;\n scope._onDirty = onDirty;\n scope._parent = parent;\n scope._disposed = false;\n scope.markDirty = () => {\n scope.needsDomUpdate = true;\n };\n scope.render = (renderFn: () => VNode) => {\n scope._renderFn = renderFn;\n return renderScope(scope) as VNode;\n };\n scope.dispose = () => {\n if (scope._disposed) {\n return;\n }\n scope._disposed = true;\n if (scope._parent) {\n unregisterOwnedChildScope(scope._parent, scope);\n }\n cleanupComponent(componentInstance);\n scope._renderFn = undefined;\n scope.previousVnode = undefined;\n scope.vnode = undefined;\n scope.dom = undefined;\n scope.needsDomUpdate = false;\n scope.hydrationPending = false;\n componentInstance.hasPendingUpdate = false;\n };\n\n componentInstance._pendingFlushTask = () => {\n componentInstance.hasPendingUpdate = false;\n renderScope(scope);\n scope._onDirty?.();\n };\n\n if (parent) {\n registerOwnedChildScope(parent, scope);\n }\n\n return scope;\n}\n"],"mappings":";;;;AAmCA,SAAS,YAAY,OAA6C;CAChE,IAAI,MAAM,WAAW;EACnB,IAAI,0BAA0B,EAC5B,MAAM,IAAI,MACR,mDAAmD,OAAO,MAAM,IAAI,CAAC,GACtE;EAEH,OAAO,MAAM;;CAGf,IAAI,CAAC,MAAM,WACT,OAAO,MAAM;CAGf,MAAM,EAAE,sBAAsB;CAC9B,MAAM,gBAAgB,MAAM;CAE5B,IAAI;EACF,MAAM,YAAY,sBAChB,mBACA,MAAM,kBACN,MAAM,UACP;EACD,IACE,iBACA,aACA,cAAc,cAAc,IAC5B,cAAc,UAAU,IACxB,OAAO,cAAc,SAAS,cAC9B,cAAc,SAAS,UAAU,QACjC,gBAAgB,iBAChB,EAAE,gBAAgB,YAElB,UAIE,aACA,cAGA;EAEJ,MAAM,gBAAgB;EACtB,MAAM,QAAQ;EACd,MAAM,WAAW;EACjB,0BAA0B,kBAAkB;EAC5C,OAAO,MAAM;UACN,OAAO;EACd,kBAAkB,mBAAmB;EACrC,MAAM;;;AAIV,SAAgB,mBAAmB,OAAsC;CACvE,OAAO,YAAY,MAA2B;;AAGhD,SAAgB,kBAAkB,OAAyB;CACzD,MAAM,SAAS;;AAGjB,SAAgB,iBACd,QACA,KACA,SACY;CACZ,MAAM,QAAQ,EAAE;CAEhB,MAAM,oBAAoB,wBACxB,eAAe,OAAO,IAAI,UACpB,MAAM,aAAa,IAAI,MAC7B,EAAE,EACF,KACD;CAED,IAAI,QACF,kBAAkB,aAAa,OAAO;CAGxC,MAAM,MAAM;CACZ,MAAM,oBAAoB;CAC1B,MAAM,gBAAgB;CACtB,MAAM,QAAQ;CACd,MAAM,MAAM;CACZ,MAAM,iBAAiB;CACvB,MAAM,mBAAmB;CACzB,MAAM,mBAAmB,sBAAsB;CAC/C,MAAM,YAAY;CAClB,MAAM,WAAW;CACjB,MAAM,UAAU;CAChB,MAAM,YAAY;CAClB,MAAM,kBAAkB;EACtB,MAAM,iBAAiB;;CAEzB,MAAM,UAAU,aAA0B;EACxC,MAAM,YAAY;EAClB,OAAO,YAAY,MAAM;;CAE3B,MAAM,gBAAgB;EACpB,IAAI,MAAM,WACR;EAEF,MAAM,YAAY;EAClB,IAAI,MAAM,SACR,0BAA0B,MAAM,SAAS,MAAM;EAEjD,iBAAiB,kBAAkB;EACnC,MAAM,YAAY;EAClB,MAAM,gBAAgB;EACtB,MAAM,QAAQ;EACd,MAAM,MAAM;EACZ,MAAM,iBAAiB;EACvB,MAAM,mBAAmB;EACzB,kBAAkB,mBAAmB;;CAGvC,kBAAkB,0BAA0B;EAC1C,kBAAkB,mBAAmB;EACrC,YAAY,MAAM;EAClB,MAAM,YAAY;;CAGpB,IAAI,QACF,wBAAwB,QAAQ,MAAM;CAGxC,OAAO"}
|
|
@@ -401,7 +401,7 @@ function claimHookIndex(instance, hookName) {
|
|
|
401
401
|
if (index < instance.stateIndexCheck) throw new Error(`Hook index violation: ${hookName}() call at index ${index}, but previously saw index ${instance.stateIndexCheck}. This happens when render-scoped hooks are called conditionally (inside if/for/etc). Move all ${hookName}() calls to the top level of your component function, before any conditionals.`);
|
|
402
402
|
instance.stateIndexCheck = index;
|
|
403
403
|
if (instance.firstRenderComplete) {
|
|
404
|
-
if (
|
|
404
|
+
if (instance.expectedStateIndices[index] !== index) throw new Error(`Hook order violation: ${hookName}() called at index ${index}, but this index was not in the first render's sequence [${instance.expectedStateIndices.join(", ")}]. This usually means ${hookName}() is inside a conditional or loop. Move all render-scoped hooks to the top level of your component function.`);
|
|
405
405
|
} else instance.expectedStateIndices.push(index);
|
|
406
406
|
return index;
|
|
407
407
|
}
|
|
@@ -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 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;EAC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O,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[index] !== index) {\n throw new Error(\n `Hook order violation: ${hookName}() called at index ${index}, ` +\n `but this index was not in the first render's sequence [${instance.expectedStateIndices.join(', ')}]. ` +\n `This usually means ${hookName}() is inside a conditional or loop. ` +\n `Move all render-scoped hooks to the top level of your component function.`\n );\n }\n } else {\n instance.expectedStateIndices.push(index);\n }\n\n return index;\n}\n\nexport function getCurrentStateIndex(): number {\n return stateIndex;\n}\n\nexport function resetStateIndex(): void {\n stateIndex = 0;\n}\n\nexport function setStateIndex(value: number): void {\n stateIndex = value;\n}\n\n/**\n * Mount a component instance.\n * This is just an alias to executeComponent() to maintain API compatibility.\n * All lifecycle logic is unified in executeComponent().\n */\nexport function mountComponent(instance: ComponentInstance): void {\n executeComponent(instance);\n}\n\n/**\n * Clean up component — abort pending operations\n * Called on unmount or route change\n */\nexport function cleanupComponent(instance: ComponentInstance): void {\n const 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);\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