@askrjs/askr 0.0.49 → 0.0.51
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-table.js.map +1 -1
- package/dist/benchmark.js +5 -4
- package/dist/benchmark.js.map +1 -1
- package/dist/bin/askr-ssg.d.ts.map +1 -1
- package/dist/bin/askr-ssg.js.map +1 -1
- package/dist/boot/hydration.js.map +1 -1
- package/dist/boot/index.js +2 -1
- package/dist/boot/index.js.map +1 -1
- package/dist/boot/root-lifecycle.d.ts.map +1 -1
- package/dist/boot/root-lifecycle.js +4 -4
- package/dist/boot/root-lifecycle.js.map +1 -1
- package/dist/boot/route-startup.js.map +1 -1
- package/dist/common/error-boundary.d.ts +16 -0
- package/dist/common/error-boundary.d.ts.map +1 -0
- package/dist/common/invariant.js +17 -0
- package/dist/common/invariant.js.map +1 -0
- package/dist/common/jsx.d.ts +6 -2
- package/dist/common/jsx.d.ts.map +1 -1
- package/dist/common/jsx.js.map +1 -1
- package/dist/{dev → common}/logger.js +5 -6
- package/dist/common/logger.js.map +1 -0
- package/dist/common/vnode.d.ts +2 -2
- package/dist/common/vnode.d.ts.map +1 -1
- package/dist/common/vnode.js.map +1 -1
- package/dist/components/error-boundary.d.ts +2 -15
- package/dist/components/error-boundary.d.ts.map +1 -1
- package/dist/components/error-boundary.js +2 -74
- package/dist/components/error-boundary.js.map +1 -1
- package/dist/components/index.d.ts +2 -1
- package/dist/components/link.js +2 -0
- package/dist/components/link.js.map +1 -1
- package/dist/control/case.d.ts.map +1 -1
- package/dist/control/case.js +1 -0
- package/dist/control/case.js.map +1 -1
- package/dist/control/for.d.ts +3 -3
- package/dist/control/for.d.ts.map +1 -1
- package/dist/control/for.js +2 -2
- package/dist/control/for.js.map +1 -1
- package/dist/control/show.js +1 -0
- package/dist/control/show.js.map +1 -1
- package/dist/data/data-runtime.js.map +1 -1
- package/dist/data/invalidation.js +2 -2
- package/dist/data/invalidation.js.map +1 -1
- package/dist/data/mutation-cell.d.ts.map +1 -1
- package/dist/data/mutation-cell.js +1 -1
- package/dist/data/mutation-cell.js.map +1 -1
- package/dist/data/query-cell.js +2 -2
- package/dist/data/query-cell.js.map +1 -1
- package/dist/data/shared.js +1 -0
- package/dist/data/shared.js.map +1 -1
- package/dist/data/testing.js +2 -0
- package/dist/foundations/index.d.ts +1 -1
- package/dist/foundations/index.js +1 -1
- package/dist/foundations/state/controllable.d.ts +0 -1
- package/dist/foundations/state/controllable.d.ts.map +1 -1
- package/dist/foundations/state/controllable.js +1 -0
- package/dist/foundations/state/controllable.js.map +1 -1
- package/dist/foundations/structures/index.d.ts +1 -1
- package/dist/foundations/structures/index.js +2 -1
- package/dist/foundations/structures/portal.d.ts +2 -24
- package/dist/foundations/structures/portal.js +3 -187
- package/dist/fx/fx.js +2 -2
- package/dist/fx/fx.js.map +1 -1
- package/dist/fx/index.js +1 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/jsx/index.d.ts +1 -1
- package/dist/jsx/types.d.ts +2 -2
- package/dist/jsx-dev-runtime.d.ts +2 -2
- package/dist/jsx-dev-runtime.d.ts.map +1 -1
- package/dist/jsx-dev-runtime.js +1 -0
- package/dist/jsx-dev-runtime.js.map +1 -1
- package/dist/jsx-runtime.d.ts +2 -2
- package/dist/jsx-runtime.d.ts.map +1 -1
- package/dist/jsx-runtime.js +1 -0
- package/dist/jsx-runtime.js.map +1 -1
- package/dist/jsx-runtime2.d.ts +1 -1
- package/dist/renderer/attributes.js +1 -0
- package/dist/renderer/attributes.js.map +1 -1
- package/dist/renderer/boundaries.js +5 -5
- package/dist/renderer/boundaries.js.map +1 -1
- package/dist/renderer/child-shape.js +2 -2
- package/dist/renderer/child-shape.js.map +1 -1
- package/dist/renderer/children-fastpath.js +149 -0
- package/dist/renderer/children-fastpath.js.map +1 -0
- package/dist/renderer/children.js +3 -138
- package/dist/renderer/children.js.map +1 -1
- package/dist/renderer/cleanup.js +2 -2
- package/dist/renderer/cleanup.js.map +1 -1
- package/dist/renderer/component-host-cleanup.js +1 -1
- package/dist/renderer/component-host-cleanup.js.map +1 -1
- package/dist/renderer/component-host-instances.js +1 -1
- package/dist/renderer/component-host-instances.js.map +1 -1
- package/dist/renderer/component-host.js +1 -1
- package/dist/renderer/component-host.js.map +1 -1
- package/dist/renderer/dom-host.js.map +1 -1
- package/dist/renderer/dom-internal.js +5 -4
- package/dist/renderer/dom-internal.js.map +1 -1
- package/dist/renderer/dom.js +2 -1
- package/dist/renderer/element-children.js.map +1 -1
- package/dist/renderer/error-boundary-dom.js +51 -2
- package/dist/renderer/error-boundary-dom.js.map +1 -1
- package/dist/renderer/evaluate-reconcile.js +6 -5
- package/dist/renderer/evaluate-reconcile.js.map +1 -1
- package/dist/renderer/evaluate.js.map +1 -1
- package/dist/renderer/fastpath.js +3 -2
- package/dist/renderer/fastpath.js.map +1 -1
- package/dist/renderer/for-commit-dom-map.js.map +1 -1
- package/dist/renderer/for-commit-removal.js +2 -2
- package/dist/renderer/for-commit-removal.js.map +1 -1
- package/dist/renderer/for-commit-reorder.js +2 -2
- package/dist/renderer/for-commit-reorder.js.map +1 -1
- package/dist/renderer/for-commit.js +3 -3
- package/dist/renderer/for-commit.js.map +1 -1
- package/dist/renderer/index.js +3 -1
- package/dist/renderer/index.js.map +1 -1
- package/dist/renderer/prop-bindings.js +4 -4
- package/dist/renderer/prop-bindings.js.map +1 -1
- package/dist/renderer/reactive-child-dom.js.map +1 -1
- package/dist/renderer/reactive-children.js +4 -4
- package/dist/renderer/reactive-children.js.map +1 -1
- package/dist/renderer/reconcile-fastpaths.js +2 -1
- package/dist/renderer/reconcile-fastpaths.js.map +1 -1
- package/dist/renderer/reconcile-resolution.js +3 -3
- package/dist/renderer/reconcile-resolution.js.map +1 -1
- package/dist/renderer/retained-element-rollback.js +2 -1
- package/dist/renderer/retained-element-rollback.js.map +1 -1
- package/dist/renderer/stable-patch.js +2 -3
- package/dist/renderer/stable-patch.js.map +1 -1
- package/dist/renderer/utils.js +2 -1
- package/dist/renderer/utils.js.map +1 -1
- package/dist/resources/index.js +1 -2
- package/dist/router/activity.d.ts.map +1 -1
- package/dist/router/activity.js +20 -22
- package/dist/router/activity.js.map +1 -1
- package/dist/router/authoring.js +1 -1
- package/dist/router/authoring.js.map +1 -1
- package/dist/router/index.d.ts +1 -1
- package/dist/router/navigate.js +1 -1
- package/dist/router/navigate.js.map +1 -1
- package/dist/router/navigation-registry.js +1 -1
- package/dist/router/navigation-registry.js.map +1 -1
- package/dist/router/navigation-targets.d.ts.map +1 -1
- package/dist/router/navigation-targets.js +7 -5
- package/dist/router/navigation-targets.js.map +1 -1
- package/dist/router/rendering.js +1 -0
- package/dist/router/rendering.js.map +1 -1
- package/dist/router/resolution.d.ts +1 -14
- package/dist/router/resolution.d.ts.map +1 -1
- package/dist/router/resolution.js +6 -173
- package/dist/router/resolution.js.map +1 -1
- package/dist/router/route-matching.d.ts +20 -0
- package/dist/router/route-matching.d.ts.map +1 -0
- package/dist/router/route-matching.js +175 -0
- package/dist/router/route-matching.js.map +1 -0
- package/dist/router/route.js +4 -2
- package/dist/router/testing.js +4 -0
- package/dist/runtime/access.d.ts +20 -0
- package/dist/runtime/access.d.ts.map +1 -0
- package/dist/runtime/component-cleanup.js +1 -1
- package/dist/runtime/component-cleanup.js.map +1 -1
- package/dist/runtime/component-commit.js +1 -1
- package/dist/runtime/component-commit.js.map +1 -1
- package/dist/runtime/component-internal.d.ts +1 -1
- package/dist/runtime/component-internal.js +1 -1
- package/dist/runtime/component-internal.js.map +1 -1
- package/dist/runtime/component-lifecycle.d.ts +1 -1
- package/dist/runtime/component-lifecycle.js +1 -1
- package/dist/runtime/component-lifecycle.js.map +1 -1
- package/dist/runtime/component-scope.d.ts +1 -1
- package/dist/runtime/dev-namespace.d.ts +31 -0
- package/dist/runtime/dev-namespace.d.ts.map +1 -0
- package/dist/runtime/error-boundary.d.ts +5 -0
- package/dist/runtime/error-boundary.d.ts.map +1 -0
- package/dist/runtime/error-boundary.js +31 -0
- package/dist/runtime/error-boundary.js.map +1 -0
- package/dist/runtime/events.d.ts +58 -0
- package/dist/runtime/events.d.ts.map +1 -0
- package/dist/runtime/events.js +1 -1
- package/dist/runtime/events.js.map +1 -1
- package/dist/runtime/execution-model.d.ts +7 -0
- package/dist/runtime/execution-model.d.ts.map +1 -0
- package/dist/runtime/fastlane.d.ts +34 -0
- package/dist/runtime/fastlane.d.ts.map +1 -0
- package/dist/runtime/for-internal.d.ts +5 -5
- package/dist/runtime/for-internal.d.ts.map +1 -1
- package/dist/runtime/for-internal.js.map +1 -1
- package/dist/runtime/for-signals.d.ts +1 -1
- package/dist/runtime/for-signals.d.ts.map +1 -1
- package/dist/runtime/for-signals.js +1 -1
- package/dist/runtime/for-signals.js.map +1 -1
- package/dist/runtime/for-types.d.ts +9 -0
- package/dist/runtime/for-types.d.ts.map +1 -0
- package/dist/runtime/index.d.ts +24 -0
- package/dist/runtime/index.js +31 -0
- package/dist/runtime/perf-metrics.d.ts +26 -0
- package/dist/runtime/perf-metrics.d.ts.map +1 -0
- package/dist/runtime/portal.d.ts +22 -0
- package/dist/runtime/portal.d.ts.map +1 -0
- package/dist/runtime/portal.js +213 -0
- package/dist/runtime/portal.js.map +1 -0
- package/dist/runtime/resource-cell.js +1 -1
- package/dist/runtime/resource-cell.js.map +1 -1
- package/dist/runtime/resource-operation.js +1 -1
- package/dist/runtime/runtime.d.ts +1 -1
- package/dist/runtime/scheduler.js +2 -2
- package/dist/runtime/scheduler.js.map +1 -1
- package/dist/runtime/selector-store.js +24 -0
- package/dist/runtime/selector-store.js.map +1 -0
- package/dist/runtime/selector.d.ts.map +1 -1
- package/dist/runtime/selector.js +3 -18
- package/dist/runtime/selector.js.map +1 -1
- package/dist/ssg/create-static-gen.js +1 -0
- package/dist/ssg/create-static-gen.js.map +1 -1
- package/dist/ssg/static-routes.js +1 -0
- package/dist/ssg/static-routes.js.map +1 -1
- package/dist/ssr/boundaries.js +2 -2
- package/dist/ssr/boundaries.js.map +1 -1
- package/dist/ssr/component-runtime.js +3 -3
- package/dist/ssr/component-runtime.js.map +1 -1
- package/dist/ssr/render-resolved.js +1 -1
- package/dist/ssr/render-sync.js +1 -1
- package/dist/ssr/render-sync.js.map +1 -1
- package/dist/ssr/route-policy-resolution.js +2 -1
- package/dist/ssr/route-policy-resolution.js.map +1 -1
- package/dist/ssr/route-render.js +2 -1
- package/dist/ssr/route-render.js.map +1 -1
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +3 -2
- package/dist/testing/index.js.map +1 -1
- package/package.json +4 -4
- package/dist/dev/invariant.js +0 -29
- package/dist/dev/invariant.js.map +0 -1
- package/dist/dev/logger.js.map +0 -1
- package/dist/foundations/structures/portal.d.ts.map +0 -1
- package/dist/foundations/structures/portal.js.map +0 -1
- package/dist/runtime/component-contracts.js +0 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stable-patch.js","names":[],"sources":["../../src/renderer/stable-patch.ts"],"sourcesContent":["import { isPromiseLike } from '../common/promise';\nimport {\n captureInlineRenderSnapshot,\n getCurrentInstance,\n renderComponentInline,\n warnUnusedStateReads,\n type ComponentFunction,\n} from '../runtime
|
|
1
|
+
{"version":3,"file":"stable-patch.js","names":[],"sources":["../../src/renderer/stable-patch.ts"],"sourcesContent":["import { isPromiseLike } from '../common/promise';\nimport {\n captureInlineRenderSnapshot,\n getCurrentInstance,\n renderComponentInline,\n warnUnusedStateReads,\n type ComponentFunction,\n} from '../runtime';\nimport {\n getCurrentContextFrame,\n getVNodeContextFrame,\n withContext,\n} from '../runtime';\nimport { incDevCounter } from '../runtime';\nimport { recordBenchEvent } from '../runtime';\nimport {\n findHostInstanceByType,\n inheritComponentCleanupStrict,\n inheritComponentKey,\n isRouteRootComponentVNode,\n resolveNestedComponentResult,\n} from './component-host';\nimport { getRendererDOMHost, type InstanceHostElement } from './dom-host';\nimport { _isDOMElement, type DOMElement, type VNode } from './types';\nimport { tagNamesEqualIgnoreCase } from './utils';\n\nfunction normalizeStableIntrinsicChildren(\n children: VNode | VNode[] | undefined\n): VNode[] {\n if (children === null || children === undefined || children === false) {\n return [];\n }\n\n return Array.isArray(children) ? children : [children];\n}\n\nfunction getStableIntrinsicChildren(vnode: DOMElement): VNode[] {\n return normalizeStableIntrinsicChildren(\n (vnode.props?.children as VNode | VNode[] | undefined) ?? vnode.children\n );\n}\n\nfunction patchStableIntrinsicText(domNode: Node, nextVNode: VNode): boolean {\n if (\n domNode.nodeType !== 3 ||\n (typeof nextVNode !== 'string' && typeof nextVNode !== 'number')\n ) {\n return false;\n }\n\n const nextText = String(nextVNode);\n const textNode = domNode as Text;\n if (textNode.data !== nextText) {\n recordBenchEvent('domTextSet');\n textNode.data = nextText;\n }\n\n return true;\n}\n\nfunction patchStableIntrinsicElement(\n dom: Element,\n nextVNode: DOMElement\n): boolean {\n if (\n typeof nextVNode.type !== 'string' ||\n !tagNamesEqualIgnoreCase(dom.tagName, nextVNode.type)\n ) {\n return false;\n }\n\n getRendererDOMHost().updateElementFromVnode(dom, nextVNode, false);\n\n const nextChildren = getStableIntrinsicChildren(nextVNode);\n if (dom.childNodes.length !== nextChildren.length) {\n return false;\n }\n\n for (let index = 0; index < nextChildren.length; index += 1) {\n const nextChild = nextChildren[index];\n\n const currentChildNode = dom.childNodes[index];\n if (!currentChildNode) {\n return false;\n }\n\n if (patchStableIntrinsicText(currentChildNode, nextChild)) {\n continue;\n }\n\n if (\n currentChildNode instanceof Element &&\n _isDOMElement(nextChild) &&\n typeof nextChild.type === 'string' &&\n patchStableIntrinsicElement(currentChildNode, nextChild)\n ) {\n continue;\n }\n\n return false;\n }\n\n return true;\n}\n\nfunction resolveStableIntrinsicPatchVNode(\n dom: Element,\n vnode: VNode\n): DOMElement | null {\n if (!_isDOMElement(vnode)) {\n return null;\n }\n\n if (typeof vnode.type === 'string') {\n return tagNamesEqualIgnoreCase(dom.tagName, vnode.type) ? vnode : null;\n }\n\n if (typeof vnode.type !== 'function') {\n return null;\n }\n\n const host = dom as InstanceHostElement;\n const existingInstance = findHostInstanceByType(\n host,\n vnode.type as ComponentFunction\n );\n if (\n !existingInstance ||\n existingInstance.fn !== vnode.type ||\n host.__ASKR_WRAPPER_HOST\n ) {\n return null;\n }\n\n const snapshot =\n getVNodeContextFrame(vnode) ||\n getCurrentContextFrame() ||\n existingInstance.ownerFrame ||\n null;\n\n captureInlineRenderSnapshot(existingInstance);\n\n existingInstance.props =\n (((vnode as DOMElement).props ?? {}) as Record<string, unknown>) || {};\n existingInstance.isRoot = isRouteRootComponentVNode(vnode);\n existingInstance.portalScope =\n getCurrentInstance()?.portalScope ?? existingInstance.portalScope;\n inheritComponentCleanupStrict(existingInstance);\n\n if (snapshot) {\n existingInstance.ownerFrame = snapshot;\n }\n\n const result = withContext(snapshot, () =>\n renderComponentInline(existingInstance)\n );\n if (isPromiseLike(result)) {\n throw new Error(\n 'Async components are not supported. Components must return synchronously.'\n );\n }\n\n const resolvedResult = resolveNestedComponentResult(\n result,\n snapshot ?? null,\n existingInstance\n );\n if (\n _isDOMElement(resolvedResult) &&\n typeof resolvedResult.type === 'string' &&\n tagNamesEqualIgnoreCase(dom.tagName, resolvedResult.type)\n ) {\n return inheritComponentKey(resolvedResult, vnode as DOMElement);\n }\n\n return null;\n}\n\nexport function tryPatchStableForDirtyItem(scope: {\n dom?: Node;\n vnode?: VNode;\n}): boolean {\n incDevCounter('stableForPatchAttempt');\n if (!(scope.dom instanceof Element) || scope.vnode === undefined) {\n return false;\n }\n\n const nextIntrinsic = resolveStableIntrinsicPatchVNode(\n scope.dom,\n scope.vnode\n );\n if (!nextIntrinsic) {\n return false;\n }\n\n const didPatch = patchStableIntrinsicElement(scope.dom, nextIntrinsic);\n\n const existingInstance = (scope.dom as InstanceHostElement).__ASKR_INSTANCE;\n if (didPatch && existingInstance) {\n warnUnusedStateReads(existingInstance);\n }\n\n if (didPatch) {\n incDevCounter('stableForPatchHit');\n }\n\n return didPatch;\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|
-
import { logger } from "../
|
|
2
|
+
import { logger } from "../common/logger.js";
|
|
3
3
|
import { runRuntimeHandlerScope } from "../runtime/access.js";
|
|
4
4
|
import { incDevCounter, setDevValue } from "../runtime/dev-namespace.js";
|
|
5
|
+
import "../runtime/index.js";
|
|
5
6
|
import { getPublicAttributeName } from "../common/attr-names.js";
|
|
6
7
|
import "./env.js";
|
|
7
8
|
//#region src/renderer/utils.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":[],"sources":["../../src/renderer/utils.ts"],"sourcesContent":["/**\n * Shared utilities for the renderer module.\n * Consolidates common patterns to reduce code duplication.\n */\n\nimport { runRuntimeHandlerScope } from '../runtime/access';\nimport { logger } from '../dev/logger';\nimport { getPublicAttributeName } from '../common/attr-names';\nimport { getRuntimeEnv } from './env';\nimport { setDevValue, incDevCounter } from '../runtime/dev-namespace';\n\nconst SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n\n// Keep direct replaceChildren(...nodes) commits below a conservative argument\n// count until browser benchmarks prove larger spreads are safe.\nexport const DIRECT_REPLACE_CHILDREN_SPREAD_LIMIT = 4096;\n\nexport function canUseDirectReplaceChildrenSpread(count: number): boolean {\n return count <= DIRECT_REPLACE_CHILDREN_SPREAD_LIMIT;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Types\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface ListenerEntry {\n handler: EventListener;\n original: EventListener;\n eventName: string;\n options?: boolean | AddEventListenerOptions;\n updateHandler?: (nextHandler: EventListener) => void;\n}\n\nexport interface ParsedEventProp {\n eventName: string;\n capture: boolean;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Event Handler Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n// Handler pooling cache to avoid recreating wrapped handlers\n// Key: handler reference, Value: { wrapped: EventListener, flushAfter: boolean }\nconst handlerCache = new WeakMap<EventListener, Map<boolean, EventListener>>();\nlet cacheSize = 0;\nconst MAX_CACHE_SIZE = 1000;\n\n/**\n * Parse an event prop name (e.g., 'onClick') to its DOM event name (e.g., 'click')\n */\nexport function parseEventName(propName: string): string | null {\n return parseEventProp(propName)?.eventName ?? null;\n}\n\nexport function parseEventProp(propName: string): ParsedEventProp | null {\n if (!propName.startsWith('on') || propName.length <= 2) return null;\n const capture =\n propName.endsWith('Capture') && propName.length > 'onCapture'.length;\n const normalizedPropName = capture\n ? propName.slice(0, -'Capture'.length)\n : propName;\n\n return normalizedPropName.length <= 2\n ? null\n : {\n eventName:\n normalizedPropName.slice(2).charAt(0).toLowerCase() +\n normalizedPropName.slice(3).toLowerCase(),\n capture,\n };\n}\n\nexport function getEventListenerKey(\n eventName: string,\n capture = false\n): string {\n return capture ? `${eventName}:capture` : eventName;\n}\n\nexport function getEventListenerOptions(\n eventName: string,\n capture = false\n): AddEventListenerOptions | undefined {\n const passiveOptions = getPassiveOptions(eventName);\n if (!capture) {\n return passiveOptions;\n }\n\n return passiveOptions\n ? { ...passiveOptions, capture: true }\n : { capture: true };\n}\n\n/**\n * Get default event listener options for passive events\n */\nexport function getPassiveOptions(\n eventName: string\n): AddEventListenerOptions | undefined {\n if (\n eventName === 'wheel' ||\n eventName === 'scroll' ||\n eventName.startsWith('touch')\n ) {\n return { passive: true };\n }\n return undefined;\n}\n\n/**\n * Create a wrapped event handler that integrates with the scheduler\n * Uses caching to avoid recreating wrappers for the same handler\n */\nexport function createWrappedHandler(\n handler: EventListener,\n flushAfter = false\n): EventListener {\n // Check cache first\n const cachedByFlush = handlerCache.get(handler);\n if (cachedByFlush) {\n const cached = cachedByFlush.get(flushAfter);\n if (cached) return cached;\n }\n\n const wrapped: EventListener = (event: Event) => {\n try {\n runRuntimeHandlerScope(\n () => {\n try {\n handler(event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n }\n },\n flushAfter ? 'sync' : 'defer'\n );\n } catch (err) {\n if (flushAfter) {\n queueMicrotask(() => {\n throw err;\n });\n } else {\n logger.error('[Askr] Event handler error:', err);\n }\n }\n };\n\n // Cache the wrapped handler\n try {\n if (!handlerCache.has(handler)) {\n // Limit cache size to prevent memory leaks\n if (cacheSize >= MAX_CACHE_SIZE) {\n // Simple eviction - just don't cache new entries when full\n } else {\n cacheSize++;\n handlerCache.set(handler, new Map());\n }\n }\n handlerCache.get(handler)?.set(flushAfter, wrapped);\n } catch {\n // WeakMap can throw if handler is not a valid key\n }\n\n return wrapped;\n}\n\nexport function createMutableWrappedHandler(\n handler: EventListener,\n flushAfter = false\n): {\n handler: EventListener;\n updateHandler: (nextHandler: EventListener) => void;\n} {\n let currentHandler = handler;\n\n const wrapped: EventListener = (event: Event) => {\n try {\n runRuntimeHandlerScope(\n () => {\n try {\n currentHandler(event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n }\n },\n flushAfter ? 'sync' : 'defer'\n );\n } catch (err) {\n if (flushAfter) {\n queueMicrotask(() => {\n throw err;\n });\n } else {\n logger.error('[Askr] Event handler error:', err);\n }\n }\n };\n\n return {\n handler: wrapped,\n updateHandler(nextHandler: EventListener) {\n currentHandler = nextHandler;\n },\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Prop/Attribute Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Props that should be skipped during attribute processing */\nexport function isSkippedProp(key: string): boolean {\n return key === 'children' || key === 'key' || key === 'ref';\n}\n\n/** Check if prop should be ignored for prop-change detection */\nexport function isIgnoredForPropChanges(key: string): boolean {\n if (key === 'children' || key === 'key') return true;\n if (key.startsWith('on') && key.length > 2) return true;\n if (key.startsWith('data-')) return true;\n return false;\n}\n\n/**\n * Check if an element's current attribute value differs from vnode value\n */\nexport function hasPropChanged(\n el: Element,\n key: string,\n value: unknown\n): boolean {\n try {\n if (key === 'class' || key === 'className') {\n return readElementClassName(el) !== String(value);\n }\n if (key === 'value' || key === 'checked') {\n return (el as HTMLElement & Record<string, unknown>)[key] !== value;\n }\n const attr = el.getAttribute(getRenderedAttributeName(el, key));\n if (value === undefined || value === null || value === false) {\n return attr !== null;\n }\n return String(value) !== attr;\n } catch {\n return true;\n }\n}\n\nexport function isSVGDomElement(el: Element): el is SVGElement {\n return typeof SVGElement !== 'undefined' && el instanceof SVGElement;\n}\n\nexport function getRenderedAttributeName(\n el: Element,\n propName: string\n): string {\n const attributeName = getPublicAttributeName(propName);\n\n return el.namespaceURI === SVG_NAMESPACE\n ? attributeName\n : attributeName.toLowerCase();\n}\n\nexport function setRenderedAttribute(\n el: Element,\n propName: string,\n value: string\n): void {\n el.setAttribute(getRenderedAttributeName(el, propName), value);\n}\n\nexport function removeRenderedAttribute(el: Element, propName: string): void {\n el.removeAttribute(getRenderedAttributeName(el, propName));\n}\n\nexport function readElementClassName(el: Element): string {\n if (isSVGDomElement(el)) {\n return el.getAttribute('class') ?? '';\n }\n\n return (el as HTMLElement).className;\n}\n\nexport function writeElementClassName(el: Element, value: string): void {\n if (isSVGDomElement(el)) {\n if (value.length > 0) {\n el.setAttribute('class', value);\n } else {\n el.removeAttribute('class');\n }\n return;\n }\n\n (el as HTMLElement).className = value;\n}\n\nexport function tagNamesEqualIgnoreCase(a: string, b: string): boolean {\n if (a === b) return true;\n if (a.length !== b.length) return false;\n\n for (let index = 0; index < a.length; index += 1) {\n const aCode = a.charCodeAt(index);\n const bCode = b.charCodeAt(index);\n if (aCode === bCode) continue;\n\n const normalizedA = aCode >= 65 && aCode <= 90 ? aCode + 32 : aCode;\n const normalizedB = bCode >= 65 && bCode <= 90 ? bCode + 32 : bCode;\n if (normalizedA !== normalizedB) return false;\n }\n\n return true;\n}\n\n/**\n * Check if a vnode has non-trivial props (excluding events and data-*)\n */\nexport function hasNonTrivialProps(props: Record<string, unknown>): boolean {\n for (const k of Object.keys(props)) {\n if (isIgnoredForPropChanges(k)) continue;\n return true;\n }\n return false;\n}\n\n/**\n * Check for prop changes between vnode and existing element\n */\nexport function checkPropChanges(\n el: Element,\n props: Record<string, unknown>\n): boolean {\n for (const k of Object.keys(props)) {\n if (isIgnoredForPropChanges(k)) continue;\n if (hasPropChanged(el, k, props[k])) {\n return true;\n }\n }\n return false;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Key Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Extract key from a vnode object\n */\nexport function extractKey(vnode: unknown): string | number | undefined {\n if (typeof vnode !== 'object' || vnode === null) return undefined;\n const obj = vnode as Record<string, unknown>;\n const rawKey =\n obj.key ?? (obj.props as Record<string, unknown> | undefined)?.key;\n if (rawKey === undefined || rawKey === null) return undefined;\n return typeof rawKey === 'symbol'\n ? String(rawKey)\n : (rawKey as string | number);\n}\n\n/**\n * Build a key map from element's children\n */\nexport function buildKeyMapFromChildren(\n parent: Element\n): Map<string | number, Element> {\n const map = new Map<string | number, Element>();\n for (let ch = parent.firstElementChild; ch; ch = ch.nextElementSibling) {\n const k = ch.getAttribute('data-key');\n if (k !== null) {\n map.set(k, ch);\n const n = Number(k);\n if (!Number.isNaN(n)) map.set(n, ch);\n }\n }\n return map;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Diagnostic Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Record DOM replace operation for diagnostics\n */\nexport function recordDOMReplace(source: string): void {\n try {\n incDevCounter('__DOM_REPLACE_COUNT');\n setDevValue(`__LAST_DOM_REPLACE_STACK_${source}`, new Error().stack);\n } catch {\n // ignore\n }\n}\n\n/**\n * Record fast-path stats for diagnostics\n */\nexport function recordFastPathStats(\n stats: Record<string, unknown>,\n counterName?: string\n): void {\n try {\n setDevValue('__LAST_FASTPATH_STATS', stats);\n setDevValue('__LAST_FASTPATH_COMMIT_COUNT', 1);\n if (counterName) {\n incDevCounter(counterName);\n }\n } catch {\n // ignore\n }\n}\n\n/**\n * Conditionally log debug info for fast-path operations\n */\nexport function logFastPathDebug(\n message: string,\n indexOrData?: number | unknown,\n data?: unknown\n): void {\n const env = getRuntimeEnv();\n if (env.ASKR_FASTPATH_DEBUG === '1' || env.ASKR_FASTPATH_DEBUG === 'true') {\n if (data !== undefined) {\n logger.warn(`[Askr][FASTPATH] ${message}`, indexOrData, data);\n } else if (indexOrData !== undefined) {\n logger.warn(`[Askr][FASTPATH] ${message}`, indexOrData);\n } else {\n logger.warn(`[Askr][FASTPATH] ${message}`);\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Performance Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get current high-resolution timestamp\n */\nexport function now(): number {\n return typeof performance !== 'undefined' && performance.now\n ? performance.now()\n : Date.now();\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,gBAAgB;AAItB,MAAa,uCAAuC;AAEpD,SAAgB,kCAAkC,OAAwB;CACxE,OAAO,SAAS;AAClB;AAyBA,MAAM,+BAAe,IAAI,QAAoD;AAC7E,IAAI,YAAY;AAChB,MAAM,iBAAiB;;;;AAKvB,SAAgB,eAAe,UAAiC;CAC9D,OAAO,eAAe,QAAQ,CAAC,EAAE,aAAa;AAChD;AAEA,SAAgB,eAAe,UAA0C;CACvE,IAAI,CAAC,SAAS,WAAW,IAAI,KAAK,SAAS,UAAU,GAAG,OAAO;CAC/D,MAAM,UACJ,SAAS,SAAS,SAAS,KAAK,SAAS,SAAS;CACpD,MAAM,qBAAqB,UACvB,SAAS,MAAM,GAAG,EAAiB,IACnC;CAEJ,OAAO,mBAAmB,UAAU,IAChC,OACA;EACE,WACE,mBAAmB,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,YAAY,IAClD,mBAAmB,MAAM,CAAC,CAAC,CAAC,YAAY;EAC1C;CACF;AACN;AAEA,SAAgB,oBACd,WACA,UAAU,OACF;CACR,OAAO,UAAU,GAAG,UAAU,YAAY;AAC5C;AAEA,SAAgB,wBACd,WACA,UAAU,OAC2B;CACrC,MAAM,iBAAiB,kBAAkB,SAAS;CAClD,IAAI,CAAC,SACH,OAAO;CAGT,OAAO,iBACH;EAAE,GAAG;EAAgB,SAAS;CAAK,IACnC,EAA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;GACd,IAAI,IAAI,GAAG,EAAE;GACb,MAAM,IAAI,OAAO,CAAC;GAClB,IAAI,CAAC,OAAO,MAAM,CAAC,GAAG,IAAI,IAAI,GAAG,EAAE;EACrC;CACF;CACA,OAAO;AACT;;;;AASA,SAAgB,iBAAiB,QAAsB;CACrD,IAAI;EACF,cAAc,qBAAqB;EACnC,YAAY,4BAA4B,2BAAU,IAAI,MAAM,EAAC,CAAC,KAAK;CACrE,QAAQ,CAER;AACF;;;;AAKA,SAAgB,oBACd,OACA,aACM;CACN,IAAI;EACF,YAAY,yBAAyB,KAAK;EAC1C,YAAY,gCAAgC,CAAC;EAC7C,IAAI,aACF,cAAc,WAAW;CAE7B,QAAQ,CAER;AACF;;;;AAKA,SAAgB,iBACd,SACA,aACA,MACM;CACN,MAAM,MAAM,cAAc;CAC1B,IAAI,IAAI,wBAAwB,OAAO,IAAI,wBAAwB,QACjE,IAAI,SAAS,QACX,OAAO,KAAK,oBAAoB,WAAW,aAAa,IAAI;MACvD,IAAI,gBAAgB,QACzB,OAAO,KAAK,oBAAoB,WAAW,WAAW;MAEtD,OAAO,KAAK,oBAAoB,SAAS;AAG/C;;;;AASA,SAAgB,MAAc;CAC5B,OAAO,OAAO,gBAAgB,eAAe,YAAY,MACrD,YAAY,IAAI,IAChB,KAAK,IAAI;AACf"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../../src/renderer/utils.ts"],"sourcesContent":["/**\n * Shared utilities for the renderer module.\n * Consolidates common patterns to reduce code duplication.\n */\n\nimport { runRuntimeHandlerScope } from '../runtime';\nimport { logger } from '../common/logger';\nimport { getPublicAttributeName } from '../common/attr-names';\nimport { getRuntimeEnv } from './env';\nimport { setDevValue, incDevCounter } from '../runtime';\n\nconst SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n\n// Keep direct replaceChildren(...nodes) commits below a conservative argument\n// count until browser benchmarks prove larger spreads are safe.\nexport const DIRECT_REPLACE_CHILDREN_SPREAD_LIMIT = 4096;\n\nexport function canUseDirectReplaceChildrenSpread(count: number): boolean {\n return count <= DIRECT_REPLACE_CHILDREN_SPREAD_LIMIT;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Types\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface ListenerEntry {\n handler: EventListener;\n original: EventListener;\n eventName: string;\n options?: boolean | AddEventListenerOptions;\n updateHandler?: (nextHandler: EventListener) => void;\n}\n\nexport interface ParsedEventProp {\n eventName: string;\n capture: boolean;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Event Handler Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n// Handler pooling cache to avoid recreating wrapped handlers\n// Key: handler reference, Value: { wrapped: EventListener, flushAfter: boolean }\nconst handlerCache = new WeakMap<EventListener, Map<boolean, EventListener>>();\nlet cacheSize = 0;\nconst MAX_CACHE_SIZE = 1000;\n\n/**\n * Parse an event prop name (e.g., 'onClick') to its DOM event name (e.g., 'click')\n */\nexport function parseEventName(propName: string): string | null {\n return parseEventProp(propName)?.eventName ?? null;\n}\n\nexport function parseEventProp(propName: string): ParsedEventProp | null {\n if (!propName.startsWith('on') || propName.length <= 2) return null;\n const capture =\n propName.endsWith('Capture') && propName.length > 'onCapture'.length;\n const normalizedPropName = capture\n ? propName.slice(0, -'Capture'.length)\n : propName;\n\n return normalizedPropName.length <= 2\n ? null\n : {\n eventName:\n normalizedPropName.slice(2).charAt(0).toLowerCase() +\n normalizedPropName.slice(3).toLowerCase(),\n capture,\n };\n}\n\nexport function getEventListenerKey(\n eventName: string,\n capture = false\n): string {\n return capture ? `${eventName}:capture` : eventName;\n}\n\nexport function getEventListenerOptions(\n eventName: string,\n capture = false\n): AddEventListenerOptions | undefined {\n const passiveOptions = getPassiveOptions(eventName);\n if (!capture) {\n return passiveOptions;\n }\n\n return passiveOptions\n ? { ...passiveOptions, capture: true }\n : { capture: true };\n}\n\n/**\n * Get default event listener options for passive events\n */\nexport function getPassiveOptions(\n eventName: string\n): AddEventListenerOptions | undefined {\n if (\n eventName === 'wheel' ||\n eventName === 'scroll' ||\n eventName.startsWith('touch')\n ) {\n return { passive: true };\n }\n return undefined;\n}\n\n/**\n * Create a wrapped event handler that integrates with the scheduler\n * Uses caching to avoid recreating wrappers for the same handler\n */\nexport function createWrappedHandler(\n handler: EventListener,\n flushAfter = false\n): EventListener {\n // Check cache first\n const cachedByFlush = handlerCache.get(handler);\n if (cachedByFlush) {\n const cached = cachedByFlush.get(flushAfter);\n if (cached) return cached;\n }\n\n const wrapped: EventListener = (event: Event) => {\n try {\n runRuntimeHandlerScope(\n () => {\n try {\n handler(event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n }\n },\n flushAfter ? 'sync' : 'defer'\n );\n } catch (err) {\n if (flushAfter) {\n queueMicrotask(() => {\n throw err;\n });\n } else {\n logger.error('[Askr] Event handler error:', err);\n }\n }\n };\n\n // Cache the wrapped handler\n try {\n if (!handlerCache.has(handler)) {\n // Limit cache size to prevent memory leaks\n if (cacheSize >= MAX_CACHE_SIZE) {\n // Simple eviction - just don't cache new entries when full\n } else {\n cacheSize++;\n handlerCache.set(handler, new Map());\n }\n }\n handlerCache.get(handler)?.set(flushAfter, wrapped);\n } catch {\n // WeakMap can throw if handler is not a valid key\n }\n\n return wrapped;\n}\n\nexport function createMutableWrappedHandler(\n handler: EventListener,\n flushAfter = false\n): {\n handler: EventListener;\n updateHandler: (nextHandler: EventListener) => void;\n} {\n let currentHandler = handler;\n\n const wrapped: EventListener = (event: Event) => {\n try {\n runRuntimeHandlerScope(\n () => {\n try {\n currentHandler(event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n }\n },\n flushAfter ? 'sync' : 'defer'\n );\n } catch (err) {\n if (flushAfter) {\n queueMicrotask(() => {\n throw err;\n });\n } else {\n logger.error('[Askr] Event handler error:', err);\n }\n }\n };\n\n return {\n handler: wrapped,\n updateHandler(nextHandler: EventListener) {\n currentHandler = nextHandler;\n },\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Prop/Attribute Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Props that should be skipped during attribute processing */\nexport function isSkippedProp(key: string): boolean {\n return key === 'children' || key === 'key' || key === 'ref';\n}\n\n/** Check if prop should be ignored for prop-change detection */\nexport function isIgnoredForPropChanges(key: string): boolean {\n if (key === 'children' || key === 'key') return true;\n if (key.startsWith('on') && key.length > 2) return true;\n if (key.startsWith('data-')) return true;\n return false;\n}\n\n/**\n * Check if an element's current attribute value differs from vnode value\n */\nexport function hasPropChanged(\n el: Element,\n key: string,\n value: unknown\n): boolean {\n try {\n if (key === 'class' || key === 'className') {\n return readElementClassName(el) !== String(value);\n }\n if (key === 'value' || key === 'checked') {\n return (el as HTMLElement & Record<string, unknown>)[key] !== value;\n }\n const attr = el.getAttribute(getRenderedAttributeName(el, key));\n if (value === undefined || value === null || value === false) {\n return attr !== null;\n }\n return String(value) !== attr;\n } catch {\n return true;\n }\n}\n\nexport function isSVGDomElement(el: Element): el is SVGElement {\n return typeof SVGElement !== 'undefined' && el instanceof SVGElement;\n}\n\nexport function getRenderedAttributeName(\n el: Element,\n propName: string\n): string {\n const attributeName = getPublicAttributeName(propName);\n\n return el.namespaceURI === SVG_NAMESPACE\n ? attributeName\n : attributeName.toLowerCase();\n}\n\nexport function setRenderedAttribute(\n el: Element,\n propName: string,\n value: string\n): void {\n el.setAttribute(getRenderedAttributeName(el, propName), value);\n}\n\nexport function removeRenderedAttribute(el: Element, propName: string): void {\n el.removeAttribute(getRenderedAttributeName(el, propName));\n}\n\nexport function readElementClassName(el: Element): string {\n if (isSVGDomElement(el)) {\n return el.getAttribute('class') ?? '';\n }\n\n return (el as HTMLElement).className;\n}\n\nexport function writeElementClassName(el: Element, value: string): void {\n if (isSVGDomElement(el)) {\n if (value.length > 0) {\n el.setAttribute('class', value);\n } else {\n el.removeAttribute('class');\n }\n return;\n }\n\n (el as HTMLElement).className = value;\n}\n\nexport function tagNamesEqualIgnoreCase(a: string, b: string): boolean {\n if (a === b) return true;\n if (a.length !== b.length) return false;\n\n for (let index = 0; index < a.length; index += 1) {\n const aCode = a.charCodeAt(index);\n const bCode = b.charCodeAt(index);\n if (aCode === bCode) continue;\n\n const normalizedA = aCode >= 65 && aCode <= 90 ? aCode + 32 : aCode;\n const normalizedB = bCode >= 65 && bCode <= 90 ? bCode + 32 : bCode;\n if (normalizedA !== normalizedB) return false;\n }\n\n return true;\n}\n\n/**\n * Check if a vnode has non-trivial props (excluding events and data-*)\n */\nexport function hasNonTrivialProps(props: Record<string, unknown>): boolean {\n for (const k of Object.keys(props)) {\n if (isIgnoredForPropChanges(k)) continue;\n return true;\n }\n return false;\n}\n\n/**\n * Check for prop changes between vnode and existing element\n */\nexport function checkPropChanges(\n el: Element,\n props: Record<string, unknown>\n): boolean {\n for (const k of Object.keys(props)) {\n if (isIgnoredForPropChanges(k)) continue;\n if (hasPropChanged(el, k, props[k])) {\n return true;\n }\n }\n return false;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Key Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Extract key from a vnode object\n */\nexport function extractKey(vnode: unknown): string | number | undefined {\n if (typeof vnode !== 'object' || vnode === null) return undefined;\n const obj = vnode as Record<string, unknown>;\n const rawKey =\n obj.key ?? (obj.props as Record<string, unknown> | undefined)?.key;\n if (rawKey === undefined || rawKey === null) return undefined;\n return typeof rawKey === 'symbol'\n ? String(rawKey)\n : (rawKey as string | number);\n}\n\n/**\n * Build a key map from element's children\n */\nexport function buildKeyMapFromChildren(\n parent: Element\n): Map<string | number, Element> {\n const map = new Map<string | number, Element>();\n for (let ch = parent.firstElementChild; ch; ch = ch.nextElementSibling) {\n const k = ch.getAttribute('data-key');\n if (k !== null) {\n map.set(k, ch);\n const n = Number(k);\n if (!Number.isNaN(n)) map.set(n, ch);\n }\n }\n return map;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Diagnostic Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Record DOM replace operation for diagnostics\n */\nexport function recordDOMReplace(source: string): void {\n try {\n incDevCounter('__DOM_REPLACE_COUNT');\n setDevValue(`__LAST_DOM_REPLACE_STACK_${source}`, new Error().stack);\n } catch {\n // ignore\n }\n}\n\n/**\n * Record fast-path stats for diagnostics\n */\nexport function recordFastPathStats(\n stats: Record<string, unknown>,\n counterName?: string\n): void {\n try {\n setDevValue('__LAST_FASTPATH_STATS', stats);\n setDevValue('__LAST_FASTPATH_COMMIT_COUNT', 1);\n if (counterName) {\n incDevCounter(counterName);\n }\n } catch {\n // ignore\n }\n}\n\n/**\n * Conditionally log debug info for fast-path operations\n */\nexport function logFastPathDebug(\n message: string,\n indexOrData?: number | unknown,\n data?: unknown\n): void {\n const env = getRuntimeEnv();\n if (env.ASKR_FASTPATH_DEBUG === '1' || env.ASKR_FASTPATH_DEBUG === 'true') {\n if (data !== undefined) {\n logger.warn(`[Askr][FASTPATH] ${message}`, indexOrData, data);\n } else if (indexOrData !== undefined) {\n logger.warn(`[Askr][FASTPATH] ${message}`, indexOrData);\n } else {\n logger.warn(`[Askr][FASTPATH] ${message}`);\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Performance Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get current high-resolution timestamp\n */\nexport function now(): number {\n return typeof performance !== 'undefined' && performance.now\n ? performance.now()\n : Date.now();\n}\n"],"mappings":";;;;;;;;;;;;AAWA,MAAM,gBAAgB;AAItB,MAAa,uCAAuC;AAEpD,SAAgB,kCAAkC,OAAwB;CACxE,OAAO,SAAS;AAClB;AAyBA,MAAM,+BAAe,IAAI,QAAoD;AAC7E,IAAI,YAAY;AAChB,MAAM,iBAAiB;;;;AAKvB,SAAgB,eAAe,UAAiC;CAC9D,OAAO,eAAe,QAAQ,CAAC,EAAE,aAAa;AAChD;AAEA,SAAgB,eAAe,UAA0C;CACvE,IAAI,CAAC,SAAS,WAAW,IAAI,KAAK,SAAS,UAAU,GAAG,OAA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AAG/C;;;;AASA,SAAgB,MAAc;CAC5B,OAAO,OAAO,gBAAgB,eAAe,YAAY,MACrD,YAAY,IAAI,IAChB,KAAK,IAAI;AACf"}
|
package/dist/resources/index.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { getSignal } from "../runtime/component-scope.js";
|
|
2
|
-
import "../runtime/component.js";
|
|
3
2
|
import { resource } from "../runtime/resource-operation.js";
|
|
4
3
|
import { capture, documentVisible, on, routeActive, stream, task, timer, windowFocused } from "../runtime/lifecycle-operations.js";
|
|
5
|
-
import "../runtime/
|
|
4
|
+
import "../runtime/index.js";
|
|
6
5
|
export { capture, documentVisible, getSignal, on, resource, routeActive, stream, task, timer, windowFocused };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"activity.d.ts","names":[],"sources":["../../src/router/activity.ts"],"mappings":";;;iBAyBgB,iBAAA,CAAkB,GAAkB;AAAA,
|
|
1
|
+
{"version":3,"file":"activity.d.ts","names":[],"sources":["../../src/router/activity.ts"],"mappings":";;;iBAyBgB,iBAAA,CAAkB,GAAkB;AAAA,iBA0FpC,iBAAA,CACd,WAAuC;AAAA,iBAsDzB,YAAA,iBACE,WAAA,GAAc,WAAA,KAC3B,aAAA,CAAc,OAAA;AAAA,iBAiBH,wBAAA,CACd,QAAA,UACA,MAAA,UACA,IAAA,UACA,eAAA,YAA2B,UAAU"}
|
package/dist/router/activity.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { markReactivePropsDirtySource, markReadableDerivedSubscribersDirty, notifyReadableReaders, recordReadableRead } from "../runtime/readable.js";
|
|
2
2
|
import { getCurrentComponentInstance } from "../runtime/component-scope.js";
|
|
3
|
-
import "../runtime/component.js";
|
|
4
3
|
import { getActiveRenderContext } from "../common/render-context.js";
|
|
5
|
-
import { getActiveRoutes } from "./store.js";
|
|
6
4
|
import { syncRouteActivitySnapshot } from "../common/route-activity.js";
|
|
5
|
+
import "../runtime/index.js";
|
|
6
|
+
import { getActiveRoutes } from "./store.js";
|
|
7
7
|
import { deepFreeze, makeQuery, parseLocation } from "./route-context.js";
|
|
8
|
-
import { computeMatchesFromRoutes } from "./
|
|
8
|
+
import { computeMatchesFromRoutes } from "./route-matching.js";
|
|
9
|
+
import "./resolution.js";
|
|
9
10
|
//#region src/router/activity.ts
|
|
10
11
|
let currentRouteSnapshot = buildRouteSnapshot("/", "", "");
|
|
11
12
|
const currentRouteSource = (() => currentRouteSnapshot);
|
|
@@ -39,28 +40,25 @@ function setCurrentRouteSnapshot(pathname, search, hash, activityMatches) {
|
|
|
39
40
|
markReactivePropsDirtySource(currentRouteSource);
|
|
40
41
|
notifyReadableReaders(currentRouteSource, instance);
|
|
41
42
|
}
|
|
43
|
+
function readCurrentRouteLocation() {
|
|
44
|
+
const renderContext = getActiveRenderContext();
|
|
45
|
+
if (renderContext?.url) return parseLocation(renderContext.url);
|
|
46
|
+
if (typeof window !== "undefined" && window.location) return {
|
|
47
|
+
pathname: window.location.pathname || "/",
|
|
48
|
+
search: window.location.search || "",
|
|
49
|
+
hash: window.location.hash || ""
|
|
50
|
+
};
|
|
51
|
+
if (serverLocation) return parseLocation(serverLocation);
|
|
52
|
+
return {
|
|
53
|
+
pathname: currentRouteSnapshot.path,
|
|
54
|
+
search: "",
|
|
55
|
+
hash: currentRouteSnapshot.hash ?? ""
|
|
56
|
+
};
|
|
57
|
+
}
|
|
42
58
|
function readCurrentRouteSnapshot() {
|
|
43
59
|
const instance = getCurrentComponentInstance();
|
|
44
60
|
if (!instance) throw new Error("currentRoute() can only be called during component render execution. Call currentRoute() from inside your component function.");
|
|
45
|
-
|
|
46
|
-
let search = "";
|
|
47
|
-
let hash = "";
|
|
48
|
-
const renderContext = getActiveRenderContext();
|
|
49
|
-
if (instance.ssr && renderContext?.url) {
|
|
50
|
-
const parsed = parseLocation(renderContext.url);
|
|
51
|
-
pathname = parsed.pathname;
|
|
52
|
-
search = parsed.search;
|
|
53
|
-
hash = parsed.hash;
|
|
54
|
-
} else if (typeof window !== "undefined" && window.location) {
|
|
55
|
-
pathname = window.location.pathname || "/";
|
|
56
|
-
search = window.location.search || "";
|
|
57
|
-
hash = window.location.hash || "";
|
|
58
|
-
} else if (serverLocation) {
|
|
59
|
-
const parsed = parseLocation(serverLocation);
|
|
60
|
-
pathname = parsed.pathname;
|
|
61
|
-
search = parsed.search;
|
|
62
|
-
hash = parsed.hash;
|
|
63
|
-
}
|
|
61
|
+
const { pathname, search, hash } = readCurrentRouteLocation();
|
|
64
62
|
const query = makeQuery(search);
|
|
65
63
|
const matches = computeMatchesFromRoutes(pathname, getActiveRoutes());
|
|
66
64
|
const instanceParams = instance.props;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"activity.js","names":[],"sources":["../../src/router/activity.ts"],"sourcesContent":["import type { RouteMatch, RouteParams, RouteSnapshot } from '../common/router';\nimport { syncRouteActivitySnapshot } from '../common/route-activity';\nimport { getActiveRenderContext } from '../common/render-context';\nimport { getCurrentComponentInstance } from '../runtime
|
|
1
|
+
{"version":3,"file":"activity.js","names":[],"sources":["../../src/router/activity.ts"],"sourcesContent":["import type { RouteMatch, RouteParams, RouteSnapshot } from '../common/router';\nimport { syncRouteActivitySnapshot } from '../common/route-activity';\nimport { getActiveRenderContext } from '../common/render-context';\nimport { getCurrentComponentInstance } from '../runtime';\nimport {\n markReadableDerivedSubscribersDirty,\n markReactivePropsDirtySource,\n notifyReadableReaders,\n recordReadableRead,\n type ReadableSource,\n} from '../runtime';\nimport { deepFreeze, makeQuery, parseLocation } from './route-context';\nimport { computeMatchesFromRoutes } from './resolution';\nimport { getActiveRoutes } from './store';\n\nlet currentRouteSnapshot = buildRouteSnapshot('/', '', '');\n\nconst currentRouteSource = (() =>\n currentRouteSnapshot) as ReadableSource<RouteSnapshot> &\n (() => RouteSnapshot);\n\ncurrentRouteSource._readers = new Map();\n\nlet serverLocation: string | null = null;\n\nexport function setServerLocation(url: string | null): void {\n serverLocation = url;\n if (url) {\n const parsed = parseLocation(url);\n syncRouteActivitySnapshot(\n parsed.pathname,\n computeMatchesFromRoutes(parsed.pathname, getActiveRoutes())\n );\n return;\n }\n\n syncRouteActivitySnapshot(\n currentRouteSnapshot.path,\n currentRouteSnapshot.matches\n );\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 activityMatches?: readonly RouteMatch[]\n): void {\n currentRouteSnapshot = buildRouteSnapshot(pathname, search, hash);\n syncRouteActivitySnapshot(\n pathname,\n activityMatches ?? currentRouteSnapshot.matches\n );\n\n const instance = getCurrentComponentInstance();\n markReadableDerivedSubscribersDirty(currentRouteSource);\n markReactivePropsDirtySource(currentRouteSource);\n notifyReadableReaders(currentRouteSource, instance);\n}\n\nfunction normalizeRouteActivityPath(path: string): string {\n const parsed = parseLocation(path);\n const pathname = parsed.pathname || '/';\n const absolutePathname = pathname.startsWith('/') ? pathname : `/${pathname}`;\n return absolutePathname.endsWith('/') && absolutePathname !== '/'\n ? absolutePathname.slice(0, -1)\n : absolutePathname;\n}\n\nfunction readCurrentRouteLocation(): {\n pathname: string;\n search: string;\n hash: string;\n} {\n const renderContext = getActiveRenderContext();\n if (renderContext?.url) {\n return parseLocation(renderContext.url);\n }\n\n if (typeof window !== 'undefined' && window.location) {\n return {\n pathname: window.location.pathname || '/',\n search: window.location.search || '',\n hash: window.location.hash || '',\n };\n }\n\n if (serverLocation) {\n return parseLocation(serverLocation);\n }\n\n return {\n pathname: currentRouteSnapshot.path,\n search: '',\n hash: currentRouteSnapshot.hash ?? '',\n };\n}\n\nexport function isRoutePathActive(\n pathOrPaths: string | readonly string[]\n): boolean {\n const candidates = new Set(\n (Array.isArray(pathOrPaths) ? pathOrPaths : [pathOrPaths]).map(\n normalizeRouteActivityPath\n )\n );\n\n const activePath = normalizeRouteActivityPath(\n readCurrentRouteLocation().pathname\n );\n if (candidates.has(activePath)) {\n return true;\n }\n\n const matches = computeMatchesFromRoutes(activePath, getActiveRoutes());\n return matches.some((match) =>\n candidates.has(normalizeRouteActivityPath(match.path))\n );\n}\n\nfunction readCurrentRouteSnapshot<\n TParams extends RouteParams = RouteParams,\n>(): RouteSnapshot<TParams> {\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 const { pathname, search, hash } = readCurrentRouteLocation();\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 }) as RouteSnapshot<TParams>;\n}\n\nexport function currentRoute<\n TParams extends RouteParams = RouteParams,\n>(): RouteSnapshot<TParams> {\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<TParams>();\n }\n\n recordReadableRead(currentRouteSource);\n return readCurrentRouteSnapshot<TParams>();\n}\n\nexport function syncCurrentRouteSnapshot(\n pathname: string,\n search: string,\n hash: string,\n activityMatches?: readonly RouteMatch[]\n): void {\n setCurrentRouteSnapshot(pathname, search, hash, activityMatches);\n}\n"],"mappings":";;;;;;;;;;AAeA,IAAI,uBAAuB,mBAAmB,KAAK,IAAI,EAAE;AAEzD,MAAM,4BACJ;AAGF,mBAAmB,2BAAW,IAAI,IAA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U,QAAQ,SAAS,yBAAyB;CAE5D,MAAM,QAAQ,UAAU,MAAM;CAC9B,MAAM,UAAU,yBAAyB,UAAU,gBAAgB,CAAC;CACpE,MAAM,iBAAiB,SAAS;CAKhC,MAAM,SAAS,WAAW,EACxB,GAJA,OAAO,KAAK,cAAc,CAAC,CAAC,SAAS,IACjC,iBACC,QAAQ,EAAE,EAAE,UAAU,CAAC,EAG9B,CAAC;CAED,OAAO,OAAO,OAAO;EACnB,MAAM;EACN;EACA;EACA,MAAM,QAAQ;EACd,SAAS,OAAO,OAAO,OAAO;CAChC,CAAC;AACH;AAEA,SAAgB,eAEY;CAC1B,MAAM,WAAW,4BAA4B;CAC7C,IAAI,CAAC,UACH,MAAM,IAAI,MACR,+HAEF;CAGF,IAAI,OAAO,WAAW,eAAe,SAAS,KAC5C,OAAO,yBAAkC;CAG3C,mBAAmB,kBAAkB;CACrC,OAAO,yBAAkC;AAC3C;AAEA,SAAgB,yBACd,UACA,QACA,MACA,iBACM;CACN,wBAAwB,UAAU,QAAQ,MAAM,eAAe;AACjE"}
|
package/dist/router/authoring.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { getCurrentComponentInstance } from "../runtime/component-scope.js";
|
|
2
|
-
import "../runtime/component.js";
|
|
3
2
|
import { getExecutionModel } from "../runtime/execution-model.js";
|
|
3
|
+
import "../runtime/index.js";
|
|
4
4
|
import { computeRank, normalizeRouteSegmentName, parseSegments } from "./match.js";
|
|
5
5
|
import { compileNodePolicies, nextAccessScopeState, validateAccessMetadata } from "./access.js";
|
|
6
6
|
import { createRouteHandler } from "./rendering.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authoring.js","names":[],"sources":["../../src/router/authoring.ts"],"sourcesContent":["import type {\n GroupHelperOptions,\n PageHelperOptions,\n RegisterRoutesOptions,\n RouteComponent,\n RouteDefinition,\n RouteOptions,\n RouteParams,\n RoutePathParams,\n} from '../common/router';\nimport { getCurrentComponentInstance } from '../runtime/component';\nimport { getExecutionModel } from '../runtime/execution-model';\nimport { computeRank, normalizeRouteSegmentName, parseSegments } from './match';\nimport {\n compileNodePolicies,\n nextAccessScopeState,\n validateAccessMetadata,\n} from './access';\nimport type { AnyRouteComponent, InternalRouteRecord } from './internal-types';\nimport { createRouteHandler } from './rendering';\nimport {\n addRouteToStores,\n assertRouteRegistrationUnlocked,\n getCurrentAccessScopeState,\n getCurrentInheritedPolicies,\n getCurrentLayoutChain,\n getCurrentPageChain,\n getCurrentPageScope,\n getCurrentPathPrefix,\n getCurrentRegistrationSession,\n getCurrentScopeKind,\n hasActivePageScope,\n insertRecordSorted,\n pushRegistrationScope,\n pushRegistrationSession,\n setDefaultRouteAuthOptions,\n} from './store';\n\ntype RouteComponentParam<TComponent extends AnyRouteComponent> =\n Parameters<TComponent> extends [] ? unknown : Parameters<TComponent>[0];\n\ntype CompatibleAbsoluteRouteComponent<\n Path extends string,\n TComponent extends AnyRouteComponent,\n> =\n Parameters<TComponent> extends []\n ? TComponent\n : RoutePathParams<Path> extends RouteComponentParam<TComponent>\n ? TComponent\n : never;\n\ntype CompatibleRelativeRouteComponent<\n Path extends string,\n TComponent extends AnyRouteComponent,\n> =\n Parameters<TComponent> extends []\n ? TComponent\n : RouteComponentParam<TComponent> extends Record<\n keyof RoutePathParams<Path>,\n string\n >\n ? TComponent\n : never;\n\ntype CompatibleRouteComponent<\n Path extends string,\n TComponent extends AnyRouteComponent,\n> = Path extends `/${string}`\n ? CompatibleAbsoluteRouteComponent<Path, TComponent>\n : CompatibleRelativeRouteComponent<Path, TComponent>;\n\ntype RouteOptionsForComponent<\n Path extends string,\n TComponent extends AnyRouteComponent,\n> =\n Parameters<TComponent> extends []\n ? RouteOptions<RoutePathParams<Path>>\n : RouteComponentParam<TComponent> extends RouteParams\n ? RouteOptions<RouteComponentParam<TComponent>>\n : RouteOptions<RoutePathParams<Path>>;\n\nfunction validateRoutePath(path: string): void {\n if (!path.startsWith('/')) {\n throw new Error(`Route path must begin with \"/\". Got: \"${path}\"`);\n }\n if (/\\/{2,}/.test(path)) {\n throw new Error('Route path cannot contain consecutive slashes.');\n }\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 const segments = path.split('/').filter(Boolean);\n const seenParamNames = new Set<string>();\n\n for (let index = 0; index < segments.length; index++) {\n const segment = segments[index];\n if (segment === '*') {\n continue;\n }\n\n const hasOpenBrace = segment.includes('{');\n const hasCloseBrace = segment.includes('}');\n\n if (!hasOpenBrace && !hasCloseBrace) {\n continue;\n }\n\n if (!(segment.startsWith('{') && segment.endsWith('}'))) {\n throw new Error(\n 'Route parameter segments must use complete {name} interpolation.'\n );\n }\n\n const rawParamName = normalizeRouteSegmentName(segment.slice(1, -1));\n const isSplat = rawParamName.startsWith('*');\n const paramName = isSplat\n ? normalizeRouteSegmentName(rawParamName.slice(1))\n : rawParamName;\n\n if (!paramName) {\n throw new Error(\n isSplat\n ? 'Route splat parameter name cannot be empty.'\n : 'Route parameter name cannot be empty.'\n );\n }\n\n if (isSplat && paramName === '*') {\n throw new Error('Route named splat parameter name cannot be \"*\".');\n }\n\n if (isSplat && index !== segments.length - 1) {\n throw new Error(\n 'Route named splat parameters must be the final segment.'\n );\n }\n\n if (seenParamNames.has(paramName)) {\n throw new Error(\n `Route path cannot reuse duplicate parameter name \"${paramName}\".`\n );\n }\n\n seenParamNames.add(paramName);\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\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 hasIndex: false,\n policies,\n state: nextAccessScopeState(options, getCurrentAccessScopeState()),\n },\n fn\n );\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 registerRouteAtResolvedPath(\n path: string,\n Component: RouteComponent,\n options?: RouteOptions,\n metadata?: {\n isFallback?: boolean;\n fallbackPrefix?: string;\n }\n): void {\n validateRoutePath(path);\n\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 = createRouteHandler(comp, pageChain, chain);\n const renderHandler = createRouteHandler(comp, pageChain, chain, true);\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 renderHandler,\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 group(options: GroupHelperOptions, fn: RouteDefinition): void;\nexport function group(options: GroupHelperOptions, fn: RouteDefinition): void {\n pushGroupScope(options, fn);\n}\n\nexport function page<const TPath extends string>(\n path: TPath,\n Component: RouteComponent<RoutePathParams<TPath>>,\n fn: RouteDefinition\n): void;\nexport function page<\n const TPath extends string,\n TComponent extends AnyRouteComponent,\n>(\n path: TPath,\n Component: CompatibleRouteComponent<TPath, TComponent>,\n fn: RouteDefinition\n): void;\nexport function page<const TPath extends string>(\n path: TPath,\n Component: RouteComponent<RoutePathParams<TPath>>,\n options: PageHelperOptions,\n fn: RouteDefinition\n): void;\nexport function page<\n const TPath extends string,\n TComponent extends AnyRouteComponent,\n>(\n path: TPath,\n Component: CompatibleRouteComponent<TPath, TComponent>,\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 const pageScope = getCurrentPageScope();\n if (pageScope?.hasIndex) {\n throw new Error('page() cannot declare multiple index routes.');\n }\n\n if (pageScope) {\n pageScope.hasIndex = true;\n }\n\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 =\n getCurrentInheritedPolicies().length === 0 &&\n !getCurrentAccessScopeState().guestOnly &&\n !getCurrentAccessScopeState().authenticated;\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\nexport function registerRoutes(\n definition: RouteDefinition,\n options: RegisterRoutesOptions = {}\n): void {\n setDefaultRouteAuthOptions(options.auth);\n pushRegistrationSession(\n {\n authConfigured: !!options.auth?.resolve,\n },\n definition\n );\n}\n\nexport function route<const TPath extends string>(\n path: TPath,\n Component: RouteComponent<RoutePathParams<TPath>>,\n options?: RouteOptions<RoutePathParams<TPath>>\n): void;\nexport function route<\n const TPath extends string,\n TComponent extends AnyRouteComponent,\n>(\n path: TPath,\n Component: CompatibleRouteComponent<TPath, TComponent>,\n options?: RouteOptionsForComponent<TPath, TComponent>\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 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 assertRouteRegistrationUnlocked();\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"],"mappings":";;;;;;;;AAiFA,SAAS,kBAAkB,MAAoB;CAC7C,IAAI,CAAC,KAAK,WAAW,GAAG,GACtB,MAAM,IAAI,MAAM,yCAAyC,KAAK,EAAE;CAElE,IAAI,SAAS,KAAK,IAAI,GACpB,MAAM,IAAI,MAAM,gDAAgD;CAElE,IAAI,aAAa,KAAK,IAAI,GAAG;EAC3B,MAAM,YAAY,KAAK,QAAQ,eAAe,MAAM;EACpD,MAAM,IAAI,MACR,qEACU,UAAU,gBAAgB,KAAK,GAC3C;CACF;CAEA,MAAM,WAAW,KAAK,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO;CAC/C,MAAM,iCAAiB,IAAI,IAAY;CAEvC,KAAK,IAAI,QAAQ,GAAG,QAAQ,SAAS,QAAQ,SAAS;EACpD,MAAM,UAAU,SAAS;EACzB,IAAI,YAAY,KACd;EAGF,MAAM,eAAe,QAAQ,SAAS,GAAG;EACzC,MAAM,gBAAgB,QAAQ,SAAS,GAAG;EAE1C,IAAI,CAAC,gBAAgB,CAAC,eACpB;EAGF,IAAI,EAAE,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,GAAG,IACnD,MAAM,IAAI,MACR,kEACF;EAGF,MAAM,eAAe,0BAA0B,QAAQ,MAAM,GAAG,EAAE,CAAC;EACnE,MAAM,UAAU,aAAa,WAAW,GAAG;EAC3C,MAAM,YAAY,UACd,0BAA0B,aAAa,MAAM,CAAC,CAAC,IAC/C;EAEJ,IAAI,CAAC,WACH,MAAM,IAAI,MACR,UACI,gDACA,uCACN;EAGF,IAAI,WAAW,cAAc,KAC3B,MAAM,IAAI,MAAM,mDAAiD;EAGnE,IAAI,WAAW,UAAU,SAAS,SAAS,GACzC,MAA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3,"file":"authoring.js","names":[],"sources":["../../src/router/authoring.ts"],"sourcesContent":["import type {\n GroupHelperOptions,\n PageHelperOptions,\n RegisterRoutesOptions,\n RouteComponent,\n RouteDefinition,\n RouteOptions,\n RouteParams,\n RoutePathParams,\n} from '../common/router';\nimport { getCurrentComponentInstance } from '../runtime';\nimport { getExecutionModel } from '../runtime';\nimport { computeRank, normalizeRouteSegmentName, parseSegments } from './match';\nimport {\n compileNodePolicies,\n nextAccessScopeState,\n validateAccessMetadata,\n} from './access';\nimport type { AnyRouteComponent, InternalRouteRecord } from './internal-types';\nimport { createRouteHandler } from './rendering';\nimport {\n addRouteToStores,\n assertRouteRegistrationUnlocked,\n getCurrentAccessScopeState,\n getCurrentInheritedPolicies,\n getCurrentLayoutChain,\n getCurrentPageChain,\n getCurrentPageScope,\n getCurrentPathPrefix,\n getCurrentRegistrationSession,\n getCurrentScopeKind,\n hasActivePageScope,\n insertRecordSorted,\n pushRegistrationScope,\n pushRegistrationSession,\n setDefaultRouteAuthOptions,\n} from './store';\n\ntype RouteComponentParam<TComponent extends AnyRouteComponent> =\n Parameters<TComponent> extends [] ? unknown : Parameters<TComponent>[0];\n\ntype CompatibleAbsoluteRouteComponent<\n Path extends string,\n TComponent extends AnyRouteComponent,\n> =\n Parameters<TComponent> extends []\n ? TComponent\n : RoutePathParams<Path> extends RouteComponentParam<TComponent>\n ? TComponent\n : never;\n\ntype CompatibleRelativeRouteComponent<\n Path extends string,\n TComponent extends AnyRouteComponent,\n> =\n Parameters<TComponent> extends []\n ? TComponent\n : RouteComponentParam<TComponent> extends Record<\n keyof RoutePathParams<Path>,\n string\n >\n ? TComponent\n : never;\n\ntype CompatibleRouteComponent<\n Path extends string,\n TComponent extends AnyRouteComponent,\n> = Path extends `/${string}`\n ? CompatibleAbsoluteRouteComponent<Path, TComponent>\n : CompatibleRelativeRouteComponent<Path, TComponent>;\n\ntype RouteOptionsForComponent<\n Path extends string,\n TComponent extends AnyRouteComponent,\n> =\n Parameters<TComponent> extends []\n ? RouteOptions<RoutePathParams<Path>>\n : RouteComponentParam<TComponent> extends RouteParams\n ? RouteOptions<RouteComponentParam<TComponent>>\n : RouteOptions<RoutePathParams<Path>>;\n\nfunction validateRoutePath(path: string): void {\n if (!path.startsWith('/')) {\n throw new Error(`Route path must begin with \"/\". Got: \"${path}\"`);\n }\n if (/\\/{2,}/.test(path)) {\n throw new Error('Route path cannot contain consecutive slashes.');\n }\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 const segments = path.split('/').filter(Boolean);\n const seenParamNames = new Set<string>();\n\n for (let index = 0; index < segments.length; index++) {\n const segment = segments[index];\n if (segment === '*') {\n continue;\n }\n\n const hasOpenBrace = segment.includes('{');\n const hasCloseBrace = segment.includes('}');\n\n if (!hasOpenBrace && !hasCloseBrace) {\n continue;\n }\n\n if (!(segment.startsWith('{') && segment.endsWith('}'))) {\n throw new Error(\n 'Route parameter segments must use complete {name} interpolation.'\n );\n }\n\n const rawParamName = normalizeRouteSegmentName(segment.slice(1, -1));\n const isSplat = rawParamName.startsWith('*');\n const paramName = isSplat\n ? normalizeRouteSegmentName(rawParamName.slice(1))\n : rawParamName;\n\n if (!paramName) {\n throw new Error(\n isSplat\n ? 'Route splat parameter name cannot be empty.'\n : 'Route parameter name cannot be empty.'\n );\n }\n\n if (isSplat && paramName === '*') {\n throw new Error('Route named splat parameter name cannot be \"*\".');\n }\n\n if (isSplat && index !== segments.length - 1) {\n throw new Error(\n 'Route named splat parameters must be the final segment.'\n );\n }\n\n if (seenParamNames.has(paramName)) {\n throw new Error(\n `Route path cannot reuse duplicate parameter name \"${paramName}\".`\n );\n }\n\n seenParamNames.add(paramName);\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\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 hasIndex: false,\n policies,\n state: nextAccessScopeState(options, getCurrentAccessScopeState()),\n },\n fn\n );\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 registerRouteAtResolvedPath(\n path: string,\n Component: RouteComponent,\n options?: RouteOptions,\n metadata?: {\n isFallback?: boolean;\n fallbackPrefix?: string;\n }\n): void {\n validateRoutePath(path);\n\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 = createRouteHandler(comp, pageChain, chain);\n const renderHandler = createRouteHandler(comp, pageChain, chain, true);\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 renderHandler,\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 group(options: GroupHelperOptions, fn: RouteDefinition): void;\nexport function group(options: GroupHelperOptions, fn: RouteDefinition): void {\n pushGroupScope(options, fn);\n}\n\nexport function page<const TPath extends string>(\n path: TPath,\n Component: RouteComponent<RoutePathParams<TPath>>,\n fn: RouteDefinition\n): void;\nexport function page<\n const TPath extends string,\n TComponent extends AnyRouteComponent,\n>(\n path: TPath,\n Component: CompatibleRouteComponent<TPath, TComponent>,\n fn: RouteDefinition\n): void;\nexport function page<const TPath extends string>(\n path: TPath,\n Component: RouteComponent<RoutePathParams<TPath>>,\n options: PageHelperOptions,\n fn: RouteDefinition\n): void;\nexport function page<\n const TPath extends string,\n TComponent extends AnyRouteComponent,\n>(\n path: TPath,\n Component: CompatibleRouteComponent<TPath, TComponent>,\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 const pageScope = getCurrentPageScope();\n if (pageScope?.hasIndex) {\n throw new Error('page() cannot declare multiple index routes.');\n }\n\n if (pageScope) {\n pageScope.hasIndex = true;\n }\n\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 =\n getCurrentInheritedPolicies().length === 0 &&\n !getCurrentAccessScopeState().guestOnly &&\n !getCurrentAccessScopeState().authenticated;\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\nexport function registerRoutes(\n definition: RouteDefinition,\n options: RegisterRoutesOptions = {}\n): void {\n setDefaultRouteAuthOptions(options.auth);\n pushRegistrationSession(\n {\n authConfigured: !!options.auth?.resolve,\n },\n definition\n );\n}\n\nexport function route<const TPath extends string>(\n path: TPath,\n Component: RouteComponent<RoutePathParams<TPath>>,\n options?: RouteOptions<RoutePathParams<TPath>>\n): void;\nexport function route<\n const TPath extends string,\n TComponent extends AnyRouteComponent,\n>(\n path: TPath,\n Component: CompatibleRouteComponent<TPath, TComponent>,\n options?: RouteOptionsForComponent<TPath, TComponent>\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 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 assertRouteRegistrationUnlocked();\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"],"mappings":";;;;;;;;AAiFA,SAAS,kBAAkB,MAAoB;CAC7C,IAAI,CAAC,KAAK,WAAW,GAAG,GACtB,MAAM,IAAI,MAAM,yCAAyC,KAAK,EAAE;CAElE,IAAI,SAAS,KAAK,IAAI,GACpB,MAAM,IAAI,MAAM,gDAAgD;CAElE,IAAI,aAAa,KAAK,IAAI,GAAG;EAC3B,MAAM,YAAY,KAAK,QAAQ,eAAe,MAAM;EACpD,MAAM,IAAI,MACR,qEACU,UAAU,gBAAgB,KAAK,GAC3C;CACF;CAEA,MAAM,WAAW,KAAK,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO;CAC/C,MAAM,iCAAiB,IAAI,IAAY;CAEvC,KAAK,IAAI,QAAQ,GAAG,QAAQ,SAAS,QAAQ,SAAS;EACpD,MAAM,UAAU,SAAS;EACzB,IAAI,YAAY,KACd;EAGF,MAAM,eAAe,QAAQ,SAAS,GAAG;EACzC,MAAM,gBAAgB,QAAQ,SAAS,GAAG;EAE1C,IAAI,CAAC,gBAAgB,CAAC,eACpB;EAGF,IAAI,EAAE,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,GAAG,IACnD,MAAM,IAAI,MACR,kEACF;EAGF,MAAM,eAAe,0BAA0B,QAAQ,MAAM,GAAG,EAAE,CAAC;EACnE,MAAM,UAAU,aAAa,WAAW,GAAG;EAC3C,MAAM,YAAY,UACd,0BAA0B,aAAa,MA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,IAAI,eAAe,YAAY,KAC7B,MAAM,IAAI,MACR,6FACF;CAGF,gCAAgC;CAEhC,IAAI,OAAO,cAAc,YACvB,MAAM,IAAI,MACR,wIAEF;CAGF,4BACE,6BAA6B,IAAI,GACjC,WACA,OACF;AACF"}
|
package/dist/router/index.d.ts
CHANGED
|
@@ -5,10 +5,10 @@ import { RouteQueryParamInput, RouteQueryParamValue, RouteQueryUpdater, RouteQue
|
|
|
5
5
|
import { navigate } from "./navigate.js";
|
|
6
6
|
import { fallback, group, index, page, registerRoutes, route } from "./authoring.js";
|
|
7
7
|
import { currentRoute } from "./activity.js";
|
|
8
|
+
import { allow, deny, forbidden, notFound, redirect, requireAuth, requirePermission, requireRole, unauthorized } from "./policy.js";
|
|
8
9
|
import { clearRoutes, createRouteRegistry, getManifest } from "./manifest.js";
|
|
9
10
|
import { getRoutes } from "./store.js";
|
|
10
11
|
import { lazy } from "./lazy.js";
|
|
11
12
|
import { Outlet } from "./rendering.js";
|
|
12
|
-
import { allow, deny, forbidden, notFound, redirect, requireAuth, requirePermission, requireRole, unauthorized } from "./policy.js";
|
|
13
13
|
import { Link, LinkProps } from "../components/link.js";
|
|
14
14
|
export { type AccessDecision, type AccessDenyDecision, type AccessRedirectDecision, type GroupHelperOptions, type HistoryScrollBehavior, type LayoutScopeRecord, Link, type LinkProps, type NavigateOptions, type NavigationScrollBehavior, Outlet, type PageHelperOptions, type PageScopeRecord, type ParsedSegment, type RegisterRoutesOptions, type Route, type RouteAuthMode, type RouteAuthOptions, type RouteAuthResolver, type RouteAuthState, type RouteComponent, type RouteContext, type RouteDefinition, type RouteHandler, type RouteManifest, type RouteMatch, type RouteMode, type RouteOptions, type RouteParams, type RoutePathParams, type RoutePolicy, type RouteQuery, type RouteQueryParamInput, type RouteQueryParamValue, type RouteQueryUpdater, type RouteQueryUpdates, type RouteRecord, type RouteRegistry, type RouteRenderResult, type RouteRequestOptions, type RouteRequestResult, type RouteSnapshot, type ScrollRestorationOptions, type UpdateRouteQueryOptions, allow, clearRoutes, createRouteRegistry, currentRoute, deny, fallback, forbidden, getManifest, getRoutes, group, index, lazy, navigate, notFound, page, redirect, registerRoutes, requireAuth, requirePermission, requireRole, route, unauthorized, updateRouteQuery };
|
package/dist/router/navigate.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { logger } from "../
|
|
1
|
+
import { logger } from "../common/logger.js";
|
|
2
2
|
import { isPromiseLike } from "../common/promise.js";
|
|
3
3
|
import { configureScrollRestoration, saveScrollPosition } from "./navigation-scroll.js";
|
|
4
4
|
import { configureNavigationRegistryHost, getCurrentHref, hasRegisteredApps, parseTargetUrl, registerAppInstance, unregisterAppInstance } from "./navigation-registry.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"navigate.js","names":[],"sources":["../../src/router/navigate.ts"],"sourcesContent":["/**\n * Client-side navigation with History API\n */\n\nimport { isPromiseLike } from '../common/promise';\nimport { logger } from '../
|
|
1
|
+
{"version":3,"file":"navigate.js","names":[],"sources":["../../src/router/navigate.ts"],"sourcesContent":["/**\n * Client-side navigation with History API\n */\n\nimport { isPromiseLike } from '../common/promise';\nimport { logger } from '../common/logger';\nimport { saveScrollPosition } from './navigation-scroll';\nimport {\n configureNavigationRegistryHost,\n getCurrentHref,\n hasRegisteredApps,\n parseTargetUrl,\n} from './navigation-registry';\nimport {\n applyNavigationTargets,\n applyPopStateNavigationTargets,\n beginRouteRequest,\n cancelRouteRequests,\n isStaleRouteRequest,\n resolveNavigationTargetsForApps,\n type AppNavigationTarget,\n type NavigateOptions,\n type NavigationRedirectState,\n} from './navigation-targets';\n\nexport { configureScrollRestoration } from './navigation-scroll';\nexport type {\n HistoryScrollBehavior,\n NavigationScrollBehavior,\n ScrollRestorationOptions,\n} from './navigation-scroll';\nexport {\n registerAppInstance,\n unregisterAppInstance,\n} from './navigation-registry';\nexport { updateRouteQuery } from './route-query';\nexport type {\n RouteQueryParamInput,\n RouteQueryParamValue,\n RouteQueryUpdater,\n RouteQueryUpdates,\n UpdateRouteQueryOptions,\n} from './route-query';\nexport type { NavigateOptions };\n\nlet navigationInitialized = false;\n\nconfigureNavigationRegistryHost({\n cancelRouteRequests,\n});\n\nexport function navigate(path: string, options: NavigateOptions = {}): void {\n if (typeof window === 'undefined') {\n return;\n }\n\n const initialTarget = parseTargetUrl(path);\n navigateWithRedirectState(path, options, {\n redirects: 0,\n visited: new Set([\n `${initialTarget.pathname}${initialTarget.search}${initialTarget.hash}`,\n ]),\n });\n}\n\nfunction navigateWithRedirectState(\n path: string,\n options: NavigateOptions,\n redirectState: NavigationRedirectState\n): void {\n if (typeof window === 'undefined') {\n return;\n }\n\n const request = beginRouteRequest();\n\n const target = parseTargetUrl(path);\n const pathname = target.pathname;\n const href = `${target.pathname}${target.search}${target.hash}`;\n const resolvedTargets = resolveNavigationTargetsForApps(\n pathname,\n href,\n request.signal\n );\n\n if (isPromiseLike(resolvedTargets)) {\n void Promise.resolve(resolvedTargets).then(\n (targets) => {\n if (isStaleRouteRequest(request.id)) {\n return;\n }\n\n try {\n applyNavigationTargets(\n path,\n options,\n redirectState,\n pathname,\n href,\n targets,\n navigateWithRedirectState\n );\n } catch (error) {\n logger.error('[Askr] navigation failed:', error);\n }\n },\n (error) => {\n logger.error('[Askr] navigation failed:', error);\n }\n );\n return;\n }\n\n applyNavigationTargets(\n path,\n options,\n redirectState,\n pathname,\n href,\n resolvedTargets,\n navigateWithRedirectState\n );\n}\n\nfunction handlePopState(event: PopStateEvent): void {\n const request = beginRouteRequest();\n const previousHref = getCurrentHref();\n const pathname = window.location.pathname;\n const href = `${window.location.pathname}${window.location.search}${window.location.hash}`;\n\n saveScrollPosition(previousHref);\n\n if (!hasRegisteredApps()) {\n return;\n }\n\n const applyResolved = (targets: AppNavigationTarget[]) => {\n try {\n applyPopStateNavigationTargets(\n request.id,\n pathname,\n href,\n event.state,\n targets,\n navigate\n );\n } catch (error) {\n logger.error('[Askr] popstate navigation failed:', error);\n }\n };\n\n const resolvedTargets = resolveNavigationTargetsForApps(\n pathname,\n href,\n request.signal\n );\n\n if (isPromiseLike<AppNavigationTarget[]>(resolvedTargets)) {\n void Promise.resolve(resolvedTargets).then(\n (next) => {\n applyResolved(next);\n },\n (error) => {\n logger.error('[Askr] popstate navigation failed:', error);\n }\n );\n return;\n }\n\n applyResolved(resolvedTargets);\n}\n\nexport function initializeNavigation(): void {\n if (typeof window === 'undefined' || navigationInitialized) {\n return;\n }\n\n navigationInitialized = true;\n window.addEventListener('popstate', handlePopState);\n}\n\nexport function cleanupNavigation(): void {\n cancelRouteRequests();\n\n if (typeof window === 'undefined' || !navigationInitialized) {\n return;\n }\n\n navigationInitialized = false;\n window.removeEventListener('popstate', handlePopState);\n}\n"],"mappings":";;;;;;;;;;AA6CA,IAAI,wBAAwB;AAE5B,gCAAgC,EAC9B,oBACF,CAAC;AAED,SAAgB,SAAS,MAAc,UAA2B,CAAC,GAAS;CAC1E,IAAI,OAAO,WAAW,aACpB;CAGF,MAAM,gBAAgB,eAAe,IAAI;CACzC,0BAA0B,MAAM,SAAS;EACvC,WAAW;EACX,yBAAS,IAAI,IAAI,CACf,GAAG,cAAc,WAAW,cAAc,SAAS,cAAc,MACnE,CAAC;CACH,CAAC;AACH;AAEA,SAAS,0BACP,MACA,SACA,eACM;CACN,IAAI,OAAO,WAAW,aACpB;CAGF,MAAM,UAAU,kBAAkB;CAElC,MAAM,SAAS,eAAe,IAAI;CAClC,MAAM,WAAW,OAAO;CACxB,MAAM,OAAO,GAAG,OAAO,WAAW,OAAO,SAAS,OAAO;CACzD,MAAM,kBAAkB,gCACtB,UACA,MACA,QAAQ,MACV;CAEA,IAAI,cAAc,eAAe,GAAG;EAClC,AAAK,QAAQ,QAAQ,eAAe,CAAC,CAAC,MACnC,YAAY;GACX,IAAI,oBAAoB,QAAQ,EAAE,GAChC;GAGF,IAAI;IACF,uBACE,MACA,SACA,eACA,UACA,MACA,SACA,yBACF;GACF,SAAS,OAAO;IACd,OAAO,MAAM,6BAA6B,KAAK;GACjD;EACF,IACC,UAAU;GACT,OAAO,MAAM,6BAA6B,KAAK;EACjD,CACF;EACA;CACF;CAEA,uBACE,MACA,SACA,eACA,UACA,MACA,iBACA,yBACF;AACF;AAEA,SAAS,eAAe,OAA4B;CAClD,MAAM,UAAU,kBAAkB;CAClC,MAAM,eAAe,eAAe;CACpC,MAAM,WAAW,OAAO,SAAS;CACjC,MAAM,OAAO,GAAG,OAAO,SAAS,WAAW,OAAO,SAAS,SAAS,OAAO,SAAS;CAEpF,mBAAmB,YAAY;CAE/B,IAAI,CAAC,kBAAkB,GACrB;CAGF,MAAM,iBAAiB,YAAmC;EACxD,IAAI;GACF,+BACE,QAAQ,IACR,UACA,MACA,MAAM,OACN,SACA,QACF;EACF,SAAS,OAAO;GACd,OAAO,MAAM,sCAAsC,KAAK;EAC1D;CACF;CAEA,MAAM,kBAAkB,gCACtB,UACA,MACA,QAAQ,MACV;CAEA,IAAI,cAAqC,eAAe,GAAG;EACzD,AAAK,QAAQ,QAAQ,eAAe,CAAC,CAAC,MACnC,SAAS;GACR,cAAc,IAAI;EACpB,IACC,UAAU;GACT,OAAO,MAAM,sCAAsC,KAAK;EAC1D,CACF;EACA;CACF;CAEA,cAAc,eAAe;AAC/B;AAEA,SAAgB,uBAA6B;CAC3C,IAAI,OAAO,WAAW,eAAe,uBACnC;CAGF,wBAAwB;CACxB,OAAO,iBAAiB,YAAY,cAAc;AACpD"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { isProductionEnvironment } from "../common/env.js";
|
|
2
2
|
import { lockRouteRegistration } from "./store.js";
|
|
3
|
-
import { computeRouteActivityMatches } from "./
|
|
3
|
+
import { computeRouteActivityMatches } from "./route-matching.js";
|
|
4
4
|
import { syncCurrentRouteSnapshot } from "./activity.js";
|
|
5
5
|
import "./route.js";
|
|
6
6
|
//#region src/router/navigation-registry.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"navigation-registry.js","names":[],"sources":["../../src/router/navigation-registry.ts"],"sourcesContent":["import type { Route, RouteAuthOptions, RouteManifest } from '../common/router';\nimport { isProductionEnvironment } from '../common/env';\nimport type { ComponentInstance } from '../runtime
|
|
1
|
+
{"version":3,"file":"navigation-registry.js","names":[],"sources":["../../src/router/navigation-registry.ts"],"sourcesContent":["import type { Route, RouteAuthOptions, RouteManifest } from '../common/router';\nimport { isProductionEnvironment } from '../common/env';\nimport type { ComponentInstance } from '../runtime';\nimport {\n computeRouteActivityMatches,\n lockRouteRegistration,\n syncCurrentRouteSnapshot,\n} from './route';\n\nexport type AppNavigationSource = {\n manifest?: RouteManifest;\n routes?: readonly Route[];\n auth?: RouteAuthOptions;\n};\n\nexport type AppRegistration = AppNavigationSource & {\n instance: ComponentInstance;\n pathname: string;\n href: string;\n};\n\ntype NavigationRegistryHost = {\n cancelRouteRequests(): void;\n};\n\nlet currentInstance: ComponentInstance | null = null;\nlet currentPathname = '/';\nlet currentHref = '/';\nlet navigationRegistryHost: NavigationRegistryHost | null = null;\n\nconst registeredApps: AppRegistration[] = [];\n\nexport function configureNavigationRegistryHost(\n host: NavigationRegistryHost\n): void {\n navigationRegistryHost = host;\n}\n\nexport function getCurrentPathname(): string {\n return currentPathname;\n}\n\nexport function getCurrentHref(): string {\n return currentHref;\n}\n\nexport function setCurrentRouteLocation(pathname: string, href: string): void {\n currentPathname = pathname;\n currentHref = href;\n}\n\nexport function getWindowHref(): string {\n if (typeof window === 'undefined') {\n return currentHref;\n }\n\n return `${window.location.pathname}${window.location.search}${window.location.hash}`;\n}\n\nexport function parseTargetUrl(path: string): URL {\n const pathname = window.location.pathname || '/';\n const search = window.location.search || '';\n const hash = window.location.hash || '';\n const href =\n typeof window.location.href === 'string' ? window.location.href : '';\n const base =\n href &&\n href !== 'about:blank' &&\n !href.startsWith('about:') &&\n !href.startsWith('data:')\n ? href\n : `http://localhost${pathname}${search}${hash}`;\n\n return new URL(path, base);\n}\n\nexport function getRegisteredAppsSnapshot(): AppRegistration[] {\n return [...registeredApps];\n}\n\nexport function hasRegisteredApps(): boolean {\n return registeredApps.length > 0;\n}\n\nexport function syncAppRegistrationLocation(\n app: AppRegistration,\n pathname: string,\n href: string\n): void {\n app.pathname = pathname;\n app.href = href;\n}\n\nfunction collectRouteActivityMatches(\n pathname: string,\n apps: readonly AppRegistration[] = registeredApps\n) {\n const matches: ReturnType<typeof computeRouteActivityMatches> = [];\n const seenPaths = new Set<string>();\n\n for (const app of apps) {\n const appMatches = computeRouteActivityMatches(pathname, {\n manifest: app.manifest,\n routes: app.routes,\n });\n\n for (const match of appMatches) {\n if (seenPaths.has(match.path)) {\n continue;\n }\n seenPaths.add(match.path);\n matches.push(match);\n }\n }\n\n return matches;\n}\n\nexport function syncRegisteredRouteSnapshot(): void {\n if (typeof window === 'undefined') {\n return;\n }\n\n const pathname = window.location.pathname || '/';\n syncCurrentRouteSnapshot(\n pathname,\n window.location.search || '',\n window.location.hash || '',\n collectRouteActivityMatches(pathname)\n );\n}\n\nexport function registerAppInstance(\n instance: ComponentInstance,\n path: string,\n source: AppNavigationSource = {}\n): void {\n const existingIndex = registeredApps.findIndex(\n (app) => app.instance === instance\n );\n const registration: AppRegistration = {\n instance,\n pathname: path,\n href: getWindowHref(),\n ...source,\n };\n if (existingIndex >= 0) {\n registeredApps[existingIndex] = registration;\n } else {\n registeredApps.push(registration);\n }\n\n currentInstance = instance;\n currentPathname = path;\n currentHref = getWindowHref();\n syncRegisteredRouteSnapshot();\n if (isProductionEnvironment()) {\n lockRouteRegistration();\n }\n}\n\nexport function unregisterAppInstance(instance: ComponentInstance): void {\n const existingIndex = registeredApps.findIndex(\n (app) => app.instance === instance\n );\n if (existingIndex >= 0) {\n registeredApps.splice(existingIndex, 1);\n }\n syncRegisteredRouteSnapshot();\n\n if (currentInstance !== instance) {\n return;\n }\n\n const nextApp =\n registeredApps.length > 0\n ? registeredApps[registeredApps.length - 1]!\n : null;\n currentInstance = nextApp?.instance ?? null;\n if (nextApp) {\n currentPathname = nextApp.pathname;\n currentHref = nextApp.href;\n syncRegisteredRouteSnapshot();\n return;\n }\n\n navigationRegistryHost?.cancelRouteRequests();\n currentPathname = '/';\n currentHref = '/';\n if (typeof window === 'undefined') {\n syncCurrentRouteSnapshot('/', '', '', []);\n }\n}\n"],"mappings":";;;;;;AAyBA,IAAI,kBAA4C;AAChD,IAAI,kBAAkB;AACtB,IAAI,cAAc;AAClB,IAAI,yBAAwD;AAE5D,MAAM,iBAAoC,CAAC;AAE3C,SAAgB,gCACd,MACM;CACN,yBAAyB;AAC3B;AAEA,SAAgB,qBAA6B;CAC3C,OAAO;AACT;AAEA,SAAgB,iBAAyB;CACvC,OAAO;AACT;AAEA,SAAgB,wBAAwB,UAAkB,MAAoB;CAC5E,kBAAkB;CAClB,cAAc;AAChB;AAEA,SAAgB,gBAAwB;CACtC,IAAI,OAAO,WAAW,aACpB,OAAO;CAGT,OAAO,GAAG,OAAO,SAAS,WAAW,OAAO,SAAS,SAAS,OAAO,SAAS;AAChF;AAEA,SAAgB,eAAe,MAAmB;CAChD,MAAM,WAAW,OAAO,SAAS,YAAY;CAC7C,MAAM,SAAS,OAAO,SAAS,UAAU;CACzC,MAAM,OAAO,OAAO,SAAS,QAAQ;CACrC,MAAM,OACJ,OAAO,OAAO,SAAS,SAAS,WAAW,OAAO,SAAS,OAAO;CACpE,MAAM,OACJ,QACA,SAAS,iBACT,CAAC,KAAK,WAAW,QAAQ,KACzB,CAAC,KAAK,WAAW,OAAO,IACpB,OACA,mBAAmB,WAAW,SAAS;CAE7C,OAAO,IAAI,IAAI,MAAM,IAAI;AAC3B;AAEA,SAAgB,4BAA+C;CAC7D,OAAO,CAAC,GAAG,cAAc;AAC3B;AAEA,SAAgB,oBAA6B;CAC3C,OAAO,eAAe,SAAS;AACjC;AAEA,SAAgB,4BACd,KACA,UACA,MACM;CACN,IAAI,WAAW;CACf,IAAI,OAAO;AACb;AAEA,SAAS,4BACP,UACA,OAAmC,gBACnC;CACA,MAAM,UAA0D,CAAC;CACjE,MAAM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O,WAAW,aACpB,yBAAyB,KAAK,IAAI,IAAI,CAAC,CAAC;AAE5C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"navigation-targets.d.ts","names":[],"sources":["../../src/router/navigation-targets.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"navigation-targets.d.ts","names":[],"sources":["../../src/router/navigation-targets.ts"],"mappings":";;;;;KAkCY,eAAA;EACV,OAAA;EACA,OAAA;EACA,MAAA,GAAS,wBAAwB;AAAA;AAAA,KAGvB,uBAAA;EACV,SAAA;EACA,OAAA,EAAS,GAAG;AAAA;AAAA,KAGF,mBAAA;EACV,GAAA,EAAK,eAAA;EACL,QAAA,EAAU,kBAAkB;AAAA;AAAA,iBAQd,iBAAA;EAAuB,EAAA;EAAY,MAAA,EAAQ,WAAW;AAAA;AAAA,iBAWtD,mBAAA,CAAoB,SAAiB;AAAA,iBAIrC,mBAAA;AAAA,iBAYA,sBAAA,CACd,OAA4B;AAAA,iBA+Kd,+BAAA,CACd,QAAA,UACA,IAAA,UACA,MAAA,EAAQ,WAAA,GACP,mBAAA,KAAwB,OAAA,CAAQ,mBAAA;AAAA,iBAgDnB,sBAAA,CACd,IAAA,UACA,OAAA,EAAS,eAAA,EACT,aAAA,EAAe,uBAAA,EACf,QAAA,UACA,IAAA,UACA,OAAA,EAAS,mBAAA,IACT,yBAAA,GACE,IAAA,UACA,OAAA,EAAS,eAAA,EACT,aAAA,EAAe,uBAAA;AAAA,iBA6FH,8BAAA,CACd,SAAA,UACA,QAAA,UACA,IAAA,UACA,KAAA,WACA,OAAA,EAAS,mBAAA,IACT,QAAA,GAAW,IAAA,UAAc,OAAA,EAAS,eAAe"}
|
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
import { isDevelopmentEnvironment } from "../common/env.js";
|
|
2
|
-
import { logger } from "../
|
|
2
|
+
import { logger } from "../common/logger.js";
|
|
3
3
|
import { ELEMENT_TYPE, Fragment } from "../common/jsx.js";
|
|
4
4
|
import { cleanupComponent } from "../runtime/component-cleanup.js";
|
|
5
5
|
import { isPromiseLike } from "../common/promise.js";
|
|
6
6
|
import { mountComponent } from "../runtime/component-internal.js";
|
|
7
|
-
import "../runtime/
|
|
7
|
+
import { DefaultPortal, clearDefaultPortalForInstance } from "../runtime/portal.js";
|
|
8
|
+
import "../runtime/index.js";
|
|
8
9
|
import { cleanupInstancesUnder } from "../renderer/cleanup.js";
|
|
10
|
+
import "../renderer/index.js";
|
|
9
11
|
import { applyHistoryScroll, applyNavigationScroll, saveScrollPosition } from "./navigation-scroll.js";
|
|
10
|
-
import { resolveRouteFromRoutes
|
|
12
|
+
import { resolveRouteFromRoutes } from "./route-matching.js";
|
|
13
|
+
import { resolveRouteRequest } from "./resolution.js";
|
|
11
14
|
import "./route.js";
|
|
12
15
|
import { getCurrentHref, getCurrentPathname, getRegisteredAppsSnapshot, parseTargetUrl, setCurrentRouteLocation, syncAppRegistrationLocation, syncRegisteredRouteSnapshot } from "./navigation-registry.js";
|
|
13
|
-
import { DefaultPortal, clearDefaultPortalForInstance } from "../foundations/structures/portal.js";
|
|
14
16
|
import "../jsx/index.js";
|
|
15
17
|
//#region src/router/navigation-targets.ts
|
|
16
18
|
const MAX_NAVIGATION_REDIRECTS = 20;
|
|
@@ -63,7 +65,7 @@ function wrapRootRouteHandler(componentFn) {
|
|
|
63
65
|
const portalVNode = {
|
|
64
66
|
$$typeof: ELEMENT_TYPE,
|
|
65
67
|
type: DefaultPortal,
|
|
66
|
-
props: {},
|
|
68
|
+
props: { __askrAutoDefaultPortal: true },
|
|
67
69
|
key: "__default_portal"
|
|
68
70
|
};
|
|
69
71
|
return {
|