### Quick Start Commands for Path-to-Regexp Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/INDEX.md This snippet demonstrates essential functions for path manipulation. It covers importing, matching, building paths, parsing, converting to regular expressions, and stringifying parsed data. Ensure you have the library installed and imported correctly. ```typescript // Import import { match, compile, parse, pathToRegexp, stringify } from "path-to-regexp"; // Match const fn = match("/user/:id"); fn("/user/123"); // Build const toPath = compile("/user/:id"); toPath({ id: "123" }); // Parse const data = parse("/user/:id"); // RegExp const { regexp, keys } = pathToRegexp("/user/:id"); // Stringify stringify(data); ``` -------------------------------- ### Install Path-to-RegExp Source: https://github.com/pillarjs/path-to-regexp/blob/master/Readme.md Install the path-to-regexp package using npm. ```bash npm install path-to-regexp --save ``` -------------------------------- ### Framework Integration Example (Express-like) Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/README.md Illustrates how to integrate path-to-regexp with a framework like Express by matching HTTP methods and paths to specific handlers. This example demonstrates a common pattern for server-side routing. ```typescript import { match } from "path-to-regexp"; const routes = { "GET /user/:id": (params) => getUserById(params.id), "POST /user": () => createUser(), "DELETE /user/:id": (params) => deleteUser(params.id) }; function route(method: string, path: string) { for (const [pattern, handler] of Object.entries(routes)) { if (pattern.startsWith(method)) { const pathPattern = pattern.slice(method.length + 1); const matcher = match(pathPattern); const result = matcher(path); if (result) { return handler(result.params); } } } } ``` -------------------------------- ### Keys Array Example Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/types.md An example showing how the 'keys' array is returned by pathToRegexp. It contains Parameter and Wildcard tokens corresponding to the path's capturing groups. ```typescript const { regexp, keys } = pathToRegexp("/user/:id/posts/:postId"); // keys = [ // { type: "param", name: "id" }, // { type: "param", name: "postId" } // ] ``` -------------------------------- ### MatchResult Example Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/types.md An example demonstrating how to define and initialize a MatchResult object with specific parameter types. ```typescript const result: MatchResult<{ id: string }> = { path: "/user/123", params: { id: "123" } }; ``` -------------------------------- ### Path Building Example Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/README.md Shows how to use the `compile` function to create a path builder for a specific route pattern. This is useful for generating URLs with dynamic parameters. ```typescript import { compile } from "path-to-regexp"; const userUrl = compile("/user/:id/posts/:postId"); const path = userUrl({ id: "123", postId: "456" }); // "/user/123/posts/456" ``` -------------------------------- ### Quick Start: Path-to-Regexp Core Functions Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/usage-guide.md Demonstrates the primary functions: matching paths, compiling paths, parsing path structures, and generating regular expressions. Useful for a rapid overview of the library's capabilities. ```typescript import { match, compile, parse, stringify, pathToRegexp } from "path-to-regexp"; // Match incoming paths const fn = match("/user/:id"); fn("/user/123"); // { path: "/user/123", params: { id: "123" } } // Build paths with parameters const toPath = compile("/user/:id"); toPath({ id: "123" }); // "/user/123" // Parse paths to tokens const data = parse("/user/:id"); // data.tokens = [{ type: "text", value: "/user/" }, { type: "param", name: "id" }] // Convert tokens back to string stringify(data); // "/user/:id" // Get regexp directly const { regexp, keys } = pathToRegexp("/user/:id"); regexp.exec("/user/123"); // ["/user/123", "123"] ``` -------------------------------- ### Route Matching Example Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/README.md Demonstrates how to use the `match` function to create multiple route matchers and iterate through them to handle requests. This pattern is common for building simple routing systems. ```typescript import { match } from "path-to-regexp"; const routes = [ match("/user/:id"), match("/post/:id"), match("/files/*path") ]; function handleRequest(path: string) { for (const matcher of routes) { const result = matcher(path); if (result) { // Handle matched route return result.params; } } // No match found } ``` -------------------------------- ### MatchFunction Example Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/types.md Illustrates the usage of a MatchFunction created by `match()`. The function is used to test a given path string against a predefined route. ```typescript const fn: MatchFunction<{ id: string }> = match("/user/:id"); const result = fn("/user/123"); // MatchResult or false ``` -------------------------------- ### Group Type Example Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/types.md An example demonstrating the creation of a Group type object. This represents an optional segment within a path, composed of other tokens. ```typescript const group: Group = { type: "group", tokens: [ { type: "text", value: "/" }, { type: "param", name: "id" } ] }; ``` -------------------------------- ### Wildcard Type Example Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/types.md An example demonstrating the creation of a Wildcard type object. This is used to represent named multi-segment parameters in path definitions. ```typescript const wildcard: Wildcard = { type: "wildcard", name: "path" }; ``` -------------------------------- ### TokenData Class Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/MANIFEST.txt Documentation for the TokenData class, including its signature, constructor, properties, and usage examples. ```APIDOC ## Class: TokenData ### Description Provides detailed information about a token parsed from a path. ### Class Signature ```typescript class TokenData ``` ### Constructor Details about the constructor parameters and their types. ### Properties - **name** (string) - The name of the token. - **prefix** (string) - The prefix of the token. - **delimiter** (string) - The delimiter used for the token. - **optional** (boolean) - Indicates if the token is optional. - **repeat** (boolean) - Indicates if the token is repeatable. - **suffix** (string) - The suffix of the token. - **rest** (boolean) - Indicates if the token matches the rest of the path. - **indexed** (boolean) - Indicates if the token is indexed. ### Usage Examples Includes 5 real-world usage examples demonstrating how to work with TokenData. ### Behavior Details Explains the behavior and characteristics of the TokenData class. ### Related Types and Functions Cross-references to related types and functions within the library. ``` -------------------------------- ### Example Decode Function: decodeURIComponent Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/types.md An example implementation of the `Decode` type using `decodeURIComponent` for string decoding. ```typescript const decode: Decode = (value) => decodeURIComponent(value); ``` -------------------------------- ### Example Decode Function: JSON.parse Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/types.md An example implementation of the `Decode` type that parses a string as JSON. ```typescript const decode: Decode = (value) => JSON.parse(value); ``` -------------------------------- ### Example Encode Function: encodeURIComponent Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/types.md An example implementation of the `Encode` type using `encodeURIComponent` for string encoding. ```typescript const encode: Encode = (value) => encodeURIComponent(value); ``` -------------------------------- ### URL Decoding Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/api-reference/match.md By default, path parameters are URL-decoded. This example shows how encoded characters in the URL are automatically decoded into their corresponding characters in the matched parameters. ```typescript const fn = match("/search/:query"); console.log(fn("/search/hello%20world")); // { path: "/search/hello%20world", params: { query: "hello world" } } console.log(fn("/search/caf%C3%A9")); // { path: "/search/caf%C3%A9", params: { query: "café" } } ``` -------------------------------- ### Basic path matching and building with path-to-regexp Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/README.md Demonstrates how to match an incoming path against a pattern and extract parameters, and how to compile a pattern into a function for building paths. Use the `match` function for matching and the `compile` function for building. ```typescript // Match a path const matcher = match("/user/:id"); matcher("/user/123"); // { path: "/user/123", params: { id: "123" } } // Build a path const builder = compile("/user/:id"); builder({ id: "123" }); // "/user/123" ``` -------------------------------- ### Example Encode Function: toUpperCase Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/types.md An example implementation of the `Encode` type that converts a string to uppercase. ```typescript const encode: Encode = (value) => value.toUpperCase(); ``` -------------------------------- ### Basic Usage Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/README.md Demonstrates basic usage of the path-to-regexp library for matching paths, building paths, and generating regular expressions. ```APIDOC ## Basic Usage ### Description Demonstrates basic usage of the path-to-regexp library for matching paths, building paths, and generating regular expressions. ### Match a path ```typescript // Match a path const matcher = match("/user/:id"); matcher("/user/123"); // { path: "/user/123", params: { id: "123" } } ``` ### Build a path ```typescript // Build a path const builder = compile("/user/:id"); builder({ id: "123" }); // "/user/123" ``` ### Get regexp ```typescript // Get regexp const { regexp, keys } = pathToRegexp("/user/:id"); regexp.exec("/user/123"); // ["/user/123", "123"] ``` ``` -------------------------------- ### pathToRegexp with Parameters Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/api-reference/pathToRegexp.md Shows how to use pathToRegexp with path parameters, which are captured into the keys array and the RegExp. ```typescript import { pathToRegexp } from 'path-to-regexp'; const { regexp, keys } = pathToRegexp('/user/:id'); console.log(regexp); // /^ooar/i console.log(keys); // [{ name: 'id', prefix: '/', suffix: '', repeat: false, optional: false, partial: false, delegate: undefined }] ``` -------------------------------- ### Basic pathToRegexp Usage Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/api-reference/pathToRegexp.md Demonstrates the basic conversion of a path string to a RegExp and keys. This is useful for simple path matching scenarios. ```typescript import { pathToRegexp } from 'path-to-regexp'; const { regexp, keys } = pathToRegexp('/foo/bar'); console.log(regexp); // /^ooar/i console.log(keys); // [] ``` -------------------------------- ### Match Basic Parameters Source: https://github.com/pillarjs/path-to-regexp/blob/master/Readme.md Use the `match` function to create a matcher for a path with parameters. The parameters are captured as key-value pairs in the returned object. ```javascript const fn = match("/:foo/:bar"); fn("/test/route"); //=> { path: '/test/route', params: { foo: 'test', bar: 'route' } } ``` -------------------------------- ### Create TokenData from parse() Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/api-reference/TokenData.md Demonstrates creating a TokenData instance by parsing a path string using the `parse` function. Shows how to access the tokens and original path. ```typescript import { parse } from "path-to-regexp"; const data = parse("/user/:id"); console.log(data instanceof TokenData); // true console.log(data.tokens); // [ // { type: "text", value: "/" }, // { type: "param", name: "id" } // ] console.log(data.originalPath); // "/user/:id" ``` -------------------------------- ### pathToRegexp with Wildcards Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/api-reference/pathToRegexp.md Shows how to use wildcards like '*' in path patterns, which are captured as 'wildcard' keys in the output. ```typescript import { pathToRegexp } from 'path-to-regexp'; const { regexp, keys } = pathToRegexp('/files/*'); console.log(regexp); // /^iles/i console.log(keys); // [{ name: 0, prefix: '/', suffix: '', repeat: true, optional: false, partial: false, delegate: undefined }] ``` -------------------------------- ### Parameter Validation and Processing Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/usage-guide.md Validate and process extracted parameters from a matched path. This example demonstrates checking if a user ID is a numeric integer before proceeding. ```typescript import { match, ParamData } from "path-to-regexp"; const userRoute = match("/user/:id"); function handleRequest(path: string) { const result = userRoute(path); if (!result) { console.log("No match"); return; } const { id } = result.params as { id: string }; // Validate if (!Number.isInteger(Number(id))) { console.log("ID must be numeric"); return; } // Process console.log("User ID:", id); } handleRequest("/user/123"); // User ID: 123 handleRequest("/user/abc"); // ID must be numeric handleRequest("/admin/123"); // No match ``` -------------------------------- ### Path-to-Regexp with Custom Delimiter Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/configuration.md Generates a regexp using a custom `delimiter` option, changing the character that separates path segments from the default '/' to '.' in this example. ```typescript import { pathToRegexp } from "path-to-regexp"; // Custom delimiter const { regexp: r5 } = pathToRegexp("user.name", { delimiter: "." }); r5.exec("user.name"); // match ``` -------------------------------- ### Import Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/README.md Import various functions, classes, and types from the path-to-regexp library. ```APIDOC ## Import ### Description Import various functions, classes, and types from the path-to-regexp library. ### Code ```typescript import { // Functions parse, pathToRegexp, match, compile, stringify, // Classes TokenData, PathError, // Types Encode, Decode, ParseOptions, PathToRegexpOptions, MatchOptions, CompileOptions, Text, Parameter, Wildcard, Group, Key, Keys, Token, ParamData, PathFunction, MatchResult, Match, MatchFunction, Path } from "path-to-regexp"; ``` ``` -------------------------------- ### pathToRegexp with Multiple Paths Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/api-reference/pathToRegexp.md Demonstrates how to provide an array of path patterns to pathToRegexp, creating a single RegExp that matches any of the provided paths. ```typescript import { pathToRegexp } from 'path-to-regexp'; const { regexp, keys } = pathToRegexp(['/foo', '/bar']); console.log(regexp); // /^ooar/i console.log(keys); // [] ``` -------------------------------- ### Combine PathToRegexpOptions and ParseOptions Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/configuration.md Demonstrates how to use a single options object to configure both path-to-regexp matching and parsing behavior. Note the 'decode: false' option which is specific to MatchOptions. ```typescript import { match, compile } from "path-to-regexp"; const options = { // PathToRegexpOptions sensitive: true, end: true, trailing: false, delimiter: "/", // ParseOptions encodePath: (str) => str.toLowerCase(), // MatchOptions only decode: false }; const fn = match("/User/:id/posts/:postId", options); fn("/user/123/posts/456"); // null (sensitive: true, case mismatch) ``` -------------------------------- ### Custom Encoding Function with compile() Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/api-reference/compile.md Provide a custom `encode` function to compile() to control how parameter values are transformed. This example converts values to uppercase. ```typescript const toPath = compile("/search/:query", { encode: (str) => { // Custom encoding logic return str.toUpperCase(); } }); console.log(toPath({ query: "hello" })); // "/search/HELLO" ``` -------------------------------- ### Import path-to-regexp functions and types Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/README.md Import necessary functions and types from the path-to-regexp library. This is the first step before using any of its utilities. ```typescript import { // Functions parse, pathToRegexp, match, compile, stringify, // Classes TokenData, PathError, // Types Encode, Decode, ParseOptions, PathToRegexpOptions, MatchOptions, CompileOptions, Text, Parameter, Wildcard, Group, Key, Keys, Token, ParamData, PathFunction, MatchResult, Match, MatchFunction, Path } from "path-to-regexp"; ``` -------------------------------- ### Handling Unterminated Quoted Parameter Name Errors Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/errors.md Shows how to catch PathError when a quoted parameter name is not properly closed with a double quote. This applies to both the start of a parameter and within a parameter name. ```typescript try { parse('/:"incomplete'); // Missing closing quote } catch (error) { // Error: "Unterminated quote at index 2: /:"incomplete; visit ..." } ``` ```typescript try { parse('/:foo/:"another name'); // Quote in middle parameter } catch (error) { // Error: "Unterminated quote at index {n}: ..." } ``` -------------------------------- ### Multiple Path Patterns for Matching Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/api-reference/pathToRegexp.md Demonstrates how to provide an array of path strings to `pathToRegexp`. The generated regular expression will match any of the provided patterns. ```typescript const { regexp, keys } = pathToRegexp([ "/user/:id", "/admin/:id" ]); console.log(keys); // [{ type: "param", name: "id" }, { type: "param", name: "id" }] // Both patterns match: console.log(regexp.exec("/user/123")); // match console.log(regexp.exec("/admin/456")); // match ``` -------------------------------- ### Manually construct TokenData Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/api-reference/TokenData.md Shows how to manually create a TokenData instance by providing an array of tokens and an optional original path string. Useful for programmatic path generation. ```typescript import { TokenData } from "path-to-regexp"; const data = new TokenData( [ { type: "text", value: "/user/" }, { type: "param", name: "id" } ], "/user/:id" ); console.log(data.tokens.length); // 2 console.log(data.originalPath); // "/user/:id" ``` -------------------------------- ### Validate Parameters Before Path Building Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/errors.md Perform explicit validation on parameters before attempting to build a path to catch common issues like missing or incorrectly typed parameters. This example checks for the existence and type of a required 'id' parameter. ```typescript import { compile, ParamData } from "path-to-regexp"; const toPath = compile("/user/:id"); const params: ParamData = getUserParams(); // From user input try { // Validate required params exist if (!params.id || typeof params.id !== "string" || params.id.length === 0) { throw new TypeError('Missing required parameter: "id"'); } const path = toPath(params); } catch (error) { console.error("Path building failed:", error.message); } ``` -------------------------------- ### Import Path-to-RegExp Functions Source: https://github.com/pillarjs/path-to-regexp/blob/master/Readme.md Import necessary functions from the path-to-regexp library for use in your project. ```javascript const { match, pathToRegexp, compile, parse, stringify, } = require("path-to-regexp"); ``` -------------------------------- ### TokenData with an array of path patterns for match() Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/api-reference/TokenData.md Demonstrates how to use an array of TokenData instances with the `match` function to handle multiple possible path patterns. This allows a single matcher to resolve different routes. ```typescript import { TokenData, match } from "path-to-regexp"; const userPath = new TokenData([ { type: "text", value: "/user/" }, { type: "param", name: "id" } ]); const adminPath = new TokenData([ { type: "text", value: "/admin/" }, { type: "param", name: "id" } ]); const fn = match([userPath, adminPath]); console.log(fn("/user/123")); // { path: "/user/123", params: { id: "123" } } console.log(fn("/admin/456")); // { path: "/admin/456", params: { id: "456" } } ``` -------------------------------- ### Using Pre-parsed TokenData Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/api-reference/match.md Demonstrates using pre-parsed token data with the `match` function. This can be more efficient if the same path pattern is parsed multiple times. ```typescript import { parse, match } from "path-to-regexp"; const data = parse("/api/:version/resource/:id"); const fn = match(data); console.log(fn("/api/v1/resource/42")); // { path: "/api/v1/resource/42", params: { version: "v1", id: "42" } } ``` -------------------------------- ### Path Building with Parameters Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/usage-guide.md Use the `compile` function to generate URL strings from path templates and parameter objects. Handles simple, multiple, optional, and wildcard segments. ```typescript import { compile } from "path-to-regexp"; // Build simple paths const userPath = compile("/user/:id"); userPath({ id: "john" }); // "/user/john" // Multiple parameters const postPath = compile("/blog/:year/:month/:slug"); postPath({ year: "2024", month: "07", slug: "my-post" }); // "/blog/2024/07/my-post" // With optional segments const editPath = compile("/user/:id{/edit}"); editPath({ id: "123" }); // "/user/123" editPath({ id: "123" }); // "/user/123" editPath({ id: "123" }); // Still "/user/123" (edit is optional) // To include optional segment: const editFormPath = compile("/user/:id{/:action}"); editFormPath({ id: "123", action: "edit" }); // "/user/123/edit" editFormPath({ id: "123" }); // "/user/123" // With wildcard parameters const downloadPath = compile("/files/*path"); downloadPath({ path: ["documents", "report.pdf"] }); // "/files/documents/report.pdf" ``` -------------------------------- ### Standard URL Path Matching Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/configuration.md Use the default settings for standard web routing to match URL paths. ```typescript // Standard web routing — use defaults const fn = match("/user/:id"); ``` -------------------------------- ### Match() with Prefix Matching Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/configuration.md Shows how to use match() with the 'end: false' option to allow for prefix matching. ```typescript // Prefix matching const fn5 = match("/api/:version", { end: false }); fn5("/api/v1/users"); // still matches ``` -------------------------------- ### Optional Parameters Matching Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/api-reference/match.md Demonstrates how to define optional parameters using curly braces `{}`. If the optional part is not present, the match still succeeds. ```typescript const fn = match("/user{/:id}/profile"); console.log(fn("/user/profile")); // { path: "/user/profile", params: {} } console.log(fn("/user/123/profile")); // { path: "/user/123/profile", params: { id: "123" } } ``` -------------------------------- ### Catching TypeErrors during Path Building Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/errors.md Demonstrates how to use try-catch blocks to handle TypeError exceptions when building paths with `compile()`. Covers missing and invalid parameter values. ```typescript import { compile } from "path-to-regexp"; const toPath = compile("/user/:id"); // Missing parameter try { toPath({}); // id is required } catch (error) { if (error instanceof TypeError) { console.log("Build error:", error.message); // "Missing parameters: id" } } // Invalid parameter value try { toPath({ id: "" }); // Empty string not allowed } catch (error) { if (error instanceof TypeError) { console.log("Build error:", error.message); // 'Expected "id" to be a non-empty string' } } ``` -------------------------------- ### match() Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/_VERIFICATION.txt Matches a URL path against a given path string or RegExp, returning an object with matched parameters if successful. ```APIDOC ## match() ### Description Attempts to match a URL path against a given path string or regular expression, returning an object containing the extracted parameters if the match is successful. ### Method `match(path: string | RegExp, options?: MatchOptions): (url: string) => ({ [key: string]: string } | false)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **path** (string | RegExp) - Required - The path string or RegExp to match against. - **options** (MatchOptions) - Optional - Configuration options for matching. - **delimiter** (string) - Optional - The delimiter used in the path (default: \/). - **sensitive** (boolean) - Optional - Whether the path matching should be case-sensitive (default: false). - **end** (boolean) - Optional - Whether the path must match the entire string (default: true). - **strict** (boolean) - Optional - Whether the path must end with a slash if it is the root (default: true). - **start** (boolean) - Optional - Whether the path must match from the beginning of the string (default: true). ### Request Example ```javascript import { match } from 'path-to-regexp'; const matcher = match('/user/:id'); const result = matcher('/user/456'); if (result) { console.log('Matched parameters:', result); } else { console.log('No match.'); } ``` ### Response #### Success Response (200) - **matcher function** - Returns a function that takes a URL string and returns an object with matched parameters or `false` if no match. #### Response Example ```json { "id": "456" } ``` ``` -------------------------------- ### Manual TokenData Creation and Stringification Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/api-reference/stringify.md Creates a `TokenData` object manually and then uses `stringify` to convert it into a path string. Requires `stringify` and `TokenData` to be imported. ```typescript import { stringify, TokenData } from "path-to-regexp"; const data = new TokenData([ { type: "text", value: "/api/" }, { type: "param", name: "version" }, { type: "text", value: "/users/" }, { type: "param", name: "id" } ]); const str = stringify(data); console.log(str); // "/api/:version/users/:id" ``` -------------------------------- ### Use TokenData with compile() Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/api-reference/TokenData.md Demonstrates using a TokenData instance with the `compile` function to create a path builder. This allows generating URL strings from parameter objects. ```typescript import { TokenData, compile } from "path-to-regexp"; const data = new TokenData([ { type: "text", value: "/api/" }, { type: "param", name: "version" } ]); const toPath = compile(data); console.log(toPath({ version: "v1" })); // "/api/v1" ``` -------------------------------- ### pathToRegexp Function Signature Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/api-reference/pathToRegexp.md The primary function `pathToRegexp` takes a path pattern and optional configuration options to generate a regular expression and an array of keys for path matching. ```APIDOC ## pathToRegexp() ### Description Convert a path pattern into a regular expression and an array of capture keys. ### Signature ```typescript pathToRegexp( path: Path | Path[], options?: PathToRegexpOptions & ParseOptions ): { regexp: RegExp; keys: Keys } ``` ### Parameters #### Path Parameters - **path** (string | TokenData | (string | TokenData)[]) - Required - Path pattern(s) as a string, `TokenData`, or array thereof #### Query Parameters - **options** (PathToRegexpOptions & ParseOptions) - Optional - Configuration for regexp generation and parsing - **options.sensitive** (boolean) - Optional - Case-sensitive matching (default is case-insensitive) - **options.end** (boolean) - Optional - Require the match to reach the end of the string - **options.trailing** (boolean) - Optional - Allow optional trailing delimiter - **options.delimiter** (string) - Optional - The delimiter character for segments - **options.encodePath** ((value: string) => string) - Optional - Function for encoding text segments (used when parsing a string path) ### Returns **Type:** `{ regexp: RegExp; keys: Keys }` - `regexp`: A `RegExp` object for matching paths - Includes capturing groups for each parameter and wildcard - Flags: case-insensitive by default (`i` flag), or case-sensitive if `sensitive: true` - `keys`: Array of `Key` objects (type `Parameter | Wildcard`) - Each key corresponds to a capturing group in the regexp - Order matches the order of groups in the regexp ``` -------------------------------- ### compile Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/README.md Creates a function that compiles a path string into a URL, substituting parameters from an object. ```APIDOC ## compile ### Description Creates a function that compiles a path string into a URL, substituting parameters from an object. ### Signature `compile
(path: Path, options?: CompileOptions): PathFunction
` ### Parameters * **path** (Path) - The path string to compile. * **options** (CompileOptions) - Optional. An object to configure compilation. * **encode** (Encode | false) - Optional - A function to encode path segments. Defaults to `encodeURIComponent`. * **delimiter** (string) - Optional - The delimiter used in the path. Defaults to `/`. ``` -------------------------------- ### match Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/README.md Creates a function that matches a given path against a path string. It returns the matched parameters if successful, or false otherwise. ```APIDOC ## match ### Description Creates a function that matches a given path against a path string. ### Signature `match
(path: Path | Path[], options?: MatchOptions): MatchFunction
` ### Parameters * **path** (Path | Path[]) - The path string or an array of path strings to match against. * **options** (MatchOptions) - Optional. An object to configure matching, extending `PathToRegexpOptions`. * **decode** (Decode | false) - Optional - A function to decode matched parameters. Defaults to `decodeURIComponent`. * **sensitive** (boolean) - Optional - If true, the matching will be case-sensitive. Defaults to `false`. * **end** (boolean) - Optional - If true, the match must consume the entire string. Defaults to `true`. * **trailing** (boolean) - Optional - If true, an optional trailing slash is allowed. Defaults to `true`. * **delimiter** (string) - Optional - The delimiter used in the path. Defaults to `/`. ``` -------------------------------- ### Use TokenData with match() Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/api-reference/TokenData.md Illustrates using a TokenData instance with the `match` function to create a path matching function. This function can then be used to test URL strings against the defined path. ```typescript import { TokenData, match } from "path-to-regexp"; const data = new TokenData([ { type: "text", value: "/user/" }, { type: "param", name: "id" } ]); const fn = match(data); console.log(fn("/user/123")); // { path: "/user/123", params: { id: "123" } } ``` -------------------------------- ### pathToRegexp with Options Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/api-reference/pathToRegexp.md Illustrates using options like 'sensitive' and 'end' to customize the generated RegExp. Use 'sensitive: true' for case-sensitive matching and 'end: false' to allow partial matches. ```typescript import { pathToRegexp } from 'path-to-regexp'; const { regexp, keys } = pathToRegexp('/user/:id', { sensitive: true, end: false }); console.log(regexp); // /^ooar/i console.log(keys); // [{ name: 'id', prefix: '/', suffix: '', repeat: false, optional: false, partial: false, delegate: undefined }] ``` -------------------------------- ### Match Wildcard Parameters Source: https://github.com/pillarjs/path-to-regexp/blob/master/Readme.md Use wildcard parameters (prefixed with `*`) to match multiple path segments. The matched segments are returned as an array. ```javascript const fn = match("/*splat"); fn("/bar/baz"); //=> { path: '/bar/baz', params: { splat: [ 'bar', 'baz' ] } } ``` -------------------------------- ### Match() with Default Decoding Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/configuration.md Demonstrates using match() with the default decodeURIComponent for URL parameters. ```typescript import { match } from "path-to-regexp"; // Default decoding with decodeURIComponent const fn1 = match("/search/:query"); fn1("/search/hello%20world"); // { path: "/search/hello world", params: { query: "hello world" } } ``` -------------------------------- ### URL Encoding and Decoding Handling Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/usage-guide.md Demonstrates how `path-to-regexp` automatically handles URL encoding during path compilation and decoding during matching. Options to disable this behavior are also shown. ```typescript import { match, compile } from "path-to-regexp"; // Automatic URL encoding in compile const searchPath = compile("/search/:query"); searchPath({ query: "hello world" }); // "/search/hello%20world" searchPath({ query: "café" }); // "/search/caf%C3%A9" // Automatic URL decoding in match const searchMatcher = match("/search/:query"); searchMatcher("/search/hello%20world"); // { params: { query: "hello world" } } searchMatcher("/search/caf%C3%A9"); // { params: { query: "café" } } // Disable encoding/decoding if data is pre-encoded const builder = compile("/search/:query", { encode: false }); builder({ query: "already%20encoded" }); // "/search/already%20encoded" const matcher = match("/search/:query", { decode: false }); matcher("/search/hello%20world"); // { params: { query: "hello%20world" } } — not decoded ``` -------------------------------- ### stringify() Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/_VERIFICATION.txt Generates a URL string from a path pattern and an object of parameters. This is a convenience function that uses `compile()` internally. ```APIDOC ## stringify() ### Description Generates a URL string from a path pattern and an object of parameters. This is a convenience function that internally uses the `compile` method. ### Method `stringify(path: string | RegExp, params: { [key: string]: string }, options?: CompileOptions): string` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **path** (string | RegExp) - Required - The path string or RegExp pattern. - **params** ({ [key: string]: string }) - Required - An object containing the parameters to substitute into the path. - **options** (CompileOptions) - Optional - Configuration options for compiling the path (same as `compile` options). ### Request Example ```javascript import { stringify } from 'path-to-regexp'; const url = stringify('/posts/:year/:month', { year: '2023', month: '10' }); console.log(url); ``` ### Response #### Success Response (200) - **url** (string) - The generated URL string. #### Response Example ```javascript "/posts/2023/10" ``` ``` -------------------------------- ### match() Function Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/api-reference/match.md Creates a function that matches paths against a pattern and extracts parameters. The returned function takes an input string and returns either false if the input does not match, or a MatchResult object with the matched path and extracted parameters. ```APIDOC ## match() ### Description Creates a function that matches paths against a pattern and extracts parameters. ### Signature ```typescript match
(path: Path | Path[], options?: MatchOptions & ParseOptions): MatchFunction
``` ### Parameters #### Path Parameter - **path** (string | TokenData | (string | TokenData)[]) - Required - Path pattern(s) as a string, `TokenData`, or array thereof #### Options - **options** (MatchOptions & ParseOptions) - Optional - Configuration for matching and parsing - **options.decode** ( (value: string) => string | false ) - Optional - Function to decode matched parameters, or `false` to disable decoding. Default: `decodeURIComponent` - **options.sensitive** ( boolean ) - Optional - Case-sensitive matching (default is case-insensitive). Default: `false` - **options.end** ( boolean ) - Optional - Require the match to reach the end of the string. Default: `true` - **options.trailing** ( boolean ) - Optional - Allow optional trailing delimiter. Default: `true` - **options.delimiter** ( string ) - Optional - The delimiter character for segments. Default: `/` - **options.encodePath** ( (value: string) => string ) - Optional - Function for encoding text segments (used when parsing a string path). Default: Identity function ### Returns **Type:** `MatchFunction
` — A function with signature `(input: string) => Match
`
The returned function accepts an input string and returns either:
- `false` if the input does not match the pattern
- A `MatchResult` object with `{ path: string; params: P }` on match
```
--------------------------------
### PathToRegexpOptions Interface
Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/configuration.md
Defines configuration options for the `pathToRegexp` function. These control matching behavior like end-of-string, trailing delimiters, case sensitivity, and segment delimiters.
```typescript
interface PathToRegexpOptions {
end?: boolean;
trailing?: boolean;
sensitive?: boolean;
delimiter?: string;
}
```
--------------------------------
### Match() with Case-Sensitive and Custom Delimiter
Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/configuration.md
Demonstrates configuring match() for case-sensitive matching and using a custom delimiter.
```typescript
// Case-sensitive + custom delimiter
const fn4 = match("Host.example.com", {
sensitive: true,
delimiter: "."
});
```
--------------------------------
### pathToRegexp()
Source: https://github.com/pillarjs/path-to-regexp/blob/master/_autodocs/_VERIFICATION.txt
Converts a path string into a regular expression. This is the core function for matching URL paths against defined routes.
```APIDOC
## pathToRegexp()
### Description
Converts a path string into a regular expression object that can be used for matching URL paths.
### Method
`pathToRegexp(path: string | RegExp, tokens?: Array