| 1 | /**
|
| 2 | * react-router v8.3.0
|
| 3 | *
|
| 4 | * Copyright (c) Remix Software Inc.
|
| 5 | *
|
| 6 | * This source code is licensed under the MIT license found in the
|
| 7 | * LICENSE.md file in the root directory of this source tree.
|
| 8 | *
|
| 9 | * @license MIT
|
| 10 | */
|
| 11 | import { encodePathParam } from "./router/utils.js";
|
| 12 | //#region lib/href.ts
|
| 13 | function stringify(p) {
|
| 14 | return p == null ? "" : typeof p === "string" ? p : String(p);
|
| 15 | }
|
| 16 | /**
|
| 17 | * Returns a resolved URL path for the specified route.
|
| 18 | *
|
| 19 | * Param values are percent-encoded for use in a path segment: characters that
|
| 20 | * would change the URL structure (`/`, `?`, `#`, `%`, whitespace, non-ASCII)
|
| 21 | * are escaped, while characters that RFC 3986 allows literally in a path
|
| 22 | * segment (`$ & + , ; = : @`) are kept as-is. Note this differs from query-string
|
| 23 | * encoding (`encodeURIComponent`/`URLSearchParams`), where those characters are
|
| 24 | * delimiters and must be escaped. Splat (`*`) values are encoded per segment,
|
| 25 | * preserving `/` separators.
|
| 26 | *
|
| 27 | * See [RFC 3986 §3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3)
|
| 28 | *
|
| 29 | * @example
|
| 30 | * const h = href("/:lang?/about", { lang: "en" })
|
| 31 | * // -> `/en/about`
|
| 32 | *
|
| 33 | * <Link to={href("/products/:id", { id: "abc123" })} />
|
| 34 | *
|
| 35 | * @public
|
| 36 | * @category Utils
|
| 37 | * @mode framework
|
| 38 | * @param path The route path to resolve
|
| 39 | * @param args The route params to use when resolving the path
|
| 40 | * @returns The resolved URL path
|
| 41 | */
|
| 42 | function href(path, ...args) {
|
| 43 | let params = args[0];
|
| 44 | let result = trimTrailingSplat(path).replace(/\/:([\w-]+)(\?)?/g, (_, param, questionMark) => {
|
| 45 | const isRequired = questionMark === void 0;
|
| 46 | const value = params?.[param];
|
| 47 | if (isRequired && value === void 0) throw new Error(`Path '${path}' requires param '${param}' but it was not provided`);
|
| 48 | return value == null ? "" : "/" + encodePathParam(stringify(value));
|
| 49 | });
|
| 50 | if (path.endsWith("*")) {
|
| 51 | const value = params?.["*"];
|
| 52 | if (value !== void 0) result += "/" + stringify(value).split("/").map(encodePathParam).join("/");
|
| 53 | }
|
| 54 | return result || "/";
|
| 55 | }
|
| 56 | /**
|
| 57 | * Removes a trailing splat and any number of slashes from the end of the path.
|
| 58 | *
|
| 59 | * Benchmarked to be faster than `path.replace(/\/*\*?$/, "")`, which backtracks.
|
| 60 | */
|
| 61 | function trimTrailingSplat(path) {
|
| 62 | let i = path.length - 1;
|
| 63 | let char = path[i];
|
| 64 | if (char !== "*" && char !== "/") return path;
|
| 65 | i--;
|
| 66 | for (; i >= 0; i--) if (path[i] !== "/") break;
|
| 67 | return path.slice(0, i + 1);
|
| 68 | }
|
| 69 | //#endregion
|
| 70 | export { href };
|