Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(web): introduce standalone split router (#6727)

dev-rbf98b8c038d94
diff --git a/apps/web/package.json b/apps/web/package.json
index 0a324e663d..b7274ec4b4 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -106,6 +106,7 @@
"@solid-primitives/storage": "^4.3.3",
"@solid-primitives/stream": "^0.7.4",
"@solidjs/router": "^0.15.3",
+ "@standard-schema/spec": "^1.1.0",
"@tailwindcss/vite": "^4.2.4",
"@tanstack/pacer": "^0.17.3",
"@tanstack/solid-query": "5.90.3",
diff --git a/apps/web/src/lib/split-router/README.md b/apps/web/src/lib/split-router/README.md
new file mode 100644
index 0000000000..136d36247a
--- /dev/null
+++ b/apps/web/src/lib/split-router/README.md
@@ -0,0 +1,97 @@
+# Split router
+
+A standalone, route-only router for independently navigable panes. The host supplies
+layout and external-location adapters; application content and resource lifecycles
+stay outside this library.
+
+## Ownership and routes
+
+- Supply one static `SplitRoutes` declaration tree, or an explicit
+ `SplitRoutesManifest`. A router compiles its own manifest once and exposes it as
+ `router.routes`; there is no global runtime cache.
+- `defineRoute()` preserves literal IDs and synchronous Standard Schema param
+ types. Use route-object destinations and `useRouteParams(route)` for typed
+ navigation and reads.
+- Matching follows declaration order, trying canonical patterns before aliases.
+ Schema and child failures backtrack. Formatting always uses canonical paths.
+- Every accepted location has a nonempty, structurally valid match branch.
+ Resolve persisted/legacy data in the host adapter before returning snapshots.
+ Runtime schema outputs are not blindly revalidated as schema inputs.
+- Nested outlets preserve component identity while their match remains stable.
+ Use `remountKey` for intentional resets.
+
+## Search and history
+
+- Raw query values are `Record<string, string[]>`; repeated values retain order.
+ Route namespaces are inherited. URL reads filter unowned namespaces, while
+ explicit writes reject them.
+- `createSearchParams()` binds a synchronous Standard Schema to route-owned raw
+ search. `createSearchParamsCodec()` is the corresponding pure conversion API.
+- Per-pane history belongs to the router. Numeric navigation traverses it;
+ external/browser history restores the complete positional layout.
+- Clearing search retains the route. Ordinary unprefixed external/global search
+ keys remain distinct from namespaced split search.
+
+## Claims
+
+A route may return `{ namespace, id }` from `claim(params)`. Providers are checked
+from the deepest match toward the root; an undefined child claim allows ancestor
+fallback. Claims identify resources independently of URL spelling and search.
+
+### Acquisition policy
+
+Explicit navigation, pane-history traversal, and search changes all check the
+**final middleware-resolved destination**. An already accepted owner is activated
+instead of committing the contender. The contender's pane and history cursor stay
+unchanged. Activation cancels any pending departure of the accepted owner, keeping
+that owner on the requested resource.
+
+Changing search or route parameters without changing the target pane's current
+claim is not a new acquisition. This preserves independently restored duplicates.
+Initial, external, and host-layout reconciliation do not deduplicate entries.
+
+`allowDuplicate` bypasses both accepted-owner checks and pending reservations,
+including on numeric history navigation. It does not override duplicate policy in
+the host layout. Claims currently cover panes within one router, not previews,
+popovers, or other routers.
+
+### Pending requests
+
+Each entry transition tentatively reserves its proposed claim before middleware.
+All contenders still run middleware: an original URL's owner must not prevent a
+redirect to a different resource. Once the destination is resolved, the reservation
+moves to the final claim, releasing the original one.
+
+For a claim with no accepted owner, the first outstanding reservation gets the
+first turn. Later contenders wait, then recheck accepted ownership after the prior
+request commits, redirects, or exits. This avoids duplicate pending opens without
+making completion timing choose the winner. A redirect joins the destination
+claim's existing queue rather than jumping ahead.
+
+Reservations are router-owned and released on completion, failure, cancellation,
+supersession, layout replacement, or disposal. Cleanup belongs to the individual
+transition, so a stale completion cannot release a newer reservation. Middleware
+that ignores abort cannot commit after cancellation. Calls after disposal are
+ignored.
+
+## Middleware and errors
+
+Middleware runs for proposed entries and may redirect synchronously or
+asynchronously. Synchronous navigation stays synchronous when no reservation wait
+is necessary. Signals cancel superseded work; middleware should honor them when
+possible.
+
+Ordinary middleware errors are logged and fall back to the original valid
+proposal, which still passes claim arbitration. Abort errors do not fall back.
+Malformed proposals cannot enter accepted layout/history state. Async transition
+failures are logged and release their reservations.
+
+## Modules
+
+- `routes.ts`, `path.ts`: manifest, matching, params, ownership, and claim derivation.
+- `router.ts`, `transitions.ts`, `claims.ts`: orchestration, cancellation, pending claims.
+- `history.ts`, `layout.ts`, `location-sync.ts`: pane history and host boundaries.
+- `url.ts`, `search.ts`: URL framing and raw search state.
+- `search-params-codec.ts`, `create-search-params.ts`: typed search conversion/binding.
+- `solid.tsx`: providers, hooks, and nested outlets.
+- `integrations/`: memory and Solid Router external-location adapters.
diff --git a/apps/web/src/lib/split-router/claims.ts b/apps/web/src/lib/split-router/claims.ts
new file mode 100644
index 0000000000..80897ffe2b
--- /dev/null
+++ b/apps/web/src/lib/split-router/claims.ts
@@ -0,0 +1,84 @@
+import type { SplitRouteClaim } from './types';
+import { throwIfAborted } from './utils';
+
+export type ClaimReservation = {
+ move(claim: SplitRouteClaim | undefined): void;
+ wait(signal: AbortSignal): void | Promise<void>;
+ release(): void;
+};
+
+/** Pending ownership only. Accepted ownership is read from the host layout. */
+export function createClaimReservations() {
+ type Slot = { key?: string; released: boolean };
+ const queues = new Map<string, Set<Slot>>();
+ const listeners = new Set<() => void>();
+ const notify = () => {
+ for (const listener of [...listeners]) listener();
+ };
+ const remove = (slot: Slot) => {
+ if (slot.key === undefined) return;
+ const queue = queues.get(slot.key);
+ queue?.delete(slot);
+ if (queue?.size === 0) queues.delete(slot.key);
+ slot.key = undefined;
+ };
+
+ return {
+ reserve(claim: SplitRouteClaim | undefined): ClaimReservation {
+ const slot: Slot = { released: false };
+ const ownsTurn = () =>
+ slot.key === undefined ||
+ queues.get(slot.key)?.values().next().value === slot;
+ const reservation: ClaimReservation = {
+ move(next) {
+ if (slot.released) return;
+ const key = next
+ ? JSON.stringify([next.namespace, next.id])
+ : undefined;
+ if (key === slot.key) return;
+ remove(slot);
+ if (key !== undefined) {
+ const queue = queues.get(key) ?? new Set<Slot>();
+ queue.add(slot);
+ queues.set(key, queue);
+ slot.key = key;
+ }
+ notify();
+ },
+ wait(signal) {
+ throwIfAborted(signal);
+ if (ownsTurn()) return;
+ return new Promise<void>((resolve, reject) => {
+ const cleanup = () => {
+ listeners.delete(check);
+ signal.removeEventListener('abort', abort);
+ };
+ const abort = () => {
+ cleanup();
+ reject(
+ signal.reason ?? new DOMException('Aborted', 'AbortError')
+ );
+ };
+ const check = () => {
+ if (signal.aborted) return abort();
+ if (!ownsTurn()) return;
+ cleanup();
+ resolve();
+ };
+ listeners.add(check);
+ signal.addEventListener('abort', abort, { once: true });
+ check();
+ });
+ },
+ release() {
+ if (slot.released) return;
+ slot.released = true;
+ remove(slot);
+ notify();
+ },
+ };
+ reservation.move(claim);
+ return reservation;
+ },
+ };
+}
diff --git a/apps/web/src/lib/split-router/create-search-params.ts b/apps/web/src/lib/split-router/create-search-params.ts
new file mode 100644
index 0000000000..e7e9001dbc
--- /dev/null
+++ b/apps/web/src/lib/split-router/create-search-params.ts
@@ -0,0 +1,76 @@
+import deepEqual from 'fast-deep-equal';
+import { createEffect, createMemo, on } from 'solid-js';
+import {
+ createSearchParamsCodec,
+ type SearchParamsCodecOptions,
+ type SearchParamsRecord,
+} from './search-params-codec';
+import { useSplitRouterScope, useSplitRouterState } from './solid';
+import type { BrowserHistoryIntent } from './types';
+import { reactiveRecord } from './utils';
+
+export type CreateSearchParamsOptions<T extends SearchParamsRecord> =
+ SearchParamsCodecOptions<T> & { namespace: string };
+
+export type SetSearchParamsOptions = {
+ mode?: 'merge' | 'replace';
+ history?: BrowserHistoryIntent;
+};
+
+export type SearchParamsPatch<T extends SearchParamsRecord> = {
+ [Key in keyof T]?: T[Key] | undefined;
+};
+
+export type SetSearchParams<T extends SearchParamsRecord> = (
+ next: SearchParamsPatch<T> | ((current: T) => SearchParamsPatch<T>),
+ options?: SetSearchParamsOptions
+) => void;
+
+export function createSearchParams<T extends SearchParamsRecord>(
+ options: CreateSearchParamsOptions<T>
+): [T, SetSearchParams<T>] {
+ const { router, search } = useSplitRouterState<unknown>();
+ const splitId = useSplitRouterScope<unknown>();
+ const codec = createSearchParamsCodec(options);
+ const raw = () => search(splitId(), options.namespace);
+ const parsed = createMemo(() => codec.parse(raw()));
+
+ createEffect(
+ on([parsed, raw], ([current, rawParams]) => {
+ const canonical = current.valid
+ ? codec.serialize(current.value)
+ : undefined;
+ if (deepEqual(rawParams, canonical)) return;
+ router.updateSearch(splitId(), options.namespace, canonical, {
+ history: 'replace',
+ });
+ })
+ );
+
+ const setParams: SetSearchParams<T> = (next, setOptions = {}) => {
+ const previous = parsed().value;
+ const patch = typeof next === 'function' ? next(previous) : next;
+ const candidate: SearchParamsRecord = {
+ ...(setOptions.mode === 'replace' ? options.defaults : previous),
+ };
+ for (const [key, value] of Object.entries(patch)) {
+ candidate[key] = value === undefined ? options.defaults[key] : value;
+ }
+ const nextValue = codec.validate(candidate);
+ if (!nextValue.success) {
+ console.error(
+ `Invalid search params for namespace "${options.namespace}"`,
+ nextValue.error
+ );
+ return;
+ }
+ router.updateSearch(
+ splitId(),
+ options.namespace,
+ codec.serialize(nextValue.data),
+ { history: setOptions.history }
+ );
+ };
+
+ return [reactiveRecord(() => parsed().value), setParams];
+}
diff --git a/apps/web/src/lib/split-router/history.ts b/apps/web/src/lib/split-router/history.ts
new file mode 100644
index 0000000000..0772bb6b24
--- /dev/null
+++ b/apps/web/src/lib/split-router/history.ts
@@ -0,0 +1,130 @@
+export type SplitRouterHistory<TEntry> = {
+ entries(): readonly TEntry[];
+ index(): number;
+ current(): TEntry;
+ canGo(delta: number): boolean;
+ peek(delta: number): TEntry | undefined;
+ go(delta: number): boolean;
+ push(entry: TEntry): boolean;
+ replace(entry: TEntry): boolean;
+ accept(entry: TEntry, intent: 'push' | 'replace'): boolean;
+};
+
+export function createSplitRouterHistory<TEntry>(
+ initial: TEntry,
+ equals: (left: TEntry, right: TEntry) => boolean
+): SplitRouterHistory<TEntry> {
+ let items = [initial];
+ let currentIndex = 0;
+
+ const targetIndex = (delta: number) => {
+ if (!Number.isSafeInteger(delta) || delta === 0) return;
+
+ const target = currentIndex + delta;
+ return target >= 0 && target < items.length ? target : undefined;
+ };
+
+ return {
+ entries: () => items,
+ index: () => currentIndex,
+ current: () => items[currentIndex]!,
+
+ canGo(delta) {
+ return targetIndex(delta) !== undefined;
+ },
+
+ peek(delta) {
+ const target = targetIndex(delta);
+ return target === undefined ? undefined : items[target];
+ },
+
+ go(delta) {
+ const target = targetIndex(delta);
+ if (target === undefined) return false;
+
+ currentIndex = target;
+ return true;
+ },
+
+ push(entry) {
+ if (equals(items[currentIndex]!, entry)) return false;
+
+ items = [...items.slice(0, currentIndex + 1), entry];
+ currentIndex = items.length - 1;
+ return true;
+ },
+
+ replace(entry) {
+ if (equals(items[currentIndex]!, entry)) return false;
+
+ items = items.with(currentIndex, entry);
+ return true;
+ },
+
+ accept(entry, intent) {
+ if (equals(items[currentIndex]!, entry)) return false;
+
+ const existingIndex = items.findIndex((candidate) =>
+ equals(candidate, entry)
+ );
+ if (existingIndex >= 0) {
+ currentIndex = existingIndex;
+ return true;
+ }
+
+ if (intent === 'replace') {
+ items = items.with(currentIndex, entry);
+ } else {
+ items = [...items.slice(0, currentIndex + 1), entry];
+ currentIndex = items.length - 1;
+ }
+ return true;
+ },
+ };
+}
+
+export function createSplitRouterHistories<TId, TEntry>(
+ equals: (left: TEntry, right: TEntry) => boolean
+) {
+ const histories = new Map<TId, SplitRouterHistory<TEntry>>();
+ let order: TId[] = [];
+
+ return {
+ get: (id: TId) => histories.get(id),
+
+ reconcile(
+ entries: readonly { id: TId; entry: TEntry }[],
+ intent: 'push' | 'replace',
+ mode: 'move' | 'write'
+ ) {
+ const liveIds = new Set(entries.map(({ id }) => id));
+ const nextOrder = entries.map(({ id }) => id);
+
+ entries.forEach(({ id, entry }, index) => {
+ let history = histories.get(id);
+
+ if (!history) {
+ const previousId = order[index];
+ if (previousId !== undefined && !liveIds.has(previousId)) {
+ history = histories.get(previousId);
+ histories.delete(previousId);
+ if (history) histories.set(id, history);
+ }
+ }
+
+ if (history) {
+ if (mode === 'move') history.accept(entry, intent);
+ else if (intent === 'replace') history.replace(entry);
+ else history.push(entry);
+ } else {
+ histories.set(id, createSplitRouterHistory(entry, equals));
+ }
+ });
+
+ for (const id of histories.keys()) {
+ if (!liveIds.has(id)) histories.delete(id);
+ }
+ order = nextOrder;
+ },
+ };
+}
diff --git a/apps/web/src/lib/split-router/index.ts b/apps/web/src/lib/split-router/index.ts
new file mode 100644
index 0000000000..141ec24564
--- /dev/null
+++ b/apps/web/src/lib/split-router/index.ts
@@ -0,0 +1,118 @@
+import { SplitRouter as SplitRouterComponents } from './solid';
+import type { SplitRouter as SplitRouterContract } from './types';
+
+export type SplitRouter<TSplitId> = SplitRouterContract<TSplitId>;
+
+export const SplitRouter = SplitRouterComponents;
+
+export {
+ type CreateSearchParamsOptions,
+ createSearchParams,
+ type SetSearchParams,
+ type SetSearchParamsOptions,
+} from './create-search-params';
+export {
+ createMemorySplitRouterLocation,
+ type MemorySplitRouterLocation,
+} from './integrations/memory';
+export {
+ createSolidRouterLocation,
+ type SolidRouterLocationOptions,
+} from './integrations/solid-router';
+export { runSplitRouterMiddleware } from './middleware';
+export type { RoutePattern } from './path';
+export { createSplitRouter } from './router';
+export {
+ createRoutesManifest,
+ decodeRoute,
+ defineRoute,
+ encodeRoute,
+ filterRouteSearch,
+ getExternalSearchKeys,
+ getRouteClaim,
+ getRouteId,
+ getRouteSearchNamespaces,
+ type RouteParamsCodec,
+ resolveRouteBranch,
+ rootRouteMatch,
+ routeParams,
+ type SplitRouteNode,
+ type SplitRoutesManifest,
+ validateSplitRoutes,
+} from './routes';
+export {
+ createSearchParamsCodec,
+ type SearchParamsCodec,
+ type SearchParamsCodecOptions,
+ type SearchParamsDeserializer,
+ type SearchParamsSchema,
+ type SearchParamsSerializer,
+} from './search-params-codec';
+export {
+ Outlet,
+ Root,
+ Scope,
+ type SplitRouterOutletProps,
+ type SplitRouterRootProps,
+ type SplitRouterScopeProps,
+ useCanGo,
+ useNavigate,
+ useParams,
+ useRouteParams,
+ useSplitHistory,
+ useSplitRouter,
+} from './solid';
+export type {
+ BrowserHistoryIntent,
+ InferSplitRouteParams,
+ SerializedSearchParams,
+ SplitLocation,
+ SplitNavigate,
+ SplitNavigateOptions,
+ SplitNavigateTo,
+ SplitNonRouteNavigateTo,
+ SplitParentNavigationTarget,
+ SplitRouteClaim,
+ SplitRouteDefinition,
+ SplitRouteMatch,
+ SplitRouteNavigationTarget,
+ SplitRouteParams,
+ SplitRouteRawParams,
+ SplitRouterEntry,
+ SplitRouterExternalLocation,
+ SplitRouterExternalLocationValue,
+ SplitRouterHistorySnapshot,
+ SplitRouterLayout,
+ SplitRouterLayoutEntry,
+ SplitRouterLayoutSnapshot,
+ SplitRouterMiddleware,
+ SplitRouterMiddlewareConfig,
+ SplitRouterMiddlewareContext,
+ SplitRouterMiddlewareRedirect,
+ SplitRouterMiddlewareRequest,
+ SplitRouterMiddlewareResult,
+ SplitRouterMiddlewareRun,
+ SplitRouterNavigationCause,
+ SplitRouterOptions,
+ SplitRouterSettledChange,
+ SplitRouteState,
+ SplitRoutes,
+ SplitSearchState,
+ SplitSearchUpdate,
+ SplitSearchUpdateOptions,
+ UnmatchedSplitPathContext,
+ UnmatchedSplitPathHandler,
+} from './types';
+export {
+ type DecodedSplitRouterLocation,
+ decodeRouteLayout,
+ decodeSplitRouterLocation,
+ encodeRouteLayout,
+ externalLocationToString,
+ formatRoutePathname,
+ parseExternalLocation,
+ parseRoutePathname,
+ SPLIT_PATH_SEPARATOR,
+ serializeSplitRouterLocation,
+} from './url';
+export { isSafeName, takeLast } from './utils';
diff --git a/apps/web/src/lib/split-router/integrations/memory.ts b/apps/web/src/lib/split-router/integrations/memory.ts
new file mode 100644
index 0000000000..3ec6ef3b5e
--- /dev/null
+++ b/apps/web/src/lib/split-router/integrations/memory.ts
@@ -0,0 +1,87 @@
+import type {
+ SplitRouterExternalLocation,
+ SplitRouterExternalLocationValue,
+} from '../types';
+import { parseExternalLocation } from '../url';
+
+export interface MemorySplitRouterLocation extends SplitRouterExternalLocation {
+ history(): SplitRouterExternalLocationValue[];
+ index(): number;
+ back(): boolean;
+ forward(): boolean;
+ set(
+ location: string | SplitRouterExternalLocationValue,
+ options?: { replace?: boolean }
+ ): void;
+}
+
+export function createMemorySplitRouterLocation(
+ initial: string | SplitRouterExternalLocationValue = '/'
+): MemorySplitRouterLocation {
+ let entries = [parseExternalLocation(initial)];
+ let currentIndex = 0;
+ const listeners = new Set<
+ (location: SplitRouterExternalLocationValue) => void
+ >();
+
+ const notify = () => {
+ const current = entries[currentIndex]!;
+
+ for (const listener of listeners) listener(current);
+ };
+
+ const commit = (
+ location: SplitRouterExternalLocationValue,
+ replace: boolean
+ ) => {
+ const next = parseExternalLocation(location);
+
+ if (replace) {
+ entries = entries.with(currentIndex, next);
+ } else {
+ entries = [...entries.slice(0, currentIndex + 1), next];
+ currentIndex++;
+ }
+
+ notify();
+ };
+
+ return {
+ read: () => entries[currentIndex]!,
+
+ subscribe(listener) {
+ listeners.add(listener);
+
+ return () => listeners.delete(listener);
+ },
+
+ commit(location, options) {
+ commit(location, options.history === 'replace');
+ },
+
+ history: () => entries,
+ index: () => currentIndex,
+
+ back() {
+ if (currentIndex === 0) return false;
+
+ currentIndex--;
+ notify();
+
+ return true;
+ },
+
+ forward() {
+ if (currentIndex >= entries.length - 1) return false;
+
+ currentIndex++;
+ notify();
+
+ return true;
+ },
+
+ set(location, options = {}) {
+ commit(parseExternalLocation(location), options.replace ?? false);
+ },
+ };
+}
diff --git a/apps/web/src/lib/split-router/integrations/solid-router.ts b/apps/web/src/lib/split-router/integrations/solid-router.ts
new file mode 100644
index 0000000000..90d10df223
--- /dev/null
+++ b/apps/web/src/lib/split-router/integrations/solid-router.ts
@@ -0,0 +1,59 @@
+import { type Accessor, createEffect, createRoot, on } from 'solid-js';
+import type {
+ SplitRouterExternalLocation,
+ SplitRouterExternalLocationValue,
+} from '../types';
+import { externalLocationToString } from '../url';
+
+export type SolidRouterLocationOptions = {
+ pathname: Accessor<string>;
+ search?: Accessor<string>;
+ hash?: Accessor<string>;
+ navigate: (to: string, options: { replace: boolean }) => unknown;
+};
+
+/**
+ * Adapts reactive location accessors without depending on app components or
+ * on a particular Solid Router location object.
+ */
+export function createSolidRouterLocation(
+ options: SolidRouterLocationOptions
+): SplitRouterExternalLocation {
+ const read = (): SplitRouterExternalLocationValue => ({
+ pathname: options.pathname(),
+ search: options.search?.() ?? '',
+ hash: options.hash?.() ?? '',
+ });
+
+ return {
+ read,
+
+ subscribe(listener) {
+ return createRoot((dispose) => {
+ createEffect(
+ on(
+ () => {
+ const location = read();
+
+ return JSON.stringify([
+ location.pathname,
+ location.search,
+ location.hash,
+ ]);
+ },
+ () => listener(read()),
+ { defer: true }
+ )
+ );
+
+ return dispose;
+ });
+ },
+
+ commit(location, commitOptions) {
+ options.navigate(externalLocationToString(location), {
+ replace: commitOptions.history === 'replace',
+ });
+ },
+ };
+}
diff --git a/apps/web/src/lib/split-router/layout.ts b/apps/web/src/lib/split-router/layout.ts
new file mode 100644
index 0000000000..61ddd02e4d
--- /dev/null
+++ b/apps/web/src/lib/split-router/layout.ts
@@ -0,0 +1,111 @@
+import deepEqual from 'fast-deep-equal';
+import { assertRouteEntry, type SplitRoutesManifest } from './routes';
+import type {
+ SplitRouterEntry,
+ SplitRouterLayout,
+ SplitRouterLayoutEntry,
+} from './types';
+
+export function createLayoutAdapter<TSplitId>(
+ layout: SplitRouterLayout<TSplitId>,
+ routes: SplitRoutesManifest
+) {
+ const snapshot = () => {
+ const value = layout.snapshot();
+ for (const entry of value.entries) assertRouteEntry(routes, entry);
+ return value;
+ };
+ const entries = (): SplitRouterEntry[] =>
+ snapshot().entries.map((entry) => ({
+ location: entry.location,
+ }));
+
+ const find = (
+ splitId: TSplitId
+ ): SplitRouterLayoutEntry<TSplitId> | undefined =>
+ snapshot().entries.find((entry) => Object.is(entry.splitId, splitId));
+
+ const entryEquals = (
+ left: SplitRouterEntry | undefined,
+ right: SplitRouterEntry | undefined
+ ): boolean =>
+ left === right ||
+ (left !== undefined &&
+ right !== undefined &&
+ deepEqual(left.location, right.location));
+
+ const layoutsEqual = (
+ left: SplitRouterEntry[],
+ right: SplitRouterEntry[]
+ ): boolean =>
+ left.length === right.length &&
+ left.every((entry, index) => entryEquals(entry, right[index]));
+
+ const changedIds = (
+ before: SplitRouterEntry[],
+ after: SplitRouterEntry[]
+ ): Set<TSplitId> => {
+ const visible = snapshot().entries;
+ const changed = new Set<TSplitId>();
+
+ after.forEach((entry, index) => {
+ if (entryEquals(before[index], entry)) return;
+
+ const splitId = visible[index]?.splitId;
+ if (splitId !== undefined) changed.add(splitId);
+ });
+
+ return changed;
+ };
+
+ const reconcile = (
+ current: SplitRouterEntry[],
+ requested: SplitRouterEntry[]
+ ): boolean => {
+ for (const entry of requested) assertRouteEntry(routes, entry);
+ if (layoutsEqual(current, requested)) return false;
+
+ layout.reconcile(requested);
+ return true;
+ };
+
+ const apply = (options: {
+ entry: SplitRouterEntry;
+ target: TSplitId | 'new-split';
+ replace: boolean;
+ requireExistingTarget?: boolean;
+ }): boolean => {
+ assertRouteEntry(routes, options.entry);
+ const targetId =
+ options.target === 'new-split' ? undefined : options.target;
+ const current = targetId === undefined ? undefined : find(targetId);
+
+ if (options.requireExistingTarget && !current) return false;
+
+ if (targetId !== undefined && current) {
+ if (deepEqual(current.location, options.entry.location)) return false;
+
+ layout.updateCurrentEntry(targetId, () => options.entry);
+ return true;
+ }
+
+ layout.open({
+ location: options.entry.location,
+ target: options.target,
+ replace: options.replace,
+ });
+ return true;
+ };
+
+ return {
+ activate: (splitId: TSplitId) => layout.activate(splitId),
+ apply,
+ changedIds,
+ entries,
+ entryEquals,
+ find,
+ layoutsEqual,
+ reconcile,
+ snapshot,
+ };
+}
diff --git a/apps/web/src/lib/split-router/location-sync.ts b/apps/web/src/lib/split-router/location-sync.ts
new file mode 100644
index 0000000000..ff9b483bfa
--- /dev/null
+++ b/apps/web/src/lib/split-router/location-sync.ts
@@ -0,0 +1,94 @@
+import type { SplitRoutesManifest } from './routes';
+import type {
+ BrowserHistoryIntent,
+ SplitRouterEntry,
+ SplitRouterExternalLocation,
+ SplitRouterExternalLocationValue,
+} from './types';
+import { encodeSplitRouterLocation } from './url';
+
+function externalLocationSignature(
+ location: SplitRouterExternalLocationValue
+): string {
+ const query = [...new URLSearchParams(location.search)].sort(
+ ([leftKey, leftValue], [rightKey, rightValue]) =>
+ leftKey === rightKey
+ ? leftValue.localeCompare(rightValue)
+ : leftKey.localeCompare(rightKey)
+ );
+ const pathname =
+ location.pathname.length > 1
+ ? location.pathname.replace(/\/+$/g, '')
+ : location.pathname || '/';
+
+ return JSON.stringify([pathname, query, location.hash]);
+}
+
+export type LocationSync = {
+ acknowledge(location: SplitRouterExternalLocationValue): boolean;
+ commit(
+ entries: SplitRouterEntry[],
+ options: {
+ history: BrowserHistoryIntent;
+ preserveHash: boolean;
+ preserveExternalSearch?: boolean;
+ }
+ ): void;
+};
+
+export function createLocationSync(options: {
+ routes: SplitRoutesManifest;
+ location: SplitRouterExternalLocation;
+}): LocationSync {
+ const outbound: string[] = [];
+ let desired = options.location.read();
+
+ const commitExternal = (
+ next: SplitRouterExternalLocationValue,
+ history: BrowserHistoryIntent
+ ) => {
+ const signature = externalLocationSignature(next);
+
+ if (
+ signature === externalLocationSignature(options.location.read()) ||
+ outbound.includes(signature)
+ ) {
+ return;
+ }
+
+ outbound.push(signature);
+ options.location.commit(next, { history });
+ };
+
+ return {
+ acknowledge(external) {
+ const signature = externalLocationSignature(external);
+ const index = outbound.indexOf(signature);
+
+ if (index < 0) return false;
+
+ outbound.splice(index, 1);
+
+ const desiredSignature = externalLocationSignature(desired);
+ if (
+ signature !== desiredSignature &&
+ !outbound.includes(desiredSignature)
+ ) {
+ commitExternal(desired, 'replace');
+ }
+
+ return true;
+ },
+
+ commit(entries, commitOptions) {
+ desired = encodeSplitRouterLocation({
+ routes: options.routes,
+ entries,
+ previous: options.location.read(),
+ preserveHash: commitOptions.preserveHash,
+ preserveExternalSearch: commitOptions.preserveExternalSearch,
+ });
+ commitExternal(desired, commitOptions.history);
+ },
+ };
+}
diff --git a/apps/web/src/lib/split-router/middleware.ts b/apps/web/src/lib/split-router/middleware.ts
new file mode 100644
index 0000000000..c535ff0492
--- /dev/null
+++ b/apps/web/src/lib/split-router/middleware.ts
@@ -0,0 +1,166 @@
+import { resolveNavigation } from './navigation';
+import {
+ assertRouteEntry,
+ encodeRoute,
+ type SplitRoutesManifest,
+} from './routes';
+import type {
+ SplitLocation,
+ SplitRouterEntry,
+ SplitRouterMiddlewareConfig,
+ SplitRouterMiddlewareRequest,
+ SplitRouterMiddlewareResult,
+ SplitRouterMiddlewareRun,
+} from './types';
+import { formatRoutePathname } from './url';
+import { isAbortError, isPromise, throwIfAborted } from './utils';
+
+type BatchRequest = {
+ from?: readonly SplitRouterEntry[];
+ to: SplitRouterEntry[];
+ cause: SplitRouterMiddlewareRequest['cause'];
+ signal: AbortSignal;
+};
+
+type PreparedEntries = SplitRouterEntry[] | Promise<SplitRouterEntry[]>;
+
+function withSearch(
+ entry: SplitRouterEntry,
+ search: SplitLocation['search']
+): SplitRouterEntry {
+ if (!search || entry.location.search) return entry;
+
+ return {
+ location: {
+ ...entry.location,
+ search,
+ },
+ };
+}
+
+function entryPath(
+ routes: SplitRoutesManifest,
+ entry: SplitRouterEntry
+): string {
+ return formatRoutePathname(routes, encodeRoute(routes, entry));
+}
+
+/**
+ * Runs one proposed entry through middleware, following redirects safely.
+ * Remains synchronous until a middleware actually returns a Promise.
+ */
+export function runSplitRouterMiddleware(
+ config: SplitRouterMiddlewareConfig,
+ request: SplitRouterMiddlewareRequest
+): SplitRouterMiddlewareRun {
+ const visited = new Set<string>();
+
+ const runEntry = (current: SplitRouterEntry): SplitRouterMiddlewareRun => {
+ throwIfAborted(request.signal);
+ assertRouteEntry(config.routes, current);
+
+ const path = entryPath(config.routes, current);
+ const signature = JSON.stringify([path, current.location.search]);
+ if (visited.has(signature)) {
+ throw new Error(`Split router middleware redirect loop at ${signature}`);
+ }
+ visited.add(signature);
+
+ const handleResult = (
+ result: SplitRouterMiddlewareResult,
+ nextIndex: number
+ ): SplitRouterMiddlewareRun => {
+ throwIfAborted(request.signal);
+
+ if (!result) return runAt(nextIndex);
+
+ const next = resolveNavigation(
+ config.routes,
+ current,
+ current,
+ result.to
+ );
+ if (!next) {
+ throw new Error(
+ `Split router middleware redirected to an invalid route: ${result.to}`
+ );
+ }
+
+ return runEntry(withSearch(next, current.location.search));
+ };
+
+ const runAt = (index: number): SplitRouterMiddlewareRun => {
+ throwIfAborted(request.signal);
+
+ const handler = config.handlers[index];
+ if (!handler) {
+ assertRouteEntry(config.routes, current);
+ return current;
+ }
+
+ const result = handler({
+ from: request.from,
+ to: current,
+ path,
+ cause: request.cause,
+ signal: request.signal,
+ redirect: (to) => ({ type: 'redirect', to }),
+ });
+
+ return isPromise(result)
+ ? result.then((settled) => handleResult(settled, index + 1))
+ : handleResult(result, index + 1);
+ };
+
+ return runAt(0);
+ };
+
+ return runEntry(request.to);
+}
+
+function recoverFailure(
+ error: unknown,
+ config: SplitRouterMiddlewareConfig,
+ request: SplitRouterMiddlewareRequest
+): SplitRouterEntry {
+ if (isAbortError(error, request.signal)) throw error;
+ // Failure recovery must never publish a malformed original proposal.
+ assertRouteEntry(config.routes, request.to);
+
+ console.error('Split router middleware failed; continuing navigation', error);
+ return request.to;
+}
+
+export function prepareEntry(
+ config: SplitRouterMiddlewareConfig,
+ request: SplitRouterMiddlewareRequest
+): SplitRouterMiddlewareRun {
+ assertRouteEntry(config.routes, request.to);
+ try {
+ const prepared = runSplitRouterMiddleware(config, request);
+
+ return isPromise(prepared)
+ ? prepared.catch((error) => recoverFailure(error, config, request))
+ : prepared;
+ } catch (error) {
+ return recoverFailure(error, config, request);
+ }
+}
+
+export function prepareEntries(
+ config: SplitRouterMiddlewareConfig,
+ request: BatchRequest
+): PreparedEntries {
+ const prepared = request.to.map((entry, index) =>
+ prepareEntry(config, {
+ from: request.from?.[index],
+ to: entry,
+ cause: request.cause,
+ signal: request.signal,
+ })
+ );
+
+ return prepared.some(isPromise)
+ ? Promise.all(prepared)
+ : (prepared as SplitRouterEntry[]);
+}
diff --git a/apps/web/src/lib/split-router/navigation.ts b/apps/web/src/lib/split-router/navigation.ts
new file mode 100644
index 0000000000..31745cf8c3
--- /dev/null
+++ b/apps/web/src/lib/split-router/navigation.ts
@@ -0,0 +1,148 @@
+import {
+ decodeRoute,
+ encodeRoute,
+ findRouteBranch,
+ getRouteId,
+ type SplitRoutesManifest,
+} from './routes';
+import { parseSplitSearch } from './search';
+import type {
+ SplitLocation,
+ SplitNavigateTo,
+ SplitRouteParams,
+ SplitRouterEntry,
+ SplitRouteState,
+} from './types';
+import { parseExternalLocation, parseRoutePathname } from './url';
+
+function decodeRouteState(
+ routes: SplitRoutesManifest,
+ route: SplitRouteState
+): SplitRouterEntry | undefined {
+ return decodeRoute(routes, encodeRoute(routes, { location: { route } }));
+}
+
+function resolveRouteTarget(
+ routes: SplitRoutesManifest,
+ current: SplitRouterEntry,
+ target: { route: { id: string }; params?: unknown }
+): SplitRouterEntry | undefined {
+ const routeId = target.route.id;
+ const targetParams =
+ target.params &&
+ typeof target.params === 'object' &&
+ !Array.isArray(target.params)
+ ? (target.params as SplitRouteParams)
+ : {};
+ const branch = findRouteBranch(routes, routeId);
+ if (!branch) return;
+
+ const currentMatches = current.location.route.matches;
+ const matches = branch.map(({ definition }, index) => {
+ const currentMatch = currentMatches[index];
+ const params =
+ currentMatch?.id === definition.id ? currentMatch.params : {};
+
+ return {
+ id: definition.id,
+ params:
+ index === branch.length - 1 ? { ...params, ...targetParams } : params,
+ };
+ });
+
+ const [first, ...rest] = matches;
+ if (!first) return;
+
+ return decodeRouteState(routes, { matches: [first, ...rest] });
+}
+
+function resolveParentTarget(
+ routes: SplitRoutesManifest,
+ current: SplitRouterEntry,
+ levels: number | undefined
+): SplitRouterEntry | undefined {
+ const route = current.location.route;
+ if (route.matches.length === 1) return;
+
+ const count = levels ?? 1;
+ if (!Number.isSafeInteger(count) || count < 1) return;
+
+ const length = Math.max(1, route.matches.length - count);
+ const [first, ...rest] = route.matches.slice(0, length);
+ if (!first) return;
+
+ return decodeRouteState(routes, { matches: [first, ...rest] });
+}
+
+function resolvePathTarget(
+ routes: SplitRoutesManifest,
+ current: SplitRouterEntry,
+ to: string
+):
+ | {
+ entry: SplitRouterEntry;
+ explicitSearch: SplitLocation['search'];
+ }
+ | undefined {
+ const childRelative = to.startsWith('./');
+ const value = childRelative ? to.slice(2) : to;
+ const targetUrl = parseExternalLocation(
+ value.startsWith('/') ? value : `/${value}`
+ );
+ const requested = parseRoutePathname(routes, targetUrl.pathname);
+
+ if (!requested) return;
+
+ let segments: string[];
+ if (value.startsWith('/')) {
+ segments = requested;
+ } else if (childRelative) {
+ segments = [...encodeRoute(routes, current), ...requested];
+ } else if (requested.length > 0) {
+ segments = [encodeRoute(routes, current)[0]!, ...requested];
+ } else {
+ segments = encodeRoute(routes, current);
+ }
+
+ const entry = decodeRoute(routes, segments);
+ if (!entry) return;
+
+ return {
+ entry,
+ explicitSearch: parseSplitSearch(targetUrl.search).get(0),
+ };
+}
+
+export function resolveNavigation(
+ routes: SplitRoutesManifest,
+ current: SplitRouterEntry,
+ target: SplitRouterEntry | undefined,
+ to: Exclude<SplitNavigateTo, number>
+): SplitRouterEntry | undefined {
+ const resolved =
+ typeof to === 'string'
+ ? resolvePathTarget(routes, current, to)
+ : 'route' in to
+ ? {
+ entry: resolveRouteTarget(routes, current, to),
+ explicitSearch: undefined,
+ }
+ : {
+ entry: resolveParentTarget(routes, current, to.levels),
+ explicitSearch: undefined,
+ };
+ const decoded = resolved?.entry;
+ if (!decoded) return;
+
+ const matchingRoute = target && getRouteId(target) === getRouteId(decoded);
+ let search = resolved.explicitSearch;
+
+ if (!search && matchingRoute) search = target.location.search;
+
+ return {
+ location: {
+ ...decoded.location,
+ ...(search ? { search } : {}),
+ },
+ };
+}
diff --git a/apps/web/src/lib/split-router/path.ts b/apps/web/src/lib/split-router/path.ts
new file mode 100644
index 0000000000..27fd319e3c
--- /dev/null
+++ b/apps/web/src/lib/split-router/path.ts
@@ -0,0 +1,169 @@
+import type { SplitRouteParams, SplitRouteRawParams } from './types';
+
+type PathToken =
+ | { type: 'static'; value: string }
+ | { type: 'param'; name: string; optional: boolean }
+ | { type: 'catchAll'; name: string };
+
+type PatternMatch = {
+ params: SplitRouteRawParams;
+ consumed: number;
+};
+
+const PARAM_NAME = /^[A-Za-z][A-Za-z0-9_]*$/;
+
+function patternSegments(pattern: string): string[] {
+ return pattern
+ .replace(/^\/+|\/+$/g, '')
+ .split('/')
+ .filter(Boolean);
+}
+
+function routePatternTokens(pattern: string): readonly PathToken[] {
+ const tokens = patternSegments(pattern).map((segment): PathToken => {
+ if (segment.startsWith(':')) {
+ const optional = segment.endsWith('?');
+ const name = segment.slice(1, optional ? -1 : undefined);
+ if (!PARAM_NAME.test(name)) {
+ throw new Error(`Invalid split route parameter "${segment}"`);
+ }
+ return { type: 'param', name, optional };
+ }
+
+ if (segment.startsWith('*')) {
+ const name = segment.slice(1);
+ if (!PARAM_NAME.test(name)) {
+ throw new Error(`Invalid split route catch-all parameter "${segment}"`);
+ }
+ return { type: 'catchAll', name };
+ }
+
+ if (segment === '~') {
+ throw new Error(`Invalid split route path "${pattern}"`);
+ }
+
+ return { type: 'static', value: segment };
+ });
+
+ const catchAllIndex = tokens.findIndex((token) => token.type === 'catchAll');
+ if (catchAllIndex >= 0 && catchAllIndex !== tokens.length - 1) {
+ throw new Error(
+ `Split route catch-all parameter must be the final segment in "${pattern}"`
+ );
+ }
+
+ return tokens;
+}
+
+export type RoutePattern = {
+ match(segments: readonly string[]): IterableIterator<PatternMatch>;
+ format(params: SplitRouteParams): string[];
+};
+
+export function compileRoutePattern(options: {
+ path: string;
+ aliases?: readonly string[];
+}): RoutePattern {
+ const canonical = routePatternTokens(options.path);
+ const alternatives = [
+ canonical,
+ ...(options.aliases ?? []).map(routePatternTokens),
+ ];
+ return {
+ *match(segments) {
+ // Stay lazy: only try aliases if canonical matching/validation/children fail.
+ for (const tokens of alternatives) yield* matchTokens(tokens, segments);
+ },
+ format: (params) => formatTokens(canonical, params),
+ };
+}
+
+function matchTokens(
+ tokens: readonly PathToken[],
+ segments: readonly string[]
+): PatternMatch[] {
+ const matches: PatternMatch[] = [];
+
+ const visit = (
+ tokenIndex: number,
+ segmentIndex: number,
+ params: SplitRouteRawParams
+ ) => {
+ const token = tokens[tokenIndex];
+ if (!token) {
+ matches.push({ params, consumed: segmentIndex });
+ return;
+ }
+
+ if (token.type === 'static') {
+ if (segments[segmentIndex] !== token.value) return;
+ visit(tokenIndex + 1, segmentIndex + 1, params);
+ return;
+ }
+
+ if (token.type === 'catchAll') {
+ const value = segments.slice(segmentIndex);
+ if (value.length === 0) return;
+ visit(tokens.length, segments.length, { ...params, [token.name]: value });
+ return;
+ }
+
+ const value = segments[segmentIndex];
+ if (value !== undefined) {
+ visit(tokenIndex + 1, segmentIndex + 1, {
+ ...params,
+ [token.name]: value,
+ });
+ }
+ if (token.optional) visit(tokenIndex + 1, segmentIndex, params);
+ };
+
+ visit(0, 0, {});
+ return matches;
+}
+
+function serializeValue(value: unknown, name: string): string {
+ if (
+ typeof value === 'string' ||
+ typeof value === 'number' ||
+ typeof value === 'boolean' ||
+ typeof value === 'bigint'
+ ) {
+ return String(value);
+ }
+
+ throw new Error(`Split route parameter "${name}" requires serializeParams`);
+}
+
+function formatTokens(
+ tokens: readonly PathToken[],
+ params: SplitRouteParams
+): string[] {
+ const segments: string[] = [];
+
+ for (const token of tokens) {
+ if (token.type === 'static') {
+ segments.push(token.value);
+ continue;
+ }
+
+ const value = params[token.name];
+ if (token.type === 'catchAll') {
+ if (!Array.isArray(value) || value.length === 0) {
+ throw new Error(
+ `Missing split route catch-all parameter "${token.name}"`
+ );
+ }
+ segments.push(...value.map((item) => serializeValue(item, token.name)));
+ continue;
+ }
+
+ if (value === undefined) {
+ if (token.optional) continue;
+ throw new Error(`Missing split route parameter "${token.name}"`);
+ }
+ segments.push(serializeValue(value, token.name));
+ }
+
+ return segments;
+}
diff --git a/apps/web/src/lib/split-router/router.ts b/apps/web/src/lib/split-router/router.ts
new file mode 100644
index 0000000000..0a1b3b62cc
--- /dev/null
+++ b/apps/web/src/lib/split-router/router.ts
@@ -0,0 +1,678 @@
+import deepEqual from 'fast-deep-equal';
+import { createClaimReservations } from './claims';
+import { createSplitRouterHistories } from './history';
+import { createLayoutAdapter } from './layout';
+import { createLocationSync } from './location-sync';
+import { prepareEntries, prepareEntry } from './middleware';
+import { resolveNavigation } from './navigation';
+import {
+ assertRouteEntry,
+ assertSearchNamespacesAllowed,
+ createRoutesManifest,
+ getRouteClaim,
+} from './routes';
+import { assertSafeSearchName, updateSearchState } from './search';
+import { createTransitionManager } from './transitions';
+import type {
+ BrowserHistoryIntent,
+ SplitNavigateOptions,
+ SplitNavigateTo,
+ SplitRouteClaim,
+ SplitRouter,
+ SplitRouterEntry,
+ SplitRouterExternalLocationValue,
+ SplitRouterOptions,
+} from './types';
+import { decodeSplitRouterLocation, serializeSplitRouterLocation } from './url';
+import { isPromise, throwIfAborted } from './utils';
+
+type CommitOptions = {
+ history: BrowserHistoryIntent;
+ preserveHash: boolean;
+ preserveExternalSearch?: boolean;
+};
+
+type LayoutTransition = {
+ entries: SplitRouterEntry[];
+ cause: 'initial' | 'external' | 'layout';
+ apply: (entries: SplitRouterEntry[]) => void;
+};
+
+type ApplyOptions<TSplitId> = {
+ entry: SplitRouterEntry;
+ target: TSplitId | 'new-split';
+ replace: boolean;
+ history: BrowserHistoryIntent;
+ preserveHash: boolean;
+ requireTarget?: boolean;
+ recordHistory?: boolean;
+};
+
+type EntryTransition<TSplitId> = {
+ key: unknown;
+ splitId?: TSplitId;
+ entry: SplitRouterEntry;
+ from: SplitRouterEntry | undefined;
+ cause: 'navigate' | 'history' | 'search';
+ allowDuplicate?: boolean;
+ apply: (entry: SplitRouterEntry) => boolean;
+};
+
+const GLOBAL_TRANSITION = Symbol('split-router-global-transition');
+
+export function createSplitRouter<TSplitId>(
+ options: SplitRouterOptions<TSplitId>
+): SplitRouter<TSplitId> {
+ const routes =
+ 'definitions' in options.routes
+ ? createRoutesManifest(options.routes)
+ : options.routes;
+
+ const middleware = options.middleware ?? [];
+ const claims = createClaimReservations();
+ const entryControllers = new Map<unknown, AbortController>();
+ const subscribers = new Set<(splitId: TSplitId | undefined) => void>();
+ let accepted: SplitRouterEntry[] = [];
+ let expectedLayout: SplitRouterEntry[] | undefined;
+ let layoutChangeQueued = false;
+ let queuedHistory: BrowserHistoryIntent = 'push';
+ let ready = false;
+ let disposed = false;
+
+ const locationSync = createLocationSync({
+ routes,
+ location: options.location,
+ });
+ const middlewareConfig = { routes, handlers: middleware };
+ const layout = createLayoutAdapter(options.layout, routes);
+ const histories = createSplitRouterHistories<TSplitId, SplitRouterEntry>(
+ layout.entryEquals
+ );
+
+ const reconcileHistories = (
+ intent: BrowserHistoryIntent,
+ mode: 'move' | 'write'
+ ) => {
+ histories.reconcile(
+ layout.snapshot().entries.map(({ splitId, location }) => ({
+ id: splitId,
+ entry: { location },
+ })),
+ intent,
+ mode
+ );
+ };
+
+ const notify = (splitId?: TSplitId) => {
+ for (const listener of subscribers) listener(splitId);
+ };
+
+ const transitions = createTransitionManager<TSplitId, SplitRouterEntry>({
+ onError(error) {
+ console.error('Split router transition failed', error);
+ },
+ onSettled(splitId, publicStateChanged) {
+ const becameReady = !ready;
+ ready = true;
+ if (becameReady) notify();
+ else if (publicStateChanged) notify(splitId);
+ },
+ });
+ const findEntry = (splitId: TSplitId) =>
+ transitions.pending(splitId) ?? layout.find(splitId);
+
+ const findClaimedSplit = (
+ claim: SplitRouteClaim,
+ targetId: TSplitId | undefined
+ ) =>
+ layout
+ .snapshot()
+ .entries.find(
+ (candidate) =>
+ !Object.is(candidate.splitId, targetId) &&
+ deepEqual(getRouteClaim(routes, candidate.location.route), claim)
+ );
+
+ const claimToAcquire = (
+ entry: SplitRouterEntry,
+ config: EntryTransition<TSplitId>
+ ) => {
+ if (config.allowDuplicate) return;
+ const claim = getRouteClaim(routes, entry.location.route);
+ const current =
+ config.splitId === undefined ? undefined : layout.find(config.splitId);
+ // Updating an existing owner is not a new acquisition. In particular,
+ // search/parameter updates must not collapse restored duplicate panes.
+ if (
+ current &&
+ deepEqual(getRouteClaim(routes, current.location.route), claim)
+ )
+ return;
+ return claim;
+ };
+
+ const notifyLayoutChanges = (
+ before: SplitRouterEntry[],
+ after: SplitRouterEntry[]
+ ) => {
+ for (const splitId of layout.changedIds(before, after)) {
+ notify(splitId);
+ }
+ };
+
+ const expectLayoutEcho = () => {
+ expectedLayout = layout.entries();
+ };
+
+ const reconcileEntries = (
+ current: SplitRouterEntry[],
+ requested: SplitRouterEntry[]
+ ): boolean => {
+ if (!layout.reconcile(current, requested)) {
+ return false;
+ }
+
+ expectLayoutEcho();
+ return true;
+ };
+
+ const commitLayout = (commit: CommitOptions) => {
+ locationSync.commit(layout.entries(), commit);
+ };
+
+ const abortAllTransitions = (publish = true) => {
+ for (const controller of [...entryControllers.values()]) controller.abort();
+ const hadPendingEntries = transitions.abortAll();
+ if (publish && hadPendingEntries) notify();
+ };
+
+ const cancelTargetTransition = (key: unknown) => {
+ if (transitions.has(GLOBAL_TRANSITION)) abortAllTransitions();
+ entryControllers.get(key)?.abort();
+ transitions.cancel(key);
+ };
+
+ const applyDecoded = (entries: SplitRouterEntry[]) => {
+ const layoutChanged = reconcileEntries(layout.entries(), entries);
+ accepted = layout.entries();
+ reconcileHistories('replace', 'move');
+ commitLayout({ history: 'replace', preserveHash: true });
+ const becameReady = !ready;
+ ready = true;
+ if (layoutChanged || becameReady) notify();
+ };
+
+ const transitionLayout = (transition: LayoutTransition) => {
+ abortAllTransitions();
+ if (middleware.length === 0) {
+ transition.apply(transition.entries);
+ return;
+ }
+
+ const controller = new AbortController();
+ const prepared = prepareEntries(middlewareConfig, {
+ from: transition.cause === 'initial' ? undefined : accepted,
+ to: transition.entries,
+ cause: transition.cause,
+ signal: controller.signal,
+ });
+
+ if (!isPromise(prepared)) {
+ transition.apply(prepared);
+ return;
+ }
+
+ void transitions.start(GLOBAL_TRANSITION, {
+ controller,
+ async run() {
+ const result = await prepared;
+ throwIfAborted(controller.signal);
+ transition.apply(result);
+ },
+ });
+ };
+
+ const applyInbound = (
+ external: SplitRouterExternalLocationValue,
+ cause: 'initial' | 'external'
+ ) => {
+ if (cause === 'external' && locationSync.acknowledge(external)) return;
+
+ const decoded = decodeSplitRouterLocation({
+ routes,
+ location: external,
+ });
+
+ transitionLayout({
+ entries: decoded.entries,
+ cause,
+ apply: applyDecoded,
+ });
+ };
+
+ accepted = layout.entries();
+ applyInbound(options.location.read(), 'initial');
+
+ const applyPrepared = (
+ original: SplitRouterEntry[],
+ prepared: SplitRouterEntry[],
+ history: BrowserHistoryIntent
+ ) => {
+ const before = accepted;
+
+ reconcileEntries(original, prepared);
+ accepted = layout.entries();
+ reconcileHistories(history, 'move');
+ commitLayout({
+ history,
+ preserveHash: false,
+ preserveExternalSearch: false,
+ });
+ notifyLayoutChanges(before, accepted);
+ };
+
+ const onLayoutChange = (history: BrowserHistoryIntent) => {
+ if (disposed) return;
+
+ const entries = layout.entries();
+ if (expectedLayout && layout.layoutsEqual(expectedLayout, entries)) {
+ expectedLayout = undefined;
+ accepted = entries;
+ return;
+ }
+ expectedLayout = undefined;
+
+ transitionLayout({
+ entries,
+ cause: 'layout',
+ apply: (prepared) => applyPrepared(entries, prepared, history),
+ });
+ };
+
+ const applyEntry = (config: ApplyOptions<TSplitId>): boolean => {
+ const changed = layout.apply({
+ entry: config.entry,
+ target: config.target,
+ replace: config.replace,
+ requireExistingTarget: config.requireTarget,
+ });
+ if (!changed) return false;
+
+ expectLayoutEcho();
+ accepted = layout.entries();
+ if (config.recordHistory !== false) {
+ reconcileHistories(config.history, 'write');
+ }
+ commitLayout({
+ history: config.history,
+ preserveHash: config.preserveHash,
+ preserveExternalSearch: false,
+ });
+ return true;
+ };
+
+ const publishEntry = (
+ transition: EntryTransition<TSplitId>,
+ entry: SplitRouterEntry
+ ) => {
+ const changed = transition.apply(entry);
+ if (changed) notify(transition.splitId);
+ return changed;
+ };
+
+ const startAsyncEntry = (
+ config: EntryTransition<TSplitId>,
+ controller: AbortController,
+ prepared: Promise<SplitRouterEntry | undefined>,
+ finish: () => void,
+ checkClaim: (entry: SplitRouterEntry) => SplitRouterEntry | undefined
+ ) => {
+ const { splitId } = config;
+
+ void transitions.start(config.key, {
+ controller,
+ target: splitId,
+ pending: splitId === undefined ? undefined : config.entry,
+ async run(transition) {
+ try {
+ const entry = await prepared;
+ throwIfAborted(controller.signal);
+ if (!entry) return;
+ assertRouteEntry(routes, entry);
+
+ if (
+ splitId !== undefined &&
+ !layout.entryEquals(transition.pending, entry)
+ ) {
+ transition.pending = entry;
+ notify(splitId);
+ }
+
+ // Pending-state subscribers may navigate or create another owner.
+ // Recheck synchronously at the actual commit boundary.
+ throwIfAborted(controller.signal);
+ if (!checkClaim(entry)) return;
+ throwIfAborted(controller.signal);
+ const changed = config.apply(entry);
+ if (changed && splitId === undefined) notify();
+ } finally {
+ finish();
+ }
+ },
+ onSettled:
+ splitId === undefined
+ ? undefined
+ : (transition) =>
+ !layout.entryEquals(transition.pending, layout.find(splitId)),
+ });
+
+ if (splitId !== undefined) notify(splitId);
+ };
+
+ const transitionEntry = (config: EntryTransition<TSplitId>) => {
+ const hadPending = transitions.pending(config.key) !== undefined;
+ cancelTargetTransition(config.key);
+ const controller = new AbortController();
+ const reservation = claims.reserve(undefined);
+ entryControllers.set(config.key, controller);
+ const finish = () => {
+ reservation.release();
+ controller.signal.removeEventListener('abort', finish);
+ if (entryControllers.get(config.key) === controller) {
+ entryControllers.delete(config.key);
+ }
+ };
+ controller.signal.addEventListener('abort', finish, { once: true });
+
+ const reuseOrAccept = (
+ entry: SplitRouterEntry,
+ claim: SplitRouteClaim | undefined
+ ) => {
+ throwIfAborted(controller.signal);
+ const owner = claim && findClaimedSplit(claim, config.splitId);
+ if (!owner) return entry;
+ // Keep the accepted owner on the requested resource rather than allowing
+ // an in-flight departure to replace it immediately after activation.
+ const hadPending = transitions.pending(owner.splitId) !== undefined;
+ cancelTargetTransition(owner.splitId);
+ layout.activate(owner.splitId);
+ if (hadPending) notify(owner.splitId);
+ };
+ const waitForClaim = async (
+ turn: Promise<void>,
+ entry: SplitRouterEntry,
+ claim: SplitRouteClaim | undefined
+ ) => {
+ await turn;
+ // The earlier request may have committed, redirected, or failed.
+ return reuseOrAccept(entry, claim);
+ };
+ const accept = (entry: SplitRouterEntry) => {
+ throwIfAborted(controller.signal);
+ assertRouteEntry(routes, entry);
+ const claim = claimToAcquire(entry, config);
+ reservation.move(claim);
+ if (claim && findClaimedSplit(claim, config.splitId)) {
+ return reuseOrAccept(entry, claim);
+ }
+ const turn = reservation.wait(controller.signal);
+ if (!isPromise(turn)) return reuseOrAccept(entry, claim);
+ return waitForClaim(turn, entry, claim);
+ };
+ const acceptPrepared = async (prepared: Promise<SplitRouterEntry>) =>
+ accept(await prepared);
+
+ try {
+ reservation.move(claimToAcquire(config.entry, config));
+ const prepared =
+ middleware.length === 0
+ ? config.entry
+ : prepareEntry(middlewareConfig, {
+ from: config.from,
+ to: config.entry,
+ cause: config.cause,
+ signal: controller.signal,
+ });
+ const resolved = isPromise(prepared)
+ ? acceptPrepared(prepared)
+ : accept(prepared);
+ if (isPromise(resolved)) {
+ assertRouteEntry(routes, config.entry);
+ startAsyncEntry(config, controller, resolved, finish, (entry) =>
+ reuseOrAccept(entry, claimToAcquire(entry, config))
+ );
+ } else {
+ try {
+ const changed = resolved ? publishEntry(config, resolved) : false;
+ if (!changed && hadPending) notify(config.splitId);
+ } finally {
+ finish();
+ }
+ }
+ } catch (error) {
+ finish();
+ if (hadPending) notify(config.splitId);
+ throw error;
+ }
+ };
+
+ const navigateHistory = (
+ splitId: TSplitId,
+ delta: number,
+ current: SplitRouterEntry,
+ navigateOptions: SplitNavigateOptions<TSplitId>
+ ) => {
+ if (
+ (navigateOptions.target !== undefined &&
+ navigateOptions.target !== 'current') ||
+ navigateOptions.search !== undefined
+ ) {
+ return;
+ }
+
+ const history = histories.get(splitId);
+ const historical = history?.peek(delta);
+ if (!history || !historical) return;
+
+ transitionEntry({
+ key: splitId,
+ splitId,
+ entry: historical,
+ from: current,
+ cause: 'history',
+ allowDuplicate: navigateOptions.allowDuplicate,
+ apply: (entry) => {
+ if (!layout.find(splitId)) return false;
+
+ const changed = applyEntry({
+ entry,
+ target: splitId,
+ replace: true,
+ history: 'replace',
+ preserveHash: true,
+ requireTarget: true,
+ recordHistory: false,
+ });
+ const moved = history.go(delta);
+ if (moved && !layout.entryEquals(history.current(), entry)) {
+ history.replace(entry);
+ }
+ reconcileHistories('replace', 'write');
+
+ return changed || moved;
+ },
+ });
+ };
+
+ const unsubscribeLayout = options.layout.subscribe((change) => {
+ queuedHistory = change.history;
+ if (layoutChangeQueued) return;
+
+ layoutChangeQueued = true;
+ queueMicrotask(() => {
+ layoutChangeQueued = false;
+ onLayoutChange(queuedHistory);
+ });
+ });
+ const unsubscribeLocation = options.location.subscribe((external) =>
+ applyInbound(external, 'external')
+ );
+
+ const router: SplitRouter<TSplitId> = {
+ routes,
+ route(splitId) {
+ const entry = findEntry(splitId);
+ return entry?.location.route;
+ },
+
+ location: (splitId) => findEntry(splitId)?.location,
+
+ search(splitId, namespace) {
+ assertSafeSearchName(namespace, 'namespace');
+
+ return findEntry(splitId)?.location?.search?.[namespace];
+ },
+
+ canGo(splitId, delta) {
+ return histories.get(splitId)?.canGo(delta) ?? false;
+ },
+
+ history(splitId) {
+ const history = histories.get(splitId);
+ if (!history) return;
+
+ return {
+ entries: history.entries().map((entry) => entry.location),
+ index: history.index(),
+ };
+ },
+
+ navigate(
+ splitId: TSplitId,
+ to: SplitNavigateTo,
+ navigateOptions: SplitNavigateOptions<TSplitId> = {}
+ ) {
+ if (disposed) return;
+ const current = findEntry(splitId);
+
+ if (!current) return;
+
+ if (typeof to === 'number') {
+ navigateHistory(splitId, to, current, navigateOptions);
+ return;
+ }
+
+ const target =
+ navigateOptions.target === undefined ||
+ navigateOptions.target === 'current'
+ ? splitId
+ : navigateOptions.target;
+ const targetEntry =
+ target === 'new-split' ? undefined : findEntry(target);
+ const decoded = resolveNavigation(routes, current, targetEntry, to);
+
+ if (!decoded) return;
+
+ assertSearchNamespacesAllowed(
+ routes,
+ decoded.location.route,
+ Object.keys(navigateOptions.search ?? {})
+ );
+
+ const next: SplitRouterEntry = {
+ location: updateSearchState(decoded.location, navigateOptions.search),
+ };
+ const history = navigateOptions.replace ? 'replace' : 'push';
+ const targetId =
+ target === 'new-split' ? undefined : (target as TSplitId);
+ transitionEntry({
+ key: targetId ?? Symbol('new-split-transition'),
+ splitId: targetId,
+ entry: next,
+ from: targetEntry,
+ cause: 'navigate',
+ allowDuplicate: navigateOptions.allowDuplicate,
+ apply: (entry) =>
+ applyEntry({
+ entry,
+ target,
+ replace: navigateOptions.replace ?? false,
+ history,
+ preserveHash: false,
+ }),
+ });
+ },
+
+ updateSearch(splitId, namespace, update, updateOptions = {}) {
+ if (disposed) return;
+ assertSafeSearchName(namespace, 'namespace');
+ const entry = findEntry(splitId);
+ if (!entry) return;
+ assertSearchNamespacesAllowed(routes, entry.location.route, [namespace]);
+
+ const next: SplitRouterEntry = {
+ location: updateSearchState(entry.location, {
+ [namespace]: update,
+ }),
+ };
+ const history = updateOptions.history ?? 'push';
+
+ transitionEntry({
+ key: splitId,
+ splitId,
+ entry: next,
+ from: entry,
+ cause: 'search',
+ apply: (prepared) =>
+ applyEntry({
+ entry: prepared,
+ target: splitId,
+ replace: history === 'replace',
+ history,
+ preserveHash: true,
+ requireTarget: true,
+ }),
+ });
+ },
+
+ href(splitId) {
+ const entry = findEntry(splitId);
+
+ if (!entry) return '';
+
+ return serializeSplitRouterLocation({
+ routes,
+ entries: [entry],
+ previous: options.location.read(),
+ preserveHash: true,
+ });
+ },
+
+ isReady: () => ready,
+
+ async settled() {
+ do {
+ await Promise.resolve();
+ await Promise.all(transitions.promises());
+ } while (layoutChangeQueued || transitions.size > 0);
+ },
+
+ subscribe(listener) {
+ subscribers.add(listener);
+
+ return () => subscribers.delete(listener);
+ },
+
+ dispose() {
+ if (disposed) return;
+
+ disposed = true;
+ subscribers.clear();
+ abortAllTransitions(false);
+ unsubscribeLayout();
+ unsubscribeLocation();
+ },
+ };
+
+ return router;
+}
diff --git a/apps/web/src/lib/split-router/routes.ts b/apps/web/src/lib/split-router/routes.ts
new file mode 100644
index 0000000000..ce1bb622ef
--- /dev/null
+++ b/apps/web/src/lib/split-router/routes.ts
@@ -0,0 +1,419 @@
+import type { StandardSchemaV1 } from '@standard-schema/spec';
+import { compileRoutePattern, type RoutePattern } from './path';
+import { assertSafeSearchName } from './search';
+import type {
+ SplitRouteClaim,
+ SplitRouteDefinition,
+ SplitRouteMatch,
+ SplitRouteParams,
+ SplitRouteRawParams,
+ SplitRouterEntry,
+ SplitRouteState,
+ SplitRoutes,
+ SplitSearchState,
+ UnmatchedSplitPathHandler,
+} from './types';
+import { isRecord, isSafeName, takeLast } from './utils';
+
+type SplitRouteDefinitionConstraint = {
+ id: string;
+ path: string;
+ aliases?: readonly string[];
+ component?: unknown;
+ children?: readonly SplitRouteDefinitionConstraint[];
+ params?: StandardSchemaV1;
+ serializeParams?: unknown;
+ claim?: unknown;
+ search?: readonly string[] | '*';
+ externalSearch?: readonly string[] | ((entry: never) => readonly string[]);
+ remountKey?: (params: never) => string | number | undefined;
+};
+
+export function defineRoute<
+ const TParamsSchema extends StandardSchemaV1,
+ const TDefinition extends SplitRouteDefinitionConstraint,
+>(
+ definition: TDefinition & {
+ params: TParamsSchema;
+ serializeParams?: (
+ params: StandardSchemaV1.InferOutput<TParamsSchema>
+ ) => SplitRouteRawParams;
+ claim?: (
+ params: StandardSchemaV1.InferOutput<TParamsSchema>
+ ) => SplitRouteClaim | undefined;
+ }
+): TDefinition & {
+ params: TParamsSchema;
+ serializeParams?: (
+ params: StandardSchemaV1.InferOutput<TParamsSchema>
+ ) => SplitRouteRawParams;
+ claim?: (
+ params: StandardSchemaV1.InferOutput<TParamsSchema>
+ ) => SplitRouteClaim | undefined;
+};
+export function defineRoute<
+ const TDefinition extends SplitRouteDefinitionConstraint,
+>(definition: TDefinition & { params?: undefined }): TDefinition;
+export function defineRoute(
+ definition: SplitRouteDefinitionConstraint
+): SplitRouteDefinitionConstraint {
+ return definition;
+}
+
+export type RouteParamsCodec = {
+ parse(params: SplitRouteRawParams): SplitRouteParams | undefined;
+ serialize(params: SplitRouteParams): SplitRouteParams;
+};
+
+function createRouteParamsCodec(
+ definition: SplitRouteDefinition
+): RouteParamsCodec {
+ const schema = definition.params;
+ const serialize = definition.serializeParams?.bind(definition);
+ return {
+ parse: (params) => validateRouteParams(schema, params),
+ // Without a custom serializer, the pattern encodes its primitive fields.
+ serialize: (params) => serialize?.(params) ?? params,
+ };
+}
+
+export type SplitRouteNode<TComponent = unknown> = {
+ readonly definition: SplitRouteDefinition<TComponent>;
+ readonly parent?: SplitRouteNode<TComponent>;
+ readonly branch: readonly SplitRouteNode<TComponent>[];
+ readonly pattern: RoutePattern;
+ readonly params: RouteParamsCodec;
+ readonly children: readonly SplitRouteNode<TComponent>[];
+ readonly search: ReadonlySet<string>;
+ readonly claims: readonly SplitRouteDefinition<TComponent>[];
+ readonly externalSearch: readonly SplitRouteDefinition<TComponent>[];
+};
+
+/** Runtime route state owned by a router, or explicitly supplied by its host. */
+export type SplitRoutesManifest<TComponent = unknown> = {
+ readonly roots: readonly SplitRouteNode<TComponent>[];
+ readonly byId: ReadonlyMap<string, SplitRouteNode<TComponent>>;
+ readonly basePath: readonly string[];
+ readonly globalSearch: ReadonlySet<string>;
+ readonly unmatchedPathHandlers: readonly UnmatchedSplitPathHandler[];
+ readonly defaultEntry?: SplitRoutes['defaultEntry'];
+};
+
+function routeSearchNamespaces(
+ search: SplitRouteDefinition['search']
+): Set<string> {
+ if (search === '*') return new Set(['*']);
+ const namespaces = new Set<string>();
+ for (const namespace of search ?? []) {
+ assertSafeSearchName(namespace, 'namespace');
+ if (namespaces.has(namespace)) {
+ throw new Error(`Duplicate split route search namespace "${namespace}"`);
+ }
+ namespaces.add(namespace);
+ }
+ return namespaces;
+}
+
+/** Compile static definitions into independent, caller-owned runtime state. */
+export function createRoutesManifest<TComponent>(
+ routes: SplitRoutes<TComponent>
+): SplitRoutesManifest<TComponent> {
+ const byId = new Map<string, SplitRouteNode<TComponent>>();
+ const globalSearch = new Set(routes.globalSearch ?? []);
+ for (const key of globalSearch) {
+ if (!isSafeName(key)) {
+ throw new Error(`Invalid global search key "${key}"`);
+ }
+ }
+
+ const visit = (
+ definitions: readonly SplitRouteDefinition<TComponent>[],
+ parent?: SplitRouteNode<TComponent>
+ ): SplitRouteNode<TComponent>[] => {
+ const siblingPaths = new Set<string>();
+ return definitions.map((definition) => {
+ if (!isSafeName(definition.id)) {
+ throw new Error(`Invalid split route id "${definition.id}"`);
+ }
+ if (byId.has(definition.id)) {
+ throw new Error(`Duplicate split route id "${definition.id}"`);
+ }
+
+ for (const path of [definition.path, ...(definition.aliases ?? [])]) {
+ if (!path) throw new Error(`Invalid split route path "${path}"`);
+ const normalized = path.replace(/^\/+|\/+$/g, '');
+ if (siblingPaths.has(normalized)) {
+ throw new Error(`Duplicate sibling split route path "${normalized}"`);
+ }
+ siblingPaths.add(normalized);
+ }
+
+ const namespaces = routeSearchNamespaces(definition.search);
+ const branch = [...(parent?.branch ?? [])];
+ const children: SplitRouteNode<TComponent>[] = [];
+ const node: SplitRouteNode<TComponent> = {
+ definition,
+ parent,
+ branch,
+ pattern: compileRoutePattern(definition),
+ params: createRouteParamsCodec(definition),
+ children,
+ search: new Set([...(parent?.search ?? []), ...namespaces]),
+ claims: [
+ ...(parent?.claims ?? []),
+ ...(definition.claim ? [definition] : []),
+ ],
+ externalSearch: [
+ ...(parent?.externalSearch ?? []),
+ ...(definition.externalSearch ? [definition] : []),
+ ],
+ };
+ branch.push(node);
+ byId.set(definition.id, node);
+ children.push(...visit(definition.children ?? [], node));
+ return node;
+ });
+ };
+
+ return {
+ roots: visit(routes.definitions),
+ byId,
+ basePath:
+ typeof routes.basePath === 'string'
+ ? routes.basePath.split('/').filter(Boolean)
+ : [...(routes.basePath ?? [])],
+ globalSearch,
+ unmatchedPathHandlers: [...(routes.unmatchedPathHandlers ?? [])],
+ defaultEntry: routes.defaultEntry,
+ };
+}
+
+export function validateSplitRoutes<TComponent>(
+ routes: SplitRoutes<TComponent>
+): void {
+ createRoutesManifest(routes);
+}
+
+/** Root pattern match only, including partial paths rejected by schema/children. */
+export function findMatchingRouteId(
+ routes: SplitRoutesManifest,
+ segments: readonly string[]
+): string | undefined {
+ return routes.roots.find((node) => !node.pattern.match(segments).next().done)
+ ?.definition.id;
+}
+
+export function validateRouteParams(
+ schema: StandardSchemaV1 | undefined,
+ params: SplitRouteParams
+): SplitRouteParams | undefined {
+ if (!schema) return params;
+ const result = schema['~standard'].validate(params);
+ if (result instanceof Promise) {
+ throw new Error('Split route parameter schemas must be synchronous');
+ }
+ if (result.issues) return;
+ if (
+ !result.value ||
+ typeof result.value !== 'object' ||
+ Array.isArray(result.value)
+ ) {
+ throw new Error('Split route parameter schemas must return an object');
+ }
+ return result.value as SplitRouteParams;
+}
+
+export function rootRouteMatch(route: SplitRouteState | undefined) {
+ return route?.matches[0];
+}
+
+export function routeParams<
+ TParams extends SplitRouteParams = SplitRouteParams,
+>(route: SplitRouteState | undefined): TParams {
+ return Object.assign(
+ {},
+ ...(route?.matches.map((match) => match.params) ?? [])
+ ) as TParams;
+}
+
+export function findRouteBranch<TComponent>(
+ routes: SplitRoutesManifest<TComponent>,
+ routeId: string
+): readonly SplitRouteNode<TComponent>[] | undefined {
+ return routes.byId.get(routeId)?.branch;
+}
+
+/** Validate host/persisted state without treating schema outputs as schema inputs. */
+export function assertRouteState(
+ routes: SplitRoutesManifest,
+ route: unknown
+): asserts route is SplitRouteState {
+ if (
+ !isRecord(route) ||
+ !Array.isArray(route.matches) ||
+ route.matches.length === 0
+ ) {
+ throw new Error('Split route state requires a nonempty match branch');
+ }
+ let parent: SplitRouteNode | undefined;
+ for (const match of route.matches) {
+ if (
+ !isRecord(match) ||
+ typeof match.id !== 'string' ||
+ !isRecord(match.params)
+ ) {
+ throw new Error('Split route state contains an invalid match');
+ }
+ const node = routes.byId.get(match.id);
+ if (!node || node.parent !== parent) {
+ throw new Error('Split route state contains an invalid match branch');
+ }
+ parent = node;
+ }
+}
+
+export function assertRouteEntry(
+ routes: SplitRoutesManifest,
+ entry: SplitRouterEntry
+): void {
+ assertRouteState(routes, entry?.location?.route);
+}
+
+function resolveRouteNode<TComponent>(
+ routes: SplitRoutesManifest<TComponent>,
+ route: SplitRouteState
+): SplitRouteNode<TComponent> {
+ const leaf = takeLast(route.matches)!;
+ const node = routes.byId.get(leaf.id);
+ if (
+ !node ||
+ node.branch.length !== route.matches.length ||
+ node.branch.some(
+ (ancestor, index) => ancestor.definition.id !== route.matches[index]!.id
+ )
+ ) {
+ throw new Error('Split route state contains an invalid match branch');
+ }
+ return node;
+}
+
+export function resolveRouteBranch<TComponent>(
+ routes: SplitRoutesManifest<TComponent>,
+ route: SplitRouteState
+): readonly SplitRouteNode<TComponent>[] {
+ return resolveRouteNode(routes, route).branch;
+}
+
+export function getRouteClaim(
+ routes: SplitRoutesManifest,
+ route: SplitRouteState
+): SplitRouteClaim | undefined {
+ const claims = resolveRouteNode(routes, route).claims;
+ const params = routeParams(route);
+ for (let index = claims.length - 1; index >= 0; index -= 1) {
+ const claim = claims[index]?.claim?.(params);
+ if (!claim) continue;
+ if (!isSafeName(claim.namespace) || claim.id.length === 0) {
+ throw new Error('Split route returned an invalid claim');
+ }
+ return claim;
+ }
+}
+
+function decodeRouteBranch<TComponent>(
+ nodes: readonly SplitRouteNode<TComponent>[],
+ segments: string[]
+): SplitRouteState | undefined {
+ for (const node of nodes) {
+ for (const patternMatch of node.pattern.match(segments)) {
+ const params = node.params.parse(patternMatch.params);
+ if (!params) continue;
+ const match: SplitRouteMatch = { id: node.definition.id, params };
+ const childSegments = segments.slice(patternMatch.consumed);
+ if (childSegments.length === 0) return { matches: [match] };
+ const child = decodeRouteBranch(node.children, childSegments);
+ if (child) return { matches: [match, ...child.matches] };
+ }
+ }
+}
+
+export function decodeRoute(
+ routes: SplitRoutesManifest,
+ segments: string[]
+): SplitRouterEntry | undefined {
+ const route = decodeRouteBranch(routes.roots, segments);
+ return route ? { location: { route } } : undefined;
+}
+
+export function encodeRoute(
+ routes: SplitRoutesManifest,
+ entry: SplitRouterEntry
+): string[] {
+ const route = entry.location.route;
+ const node = resolveRouteNode(routes, route);
+ return node.branch.flatMap((ancestor, index) =>
+ ancestor.pattern.format(
+ ancestor.params.serialize(route.matches[index]!.params)
+ )
+ );
+}
+
+export function getRouteId(entry: SplitRouterEntry): string {
+ return entry.location.route.matches[0].id;
+}
+
+export function getRouteSearchNamespaces<TComponent>(
+ routes: SplitRoutesManifest<TComponent>,
+ route: SplitRouteState
+): ReadonlySet<string> {
+ return resolveRouteNode(routes, route).search;
+}
+
+export function assertSearchNamespacesAllowed(
+ routes: SplitRoutesManifest,
+ route: SplitRouteState,
+ namespaces: readonly string[]
+): void {
+ const owned = getRouteSearchNamespaces(routes, route);
+ for (const namespace of namespaces) {
+ assertSafeSearchName(namespace, 'namespace');
+ if (!owned.has('*') && !owned.has(namespace)) {
+ throw new Error(
+ `Split route does not own search namespace "${namespace}"`
+ );
+ }
+ }
+}
+
+export function filterRouteSearch<TComponent>(
+ routes: SplitRoutesManifest<TComponent>,
+ route: SplitRouteState,
+ search: SplitSearchState | undefined
+): SplitSearchState | undefined {
+ if (!search) return;
+ const owned = getRouteSearchNamespaces(routes, route);
+ if (owned.has('*')) return search;
+ const filtered = Object.fromEntries(
+ Object.entries(search).filter(([namespace]) => owned.has(namespace))
+ );
+ return Object.keys(filtered).length > 0 ? filtered : undefined;
+}
+
+export function getExternalSearchKeys(
+ routes: SplitRoutesManifest,
+ entries: SplitRouterEntry[]
+): Set<string> {
+ const result = new Set(routes.globalSearch);
+ for (const entry of entries) {
+ for (const definition of resolveRouteNode(routes, entry.location.route)
+ .externalSearch) {
+ const externalSearch = definition.externalSearch;
+ const keys =
+ typeof externalSearch === 'function'
+ ? externalSearch(entry)
+ : (externalSearch ?? []);
+ for (const key of keys) result.add(key);
+ }
+ }
+ return result;
+}
diff --git a/apps/web/src/lib/split-router/search-params-codec.ts b/apps/web/src/lib/split-router/search-params-codec.ts
new file mode 100644
index 0000000000..b386d47457
--- /dev/null
+++ b/apps/web/src/lib/split-router/search-params-codec.ts
@@ -0,0 +1,123 @@
+import type { StandardSchemaV1 } from '@standard-schema/spec';
+import deepEqual from 'fast-deep-equal';
+import type { SerializedSearchParams } from './types';
+import { takeLast } from './utils';
+
+export type SearchParamsRecord = Record<string, unknown>;
+export type SearchParamsSchema<T> = StandardSchemaV1<unknown, T>;
+export type SearchParamsSerializer<T> = (
+ value: T,
+ context: { defaults: T }
+) => SerializedSearchParams | undefined;
+export type SearchParamsDeserializer<T> = (
+ params: SerializedSearchParams
+) => Partial<T>;
+
+export type SearchParamsCodecOptions<T extends SearchParamsRecord> = {
+ schema: SearchParamsSchema<T>;
+ defaults: T;
+} & (
+ | { serialize?: never; deserialize?: never }
+ | {
+ serialize: SearchParamsSerializer<T>;
+ deserialize: SearchParamsDeserializer<T>;
+ }
+);
+
+type ValidationResult<T> =
+ | { success: true; data: T }
+ | { success: false; error: unknown };
+
+export type SearchParamsCodec<T> = {
+ parse(params: SerializedSearchParams | undefined): {
+ value: T;
+ valid: boolean;
+ };
+ serialize(value: T): SerializedSearchParams | undefined;
+ validate(value: unknown): ValidationResult<T>;
+};
+
+function defaultDeserialize<T extends SearchParamsRecord>(
+ params: SerializedSearchParams | undefined,
+ defaults: T
+): Partial<T> {
+ if (!params) return {};
+ const result: SearchParamsRecord = {};
+ for (const key of Object.keys(defaults)) {
+ const values = params[key];
+ if (!values || values.length === 0) continue;
+ const fallback = defaults[key];
+ if (Array.isArray(fallback)) {
+ result[key] = values.length === 1 && values[0] === '' ? [] : [...values];
+ } else if (typeof fallback === 'number') {
+ result[key] = Number(takeLast(values));
+ } else if (typeof fallback === 'boolean') {
+ result[key] = takeLast(values) === 'true';
+ } else {
+ result[key] = takeLast(values);
+ }
+ }
+ return result as Partial<T>;
+}
+
+function defaultSerialize<T extends SearchParamsRecord>(
+ value: T,
+ defaults: T
+): SerializedSearchParams | undefined {
+ const result: SerializedSearchParams = {};
+ for (const [key, field] of Object.entries(value)) {
+ if (field === undefined || deepEqual(field, defaults[key])) continue;
+ if (Array.isArray(field)) {
+ result[key] =
+ field.length === 0 ? [''] : field.map((item) => String(item));
+ } else {
+ result[key] = [String(field)];
+ }
+ }
+ return Object.keys(result).length > 0 ? result : undefined;
+}
+
+export function createSearchParamsCodec<T extends SearchParamsRecord>(
+ options: SearchParamsCodecOptions<T>
+): SearchParamsCodec<T> {
+ const validate = (value: unknown): ValidationResult<T> => {
+ const result = options.schema['~standard'].validate(value);
+ if (result instanceof Promise) {
+ throw new Error('Search parameter schemas must be synchronous');
+ }
+ return result.issues
+ ? { success: false, error: result.issues }
+ : { success: true, data: result.value };
+ };
+
+ if (!validate(options.defaults).success) {
+ throw new Error('Invalid defaults for search params');
+ }
+
+ return {
+ validate,
+ parse(params) {
+ try {
+ const decoded = options.deserialize
+ ? options.deserialize(params ?? {})
+ : defaultDeserialize(params, options.defaults);
+ const parsed = validate({ ...options.defaults, ...decoded });
+ if (parsed.success) return { value: parsed.data, valid: true };
+ } catch {
+ // Invalid inbound URL state falls back to defaults and is canonicalized.
+ }
+ return { value: options.defaults, valid: false };
+ },
+ serialize(value) {
+ if (deepEqual(value, options.defaults)) return;
+ if (!options.serialize) return defaultSerialize(value, options.defaults);
+ const params = options.serialize(value, { defaults: options.defaults });
+ // Keep the codec's result separate from mutable/custom serializer state.
+ const entries = Object.entries(params ?? {}).map(([key, values]) => [
+ key,
+ [...values],
+ ]);
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
+ },
+ };
+}
diff --git a/apps/web/src/lib/split-router/search.ts b/apps/web/src/lib/split-router/search.ts
new file mode 100644
index 0000000000..d8da3a968c
--- /dev/null
+++ b/apps/web/src/lib/split-router/search.ts
@@ -0,0 +1,167 @@
+import type {
+ SerializedSearchParams,
+ SplitLocation,
+ SplitSearchState,
+ SplitSearchUpdate,
+} from './types';
+import { isRecord, isSafeName } from './utils';
+
+const SPLIT_SEARCH_PREFIX = /^s\d+\./;
+const SPLIT_SEARCH_KEY =
+ /^s(\d+)\.([A-Za-z][A-Za-z0-9_-]*)\.([A-Za-z][A-Za-z0-9_-]*)$/;
+const MAX_SEARCH_VALUE_LENGTH = 16_384;
+
+export function isSplitSearchKey(key: string): boolean {
+ return SPLIT_SEARCH_PREFIX.test(key);
+}
+
+export function assertSafeSearchName(
+ value: string,
+ kind: 'namespace' | 'field'
+): void {
+ if (!isSafeName(value)) {
+ throw new Error(`Invalid split search ${kind} "${value}"`);
+ }
+}
+
+export function parseSplitSearch(value: string): Map<number, SplitSearchState> {
+ const splits = new Map<number, SplitSearchState>();
+
+ for (const [key, fieldValue] of new URLSearchParams(value)) {
+ const match = SPLIT_SEARCH_KEY.exec(key);
+
+ if (!match || fieldValue.length > MAX_SEARCH_VALUE_LENGTH) continue;
+
+ const splitIndex = Number(match[1]);
+ const namespace = match[2]!;
+ const field = match[3]!;
+
+ if (
+ !Number.isSafeInteger(splitIndex) ||
+ !isSafeName(namespace) ||
+ !isSafeName(field)
+ ) {
+ continue;
+ }
+
+ const namespaces = splits.get(splitIndex) ?? {};
+ const fields = namespaces[namespace] ?? {};
+
+ fields[field] = [...(fields[field] ?? []), fieldValue];
+ namespaces[namespace] = fields;
+ splits.set(splitIndex, namespaces);
+ }
+
+ return splits;
+}
+
+/** Recover compatible fields from untrusted persisted search metadata. */
+export function parseSearchState(value: unknown): SplitSearchState | undefined {
+ if (!isRecord(value)) return;
+ const search: SplitSearchState = {};
+ for (const [namespace, rawFields] of Object.entries(value)) {
+ if (!isSafeName(namespace) || !isRecord(rawFields)) continue;
+ const fields: SerializedSearchParams = {};
+ for (const [field, rawValues] of Object.entries(rawFields)) {
+ if (!isSafeName(field) || !Array.isArray(rawValues)) continue;
+ const values = rawValues.filter(
+ (item): item is string =>
+ typeof item === 'string' && item.length <= MAX_SEARCH_VALUE_LENGTH
+ );
+ if (values.length > 0) fields[field] = values;
+ }
+ if (Object.keys(fields).length > 0) search[namespace] = fields;
+ }
+ return Object.keys(search).length > 0 ? search : undefined;
+}
+
+/** Replaces split-owned keys in the query, preserving other search params. */
+export function replaceSplitSearchParams(
+ query: URLSearchParams,
+ entries: Array<{ location?: { search?: SplitSearchState } }>
+): void {
+ for (const key of [...query.keys()]) {
+ if (isSplitSearchKey(key)) query.delete(key);
+ }
+
+ entries.forEach((entry, splitIndex) => {
+ const search = entry.location?.search;
+
+ if (!search) return;
+
+ for (const namespace of Object.keys(search).sort()) {
+ assertSafeSearchName(namespace, 'namespace');
+
+ const params = search[namespace];
+
+ if (!params) continue;
+
+ for (const field of Object.keys(params).sort()) {
+ assertSafeSearchName(field, 'field');
+
+ for (const value of params[field] ?? []) {
+ if (value.length > MAX_SEARCH_VALUE_LENGTH) {
+ throw new Error(`Split search value for "${field}" is too long`);
+ }
+
+ query.append(`s${splitIndex}.${namespace}.${field}`, value);
+ }
+ }
+ }
+ });
+}
+
+export function normalizeSearchParams(
+ params: SerializedSearchParams | undefined
+): SerializedSearchParams | undefined {
+ if (!params) return;
+
+ const result: Record<string, string[]> = {};
+
+ for (const field of Object.keys(params).sort()) {
+ assertSafeSearchName(field, 'field');
+
+ const values = params[field];
+
+ if (values?.length) result[field] = [...values];
+ }
+
+ return Object.keys(result).length ? result : undefined;
+}
+
+export function withSearchNamespace(
+ current: SplitLocation,
+ namespace: string,
+ params: SerializedSearchParams | undefined
+): SplitLocation {
+ const search = { ...(current.search ?? {}) };
+
+ if (params && Object.keys(params).length > 0) search[namespace] = params;
+ else delete search[namespace];
+
+ return Object.keys(search).length > 0
+ ? { route: current.route, search }
+ : { route: current.route };
+}
+
+export function updateSearchState(
+ location: SplitLocation,
+ updates: Record<string, SplitSearchUpdate> | undefined
+): SplitLocation {
+ let next = location;
+
+ for (const [namespace, update] of Object.entries(updates ?? {})) {
+ assertSafeSearchName(namespace, 'namespace');
+
+ const current = next.search?.[namespace];
+ const requested = typeof update === 'function' ? update(current) : update;
+
+ next = withSearchNamespace(
+ next,
+ namespace,
+ normalizeSearchParams(requested)
+ );
+ }
+
+ return next;
+}
diff --git a/apps/web/src/lib/split-router/solid.tsx b/apps/web/src/lib/split-router/solid.tsx
new file mode 100644
index 0000000000..784229f788
--- /dev/null
+++ b/apps/web/src/lib/split-router/solid.tsx
@@ -0,0 +1,310 @@
+import {
+ type Accessor,
+ type Component,
+ createContext,
+ createMemo,
+ createSignal,
+ type JSX,
+ onCleanup,
+ Show,
+ type Signal,
+ useContext,
+} from 'solid-js';
+import { Dynamic } from 'solid-js/web';
+import { createSplitRouter } from './router';
+import {
+ resolveRouteBranch,
+ routeParams,
+ type SplitRoutesManifest,
+} from './routes';
+import type {
+ InferSplitRouteParams,
+ SplitNavigate,
+ SplitNavigateOptions,
+ SplitNavigateTo,
+ SplitRouteParams,
+ SplitRouter as SplitRouterController,
+ SplitRouterExternalLocation,
+ SplitRouterLayout,
+ SplitRouterMiddleware,
+ SplitRouteState,
+ SplitRoutes,
+} from './types';
+import { reactiveRecord } from './utils';
+
+type UnknownSplitRouter = SplitRouterController<unknown>;
+
+export type SplitRouterContextValue = {
+ router: UnknownSplitRouter;
+ globalRevision: Accessor<number>;
+ track: (splitId: unknown) => void;
+};
+
+type SplitRouterOutletContextValue = {
+ splitId: Accessor<unknown>;
+ depth: Accessor<number>;
+};
+
+export const SplitRouterContext = createContext<SplitRouterContextValue>();
+export const SplitRouterScopeContext = createContext<Accessor<unknown>>();
+const SplitRouterOutletContext = createContext<SplitRouterOutletContextValue>();
+
+function useSplitRouterContext() {
+ const context = useContext(SplitRouterContext);
+
+ if (!context) {
+ throw new Error(
+ 'Split router hooks must be used inside <SplitRouter.Root>'
+ );
+ }
+
+ return context;
+}
+
+export function useSplitRouter<TSplitId>(): SplitRouterController<TSplitId> {
+ return useSplitRouterContext()
+ .router as unknown as SplitRouterController<TSplitId>;
+}
+
+export function useSplitRouterState<TSplitId>() {
+ const context = useSplitRouterContext();
+ const router = context.router as unknown as SplitRouterController<TSplitId>;
+
+ return {
+ router,
+ canGo(splitId: TSplitId, delta: number) {
+ context.track(splitId);
+
+ return router.canGo(splitId, delta);
+ },
+ history(splitId: TSplitId) {
+ context.track(splitId);
+
+ return router.history(splitId);
+ },
+ route(splitId: TSplitId) {
+ context.track(splitId);
+
+ return router.route(splitId);
+ },
+ location(splitId: TSplitId) {
+ context.track(splitId);
+
+ return router.location(splitId);
+ },
+ search(splitId: TSplitId, namespace: string) {
+ context.track(splitId);
+
+ return router.search(splitId, namespace);
+ },
+ };
+}
+
+export function useSplitRouterScope<TSplitId>(): Accessor<TSplitId> {
+ const splitId = useContext(SplitRouterScopeContext);
+
+ if (!splitId) {
+ throw new Error(
+ 'Split router hooks must be used inside <SplitRouter.Scope> or <SplitRouter.Outlet>'
+ );
+ }
+
+ return splitId as Accessor<TSplitId>;
+}
+
+export function useNavigate<TSplitId = unknown>(): SplitNavigate<TSplitId> {
+ const router = useSplitRouter<TSplitId>();
+ const splitId = useSplitRouterScope<TSplitId>();
+
+ const navigate = router.navigate as (
+ splitId: TSplitId,
+ to: SplitNavigateTo,
+ options?: SplitNavigateOptions<TSplitId>
+ ) => void;
+
+ return ((to: SplitNavigateTo, options: SplitNavigateOptions<TSplitId> = {}) =>
+ navigate(splitId(), to, options)) as SplitNavigate<TSplitId>;
+}
+
+export function useCanGo(delta: number): Accessor<boolean> {
+ const router = useSplitRouterState<unknown>();
+ const splitId = useSplitRouterScope<unknown>();
+
+ return () => router.canGo(splitId(), delta);
+}
+
+export function useSplitHistory() {
+ const router = useSplitRouterState<unknown>();
+ const splitId = useSplitRouterScope<unknown>();
+
+ return () => router.history(splitId());
+}
+
+export function useParams<T extends SplitRouteParams = SplitRouteParams>(): T {
+ const router = useSplitRouterState<unknown>();
+ const splitId = useSplitRouterScope<unknown>();
+ const params = createMemo(() => routeParams(router.route(splitId())));
+
+ return reactiveRecord(params) as T;
+}
+
+export function useRouteParams<const TRoute extends { id: string }>(
+ route: TRoute
+): InferSplitRouteParams<TRoute> {
+ const router = useSplitRouterState<unknown>();
+ const splitId = useSplitRouterScope<unknown>();
+ const params = createMemo(
+ () =>
+ router.route(splitId())?.matches.find((match) => match.id === route.id)
+ ?.params ?? {}
+ );
+
+ return reactiveRecord(params) as InferSplitRouteParams<TRoute>;
+}
+
+export type SplitRouterRootProps<TSplitId, TComponent = unknown> = {
+ layout: SplitRouterLayout<TSplitId>;
+ routes: SplitRoutes<TComponent> | SplitRoutesManifest<TComponent>;
+ location: SplitRouterExternalLocation;
+ middleware?: readonly SplitRouterMiddleware[];
+ children?: JSX.Element;
+};
+
+export function Root<TSplitId, TComponent = unknown>(
+ props: SplitRouterRootProps<TSplitId, TComponent>
+) {
+ const router = createSplitRouter({
+ layout: props.layout,
+ routes: props.routes,
+ location: props.location,
+ middleware: props.middleware,
+ });
+ const [globalRevision, setGlobalRevision] = createSignal(0);
+ const splitRevisions = new Map<unknown, Signal<number>>();
+ const splitRevision = (splitId: unknown) => {
+ let revision = splitRevisions.get(splitId);
+
+ if (!revision) {
+ revision = createSignal(0);
+ splitRevisions.set(splitId, revision);
+ }
+
+ return revision;
+ };
+
+ router.subscribe((splitId) => {
+ if (splitId === undefined) {
+ setGlobalRevision((value) => value + 1);
+ return;
+ }
+
+ splitRevision(splitId)[1]((value) => value + 1);
+ });
+ onCleanup(() => router.dispose());
+
+ const ready = () => {
+ globalRevision();
+
+ return router.isReady();
+ };
+
+ return (
+ <SplitRouterContext.Provider
+ value={{
+ router: router as unknown as SplitRouterController<unknown>,
+ globalRevision,
+ track: (splitId) => {
+ globalRevision();
+ splitRevision(splitId)[0]();
+ },
+ }}
+ >
+ <Show when={ready()}>{props.children}</Show>
+ </SplitRouterContext.Provider>
+ );
+}
+
+export type SplitRouterScopeProps<TSplitId> = {
+ splitId: TSplitId;
+ children?: JSX.Element;
+};
+
+export function Scope<TSplitId>(props: SplitRouterScopeProps<TSplitId>) {
+ return (
+ <SplitRouterScopeContext.Provider value={() => props.splitId}>
+ {props.children}
+ </SplitRouterScopeContext.Provider>
+ );
+}
+
+export type SplitRouterOutletProps<TSplitId> = {
+ splitId?: TSplitId;
+ fallback?: () => JSX.Element;
+};
+
+export function Outlet<TSplitId>(props: SplitRouterOutletProps<TSplitId>) {
+ const context = useSplitRouterContext();
+ const parent = useContext(SplitRouterOutletContext);
+ const scope = useContext(SplitRouterScopeContext);
+ const splitId: Accessor<unknown> = () => {
+ if (props.splitId !== undefined) return props.splitId;
+ if (parent) return parent.splitId();
+ if (scope) return scope();
+
+ throw new Error(
+ 'SplitRouter.Outlet requires a splitId or <SplitRouter.Scope>'
+ );
+ };
+ const startDepth = () =>
+ props.splitId === undefined && parent ? parent.depth() : 0;
+ const route = (): SplitRouteState | undefined => {
+ context.track(splitId());
+ return context.router.route(splitId());
+ };
+ const resolved = createMemo(() => {
+ const currentRoute = route();
+ if (!currentRoute) return;
+ const branch = resolveRouteBranch(context.router.routes, currentRoute);
+
+ for (let index = startDepth(); index < branch.length; index += 1) {
+ const definition = branch[index]?.definition;
+ const component = definition?.component;
+ if (definition && typeof component === 'function') {
+ const remountKey = definition.remountKey?.(
+ currentRoute.matches[index]!.params
+ );
+
+ return {
+ component: component as Component,
+ renderKey: JSON.stringify([definition.id, remountKey ?? null]),
+ nextDepth: index + 1,
+ };
+ }
+ }
+ });
+ const component = () => resolved()?.component;
+ const renderKey = () => resolved()?.renderKey;
+ const outletContext: SplitRouterOutletContextValue = {
+ splitId,
+ depth: () => resolved()?.nextDepth ?? startDepth(),
+ };
+ const Fallback = () => props.fallback?.();
+
+ return (
+ <SplitRouterScopeContext.Provider value={splitId}>
+ <Show keyed when={renderKey()} fallback={<Fallback />}>
+ {(_key) => (
+ <SplitRouterOutletContext.Provider value={outletContext}>
+ <Dynamic component={component()} />
+ </SplitRouterOutletContext.Provider>
+ )}
+ </Show>
+ </SplitRouterScopeContext.Provider>
+ );
+}
+
+export const SplitRouter = {
+ Root,
+ Scope,
+ Outlet,
+};
diff --git a/apps/web/src/lib/split-router/tests/claims.test.ts b/apps/web/src/lib/split-router/tests/claims.test.ts
new file mode 100644
index 0000000000..26fd999d62
--- /dev/null
+++ b/apps/web/src/lib/split-router/tests/claims.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from 'vitest';
+import { createClaimReservations } from '../claims';
+
+const one = { namespace: 'document', id: 'one' };
+const two = { namespace: 'document', id: 'two' };
+
+describe('pending claim reservations', () => {
+ it('grants contenders turns in reservation order', async () => {
+ const claims = createClaimReservations();
+ const first = claims.reserve(one);
+ const second = claims.reserve(one);
+ const third = claims.reserve(one);
+ const signal = new AbortController().signal;
+ expect(first.wait(signal)).toBeUndefined();
+ const secondTurn = second.wait(signal);
+ let thirdReady = false;
+ const thirdTurn = (async () => {
+ await third.wait(signal);
+ thirdReady = true;
+ })();
+ first.release();
+ await secondTurn;
+ expect(thirdReady).toBe(false);
+ second.release();
+ await thirdTurn;
+ expect(thirdReady).toBe(true);
+ third.release();
+ });
+
+ it('moves redirected reservations without blocking the original claim', async () => {
+ const claims = createClaimReservations();
+ const first = claims.reserve(one);
+ const second = claims.reserve(one);
+ const other = claims.reserve(two);
+ const signal = new AbortController().signal;
+ const secondTurn = second.wait(signal);
+ first.move(two);
+ await secondTurn;
+ let firstReady = false;
+ const firstTurn = (async () => {
+ await first.wait(signal);
+ firstReady = true;
+ })();
+ await Promise.resolve();
+ expect(firstReady).toBe(false);
+ other.release();
+ await firstTurn;
+ first.release();
+ second.release();
+ });
+
+ it('does not let an obsolete release remove a newer reservation', () => {
+ const claims = createClaimReservations();
+ const stale = claims.reserve(one);
+ stale.release();
+ const owner = claims.reserve(one);
+ const waiter = claims.reserve(one);
+ stale.release();
+ stale.move(one);
+ expect(owner.wait(new AbortController().signal)).toBeUndefined();
+ const controller = new AbortController();
+ const waiting = waiter.wait(controller.signal);
+ expect(waiting).toBeInstanceOf(Promise);
+ controller.abort();
+ owner.release();
+ waiter.release();
+ return expect(waiting).rejects.toMatchObject({ name: 'AbortError' });
+ });
+
+ it('removes aborted wait listeners and distinguishes namespaces and IDs', async () => {
+ const claims = createClaimReservations();
+ const owner = claims.reserve(one);
+ const waiter = claims.reserve(one);
+ const controller = new AbortController();
+ const waiting = waiter.wait(controller.signal);
+ controller.abort();
+ await expect(waiting).rejects.toMatchObject({ name: 'AbortError' });
+ waiter.release();
+ owner.release();
+ const other = claims.reserve({ namespace: 'folder', id: one.id });
+ const document = claims.reserve(one);
+ expect(other.wait(new AbortController().signal)).toBeUndefined();
+ expect(document.wait(new AbortController().signal)).toBeUndefined();
+ other.release();
+ document.release();
+ });
+
+ it('keeps reservation state local to each router owner', () => {
+ const first = createClaimReservations().reserve(one);
+ const second = createClaimReservations().reserve(one);
+ expect(first.wait(new AbortController().signal)).toBeUndefined();
+ expect(second.wait(new AbortController().signal)).toBeUndefined();
+ first.release();
+ second.release();
+ });
+});
diff --git a/apps/web/src/lib/split-router/tests/history.test.ts b/apps/web/src/lib/split-router/tests/history.test.ts
new file mode 100644
index 0000000000..ba4c1660ba
--- /dev/null
+++ b/apps/web/src/lib/split-router/tests/history.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from 'vitest';
+import {
+ createSplitRouterHistories,
+ createSplitRouterHistory,
+} from '../history';
+
+describe('split router history', () => {
+ it('pushes, replaces, and traverses entries', () => {
+ const history = createSplitRouterHistory<string>('one', Object.is);
+
+ expect(history.push('two')).toBe(true);
+ expect(history.push('three')).toBe(true);
+ expect(history.entries()).toEqual(['one', 'two', 'three']);
+ expect(history.canGo(-2)).toBe(true);
+ expect(history.go(-1)).toBe(true);
+ expect(history.current()).toBe('two');
+ expect(history.replace('second')).toBe(true);
+ expect(history.entries()).toEqual(['one', 'second', 'three']);
+ expect(history.go(1)).toBe(true);
+ expect(history.current()).toBe('three');
+ });
+
+ it('truncates forward entries after a push', () => {
+ const history = createSplitRouterHistory<string>('one', Object.is);
+
+ history.push('two');
+ history.push('three');
+ history.go(-2);
+ history.push('four');
+
+ expect(history.entries()).toEqual(['one', 'four']);
+ expect(history.canGo(1)).toBe(false);
+ });
+
+ it('accepts an existing entry by moving the index', () => {
+ const history = createSplitRouterHistory<string>('one', Object.is);
+
+ history.push('two');
+ history.push('three');
+
+ expect(history.accept('one', 'replace')).toBe(true);
+ expect(history.index()).toBe(0);
+ expect(history.entries()).toEqual(['one', 'two', 'three']);
+ });
+
+ it('transfers positional history when a layout replaces an id', () => {
+ const histories = createSplitRouterHistories<string, string>(Object.is);
+
+ histories.reconcile([{ id: 'first', entry: 'one' }], 'replace', 'move');
+ histories.reconcile([{ id: 'first', entry: 'two' }], 'push', 'write');
+ histories.reconcile([{ id: 'second', entry: 'two' }], 'replace', 'move');
+
+ expect(histories.get('first')).toBeUndefined();
+ expect(histories.get('second')?.entries()).toEqual(['one', 'two']);
+
+ histories.reconcile([], 'replace', 'move');
+ expect(histories.get('second')).toBeUndefined();
+ });
+
+ it('ignores invalid deltas and structurally equal writes', () => {
+ const history = createSplitRouterHistory(
+ { value: 'one' },
+ (left, right) => left.value === right.value
+ );
+
+ expect(history.push({ value: 'one' })).toBe(false);
+ expect(history.replace({ value: 'one' })).toBe(false);
+ expect(history.canGo(0)).toBe(false);
+ expect(history.go(Number.NaN)).toBe(false);
+ });
+});
diff --git a/apps/web/src/lib/split-router/tests/location-sync.test.ts b/apps/web/src/lib/split-router/tests/location-sync.test.ts
new file mode 100644
index 0000000000..d650027935
--- /dev/null
+++ b/apps/web/src/lib/split-router/tests/location-sync.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it, vi } from 'vitest';
+import { createLocationSync } from '../location-sync';
+import { createRoutesManifest, decodeRoute } from '../routes';
+import type { SplitRouterExternalLocationValue } from '../types';
+import { parseExternalLocation } from '../url';
+
+const routes = createRoutesManifest({
+ definitions: [{ id: 'item', path: 'item/:id' }],
+});
+
+function setup() {
+ let current = parseExternalLocation('/item/initial');
+ const commit = vi.fn();
+ const sync = createLocationSync({
+ routes,
+ location: {
+ read: () => current,
+ commit,
+ subscribe: () => () => {},
+ },
+ });
+ const acknowledge = (next: SplitRouterExternalLocationValue) => {
+ current = next;
+ return sync.acknowledge(next);
+ };
+ const navigate = (id: string) =>
+ sync.commit([decodeRoute(routes, ['item', id])!], {
+ history: 'push',
+ preserveHash: false,
+ });
+ return { sync, commit, acknowledge, navigate };
+}
+
+describe('external location synchronization', () => {
+ it('does not recommit the current location or an outstanding request', () => {
+ const { commit, navigate, acknowledge } = setup();
+ navigate('initial');
+ expect(commit).not.toHaveBeenCalled();
+ navigate('next');
+ navigate('next');
+ expect(commit).toHaveBeenCalledTimes(1);
+ expect(acknowledge(parseExternalLocation('/item/next/'))).toBe(true);
+ expect(acknowledge(parseExternalLocation('/item/external'))).toBe(false);
+ });
+
+ it('repairs stale acknowledgments without pushing another history entry', () => {
+ const { commit, navigate, acknowledge } = setup();
+ navigate('first');
+ navigate('second');
+ expect(commit).toHaveBeenCalledTimes(2);
+ expect(acknowledge(parseExternalLocation('/item/second'))).toBe(true);
+ expect(acknowledge(parseExternalLocation('/item/first'))).toBe(true);
+ expect(commit).toHaveBeenCalledTimes(3);
+ expect(commit).toHaveBeenLastCalledWith(
+ parseExternalLocation('/item/second'),
+ { history: 'replace' }
+ );
+ expect(acknowledge(parseExternalLocation('/item/second'))).toBe(true);
+ expect(commit).toHaveBeenCalledTimes(3);
+ });
+});
diff --git a/apps/web/src/lib/split-router/tests/middleware.test.ts b/apps/web/src/lib/split-router/tests/middleware.test.ts
new file mode 100644
index 0000000000..9bf7c1391e
--- /dev/null
+++ b/apps/web/src/lib/split-router/tests/middleware.test.ts
@@ -0,0 +1,188 @@
+import { describe, expect, it, vi } from 'vitest';
+import { z } from 'zod';
+import { prepareEntry, runSplitRouterMiddleware } from '../middleware';
+import {
+ createRoutesManifest,
+ defineRoute,
+ rootRouteMatch,
+ routeParams,
+} from '../routes';
+import type { SplitRouterMiddleware } from '../types';
+
+const routes = createRoutesManifest({
+ definitions: [
+ defineRoute({
+ id: 'drive',
+ path: 'drive',
+ children: [
+ {
+ id: 'drive-document',
+ path: 'md/:documentId',
+ params: z.object({ documentId: z.string() }),
+ },
+ ],
+ }),
+ {
+ id: 'legacy',
+ path: 'legacy/:id',
+ params: z.object({ id: z.string() }),
+ },
+ ],
+});
+
+const legacyEntry = {
+ location: {
+ route: {
+ matches: [{ id: 'legacy', params: { id: 'document-1' } }] as const,
+ },
+ search: { view: { mode: ['compact'] } },
+ },
+};
+
+describe('split router middleware', () => {
+ it('stays synchronous when every middleware is synchronous', () => {
+ const result = runSplitRouterMiddleware(
+ {
+ routes,
+ handlers: [
+ ({ to, redirect }) =>
+ rootRouteMatch(to.location.route)?.id === 'legacy'
+ ? redirect(`/drive/md/${routeParams(to.location.route).id}`)
+ : undefined,
+ ],
+ },
+ {
+ to: legacyEntry,
+ cause: 'navigate',
+ signal: new AbortController().signal,
+ }
+ );
+
+ expect(result).not.toBeInstanceOf(Promise);
+ expect(result).toMatchObject({
+ location: {
+ route: {
+ matches: [
+ { id: 'drive', params: {} },
+ {
+ id: 'drive-document',
+ params: { documentId: 'document-1' },
+ },
+ ],
+ },
+ },
+ });
+ });
+
+ it('awaits middleware and restarts the pipeline after a redirect', async () => {
+ const visits: string[] = [];
+ const middleware: SplitRouterMiddleware[] = [
+ async ({ path }) => {
+ await Promise.resolve();
+ visits.push(`preload:${path}`);
+ },
+ ({ to, redirect }) => {
+ const routeId = rootRouteMatch(to.location.route)?.id;
+ visits.push(`redirect:${routeId}`);
+ if (routeId === 'legacy') {
+ return redirect(`/drive/md/${routeParams(to.location.route).id}`);
+ }
+ },
+ ];
+
+ const result = await runSplitRouterMiddleware(
+ { routes, handlers: middleware },
+ {
+ to: legacyEntry,
+ cause: 'navigate',
+ signal: new AbortController().signal,
+ }
+ );
+
+ expect(visits).toEqual([
+ 'preload:/legacy/document-1',
+ 'redirect:legacy',
+ 'preload:/drive/md/document-1',
+ 'redirect:drive',
+ ]);
+ expect(result).toEqual({
+ location: {
+ route: {
+ matches: [
+ { id: 'drive', params: {} },
+ {
+ id: 'drive-document',
+ params: { documentId: 'document-1' },
+ },
+ ],
+ },
+ search: { view: { mode: ['compact'] } },
+ },
+ });
+ });
+
+ it('passes cancellation to pending preload work', async () => {
+ const controller = new AbortController();
+ const observed = vi.fn();
+ const pending = runSplitRouterMiddleware(
+ {
+ routes,
+ handlers: [
+ ({ signal }) =>
+ new Promise<void>((_resolve, reject) => {
+ signal.addEventListener('abort', () => {
+ observed();
+ reject(signal.reason);
+ });
+ }),
+ ],
+ },
+ {
+ to: legacyEntry,
+ cause: 'external',
+ signal: controller.signal,
+ }
+ );
+
+ controller.abort(new DOMException('Superseded', 'AbortError'));
+
+ await expect(pending).rejects.toMatchObject({ name: 'AbortError' });
+ expect(observed).toHaveBeenCalledOnce();
+ });
+
+ it('rejects invalid asynchronous results instead of recovering to a malformed proposal', async () => {
+ const pending = prepareEntry(
+ {
+ routes,
+ handlers: [
+ async ({ to }) => {
+ await Promise.resolve();
+ to.location.route = { matches: [{ id: 'missing', params: {} }] };
+ },
+ ],
+ },
+ {
+ to: { location: { route: { matches: [{ id: 'drive', params: {} }] } } },
+ cause: 'navigate',
+ signal: new AbortController().signal,
+ }
+ );
+ await expect(pending).rejects.toThrow('invalid match branch');
+ });
+
+ it('rejects redirect loops', () => {
+ expect(() =>
+ runSplitRouterMiddleware(
+ {
+ routes,
+ handlers: [({ path, redirect }) => redirect(path)],
+ },
+ {
+ to: legacyEntry,
+ cause: 'navigate',
+ signal: new AbortController().signal,
+ }
+ )
+ ).toThrow('redirect loop');
+ });
+});
diff --git a/apps/web/src/lib/split-router/tests/navigation.test.ts b/apps/web/src/lib/split-router/tests/navigation.test.ts
new file mode 100644
index 0000000000..35422f890f
--- /dev/null
+++ b/apps/web/src/lib/split-router/tests/navigation.test.ts
@@ -0,0 +1,153 @@
+import { describe, expect, expectTypeOf, it } from 'vitest';
+import { z } from 'zod';
+import { resolveNavigation } from '../navigation';
+import {
+ createRoutesManifest,
+ decodeRoute,
+ defineRoute,
+ routeParams,
+} from '../routes';
+import type { SplitNavigate, SplitRouterEntry } from '../types';
+
+const workspaceDetailRoute = defineRoute({
+ id: 'workspace-detail',
+ path: 'detail/:documentId',
+ params: z.object({ documentId: z.string() }),
+});
+
+const workspacePageRoute = defineRoute({
+ id: 'workspace-page',
+ path: 'page/:page',
+ params: z.object({ page: z.coerce.number().int().positive() }),
+});
+
+const workspaceFolderRoute = defineRoute({
+ id: 'workspace-folder',
+ path: 'folder/:folderId',
+ params: z.object({ folderId: z.string() }),
+ children: [workspaceDetailRoute],
+});
+
+const workspaceRoute = defineRoute({
+ id: 'workspace',
+ path: 'workspace',
+ search: ['workspace'],
+ children: [workspaceFolderRoute, workspacePageRoute],
+});
+
+const routes = createRoutesManifest({
+ definitions: [workspaceRoute],
+});
+
+function entry(path: string[]): SplitRouterEntry {
+ return decodeRoute(routes, path)!;
+}
+
+function assertTypedRouteTargets(navigate: SplitNavigate<string>) {
+ navigate({
+ route: workspaceDetailRoute,
+ params: { documentId: 'document-1' },
+ });
+ navigate({ route: workspaceRoute });
+ navigate({ route: workspacePageRoute, params: { page: 2 } });
+ // @ts-expect-error navigation uses the schema output type
+ navigate({ route: workspacePageRoute, params: { page: '2' } });
+ // @ts-expect-error documentId is required by the route schema
+ navigate({ route: workspaceDetailRoute });
+ // @ts-expect-error documentId must be a string
+ navigate({
+ route: workspaceDetailRoute,
+ params: { documentId: 1 },
+ });
+}
+
+describe('split route navigation', () => {
+ it('requires params inferred from typed route schemas', () => {
+ expectTypeOf(assertTypedRouteTargets).toBeFunction();
+ });
+
+ it('round trips typed navigation params through route schemas', () => {
+ const current = entry(['workspace']);
+ const next = resolveNavigation(routes, current, current, {
+ route: workspacePageRoute,
+ params: { page: 2 },
+ });
+
+ expect(next?.location?.route?.matches).toEqual([
+ { id: 'workspace', params: {} },
+ { id: 'workspace-page', params: { page: 2 } },
+ ]);
+ });
+
+ it('appends explicit child-relative paths to the current route', () => {
+ const current = entry(['workspace', 'folder', 'folder-1']);
+ const next = resolveNavigation(
+ routes,
+ current,
+ current,
+ './detail/document-1'
+ );
+
+ expect(next?.location?.route?.matches).toEqual([
+ { id: 'workspace', params: {} },
+ { id: 'workspace-folder', params: { folderId: 'folder-1' } },
+ { id: 'workspace-detail', params: { documentId: 'document-1' } },
+ ]);
+ });
+
+ it('navigates to a parent while preserving its params and search', () => {
+ const current = entry([
+ 'workspace',
+ 'folder',
+ 'folder-1',
+ 'detail',
+ 'document-1',
+ ]);
+ current.location = {
+ ...current.location,
+ search: { workspace: { sort: ['name'] } },
+ };
+ const next = resolveNavigation(routes, current, current, { parent: true });
+
+ expect(next?.location).toEqual({
+ route: {
+ matches: [
+ { id: 'workspace', params: {} },
+ { id: 'workspace-folder', params: { folderId: 'folder-1' } },
+ ],
+ },
+ search: { workspace: { sort: ['name'] } },
+ });
+ });
+
+ it('navigates by a typed route and preserves matching ancestor params', () => {
+ const current = entry(['workspace', 'folder', 'folder-1']);
+ const next = resolveNavigation(routes, current, current, {
+ route: workspaceDetailRoute,
+ params: { documentId: 'document-2' },
+ });
+
+ expect(next?.location?.route?.matches).toEqual([
+ { id: 'workspace', params: {} },
+ { id: 'workspace-folder', params: { folderId: 'folder-1' } },
+ { id: 'workspace-detail', params: { documentId: 'document-2' } },
+ ]);
+ expect(routeParams(next?.location?.route)).toEqual({
+ folderId: 'folder-1',
+ documentId: 'document-2',
+ });
+ });
+
+ it('returns undefined for invalid parent and route destinations', () => {
+ const current = entry(['workspace']);
+
+ expect(
+ resolveNavigation(routes, current, current, { parent: true })
+ ).toBeUndefined();
+ expect(
+ resolveNavigation(routes, current, current, {
+ route: { id: 'missing' },
+ })
+ ).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/lib/split-router/tests/path.test.ts b/apps/web/src/lib/split-router/tests/path.test.ts
new file mode 100644
index 0000000000..14f6955687
--- /dev/null
+++ b/apps/web/src/lib/split-router/tests/path.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from 'vitest';
+import { compileRoutePattern } from '../path';
+
+describe('split route path patterns', () => {
+ it('matches required and optional parameters', () => {
+ const required = compileRoutePattern({ path: 'folder/:folderId' });
+ const optional = compileRoutePattern({ path: 'folder/:folderId?' });
+ expect([...required.match(['folder', 'one'])]).toEqual([
+ { params: { folderId: 'one' }, consumed: 2 },
+ ]);
+ expect([...optional.match(['folder'])]).toEqual([
+ { params: {}, consumed: 1 },
+ ]);
+ expect(optional.format({})).toEqual(['folder']);
+ });
+
+ it('matches and formats a final catch-all parameter', () => {
+ const pattern = compileRoutePattern({ path: 'files/*remaining' });
+ expect([...pattern.match(['files', 'a', 'b'])]).toEqual([
+ { params: { remaining: ['a', 'b'] }, consumed: 3 },
+ ]);
+ expect([...pattern.match(['files'])]).toEqual([]);
+ expect(() => pattern.format({ remaining: [] })).toThrow(
+ 'Missing split route catch-all parameter "remaining"'
+ );
+ expect(pattern.format({ remaining: ['a', 'b'] })).toEqual([
+ 'files',
+ 'a',
+ 'b',
+ ]);
+ });
+
+ it('rejects malformed canonical paths and aliases', () => {
+ expect(() => compileRoutePattern({ path: 'folder/:' })).toThrow(
+ 'Invalid split route parameter'
+ );
+ expect(() => compileRoutePattern({ path: 'files/*' })).toThrow(
+ 'Invalid split route catch-all parameter "*"'
+ );
+ expect(() =>
+ compileRoutePattern({ path: 'files/*remaining/edit' })
+ ).toThrow('catch-all parameter must be the final segment');
+ expect(() =>
+ compileRoutePattern({ path: 'folder', aliases: ['folder/~/child'] })
+ ).toThrow('Invalid split route path');
+ });
+
+ it('matches canonical paths and aliases but formats only canonical segments', () => {
+ const pattern = compileRoutePattern({
+ path: 'document/:id',
+ aliases: ['doc/:id'],
+ });
+ expect([...pattern.match(['document', 'a/b c'])]).toEqual([
+ { params: { id: 'a/b c' }, consumed: 2 },
+ ]);
+ expect([...pattern.match(['doc', 'a/b c'])]).toEqual([
+ { params: { id: 'a/b c' }, consumed: 2 },
+ ]);
+ // Percent-encoding belongs to the full URL layer, not the pattern.
+ expect(pattern.format({ id: 'a/b c' })).toEqual(['document', 'a/b c']);
+ });
+
+ it('tries the canonical pattern before aliases in declaration order', () => {
+ const pattern = compileRoutePattern({
+ path: ':first',
+ aliases: [':second', '*rest'],
+ });
+ expect([...pattern.match(['one'])]).toEqual([
+ { params: { first: 'one' }, consumed: 1 },
+ { params: { second: 'one' }, consumed: 1 },
+ { params: { rest: ['one'] }, consumed: 1 },
+ ]);
+ });
+
+ it('formats URL-safe primitive parameters', () => {
+ const pattern = compileRoutePattern({
+ path: 'item/:id/:enabled/:revision',
+ });
+ expect(pattern.format({ id: 42, enabled: true, revision: 3n })).toEqual([
+ 'item',
+ '42',
+ 'true',
+ '3',
+ ]);
+ });
+
+ it('requires transformed values to be serialized before formatting', () => {
+ const pattern = compileRoutePattern({ path: 'calendar/:day' });
+ const day = new Date('2026-01-02T00:00:00.000Z');
+ expect(() => pattern.format({ day })).toThrow('requires serializeParams');
+ expect(pattern.format({ day: day.toISOString().slice(0, 10) })).toEqual([
+ 'calendar',
+ '2026-01-02',
+ ]);
+ });
+});
diff --git a/apps/web/src/lib/split-router/tests/router.test.ts b/apps/web/src/lib/split-router/tests/router.test.ts
new file mode 100644
index 0000000000..b4b673d2a7
--- /dev/null
+++ b/apps/web/src/lib/split-router/tests/router.test.ts
@@ -0,0 +1,1375 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { z } from 'zod';
+import { createMemorySplitRouterLocation } from '../integrations/memory';
+import * as path from '../path';
+import { createSplitRouter } from '../router';
+import { defineRoute, rootRouteMatch, routeParams } from '../routes';
+import type {
+ SplitRouterEntry,
+ SplitRouterExternalLocation,
+ SplitRouterExternalLocationValue,
+ SplitRouterLayout,
+ SplitRouterLayoutSnapshot,
+ SplitRouterMiddleware,
+ SplitRouterSettledChange,
+ SplitRoutes,
+} from '../types';
+
+type Layout = SplitRouterLayout<string> & {
+ reconcileCount(): number;
+ activatedSplitId(): string | undefined;
+};
+
+const driveFolderRoute = defineRoute({
+ id: 'drive-folder',
+ path: 'folder/:folderId',
+ params: z.object({ folderId: z.string() }),
+ claim: ({ folderId }) => ({ namespace: 'folder', id: folderId }),
+});
+
+const routes: SplitRoutes = {
+ definitions: [
+ defineRoute({
+ id: 'drive',
+ path: 'drive',
+ search: ['drive'],
+ children: [driveFolderRoute],
+ }),
+ {
+ id: 'legacy',
+ path: 'legacy/:id',
+ params: z.object({ id: z.string() }),
+ },
+ ],
+ globalSearch: ['referral_code'],
+};
+
+function createLayout(): Layout {
+ let nextId = 0;
+ let reconciliations = 0;
+ let activatedSplitId: string | undefined;
+ let entries: SplitRouterLayoutSnapshot<string>['entries'] = [];
+ const listeners = new Set<(change: SplitRouterSettledChange) => void>();
+
+ const notify = (history: 'push' | 'replace' = 'push') => {
+ for (const listener of listeners) {
+ listener({ history });
+ }
+ };
+
+ return {
+ snapshot: () => ({ entries }),
+
+ updateCurrentEntry(splitId, update) {
+ entries = entries.map((entry) =>
+ entry.splitId === splitId ? { splitId, ...update(entry) } : entry
+ );
+ notify();
+ },
+
+ open({ location, target, replace }) {
+ const next = {
+ splitId: `split-${++nextId}`,
+ location,
+ };
+ if (target === 'new-split' || !target) {
+ entries = [...entries, next];
+ } else {
+ const index = entries.findIndex((entry) => entry.splitId === target);
+
+ if (index < 0) {
+ entries = [...entries, next];
+ } else {
+ entries = entries.with(index, {
+ ...next,
+ splitId: entries[index]!.splitId,
+ });
+ }
+ }
+ notify(replace ? 'replace' : 'push');
+ },
+
+ reconcile(nextEntries) {
+ reconciliations++;
+ entries = nextEntries.map((entry, index) => {
+ const current = entries[index];
+
+ return {
+ splitId: current?.splitId ?? `split-${++nextId}`,
+ ...entry,
+ };
+ });
+ notify('replace');
+ },
+
+ activate(splitId) {
+ activatedSplitId = splitId;
+ },
+
+ subscribe(listener) {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+
+ reconcileCount: () => reconciliations,
+ activatedSplitId: () => activatedSplitId,
+ };
+}
+
+const settle = () => new Promise<void>((resolve) => queueMicrotask(resolve));
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('split router', () => {
+ it('owns one manifest per router and only shares explicitly supplied state', async () => {
+ const compile = vi.spyOn(path, 'compileRoutePattern');
+ const layout = createLayout();
+ const first = createSplitRouter({
+ layout,
+ routes,
+ location: createMemorySplitRouterLocation('/drive/folder/one'),
+ });
+ const manifest = first.routes;
+ expect(compile).toHaveBeenCalledTimes(3);
+ const splitId = layout.snapshot().entries[0]!.splitId;
+ first.navigate(splitId, {
+ route: driveFolderRoute,
+ params: { folderId: 'two' },
+ });
+ await first.settled();
+ first.updateSearch(splitId, 'drive', { sort: ['name'] });
+ await first.settled();
+ expect(first.href(splitId)).toBe('/drive/folder/two?s0.drive.sort=name');
+ expect(first.routes).toBe(manifest);
+ expect(compile).toHaveBeenCalledTimes(3);
+
+ const second = createSplitRouter({
+ layout: createLayout(),
+ routes,
+ location: createMemorySplitRouterLocation('/drive'),
+ });
+ expect(second.routes).not.toBe(manifest);
+ expect(second.routes.byId).not.toBe(manifest.byId);
+ expect(compile).toHaveBeenCalledTimes(6);
+
+ const adopted = createSplitRouter({
+ layout: createLayout(),
+ routes: manifest,
+ location: createMemorySplitRouterLocation('/drive'),
+ });
+ expect(adopted.routes).toBe(manifest);
+ expect(compile).toHaveBeenCalledTimes(6);
+ first.dispose();
+ second.dispose();
+ adopted.dispose();
+ });
+ it('rejects unresolved host snapshots before accepting state or committing a URL', () => {
+ const layout = createLayout();
+ layout.reconcile([{ location: {} } as SplitRouterEntry]);
+ const location = createMemorySplitRouterLocation('/drive');
+ expect(() => createSplitRouter({ layout, routes, location })).toThrow(
+ 'nonempty match branch'
+ );
+ expect(location.history()).toHaveLength(1);
+ });
+
+ it('does not accept malformed middleware proposals into layout or history', () => {
+ const layout = createLayout();
+ const location = createMemorySplitRouterLocation('/drive');
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [
+ ({ to, cause }) => {
+ if (cause === 'navigate')
+ to.location.route = { matches: [{ id: 'missing', params: {} }] };
+ },
+ ],
+ });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+ expect(() => router.navigate(splitId, 'folder/one')).toThrow(
+ 'invalid match branch'
+ );
+ expect(router.route(splitId)?.matches[0].id).toBe('drive');
+ expect(router.history(splitId)?.entries).toHaveLength(1);
+ expect(location.read().pathname).toBe('/drive');
+ expect(router.location('missing')).toBeUndefined();
+ router.dispose();
+ });
+
+ it('keeps same-route search state during relative navigation', async () => {
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one?s0.drive.sort=created_at'
+ );
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.navigate(splitId, 'folder/two');
+ await settle();
+
+ expect(location.read()).toEqual({
+ pathname: '/drive/folder/two',
+ search: '?s0.drive.sort=created_at',
+ hash: '',
+ });
+
+ location.back();
+ expect(routeParams(router.location(splitId)?.route).folderId).toBe('one');
+ expect(router.canGo(splitId, 1)).toBe(true);
+ location.forward();
+ expect(routeParams(router.location(splitId)?.route).folderId).toBe('two');
+ expect(router.canGo(splitId, -1)).toBe(true);
+ });
+
+ it('navigates to a typed route with typed params', async () => {
+ const location = createMemorySplitRouterLocation('/drive/folder/one');
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.navigate(splitId, {
+ route: driveFolderRoute,
+ params: { folderId: 'two' },
+ });
+ await router.settled();
+
+ expect(location.read().pathname).toBe('/drive/folder/two');
+ });
+
+ it('activates an existing split that owns the same route claim', async () => {
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one/~/drive/folder/two'
+ );
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const [first, second] = layout.snapshot().entries;
+
+ router.navigate(second!.splitId, {
+ route: driveFolderRoute,
+ params: { folderId: 'one' },
+ });
+ await router.settled();
+
+ expect(layout.activatedSplitId()).toBe(first!.splitId);
+ expect(location.read().pathname).toBe(
+ '/drive/folder/one/~/drive/folder/two'
+ );
+ });
+
+ it('allows callers to bypass a route claim explicitly', async () => {
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one/~/drive/folder/two'
+ );
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const second = layout.snapshot().entries[1]!;
+
+ router.navigate(
+ second.splitId,
+ {
+ route: driveFolderRoute,
+ params: { folderId: 'one' },
+ },
+ { allowDuplicate: true }
+ );
+ await router.settled();
+
+ expect(layout.activatedSplitId()).toBeUndefined();
+ expect(location.read().pathname).toBe(
+ '/drive/folder/one/~/drive/folder/one'
+ );
+ });
+
+ it.each([false, true])(
+ 'checks final claims after middleware (async: %s)',
+ async (asyncMiddleware) => {
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one/~/drive/folder/two'
+ );
+ const layout = createLayout();
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [
+ ({ cause, path, redirect }) => {
+ if (cause !== 'navigate' || path !== '/drive/folder/three') return;
+ const result = redirect('/drive/folder/one');
+ return asyncMiddleware ? Promise.resolve(result) : result;
+ },
+ ],
+ });
+ const [first, second] = layout.snapshot().entries;
+ router.navigate(second!.splitId, '/drive/folder/three');
+ await router.settled();
+ expect(layout.activatedSplitId()).toBe(first!.splitId);
+ expect(location.read().pathname).toBe(
+ '/drive/folder/one/~/drive/folder/two'
+ );
+ expect(router.history(second!.splitId)?.entries).toHaveLength(1);
+ router.dispose();
+ }
+ );
+
+ it.each([false, true])(
+ 'rechecks reentrant navigation at the async commit boundary (new owner: %s)',
+ async (newOwner) => {
+ const layout = createLayout();
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one/~/drive/folder/two'
+ );
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [
+ ({ cause, path, redirect }) => {
+ if (cause === 'navigate' && path === '/drive/folder/three') {
+ return Promise.resolve(redirect('/drive/folder/shared'));
+ }
+ },
+ ],
+ });
+ const [first, second] = layout.snapshot().entries;
+ let handled = false;
+ router.subscribe((splitId) => {
+ if (
+ handled ||
+ splitId !== first!.splitId ||
+ routeParams(router.route(splitId)).folderId !== 'shared'
+ )
+ return;
+ handled = true;
+ if (newOwner) {
+ router.navigate(second!.splitId, '/drive/folder/shared', {
+ allowDuplicate: true,
+ });
+ } else {
+ router.navigate(first!.splitId, '/drive/folder/other');
+ }
+ });
+ router.navigate(first!.splitId, '/drive/folder/three');
+ await router.settled();
+ expect(handled).toBe(true);
+ expect(location.read().pathname).toBe(
+ newOwner
+ ? '/drive/folder/one/~/drive/folder/shared'
+ : '/drive/folder/other/~/drive/folder/two'
+ );
+ if (newOwner) {
+ expect(layout.activatedSplitId()).toBe(second!.splitId);
+ expect(router.history(first!.splitId)?.entries).toHaveLength(1);
+ }
+ router.dispose();
+ }
+ );
+
+ it('does not activate the original claim when middleware redirects away', async () => {
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one/~/drive/folder/two'
+ );
+ const layout = createLayout();
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [
+ ({ cause, path, redirect }) => {
+ if (cause === 'navigate' && path === '/drive/folder/one')
+ return redirect('/drive/folder/three');
+ },
+ ],
+ });
+ const second = layout.snapshot().entries[1]!;
+ router.navigate(second.splitId, '/drive/folder/one');
+ await router.settled();
+ expect(layout.activatedSplitId()).toBeUndefined();
+ expect(location.read().pathname).toBe(
+ '/drive/folder/one/~/drive/folder/three'
+ );
+ router.dispose();
+ });
+
+ it.each(['current', 'new-split'] as const)(
+ 'reserves concurrent claims in request order (%s)',
+ async (target) => {
+ const gates = [
+ Promise.withResolvers<void>(),
+ Promise.withResolvers<void>(),
+ ];
+ let requests = 0;
+ const layout = createLayout();
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one/~/drive/folder/two/~/drive/folder/three'
+ );
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [
+ ({ cause }) => {
+ if (cause === 'navigate') return gates[requests++]!.promise;
+ },
+ ],
+ });
+ const [, second, third] = layout.snapshot().entries;
+ router.navigate(second!.splitId, '/drive/folder/shared', { target });
+ router.navigate(third!.splitId, '/drive/folder/shared', { target });
+ gates[1]!.resolve();
+ await settle();
+ await settle();
+ expect(location.read().pathname).not.toContain('shared');
+ gates[0]!.resolve();
+ await router.settled();
+ const entries = layout.snapshot().entries;
+ const owners = entries.filter(
+ (entry) => routeParams(entry.location.route).folderId === 'shared'
+ );
+ expect(owners).toHaveLength(1);
+ expect(entries).toHaveLength(target === 'new-split' ? 4 : 3);
+ expect(layout.activatedSplitId()).toBe(owners[0]!.splitId);
+ if (target === 'current') {
+ expect(owners[0]!.splitId).toBe(second!.splitId);
+ expect(router.history(third!.splitId)?.entries).toHaveLength(1);
+ }
+ router.dispose();
+ }
+ );
+
+ it('releases the old reservation when its owner redirects elsewhere', async () => {
+ const gate = Promise.withResolvers<void>();
+ let requests = 0;
+ const layout = createLayout();
+ const location = createMemorySplitRouterLocation('/drive');
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [
+ async ({ cause, path, redirect }) => {
+ if (cause !== 'navigate' || path !== '/drive/folder/shared') return;
+ if (++requests === 1) {
+ await gate.promise;
+ return redirect('/drive/folder/other');
+ }
+ },
+ ],
+ });
+ await router.settled();
+ const splitId = layout.snapshot().entries[0]!.splitId;
+ router.navigate(splitId, '/drive/folder/shared', { target: 'new-split' });
+ router.navigate(splitId, '/drive/folder/shared', { target: 'new-split' });
+ gate.resolve();
+ await router.settled();
+ expect(
+ layout
+ .snapshot()
+ .entries.map((entry) => routeParams(entry.location.route).folderId)
+ ).toEqual([undefined, 'other', 'shared']);
+ router.dispose();
+ });
+
+ it('releases superseded claims even when the old middleware ignores abort', async () => {
+ const gate = Promise.withResolvers<void>();
+ let requests = 0;
+ const layout = createLayout();
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one/~/drive/folder/two'
+ );
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [
+ ({ cause, path }) => {
+ if (
+ cause === 'navigate' &&
+ path === '/drive/folder/shared' &&
+ ++requests === 1
+ )
+ return gate.promise;
+ },
+ ],
+ });
+ const [first, second] = layout.snapshot().entries;
+ router.navigate(first!.splitId, '/drive/folder/shared');
+ router.navigate(second!.splitId, '/drive/folder/shared');
+ router.navigate(first!.splitId, '/drive/folder/other');
+ await router.settled();
+ expect(location.read().pathname).toBe(
+ '/drive/folder/other/~/drive/folder/shared'
+ );
+ gate.resolve();
+ await settle();
+ await settle();
+ expect(location.read().pathname).toBe(
+ '/drive/folder/other/~/drive/folder/shared'
+ );
+ router.dispose();
+ });
+
+ it('releases a failed transition claim so its next contender can commit', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const gate = Promise.withResolvers<void>();
+ let requests = 0;
+ const layout = createLayout();
+ const location = createMemorySplitRouterLocation('/drive');
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [
+ async ({ cause, to }) => {
+ if (cause !== 'navigate' || ++requests !== 1) return;
+ await gate.promise;
+ to.location.route = { matches: [{ id: 'missing', params: {} }] };
+ },
+ ],
+ });
+ await router.settled();
+ const splitId = layout.snapshot().entries[0]!.splitId;
+ router.navigate(splitId, '/drive/folder/shared', { target: 'new-split' });
+ router.navigate(splitId, '/drive/folder/shared', { target: 'new-split' });
+ gate.resolve();
+ await router.settled();
+ expect(location.read().pathname).toBe('/drive/~/drive/folder/shared');
+ expect(console.error).toHaveBeenCalledWith(
+ 'Split router transition failed',
+ expect.any(Error)
+ );
+ router.dispose();
+ });
+
+ it('bypasses pending and redirected claims with allowDuplicate', async () => {
+ const gate = Promise.withResolvers<void>();
+ let requests = 0;
+ const layout = createLayout();
+ const location = createMemorySplitRouterLocation('/drive');
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [
+ ({ cause, path, redirect }) => {
+ if (cause !== 'navigate') return;
+ if (path === '/drive/folder/alias')
+ return redirect('/drive/folder/shared');
+ if (path === '/drive/folder/shared' && ++requests === 1)
+ return gate.promise;
+ },
+ ],
+ });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+ router.navigate(splitId, '/drive/folder/shared', { target: 'new-split' });
+ router.navigate(splitId, '/drive/folder/alias', {
+ target: 'new-split',
+ allowDuplicate: true,
+ });
+ await settle();
+ expect(location.read().pathname).toBe('/drive/~/drive/folder/shared');
+ gate.resolve();
+ await router.settled();
+ expect(location.read().pathname).toBe('/drive/~/drive/folder/shared');
+ router.navigate(splitId, '/drive/folder/alias', {
+ target: 'new-split',
+ allowDuplicate: true,
+ });
+ await router.settled();
+ expect(location.read().pathname).toBe(
+ '/drive/~/drive/folder/shared/~/drive/folder/shared'
+ );
+ router.dispose();
+ });
+
+ it('checks history claims without moving the cursor when another pane owns the destination', async () => {
+ const layout = createLayout();
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one/~/drive/folder/two'
+ );
+ const router = createSplitRouter({ layout, routes, location });
+ const [first, second] = layout.snapshot().entries;
+ router.navigate(first!.splitId, '/drive/folder/three');
+ router.navigate(second!.splitId, '/drive/folder/one');
+ await router.settled();
+ router.navigate(first!.splitId, -1);
+ await router.settled();
+ expect(layout.activatedSplitId()).toBe(second!.splitId);
+ expect(router.history(first!.splitId)?.index).toBe(1);
+ expect(location.read().pathname).toBe(
+ '/drive/folder/three/~/drive/folder/one'
+ );
+ router.navigate(first!.splitId, -1, { allowDuplicate: true });
+ await router.settled();
+ expect(router.history(first!.splitId)?.index).toBe(0);
+ expect(location.read().pathname).toBe(
+ '/drive/folder/one/~/drive/folder/one'
+ );
+ router.dispose();
+ });
+
+ it('checks search redirects but preserves same-claim updates in restored duplicate panes', async () => {
+ const layout = createLayout();
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one/~/drive/folder/one/~/drive/folder/two'
+ );
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [
+ ({ cause, path, redirect }) => {
+ if (cause === 'search' && path === '/drive/folder/two')
+ return redirect('/drive/folder/one');
+ },
+ ],
+ });
+ const [first, second, third] = layout.snapshot().entries;
+ router.updateSearch(second!.splitId, 'drive', { sort: ['name'] });
+ await router.settled();
+ expect(router.search(second!.splitId, 'drive')).toEqual({ sort: ['name'] });
+ expect(layout.activatedSplitId()).toBeUndefined();
+ router.updateSearch(third!.splitId, 'drive', { sort: ['name'] });
+ await router.settled();
+ expect(layout.activatedSplitId()).toBe(first!.splitId);
+ expect(router.search(third!.splitId, 'drive')).toBeUndefined();
+ expect(router.history(third!.splitId)?.entries).toHaveLength(1);
+ router.dispose();
+ });
+
+ it('cancels an accepted owner’s pending departure when activating its claim', async () => {
+ const gate = Promise.withResolvers<void>();
+ const layout = createLayout();
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one/~/drive/folder/two'
+ );
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [
+ ({ cause, path }) => {
+ if (cause === 'navigate' && path === '/drive/folder/three')
+ return gate.promise;
+ },
+ ],
+ });
+ const [first, second] = layout.snapshot().entries;
+ router.navigate(first!.splitId, '/drive/folder/three');
+ expect(routeParams(router.route(first!.splitId)).folderId).toBe('three');
+ router.navigate(second!.splitId, '/drive/folder/one');
+ expect(routeParams(router.route(first!.splitId)).folderId).toBe('one');
+ gate.resolve();
+ await router.settled();
+ expect(layout.activatedSplitId()).toBe(first!.splitId);
+ expect(location.read().pathname).toBe(
+ '/drive/folder/one/~/drive/folder/two'
+ );
+ router.dispose();
+ });
+
+ it('restores external duplicates while canceling reservations and permits a fresh acquisition', async () => {
+ const gate = Promise.withResolvers<void>();
+ let requests = 0;
+ const layout = createLayout();
+ const location = createMemorySplitRouterLocation('/drive');
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [
+ ({ cause }) => {
+ if (cause === 'navigate' && ++requests === 1) return gate.promise;
+ },
+ ],
+ });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+ router.navigate(splitId, '/drive/folder/shared', { target: 'new-split' });
+ router.navigate(splitId, '/drive/folder/shared', { target: 'new-split' });
+ location.set('/drive/folder/one/~/drive/folder/one');
+ await router.settled();
+ expect(location.read().pathname).toBe(
+ '/drive/folder/one/~/drive/folder/one'
+ );
+ router.navigate(splitId, '/drive/folder/shared', { target: 'new-split' });
+ await router.settled();
+ gate.resolve();
+ await settle();
+ await settle();
+ expect(location.read().pathname).toBe(
+ '/drive/folder/one/~/drive/folder/one/~/drive/folder/shared'
+ );
+ router.dispose();
+ });
+
+ it('publishes pending-state removal when a replacement navigation reuses another owner', async () => {
+ const gate = Promise.withResolvers<void>();
+ const layout = createLayout();
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one/~/drive/folder/two'
+ );
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [
+ ({ cause, path }) => {
+ if (cause === 'navigate' && path === '/drive/folder/three')
+ return gate.promise;
+ },
+ ],
+ });
+ const [first, second] = layout.snapshot().entries;
+ const seen: unknown[] = [];
+ router.subscribe((splitId) => {
+ if (splitId === second!.splitId)
+ seen.push(routeParams(router.route(splitId)).folderId);
+ });
+ router.navigate(second!.splitId, '/drive/folder/three');
+ router.navigate(second!.splitId, '/drive/folder/one');
+ expect(seen).toEqual(['three', 'two']);
+ expect(layout.activatedSplitId()).toBe(first!.splitId);
+ gate.resolve();
+ await router.settled();
+ router.dispose();
+ });
+
+ it('cancels pending reservations on disposal and ignores subsequent navigation', async () => {
+ const gate = Promise.withResolvers<void>();
+ let requests = 0;
+ const layout = createLayout();
+ const location = createMemorySplitRouterLocation('/drive');
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [
+ ({ cause }) => {
+ if (cause === 'navigate' && ++requests === 1) return gate.promise;
+ },
+ ],
+ });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+ router.navigate(splitId, '/drive/folder/shared', { target: 'new-split' });
+ router.navigate(splitId, '/drive/folder/shared', { target: 'new-split' });
+ router.dispose();
+ gate.resolve();
+ await router.settled();
+ router.navigate(splitId, '/drive/folder/other');
+ router.updateSearch(splitId, 'drive', { sort: ['name'] });
+ expect(location.read().pathname).toBe('/drive');
+ expect(location.read().search).toBe('');
+ });
+
+ it('traverses route history without changing another split', async () => {
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one/~/drive/folder/other'
+ );
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const [first, second] = layout.snapshot().entries;
+
+ router.navigate(first!.splitId, '/drive/folder/two');
+ router.navigate(first!.splitId, '/drive/folder/three');
+ await router.settled();
+
+ expect(router.canGo(first!.splitId, -2)).toBe(true);
+ router.navigate(first!.splitId, -1);
+ await router.settled();
+
+ expect(routeParams(router.route(first!.splitId)).folderId).toBe('two');
+ expect(routeParams(router.route(second!.splitId)).folderId).toBe('other');
+ expect(router.canGo(first!.splitId, 1)).toBe(true);
+ expect(router.history(first!.splitId)?.index).toBe(1);
+ expect(router.history(first!.splitId)?.entries).toHaveLength(3);
+
+ router.navigate(first!.splitId, 1);
+ await router.settled();
+ expect(routeParams(router.route(first!.splitId)).folderId).toBe('three');
+ });
+
+ it('pushes a repeated route as a new history entry', async () => {
+ const location = createMemorySplitRouterLocation('/drive/folder/one');
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.navigate(splitId, '/drive/folder/two');
+ await router.settled();
+ router.navigate(splitId, '/drive/folder/one');
+ await router.settled();
+ router.navigate(splitId, -1);
+ await router.settled();
+
+ expect(routeParams(router.route(splitId)).folderId).toBe('two');
+ });
+
+ it('restores search state during history traversal', async () => {
+ const location = createMemorySplitRouterLocation('/drive/folder/one');
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.updateSearch(splitId, 'drive', { sort: ['name'] });
+ await router.settled();
+ expect(router.search(splitId, 'drive')).toEqual({ sort: ['name'] });
+
+ router.navigate(splitId, -1);
+ await router.settled();
+ expect(router.search(splitId, 'drive')).toBeUndefined();
+
+ router.navigate(splitId, 1);
+ await router.settled();
+ expect(router.search(splitId, 'drive')).toEqual({ sort: ['name'] });
+ });
+
+ it('replaces history and truncates forward entries', async () => {
+ const location = createMemorySplitRouterLocation('/drive/folder/one');
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.navigate(splitId, '/drive/folder/two', { replace: true });
+ await router.settled();
+ expect(router.canGo(splitId, -1)).toBe(false);
+
+ router.navigate(splitId, '/drive/folder/three');
+ await router.settled();
+ router.navigate(splitId, -1);
+ await router.settled();
+ router.navigate(splitId, '/drive/folder/four');
+ await router.settled();
+
+ expect(router.canGo(splitId, 1)).toBe(false);
+ expect(routeParams(router.route(splitId)).folderId).toBe('four');
+ });
+
+ it('runs history traversal through middleware', async () => {
+ const causes: string[] = [];
+ const location = createMemorySplitRouterLocation('/drive/folder/one');
+ const layout = createLayout();
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [
+ ({ cause }) => {
+ causes.push(cause);
+ },
+ ],
+ });
+ await router.settled();
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.navigate(splitId, '/drive/folder/two');
+ await router.settled();
+ router.navigate(splitId, -1);
+ await router.settled();
+
+ expect(causes).toContain('history');
+ expect(routeParams(router.route(splitId)).folderId).toBe('one');
+ });
+
+ it('waits for async middleware before applying history traversal', async () => {
+ let release!: () => void;
+ let blockHistory = false;
+ const preload = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const location = createMemorySplitRouterLocation('/drive/folder/one');
+ const layout = createLayout();
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [
+ ({ cause }) =>
+ cause === 'history' && blockHistory ? preload : undefined,
+ ],
+ });
+ await router.settled();
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.navigate(splitId, '/drive/folder/two');
+ await router.settled();
+ blockHistory = true;
+ router.navigate(splitId, -1);
+
+ expect(location.read().pathname).toBe('/drive/folder/two');
+ expect(routeParams(router.route(splitId)).folderId).toBe('one');
+
+ release();
+ await router.settled();
+
+ expect(location.read().pathname).toBe('/drive/folder/one');
+ expect(routeParams(router.route(splitId)).folderId).toBe('one');
+ });
+
+ it('commits route and search updates together', async () => {
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one?s0.drive.scope=all&s0.drive.sort=created_at'
+ );
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.navigate(splitId, 'folder/two', {
+ search: {
+ drive(current = {}) {
+ const next = { ...current };
+
+ delete next.scope;
+
+ return next;
+ },
+ },
+ });
+ await settle();
+
+ expect(location.history()).toHaveLength(2);
+ expect(location.read()).toEqual({
+ pathname: '/drive/folder/two',
+ search: '?s0.drive.sort=created_at',
+ hash: '',
+ });
+ });
+
+ it('applies search writes without losing the latest value', async () => {
+ const location = createMemorySplitRouterLocation('/drive');
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.updateSearch(
+ splitId,
+ 'drive',
+ { sort: ['name'] },
+ { history: 'replace' }
+ );
+ router.updateSearch(
+ splitId,
+ 'drive',
+ { sort: ['created_at'] },
+ { history: 'push' }
+ );
+ await settle();
+
+ expect(location.history()).toHaveLength(2);
+ expect(location.read().search).toBe('?s0.drive.sort=created_at');
+ });
+
+ it('drops unowned route search and rejects writes to it', async () => {
+ const location = createMemorySplitRouterLocation(
+ '/drive?s0.drive.sort=name&s0.other.value=ignored'
+ );
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+ await settle();
+
+ expect(router.search(splitId, 'drive')).toEqual({ sort: ['name'] });
+ expect(router.search(splitId, 'other')).toBeUndefined();
+ expect(location.read().search).toBe('?s0.drive.sort=name');
+ expect(() =>
+ router.updateSearch(splitId, 'other', { value: ['nope'] })
+ ).toThrow('Split route does not own search namespace "other"');
+ expect(() =>
+ router.navigate(splitId, 'folder/one', {
+ search: { other: { value: ['nope'] } },
+ })
+ ).toThrow('Split route does not own search namespace "other"');
+ expect(() => router.updateSearch('missing', 'bad.name', {})).toThrow(
+ 'Invalid split search namespace "bad.name"'
+ );
+ expect(location.read().pathname).toBe('/drive');
+ expect(location.read().search).toBe('?s0.drive.sort=name');
+ });
+
+ it('merges rapid search writes while middleware is pending', async () => {
+ const middleware: SplitRouterMiddleware[] = [
+ async ({ cause }) => {
+ if (cause === 'search') await Promise.resolve();
+ },
+ ];
+ const location = createMemorySplitRouterLocation('/drive');
+ const layout = createLayout();
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware,
+ });
+ await router.settled();
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.updateSearch(splitId, 'drive', { sort: ['name'] });
+ router.updateSearch(splitId, 'drive', (current = {}) => ({
+ ...current,
+ type: ['pdf'],
+ }));
+ await router.settled();
+
+ expect(router.search(splitId, 'drive')).toEqual({
+ sort: ['name'],
+ type: ['pdf'],
+ });
+ expect(location.read().search).toBe(
+ '?s0.drive.sort=name&s0.drive.type=pdf'
+ );
+ });
+
+ it('publishes one state change for synchronous search middleware', async () => {
+ const location = createMemorySplitRouterLocation('/drive');
+ const layout = createLayout();
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [() => undefined],
+ });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+ const notifications: Array<string | undefined> = [];
+ router.subscribe((notifiedSplitId) => notifications.push(notifiedSplitId));
+
+ router.updateSearch(splitId, 'drive', { type: ['pdf'] });
+ await router.settled();
+
+ expect(notifications).toEqual([splitId]);
+ expect(location.read().search).toBe('?s0.drive.type=pdf');
+ });
+
+ it('scopes direct layout reconciliation to the changed split', async () => {
+ const location = createMemorySplitRouterLocation('/drive');
+ const layout = createLayout();
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [
+ ({ to, redirect }) =>
+ rootRouteMatch(to.location.route)?.id === 'legacy'
+ ? redirect('/drive/folder/redirected')
+ : undefined,
+ ],
+ });
+ const notifications: Array<string | undefined> = [];
+ router.subscribe((splitId) => notifications.push(splitId));
+
+ layout.open({
+ location: {
+ route: {
+ matches: [{ id: 'legacy', params: { id: 'document' } }],
+ },
+ },
+ target: 'new-split',
+ });
+ await router.settled();
+
+ const changedSplitId = layout.snapshot().entries[1]!.splitId;
+ expect(notifications).toEqual([changedSplitId]);
+ });
+
+ it('evaluates functional navigation search updates once', async () => {
+ let calls = 0;
+ const location = createMemorySplitRouterLocation('/drive');
+ const layout = createLayout();
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [() => undefined],
+ });
+ await router.settled();
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.navigate(splitId, '/drive/folder/two', {
+ search: {
+ drive(current = {}) {
+ calls++;
+ return { ...current, count: [String(calls)] };
+ },
+ },
+ });
+ await router.settled();
+
+ expect(calls).toBe(1);
+ expect(location.read().search).toBe('?s0.drive.count=1');
+ });
+
+ it('waits for async middleware before programmatic navigation', async () => {
+ let release!: () => void;
+ const preload = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const middleware: SplitRouterMiddleware[] = [
+ ({ cause }) => (cause === 'navigate' ? preload : undefined),
+ ];
+ const location = createMemorySplitRouterLocation('/drive/folder/one');
+ const layout = createLayout();
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware,
+ });
+ await router.settled();
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.navigate(splitId, '/drive/folder/two');
+
+ expect(location.read().pathname).toBe('/drive/folder/one');
+ expect(
+ routeParams(layout.snapshot().entries[0]?.location?.route).folderId
+ ).toBe('one');
+ expect(routeParams(router.location(splitId)?.route).folderId).toBe('two');
+
+ release();
+ await router.settled();
+
+ expect(location.read().pathname).toBe('/drive/folder/two');
+ expect(routeParams(router.location(splitId)?.route).folderId).toBe('two');
+ });
+
+ it('does not cancel middleware running for another split', async () => {
+ let releaseFirst!: () => void;
+ const firstPreload = new Promise<void>((resolve) => {
+ releaseFirst = resolve;
+ });
+ let firstSignal: AbortSignal | undefined;
+ const middleware: SplitRouterMiddleware[] = [
+ ({ cause, path, signal }) => {
+ if (cause === 'navigate' && path.endsWith('/one')) {
+ firstSignal = signal;
+ return firstPreload;
+ }
+ },
+ ];
+ const location = createMemorySplitRouterLocation('/drive/~/drive');
+ const layout = createLayout();
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware,
+ });
+ await router.settled();
+ const [first, second] = layout.snapshot().entries;
+
+ router.navigate(first!.splitId, '/drive/folder/one');
+ router.navigate(second!.splitId, '/drive/folder/two');
+ await settle();
+ await settle();
+
+ expect(firstSignal?.aborted).toBe(false);
+ expect(location.read().pathname).toBe('/drive/~/drive/folder/two');
+
+ releaseFirst();
+ await router.settled();
+
+ expect(location.read().pathname).toBe(
+ '/drive/folder/one/~/drive/folder/two'
+ );
+ });
+
+ it('cancels stale middleware when a newer navigation starts', async () => {
+ let firstSignal: AbortSignal | undefined;
+ const middleware: SplitRouterMiddleware[] = [
+ ({ cause, path, signal }) => {
+ if (cause !== 'navigate' || !path.endsWith('/one')) return;
+
+ firstSignal = signal;
+ return new Promise<void>((_resolve, reject) => {
+ signal.addEventListener('abort', () => reject(signal.reason));
+ });
+ },
+ ];
+ const location = createMemorySplitRouterLocation('/drive');
+ const layout = createLayout();
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware,
+ });
+ await router.settled();
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.navigate(splitId, '/drive/folder/one');
+ router.navigate(splitId, '/drive/folder/two');
+ await router.settled();
+
+ expect(firstSignal?.aborted).toBe(true);
+ expect(location.read().pathname).toBe('/drive/folder/two');
+ });
+
+ it('delays Back/Forward reconciliation until middleware settles', async () => {
+ let release!: () => void;
+ let blockExternal = false;
+ const preload = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const middleware: SplitRouterMiddleware[] = [
+ ({ cause }) =>
+ cause === 'external' && blockExternal ? preload : undefined,
+ ];
+ const location = createMemorySplitRouterLocation('/drive/folder/one');
+ const layout = createLayout();
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware,
+ });
+ await router.settled();
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.navigate(splitId, '/drive/folder/two');
+ await router.settled();
+ blockExternal = true;
+ location.back();
+
+ expect(location.read().pathname).toBe('/drive/folder/one');
+ expect(
+ routeParams(layout.snapshot().entries[0]?.location?.route).folderId
+ ).toBe('two');
+
+ release();
+ await router.settled();
+
+ expect(
+ routeParams(layout.snapshot().entries[0]?.location?.route).folderId
+ ).toBe('one');
+ });
+
+ it('repairs stale router commits that settle out of order', async () => {
+ let current: SplitRouterExternalLocationValue = {
+ pathname: '/drive',
+ search: '',
+ hash: '',
+ };
+ const pending: SplitRouterExternalLocationValue[] = [];
+ const listeners = new Set<
+ (location: SplitRouterExternalLocationValue) => void
+ >();
+ const location: SplitRouterExternalLocation = {
+ read: () => current,
+ commit: (next) => pending.push(next),
+ subscribe(listener) {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ };
+ const flush = (index = 0) => {
+ current = pending.splice(index, 1)[0]!;
+ for (const listener of listeners) listener(current);
+ };
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.updateSearch(splitId, 'drive', { sort: ['name'] });
+ router.updateSearch(splitId, 'drive', { sort: ['created_at'] });
+
+ flush(1);
+ flush();
+
+ expect(pending).toHaveLength(1);
+ flush();
+ await settle();
+
+ expect(router.search(splitId, 'drive')).toEqual({
+ sort: ['created_at'],
+ });
+ expect(location.read().search).toBe('?s0.drive.sort=created_at');
+ });
+
+ it('skips layout reconciliation for an identical external location', () => {
+ const location = createMemorySplitRouterLocation('/drive');
+ const layout = createLayout();
+ createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [() => undefined],
+ });
+
+ expect(layout.reconcileCount()).toBe(1);
+
+ location.set('/drive', { replace: true });
+
+ expect(layout.reconcileCount()).toBe(1);
+ });
+
+ it('restores duplicate routes by visible position', () => {
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one/~/drive/folder/two'
+ );
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const [first, second] = layout.snapshot().entries;
+
+ location.set('/drive/folder/three/~/drive/folder/four', { replace: true });
+
+ expect(routeParams(router.location(first!.splitId)?.route).folderId).toBe(
+ 'three'
+ );
+ expect(routeParams(router.location(second!.splitId)?.route).folderId).toBe(
+ 'four'
+ );
+ });
+
+ it('opens an explicitly requested new split', async () => {
+ const location = createMemorySplitRouterLocation('/drive');
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.navigate(splitId, 'folder/two', {
+ target: 'new-split',
+ });
+ await settle();
+
+ expect(layout.snapshot().entries).toHaveLength(2);
+ expect(location.read().pathname).toBe('/drive/~/drive/folder/two');
+ });
+
+ it('waits for async middleware before opening a new split', async () => {
+ let release!: () => void;
+ const preload = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const location = createMemorySplitRouterLocation('/drive');
+ const layout = createLayout();
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [({ cause }) => (cause === 'navigate' ? preload : undefined)],
+ });
+ await router.settled();
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.navigate(splitId, 'folder/two', { target: 'new-split' });
+
+ expect(layout.snapshot().entries).toHaveLength(1);
+
+ release();
+ await router.settled();
+
+ expect(layout.snapshot().entries).toHaveLength(2);
+ expect(location.read().pathname).toBe('/drive/~/drive/folder/two');
+ });
+
+ it('retains declared global search and drops unowned keys', async () => {
+ const location = createMemorySplitRouterLocation(
+ '/drive?referral_code=abc&temporary=value'
+ );
+ const layout = createLayout();
+ createSplitRouter({ layout, routes, location });
+
+ await settle();
+
+ expect(location.read().search).toBe('?referral_code=abc');
+ });
+});
diff --git a/apps/web/src/lib/split-router/tests/routes-manifest.test.ts b/apps/web/src/lib/split-router/tests/routes-manifest.test.ts
new file mode 100644
index 0000000000..db1b254190
--- /dev/null
+++ b/apps/web/src/lib/split-router/tests/routes-manifest.test.ts
@@ -0,0 +1,427 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { z } from 'zod';
+import * as path from '../path';
+import {
+ assertRouteState,
+ assertSearchNamespacesAllowed,
+ createRoutesManifest,
+ decodeRoute,
+ defineRoute,
+ encodeRoute,
+ filterRouteSearch,
+ findRouteBranch,
+ getExternalSearchKeys,
+ getRouteClaim,
+ getRouteSearchNamespaces,
+ resolveRouteBranch,
+ routeParams,
+} from '../routes';
+import type { SplitRouterEntry, SplitRouteState, SplitRoutes } from '../types';
+import {
+ decodeSplitRouterLocation,
+ serializeSplitRouterLocation,
+} from '../url';
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('split routes manifests', () => {
+ it('compiles once per explicit manifest, retaining original definition identity', () => {
+ const compile = vi.spyOn(path, 'compileRoutePattern');
+ const detail = defineRoute({ id: 'detail', path: 'document/:id' });
+ const workspace = defineRoute({
+ id: 'workspace',
+ path: 'workspace',
+ aliases: ['w'],
+ children: [detail],
+ search: ['workspace'],
+ });
+ const readDefinitions = vi.fn(() => [workspace]);
+ const routes: SplitRoutes = {
+ get definitions() {
+ return readDefinitions();
+ },
+ basePath: '/app',
+ };
+ const manifest = createRoutesManifest(routes);
+ expect(compile).toHaveBeenCalledTimes(2);
+ expect(readDefinitions).toHaveBeenCalledOnce();
+ expect(manifest.basePath).toEqual(['app']);
+
+ for (const id of ['one', 'two', 'three']) {
+ const entry = decodeSplitRouterLocation({
+ routes: manifest,
+ location: `/app/w/document/${id}`,
+ }).entries[0]!;
+ expect(
+ serializeSplitRouterLocation({
+ routes: manifest,
+ entries: [entry],
+ previous: '/',
+ })
+ ).toBe(`/app/workspace/document/${id}`);
+ const branch = resolveRouteBranch(manifest, entry.location.route);
+ expect(branch).toBe(findRouteBranch(manifest, 'detail'));
+ expect(branch[0]?.definition).toBe(workspace);
+ expect(branch[1]?.definition).toBe(detail);
+ expect(getRouteSearchNamespaces(manifest, entry.location.route)).toEqual(
+ new Set(['workspace'])
+ );
+ expect(getRouteClaim(manifest, entry.location.route)).toBeUndefined();
+ expect(getExternalSearchKeys(manifest, [entry])).toEqual(new Set());
+ }
+ expect(readDefinitions).toHaveBeenCalledOnce();
+ expect(compile).toHaveBeenCalledTimes(2);
+
+ // Identical definitions do not imply shared runtime state across owners.
+ const independent = createRoutesManifest(routes);
+ expect(independent).not.toBe(manifest);
+ expect(independent.byId).not.toBe(manifest.byId);
+ expect(findRouteBranch(independent, 'detail')).not.toBe(
+ findRouteBranch(manifest, 'detail')
+ );
+ expect(compile).toHaveBeenCalledTimes(4);
+ });
+
+ it('rejects unresolved runtime states without parsing schema outputs again', () => {
+ const parse = vi.fn((value: string) => new Date(value));
+ const manifest = createRoutesManifest({
+ definitions: [
+ defineRoute({
+ id: 'day',
+ path: 'day/:day',
+ params: z.object({ day: z.string().transform(parse) }),
+ serializeParams: ({ day }) => ({
+ day: day.toISOString().slice(0, 10),
+ }),
+ }),
+ ],
+ });
+ const entry = decodeRoute(manifest, ['day', '2026-01-02'])!;
+ expect(() =>
+ assertRouteState(manifest, entry.location.route)
+ ).not.toThrow();
+ expect(parse).toHaveBeenCalledTimes(1);
+ for (const state of [
+ undefined,
+ null,
+ {},
+ { matches: [] },
+ { matches: 'day' },
+ { matches: [{ id: 'missing', params: {} }] },
+ { matches: [{ id: 'day', params: [] }] },
+ { matches: [{ id: 'day' }] },
+ ]) {
+ expect(() => assertRouteState(manifest, state)).toThrow(
+ 'Split route state'
+ );
+ }
+ });
+
+ it('validates the whole manifest before matching, including unused branches', () => {
+ expect(() =>
+ createRoutesManifest({
+ definitions: [
+ { id: 'home', path: 'home' },
+ {
+ id: 'other',
+ path: 'other',
+ children: [{ id: 'home', path: 'child' }],
+ },
+ ],
+ })
+ ).toThrow('Duplicate split route id "home"');
+ expect(() =>
+ createRoutesManifest({
+ definitions: [{ id: 'bad', path: 'files/*rest/edit' }],
+ })
+ ).toThrow('must be the final segment');
+ });
+
+ it('keeps schema validation per match and falls through in declaration order', () => {
+ const parseId = vi.fn((id: number) => id);
+ const manifest = createRoutesManifest({
+ definitions: [
+ defineRoute({
+ id: 'number',
+ path: ':id',
+ params: z.object({ id: z.coerce.number().transform(parseId) }),
+ }),
+ { id: 'text', path: '*rest' },
+ ],
+ });
+ expect(parseId).not.toHaveBeenCalled();
+ expect(routeParams(decodeRoute(manifest, ['42'])?.location.route)).toEqual({
+ id: 42,
+ });
+ expect(routeParams(decodeRoute(manifest, ['43'])?.location.route)).toEqual({
+ id: 43,
+ });
+ expect(parseId).toHaveBeenCalledTimes(2);
+ expect(
+ decodeRoute(manifest, ['text'])?.location.route?.matches[0]?.id
+ ).toBe('text');
+ });
+
+ it('serializes transformed params per entry through the node codec', () => {
+ const serializeParams = vi.fn(({ day }: { day: Date }) => ({
+ day: day.toISOString().slice(0, 10),
+ }));
+ const manifest = createRoutesManifest({
+ definitions: [
+ defineRoute({
+ id: 'calendar',
+ path: 'calendar/:day',
+ params: z.object({ day: z.coerce.date() }),
+ serializeParams,
+ }),
+ ],
+ });
+ expect(serializeParams).not.toHaveBeenCalled();
+ for (const day of ['2026-01-02', '2026-02-03']) {
+ const entry = decodeRoute(manifest, ['calendar', day])!;
+ expect(encodeRoute(manifest, entry)).toEqual(['calendar', day]);
+ expect(serializeParams).toHaveBeenLastCalledWith({
+ day: new Date(`${day}T00:00:00.000Z`),
+ });
+ }
+ expect(serializeParams).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps primitive params usable without a custom serializer', () => {
+ const manifest = createRoutesManifest({
+ definitions: [
+ defineRoute({
+ id: 'page',
+ path: 'page/:id',
+ params: z.object({ id: z.coerce.number() }),
+ }),
+ ],
+ });
+ const node = manifest.byId.get('page')!;
+ const params = node.params.parse({ id: '42' })!;
+ expect(params).toEqual({ id: 42 });
+ expect(node.pattern.format(node.params.serialize(params))).toEqual([
+ 'page',
+ '42',
+ ]);
+ expect(node.params.parse({ id: 'invalid' })).toBeUndefined();
+ });
+
+ it('retains optional-parameter backtracking into children and canonical branch formatting', () => {
+ const manifest = createRoutesManifest({
+ definitions: [
+ {
+ id: 'workspace',
+ path: 'workspace/:workspaceId?',
+ aliases: ['w/:workspaceId?'],
+ children: [
+ { id: 'settings', path: 'settings/:tab', aliases: ['s/:tab'] },
+ ],
+ },
+ ],
+ });
+ const entry = decodeRoute(manifest, ['w', 's', 'account'])!;
+ expect(entry.location.route?.matches).toEqual([
+ { id: 'workspace', params: {} },
+ { id: 'settings', params: { tab: 'account' } },
+ ]);
+ expect(encodeRoute(manifest, entry)).toEqual([
+ 'workspace',
+ 'settings',
+ 'account',
+ ]);
+ });
+
+ it('tries later aliases after schema rejection but stops after the first valid match', () => {
+ const validate = vi.fn((params: { value: string }) => params);
+ const manifest = createRoutesManifest({
+ definitions: [
+ defineRoute({
+ id: 'item',
+ path: 'item/:invalid',
+ aliases: ['item/:value', ':prefix/:value'],
+ params: z.object({ value: z.string() }).transform(validate),
+ }),
+ ],
+ });
+ expect(
+ routeParams(decodeRoute(manifest, ['item', 'one'])?.location.route)
+ ).toEqual({ value: 'one' });
+ expect(validate).toHaveBeenCalledTimes(1);
+ });
+
+ it('evaluates deepest-first claims with current merged params and ancestor fallback', () => {
+ const parentClaim = vi.fn(({ workspaceId }: { workspaceId: string }) => ({
+ namespace: 'workspace',
+ id: workspaceId,
+ }));
+ const childClaim = vi.fn(
+ ({ workspaceId, id }: { workspaceId: string; id: string }) =>
+ id === 'none'
+ ? undefined
+ : { namespace: 'document', id: `${workspaceId}/${id}` }
+ );
+ const manifest = createRoutesManifest({
+ definitions: [
+ {
+ id: 'workspace',
+ path: 'workspace/:workspaceId',
+ claim: parentClaim,
+ children: [{ id: 'detail', path: 'document/:id', claim: childClaim }],
+ },
+ ],
+ });
+ expect(parentClaim).not.toHaveBeenCalled();
+ expect(childClaim).not.toHaveBeenCalled();
+ const first = decodeRoute(manifest, [
+ 'workspace',
+ 'one',
+ 'document',
+ 'first',
+ ])!;
+ expect(getRouteClaim(manifest, first.location.route)).toEqual({
+ namespace: 'document',
+ id: 'one/first',
+ });
+ expect(parentClaim).not.toHaveBeenCalled();
+ const second = decodeRoute(manifest, [
+ 'workspace',
+ 'two',
+ 'document',
+ 'none',
+ ])!;
+ expect(getRouteClaim(manifest, second.location.route)).toEqual({
+ namespace: 'workspace',
+ id: 'two',
+ });
+ expect(childClaim).toHaveBeenLastCalledWith({
+ workspaceId: 'two',
+ id: 'none',
+ });
+ expect(parentClaim).toHaveBeenLastCalledWith({
+ workspaceId: 'two',
+ id: 'none',
+ });
+ });
+
+ it('reuses inherited search ownership but evaluates dynamic external search per entry', () => {
+ const externalSearch = vi.fn((entry: SplitRouterEntry) => [
+ String(routeParams(entry.location.route).id),
+ ]);
+ const manifest = createRoutesManifest({
+ globalSearch: ['global'],
+ definitions: [
+ {
+ id: 'workspace',
+ path: 'workspace',
+ search: ['workspace'],
+ externalSearch: ['action'],
+ children: [
+ {
+ id: 'detail',
+ path: 'document/:id',
+ search: ['detail'],
+ externalSearch,
+ },
+ { id: 'legacy', path: 'legacy', search: '*' },
+ ],
+ },
+ ],
+ });
+ expect(externalSearch).not.toHaveBeenCalled();
+ const first = decodeRoute(manifest, ['workspace', 'document', 'one'])!;
+ const second = decodeRoute(manifest, ['workspace', 'document', 'two'])!;
+ expect(getRouteSearchNamespaces(manifest, first.location.route)).toBe(
+ getRouteSearchNamespaces(manifest, second.location.route)
+ );
+ expect(getRouteSearchNamespaces(manifest, first.location.route)).toEqual(
+ new Set(['workspace', 'detail'])
+ );
+ expect([...getExternalSearchKeys(manifest, [first])]).toEqual([
+ 'global',
+ 'action',
+ 'one',
+ ]);
+ expect([...getExternalSearchKeys(manifest, [second])]).toEqual([
+ 'global',
+ 'action',
+ 'two',
+ ]);
+ expect(externalSearch).toHaveBeenCalledTimes(2);
+ const search = {
+ workspace: { sort: ['name'] },
+ detail: { mode: ['edit'] },
+ extra: { x: ['1'] },
+ };
+ expect(filterRouteSearch(manifest, first.location.route, search)).toEqual({
+ workspace: search.workspace,
+ detail: search.detail,
+ });
+ const legacy = decodeRoute(manifest, ['workspace', 'legacy'])!;
+ expect(filterRouteSearch(manifest, legacy.location.route, search)).toBe(
+ search
+ );
+ });
+
+ it('validates namespace writes against inherited ownership or the legacy wildcard', () => {
+ const manifest = createRoutesManifest({
+ definitions: [
+ {
+ id: 'parent',
+ path: 'parent',
+ search: ['parent'],
+ children: [{ id: 'child', path: 'child', search: ['child'] }],
+ },
+ { id: 'legacy', path: 'legacy', search: '*' },
+ ],
+ });
+ const child = decodeRoute(manifest, ['parent', 'child'])!.location.route;
+ expect(() =>
+ assertSearchNamespacesAllowed(manifest, child, ['parent', 'child'])
+ ).not.toThrow();
+ expect(() =>
+ assertSearchNamespacesAllowed(manifest, child, ['other'])
+ ).toThrow('Split route does not own search namespace "other"');
+ const legacy = decodeRoute(manifest, ['legacy'])!.location.route;
+ expect(() =>
+ assertSearchNamespacesAllowed(manifest, legacy, ['other'])
+ ).not.toThrow();
+ for (const route of [child, legacy]) {
+ expect(() =>
+ assertSearchNamespacesAllowed(manifest, route, ['constructor'])
+ ).toThrow('Invalid split search namespace "constructor"');
+ }
+ });
+
+ it('rejects known IDs in the wrong branch rather than keeping a partial match', () => {
+ const root = {
+ id: 'root',
+ path: 'root',
+ children: [{ id: 'child', path: 'child' }],
+ };
+ const other = {
+ id: 'other',
+ path: 'other',
+ children: [{ id: 'other-child', path: 'child' }],
+ };
+ const manifest = createRoutesManifest({ definitions: [root, other] });
+ const invalid: SplitRouteState = {
+ matches: [
+ { id: 'root', params: {} },
+ { id: 'other-child', params: {} },
+ ],
+ };
+ expect(() => resolveRouteBranch(manifest, invalid)).toThrow(
+ 'invalid match branch'
+ );
+ expect(() => assertRouteState(manifest, invalid)).toThrow(
+ 'invalid match branch'
+ );
+ expect(() =>
+ encodeRoute(manifest, { location: { route: invalid } })
+ ).toThrow('invalid match branch');
+ expect(() =>
+ resolveRouteBranch(manifest, { matches: [{ id: 'child', params: {} }] })
+ ).toThrow('invalid match branch');
+ });
+});
diff --git a/apps/web/src/lib/split-router/tests/routes.test.ts b/apps/web/src/lib/split-router/tests/routes.test.ts
new file mode 100644
index 0000000000..afca13c46c
--- /dev/null
+++ b/apps/web/src/lib/split-router/tests/routes.test.ts
@@ -0,0 +1,282 @@
+import { describe, expect, expectTypeOf, it } from 'vitest';
+import { z } from 'zod';
+import {
+ createRoutesManifest,
+ decodeRoute,
+ defineRoute,
+ encodeRoute,
+ findRouteBranch,
+ getExternalSearchKeys,
+ getRouteClaim,
+ routeParams,
+ validateRouteParams,
+ validateSplitRoutes,
+} from '../routes';
+import type { InferSplitRouteParams } from '../types';
+
+const documentClaim = ({ documentId }: { documentId: string }) => ({
+ namespace: 'document',
+ id: documentId,
+});
+
+const driveRoute = defineRoute({
+ id: 'drive',
+ path: 'drive',
+ aliases: ['files'],
+ search: ['drive'],
+ externalSearch: ['action'],
+ children: [
+ {
+ id: 'drive-folder',
+ path: 'folder/:folderId',
+ params: z.object({ folderId: z.string() }),
+ children: [
+ {
+ id: 'drive-folder-detail',
+ path: 'pdf/:documentId',
+ params: z.object({ documentId: z.string() }),
+ claim: documentClaim,
+ externalSearch: ['preview'],
+ },
+ ],
+ },
+ {
+ id: 'drive-detail',
+ path: 'pdf/:documentId',
+ params: z.object({ documentId: z.string() }),
+ claim: documentClaim,
+ externalSearch: ['preview'],
+ },
+ ],
+});
+
+const routes = createRoutesManifest({
+ definitions: [
+ driveRoute,
+ {
+ id: 'legacy',
+ path: 'legacy/:id',
+ params: z.object({ id: z.string() }),
+ },
+ ],
+ globalSearch: ['referral_code'],
+});
+
+describe('split route parameter schemas', () => {
+ const issueRoute = defineRoute({
+ id: 'issue',
+ path: 'issue/:issueId',
+ params: z.object({ issueId: z.coerce.number().int().positive() }),
+ });
+
+ it('coerces URL strings to typed runtime values', () => {
+ const entry = decodeRoute(
+ createRoutesManifest({ definitions: [issueRoute] }),
+ ['issue', '42']
+ );
+
+ expect(routeParams(entry?.location.route)).toEqual({ issueId: 42 });
+ expectTypeOf(issueRoute.id).toEqualTypeOf<'issue'>();
+ expectTypeOf<InferSplitRouteParams<typeof issueRoute>>().toEqualTypeOf<{
+ issueId: number;
+ }>();
+ });
+
+ it('rejects invalid values', () => {
+ expect(
+ validateRouteParams(issueRoute.params, { issueId: 'not-a-number' })
+ ).toBeUndefined();
+ });
+
+ it('rejects asynchronous schemas', () => {
+ const schema = z.object({ id: z.string() }).transform(async ({ id }) => ({
+ id,
+ }));
+
+ expect(() => validateRouteParams(schema, { id: 'one' })).toThrow(
+ 'must be synchronous'
+ );
+ });
+});
+
+describe('split route operations', () => {
+ it('finds a route with its ancestors in manifest order', () => {
+ const branch = findRouteBranch(routes, 'drive-folder-detail');
+ expect(branch?.map(({ definition }) => definition.id)).toEqual([
+ 'drive',
+ 'drive-folder',
+ 'drive-folder-detail',
+ ]);
+ expect(branch?.[0]?.definition).toBe(driveRoute);
+ expect(findRouteBranch(routes, 'missing')).toBeUndefined();
+ });
+
+ it('matches by declaration order rather than path specificity', () => {
+ const definitions = [
+ defineRoute({ id: 'dynamic', path: ':id' }),
+ defineRoute({ id: 'static', path: 'recent' }),
+ ];
+ expect(
+ decodeRoute(createRoutesManifest({ definitions }), ['recent'])?.location
+ .route?.matches
+ ).toEqual([{ id: 'dynamic', params: { id: 'recent' } }]);
+ });
+
+ it('round trips nested feature paths', () => {
+ const entry = decodeRoute(routes, [
+ 'drive',
+ 'folder',
+ 'folder-1',
+ 'pdf',
+ 'document-1',
+ ]);
+
+ expect(entry?.location?.route).toEqual({
+ matches: [
+ { id: 'drive', params: {} },
+ { id: 'drive-folder', params: { folderId: 'folder-1' } },
+ {
+ id: 'drive-folder-detail',
+ params: { documentId: 'document-1' },
+ },
+ ],
+ });
+ expect(encodeRoute(routes, entry!)).toEqual([
+ 'drive',
+ 'folder',
+ 'folder-1',
+ 'pdf',
+ 'document-1',
+ ]);
+ });
+
+ it('merges params across a nested match branch', () => {
+ const entry = {
+ location: {
+ route: {
+ matches: [
+ { id: 'drive', params: {} },
+ { id: 'drive-folder', params: { folderId: 'folder-1' } },
+ {
+ id: 'drive-folder-detail',
+ params: { documentId: 'document-1' },
+ },
+ ] as const,
+ },
+ },
+ };
+
+ expect(routeParams(entry.location.route)).toEqual({
+ folderId: 'folder-1',
+ documentId: 'document-1',
+ });
+ expect(encodeRoute(routes, entry)).toEqual([
+ 'drive',
+ 'folder',
+ 'folder-1',
+ 'pdf',
+ 'document-1',
+ ]);
+ });
+
+ it('round trips transformed params with custom serialization', () => {
+ const calendarRoute = defineRoute({
+ id: 'calendar',
+ path: 'calendar/:day',
+ params: z.object({ day: z.coerce.date() }),
+ serializeParams: ({ day }) => ({ day: day.toISOString().slice(0, 10) }),
+ });
+ const calendarRoutes = createRoutesManifest({
+ definitions: [calendarRoute],
+ });
+ const entry = decodeRoute(calendarRoutes, ['calendar', '2026-01-02']);
+
+ expect(entry?.location?.route?.matches[0]?.params.day).toEqual(
+ new Date('2026-01-02T00:00:00.000Z')
+ );
+ expect(encodeRoute(calendarRoutes, entry!)).toEqual([
+ 'calendar',
+ '2026-01-02',
+ ]);
+ });
+
+ it('decodes aliases and encodes their canonical path', () => {
+ const entry = decodeRoute(routes, ['files', 'folder', 'folder-1']);
+
+ expect(entry?.location?.route?.matches[0]?.id).toBe('drive');
+ expect(encodeRoute(routes, entry!)).toEqual([
+ 'drive',
+ 'folder',
+ 'folder-1',
+ ]);
+ });
+
+ it('separates URL identity from claimed content identity', () => {
+ const direct = decodeRoute(routes, ['drive', 'pdf', 'document-1'])!;
+ const nested = decodeRoute(routes, [
+ 'drive',
+ 'folder',
+ 'folder-1',
+ 'pdf',
+ 'document-1',
+ ])!;
+
+ expect(getRouteClaim(routes, direct.location.route)).toEqual({
+ namespace: 'document',
+ id: 'document-1',
+ });
+ expect(getRouteClaim(routes, nested.location.route)).toEqual(
+ getRouteClaim(routes, direct.location.route)
+ );
+ });
+
+ it('returns only query keys owned by the proposed layout', () => {
+ const legacy = decodeRoute(routes, ['legacy', 'mail-1'])!;
+ const drive = decodeRoute(routes, ['drive'])!;
+ const detail = decodeRoute(routes, ['drive', 'pdf', 'document-1'])!;
+
+ expect([...getExternalSearchKeys(routes, [legacy])]).toEqual([
+ 'referral_code',
+ ]);
+ expect([...getExternalSearchKeys(routes, [drive])]).toEqual([
+ 'referral_code',
+ 'action',
+ ]);
+ expect([...getExternalSearchKeys(routes, [detail])]).toEqual([
+ 'referral_code',
+ 'action',
+ 'preview',
+ ]);
+ });
+
+ it('rejects a partial feature route instead of guessing', () => {
+ expect(decodeRoute(routes, ['drive', 'folder'])).toBeUndefined();
+ });
+
+ it('rejects ambiguous or invalid route manifests', () => {
+ expect(() =>
+ validateSplitRoutes({
+ definitions: [
+ { id: 'one', path: 'same' },
+ { id: 'two', path: 'other', aliases: ['same'] },
+ ],
+ })
+ ).toThrow('Duplicate sibling split route path "same"');
+ expect(() =>
+ validateSplitRoutes({
+ definitions: [
+ {
+ id: 'one',
+ path: 'one',
+ children: [{ id: 'one', path: 'child' }],
+ },
+ ],
+ })
+ ).toThrow('Duplicate split route id "one"');
+ expect(() =>
+ validateSplitRoutes({
+ definitions: [{ id: 'one', path: 'one', search: ['not.safe'] }],
+ })
+ ).toThrow('Invalid split search namespace "not.safe"');
+ });
+});
diff --git a/apps/web/src/lib/split-router/tests/search-params-codec.test.ts b/apps/web/src/lib/split-router/tests/search-params-codec.test.ts
new file mode 100644
index 0000000000..afc8ad01f1
--- /dev/null
+++ b/apps/web/src/lib/split-router/tests/search-params-codec.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, it } from 'vitest';
+import { z } from 'zod';
+import { createSearchParamsCodec } from '../search-params-codec';
+
+const defaults = { sort: 'name', page: 1, enabled: true, tags: ['default'] };
+const schema = z.object({
+ sort: z.enum(['name', 'recent']),
+ page: z.number().int().positive(),
+ enabled: z.boolean(),
+ tags: z.array(z.string()),
+});
+
+// No Solid owner or router is needed to exercise conversion and validation.
+describe('search params codec', () => {
+ it('uses the last scalar value while preserving repeated array values', () => {
+ const codec = createSearchParamsCodec({ schema, defaults });
+ const parsed = codec.parse({
+ sort: ['name', 'recent'],
+ page: ['2', '3'],
+ enabled: ['true', 'false'],
+ tags: ['b', 'a', 'b'],
+ });
+ expect(parsed).toEqual({
+ value: { sort: 'recent', page: 3, enabled: false, tags: ['b', 'a', 'b'] },
+ valid: true,
+ });
+ expect(codec.serialize(parsed.value)).toEqual({
+ sort: ['recent'],
+ page: ['3'],
+ enabled: ['false'],
+ tags: ['b', 'a', 'b'],
+ });
+ });
+
+ it('omits defaults and preserves the explicit empty-array marker', () => {
+ const codec = createSearchParamsCodec({ schema, defaults });
+ expect(codec.parse(undefined)).toEqual({ value: defaults, valid: true });
+ expect(codec.serialize(defaults)).toBeUndefined();
+ const empty = { ...defaults, tags: [] };
+ expect(codec.serialize(empty)).toEqual({ tags: [''] });
+ expect(codec.parse({ tags: [''] })).toEqual({ value: empty, valid: true });
+ expect(codec.parse({ tags: [] })).toEqual({ value: defaults, valid: true });
+ });
+
+ it('falls back on invalid inbound state and rejects invalid write candidates', () => {
+ const codec = createSearchParamsCodec({ schema, defaults });
+ expect(codec.parse({ page: ['not-a-number'] })).toEqual({
+ value: defaults,
+ valid: false,
+ });
+ expect(codec.validate({ ...defaults, page: -1 }).success).toBe(false);
+ expect(codec.validate({ ...defaults, page: 2 })).toEqual({
+ success: true,
+ data: { ...defaults, page: 2 },
+ });
+ expect(codec.parse({ unknown: ['ignored'] })).toEqual({
+ value: defaults,
+ valid: true,
+ });
+ });
+
+ it('passes the same array-valued representation to custom codecs', () => {
+ const codec = createSearchParamsCodec({
+ schema: z.object({ tags: z.array(z.string()) }),
+ defaults: { tags: [] as string[] },
+ deserialize: (params) => ({ tags: params.labels ?? [] }),
+ serialize: (value) => ({ labels: value.tags }),
+ });
+ const parsed = codec.parse({ labels: ['one', 'two', 'one'] });
+ expect(parsed).toEqual({
+ value: { tags: ['one', 'two', 'one'] },
+ valid: true,
+ });
+ const serialized = codec.serialize(parsed.value);
+ expect(serialized).toEqual({ labels: ['one', 'two', 'one'] });
+ expect(serialized?.labels).not.toBe(parsed.value.tags);
+ expect(codec.serialize({ tags: [] })).toBeUndefined();
+ });
+
+ it('falls back if a custom deserializer throws', () => {
+ const codec = createSearchParamsCodec({
+ schema,
+ defaults,
+ deserialize: () => {
+ throw new Error('bad URL');
+ },
+ serialize: () => undefined,
+ });
+ expect(codec.parse({ page: ['broken'] })).toEqual({
+ value: defaults,
+ valid: false,
+ });
+ });
+
+ it('accepts Standard Schema implementations without a safeParse method', () => {
+ const codec = createSearchParamsCodec({
+ defaults: { value: 'default' },
+ schema: {
+ '~standard': {
+ version: 1,
+ vendor: 'test',
+ validate: (value) => ({ value: value as { value: string } }),
+ },
+ },
+ });
+ expect(codec.parse({ value: ['one', 'two'] })).toEqual({
+ value: { value: 'two' },
+ valid: true,
+ });
+ });
+
+ it('rejects invalid defaults and asynchronous schemas at creation', () => {
+ expect(() =>
+ createSearchParamsCodec({ schema, defaults: { ...defaults, page: -1 } })
+ ).toThrow('Invalid defaults for search params');
+ expect(() =>
+ createSearchParamsCodec({
+ schema: schema.transform(async (value) => value),
+ defaults,
+ })
+ ).toThrow('must be synchronous');
+ });
+});
diff --git a/apps/web/src/lib/split-router/tests/search.test.ts b/apps/web/src/lib/split-router/tests/search.test.ts
new file mode 100644
index 0000000000..3266695f32
--- /dev/null
+++ b/apps/web/src/lib/split-router/tests/search.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from 'vitest';
+import {
+ normalizeSearchParams,
+ parseSearchState,
+ parseSplitSearch,
+ replaceSplitSearchParams,
+ updateSearchState,
+} from '../search';
+import type { SplitLocation } from '../types';
+
+describe('split search state', () => {
+ it('round trips repeated values and removes stale namespaced query keys', () => {
+ const query = new URLSearchParams('referral_code=ref&s9.old.value=stale');
+ const search = { drive: { tags: ['one', 'two'], sort: ['name'] } };
+ replaceSplitSearchParams(query, [{ location: { search } }]);
+
+ expect(query.get('referral_code')).toBe('ref');
+ expect(query.has('s9.old.value')).toBe(false);
+ expect(query.getAll('s0.drive.tags')).toEqual(['one', 'two']);
+ expect(parseSplitSearch(query.toString())).toEqual(new Map([[0, search]]));
+ });
+
+ it('ignores unsafe names and oversized inbound values', () => {
+ const query = new URLSearchParams({
+ 's0.constructor.value': 'unsafe',
+ 's0.drive.prototype': 'unsafe',
+ 's0.drive.large': 'x'.repeat(16_385),
+ 's0.drive.valid': 'ok',
+ });
+ expect(parseSplitSearch(query.toString())).toEqual(
+ new Map([[0, { drive: { valid: ['ok'] } }]])
+ );
+ expect(() => normalizeSearchParams({ constructor: ['unsafe'] })).toThrow(
+ 'Invalid split search field'
+ );
+ });
+
+ it('recovers only safe array-valued fields from persisted metadata', () => {
+ expect(
+ parseSearchState({
+ drive: {
+ tags: ['one', 42, 'two'],
+ bad: 'scalar',
+ prototype: ['unsafe'],
+ huge: ['x'.repeat(16_385)],
+ },
+ constructor: { field: ['unsafe'] },
+ other: { ok: ['value'] },
+ })
+ ).toEqual({ drive: { tags: ['one', 'two'] }, other: { ok: ['value'] } });
+ expect(parseSearchState(null)).toBeUndefined();
+ expect(parseSearchState({ drive: [] })).toBeUndefined();
+ });
+
+ it('updates namespaces without changing routes or sibling search', () => {
+ const location: SplitLocation = {
+ route: { matches: [{ id: 'drive', params: {} }] },
+ search: { drive: { tags: ['one'] }, sidebar: { view: ['tree'] } },
+ };
+ let calls = 0;
+ const next = updateSearchState(location, {
+ drive: (current) => {
+ calls += 1;
+ return { tags: [...(current?.tags ?? []), 'two'] };
+ },
+ });
+ expect(calls).toBe(1);
+ expect(next.route).toBe(location.route);
+ expect(next.search).toEqual({
+ drive: { tags: ['one', 'two'] },
+ sidebar: { view: ['tree'] },
+ });
+ expect(location.search?.drive.tags).toEqual(['one']);
+ expect(updateSearchState(next, { drive: undefined }).search).toEqual({
+ sidebar: { view: ['tree'] },
+ });
+ const cleared = updateSearchState(next, {
+ drive: undefined,
+ sidebar: undefined,
+ });
+ expect(cleared).toEqual({ route: location.route });
+ expect(cleared.route).toBe(location.route);
+ });
+});
diff --git a/apps/web/src/lib/split-router/tests/solid.test.tsx b/apps/web/src/lib/split-router/tests/solid.test.tsx
new file mode 100644
index 0000000000..9a09252757
--- /dev/null
+++ b/apps/web/src/lib/split-router/tests/solid.test.tsx
@@ -0,0 +1,419 @@
+import { cleanup, render } from '@solidjs/testing-library';
+import { type Accessor, onCleanup } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { z } from 'zod';
+import {
+ createSearchParams,
+ type SetSearchParams,
+} from '../create-search-params';
+import { createMemorySplitRouterLocation } from '../integrations/memory';
+import { defineRoute } from '../routes';
+import {
+ SplitRouter,
+ useCanGo,
+ useNavigate,
+ useParams,
+ useRouteParams,
+ useSplitHistory,
+ useSplitRouter,
+} from '../solid';
+import type {
+ SplitRouterEntry,
+ SplitRouterHistorySnapshot,
+ SplitRouterLayout,
+ SplitRouterSettledChange,
+ SplitRoutes,
+} from '../types';
+
+const coercedParamsRoute = defineRoute({
+ id: 'coerced-params',
+ path: 'coerced/:count',
+ params: z.object({ count: z.coerce.number() }),
+ component: CoercedParamsView,
+});
+
+function CoercedParamsView() {
+ const params = useRouteParams(coercedParamsRoute);
+ return <div>{`${typeof params.count}:${params.count}`}</div>;
+}
+
+function createLayout(): SplitRouterLayout<string> {
+ let entry: (SplitRouterEntry & { splitId: string }) | undefined;
+ const listeners = new Set<(change: SplitRouterSettledChange) => void>();
+ const notify = () => {
+ for (const listener of listeners) {
+ listener({ history: 'push' });
+ }
+ };
+
+ return {
+ snapshot: () => ({
+ entries: entry ? [entry] : [],
+ }),
+ updateCurrentEntry(_splitId, update) {
+ if (!entry) return;
+ entry = { splitId: entry.splitId, ...update(entry) };
+ notify();
+ },
+ open: () => {},
+ reconcile(entries) {
+ const next = entries[0];
+ entry = next ? { splitId: 'split', ...next } : undefined;
+ notify();
+ },
+ activate: () => {},
+ subscribe(listener) {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ };
+}
+
+const routes: SplitRoutes = {
+ definitions: [
+ defineRoute({
+ id: 'drive',
+ path: 'drive',
+ search: ['drive'],
+ children: [
+ {
+ id: 'drive-folder',
+ path: 'folder/:folderId',
+ params: z.object({ folderId: z.string() }),
+ },
+ ],
+ }),
+ ],
+};
+
+type SearchState = {
+ sort: 'updated_at' | 'created_at';
+ tags: string[];
+};
+
+const schema = z.object({
+ sort: z.enum(['updated_at', 'created_at']),
+ tags: z
+ .unknown()
+ .transform((value) => (Array.isArray(value) ? value.map(String) : [])),
+});
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe('Solid split router hooks', () => {
+ it('renders the outlet fallback for a missing split without a route-less entry', () => {
+ const layout = createLayout();
+ const view = render(() => (
+ <SplitRouter.Root
+ layout={layout}
+ routes={routes}
+ location={createMemorySplitRouterLocation('/unmatched')}
+ >
+ <SplitRouter.Outlet
+ splitId="missing"
+ fallback={() => <div>No split</div>}
+ />
+ </SplitRouter.Root>
+ ));
+ expect(layout.snapshot().entries).toEqual([]);
+ expect(view.getByText('No split')).toBeTruthy();
+ });
+ it('returns schema-coerced values from typed route params', () => {
+ const location = createMemorySplitRouterLocation('/coerced/42');
+ const layout = createLayout();
+ const routes: SplitRoutes = {
+ definitions: [coercedParamsRoute],
+ };
+ const result = render(() => (
+ <SplitRouter.Root layout={layout} routes={routes} location={location}>
+ <SplitRouter.Outlet splitId="split" />
+ </SplitRouter.Root>
+ ));
+
+ expect(result.getByText('number:42')).toBeTruthy();
+ });
+
+ it('renders the pinned mount fallback when the route has no component', () => {
+ const location = createMemorySplitRouterLocation('/drive');
+ const layout = createLayout();
+ const result = render(() => (
+ <SplitRouter.Root layout={layout} routes={routes} location={location}>
+ <SplitRouter.Outlet
+ splitId="split"
+ fallback={() => <div>pinned mount</div>}
+ />
+ </SplitRouter.Root>
+ ));
+
+ expect(result.getByText('pinned mount')).toBeTruthy();
+ });
+
+ it('keeps matched ancestors mounted when nested params change', async () => {
+ let parentMounts = 0;
+ let parentDisposals = 0;
+ let childMounts = 0;
+ let childDisposals = 0;
+ let router: ReturnType<typeof useSplitRouter<string>> | undefined;
+
+ const Child = () => {
+ childMounts += 1;
+ onCleanup(() => {
+ childDisposals += 1;
+ });
+ const params = useParams<{ itemId?: string }>();
+
+ return <div data-testid="child">{params.itemId}</div>;
+ };
+ const Parent = () => {
+ parentMounts += 1;
+ onCleanup(() => {
+ parentDisposals += 1;
+ });
+ router = useSplitRouter<string>();
+
+ return (
+ <div>
+ <div>parent</div>
+ <SplitRouter.Outlet />
+ </div>
+ );
+ };
+ const nestedRoutes: SplitRoutes = {
+ definitions: [
+ defineRoute({
+ id: 'parent',
+ path: 'parent',
+ component: Parent,
+ children: [
+ {
+ id: 'child',
+ path: 'child/:itemId',
+ params: z.object({ itemId: z.string() }),
+ component: Child,
+ },
+ ],
+ }),
+ ],
+ };
+ const location = createMemorySplitRouterLocation('/parent/child/one');
+ const layout = createLayout();
+ const result = render(() => (
+ <SplitRouter.Root
+ layout={layout}
+ routes={nestedRoutes}
+ location={location}
+ >
+ <SplitRouter.Outlet splitId="split" />
+ </SplitRouter.Root>
+ ));
+
+ const setChild = (itemId: string) => {
+ layout.updateCurrentEntry('split', (entry) => ({
+ ...entry,
+ location: {
+ ...entry.location,
+ route: {
+ matches: [
+ { id: 'parent', params: {} },
+ { id: 'child', params: { itemId } },
+ ],
+ },
+ },
+ }));
+ };
+
+ expect(result.getByText('parent')).toBeTruthy();
+ expect(parentMounts).toBe(1);
+
+ setChild('one');
+ await router?.settled();
+ expect(result.getByTestId('child').textContent).toBe('one');
+ expect(childMounts).toBe(1);
+
+ setChild('two');
+ await router?.settled();
+ expect(result.getByTestId('child').textContent).toBe('two');
+ expect(parentMounts).toBe(1);
+ expect(parentDisposals).toBe(0);
+ expect(childMounts).toBe(1);
+ expect(childDisposals).toBe(0);
+ });
+
+ it('remounts a route component only when its remount key changes', async () => {
+ let mounts = 0;
+ let disposals = 0;
+ let router: ReturnType<typeof useSplitRouter<string>> | undefined;
+ const View = () => {
+ mounts += 1;
+ onCleanup(() => {
+ disposals += 1;
+ });
+ router = useSplitRouter<string>();
+
+ return <div>remountable</div>;
+ };
+ const remountRoutes: SplitRoutes = {
+ definitions: [
+ {
+ id: 'remountable',
+ path: 'remountable/:version',
+ params: z.object({ version: z.string() }),
+ component: View,
+ remountKey: (params) =>
+ typeof params.version === 'string' ? params.version : undefined,
+ },
+ ],
+ };
+ const location = createMemorySplitRouterLocation('/remountable/one');
+ const layout = createLayout();
+ render(() => (
+ <SplitRouter.Root
+ layout={layout}
+ routes={remountRoutes}
+ location={location}
+ >
+ <SplitRouter.Outlet splitId="split" />
+ </SplitRouter.Root>
+ ));
+
+ expect(mounts).toBe(1);
+ router?.navigate('split', '/remountable/two');
+ await router?.settled();
+
+ expect(mounts).toBe(2);
+ expect(disposals).toBe(1);
+ });
+
+ it.each(['invalid', 'updated_at'])(
+ 'canonicalizes %s search with replacement rather than a new history entry',
+ async (sort) => {
+ const location = createMemorySplitRouterLocation(
+ `/drive?s0.drive.sort=${sort}`
+ );
+ const Harness = () => {
+ const [search] = createSearchParams<SearchState>({
+ namespace: 'drive',
+ schema,
+ defaults: { sort: 'updated_at', tags: [] },
+ });
+ return <div>{search.sort}</div>;
+ };
+ const view = render(() => (
+ <SplitRouter.Root
+ layout={createLayout()}
+ routes={routes}
+ location={location}
+ >
+ <SplitRouter.Scope splitId="split">
+ <Harness />
+ </SplitRouter.Scope>
+ </SplitRouter.Root>
+ ));
+ await new Promise<void>((resolve) => queueMicrotask(resolve));
+ expect(view.getByText('updated_at')).toBeTruthy();
+ expect(location.read().search).toBe('');
+ expect(location.history()).toHaveLength(1);
+ }
+ );
+
+ it('replaces typed search from defaults and rejects invalid setter values', async () => {
+ const location = createMemorySplitRouterLocation(
+ '/drive?s0.drive.sort=created_at&s0.drive.tags=old'
+ );
+ let setSearch: SetSearchParams<SearchState> | undefined;
+ const Harness = () => {
+ const [search, set] = createSearchParams<SearchState>({
+ namespace: 'drive',
+ schema,
+ defaults: { sort: 'updated_at', tags: [] },
+ });
+ setSearch = set;
+ return <div>{search.sort}</div>;
+ };
+ render(() => (
+ <SplitRouter.Root
+ layout={createLayout()}
+ routes={routes}
+ location={location}
+ >
+ <SplitRouter.Scope splitId="split">
+ <Harness />
+ </SplitRouter.Scope>
+ </SplitRouter.Root>
+ ));
+ setSearch?.({ tags: ['new'] }, { mode: 'replace' });
+ await new Promise<void>((resolve) => queueMicrotask(resolve));
+ expect(location.read().search).toBe('?s0.drive.tags=new');
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ // @ts-expect-error Reject untyped/invalid callers at runtime too.
+ setSearch?.({ sort: 'invalid' });
+ expect(error).toHaveBeenCalledOnce();
+ expect(location.read().search).toBe('?s0.drive.tags=new');
+ });
+
+ it('reads route and typed search state from the current split', async () => {
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one?s0.drive.sort=created_at&s0.drive.tags=a&s0.drive.tags=b'
+ );
+ const layout = createLayout();
+ let folderId: string | undefined;
+ let search: { sort: string; tags: string[] } | undefined;
+ let setSearch:
+ | ((
+ value: Partial<{
+ sort: 'updated_at' | 'created_at';
+ tags: string[];
+ }>
+ ) => void)
+ | undefined;
+ let navigate: ((to: string) => void) | undefined;
+ let canGoBack: Accessor<boolean> | undefined;
+ let history: Accessor<SplitRouterHistorySnapshot | undefined> | undefined;
+
+ const Harness = () => {
+ const params = useParams<{ folderId?: string }>();
+ [search, setSearch] = createSearchParams<SearchState>({
+ namespace: 'drive',
+ schema,
+ defaults: { sort: 'updated_at', tags: [] },
+ });
+ navigate = useNavigate();
+ canGoBack = useCanGo(-1);
+ history = useSplitHistory();
+ folderId = params.folderId;
+ return null;
+ };
+
+ render(() => (
+ <SplitRouter.Root layout={layout} routes={routes} location={location}>
+ <SplitRouter.Scope splitId="split">
+ <Harness />
+ </SplitRouter.Scope>
+ </SplitRouter.Root>
+ ));
+
+ expect(folderId).toBe('one');
+ expect(search?.sort).toBe('created_at');
+ expect(search?.tags).toEqual(['a', 'b']);
+ expect(canGoBack?.()).toBe(false);
+
+ setSearch?.({ tags: ['c'] });
+ await new Promise<void>((resolve) => queueMicrotask(resolve));
+ expect(location.read().search).toBe(
+ '?s0.drive.sort=created_at&s0.drive.tags=c'
+ );
+
+ setSearch?.({ sort: undefined, tags: undefined });
+ await new Promise<void>((resolve) => queueMicrotask(resolve));
+ expect(location.read().search).toBe('');
+
+ navigate?.('folder/two');
+ await new Promise<void>((resolve) => queueMicrotask(resolve));
+ expect(location.read().pathname).toBe('/drive/folder/two');
+ expect(canGoBack?.()).toBe(true);
+ expect(history?.()?.index).toBe((history?.()?.entries.length ?? 0) - 1);
+ });
+});
diff --git a/apps/web/src/lib/split-router/tests/url.test.ts b/apps/web/src/lib/split-router/tests/url.test.ts
new file mode 100644
index 0000000000..24dbe4ac2d
--- /dev/null
+++ b/apps/web/src/lib/split-router/tests/url.test.ts
@@ -0,0 +1,167 @@
+import { describe, expect, it, vi } from 'vitest';
+import { z } from 'zod';
+import { createRoutesManifest, decodeRoute, routeParams } from '../routes';
+import type { SplitRouterEntry, SplitRoutes } from '../types';
+import {
+ decodeRouteLayout,
+ decodeSplitRouterLocation,
+ encodeRouteLayout,
+ formatRoutePathname,
+ parseRoutePathname,
+ serializeSplitRouterLocation,
+} from '../url';
+
+const routeDefinitions: SplitRoutes = {
+ definitions: [
+ {
+ id: 'drive',
+ path: 'drive',
+ search: ['drive'],
+ children: [{ id: 'folder', path: 'folder/:folderId' }],
+ },
+ { id: 'legacy', path: 'legacy/:id' },
+ ],
+ globalSearch: ['referral_code'],
+};
+const routes = createRoutesManifest(routeDefinitions);
+
+describe('split layout URLs', () => {
+ it('frames feature routes alongside legacy splits', () => {
+ const drive = decodeRoute(routes, ['drive'])!;
+ expect(
+ encodeRouteLayout(routes, [
+ decodeRoute(routes, ['legacy', 'mail-1'])!,
+ drive,
+ ])
+ ).toEqual(['legacy', 'mail-1', '~', 'drive']);
+ });
+
+ it('runs unmatched path handlers until one handles the URL', () => {
+ const legacyRoutes = createRoutesManifest({
+ ...routeDefinitions,
+ unmatchedPathHandlers: [
+ () => undefined,
+ ({ segments }) => {
+ if (segments.length < 2 || segments.length % 2 !== 0) return;
+ const entries: SplitRouterEntry[] = [];
+ for (let index = 0; index < segments.length; index += 2) {
+ if (segments[index] !== 'legacy') return;
+ entries.push(
+ decodeRoute(routes, segments.slice(index, index + 2))!
+ );
+ }
+ return entries;
+ },
+ ],
+ });
+ const entries = decodeRouteLayout(legacyRoutes, [
+ 'legacy',
+ 'mail-1',
+ 'legacy',
+ 'mail-2',
+ ]);
+
+ expect(
+ entries.map((entry) => routeParams(entry.location.route).id)
+ ).toEqual(['mail-1', 'mail-2']);
+ expect(encodeRouteLayout(legacyRoutes, entries)).toEqual([
+ 'legacy',
+ 'mail-1',
+ '~',
+ 'legacy',
+ 'mail-2',
+ ]);
+ });
+
+ it('reports the partial root match to recovery before falling back', () => {
+ const recover = vi.fn(() => undefined);
+ const fallback = decodeRoute(routes, ['drive'])!;
+ const defaultEntry = vi.fn(() => fallback);
+ const recoveryRoutes = createRoutesManifest({
+ definitions: [
+ {
+ id: 'settings',
+ path: 'settings/:tab',
+ params: z.object({ tab: z.literal('account') }),
+ },
+ ...routeDefinitions.definitions,
+ ],
+ unmatchedPathHandlers: [recover],
+ defaultEntry,
+ });
+
+ expect(decodeRouteLayout(recoveryRoutes, ['settings', 'invalid'])).toEqual([
+ fallback,
+ ]);
+ expect(recover).toHaveBeenCalledWith({
+ segments: ['settings', 'invalid'],
+ matchedRouteId: 'settings',
+ });
+ expect(defaultEntry).toHaveBeenCalledOnce();
+ });
+
+ it('rejects unresolved default and recovered entries before returning a layout', () => {
+ const unresolved = { location: {} } as SplitRouterEntry;
+ const invalidBranch: SplitRouterEntry = {
+ location: {
+ route: { matches: [{ id: 'folder', params: { folderId: 'one' } }] },
+ },
+ };
+ for (const entry of [unresolved, invalidBranch]) {
+ const fallbackRoutes = createRoutesManifest({
+ ...routeDefinitions,
+ defaultEntry: () => entry,
+ });
+ expect(() => decodeRouteLayout(fallbackRoutes, ['unmatched'])).toThrow(
+ 'Split route state'
+ );
+ const recoveryRoutes = createRoutesManifest({
+ ...routeDefinitions,
+ unmatchedPathHandlers: [() => [entry]],
+ });
+ expect(() => decodeRouteLayout(recoveryRoutes, ['unmatched'])).toThrow(
+ 'Split route state'
+ );
+ }
+ expect(decodeRouteLayout(routes, ['unmatched'])).toEqual([]);
+ });
+
+ it('keeps framed duplicate routes in visible order', () => {
+ const parts = ['drive', '~', 'drive'];
+ const entries = decodeRouteLayout(routes, parts);
+ expect(entries).toHaveLength(2);
+ expect(encodeRouteLayout(routes, entries)).toEqual(parts);
+ });
+
+ it('round trips encoded segments with a base path', () => {
+ const basedRoutes = createRoutesManifest({
+ ...routeDefinitions,
+ basePath: '/app',
+ });
+ const segments = ['drive', 'folder', 'a/b c'];
+ const pathname = formatRoutePathname(basedRoutes, segments);
+ expect(pathname).toBe('/app/drive/folder/a%2Fb%20c');
+ expect(parseRoutePathname(basedRoutes, pathname)).toEqual(segments);
+ expect(
+ parseRoutePathname(basedRoutes, '/app/drive/%E0%A4%A')
+ ).toBeUndefined();
+ });
+
+ it('preserves owned query values and hashes without keeping unrelated search', () => {
+ const previous =
+ '/drive/folder/one?s0.drive.tags=b&s0.drive.tags=a&s0.other.x=1&referral_code=ref&unowned=1#heading';
+ const parsed = decodeSplitRouterLocation({ routes, location: previous });
+ expect(parsed.entries[0]?.location.search).toEqual({
+ drive: { tags: ['b', 'a'] },
+ });
+ expect(
+ serializeSplitRouterLocation({
+ routes,
+ entries: parsed.entries,
+ previous,
+ })
+ ).toBe(
+ '/drive/folder/one?referral_code=ref&s0.drive.tags=b&s0.drive.tags=a#heading'
+ );
+ });
+});
diff --git a/apps/web/src/lib/split-router/transitions.ts b/apps/web/src/lib/split-router/transitions.ts
new file mode 100644
index 0000000000..b56358c23c
--- /dev/null
+++ b/apps/web/src/lib/split-router/transitions.ts
@@ -0,0 +1,87 @@
+import { isAbortError } from './utils';
+
+export type Transition<TPending> = {
+ controller: AbortController;
+ promise: Promise<void>;
+ pending?: TPending;
+};
+
+export function createTransitionManager<TTarget, TPending>(callbacks: {
+ onSettled: (target: TTarget | undefined, publicStateChanged: boolean) => void;
+ onError?: (error: unknown) => void;
+}) {
+ const transitions = new Map<unknown, Transition<TPending>>();
+
+ return {
+ has(key: unknown): boolean {
+ return transitions.has(key);
+ },
+
+ pending(key: unknown): TPending | undefined {
+ return transitions.get(key)?.pending;
+ },
+
+ cancel(key: unknown): void {
+ transitions.get(key)?.controller.abort();
+ transitions.delete(key);
+ },
+
+ abortAll(): boolean {
+ let hadPending = false;
+
+ for (const transition of transitions.values()) {
+ transition.controller.abort();
+ hadPending ||= transition.pending !== undefined;
+ }
+ transitions.clear();
+
+ return hadPending;
+ },
+
+ start(
+ key: unknown,
+ options: {
+ controller: AbortController;
+ target?: TTarget;
+ pending?: TPending;
+ run: (transition: Transition<TPending>) => Promise<void>;
+ onSettled?: (transition: Transition<TPending>) => boolean;
+ }
+ ): Promise<void> {
+ transitions.get(key)?.controller.abort();
+
+ const transition: Transition<TPending> = {
+ controller: options.controller,
+ pending: options.pending,
+ promise: Promise.resolve(),
+ };
+
+ transitions.set(key, transition);
+ transition.promise = (async () => {
+ try {
+ await options.run(transition);
+ } catch (error) {
+ if (!isAbortError(error, options.controller.signal)) {
+ callbacks.onError?.(error);
+ }
+ } finally {
+ if (transitions.get(key) === transition) {
+ const publicStateChanged = options.onSettled?.(transition) ?? false;
+ transitions.delete(key);
+ callbacks.onSettled(options.target, publicStateChanged);
+ }
+ }
+ })();
+
+ return transition.promise;
+ },
+
+ promises(): Promise<void>[] {
+ return [...transitions.values()].map((transition) => transition.promise);
+ },
+
+ get size(): number {
+ return transitions.size;
+ },
+ };
+}
diff --git a/apps/web/src/lib/split-router/types.ts b/apps/web/src/lib/split-router/types.ts
new file mode 100644
index 0000000000..b918f40b28
--- /dev/null
+++ b/apps/web/src/lib/split-router/types.ts
@@ -0,0 +1,288 @@
+import type { StandardSchemaV1 } from '@standard-schema/spec';
+import type { SplitRoutesManifest } from './routes';
+
+export type BrowserHistoryIntent = 'push' | 'replace';
+export type SplitRouteParams = Record<string, unknown>;
+export type SplitRouteRawParams = Record<string, string | string[] | undefined>;
+export type SerializedSearchParams = Record<string, string[]>;
+
+export type SplitSearchUpdate =
+ | SerializedSearchParams
+ | undefined
+ | ((
+ current: SerializedSearchParams | undefined
+ ) => SerializedSearchParams | undefined);
+
+export type SplitSearchUpdateOptions = {
+ history?: BrowserHistoryIntent;
+};
+
+export type SplitRouterNavigationCause =
+ | 'initial'
+ | 'external'
+ | 'navigate'
+ | 'history'
+ | 'search'
+ | 'layout';
+
+export type SplitRouterMiddlewareRedirect = {
+ type: 'redirect';
+ to: string;
+};
+
+export type SplitRouterMiddlewareContext = {
+ /** The currently accepted entry at this visible split position, if any. */
+ from: Readonly<SplitRouterEntry> | undefined;
+ /** The proposed entry. It has not been applied to the layout yet. */
+ to: Readonly<SplitRouterEntry>;
+ /** Canonical single-split pathname for `to`. */
+ path: string;
+ cause: SplitRouterNavigationCause;
+ signal: AbortSignal;
+ redirect: (to: string) => SplitRouterMiddlewareRedirect;
+};
+
+export type SplitRouterMiddlewareResult =
+ | SplitRouterMiddlewareRedirect
+ | undefined
+ | void;
+
+export type SplitRouterMiddleware = (
+ context: SplitRouterMiddlewareContext
+) => SplitRouterMiddlewareResult | Promise<SplitRouterMiddlewareResult>;
+
+export type SplitRouterMiddlewareConfig = {
+ routes: SplitRoutesManifest;
+ handlers: readonly SplitRouterMiddleware[];
+};
+
+export type SplitRouterMiddlewareRequest = {
+ from?: SplitRouterEntry;
+ to: SplitRouterEntry;
+ cause: SplitRouterNavigationCause;
+ signal: AbortSignal;
+};
+
+export type SplitRouterMiddlewareRun =
+ | SplitRouterEntry
+ | Promise<SplitRouterEntry>;
+
+type SplitRouteReference = {
+ id: string;
+ params?: StandardSchemaV1;
+};
+
+type SplitRouteTargetParams<TRoute extends SplitRouteReference> =
+ {} extends InferSplitRouteParams<TRoute>
+ ? { params?: InferSplitRouteParams<TRoute> }
+ : { params: InferSplitRouteParams<TRoute> };
+
+export type SplitRouteNavigationTarget<
+ TRoute extends SplitRouteReference = SplitRouteReference,
+> = { route: TRoute } & SplitRouteTargetParams<TRoute>;
+
+export type SplitParentNavigationTarget = {
+ parent: true;
+ levels?: number;
+};
+
+export type SplitNonRouteNavigateTo =
+ | number
+ | string
+ | SplitParentNavigationTarget;
+
+export type SplitNavigateTo =
+ | SplitNonRouteNavigateTo
+ | {
+ route: { id: string };
+ params?: unknown;
+ };
+
+export type SplitNavigateOptions<TSplitId> = {
+ replace?: boolean;
+ target?: 'current' | 'new-split' | TSplitId;
+ search?: Record<string, SplitSearchUpdate>;
+ /** Bypasses final-destination claims and pending reservations, including history
+ * traversal. The host layout may still enforce stricter duplicate policy. */
+ allowDuplicate?: boolean;
+};
+
+export type SplitRouteClaim = {
+ namespace: string;
+ id: string;
+};
+
+export type SplitRouteMatch = {
+ id: string;
+ params: SplitRouteParams;
+};
+
+export type SplitRouteState = {
+ matches: readonly [SplitRouteMatch, ...SplitRouteMatch[]];
+};
+
+export type SplitSearchState = Record<string, SerializedSearchParams>;
+
+export type SplitLocation = {
+ route: SplitRouteState;
+ search?: SplitSearchState;
+};
+
+export type SplitRouterEntry = {
+ location: SplitLocation;
+};
+
+type SplitRouteParamCallback<TParams, TResult> = {
+ bivarianceHack(params: TParams): TResult;
+}['bivarianceHack'];
+
+export type SplitRouteDefinition<
+ TComponent = unknown,
+ TParamsSchema extends StandardSchemaV1 = StandardSchemaV1<
+ unknown,
+ SplitRouteParams
+ >,
+> = {
+ id: string;
+ path: string;
+ aliases?: readonly string[];
+ component?: TComponent;
+ children?: readonly SplitRouteDefinition<TComponent>[];
+ params?: TParamsSchema;
+ serializeParams?: SplitRouteParamCallback<
+ StandardSchemaV1.InferOutput<TParamsSchema>,
+ SplitRouteRawParams
+ >;
+ claim?: SplitRouteParamCallback<
+ StandardSchemaV1.InferOutput<TParamsSchema>,
+ SplitRouteClaim | undefined
+ >;
+ search?: readonly string[] | '*';
+ externalSearch?:
+ | readonly string[]
+ | ((entry: Readonly<SplitRouterEntry>) => readonly string[]);
+ remountKey?: (params: SplitRouteParams) => string | number | undefined;
+};
+
+export type InferSplitRouteParams<TRoute> = TRoute extends {
+ params: infer TSchema extends StandardSchemaV1;
+}
+ ? StandardSchemaV1.InferOutput<TSchema>
+ : SplitRouteParams;
+
+export type UnmatchedSplitPathContext = {
+ segments: string[];
+ matchedRouteId?: string;
+};
+
+export type UnmatchedSplitPathHandler = (
+ context: UnmatchedSplitPathContext
+) => SplitRouterEntry[] | undefined;
+
+/** Static route declarations. Do not mutate them during a router's lifetime. */
+export type SplitRoutes<TComponent = unknown> = {
+ definitions: SplitRouteDefinition<TComponent>[];
+ unmatchedPathHandlers?: UnmatchedSplitPathHandler[];
+ defaultEntry?: () => SplitRouterEntry;
+ globalSearch?: string[];
+ basePath?: string | string[];
+};
+
+export type SplitRouterLayoutEntry<TSplitId> = SplitRouterEntry & {
+ splitId: TSplitId;
+};
+
+export type SplitRouterLayoutSnapshot<TSplitId> = {
+ entries: SplitRouterLayoutEntry<TSplitId>[];
+};
+
+export type SplitRouterSettledChange = {
+ history: BrowserHistoryIntent;
+};
+
+export type SplitRouterHistorySnapshot = {
+ entries: readonly SplitLocation[];
+ index: number;
+};
+
+export interface SplitRouterLayout<TSplitId> {
+ snapshot(): SplitRouterLayoutSnapshot<TSplitId>;
+ updateCurrentEntry(
+ splitId: TSplitId,
+ update: (current: SplitRouterLayoutEntry<TSplitId>) => SplitRouterEntry
+ ): void;
+ open(
+ request: SplitRouterEntry & {
+ target?: TSplitId | 'new-split';
+ replace?: boolean;
+ }
+ ): void;
+ reconcile(entries: SplitRouterEntry[]): void;
+ activate(splitId: TSplitId): void;
+ subscribe(listener: (change: SplitRouterSettledChange) => void): () => void;
+}
+
+export type SplitRouterExternalLocationValue = {
+ pathname: string;
+ search: string;
+ hash: string;
+};
+
+export interface SplitRouterExternalLocation {
+ read(): SplitRouterExternalLocationValue;
+ subscribe(
+ listener: (location: SplitRouterExternalLocationValue) => void
+ ): () => void;
+ commit(
+ location: SplitRouterExternalLocationValue,
+ options: { history: BrowserHistoryIntent }
+ ): void;
+}
+
+export type SplitRouterOptions<TSplitId> = {
+ layout: SplitRouterLayout<TSplitId>;
+ routes: SplitRoutes | SplitRoutesManifest;
+ location: SplitRouterExternalLocation;
+ middleware?: readonly SplitRouterMiddleware[];
+};
+
+export type SplitNavigate<TSplitId> = {
+ <const TRoute extends SplitRouteReference>(
+ to: SplitRouteNavigationTarget<TRoute>,
+ options?: SplitNavigateOptions<TSplitId>
+ ): void;
+ (to: SplitNonRouteNavigateTo, options?: SplitNavigateOptions<TSplitId>): void;
+};
+
+export interface SplitRouter<TSplitId> {
+ readonly routes: SplitRoutesManifest;
+ route(splitId: TSplitId): SplitRouteState | undefined;
+ location(splitId: TSplitId): SplitLocation | undefined;
+ search(
+ splitId: TSplitId,
+ namespace: string
+ ): SerializedSearchParams | undefined;
+ navigate<const TRoute extends SplitRouteReference>(
+ splitId: TSplitId,
+ to: SplitRouteNavigationTarget<TRoute>,
+ options?: SplitNavigateOptions<TSplitId>
+ ): void;
+ navigate(
+ splitId: TSplitId,
+ to: SplitNonRouteNavigateTo,
+ options?: SplitNavigateOptions<TSplitId>
+ ): void;
+ canGo(splitId: TSplitId, delta: number): boolean;
+ history(splitId: TSplitId): SplitRouterHistorySnapshot | undefined;
+ updateSearch(
+ splitId: TSplitId,
+ namespace: string,
+ update: SplitSearchUpdate,
+ options?: SplitSearchUpdateOptions
+ ): void;
+ href(splitId: TSplitId): string;
+ isReady(): boolean;
+ settled(): Promise<void>;
+ subscribe(listener: (splitId: TSplitId | undefined) => void): () => void;
+ dispose(): void;
+}
diff --git a/apps/web/src/lib/split-router/url.ts b/apps/web/src/lib/split-router/url.ts
new file mode 100644
index 0000000000..5cdd969b55
--- /dev/null
+++ b/apps/web/src/lib/split-router/url.ts
@@ -0,0 +1,241 @@
+import {
+ assertRouteEntry,
+ decodeRoute,
+ encodeRoute,
+ filterRouteSearch,
+ findMatchingRouteId,
+ getExternalSearchKeys,
+ type SplitRoutesManifest,
+} from './routes';
+import {
+ isSplitSearchKey,
+ parseSplitSearch,
+ replaceSplitSearchParams,
+} from './search';
+import type {
+ SplitRouterEntry,
+ SplitRouterExternalLocationValue,
+} from './types';
+
+export const SPLIT_PATH_SEPARATOR = '~';
+
+function addPrefix(value: string, prefix: '?' | '#'): string {
+ if (!value || value.startsWith(prefix)) return value;
+
+ return `${prefix}${value}`;
+}
+
+export function externalLocationToString(
+ location: SplitRouterExternalLocationValue
+): string {
+ const search = addPrefix(location.search, '?');
+ const hash = addPrefix(location.hash, '#');
+
+ return `${location.pathname || '/'}${search}${hash}`;
+}
+
+export function parseExternalLocation(
+ value: string | SplitRouterExternalLocationValue
+): SplitRouterExternalLocationValue {
+ if (typeof value !== 'string') {
+ return {
+ pathname: value.pathname || '/',
+ search: addPrefix(value.search, '?'),
+ hash: addPrefix(value.hash, '#'),
+ };
+ }
+
+ const parsed = new URL(value, 'https://split-router.invalid');
+
+ return {
+ pathname: parsed.pathname,
+ search: parsed.search,
+ hash: parsed.hash,
+ };
+}
+
+export function parseRoutePathname(
+ routes: SplitRoutesManifest,
+ pathname: string
+): string[] | undefined {
+ const raw = pathname
+ .replace(/^\/+|\/+$/g, '')
+ .split('/')
+ .filter(Boolean);
+ const base = routes.basePath;
+ const segments =
+ base.length > 0 && base.every((part, index) => raw[index] === part)
+ ? raw.slice(base.length)
+ : raw;
+
+ try {
+ return segments.map(decodeURIComponent);
+ } catch {
+ return;
+ }
+}
+
+export function formatRoutePathname(
+ routes: SplitRoutesManifest,
+ segments: string[]
+): string {
+ return `/${[...routes.basePath, ...segments]
+ .map(encodeURIComponent)
+ .join('/')}`;
+}
+
+function framedParts(segments: string[]): string[][] {
+ const parts: string[][] = [[]];
+
+ for (const segment of segments) {
+ if (segment === SPLIT_PATH_SEPARATOR) {
+ parts.push([]);
+ } else {
+ parts.at(-1)!.push(segment);
+ }
+ }
+
+ return parts.filter((part) => part.length > 0);
+}
+
+export function decodeRouteLayout(
+ routes: SplitRoutesManifest,
+ segments: string[]
+): SplitRouterEntry[] {
+ const parts = segments.includes(SPLIT_PATH_SEPARATOR)
+ ? framedParts(segments)
+ : [segments];
+ const decoded = parts.map((part) => decodeRoute(routes, part));
+
+ if (decoded.length > 0 && decoded.every(Boolean)) {
+ return decoded as SplitRouterEntry[];
+ }
+
+ for (const handle of routes.unmatchedPathHandlers ?? []) {
+ const recovered = handle({
+ segments,
+ matchedRouteId: findMatchingRouteId(routes, segments),
+ });
+
+ if (recovered) {
+ for (const entry of recovered) assertRouteEntry(routes, entry);
+ return recovered;
+ }
+ }
+
+ if (!routes.defaultEntry) return [];
+ const entry = routes.defaultEntry();
+ assertRouteEntry(routes, entry);
+ return [entry];
+}
+
+export function encodeRouteLayout(
+ routes: SplitRoutesManifest,
+ entries: SplitRouterEntry[]
+): string[] {
+ return entries.flatMap((entry, index) => {
+ const segments = encodeRoute(routes, entry);
+
+ return index === 0 ? segments : [SPLIT_PATH_SEPARATOR, ...segments];
+ });
+}
+
+export type DecodedSplitRouterLocation = {
+ entries: SplitRouterEntry[];
+ externalLocation: SplitRouterExternalLocationValue;
+};
+
+export function decodeSplitRouterLocation(options: {
+ routes: SplitRoutesManifest;
+ location: string | SplitRouterExternalLocationValue;
+}): DecodedSplitRouterLocation {
+ const externalLocation = parseExternalLocation(options.location);
+ const segments = parseRoutePathname(
+ options.routes,
+ externalLocation.pathname
+ );
+ const search = parseSplitSearch(externalLocation.search);
+ const entries = decodeRouteLayout(options.routes, segments ?? []).map(
+ (entry, index) => {
+ const route = entry.location.route;
+ const splitSearch = filterRouteSearch(
+ options.routes,
+ route,
+ search.get(index)
+ );
+
+ return {
+ location: {
+ ...entry.location,
+ ...(splitSearch ? { search: splitSearch } : {}),
+ },
+ };
+ }
+ );
+
+ return { entries, externalLocation };
+}
+
+export function encodeSplitRouterLocation(options: {
+ routes: SplitRoutesManifest;
+ entries: SplitRouterEntry[];
+ previous: SplitRouterExternalLocationValue;
+ preserveHash?: boolean;
+ preserveExternalSearch?: boolean;
+}): SplitRouterExternalLocationValue {
+ const pathname = formatRoutePathname(
+ options.routes,
+ encodeRouteLayout(options.routes, options.entries)
+ );
+ const ownedSearch =
+ options.preserveExternalSearch === false
+ ? new Set(options.routes.globalSearch ?? [])
+ : getExternalSearchKeys(options.routes, options.entries);
+ const query = new URLSearchParams();
+
+ for (const [key, value] of new URLSearchParams(options.previous.search)) {
+ if (!isSplitSearchKey(key) && ownedSearch.has(key)) {
+ query.append(key, value);
+ }
+ }
+
+ replaceSplitSearchParams(
+ query,
+ options.entries.map((entry) => ({
+ location: {
+ search: filterRouteSearch(
+ options.routes,
+ entry.location.route,
+ entry.location.search
+ ),
+ },
+ }))
+ );
+ query.sort();
+
+ const search = query.toString();
+ const pathChanged =
+ pathname.replace(/\/+$/g, '') !==
+ options.previous.pathname.replace(/\/+$/g, '');
+
+ return {
+ pathname,
+ search: search ? `?${search}` : '',
+ hash: !pathChanged || options.preserveHash ? options.previous.hash : '',
+ };
+}
+
+export function serializeSplitRouterLocation(options: {
+ routes: SplitRoutesManifest;
+ entries: SplitRouterEntry[];
+ previous: string | SplitRouterExternalLocationValue;
+ preserveHash?: boolean;
+ preserveExternalSearch?: boolean;
+}): string {
+ return externalLocationToString(
+ encodeSplitRouterLocation({
+ ...options,
+ previous: parseExternalLocation(options.previous),
+ })
+ );
+}
diff --git a/apps/web/src/lib/split-router/utils.ts b/apps/web/src/lib/split-router/utils.ts
new file mode 100644
index 0000000000..cd55b41d4e
--- /dev/null
+++ b/apps/web/src/lib/split-router/utils.ts
@@ -0,0 +1,53 @@
+const SAFE_NAME = /^[A-Za-z][A-Za-z0-9_-]*$/;
+
+/** Bounded identifier safe to use as an ordinary object key. */
+export function isSafeName(value: string): boolean {
+ return (
+ value.length <= 64 &&
+ value !== 'constructor' &&
+ value !== 'prototype' &&
+ SAFE_NAME.test(value)
+ );
+}
+
+export function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+export function takeLast<T>(values: readonly T[] | undefined): T | undefined {
+ return values?.at(-1);
+}
+
+export function isPromise<T>(value: T | Promise<T>): value is Promise<T> {
+ return value instanceof Promise;
+}
+
+export function throwIfAborted(signal: AbortSignal): void {
+ if (!signal.aborted) return;
+
+ throw signal.reason ?? new DOMException('Aborted', 'AbortError');
+}
+
+export function isAbortError(error: unknown, signal: AbortSignal): boolean {
+ return (
+ signal.aborted ||
+ (error instanceof DOMException && error.name === 'AbortError')
+ );
+}
+
+export function reactiveRecord<T extends object>(read: () => T): T {
+ return new Proxy({} as T, {
+ get: (_target, key) => read()[key as keyof T],
+ has: (_target, key) => key in read(),
+ ownKeys: () => Reflect.ownKeys(read()),
+ getOwnPropertyDescriptor: (_target, key) => {
+ if (!(key in read())) return;
+
+ return {
+ configurable: true,
+ enumerable: true,
+ value: read()[key as keyof T],
+ };
+ },
+ });
+}
diff --git a/apps/web/vitest.config.ts b/apps/web/vitest.config.ts
index 07fe9a7ddd..6255d84e1a 100644
--- a/apps/web/vitest.config.ts
+++ b/apps/web/vitest.config.ts
@@ -38,7 +38,10 @@ export default defineConfig({
// Core package tests
extends: './src/lib/core/vitest.config.ts',
test: {
- include: ['src/lib/core/**/*.{test,spec}.{ts,tsx}'],
+ include: [
+ 'src/lib/core/**/*.{test,spec}.{ts,tsx}',
+ 'src/lib/split-router/**/*.{test,spec}.{ts,tsx}',
+ ],
name: 'core',
},
},
diff --git a/bun.lock b/bun.lock
index ab21d687c7..f2a43e5612 100644
--- a/bun.lock
+++ b/bun.lock
@@ -71,6 +71,7 @@
"@solid-primitives/storage": "^4.3.3",
"@solid-primitives/stream": "^0.7.4",
"@solidjs/router": "^0.15.3",
+ "@standard-schema/spec": "^1.1.0",
"@tailwindcss/vite": "^4.2.4",
"@tanstack/pacer": "^0.17.3",
"@tanstack/solid-query": "5.90.3",