@vielzeug/wayfinder 26.11.12 → 26.11.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -4
- package/dist/path.cjs +1 -1
- package/dist/path.cjs.map +1 -1
- package/dist/path.d.ts +1 -9
- package/dist/path.d.ts.map +1 -1
- package/dist/path.js +1 -9
- package/dist/path.js.map +1 -1
- package/dist/query-state.cjs +2 -0
- package/dist/query-state.cjs.map +1 -0
- package/dist/query-state.d.ts +80 -0
- package/dist/query-state.d.ts.map +1 -0
- package/dist/query-state.js +90 -0
- package/dist/query-state.js.map +1 -0
- package/dist/router.cjs +1 -1
- package/dist/router.cjs.map +1 -1
- package/dist/router.d.ts +5 -3
- package/dist/router.d.ts.map +1 -1
- package/dist/router.js +83 -112
- package/dist/router.js.map +1 -1
- package/dist/wayfinder.cjs +1 -1
- package/dist/wayfinder.cjs.map +1 -1
- package/dist/wayfinder.iife.js +1 -1
- package/dist/wayfinder.iife.js.map +1 -1
- package/dist/wayfinder.js +164 -170
- package/dist/wayfinder.js.map +1 -1
- package/package.json +2 -2
- package/dist/phase-mirror.cjs +0 -2
- package/dist/phase-mirror.cjs.map +0 -1
- package/dist/phase-mirror.d.ts +0 -51
- package/dist/phase-mirror.d.ts.map +0 -1
- package/dist/phase-mirror.js +0 -58
- package/dist/phase-mirror.js.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./history.cjs"),n=require("./middleware.cjs"),r=require("./
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./history.cjs"),n=require("./middleware.cjs"),r=require("./query-state.cjs"),i=require("./route-signals.cjs"),a=require("./router.cjs");exports.WayfinderApiError=e.WayfinderApiError,exports.WayfinderConfigError=e.WayfinderConfigError,exports.WayfinderDisposedError=e.WayfinderDisposedError,exports.WayfinderError=e.WayfinderError,exports.WayfinderRedirectLoopError=e.WayfinderRedirectLoopError,exports.WayfinderRouteError=e.WayfinderRouteError,exports.createBrowserHistory=t.createBrowserHistory,exports.createHashHistory=t.createHashHistory,exports.createHistoryForBase=t.createHistoryForBase,exports.createMemoryHistory=t.createMemoryHistory,exports.createQueryState=r.createQueryState,exports.createRouteSignals=i.createRouteSignals,exports.createRouter=a.createRouter,exports.param=r.param,exports.redirectTo=n.redirectTo;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
export { WayfinderApiError, WayfinderConfigError, WayfinderDisposedError, WayfinderError, WayfinderRedirectLoopError, WayfinderRouteError, } from './errors';
|
|
2
2
|
export { createBrowserHistory, createHashHistory, createHistoryForBase, createMemoryHistory, type HashHistoryOptions, } from './history';
|
|
3
3
|
export { redirectTo } from './middleware';
|
|
4
|
-
export type {
|
|
5
|
-
export {
|
|
4
|
+
export type { ParamSpec, QueryState, QueryStateOptions, QueryStateSetOptions, QueryStateSpec, RawParamValue, } from './query-state';
|
|
5
|
+
export { createQueryState, param } from './query-state';
|
|
6
6
|
export type { RouteSignals } from './route-signals';
|
|
7
7
|
export { createRouteSignals } from './route-signals';
|
|
8
8
|
export type { Router } from './router';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,sBAAsB,EACtB,cAAc,EACd,0BAA0B,EAC1B,mBAAmB,GACpB,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,oBAAoB,EACpB,iBAAiB,EACjB,oBAAoB,EACpB,mBAAmB,EACnB,KAAK,kBAAkB,GACxB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,YAAY,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,sBAAsB,EACtB,cAAc,EACd,0BAA0B,EAC1B,mBAAmB,GACpB,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,oBAAoB,EACpB,iBAAiB,EACjB,oBAAoB,EACpB,mBAAmB,EACnB,KAAK,kBAAkB,GACxB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,YAAY,EACV,SAAS,EACT,UAAU,EACV,iBAAiB,EACjB,oBAAoB,EACpB,cAAc,EACd,aAAa,GACd,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACxD,YAAY,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,YAAY,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,YAAY,EACV,kBAAkB,EAClB,kBAAkB,EAClB,cAAc,EACd,WAAW,EACX,MAAM,EACN,aAAa,EACb,eAAe,EACf,YAAY,EACZ,UAAU,EACV,qBAAqB,EACrB,eAAe,EACf,qBAAqB,EACrB,gBAAgB,EAChB,gBAAgB,EAChB,UAAU,EACV,WAAW,EACX,mBAAmB,EACnB,mBAAmB,EACnB,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,aAAa,EACb,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,SAAS,EACT,WAAW,EACX,eAAe,EACf,kBAAkB,EAClB,aAAa,EACb,UAAU,EACV,UAAU,EACV,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,WAAW,EACX,4BAA4B,GAC7B,MAAM,SAAS,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { WayfinderApiError as e, WayfinderConfigError as t, WayfinderDisposedError as n, WayfinderError as r, WayfinderRedirectLoopError as i, WayfinderRouteError as a } from "./errors.js";
|
|
2
2
|
import { createBrowserHistory as o, createHashHistory as s, createHistoryForBase as c, createMemoryHistory as l } from "./history.js";
|
|
3
3
|
import { redirectTo as u } from "./middleware.js";
|
|
4
|
-
import {
|
|
5
|
-
import { createRouteSignals as
|
|
6
|
-
import { createRouter as
|
|
7
|
-
export { e as WayfinderApiError, t as WayfinderConfigError, n as WayfinderDisposedError, r as WayfinderError, i as WayfinderRedirectLoopError, a as WayfinderRouteError, o as createBrowserHistory, s as createHashHistory, c as createHistoryForBase, l as createMemoryHistory, d as
|
|
4
|
+
import { createQueryState as d, param as f } from "./query-state.js";
|
|
5
|
+
import { createRouteSignals as p } from "./route-signals.js";
|
|
6
|
+
import { createRouter as m } from "./router.js";
|
|
7
|
+
export { e as WayfinderApiError, t as WayfinderConfigError, n as WayfinderDisposedError, r as WayfinderError, i as WayfinderRedirectLoopError, a as WayfinderRouteError, o as createBrowserHistory, s as createHashHistory, c as createHistoryForBase, l as createMemoryHistory, d as createQueryState, p as createRouteSignals, m as createRouter, f as param, u as redirectTo };
|
package/dist/path.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./errors.cjs");function normalizePath(e){let t=`/${e}`.replace(/\/+/g,`/`);return t!==`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function joinPaths(e,t){return normalizePath(`${e}/${t}`)}function escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function compilePathMatcher(t){let n=normalizePath(t);if(n===`/`)return{paramNames:[],pattern:/^\/$/,prefixPattern:/^\/$/};let r=[],i=n.slice(1).split(`/`),a=[`^`],o=[`^`];for(let n=0;n<i.length;n+=1){let s=i[n];if(s===`*`){if(n!==i.length-1)throw new e.WayfinderConfigError(`Wildcard "*" must be the final segment in path: ${t}`);a.push(`(?:/.*)?`);break}if(s.startsWith(`:`)&&s.endsWith(`*`)){if(n!==i.length-1)throw new e.WayfinderConfigError(`Wildcard param must be final segment in path: ${t}`);let c=s.slice(1,-1);if(!/^\w+$/.test(c))throw new e.WayfinderConfigError(`Invalid param name ":${c}" in path "${t}". Param names must only contain word characters (a–z, A–Z, 0–9, _).`);r.push(c),a.push(n===i.length-1?`(?:/(.*))?`:`/(.*)`),o.push(`/.*`);break}if(s.startsWith(`:`)){let n=s.slice(1);if(!/^\w+$/.test(n))throw new e.WayfinderConfigError(`Invalid param name ":${n}" in path "${t}". Param names must only contain word characters (a–z, A–Z, 0–9, _).`);r.push(n),a.push(`/([^/]+)`),o.push(`/[^/]+`);continue}let c=escapeRegex(s);a.push(`/${c}`),o.push(`/${c}`)}return a.push(`$`),o.push(`(?:/.*)?$`),{paramNames:r,pattern:new RegExp(a.join(``)),prefixPattern:new RegExp(o.join(``))}}function matchRecord(e,t){let n=t.matcher.pattern.exec(e);if(!n)return null;let r={};return t.matcher.paramNames.forEach((e,t)=>{let i=n[t+1]??``;try{r[e]=decodeURIComponent(i)}catch{r[e]=i}}),r}function matchRouteFor(e,t){for(let n of t){let t=matchRecord(e,n);if(t)return{params:t,record:n}}return{params:{}}}function matchesPrefix(e,t){return t.matcher.prefixPattern.test(e)}function parseQuery(e){let t=new URLSearchParams(e),n={},setQueryValue=(e,t)=>{Object.defineProperty(n,e,{configurable:!0,enumerable:!0,value:t,writable:!0})};for(let[e,r]of t.entries()){let t=Object.hasOwn(n,e)?n[e]:void 0;t===void 0?setQueryValue(e,r):Array.isArray(t)?t.push(r):setQueryValue(e,[t,r])}return n}function buildUrl(t,n,r={},i){let a=n.replace(/:(\w+)(\*)?/g,(t,n,i)=>{let a=r[n];if(a==null)throw new e.WayfinderRouteError(`Missing path param: ${n}`);return i?a.split(`/`).map(e=>encodeURIComponent(e)).join(`/`):encodeURIComponent(a)});if(i&&Object.keys(i).length){let e=new URLSearchParams;Object.entries(i).forEach(([t,n])=>{Array.isArray(n)?n.forEach(n=>{e.append(t,String(n))}):e.set(t,String(n))}),a+=`?${e.toString()}`}return joinPaths(t,a)}function stripBase(e,t=`/`){let n=normalizePath(e),r=normalizePath(t);if(r===`/`)return n;if(n===r)return`/`;let i=`${r}/`;return n.startsWith(i)?normalizePath(n.slice(r.length)):n}
|
|
1
|
+
const e=require("./errors.cjs");function normalizePath(e){let t=`/${e}`.replace(/\/+/g,`/`);return t!==`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function joinPaths(e,t){return normalizePath(`${e}/${t}`)}function escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function compilePathMatcher(t){let n=normalizePath(t);if(n===`/`)return{paramNames:[],pattern:/^\/$/,prefixPattern:/^\/$/};let r=[],i=n.slice(1).split(`/`),a=[`^`],o=[`^`];for(let n=0;n<i.length;n+=1){let s=i[n];if(s===`*`){if(n!==i.length-1)throw new e.WayfinderConfigError(`Wildcard "*" must be the final segment in path: ${t}`);a.push(`(?:/.*)?`);break}if(s.startsWith(`:`)&&s.endsWith(`*`)){if(n!==i.length-1)throw new e.WayfinderConfigError(`Wildcard param must be final segment in path: ${t}`);let c=s.slice(1,-1);if(!/^\w+$/.test(c))throw new e.WayfinderConfigError(`Invalid param name ":${c}" in path "${t}". Param names must only contain word characters (a–z, A–Z, 0–9, _).`);r.push(c),a.push(n===i.length-1?`(?:/(.*))?`:`/(.*)`),o.push(`/.*`);break}if(s.startsWith(`:`)){let n=s.slice(1);if(!/^\w+$/.test(n))throw new e.WayfinderConfigError(`Invalid param name ":${n}" in path "${t}". Param names must only contain word characters (a–z, A–Z, 0–9, _).`);r.push(n),a.push(`/([^/]+)`),o.push(`/[^/]+`);continue}let c=escapeRegex(s);a.push(`/${c}`),o.push(`/${c}`)}return a.push(`$`),o.push(`(?:/.*)?$`),{paramNames:r,pattern:new RegExp(a.join(``)),prefixPattern:new RegExp(o.join(``))}}function matchRecord(e,t){let n=t.matcher.pattern.exec(e);if(!n)return null;let r={};return t.matcher.paramNames.forEach((e,t)=>{let i=n[t+1]??``;try{r[e]=decodeURIComponent(i)}catch{r[e]=i}}),r}function matchRouteFor(e,t){for(let n of t){let t=matchRecord(e,n);if(t)return{params:t,record:n}}return{params:{}}}function matchesPrefix(e,t){return t.matcher.prefixPattern.test(e)}function parseQuery(e){let t=new URLSearchParams(e),n={},setQueryValue=(e,t)=>{Object.defineProperty(n,e,{configurable:!0,enumerable:!0,value:t,writable:!0})};for(let[e,r]of t.entries()){let t=Object.hasOwn(n,e)?n[e]:void 0;t===void 0?setQueryValue(e,r):Array.isArray(t)?t.push(r):setQueryValue(e,[t,r])}return n}function buildUrl(t,n,r={},i){let a=n.replace(/:(\w+)(\*)?/g,(t,n,i)=>{let a=r[n];if(a==null)throw new e.WayfinderRouteError(`Missing path param: ${n}`);return i?a.split(`/`).map(e=>encodeURIComponent(e)).join(`/`):encodeURIComponent(a)});if(i&&Object.keys(i).length){let e=new URLSearchParams;Object.entries(i).forEach(([t,n])=>{Array.isArray(n)?n.forEach(n=>{e.append(t,String(n))}):e.set(t,String(n))}),a+=`?${e.toString()}`}return joinPaths(t,a)}function stripBase(e,t=`/`){let n=normalizePath(e),r=normalizePath(t);if(r===`/`)return n;if(n===r)return`/`;let i=`${r}/`;return n.startsWith(i)?normalizePath(n.slice(r.length)):n}exports.buildUrl=buildUrl,exports.compilePathMatcher=compilePathMatcher,exports.joinPaths=joinPaths,exports.matchRecord=matchRecord,exports.matchRouteFor=matchRouteFor,exports.matchesPrefix=matchesPrefix,exports.normalizePath=normalizePath,exports.parseQuery=parseQuery,exports.stripBase=stripBase;
|
|
2
2
|
//# sourceMappingURL=path.cjs.map
|
package/dist/path.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"path.cjs","names":["WayfinderConfigError","WayfinderRouteError","require_errors","normalized","path","base","input","paramNames","segments","regexParts","prefixParts","i","segment","name","escaped","match","record","pathname","params","value","index","records","search","queryString","out","key","existing","pattern","isWildcard","query","item","normalizedPath","normalizedBase","prefix","history"],"sources":["../src/path.ts"],"sourcesContent":["import { WayfinderConfigError, WayfinderRouteError } from './errors';\nimport type { QueryParams, ResolvedQueryParams, RouteLocation, RouteMatcher, RouteParams, RouteRecord } from './types';\n\n/** Ensure leading slash, collapse duplicate slashes, preserve root. */\nexport function normalizePath(path: string): string {\n const normalized = `/${path}`.replace(/\\/+/g, '/');\n\n return normalized !== '/' && normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;\n}\n\nexport function joinPaths(base: string, path: string): string {\n return normalizePath(`${base}/${path}`);\n}\n\nfunction escapeRegex(input: string): string {\n return input.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nexport function compilePathMatcher(path: string): RouteMatcher {\n const normalized = normalizePath(path);\n\n if (normalized === '/') {\n return {\n paramNames: [],\n pattern: /^\\/$/,\n prefixPattern: /^\\/$/,\n };\n }\n\n const paramNames: string[] = [];\n const segments = normalized.slice(1).split('/');\n const regexParts: string[] = ['^'];\n const prefixParts: string[] = ['^'];\n\n for (let i = 0; i < segments.length; i += 1) {\n const segment = segments[i]!;\n\n if (segment === '*') {\n if (i !== segments.length - 1) {\n throw new WayfinderConfigError(`Wildcard \"*\" must be the final segment in path: ${path}`);\n }\n\n regexParts.push('(?:/.*)?');\n break;\n }\n\n if (segment.startsWith(':') && segment.endsWith('*')) {\n if (i !== segments.length - 1) {\n throw new WayfinderConfigError(`Wildcard param must be final segment in path: ${path}`);\n }\n\n const name = segment.slice(1, -1);\n\n if (!/^\\w+$/.test(name)) {\n throw new WayfinderConfigError(\n `Invalid param name \":${name}\" in path \"${path}\". Param names must only contain word characters (a–z, A–Z, 0–9, _).`,\n );\n }\n\n paramNames.push(name);\n regexParts.push(i === segments.length - 1 ? '(?:/(.*))?' : '/(.*)');\n prefixParts.push('/.*');\n break;\n }\n\n if (segment.startsWith(':')) {\n const name = segment.slice(1);\n\n if (!/^\\w+$/.test(name)) {\n throw new WayfinderConfigError(\n `Invalid param name \":${name}\" in path \"${path}\". Param names must only contain word characters (a–z, A–Z, 0–9, _).`,\n );\n }\n\n paramNames.push(name);\n regexParts.push('/([^/]+)');\n prefixParts.push('/[^/]+');\n continue;\n }\n\n const escaped = escapeRegex(segment);\n\n regexParts.push(`/${escaped}`);\n prefixParts.push(`/${escaped}`);\n }\n\n regexParts.push('$');\n prefixParts.push('(?:/.*)?$');\n\n return {\n paramNames,\n pattern: new RegExp(regexParts.join('')),\n prefixPattern: new RegExp(prefixParts.join('')),\n };\n}\n\nexport function matchRecord(pathname: string, record: RouteRecord): RouteParams | null {\n const match = record.matcher.pattern.exec(pathname);\n\n if (!match) return null;\n\n const params: RouteParams = {};\n\n record.matcher.paramNames.forEach((name: string, index: number) => {\n const value = match[index + 1] ?? '';\n\n try {\n params[name] = decodeURIComponent(value);\n } catch {\n params[name] = value;\n }\n });\n\n return params;\n}\n\nexport function matchRouteFor(\n pathname: string,\n records: readonly RouteRecord[],\n): { params: RouteParams; record?: RouteRecord } {\n for (const record of records) {\n const params = matchRecord(pathname, record);\n\n if (params) return { params, record };\n }\n\n return { params: {} };\n}\n\nexport function matchesPrefix(pathname: string, record: RouteRecord): boolean {\n return record.matcher.prefixPattern.test(pathname);\n}\n\n/**\n * Parse `?foo=a&foo=b&bar=c` into `{ foo: ['a', 'b'], bar: 'c' }`.\n *\n * @security Query keys come directly from the (attacker-controlled) URL. Plain bracket\n * assignment (`out[key] = value`) would let a key like `__proto__` reach the inherited\n * `Object.prototype.__proto__` setter and silently rewrite `out`'s own prototype instead of\n * storing a value: `setQueryValue` uses `Object.defineProperty` so every key, including\n * `__proto__`/`constructor`/`prototype`, is always stored as a plain own data property.\n */\nexport function parseQuery(queryString: string): QueryParams {\n const search = new URLSearchParams(queryString);\n const out: QueryParams = {};\n\n const setQueryValue = (key: string, value: QueryParams[string]): void => {\n Object.defineProperty(out, key, { configurable: true, enumerable: true, value, writable: true });\n };\n\n for (const [key, value] of search.entries()) {\n const existing = Object.hasOwn(out, key) ? out[key] : undefined;\n\n if (existing === undefined) {\n setQueryValue(key, value);\n continue;\n }\n\n if (Array.isArray(existing)) {\n existing.push(value);\n continue;\n }\n\n setQueryValue(key, [existing, value]);\n }\n\n return out;\n}\n\n/** Build a URL from a path pattern, params, and query, respecting the router base. */\nexport function buildUrl(base: string, pattern: string, params: RouteParams = {}, query?: ResolvedQueryParams): string {\n let path = pattern.replace(/:(\\w+)(\\*)?/g, (_match, key: string, isWildcard: string) => {\n const value = params[key];\n\n if (value == null) throw new WayfinderRouteError(`Missing path param: ${key}`);\n\n if (isWildcard) {\n return value\n .split('/')\n .map((segment) => encodeURIComponent(segment))\n .join('/');\n }\n\n return encodeURIComponent(value);\n });\n\n if (query && Object.keys(query).length) {\n const search = new URLSearchParams();\n\n Object.entries(query).forEach(([key, value]) => {\n if (Array.isArray(value))\n value.forEach((item) => {\n search.append(key, String(item));\n });\n else search.set(key, String(value));\n });\n\n path += `?${search.toString()}`;\n }\n\n return joinPaths(base, path);\n}\n\n// ─── Location helpers (formerly in resolve.ts) ────────────────────────────────\n\nexport function stripBase(pathname: string, base = '/'): string {\n const normalizedPath = normalizePath(pathname);\n const normalizedBase = normalizePath(base);\n\n if (normalizedBase === '/') return normalizedPath;\n\n if (normalizedPath === normalizedBase) return '/';\n\n const prefix = `${normalizedBase}/`;\n\n return normalizedPath.startsWith(prefix)\n ? normalizePath(normalizedPath.slice(normalizedBase.length))\n : normalizedPath;\n}\n\nexport function readLocation(\n base: string,\n history: { location: { hash: string; pathname: string; search: string; state: unknown } },\n): RouteLocation {\n return {\n hash: history.location.hash.replace(/^#/, ''),\n historyState: history.location.state,\n pathname: stripBase(history.location.pathname || '/', base),\n query: parseQuery(history.location.search || ''),\n };\n}\n"],"mappings":"A,gCAIA,SAAgB,cAAc,EAAsB,CAClD,IAAMG,EAAa,IAAIC,IAAO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kB,EAAO,IAAa,CAC9D,IAAM2B,EAAiB,cAAcd,CAAQ,EACvCe,EAAiB,cAAc3B,CAAI,EAEzC,GAAI2B,IAAmB,IAAK,OAAOD,EAEnC,GAAIA,IAAmBC,EAAgB,MAAO,IAE9C,IAAMC,EAAS,GAAGD,EAAe,GAEjC,OAAOD,EAAe,WAAWE,CAAM,EACnC,cAAcF,EAAe,MAAMC,EAAe,MAAM,CAAC,EACzDD,CACN,CAEA,SAAgB,aACd,EACA,EACe,CACf,MAAO,CACL,KAAMG,EAAQ,SAAS,KAAK,QAAQ,KAAM,EAAE,EAC5C,aAAcA,EAAQ,SAAS,MAC/B,SAAU,UAAUA,EAAQ,SAAS,UAAY,IAAK7B,CAAI,EAC1D,MAAO,WAAW6B,EAAQ,SAAS,QAAU,EAAE,CACjD,CACF,C"}
|
|
1
|
+
{"version":3,"file":"path.cjs","names":["WayfinderConfigError","WayfinderRouteError","require_errors","normalized","path","base","input","paramNames","segments","regexParts","prefixParts","i","segment","name","escaped","match","record","pathname","params","value","index","records","search","queryString","out","key","existing","pattern","isWildcard","query","item","normalizedPath","normalizedBase","prefix"],"sources":["../src/path.ts"],"sourcesContent":["import { WayfinderConfigError, WayfinderRouteError } from './errors';\nimport type { QueryParams, ResolvedQueryParams, RouteMatcher, RouteParams, RouteRecord } from './types';\n\n/** Ensure leading slash, collapse duplicate slashes, preserve root. */\nexport function normalizePath(path: string): string {\n const normalized = `/${path}`.replace(/\\/+/g, '/');\n\n return normalized !== '/' && normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;\n}\n\nexport function joinPaths(base: string, path: string): string {\n return normalizePath(`${base}/${path}`);\n}\n\nfunction escapeRegex(input: string): string {\n return input.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nexport function compilePathMatcher(path: string): RouteMatcher {\n const normalized = normalizePath(path);\n\n if (normalized === '/') {\n return {\n paramNames: [],\n pattern: /^\\/$/,\n prefixPattern: /^\\/$/,\n };\n }\n\n const paramNames: string[] = [];\n const segments = normalized.slice(1).split('/');\n const regexParts: string[] = ['^'];\n const prefixParts: string[] = ['^'];\n\n for (let i = 0; i < segments.length; i += 1) {\n const segment = segments[i]!;\n\n if (segment === '*') {\n if (i !== segments.length - 1) {\n throw new WayfinderConfigError(`Wildcard \"*\" must be the final segment in path: ${path}`);\n }\n\n regexParts.push('(?:/.*)?');\n break;\n }\n\n if (segment.startsWith(':') && segment.endsWith('*')) {\n if (i !== segments.length - 1) {\n throw new WayfinderConfigError(`Wildcard param must be final segment in path: ${path}`);\n }\n\n const name = segment.slice(1, -1);\n\n if (!/^\\w+$/.test(name)) {\n throw new WayfinderConfigError(\n `Invalid param name \":${name}\" in path \"${path}\". Param names must only contain word characters (a–z, A–Z, 0–9, _).`,\n );\n }\n\n paramNames.push(name);\n regexParts.push(i === segments.length - 1 ? '(?:/(.*))?' : '/(.*)');\n prefixParts.push('/.*');\n break;\n }\n\n if (segment.startsWith(':')) {\n const name = segment.slice(1);\n\n if (!/^\\w+$/.test(name)) {\n throw new WayfinderConfigError(\n `Invalid param name \":${name}\" in path \"${path}\". Param names must only contain word characters (a–z, A–Z, 0–9, _).`,\n );\n }\n\n paramNames.push(name);\n regexParts.push('/([^/]+)');\n prefixParts.push('/[^/]+');\n continue;\n }\n\n const escaped = escapeRegex(segment);\n\n regexParts.push(`/${escaped}`);\n prefixParts.push(`/${escaped}`);\n }\n\n regexParts.push('$');\n prefixParts.push('(?:/.*)?$');\n\n return {\n paramNames,\n pattern: new RegExp(regexParts.join('')),\n prefixPattern: new RegExp(prefixParts.join('')),\n };\n}\n\nexport function matchRecord(pathname: string, record: RouteRecord): RouteParams | null {\n const match = record.matcher.pattern.exec(pathname);\n\n if (!match) return null;\n\n const params: RouteParams = {};\n\n record.matcher.paramNames.forEach((name: string, index: number) => {\n const value = match[index + 1] ?? '';\n\n try {\n params[name] = decodeURIComponent(value);\n } catch {\n params[name] = value;\n }\n });\n\n return params;\n}\n\nexport function matchRouteFor(\n pathname: string,\n records: readonly RouteRecord[],\n): { params: RouteParams; record?: RouteRecord } {\n for (const record of records) {\n const params = matchRecord(pathname, record);\n\n if (params) return { params, record };\n }\n\n return { params: {} };\n}\n\nexport function matchesPrefix(pathname: string, record: RouteRecord): boolean {\n return record.matcher.prefixPattern.test(pathname);\n}\n\n/**\n * Parse `?foo=a&foo=b&bar=c` into `{ foo: ['a', 'b'], bar: 'c' }`.\n *\n * @security Query keys come directly from the (attacker-controlled) URL. Plain bracket\n * assignment (`out[key] = value`) would let a key like `__proto__` reach the inherited\n * `Object.prototype.__proto__` setter and silently rewrite `out`'s own prototype instead of\n * storing a value: `setQueryValue` uses `Object.defineProperty` so every key, including\n * `__proto__`/`constructor`/`prototype`, is always stored as a plain own data property.\n */\nexport function parseQuery(queryString: string): QueryParams {\n const search = new URLSearchParams(queryString);\n const out: QueryParams = {};\n\n const setQueryValue = (key: string, value: QueryParams[string]): void => {\n Object.defineProperty(out, key, { configurable: true, enumerable: true, value, writable: true });\n };\n\n for (const [key, value] of search.entries()) {\n const existing = Object.hasOwn(out, key) ? out[key] : undefined;\n\n if (existing === undefined) {\n setQueryValue(key, value);\n continue;\n }\n\n if (Array.isArray(existing)) {\n existing.push(value);\n continue;\n }\n\n setQueryValue(key, [existing, value]);\n }\n\n return out;\n}\n\n/** Build a URL from a path pattern, params, and query, respecting the router base. */\nexport function buildUrl(base: string, pattern: string, params: RouteParams = {}, query?: ResolvedQueryParams): string {\n let path = pattern.replace(/:(\\w+)(\\*)?/g, (_match, key: string, isWildcard: string) => {\n const value = params[key];\n\n if (value == null) throw new WayfinderRouteError(`Missing path param: ${key}`);\n\n if (isWildcard) {\n return value\n .split('/')\n .map((segment) => encodeURIComponent(segment))\n .join('/');\n }\n\n return encodeURIComponent(value);\n });\n\n if (query && Object.keys(query).length) {\n const search = new URLSearchParams();\n\n Object.entries(query).forEach(([key, value]) => {\n if (Array.isArray(value))\n value.forEach((item) => {\n search.append(key, String(item));\n });\n else search.set(key, String(value));\n });\n\n path += `?${search.toString()}`;\n }\n\n return joinPaths(base, path);\n}\n\n// ─── Location helpers (formerly in resolve.ts) ────────────────────────────────\n\nexport function stripBase(pathname: string, base = '/'): string {\n const normalizedPath = normalizePath(pathname);\n const normalizedBase = normalizePath(base);\n\n if (normalizedBase === '/') return normalizedPath;\n\n if (normalizedPath === normalizedBase) return '/';\n\n const prefix = `${normalizedBase}/`;\n\n return normalizedPath.startsWith(prefix)\n ? normalizePath(normalizedPath.slice(normalizedBase.length))\n : normalizedPath;\n}\n"],"mappings":"A,gCAIA,SAAgB,cAAc,EAAsB,CAClD,IAAMG,EAAa,IAAIC,IAAO,QAAQ,OAAQ,GAAG,EAEjD,OAAOD,IAAe,KAAOA,EAAW,SAAS,GAAG,EAAIA,EAAW,MAAM,EAAG,EAAE,EAAIA,CACpF,CAEA,SAAgB,UAAU,EAAc,EAAsB,CAC5D,OAAO,cAAc,GAAGE,EAAK,GAAGD,GAAM,CACxC,CAEA,SAAS,YAAY,EAAuB,CAC1C,OAAOE,EAAM,QAAQ,sBAAuB,MAAM,CACpD,CAEA,SAAgB,mBAAmB,EAA4B,CAC7D,IAAMH,EAAa,cAAcC,CAAI,EAErC,GAAID,IAAe,IACjB,MAAO,CACL,WAAY,CAAC,EACb,QAAS,OACT,cAAe,MACjB,EAGF,IAAMI,EAAuB,CAAC,EACxBC,EAAWL,EAAW,MAAM,CAAC,CAAC,CAAC,MAAM,GAAG,EACxCM,EAAuB,CAAC,GAAG,EAC3BC,EAAwB,CAAC,GAAG,EAElC,IAAK,IAAIC,EAAI,EAAGA,EAAIH,EAAS,OAAQ,GAAK,EAAG,CAC3C,IAAMI,EAAUJ,EAASG,GAEzB,GAAIC,IAAY,IAAK,CACnB,GAAID,IAAMH,EAAS,OAAS,EAC1B,MAAM,IAAIR,EAAAA,qBAAqB,mDAAmDI,GAAM,EAG1FK,EAAW,KAAK,UAAU,EAC1B,KACF,CAEA,GAAIG,EAAQ,WAAW,GAAG,GAAKA,EAAQ,SAAS,G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O,KAAKA,CAAK,CAAC,CAAC,OAAQ,CACtC,IAAMP,EAAS,IAAI,gBAEnB,OAAO,QAAQO,CAAK,CAAC,CAAC,SAAS,CAACJ,EAAKN,KAAW,CAC1C,MAAM,QAAQA,CAAK,EACrBA,EAAM,QAAS,GAAS,CACtBG,EAAO,OAAOG,EAAK,OAAOK,CAAI,CAAC,CACjC,CAAC,EACER,EAAO,IAAIG,EAAK,OAAON,CAAK,CAAC,CACpC,CAAC,EAED,GAAQ,IAAIG,EAAO,SAAS,GAC9B,CAEA,OAAO,UAAUjB,EAAMD,CAAI,CAC7B,CAIA,SAAgB,UAAU,EAAkB,EAAO,IAAa,CAC9D,IAAM2B,EAAiB,cAAcd,CAAQ,EACvCe,EAAiB,cAAc3B,CAAI,EAEzC,GAAI2B,IAAmB,IAAK,OAAOD,EAEnC,GAAIA,IAAmBC,EAAgB,MAAO,IAE9C,IAAMC,EAAS,GAAGD,EAAe,GAEjC,OAAOD,EAAe,WAAWE,CAAM,EACnC,cAAcF,EAAe,MAAMC,EAAe,MAAM,CAAC,EACzDD,CACN,C"}
|
package/dist/path.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { QueryParams, ResolvedQueryParams,
|
|
1
|
+
import type { QueryParams, ResolvedQueryParams, RouteMatcher, RouteParams, RouteRecord } from './types';
|
|
2
2
|
/** Ensure leading slash, collapse duplicate slashes, preserve root. */
|
|
3
3
|
export declare function normalizePath(path: string): string;
|
|
4
4
|
export declare function joinPaths(base: string, path: string): string;
|
|
@@ -22,12 +22,4 @@ export declare function parseQuery(queryString: string): QueryParams;
|
|
|
22
22
|
/** Build a URL from a path pattern, params, and query, respecting the router base. */
|
|
23
23
|
export declare function buildUrl(base: string, pattern: string, params?: RouteParams, query?: ResolvedQueryParams): string;
|
|
24
24
|
export declare function stripBase(pathname: string, base?: string): string;
|
|
25
|
-
export declare function readLocation(base: string, history: {
|
|
26
|
-
location: {
|
|
27
|
-
hash: string;
|
|
28
|
-
pathname: string;
|
|
29
|
-
search: string;
|
|
30
|
-
state: unknown;
|
|
31
|
-
};
|
|
32
|
-
}): RouteLocation;
|
|
33
25
|
//# sourceMappingURL=path.d.ts.map
|
package/dist/path.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"path.d.ts","sourceRoot":"","sources":["../src/path.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,mBAAmB,EAAE,
|
|
1
|
+
{"version":3,"file":"path.d.ts","sourceRoot":"","sources":["../src/path.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,mBAAmB,EAAE,YAAY,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAExG,uEAAuE;AACvE,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAIlD;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAE5D;AAMD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY,CA4E7D;AAED,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,WAAW,GAAG,IAAI,CAkBrF;AAED,wBAAgB,aAAa,CAC3B,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,SAAS,WAAW,EAAE,GAC9B;IAAE,MAAM,EAAE,WAAW,CAAC;IAAC,MAAM,CAAC,EAAE,WAAW,CAAA;CAAE,CAQ/C;AAED,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAE5E;AAED;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CAAC,WAAW,EAAE,MAAM,GAAG,WAAW,CAyB3D;AAED,sFAAsF;AACtF,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,GAAE,WAAgB,EAAE,KAAK,CAAC,EAAE,mBAAmB,GAAG,MAAM,CA+BrH;AAID,wBAAgB,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,SAAM,GAAG,MAAM,CAa9D"}
|
package/dist/path.js
CHANGED
|
@@ -111,14 +111,6 @@ function stripBase(e, t = "/") {
|
|
|
111
111
|
let i = `${r}/`;
|
|
112
112
|
return n.startsWith(i) ? normalizePath(n.slice(r.length)) : n;
|
|
113
113
|
}
|
|
114
|
-
|
|
115
|
-
return {
|
|
116
|
-
hash: t.location.hash.replace(/^#/, ""),
|
|
117
|
-
historyState: t.location.state,
|
|
118
|
-
pathname: stripBase(t.location.pathname || "/", e),
|
|
119
|
-
query: parseQuery(t.location.search || "")
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
export { buildUrl, compilePathMatcher, joinPaths, matchRecord, matchRouteFor, matchesPrefix, normalizePath, parseQuery, readLocation, stripBase };
|
|
114
|
+
export { buildUrl, compilePathMatcher, joinPaths, matchRecord, matchRouteFor, matchesPrefix, normalizePath, parseQuery, stripBase };
|
|
123
115
|
|
|
124
116
|
//# sourceMappingURL=path.js.map
|
package/dist/path.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"path.js","names":["normalized","path","base","input","paramNames","segments","regexParts","prefixParts","i","segment","WayfinderConfigError","name","escaped","match","record","pathname","params","value","index","records","search","queryString","out","key","existing","pattern","WayfinderRouteError","isWildcard","query","item","normalizedPath","normalizedBase","prefix","history"],"sources":["../src/path.ts"],"sourcesContent":["import { WayfinderConfigError, WayfinderRouteError } from './errors';\nimport type { QueryParams, ResolvedQueryParams, RouteLocation, RouteMatcher, RouteParams, RouteRecord } from './types';\n\n/** Ensure leading slash, collapse duplicate slashes, preserve root. */\nexport function normalizePath(path: string): string {\n const normalized = `/${path}`.replace(/\\/+/g, '/');\n\n return normalized !== '/' && normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;\n}\n\nexport function joinPaths(base: string, path: string): string {\n return normalizePath(`${base}/${path}`);\n}\n\nfunction escapeRegex(input: string): string {\n return input.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nexport function compilePathMatcher(path: string): RouteMatcher {\n const normalized = normalizePath(path);\n\n if (normalized === '/') {\n return {\n paramNames: [],\n pattern: /^\\/$/,\n prefixPattern: /^\\/$/,\n };\n }\n\n const paramNames: string[] = [];\n const segments = normalized.slice(1).split('/');\n const regexParts: string[] = ['^'];\n const prefixParts: string[] = ['^'];\n\n for (let i = 0; i < segments.length; i += 1) {\n const segment = segments[i]!;\n\n if (segment === '*') {\n if (i !== segments.length - 1) {\n throw new WayfinderConfigError(`Wildcard \"*\" must be the final segment in path: ${path}`);\n }\n\n regexParts.push('(?:/.*)?');\n break;\n }\n\n if (segment.startsWith(':') && segment.endsWith('*')) {\n if (i !== segments.length - 1) {\n throw new WayfinderConfigError(`Wildcard param must be final segment in path: ${path}`);\n }\n\n const name = segment.slice(1, -1);\n\n if (!/^\\w+$/.test(name)) {\n throw new WayfinderConfigError(\n `Invalid param name \":${name}\" in path \"${path}\". Param names must only contain word characters (a–z, A–Z, 0–9, _).`,\n );\n }\n\n paramNames.push(name);\n regexParts.push(i === segments.length - 1 ? '(?:/(.*))?' : '/(.*)');\n prefixParts.push('/.*');\n break;\n }\n\n if (segment.startsWith(':')) {\n const name = segment.slice(1);\n\n if (!/^\\w+$/.test(name)) {\n throw new WayfinderConfigError(\n `Invalid param name \":${name}\" in path \"${path}\". Param names must only contain word characters (a–z, A–Z, 0–9, _).`,\n );\n }\n\n paramNames.push(name);\n regexParts.push('/([^/]+)');\n prefixParts.push('/[^/]+');\n continue;\n }\n\n const escaped = escapeRegex(segment);\n\n regexParts.push(`/${escaped}`);\n prefixParts.push(`/${escaped}`);\n }\n\n regexParts.push('$');\n prefixParts.push('(?:/.*)?$');\n\n return {\n paramNames,\n pattern: new RegExp(regexParts.join('')),\n prefixPattern: new RegExp(prefixParts.join('')),\n };\n}\n\nexport function matchRecord(pathname: string, record: RouteRecord): RouteParams | null {\n const match = record.matcher.pattern.exec(pathname);\n\n if (!match) return null;\n\n const params: RouteParams = {};\n\n record.matcher.paramNames.forEach((name: string, index: number) => {\n const value = match[index + 1] ?? '';\n\n try {\n params[name] = decodeURIComponent(value);\n } catch {\n params[name] = value;\n }\n });\n\n return params;\n}\n\nexport function matchRouteFor(\n pathname: string,\n records: readonly RouteRecord[],\n): { params: RouteParams; record?: RouteRecord } {\n for (const record of records) {\n const params = matchRecord(pathname, record);\n\n if (params) return { params, record };\n }\n\n return { params: {} };\n}\n\nexport function matchesPrefix(pathname: string, record: RouteRecord): boolean {\n return record.matcher.prefixPattern.test(pathname);\n}\n\n/**\n * Parse `?foo=a&foo=b&bar=c` into `{ foo: ['a', 'b'], bar: 'c' }`.\n *\n * @security Query keys come directly from the (attacker-controlled) URL. Plain bracket\n * assignment (`out[key] = value`) would let a key like `__proto__` reach the inherited\n * `Object.prototype.__proto__` setter and silently rewrite `out`'s own prototype instead of\n * storing a value: `setQueryValue` uses `Object.defineProperty` so every key, including\n * `__proto__`/`constructor`/`prototype`, is always stored as a plain own data property.\n */\nexport function parseQuery(queryString: string): QueryParams {\n const search = new URLSearchParams(queryString);\n const out: QueryParams = {};\n\n const setQueryValue = (key: string, value: QueryParams[string]): void => {\n Object.defineProperty(out, key, { configurable: true, enumerable: true, value, writable: true });\n };\n\n for (const [key, value] of search.entries()) {\n const existing = Object.hasOwn(out, key) ? out[key] : undefined;\n\n if (existing === undefined) {\n setQueryValue(key, value);\n continue;\n }\n\n if (Array.isArray(existing)) {\n existing.push(value);\n continue;\n }\n\n setQueryValue(key, [existing, value]);\n }\n\n return out;\n}\n\n/** Build a URL from a path pattern, params, and query, respecting the router base. */\nexport function buildUrl(base: string, pattern: string, params: RouteParams = {}, query?: ResolvedQueryParams): string {\n let path = pattern.replace(/:(\\w+)(\\*)?/g, (_match, key: string, isWildcard: string) => {\n const value = params[key];\n\n if (value == null) throw new WayfinderRouteError(`Missing path param: ${key}`);\n\n if (isWildcard) {\n return value\n .split('/')\n .map((segment) => encodeURIComponent(segment))\n .join('/');\n }\n\n return encodeURIComponent(value);\n });\n\n if (query && Object.keys(query).length) {\n const search = new URLSearchParams();\n\n Object.entries(query).forEach(([key, value]) => {\n if (Array.isArray(value))\n value.forEach((item) => {\n search.append(key, String(item));\n });\n else search.set(key, String(value));\n });\n\n path += `?${search.toString()}`;\n }\n\n return joinPaths(base, path);\n}\n\n// ─── Location helpers (formerly in resolve.ts) ────────────────────────────────\n\nexport function stripBase(pathname: string, base = '/'): string {\n const normalizedPath = normalizePath(pathname);\n const normalizedBase = normalizePath(base);\n\n if (normalizedBase === '/') return normalizedPath;\n\n if (normalizedPath === normalizedBase) return '/';\n\n const prefix = `${normalizedBase}/`;\n\n return normalizedPath.startsWith(prefix)\n ? normalizePath(normalizedPath.slice(normalizedBase.length))\n : normalizedPath;\n}\n\nexport function readLocation(\n base: string,\n history: { location: { hash: string; pathname: string; search: string; state: unknown } },\n): RouteLocation {\n return {\n hash: history.location.hash.replace(/^#/, ''),\n historyState: history.location.state,\n pathname: stripBase(history.location.pathname || '/', base),\n query: parseQuery(history.location.search || ''),\n };\n}\n"],"mappings":";;AAIA,SAAgB,cAAc,GAAsB;CAClD,IAAMA,IAAa,IAAIC,IAAO,QAAQ,QAAQ,GAAG;CAEjD,OAAOD,MAAe,OAAOA,EAAW,SAAS,GAAG,IAAIA,EAAW,MAAM,GAAG,EAAE,IAAIA;AACpF;AAEA,SAAgB,UAAU,GAAc,GAAsB;CAC5D,OAAO,cAAc,GAAGE,EAAK,GAAGD,GAAM;AACxC;AAEA,SAAS,YAAY,GAAuB;CAC1C,OAAOE,EAAM,QAAQ,uBAAuB,MAAM;AACpD;AAEA,SAAgB,mBAAmB,GAA4B;CAC7D,IAAMH,IAAa,cAAcC,CAAI;CAErC,IAAID,MAAe,KACjB,OAAO;EACL,YAAY,CAAC;EACb,SAAS;EACT,eAAe;CACjB;CA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AAQ,SAAS,YAAY,KAAK/B,CAAI;EAC1D,OAAO,WAAW+B,EAAQ,SAAS,UAAU,EAAE;CACjD;AACF"}
|
|
1
|
+
{"version":3,"file":"path.js","names":["normalized","path","base","input","paramNames","segments","regexParts","prefixParts","i","segment","WayfinderConfigError","name","escaped","match","record","pathname","params","value","index","records","search","queryString","out","key","existing","pattern","WayfinderRouteError","isWildcard","query","item","normalizedPath","normalizedBase","prefix"],"sources":["../src/path.ts"],"sourcesContent":["import { WayfinderConfigError, WayfinderRouteError } from './errors';\nimport type { QueryParams, ResolvedQueryParams, RouteMatcher, RouteParams, RouteRecord } from './types';\n\n/** Ensure leading slash, collapse duplicate slashes, preserve root. */\nexport function normalizePath(path: string): string {\n const normalized = `/${path}`.replace(/\\/+/g, '/');\n\n return normalized !== '/' && normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;\n}\n\nexport function joinPaths(base: string, path: string): string {\n return normalizePath(`${base}/${path}`);\n}\n\nfunction escapeRegex(input: string): string {\n return input.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nexport function compilePathMatcher(path: string): RouteMatcher {\n const normalized = normalizePath(path);\n\n if (normalized === '/') {\n return {\n paramNames: [],\n pattern: /^\\/$/,\n prefixPattern: /^\\/$/,\n };\n }\n\n const paramNames: string[] = [];\n const segments = normalized.slice(1).split('/');\n const regexParts: string[] = ['^'];\n const prefixParts: string[] = ['^'];\n\n for (let i = 0; i < segments.length; i += 1) {\n const segment = segments[i]!;\n\n if (segment === '*') {\n if (i !== segments.length - 1) {\n throw new WayfinderConfigError(`Wildcard \"*\" must be the final segment in path: ${path}`);\n }\n\n regexParts.push('(?:/.*)?');\n break;\n }\n\n if (segment.startsWith(':') && segment.endsWith('*')) {\n if (i !== segments.length - 1) {\n throw new WayfinderConfigError(`Wildcard param must be final segment in path: ${path}`);\n }\n\n const name = segment.slice(1, -1);\n\n if (!/^\\w+$/.test(name)) {\n throw new WayfinderConfigError(\n `Invalid param name \":${name}\" in path \"${path}\". Param names must only contain word characters (a–z, A–Z, 0–9, _).`,\n );\n }\n\n paramNames.push(name);\n regexParts.push(i === segments.length - 1 ? '(?:/(.*))?' : '/(.*)');\n prefixParts.push('/.*');\n break;\n }\n\n if (segment.startsWith(':')) {\n const name = segment.slice(1);\n\n if (!/^\\w+$/.test(name)) {\n throw new WayfinderConfigError(\n `Invalid param name \":${name}\" in path \"${path}\". Param names must only contain word characters (a–z, A–Z, 0–9, _).`,\n );\n }\n\n paramNames.push(name);\n regexParts.push('/([^/]+)');\n prefixParts.push('/[^/]+');\n continue;\n }\n\n const escaped = escapeRegex(segment);\n\n regexParts.push(`/${escaped}`);\n prefixParts.push(`/${escaped}`);\n }\n\n regexParts.push('$');\n prefixParts.push('(?:/.*)?$');\n\n return {\n paramNames,\n pattern: new RegExp(regexParts.join('')),\n prefixPattern: new RegExp(prefixParts.join('')),\n };\n}\n\nexport function matchRecord(pathname: string, record: RouteRecord): RouteParams | null {\n const match = record.matcher.pattern.exec(pathname);\n\n if (!match) return null;\n\n const params: RouteParams = {};\n\n record.matcher.paramNames.forEach((name: string, index: number) => {\n const value = match[index + 1] ?? '';\n\n try {\n params[name] = decodeURIComponent(value);\n } catch {\n params[name] = value;\n }\n });\n\n return params;\n}\n\nexport function matchRouteFor(\n pathname: string,\n records: readonly RouteRecord[],\n): { params: RouteParams; record?: RouteRecord } {\n for (const record of records) {\n const params = matchRecord(pathname, record);\n\n if (params) return { params, record };\n }\n\n return { params: {} };\n}\n\nexport function matchesPrefix(pathname: string, record: RouteRecord): boolean {\n return record.matcher.prefixPattern.test(pathname);\n}\n\n/**\n * Parse `?foo=a&foo=b&bar=c` into `{ foo: ['a', 'b'], bar: 'c' }`.\n *\n * @security Query keys come directly from the (attacker-controlled) URL. Plain bracket\n * assignment (`out[key] = value`) would let a key like `__proto__` reach the inherited\n * `Object.prototype.__proto__` setter and silently rewrite `out`'s own prototype instead of\n * storing a value: `setQueryValue` uses `Object.defineProperty` so every key, including\n * `__proto__`/`constructor`/`prototype`, is always stored as a plain own data property.\n */\nexport function parseQuery(queryString: string): QueryParams {\n const search = new URLSearchParams(queryString);\n const out: QueryParams = {};\n\n const setQueryValue = (key: string, value: QueryParams[string]): void => {\n Object.defineProperty(out, key, { configurable: true, enumerable: true, value, writable: true });\n };\n\n for (const [key, value] of search.entries()) {\n const existing = Object.hasOwn(out, key) ? out[key] : undefined;\n\n if (existing === undefined) {\n setQueryValue(key, value);\n continue;\n }\n\n if (Array.isArray(existing)) {\n existing.push(value);\n continue;\n }\n\n setQueryValue(key, [existing, value]);\n }\n\n return out;\n}\n\n/** Build a URL from a path pattern, params, and query, respecting the router base. */\nexport function buildUrl(base: string, pattern: string, params: RouteParams = {}, query?: ResolvedQueryParams): string {\n let path = pattern.replace(/:(\\w+)(\\*)?/g, (_match, key: string, isWildcard: string) => {\n const value = params[key];\n\n if (value == null) throw new WayfinderRouteError(`Missing path param: ${key}`);\n\n if (isWildcard) {\n return value\n .split('/')\n .map((segment) => encodeURIComponent(segment))\n .join('/');\n }\n\n return encodeURIComponent(value);\n });\n\n if (query && Object.keys(query).length) {\n const search = new URLSearchParams();\n\n Object.entries(query).forEach(([key, value]) => {\n if (Array.isArray(value))\n value.forEach((item) => {\n search.append(key, String(item));\n });\n else search.set(key, String(value));\n });\n\n path += `?${search.toString()}`;\n }\n\n return joinPaths(base, path);\n}\n\n// ─── Location helpers (formerly in resolve.ts) ────────────────────────────────\n\nexport function stripBase(pathname: string, base = '/'): string {\n const normalizedPath = normalizePath(pathname);\n const normalizedBase = normalizePath(base);\n\n if (normalizedBase === '/') return normalizedPath;\n\n if (normalizedPath === normalizedBase) return '/';\n\n const prefix = `${normalizedBase}/`;\n\n return normalizedPath.startsWith(prefix)\n ? normalizePath(normalizedPath.slice(normalizedBase.length))\n : normalizedPath;\n}\n"],"mappings":";;AAIA,SAAgB,cAAc,GAAsB;CAClD,IAAMA,IAAa,IAAIC,IAAO,QAAQ,QAAQ,GAAG;CAEjD,OAAOD,M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CAAQ,GACvCgB,IAAiB,cAAc7B,CAAI;CAEzC,IAAI6B,MAAmB,KAAK,OAAOD;CAEnC,IAAIA,MAAmBC,GAAgB,OAAO;CAE9C,IAAMC,IAAS,GAAGD,EAAe;CAEjC,OAAOD,EAAe,WAAWE,CAAM,IACnC,cAAcF,EAAe,MAAMC,EAAe,MAAM,CAAC,IACzDD;AACN"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./errors.cjs"),t=require("./route-signals.cjs");let n=require("@vielzeug/ripple");var r=Object.freeze([]),first=e=>Array.isArray(e)?e[0]:e,i=Object.freeze({boolean(e=!1){return{decode:t=>{let n=first(t);return n===`1`||n===`true`?!0:n===`0`||n===`false`?!1:e},default:e,encode:t=>t===e?void 0:t?`1`:`0`}},list(){return{decode:e=>e===void 0?r:Array.isArray(e)?[...e]:[e],default:r,encode:e=>e.length===0?void 0:e.length===1?e[0]:[...e]}},number(e=0){return{decode:t=>{let n=first(t);if(n===void 0||n===``)return e;let r=Number(n);return Number.isFinite(r)?r:e},default:e,encode:t=>t===e||!Number.isFinite(t)?void 0:String(t)}},pick:((e,t)=>({decode:n=>{let r=first(n);return r!==void 0&&e.includes(r)?r:t},default:t,encode:e=>e===void 0||e===t?void 0:e})),string(e=``){return{decode:t=>first(t)??e,default:e,encode:t=>t===e?void 0:t}}});function createQueryState(r,i,a={}){let o=t.createRouteSignals(r),s=Object.keys(i),c={};for(let e of s){let t=i[e];c[e]=(0,n.computed)(()=>t.decode(o.query.value[e]))}let readAll=()=>{let e={};for(let t of s)e[t]=c[t]?.value;return e},write=(t,n)=>{for(let n of Object.keys(t))if(!Object.hasOwn(i,n))throw new e.WayfinderConfigError(`createQueryState: undeclared param "${n}"`);let o=r.getSnapshot().location,s={...o.query};for(let[e,n]of Object.entries(t)){let t=i[e].encode(n);t===void 0?delete s[e]:s[e]=t}let c=new URLSearchParams;for(let[e,t]of Object.entries(s))if(Array.isArray(t))for(let n of t)c.append(e,n);else c.set(e,t);let l=c.toString(),u=`${o.pathname}${l===``?``:`?${l}`}${o.hash===``?``:`#${o.hash}`}`,d={replace:!0};for(let e of[a,n])for(let[t,n]of Object.entries(e??{}))n!==void 0&&(d[t]=n);r.navigate(u,d).catch(()=>{})};return{params:c,query:(0,n.computed)(readAll),reset:e=>{let t={};for(let e of s)t[e]=i[e].default;write(t,e)},set:(e,t)=>{write(e,t)}}}exports.createQueryState=createQueryState,exports.param=i;
|
|
2
|
+
//# sourceMappingURL=query-state.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query-state.cjs","names":["createRouteSignals","computed","WayfinderConfigError","require_errors","require_route_signals","_vielzeug_ripple","EMPTY_LIST","raw","param","value","defaultValue","parsed","values","routeSignals","router","keys","spec","params","key","definition","out","patch","location","next","search","item","query","href","navigation","source","options","opts","defaults"],"sources":["../src/query-state.ts"],"sourcesContent":["import { computed, type Readable } from '@vielzeug/ripple';\nimport { WayfinderConfigError } from './errors';\nimport { createRouteSignals } from './route-signals';\nimport type { Router } from './router';\nimport type { NavigateOptions, RouteTable } from './types';\n\n/** Encode result: a raw query value, or `undefined` to omit the parameter from the URL. */\nexport type RawParamValue = string | string[] | undefined;\n\n/** One URL query parameter: a default that equals \"absent\", plus lenient decode/encode. */\nexport type ParamSpec<T> = {\n /** Missing or malformed input always decodes to `default` — the URL is untrusted. */\n decode(raw: string | string[] | undefined): T;\n /** Returning `undefined` (the value equals the default) removes the parameter. */\n encode(value: T): RawParamValue;\n readonly default: T;\n};\n\nconst EMPTY_LIST: readonly string[] = Object.freeze([]);\n\nconst first = (raw: string | string[] | undefined): string | undefined => (Array.isArray(raw) ? raw[0] : raw);\n\n/** The built-in parameter codecs; a codec's default is always the param-absent state. */\nexport interface PickParam {\n /** Without a default, absent or unknown values decode to `undefined` (and are omitted when written). */\n <const Values extends readonly string[]>(values: Values): ParamSpec<Values[number] | undefined>;\n /** Absent or unknown values decode to `defaultValue` (and are omitted when written). */\n <const Values extends readonly string[]>(values: Values, defaultValue: Values[number]): ParamSpec<Values[number]>;\n}\n\nexport const param = Object.freeze({\n boolean(defaultValue = false): ParamSpec<boolean> {\n return {\n decode: (raw) => {\n const value = first(raw);\n if (value === '1' || value === 'true') return true;\n if (value === '0' || value === 'false') return false;\n return defaultValue;\n },\n default: defaultValue,\n encode: (value) => (value === defaultValue ? undefined : value ? '1' : '0'),\n };\n },\n list(): ParamSpec<readonly string[]> {\n return {\n decode: (raw) => (raw === undefined ? EMPTY_LIST : Array.isArray(raw) ? [...raw] : [raw]),\n default: EMPTY_LIST,\n encode: (value) => (value.length === 0 ? undefined : value.length === 1 ? value[0] : [...value]),\n };\n },\n number(defaultValue = 0): ParamSpec<number> {\n return {\n decode: (raw) => {\n const value = first(raw);\n if (value === undefined || value === '') return defaultValue;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : defaultValue;\n },\n default: defaultValue,\n encode: (value) => (value === defaultValue || !Number.isFinite(value) ? undefined : String(value)),\n };\n },\n pick: ((values: readonly string[], defaultValue?: string) => ({\n decode: (raw: string | string[] | undefined) => {\n const value = first(raw);\n return value !== undefined && values.includes(value) ? value : defaultValue;\n },\n default: defaultValue,\n encode: (value: string | undefined) => (value === undefined || value === defaultValue ? undefined : value),\n })) as PickParam,\n string(defaultValue = ''): ParamSpec<string> {\n return {\n decode: (raw) => first(raw) ?? defaultValue,\n default: defaultValue,\n encode: (value) => (value === defaultValue ? undefined : value),\n };\n },\n});\n\nexport type QueryStateSpec = { readonly [key: string]: ParamSpec<unknown> };\n\ntype SpecValue<S extends QueryStateSpec> = { [K in keyof S]: S[K] extends ParamSpec<infer T> ? T : never };\n\nexport type QueryStateOptions = NavigateOptions;\n\n/** Per-write overrides of the state-level navigation options. */\nexport type QueryStateSetOptions = NavigateOptions;\n\n/**\n * Navigation options accepted by a write: the router's own `NavigateOptions`, with\n * `replace` defaulted to `true` because a query-parameter edit is a revision of the\n * current view, not a new page. Any other option (`viewTransition`, `force`, `state`)\n * is forwarded untouched, so a page whose router animates route changes can still\n * suppress the transition for a filter edit.\n */\n\nexport type QueryState<S extends QueryStateSpec> = {\n /** Reactive value per declared parameter. */\n readonly params: { readonly [K in keyof S]: Readable<S[K] extends ParamSpec<infer T> ? T : never> };\n /** Reactive snapshot of every declared parameter at once. */\n readonly query: Readable<SpecValue<S>>;\n /** Declared parameters removed from the URL (their defaults restored) in one navigation. */\n reset(options?: QueryStateSetOptions): void;\n /** Typed partial update of declared parameters; unknown keys throw. One navigation per call. */\n set(patch: Partial<SpecValue<S>>, options?: QueryStateSetOptions): void;\n};\n\n/**\n * Reactive, typed bindings between ripple state and the URL query string.\n *\n * Reads are derived from the router's live location, so back/forward and external\n * `navigate()` calls update them automatically. Writes merge into the *current* query —\n * undeclared parameters, the path, and the hash survive untouched — and land as a single\n * (replace by default) navigation through the router, so history mode, base path,\n * middleware, and guards keep working. A parameter written back to its default is removed\n * from the URL. Decoding is lenient: a malformed URL value falls back to the default\n * instead of throwing, because query strings are untrusted input.\n *\n * ```ts\n * const filters = createQueryState(router, {\n * page: param.number(1),\n * sort: param.pick(['price', 'name'] as const, 'price'),\n * tags: param.list(),\n * });\n *\n * filters.page.value; // reactive number, `1` when ?page is absent\n * filters.set({ page: 2 }); // ?page=2, replace, other params preserved\n * ```\n */\nexport function createQueryState<S extends QueryStateSpec, TRoutes extends RouteTable>(\n router: Router<TRoutes>,\n spec: S,\n options: QueryStateOptions = {},\n): QueryState<S> {\n const routeSignals = createRouteSignals(router);\n const keys = Object.keys(spec);\n\n const params: Record<string, Readable<unknown>> = {};\n for (const key of keys) {\n const definition = spec[key] as ParamSpec<unknown>;\n params[key] = computed(() => definition.decode(routeSignals.query.value[key]));\n }\n\n const readAll = (): SpecValue<S> => {\n const out: Record<string, unknown> = {};\n for (const key of keys) out[key] = params[key]?.value;\n return out as SpecValue<S>;\n };\n\n const write = (patch: Partial<SpecValue<S>>, opts: QueryStateSetOptions | undefined): void => {\n for (const key of Object.keys(patch)) {\n if (!Object.hasOwn(spec, key)) throw new WayfinderConfigError(`createQueryState: undeclared param \"${key}\"`);\n }\n const location = router.getSnapshot().location;\n const next: Record<string, string | string[]> = { ...location.query };\n for (const [key, value] of Object.entries(patch)) {\n const raw = (spec[key] as ParamSpec<unknown>).encode(value);\n if (raw === undefined) delete next[key];\n else next[key] = raw;\n }\n\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(next)) {\n if (Array.isArray(value)) for (const item of value) search.append(key, item);\n else search.set(key, value);\n }\n const query = search.toString();\n const href = `${location.pathname}${query === '' ? '' : `?${query}`}${location.hash === '' ? '' : `#${location.hash}`}`;\n\n // Fire-and-forget for UI handlers: loader failures still surface through the router's\n // onError/status channels, so the floating promise is deliberately swallowed here.\n const navigation: NavigateOptions = { replace: true };\n for (const source of [options, opts]) {\n for (const [key, value] of Object.entries(source ?? {})) {\n if (value !== undefined) (navigation as Record<string, unknown>)[key] = value;\n }\n }\n\n router.navigate(href, navigation).catch(() => {});\n };\n\n return {\n params: params as unknown as QueryState<S>['params'],\n query: computed(readAll),\n reset: (opts) => {\n const defaults: Partial<SpecValue<S>> = {};\n for (const key of keys) (defaults as Record<string, unknown>)[key] = spec[key].default;\n write(defaults, opts);\n },\n set: (patch, opts) => {\n write(patch, opts);\n },\n };\n}\n"],"mappings":"A,mGAkBA,IAAMM,EAAgC,OAAO,OAAO,CAAC,CAAC,EAEhD,MAAS,GAA4D,MAAM,QAAQC,CAAG,EAAIA,EAAI,GAAKA,EAU5FC,EAAQ,OAAO,OAAO,CACjC,QAAQ,EAAe,GAA2B,CAChD,MAAO,CACL,OAAS,GAAQ,CACf,IAAMC,EAAQ,MAAMF,CAAG,EAGvB,OAFIE,IAAU,KAAOA,IAAU,OAAe,GAC1CA,IAAU,KAAOA,IAAU,QAAgB,GACxCC,CACT,EACA,QAASA,EACT,OAAS,GAAWD,IAAUC,EAAe,IAAA,GAAYD,EAAQ,IAAM,GACzE,CACF,EACA,MAAqC,CACnC,MAAO,CACL,OAAS,GAASF,IAAQ,IAA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,CAAS,OAAO,EACvB,MAAQ,GAAS,CACf,IAAM+B,EAAkC,CAAC,EACzC,IAAK,IAAMd,KAAOH,EAAM,EAAsCG,GAAOF,EAAKE,EAAI,CAAC,QAC/E,MAAMc,EAAUD,CAAI,CACtB,EACA,KAAM,EAAO,IAAS,CACpB,MAAMV,EAAOU,CAAI,CACnB,CACF,CACF,C"}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { type Readable } from '@vielzeug/ripple';
|
|
2
|
+
import type { Router } from './router';
|
|
3
|
+
import type { NavigateOptions, RouteTable } from './types';
|
|
4
|
+
/** Encode result: a raw query value, or `undefined` to omit the parameter from the URL. */
|
|
5
|
+
export type RawParamValue = string | string[] | undefined;
|
|
6
|
+
/** One URL query parameter: a default that equals "absent", plus lenient decode/encode. */
|
|
7
|
+
export type ParamSpec<T> = {
|
|
8
|
+
/** Missing or malformed input always decodes to `default` — the URL is untrusted. */
|
|
9
|
+
decode(raw: string | string[] | undefined): T;
|
|
10
|
+
/** Returning `undefined` (the value equals the default) removes the parameter. */
|
|
11
|
+
encode(value: T): RawParamValue;
|
|
12
|
+
readonly default: T;
|
|
13
|
+
};
|
|
14
|
+
/** The built-in parameter codecs; a codec's default is always the param-absent state. */
|
|
15
|
+
export interface PickParam {
|
|
16
|
+
/** Without a default, absent or unknown values decode to `undefined` (and are omitted when written). */
|
|
17
|
+
<const Values extends readonly string[]>(values: Values): ParamSpec<Values[number] | undefined>;
|
|
18
|
+
/** Absent or unknown values decode to `defaultValue` (and are omitted when written). */
|
|
19
|
+
<const Values extends readonly string[]>(values: Values, defaultValue: Values[number]): ParamSpec<Values[number]>;
|
|
20
|
+
}
|
|
21
|
+
export declare const param: Readonly<{
|
|
22
|
+
boolean(defaultValue?: boolean): ParamSpec<boolean>;
|
|
23
|
+
list(): ParamSpec<readonly string[]>;
|
|
24
|
+
number(defaultValue?: number): ParamSpec<number>;
|
|
25
|
+
pick: PickParam;
|
|
26
|
+
string(defaultValue?: string): ParamSpec<string>;
|
|
27
|
+
}>;
|
|
28
|
+
export type QueryStateSpec = {
|
|
29
|
+
readonly [key: string]: ParamSpec<unknown>;
|
|
30
|
+
};
|
|
31
|
+
type SpecValue<S extends QueryStateSpec> = {
|
|
32
|
+
[K in keyof S]: S[K] extends ParamSpec<infer T> ? T : never;
|
|
33
|
+
};
|
|
34
|
+
export type QueryStateOptions = NavigateOptions;
|
|
35
|
+
/** Per-write overrides of the state-level navigation options. */
|
|
36
|
+
export type QueryStateSetOptions = NavigateOptions;
|
|
37
|
+
/**
|
|
38
|
+
* Navigation options accepted by a write: the router's own `NavigateOptions`, with
|
|
39
|
+
* `replace` defaulted to `true` because a query-parameter edit is a revision of the
|
|
40
|
+
* current view, not a new page. Any other option (`viewTransition`, `force`, `state`)
|
|
41
|
+
* is forwarded untouched, so a page whose router animates route changes can still
|
|
42
|
+
* suppress the transition for a filter edit.
|
|
43
|
+
*/
|
|
44
|
+
export type QueryState<S extends QueryStateSpec> = {
|
|
45
|
+
/** Reactive value per declared parameter. */
|
|
46
|
+
readonly params: {
|
|
47
|
+
readonly [K in keyof S]: Readable<S[K] extends ParamSpec<infer T> ? T : never>;
|
|
48
|
+
};
|
|
49
|
+
/** Reactive snapshot of every declared parameter at once. */
|
|
50
|
+
readonly query: Readable<SpecValue<S>>;
|
|
51
|
+
/** Declared parameters removed from the URL (their defaults restored) in one navigation. */
|
|
52
|
+
reset(options?: QueryStateSetOptions): void;
|
|
53
|
+
/** Typed partial update of declared parameters; unknown keys throw. One navigation per call. */
|
|
54
|
+
set(patch: Partial<SpecValue<S>>, options?: QueryStateSetOptions): void;
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Reactive, typed bindings between ripple state and the URL query string.
|
|
58
|
+
*
|
|
59
|
+
* Reads are derived from the router's live location, so back/forward and external
|
|
60
|
+
* `navigate()` calls update them automatically. Writes merge into the *current* query —
|
|
61
|
+
* undeclared parameters, the path, and the hash survive untouched — and land as a single
|
|
62
|
+
* (replace by default) navigation through the router, so history mode, base path,
|
|
63
|
+
* middleware, and guards keep working. A parameter written back to its default is removed
|
|
64
|
+
* from the URL. Decoding is lenient: a malformed URL value falls back to the default
|
|
65
|
+
* instead of throwing, because query strings are untrusted input.
|
|
66
|
+
*
|
|
67
|
+
* ```ts
|
|
68
|
+
* const filters = createQueryState(router, {
|
|
69
|
+
* page: param.number(1),
|
|
70
|
+
* sort: param.pick(['price', 'name'] as const, 'price'),
|
|
71
|
+
* tags: param.list(),
|
|
72
|
+
* });
|
|
73
|
+
*
|
|
74
|
+
* filters.page.value; // reactive number, `1` when ?page is absent
|
|
75
|
+
* filters.set({ page: 2 }); // ?page=2, replace, other params preserved
|
|
76
|
+
* ```
|
|
77
|
+
*/
|
|
78
|
+
export declare function createQueryState<S extends QueryStateSpec, TRoutes extends RouteTable>(router: Router<TRoutes>, spec: S, options?: QueryStateOptions): QueryState<S>;
|
|
79
|
+
export {};
|
|
80
|
+
//# sourceMappingURL=query-state.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query-state.d.ts","sourceRoot":"","sources":["../src/query-state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,KAAK,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAG3D,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,KAAK,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAE3D,2FAA2F;AAC3F,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC;AAE1D,2FAA2F;AAC3F,MAAM,MAAM,SAAS,CAAC,CAAC,IAAI;IACzB,qFAAqF;IACrF,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,GAAG,CAAC,CAAC;IAC9C,kFAAkF;IAClF,MAAM,CAAC,KAAK,EAAE,CAAC,GAAG,aAAa,CAAC;IAChC,QAAQ,CAAC,OAAO,EA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,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;KAAE,CAAC;IACpG,6DAA6D;IAC7D,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IACvC,4FAA4F;IAC5F,KAAK,CAAC,OAAO,CAAC,EAAE,oBAAoB,GAAG,IAAI,CAAC;IAC5C,gGAAgG;IAChG,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,EAAE,oBAAoB,GAAG,IAAI,CAAC;CACzE,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,cAAc,EAAE,OAAO,SAAS,UAAU,EACnF,MAAM,EAAE,MAAM,CAAC,OAAO,CAAC,EACvB,IAAI,EAAE,CAAC,EACP,OAAO,GAAE,iBAAsB,GAC9B,UAAU,CAAC,CAAC,CAAC,CA4Df"}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { WayfinderConfigError as e } from "./errors.js";
|
|
2
|
+
import { createRouteSignals as t } from "./route-signals.js";
|
|
3
|
+
import { computed as n } from "@vielzeug/ripple";
|
|
4
|
+
// src/query-state.ts
|
|
5
|
+
var r = Object.freeze([]), first = (e) => Array.isArray(e) ? e[0] : e, i = Object.freeze({
|
|
6
|
+
boolean(e = !1) {
|
|
7
|
+
return {
|
|
8
|
+
decode: (t) => {
|
|
9
|
+
let n = first(t);
|
|
10
|
+
return n === "1" || n === "true" ? !0 : n === "0" || n === "false" ? !1 : e;
|
|
11
|
+
},
|
|
12
|
+
default: e,
|
|
13
|
+
encode: (t) => t === e ? void 0 : t ? "1" : "0"
|
|
14
|
+
};
|
|
15
|
+
},
|
|
16
|
+
list() {
|
|
17
|
+
return {
|
|
18
|
+
decode: (e) => e === void 0 ? r : Array.isArray(e) ? [...e] : [e],
|
|
19
|
+
default: r,
|
|
20
|
+
encode: (e) => e.length === 0 ? void 0 : e.length === 1 ? e[0] : [...e]
|
|
21
|
+
};
|
|
22
|
+
},
|
|
23
|
+
number(e = 0) {
|
|
24
|
+
return {
|
|
25
|
+
decode: (t) => {
|
|
26
|
+
let n = first(t);
|
|
27
|
+
if (n === void 0 || n === "") return e;
|
|
28
|
+
let r = Number(n);
|
|
29
|
+
return Number.isFinite(r) ? r : e;
|
|
30
|
+
},
|
|
31
|
+
default: e,
|
|
32
|
+
encode: (t) => t === e || !Number.isFinite(t) ? void 0 : String(t)
|
|
33
|
+
};
|
|
34
|
+
},
|
|
35
|
+
pick: ((e, t) => ({
|
|
36
|
+
decode: (n) => {
|
|
37
|
+
let r = first(n);
|
|
38
|
+
return r !== void 0 && e.includes(r) ? r : t;
|
|
39
|
+
},
|
|
40
|
+
default: t,
|
|
41
|
+
encode: (e) => e === void 0 || e === t ? void 0 : e
|
|
42
|
+
})),
|
|
43
|
+
string(e = "") {
|
|
44
|
+
return {
|
|
45
|
+
decode: (t) => first(t) ?? e,
|
|
46
|
+
default: e,
|
|
47
|
+
encode: (t) => t === e ? void 0 : t
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
function createQueryState(r, i, a = {}) {
|
|
52
|
+
let o = t(r), s = Object.keys(i), c = {};
|
|
53
|
+
for (let e of s) {
|
|
54
|
+
let t = i[e];
|
|
55
|
+
c[e] = n(() => t.decode(o.query.value[e]));
|
|
56
|
+
}
|
|
57
|
+
let readAll = () => {
|
|
58
|
+
let e = {};
|
|
59
|
+
for (let t of s) e[t] = c[t]?.value;
|
|
60
|
+
return e;
|
|
61
|
+
}, write = (t, n) => {
|
|
62
|
+
for (let n of Object.keys(t)) if (!Object.hasOwn(i, n)) throw new e(`createQueryState: undeclared param "${n}"`);
|
|
63
|
+
let o = r.getSnapshot().location, s = { ...o.query };
|
|
64
|
+
for (let [e, n] of Object.entries(t)) {
|
|
65
|
+
let t = i[e].encode(n);
|
|
66
|
+
t === void 0 ? delete s[e] : s[e] = t;
|
|
67
|
+
}
|
|
68
|
+
let c = new URLSearchParams();
|
|
69
|
+
for (let [e, t] of Object.entries(s)) if (Array.isArray(t)) for (let n of t) c.append(e, n);
|
|
70
|
+
else c.set(e, t);
|
|
71
|
+
let l = c.toString(), u = `${o.pathname}${l === "" ? "" : `?${l}`}${o.hash === "" ? "" : `#${o.hash}`}`, d = { replace: !0 };
|
|
72
|
+
for (let e of [a, n]) for (let [t, n] of Object.entries(e ?? {})) n !== void 0 && (d[t] = n);
|
|
73
|
+
r.navigate(u, d).catch(() => {});
|
|
74
|
+
};
|
|
75
|
+
return {
|
|
76
|
+
params: c,
|
|
77
|
+
query: n(readAll),
|
|
78
|
+
reset: (e) => {
|
|
79
|
+
let t = {};
|
|
80
|
+
for (let e of s) t[e] = i[e].default;
|
|
81
|
+
write(t, e);
|
|
82
|
+
},
|
|
83
|
+
set: (e, t) => {
|
|
84
|
+
write(e, t);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
export { createQueryState, i as param };
|
|
89
|
+
|
|
90
|
+
//# sourceMappingURL=query-state.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query-state.js","names":["EMPTY_LIST","raw","param","value","defaultValue","parsed","values","routeSignals","createRouteSignals","router","keys","spec","params","key","definition","computed","out","patch","WayfinderConfigError","location","next","search","item","query","href","navigation","source","options","opts","defaults"],"sources":["../src/query-state.ts"],"sourcesContent":["import { computed, type Readable } from '@vielzeug/ripple';\nimport { WayfinderConfigError } from './errors';\nimport { createRouteSignals } from './route-signals';\nimport type { Router } from './router';\nimport type { NavigateOptions, RouteTable } from './types';\n\n/** Encode result: a raw query value, or `undefined` to omit the parameter from the URL. */\nexport type RawParamValue = string | string[] | undefined;\n\n/** One URL query parameter: a default that equals \"absent\", plus lenient decode/encode. */\nexport type ParamSpec<T> = {\n /** Missing or malformed input always decodes to `default` — the URL is untrusted. */\n decode(raw: string | string[] | undefined): T;\n /** Returning `undefined` (the value equals the default) removes the parameter. */\n encode(value: T): RawParamValue;\n readonly default: T;\n};\n\nconst EMPTY_LIST: readonly string[] = Object.freeze([]);\n\nconst first = (raw: string | string[] | undefined): string | undefined => (Array.isArray(raw) ? raw[0] : raw);\n\n/** The built-in parameter codecs; a codec's default is always the param-absent state. */\nexport interface PickParam {\n /** Without a default, absent or unknown values decode to `undefined` (and are omitted when written). */\n <const Values extends readonly string[]>(values: Values): ParamSpec<Values[number] | undefined>;\n /** Absent or unknown values decode to `defaultValue` (and are omitted when written). */\n <const Values extends readonly string[]>(values: Values, defaultValue: Values[number]): ParamSpec<Values[number]>;\n}\n\nexport const param = Object.freeze({\n boolean(defaultValue = false): ParamSpec<boolean> {\n return {\n decode: (raw) => {\n const value = first(raw);\n if (value === '1' || value === 'true') return true;\n if (value === '0' || value === 'false') return false;\n return defaultValue;\n },\n default: defaultValue,\n encode: (value) => (value === defaultValue ? undefined : value ? '1' : '0'),\n };\n },\n list(): ParamSpec<readonly string[]> {\n return {\n decode: (raw) => (raw === undefined ? EMPTY_LIST : Array.isArray(raw) ? [...raw] : [raw]),\n default: EMPTY_LIST,\n encode: (value) => (value.length === 0 ? undefined : value.length === 1 ? value[0] : [...value]),\n };\n },\n number(defaultValue = 0): ParamSpec<number> {\n return {\n decode: (raw) => {\n const value = first(raw);\n if (value === undefined || value === '') return defaultValue;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : defaultValue;\n },\n default: defaultValue,\n encode: (value) => (value === defaultValue || !Number.isFinite(value) ? undefined : String(value)),\n };\n },\n pick: ((values: readonly string[], defaultValue?: string) => ({\n decode: (raw: string | string[] | undefined) => {\n const value = first(raw);\n return value !== undefined && values.includes(value) ? value : defaultValue;\n },\n default: defaultValue,\n encode: (value: string | undefined) => (value === undefined || value === defaultValue ? undefined : value),\n })) as PickParam,\n string(defaultValue = ''): ParamSpec<string> {\n return {\n decode: (raw) => first(raw) ?? defaultValue,\n default: defaultValue,\n encode: (value) => (value === defaultValue ? undefined : value),\n };\n },\n});\n\nexport type QueryStateSpec = { readonly [key: string]: ParamSpec<unknown> };\n\ntype SpecValue<S extends QueryStateSpec> = { [K in keyof S]: S[K] extends ParamSpec<infer T> ? T : never };\n\nexport type QueryStateOptions = NavigateOptions;\n\n/** Per-write overrides of the state-level navigation options. */\nexport type QueryStateSetOptions = NavigateOptions;\n\n/**\n * Navigation options accepted by a write: the router's own `NavigateOptions`, with\n * `replace` defaulted to `true` because a query-parameter edit is a revision of the\n * current view, not a new page. Any other option (`viewTransition`, `force`, `state`)\n * is forwarded untouched, so a page whose router animates route changes can still\n * suppress the transition for a filter edit.\n */\n\nexport type QueryState<S extends QueryStateSpec> = {\n /** Reactive value per declared parameter. */\n readonly params: { readonly [K in keyof S]: Readable<S[K] extends ParamSpec<infer T> ? T : never> };\n /** Reactive snapshot of every declared parameter at once. */\n readonly query: Readable<SpecValue<S>>;\n /** Declared parameters removed from the URL (their defaults restored) in one navigation. */\n reset(options?: QueryStateSetOptions): void;\n /** Typed partial update of declared parameters; unknown keys throw. One navigation per call. */\n set(patch: Partial<SpecValue<S>>, options?: QueryStateSetOptions): void;\n};\n\n/**\n * Reactive, typed bindings between ripple state and the URL query string.\n *\n * Reads are derived from the router's live location, so back/forward and external\n * `navigate()` calls update them automatically. Writes merge into the *current* query —\n * undeclared parameters, the path, and the hash survive untouched — and land as a single\n * (replace by default) navigation through the router, so history mode, base path,\n * middleware, and guards keep working. A parameter written back to its default is removed\n * from the URL. Decoding is lenient: a malformed URL value falls back to the default\n * instead of throwing, because query strings are untrusted input.\n *\n * ```ts\n * const filters = createQueryState(router, {\n * page: param.number(1),\n * sort: param.pick(['price', 'name'] as const, 'price'),\n * tags: param.list(),\n * });\n *\n * filters.page.value; // reactive number, `1` when ?page is absent\n * filters.set({ page: 2 }); // ?page=2, replace, other params preserved\n * ```\n */\nexport function createQueryState<S extends QueryStateSpec, TRoutes extends RouteTable>(\n router: Router<TRoutes>,\n spec: S,\n options: QueryStateOptions = {},\n): QueryState<S> {\n const routeSignals = createRouteSignals(router);\n const keys = Object.keys(spec);\n\n const params: Record<string, Readable<unknown>> = {};\n for (const key of keys) {\n const definition = spec[key] as ParamSpec<unknown>;\n params[key] = computed(() => definition.decode(routeSignals.query.value[key]));\n }\n\n const readAll = (): SpecValue<S> => {\n const out: Record<string, unknown> = {};\n for (const key of keys) out[key] = params[key]?.value;\n return out as SpecValue<S>;\n };\n\n const write = (patch: Partial<SpecValue<S>>, opts: QueryStateSetOptions | undefined): void => {\n for (const key of Object.keys(patch)) {\n if (!Object.hasOwn(spec, key)) throw new WayfinderConfigError(`createQueryState: undeclared param \"${key}\"`);\n }\n const location = router.getSnapshot().location;\n const next: Record<string, string | string[]> = { ...location.query };\n for (const [key, value] of Object.entries(patch)) {\n const raw = (spec[key] as ParamSpec<unknown>).encode(value);\n if (raw === undefined) delete next[key];\n else next[key] = raw;\n }\n\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(next)) {\n if (Array.isArray(value)) for (const item of value) search.append(key, item);\n else search.set(key, value);\n }\n const query = search.toString();\n const href = `${location.pathname}${query === '' ? '' : `?${query}`}${location.hash === '' ? '' : `#${location.hash}`}`;\n\n // Fire-and-forget for UI handlers: loader failures still surface through the router's\n // onError/status channels, so the floating promise is deliberately swallowed here.\n const navigation: NavigateOptions = { replace: true };\n for (const source of [options, opts]) {\n for (const [key, value] of Object.entries(source ?? {})) {\n if (value !== undefined) (navigation as Record<string, unknown>)[key] = value;\n }\n }\n\n router.navigate(href, navigation).catch(() => {});\n };\n\n return {\n params: params as unknown as QueryState<S>['params'],\n query: computed(readAll),\n reset: (opts) => {\n const defaults: Partial<SpecValue<S>> = {};\n for (const key of keys) (defaults as Record<string, unknown>)[key] = spec[key].default;\n write(defaults, opts);\n },\n set: (patch, opts) => {\n write(patch, opts);\n },\n };\n}\n"],"mappings":";;;;AAkBA,IAAMA,IAAgC,OAAO,OAAO,CAAC,CAAC,GAEhD,SAAS,MAA4D,MAAM,QAAQC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S,SAAS,KAAK,KAAK,IAAIA,EAAS,UAIzGM,IAA8B,EAAE,SAAS,GAAK;EACpD,KAAK,IAAMC,KAAU,CAACC,GAASC,CAAI,GACjC,KAAK,IAAM,CAACf,GAAKV,MAAU,OAAO,QAAQuB,KAAU,CAAC,CAAC,GACpD,AAAIvB,MAAU,KAAA,MAAW,EAAwCU,KAAOV;EAI5E,EAAO,SAASqB,GAAMC,CAAU,CAAC,CAAC,YAAY,CAAC,CAAC;CAClD;CAEA,OAAO;EACG;EACR,OAAOV,EAAS,OAAO;EACvB,QAAQ,MAAS;GACf,IAAMc,IAAkC,CAAC;GACzC,KAAK,IAAMhB,KAAOH,GAAM,EAAsCG,KAAOF,EAAKE,EAAI,CAAC;GAC/E,MAAMgB,GAAUD,CAAI;EACtB;EACA,MAAM,GAAO,MAAS;GACpB,MAAMX,GAAOW,CAAI;EACnB;CACF;AACF"}
|
package/dist/router.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./_navigation.cjs"),t=require("./compile.cjs"),n=require("./context.cjs"),r=require("./errors.cjs"),i=require("./guards.cjs"),a=require("./history.cjs"),o=require("./path.cjs");function getRouteByName(e,t){let n=t.get(e);if(n)return n;let i=[...t.keys()].join(`, `);throw new r.WayfinderRouteError(i?`Unknown route name: ${e}. Available routes: ${i}`:`Unknown route name: ${e}`)}function resolveTarget(e,t,n=`/`){if(`path`in e)return e.path;let r=getRouteByName(e.name,t),i=o.buildUrl(n,r.path,e.params,e.query);return e.hash?`${i}#${e.hash}`:i}var s=Symbol(`wayfinder.routerError`);function carryError(e,t){return{[s]:!0,context:t,error:e}}function isRouterErrorCarrier(e){return typeof e==`object`&&!!e&&s in e}function unwrapCarrier(e){throw isRouterErrorCarrier(e)?e.error:e}var Router=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l=new Set;#u=e.createNavigationCoordinator();#d;#f=!1;#p=new AbortController;#m=`/`;#h=new Set;#g=new Map;#_=new Map;#v;#y;ready;constructor(e){let r=t.compileRoutes(e);if(this.#e=o.normalizePath(e.base??`/`),this.#t=e.middleware??[],this.#n=e.coerceSearch,this.#r=e.history??a.createBrowserHistory(),this.#o=e.onError,this.#s=e.scroll,this.#c=e.viewTransition??!1,this.#i=r.records,this.#a=r.routesByName,this.#d=n.createRouteState({location:{hash:``,historyState:null,pathname:`/`,query:{}},matches:[],status:`idle`}),e.notFound){let t=e.notFound,n={dataFn:t.data,name:`__notFound__`};this.#v={branchDefs:[n],leaf:n,matcher:{paramNames:[],pattern:/(?:)/,prefixPattern:/(?:)/},ownMiddleware:t.middleware??[],path:`/*`}}else this.#v=null;this.#y=this.#x();let{hash:i,pathname:s,search:c}=this.#r.location;this.#m=`${s}${c}${i}`;let l=this.#u.begin(),u=this.#A(l,o.readLocation(this.#e,this.#r),(e,t)=>{if(!l.isCurrent())return;let n=this.#F(e);t&&this.#r.replace(n,e.historyState),this.#m=n},void 0,0,!1).then(()=>void 0);this.ready=u.catch(unwrapCarrier),this.ready.catch(()=>{}),this.#w(u,{source:`initial-navigation`}),this.beforeLeave=this.beforeLeave.bind(this),this.createViewRegistry=this.createViewRegistry.bind(this),this.dispose=this.dispose.bind(this),this.getSnapshot=this.getSnapshot.bind(this),this.isActive=this.isActive.bind(this),this.load=this.load.bind(this),this.match=this.match.bind(this),this.navigate=this.navigate.bind(this),this.preload=this.preload.bind(this),this.subscribe=this.subscribe.bind(this),this.url=this.url.bind(this),this.waitFor=this.waitFor.bind(this)}getSnapshot(){return this.#d}createViewRegistry(e,t){return{resolve:n=>{let r=n.matches.at(-1)?.name;return r===`__notFound__`?t?.notFound:r?e[r]:void 0}}}subscribe(e){return this.#b(),this.#h.add(e),()=>{this.#h.delete(e)}}navigate(e,t){let n=resolveTarget(typeof e==`string`?{path:e}:e,this.#a);return this.#L(n,t)}url(e,t,n){let r=getRouteByName(e,this.#a);return o.buildUrl(this.#e,r.path,t,n)}href(e,t,n){let r=getRouteByName(e,this.#a),i=o.buildUrl(this.#e,r.path,t,n);return this.#r.href?.(i)??i}isActive(e,t={}){let n=getRouteByName(e,this.#a),r=this.#d.location.pathname;return t.exact??!1?o.matchRouteFor(r,[n]).record!=null:o.matchesPrefix(r,n)}match(e){let t=o.stripBase(o.normalizePath(e),this.#e),{params:r,record:i}=o.matchRouteFor(t,this.#i);if(!i||i.redirect)return null;let a=n.buildMatchBranch(i.branchDefs,r,t,i.branchDefs.map(()=>void 0));return a.length?a:null}async load(e,t){let r=await this.#D(e);if(r.type!==`matched`)return null;let{location:i,params:a,record:o,resolvedQuery:s}=r,c=o.branchDefs,l=c.some(e=>e.dataFn!=null),u=c.map(()=>void 0),d,f=`idle`;if(l){let e=t?.signal??new AbortController().signal,r=n.buildMatchBranch(c,a,i.pathname,u),o=n.createRouteContext(i,s,a,r,()=>Promise.resolve());try{u=await this.#E(c,o,e)}catch(e){d=e,f=`error`}}return n.createRouteState({error:d,location:i,matches:n.buildMatchBranch(c,a,i.pathname,u),status:f})}async preload(e){this.#b();let t=this.#N(resolveTarget(e,this.#a,this.#e)),n=this.#_.get(t);if(n)return n;let r=this.load(t,{signal:this.#p.signal}).then(e=>{if(this.#f)throw this.#p.signal.reason;if(e?.status===`error`)throw e.error;if(e){let t=this.#F(e.location);this.#g.size>=20&&this.#g.delete(this.#g.keys().next().value),this.#g.set(t,e.matches.map(e=>e.data))}return e}).catch(e=>{throw this.#o&&this.#C(e,{source:`preload`}),e}).finally(()=>{this.#_.delete(t)});return this.#_.set(t,r),r}waitFor(e){return this.#b(),new Promise((t,n)=>{let matchesName=t=>t.status===`idle`&&t.matches.some(t=>t.name===e);if(this.#d.status===`error`){n(this.#d.error);return}if(matchesName(this.#d)){t(this.#d);return}let r=this.subscribe(e=>{matchesName(e)?(r(),t(e)):e.status===`error`&&(r(),n(e.error))});this.#p.signal.addEventListener(`abort`,()=>{r(),n(this.#p.signal.reason)},{once:!0})})}beforeLeave(e,t){this.#b();let n={handler:e,routes:t?.routes};return this.#l.add(n),()=>{this.#l.delete(n)}}get disposalSignal(){return this.#p.signal}get disposed(){return this.#f}dispose(){this.#f||(this.#f=!0,this.#l.clear(),this.#h.clear(),this.#g.clear(),this.#_.clear(),this.#u.invalidate(new r.WayfinderDisposedError),this.#y(),this.#p.abort(new r.WayfinderDisposedError))}[Symbol.dispose](){this.dispose()}#b(){if(this.#f)throw new r.WayfinderDisposedError}#x(){return this.#r.onPopstate(()=>{let{hash:e,pathname:t,search:n}=this.#r.location,r=`${t}${n}${e}`,i=this.#m;r!==i&&this.#w(this.#S(r,i),{source:`history-listener`})})}async#S(e,t){let n=this.#u.begin(),r=this.#d.matches.map(e=>e.name),a=this.#I(e),s=await i.runLeaveBlockers(this.#l,r,a);if(!n.isCurrent())return;if(!s){this.#r.replace(t,this.#d.location.historyState);return}let c=await this.#A(n,o.readLocation(this.#e,this.#r),(e,t)=>{if(!n.isCurrent())return;let r=this.#F(e);t&&this.#r.replace(r,e.historyState),this.#m=r},void 0,0,!1);n.isCurrent()&&!c&&this.#r.replace(t,this.#d.location.historyState)}#C(e,t){n.reportError(e,t,this.#o)}#w(e,t){e.catch(e=>{isRouterErrorCarrier(e)?this.#C(e.error,e.context):this.#C(e,t)})}#T(){for(let e of[...this.#h])try{e(this.#d)}catch(e){queueMicrotask(()=>{throw e})}}async#E(e,t,n){return Promise.all(e.map(async e=>{if(!e.dataFn)return;let r=e.dataFn;try{return await r({...t,signal:n})}catch(r){if(e.onError)return e.onError(r,{...t,signal:n});throw r}}))}async#D(e){let t=e;for(let e=0;e<5;e+=1){let e=new URL(t,`http://localhost`),n={hash:e.hash.replace(/^#/,``),historyState:null,pathname:o.stripBase(e.pathname,this.#e),query:o.parseQuery(e.search)},r=await this.#O(n);if(r.type!==`redirect`)return r;t=this.#N(r.redirectTo)}throw new r.WayfinderRedirectLoopError}async#O(e){let{params:t,record:r}=o.matchRouteFor(e.pathname,this.#i);if(!r)return{location:e,params:t,type:`unmatched`};if(r.redirect)return{location:e,params:t,redirectTo:resolveTarget(r.redirect,this.#a,this.#e),type:`redirect`};let i=e.query,a=r.coerceSearch??this.#n;if(a)try{i=a(e.query)}catch(t){this.#C(t,{source:`coerce-search`}),i=e.query}return{branch:n.buildMatchBranch(r.branchDefs,t,e.pathname,r.branchDefs.map(()=>void 0)),location:e,params:t,record:r,resolvedQuery:i,type:`matched`}}async#k(e,t,r,i,a,o,s){if(!o())return;let c=e.branchDefs,l=c.some(e=>e.dataFn!=null),u=c.map(()=>void 0);if(l){let e=this.#F(r),l=this.#_.get(e);if(l&&(await l.catch(()=>void 0),!o()))return;let d=this.#g.get(e);if(d)this.#g.delete(e),u=d;else{this.#d=n.createRouteState({location:r,matches:n.buildMatchBranch(c,i,r.pathname,u),status:`loading`}),this.#T();try{u=await this.#E(c,t,a)}catch(e){if(!o())return;throw this.#d=n.createRouteState({error:e,location:r,matches:n.buildMatchBranch(c,i,r.pathname,u),status:`error`}),s?.(e),e}}}o()&&(this.#d=n.createRouteState({location:r,matches:n.buildMatchBranch(c,i,r.pathname,u),status:`idle`}))}async#A(e,t,i,a,o=0,s=!1){let c=this.#d,isCurrent=()=>e.isCurrent()&&!this.#f,l=await this.#O(t);if(!isCurrent())return!1;if(l.type===`redirect`){if(o>=5)throw new r.WayfinderRedirectLoopError;return this.#A(e,this.#P(l.redirectTo,t.historyState),i,a,o+1,!0)}if(l.type===`unmatched`){if(this.#v){let r=[this.#v.leaf],o=n.buildMatchBranch(r,{},t.pathname,[void 0]),l=!1,u,d=!1,f=!1,p=t.query,m=!1;if(this.#n)try{p=this.#n(t.query)}catch(e){this.#C(e,{source:`coerce-search`})}let run=async()=>{if(!isCurrent())return;let r=n.createRouteContext(t,p,{},o,(e,t)=>this.navigate(e,t));f=await n.executeMiddlewarePipeline(r,[...this.#t,...this.#v.ownMiddleware],async()=>{isCurrent()&&(l=!0,i(t,s),isCurrent()&&(await this.#k(this.#v,r,t,{},e.signal,isCurrent,e=>{u=e,d=!0}),isCurrent()&&(m=!0,this.#T(),this.#M(this.#d,c))))},e=>isRouterErrorCarrier(e)||d&&e===u?e:carryError(e,{routeName:`__notFound__`,source:`middleware`}))};try{await this.#j(run,a)}catch(e){throw d&&e===u?carryError(e,{routeName:`__notFound__`,source:`data-loader`}):e}finally{isCurrent()&&l&&!m&&(this.#T(),this.#M(this.#d,c))}return f&&l}return!isCurrent()||(i(l.location,s),!isCurrent())?!1:(this.#d=n.createRouteState({location:l.location,matches:[],status:`idle`}),this.#T(),this.#M(this.#d,c),!0)}let{branch:u,location:d,params:f,record:p,resolvedQuery:m}=l,h=!1,g,_=!1,v=!1,y=!1,run=async()=>{if(!isCurrent())return;let t=n.createRouteContext(d,m,f,u,(e,t)=>this.navigate(e,t));v=await n.executeMiddlewarePipeline(t,[...this.#t,...p.ownMiddleware],async()=>{isCurrent()&&(h=!0,i(d,s),isCurrent()&&(await this.#k(p,t,d,f,e.signal,isCurrent,e=>{g=e,_=!0}),isCurrent()&&(y=!0,this.#T(),this.#M(this.#d,c))))},e=>isRouterErrorCarrier(e)||_&&e===g?e:carryError(e,{routeName:p.leaf.name,source:`middleware`}))};try{await this.#j(run,a)}catch(e){throw _&&e===g?carryError(e,{routeName:p.leaf.name,source:`data-loader`}):e}finally{isCurrent()&&h&&!y&&(this.#T(),this.#M(this.#d,c))}return v&&h}async#j(e,t){if((t??this.#c)&&typeof document<`u`){let t=document.startViewTransition;if(t){await t.call(document,e).finished;return}}await e()}#M(e,t){if(!this.#s||typeof window>`u`)return;let n=this.#s(e,t);n!==`preserve`&&(n===`top`?window.scrollTo(0,0):window.scrollTo(n.x,n.y))}#N(e){let t=new URL(e,`http://localhost`),n=o.stripBase(t.pathname,this.#e);return`${o.joinPaths(this.#e,n)}${t.search}${t.hash}`}#P(e,t){let n=new URL(this.#N(e),`http://localhost`);return{hash:n.hash.replace(/^#/,``),historyState:t,pathname:o.stripBase(n.pathname,this.#e),query:o.parseQuery(n.search)}}#F(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e.query))Array.isArray(r)?r.forEach(e=>{t.append(n,e)}):t.set(n,r);let n=t.toString(),r=e.hash?`#${e.hash}`:``;return`${o.joinPaths(this.#e,e.pathname)}${n?`?${n}`:``}${r}`}#I(e){let t=new URL(e,`http://localhost`),n=o.stripBase(t.pathname,this.#e),{params:r,record:i}=o.matchRouteFor(n,this.#i);return{name:i?.leaf.name,params:r,pathname:n,query:o.parseQuery(t.search)}}async#L(e,t={}){this.#b();let n=this.#N(e);if(!t.force&&n===this.#m)return;let r=this.#u.begin(),a=this.#d.matches.map(e=>e.name),o=await i.runLeaveBlockers(this.#l,a,this.#I(n));if(r.isCurrent()&&o)try{await this.#A(r,this.#P(n,t.state),(e,t)=>{if(!r.isCurrent())return;let n=this.#F(e);t?this.#r.replace(n,e.historyState):this.#r.push(n,e.historyState),this.#m=n},t.viewTransition,0,t.replace??!1)}catch(e){throw isRouterErrorCarrier(e)?e.error:e}}};function createRouter(e){return new Router(e)}exports.createRouter=createRouter;
|
|
1
|
+
const e=require("./_navigation.cjs"),t=require("./compile.cjs"),n=require("./context.cjs"),r=require("./errors.cjs"),i=require("./guards.cjs"),a=require("./history.cjs"),o=require("./path.cjs");function getRouteByName(e,t){let n=t.get(e);if(n)return n;let i=[...t.keys()].join(`, `);throw new r.WayfinderRouteError(i?`Unknown route name: ${e}. Available routes: ${i}`:`Unknown route name: ${e}`)}function resolveTarget(e,t,n=`/`){if(`path`in e)return e.path;let r=getRouteByName(e.name,t),i=o.buildUrl(n,r.path,e.params,e.query);return e.hash?`${i}#${e.hash}`:i}var s=Symbol(`wayfinder.routerError`),c=5;function carryError(e,t){return{[s]:!0,context:t,error:e}}function isRouterErrorCarrier(e){return typeof e==`object`&&!!e&&s in e}function unwrapCarrier(e){throw isRouterErrorCarrier(e)?e.error:e}var Router=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l=new Set;#u=e.createNavigationCoordinator();#d;#f=!1;#p=new AbortController;#m=`/`;#h=new Set;#g=new Map;#_=new Map;#v;#y;ready;constructor(e){let r=t.compileRoutes(e);if(this.#e=o.normalizePath(e.base??`/`),this.#t=e.middleware??[],this.#n=e.coerceSearch,this.#r=e.history??a.createBrowserHistory(),this.#o=e.onError,this.#s=e.scroll,this.#c=e.viewTransition??!1,this.#i=r.records,this.#a=r.routesByName,this.#d=n.createRouteState({location:{hash:``,historyState:null,pathname:`/`,query:{}},matches:[],status:`idle`}),e.notFound){let t=e.notFound,n={dataFn:t.data,name:`__notFound__`};this.#v={branchDefs:[n],leaf:n,matcher:{paramNames:[],pattern:/(?:)/,prefixPattern:/(?:)/},ownMiddleware:t.middleware??[],path:`/*`}}else this.#v=null;this.#y=this.#x();let{hash:i,pathname:s,search:c,state:l}=this.#r.location,u=`${s}${c}${i}`;this.#m=u;let d=this.#u.begin(),f=this.#j(d,u,l,(e,t)=>{if(!d.isCurrent())return;let n=this.#I(e);t&&this.#r.replace(n,e.historyState),this.#m=n},void 0,!1).then(()=>void 0);this.ready=f.catch(unwrapCarrier),this.ready.catch(()=>{}),this.#w(f,{source:`initial-navigation`}),this.beforeLeave=this.beforeLeave.bind(this),this.createViewRegistry=this.createViewRegistry.bind(this),this.dispose=this.dispose.bind(this),this.getSnapshot=this.getSnapshot.bind(this),this.isActive=this.isActive.bind(this),this.load=this.load.bind(this),this.match=this.match.bind(this),this.navigate=this.navigate.bind(this),this.preload=this.preload.bind(this),this.subscribe=this.subscribe.bind(this),this.url=this.url.bind(this),this.waitFor=this.waitFor.bind(this)}getSnapshot(){return this.#d}createViewRegistry(e,t){return{resolve:n=>{let r=n.matches.at(-1)?.name;return r===`__notFound__`?t?.notFound:r?e[r]:void 0}}}subscribe(e){return this.#b(),this.#h.add(e),()=>{this.#h.delete(e)}}navigate(e,t){let n=resolveTarget(typeof e==`string`?{path:e}:e,this.#a,this.#e);return this.#R(n,t)}url(e,t,n){let r=getRouteByName(e,this.#a);return o.buildUrl(this.#e,r.path,t,n)}href(e,t,n){let r=getRouteByName(e,this.#a),i=o.buildUrl(this.#e,r.path,t,n);return this.#r.href?.(i)??i}isActive(e,t={}){let n=getRouteByName(e,this.#a),r=this.#d.location.pathname;return t.exact??!1?o.matchRouteFor(r,[n]).record!=null:o.matchesPrefix(r,n)}match(e){let t=o.stripBase(o.normalizePath(e),this.#e),{params:r,record:i}=o.matchRouteFor(t,this.#i);if(!i||i.redirect)return null;let a=n.buildMatchBranch(i.branchDefs,r,t,i.branchDefs.map(()=>void 0));return a.length?a:null}async load(e,t){let{decision:r}=await this.#D(e,null);if(r.type!==`matched`)return null;let{location:i,params:a,record:o,resolvedQuery:s}=r,c=o.branchDefs,l=c.some(e=>e.dataFn!=null),u=c.map(()=>void 0),d,f=`idle`;if(l){let e=t?.signal??new AbortController().signal,r=n.buildMatchBranch(c,a,i.pathname,u),o=n.createRouteContext(i,s,a,r,()=>Promise.resolve());try{u=await this.#E(c,o,e)}catch(e){d=e,f=`error`}}return n.createRouteState({error:d,location:i,matches:n.buildMatchBranch(c,a,i.pathname,u),status:f})}async preload(e){this.#b();let t=this.#P(resolveTarget(e,this.#a,this.#e)),n=this.#_.get(t);if(n)return n;let r=this.load(t,{signal:this.#p.signal}).then(e=>{if(this.#f)throw this.#p.signal.reason;if(e?.status===`error`)throw e.error;if(e){let t=this.#I(e.location);this.#g.size>=20&&this.#g.delete(this.#g.keys().next().value),this.#g.set(t,e.matches.map(e=>e.data))}return e}).catch(e=>{throw this.#o&&this.#C(e,{source:`preload`}),e}).finally(()=>{this.#_.delete(t)});return this.#_.set(t,r),r}waitFor(e){return this.#b(),new Promise((t,n)=>{let matchesName=t=>t.status===`idle`&&t.matches.some(t=>t.name===e);if(this.#d.status===`error`){n(this.#d.error);return}if(matchesName(this.#d)){t(this.#d);return}let r=this.subscribe(e=>{matchesName(e)?(r(),t(e)):e.status===`error`&&(r(),n(e.error))});this.#p.signal.addEventListener(`abort`,()=>{r(),n(this.#p.signal.reason)},{once:!0})})}beforeLeave(e,t){this.#b();let n={handler:e,routes:t?.routes};return this.#l.add(n),()=>{this.#l.delete(n)}}get disposalSignal(){return this.#p.signal}get disposed(){return this.#f}dispose(){this.#f||(this.#f=!0,this.#l.clear(),this.#h.clear(),this.#g.clear(),this.#_.clear(),this.#u.invalidate(new r.WayfinderDisposedError),this.#y(),this.#p.abort(new r.WayfinderDisposedError))}[Symbol.dispose](){this.dispose()}#b(){if(this.#f)throw new r.WayfinderDisposedError}#x(){return this.#r.onPopstate(()=>{let{hash:e,pathname:t,search:n}=this.#r.location,r=`${t}${n}${e}`,i=this.#m;r!==i&&this.#w(this.#S(r,i),{source:`history-listener`})})}async#S(e,t){let n=this.#u.begin(),r=this.#d.matches.map(e=>e.name),a=this.#L(e),o=await i.runLeaveBlockers(this.#l,r,a);if(!n.isCurrent())return;if(!o){this.#r.replace(t,this.#d.location.historyState);return}let s=await this.#j(n,e,this.#r.location.state,(e,t)=>{if(!n.isCurrent())return;let r=this.#I(e);t&&this.#r.replace(r,e.historyState),this.#m=r},void 0,!1);n.isCurrent()&&!s&&this.#r.replace(t,this.#d.location.historyState)}#C(e,t){n.reportError(e,t,this.#o)}#w(e,t){e.catch(e=>{isRouterErrorCarrier(e)?this.#C(e.error,e.context):this.#C(e,t)})}#T(){for(let e of[...this.#h])try{e(this.#d)}catch(e){queueMicrotask(()=>{throw e})}}async#E(e,t,n){return Promise.all(e.map(async e=>{if(!e.dataFn)return;let r=e.dataFn;try{return await r({...t,signal:n})}catch(r){if(e.onError)return e.onError(r,{...t,signal:n});throw r}}))}async#D(e,t){let n=e,i=!1;for(let e=0;;e+=1){let a=await this.#k(this.#F(n,t));if(a.type!==`redirect`)return{decision:a,hopped:i};if(e>=c)throw new r.WayfinderRedirectLoopError;n=a.redirectTo,i=!0}}#O(e,t){if(!t)return e.query;try{return t(e.query)}catch(t){return this.#C(t,{source:`coerce-search`}),e.query}}async#k(e){let{params:t,record:r}=o.matchRouteFor(e.pathname,this.#i);if(!r)return this.#v?{branch:n.buildMatchBranch(this.#v.branchDefs,{},e.pathname,[void 0]),location:e,params:{},record:this.#v,resolvedQuery:this.#O(e,this.#n),type:`matched`}:{location:e,params:t,type:`unmatched`};if(r.redirect)return{location:e,params:t,redirectTo:resolveTarget(r.redirect,this.#a,this.#e),type:`redirect`};let i=this.#O(e,r.coerceSearch??this.#n);return{branch:n.buildMatchBranch(r.branchDefs,t,e.pathname,r.branchDefs.map(()=>void 0)),location:e,params:t,record:r,resolvedQuery:i,type:`matched`}}async#A(e,t,r,i,a,o,s){if(!o())return;let c=e.branchDefs,l=c.some(e=>e.dataFn!=null),u=c.map(()=>void 0);if(l){let e=this.#I(r),l=this.#_.get(e);if(l&&(await l.catch(()=>void 0),!o()))return;let d=this.#g.get(e);if(d)this.#g.delete(e),u=d;else{this.#d=n.createRouteState({location:r,matches:n.buildMatchBranch(c,i,r.pathname,u),status:`loading`}),this.#T();try{u=await this.#E(c,t,a)}catch(e){if(!o())return;throw this.#d=n.createRouteState({error:e,location:r,matches:n.buildMatchBranch(c,i,r.pathname,u),status:`error`}),s?.(e),e}}}o()&&(this.#d=n.createRouteState({location:r,matches:n.buildMatchBranch(c,i,r.pathname,u),status:`idle`}))}async#j(e,t,r,i,a,o){let s=this.#d,isCurrent=()=>e.isCurrent()&&!this.#f,{decision:c,hopped:l}=await this.#D(t,r);if(!isCurrent())return!1;if(c.type===`unmatched`)return i(c.location,o||l),isCurrent()?(this.#d=n.createRouteState({location:c.location,matches:[],status:`idle`}),this.#T(),this.#N(this.#d,s),!0):!1;let{branch:u,location:d,params:f,record:p,resolvedQuery:m}=c,h=o||l,g=!1,_,v=!1,y=!1,b=!1,run=async()=>{if(!isCurrent())return;let t=n.createRouteContext(d,m,f,u,(e,t)=>this.navigate(e,t));y=await n.executeMiddlewarePipeline(t,[...this.#t,...p.ownMiddleware],async()=>{isCurrent()&&(g=!0,i(d,h),isCurrent()&&(await this.#A(p,t,d,f,e.signal,isCurrent,e=>{_=e,v=!0}),isCurrent()&&(b=!0,this.#T(),this.#N(this.#d,s))))},e=>isRouterErrorCarrier(e)||v&&e===_?e:carryError(e,{routeName:p.leaf.name,source:`middleware`}))};try{await this.#M(run,a)}catch(e){throw v&&e===_?carryError(e,{routeName:p.leaf.name,source:`data-loader`}):e}finally{isCurrent()&&g&&!b&&(this.#T(),this.#N(this.#d,s))}return y&&g}async#M(e,t){if((t??this.#c)&&typeof document<`u`){let t=document.startViewTransition;if(t){await t.call(document,e).finished;return}}await e()}#N(e,t){if(!this.#s||typeof window>`u`)return;let n=this.#s(e,t);n!==`preserve`&&(n===`top`?window.scrollTo(0,0):window.scrollTo(n.x,n.y))}#P(e){let t=new URL(e,`http://localhost`),n=o.stripBase(t.pathname,this.#e);return`${o.joinPaths(this.#e,n)}${t.search}${t.hash}`}#F(e,t){let n=new URL(this.#P(e),`http://localhost`);return{hash:n.hash.replace(/^#/,``),historyState:t,pathname:o.stripBase(n.pathname,this.#e),query:o.parseQuery(n.search)}}#I(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e.query))Array.isArray(r)?r.forEach(e=>{t.append(n,e)}):t.set(n,r);let n=t.toString(),r=e.hash?`#${e.hash}`:``;return`${o.joinPaths(this.#e,e.pathname)}${n?`?${n}`:``}${r}`}#L(e){let t=new URL(e,`http://localhost`),n=o.stripBase(t.pathname,this.#e),{params:r,record:i}=o.matchRouteFor(n,this.#i);return{name:i?.leaf.name,params:r,pathname:n,query:o.parseQuery(t.search)}}async#R(e,t={}){this.#b();let n=this.#P(e);if(!t.force&&n===this.#m)return;let r=this.#u.begin(),a=this.#d.matches.map(e=>e.name),o=await i.runLeaveBlockers(this.#l,a,this.#L(n));if(r.isCurrent()&&o)try{await this.#j(r,n,t.state,(e,t)=>{if(!r.isCurrent())return;let n=this.#I(e);t?this.#r.replace(n,e.historyState):this.#r.push(n,e.historyState),this.#m=n},t.viewTransition,t.replace??!1)}catch(e){throw isRouterErrorCarrier(e)?e.error:e}}};function createRouter(e){return new Router(e)}exports.createRouter=createRouter;
|
|
2
2
|
//# sourceMappingURL=router.cjs.map
|