UNPKG

@powership/server

Version:
1 lines 2.71 kB
{"version":3,"file":"routeMatch.cjs","names":["_urlPattern","_interopRequireDefault","require","e","__esModule","default","createRouteMatcher","path","_path","replace","endsWith","slice","UrlPattern"],"sources":["../src/routeMatch.ts"],"sourcesContent":["import { IsKnown } from '@powership/utils';\nimport UrlPattern from 'url-pattern';\n\n/**\n * A wrapper around UrlPattern with improved typings\n * @param path\n * see: https://github.com/snd/url-pattern\n */\nexport function createRouteMatcher<Path extends string>(\n path: Path\n): RouteMatcher<Path> {\n let _path = path\n // changing the path to the format expected by UrlPattern for optional route parameters\n // https://www.npmjs.com/package/url-pattern#optional-segments-wildcards-and-escaping\n .replace(/(\\/:?)([^?/:]*)\\?/g, '($1$2)');\n\n if (_path.endsWith('/')) {\n _path = path.slice(0, -1);\n }\n\n _path += `(/)`;\n\n return new UrlPattern(_path, {});\n}\n\nexport interface RouteMatcher<Path extends string> {\n stringify: (params: GetRouteParams<Path>) => string;\n match(route: string): GetRouteParams<Path> | null;\n}\n\nexport type AlphaNumeric = string | number;\n\n// extract route params from a string literal\nexport type ExtractRouteParams<Path extends string> =\n Path extends `:${infer Param}/${infer Rest}`\n ? Param | ExtractRouteParams<Rest>\n : Path extends `:${infer Param}`\n ? Param\n : Path extends `${string}:${infer Rest}`\n ? ExtractRouteParams<`:${Rest}`>\n : never;\n\n// used to infer if a route needs a params object\nexport type GetRouteParams<Path extends string> = IsKnown<Path> extends 0\n ? {}\n : [ExtractRouteParams<Path>] extends [never]\n ? {}\n : {\n [K in ExtractRouteParams<Path>]: K extends `${string}?`\n ? AlphaNumeric | undefined\n : AlphaNumeric;\n } extends infer Parsed\n ? {\n // removing ending \"?\" simbol\n [K in ExcludeOptionalSymbol<keyof Parsed>]: Parsed extends {\n [KK in `${K}?`]: any;\n }\n ? AlphaNumeric | undefined\n : AlphaNumeric;\n }\n : never;\n\ntype ExcludeOptionalSymbol<T> = Extract<\n T extends `${infer Value}?` ? Value : T,\n string\n>;\n"],"mappings":";;;;;;AACA,IAAAA,WAAA,GAAAC,sBAAA,CAAAC,OAAA;AAAqC,SAAAD,uBAAAE,CAAA,WAAAA,CAAA,IAAAA,CAAA,CAAAC,UAAA,GAAAD,CAAA,KAAAE,OAAA,EAAAF,CAAA;AAErC;AACA;AACA;AACA;AACA;AACO,SAASG,kBAAkBA,CAChCC,IAAU,EACU;EACpB,IAAIC,KAAK,GAAGD;EACV;EACA;EAAA,CACCE,OAAO,CAAC,oBAAoB,EAAE,QAAQ,CAAC;EAE1C,IAAID,KAAK,CAACE,QAAQ,CAAC,GAAG,CAAC,EAAE;IACvBF,KAAK,GAAGD,IAAI,CAACI,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;EAC3B;EAEAH,KAAK,IAAI,KAAK;EAEd,OAAO,IAAII,mBAAU,CAACJ,KAAK,EAAE,CAAC,CAAC,CAAC;AAClC;;AASA;;AAUA","ignoreList":[]}