/** * MIT License * * Copyright (c) 2025 Chris M. Perez * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import { Schema } from 'effect'; import type { RouteParamInput } from '@effuse/core'; import type { RouteRecord, Route, RouteLocation } from '../core/route.js'; export interface TypedRouteRecord< Params extends Record = Record, Query extends Record = Record, Meta extends Record = Record, > extends RouteRecord { readonly paramsSchema?: Schema.Schema; readonly querySchema?: Schema.Schema; readonly meta?: Meta; } export interface TypedRoute< Params extends Record = Record, Query extends Record = Record, Meta extends Record = Record, > extends Route { readonly params: Params; readonly query: Query; readonly meta: Meta; } export type ExtractRouteParams = RouteParamInput; export type TypedRouteLocation< Name extends string, Params extends Partial> = Record, > = { name: Name; params?: Params extends Record ? undefined : Params; query?: Record; hash?: string; }; export const defineRoutes = ( routes: Routes ): Routes => routes; export const createTypedNavigator = < Params extends Record, Query extends Record = Record, >( name: string, _paramsSchema?: Schema.Schema, _querySchema?: Schema.Schema ) => ({ to: (params: Params, query?: Query): RouteLocation => ({ name, params: params as Record, query: query as Record, }), matches: (route: Route): route is TypedRoute => route.name === name, }); export const validateParams = ( params: Record, schema: Schema.Schema ): A | null => { try { return Schema.decodeUnknownSync(schema)(params); } catch { return null; } }; export const createParamsGuard = ( schema: Schema.Schema, onInvalid: ( params: Record ) => RouteLocation | string = () => '/' ) => (to: Route) => { const result = validateParams(to.params, schema); if (result === null) { return onInvalid(to.params); } return true; };