@benjavicente/router-core 1.168.9 → 1.169.2
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/cjs/Matches.cjs +1 -1
- package/dist/cjs/Matches.cjs.map +1 -1
- package/dist/cjs/config.cjs +1 -1
- package/dist/cjs/config.cjs.map +1 -1
- package/dist/cjs/defer.cjs +1 -1
- package/dist/cjs/defer.cjs.map +1 -1
- package/dist/cjs/hash-scroll.cjs +1 -1
- package/dist/cjs/hash-scroll.cjs.map +1 -1
- package/dist/cjs/index.cjs +4 -0
- package/dist/cjs/index.d.cts +3 -3
- package/dist/cjs/isServer/client.cjs +1 -1
- package/dist/cjs/isServer/client.cjs.map +1 -1
- package/dist/cjs/isServer/development.cjs +1 -1
- package/dist/cjs/isServer/development.cjs.map +1 -1
- package/dist/cjs/isServer/server.cjs +1 -1
- package/dist/cjs/isServer/server.cjs.map +1 -1
- package/dist/cjs/link.cjs +1 -1
- package/dist/cjs/link.cjs.map +1 -1
- package/dist/cjs/load-matches.cjs +26 -26
- package/dist/cjs/load-matches.cjs.map +1 -1
- package/dist/cjs/manifest.cjs +31 -0
- package/dist/cjs/manifest.cjs.map +1 -1
- package/dist/cjs/manifest.d.cts +8 -0
- package/dist/cjs/new-process-route-tree.cjs +55 -67
- package/dist/cjs/new-process-route-tree.cjs.map +1 -1
- package/dist/cjs/new-process-route-tree.d.cts +4 -26
- package/dist/cjs/not-found.cjs +1 -1
- package/dist/cjs/not-found.cjs.map +1 -1
- package/dist/cjs/path.cjs +1 -22
- package/dist/cjs/path.cjs.map +1 -1
- package/dist/cjs/root.cjs +1 -1
- package/dist/cjs/root.cjs.map +1 -1
- package/dist/cjs/route.cjs.map +1 -1
- package/dist/cjs/route.d.cts +6 -34
- package/dist/cjs/router.cjs +94 -80
- package/dist/cjs/router.cjs.map +1 -1
- package/dist/cjs/router.d.cts +6 -5
- package/dist/cjs/scroll-restoration-script/server.cjs +1 -1
- package/dist/cjs/scroll-restoration-script/server.cjs.map +1 -1
- package/dist/cjs/scroll-restoration.cjs +7 -7
- package/dist/cjs/scroll-restoration.cjs.map +1 -1
- package/dist/cjs/searchParams.cjs +2 -2
- package/dist/cjs/searchParams.cjs.map +1 -1
- package/dist/cjs/ssr/constants.cjs +2 -2
- package/dist/cjs/ssr/constants.cjs.map +1 -1
- package/dist/cjs/ssr/createRequestHandler.cjs +2 -2
- package/dist/cjs/ssr/createRequestHandler.cjs.map +1 -1
- package/dist/cjs/ssr/serializer/RawStream.cjs +50 -41
- package/dist/cjs/ssr/serializer/RawStream.cjs.map +1 -1
- package/dist/cjs/ssr/serializer/RawStream.d.cts +12 -4
- package/dist/cjs/ssr/serializer/ShallowErrorPlugin.cjs +1 -1
- package/dist/cjs/ssr/serializer/ShallowErrorPlugin.cjs.map +1 -1
- package/dist/cjs/ssr/serializer/ShallowErrorPlugin.d.cts +2 -2
- package/dist/cjs/ssr/serializer/seroval-plugins.cjs +1 -1
- package/dist/cjs/ssr/serializer/seroval-plugins.cjs.map +1 -1
- package/dist/cjs/ssr/serializer/seroval-plugins.d.cts +2 -1
- package/dist/cjs/ssr/serializer/transformer.cjs +16 -14
- package/dist/cjs/ssr/serializer/transformer.cjs.map +1 -1
- package/dist/cjs/ssr/serializer/transformer.d.cts +24 -23
- package/dist/cjs/ssr/ssr-client.cjs +9 -9
- package/dist/cjs/ssr/ssr-client.cjs.map +1 -1
- package/dist/cjs/ssr/ssr-server.cjs +110 -22
- package/dist/cjs/ssr/ssr-server.cjs.map +1 -1
- package/dist/cjs/ssr/ssr-server.d.cts +4 -2
- package/dist/cjs/ssr/transformStreamWithRouter.cjs +10 -7
- package/dist/cjs/ssr/transformStreamWithRouter.cjs.map +1 -1
- package/dist/cjs/stores.cjs +57 -57
- package/dist/cjs/stores.cjs.map +1 -1
- package/dist/cjs/stores.d.cts +16 -16
- package/dist/cjs/utils.cjs +12 -7
- package/dist/cjs/utils.cjs.map +1 -1
- package/dist/cjs/utils.d.cts +1 -0
- package/dist/esm/Matches.js +1 -1
- package/dist/esm/Matches.js.map +1 -1
- package/dist/esm/config.js +1 -1
- package/dist/esm/config.js.map +1 -1
- package/dist/esm/defer.js +1 -1
- package/dist/esm/defer.js.map +1 -1
- package/dist/esm/hash-scroll.js +1 -1
- package/dist/esm/hash-scroll.js.map +1 -1
- package/dist/esm/index.d.ts +3 -3
- package/dist/esm/index.js +3 -3
- package/dist/esm/isServer/client.js +1 -1
- package/dist/esm/isServer/client.js.map +1 -1
- package/dist/esm/isServer/development.js +1 -1
- package/dist/esm/isServer/development.js.map +1 -1
- package/dist/esm/isServer/server.js +1 -1
- package/dist/esm/isServer/server.js.map +1 -1
- package/dist/esm/link.js +1 -1
- package/dist/esm/link.js.map +1 -1
- package/dist/esm/load-matches.js +26 -26
- package/dist/esm/load-matches.js.map +1 -1
- package/dist/esm/manifest.d.ts +8 -0
- package/dist/esm/manifest.js +28 -1
- package/dist/esm/manifest.js.map +1 -1
- package/dist/esm/new-process-route-tree.d.ts +4 -26
- package/dist/esm/new-process-route-tree.js +55 -68
- package/dist/esm/new-process-route-tree.js.map +1 -1
- package/dist/esm/not-found.js +1 -1
- package/dist/esm/not-found.js.map +1 -1
- package/dist/esm/path.js +1 -22
- package/dist/esm/path.js.map +1 -1
- package/dist/esm/root.js +1 -1
- package/dist/esm/root.js.map +1 -1
- package/dist/esm/route.d.ts +6 -34
- package/dist/esm/route.js.map +1 -1
- package/dist/esm/router.d.ts +6 -5
- package/dist/esm/router.js +96 -82
- package/dist/esm/router.js.map +1 -1
- package/dist/esm/scroll-restoration-script/server.js +1 -1
- package/dist/esm/scroll-restoration-script/server.js.map +1 -1
- package/dist/esm/scroll-restoration.js +7 -7
- package/dist/esm/scroll-restoration.js.map +1 -1
- package/dist/esm/searchParams.js +2 -2
- package/dist/esm/searchParams.js.map +1 -1
- package/dist/esm/ssr/constants.js +2 -2
- package/dist/esm/ssr/constants.js.map +1 -1
- package/dist/esm/ssr/createRequestHandler.js +2 -2
- package/dist/esm/ssr/createRequestHandler.js.map +1 -1
- package/dist/esm/ssr/serializer/RawStream.d.ts +12 -4
- package/dist/esm/ssr/serializer/RawStream.js +50 -41
- package/dist/esm/ssr/serializer/RawStream.js.map +1 -1
- package/dist/esm/ssr/serializer/ShallowErrorPlugin.d.ts +2 -2
- package/dist/esm/ssr/serializer/ShallowErrorPlugin.js +1 -1
- package/dist/esm/ssr/serializer/ShallowErrorPlugin.js.map +1 -1
- package/dist/esm/ssr/serializer/seroval-plugins.d.ts +2 -1
- package/dist/esm/ssr/serializer/seroval-plugins.js +1 -1
- package/dist/esm/ssr/serializer/seroval-plugins.js.map +1 -1
- package/dist/esm/ssr/serializer/transformer.d.ts +24 -23
- package/dist/esm/ssr/serializer/transformer.js +16 -14
- package/dist/esm/ssr/serializer/transformer.js.map +1 -1
- package/dist/esm/ssr/ssr-client.js +9 -9
- package/dist/esm/ssr/ssr-client.js.map +1 -1
- package/dist/esm/ssr/ssr-server.d.ts +4 -2
- package/dist/esm/ssr/ssr-server.js +110 -22
- package/dist/esm/ssr/ssr-server.js.map +1 -1
- package/dist/esm/ssr/transformStreamWithRouter.js +10 -7
- package/dist/esm/ssr/transformStreamWithRouter.js.map +1 -1
- package/dist/esm/stores.d.ts +16 -16
- package/dist/esm/stores.js +58 -58
- package/dist/esm/stores.js.map +1 -1
- package/dist/esm/utils.d.ts +1 -0
- package/dist/esm/utils.js +12 -8
- package/dist/esm/utils.js.map +1 -1
- package/package.json +4 -8
- package/skills/router-core/auth-and-guards/SKILL.md +41 -0
- package/skills/router-core/ssr/SKILL.md +59 -5
- package/skills/router-core/type-safety/SKILL.md +37 -42
- package/src/hash-scroll.ts +1 -1
- package/src/index.ts +9 -2
- package/src/load-matches.ts +14 -15
- package/src/manifest.ts +46 -0
- package/src/new-process-route-tree.ts +93 -106
- package/src/not-found.ts +1 -1
- package/src/path.ts +1 -27
- package/src/route.ts +10 -36
- package/src/router.ts +151 -140
- package/src/scroll-restoration.ts +1 -1
- package/src/ssr/createRequestHandler.ts +4 -5
- package/src/ssr/serializer/RawStream.ts +65 -56
- package/src/ssr/serializer/ShallowErrorPlugin.ts +2 -2
- package/src/ssr/serializer/seroval-plugins.ts +2 -1
- package/src/ssr/serializer/transformer.ts +71 -76
- package/src/ssr/ssr-client.ts +8 -12
- package/src/ssr/ssr-server.ts +170 -14
- package/src/ssr/transformStreamWithRouter.ts +3 -0
- package/src/stores.ts +86 -86
- package/src/utils.ts +7 -0
- package/bin/intent.js +0 -25
package/dist/esm/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":[],"sources":["../../src/utils.ts"],"sourcesContent":["import { isServer } from '@benjavicente/router-core/isServer'\nimport type { RouteIds } from './routeInfo'\nimport type { AnyRouter } from './router'\n\nexport type Awaitable<T> = T | Promise<T>\nexport type NoInfer<T> = [T][T extends any ? 0 : never]\nexport type IsAny<TValue, TYesResult, TNoResult = TValue> = 1 extends 0 & TValue\n ? TYesResult\n : TNoResult\n\nexport type PickAsRequired<TValue, TKey extends keyof TValue> = Omit<\n TValue,\n TKey\n> &\n Required<Pick<TValue, TKey>>\n\nexport type PickRequired<T> = {\n [K in keyof T as undefined extends T[K] ? never : K]: T[K]\n}\n\nexport type PickOptional<T> = {\n [K in keyof T as undefined extends T[K] ? K : never]: T[K]\n}\n\n// from https://stackoverflow.com/a/76458160\nexport type WithoutEmpty<T> = T extends any ? ({} extends T ? never : T) : never\n\nexport type Expand<T> = T extends object\n ? T extends infer O\n ? O extends Function\n ? O\n : { [K in keyof O]: O[K] }\n : never\n : T\n\nexport type DeepPartial<T> = T extends object\n ? {\n [P in keyof T]?: DeepPartial<T[P]>\n }\n : T\n\nexport type MakeDifferenceOptional<TLeft, TRight> = keyof TLeft &\n keyof TRight extends never\n ? TRight\n : Omit<TRight, keyof TLeft & keyof TRight> & {\n [K in keyof TLeft & keyof TRight]?: TRight[K]\n }\n\n// from https://stackoverflow.com/a/53955431\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport type IsUnion<T, U extends T = T> = (\n T extends any ? (U extends T ? false : true) : never\n) extends false\n ? false\n : true\n\nexport type IsNonEmptyObject<T> = T extends object\n ? keyof T extends never\n ? false\n : true\n : false\n\nexport type Assign<TLeft, TRight> = TLeft extends any\n ? TRight extends any\n ? IsNonEmptyObject<TLeft> extends false\n ? TRight\n : IsNonEmptyObject<TRight> extends false\n ? TLeft\n : keyof TLeft & keyof TRight extends never\n ? TLeft & TRight\n : Omit<TLeft, keyof TRight> & TRight\n : never\n : never\n\nexport type IntersectAssign<TLeft, TRight> = TLeft extends any\n ? TRight extends any\n ? IsNonEmptyObject<TLeft> extends false\n ? TRight\n : IsNonEmptyObject<TRight> extends false\n ? TLeft\n : TRight & TLeft\n : never\n : never\n\nexport type Timeout = ReturnType<typeof setTimeout>\n\nexport type Updater<TPrevious, TResult = TPrevious> =\n | TResult\n | ((prev?: TPrevious) => TResult)\n\nexport type NonNullableUpdater<TPrevious, TResult = TPrevious> =\n | TResult\n | ((prev: TPrevious) => TResult)\n\nexport type ExtractObjects<TUnion> = TUnion extends MergeAllPrimitive\n ? never\n : TUnion\n\nexport type PartialMergeAllObject<TUnion> =\n ExtractObjects<TUnion> extends infer TObj\n ? [TObj] extends [never]\n ? never\n : {\n [TKey in TObj extends any ? keyof TObj : never]?: TObj extends any\n ? TKey extends keyof TObj\n ? TObj[TKey]\n : never\n : never\n }\n : never\n\nexport type MergeAllPrimitive =\n | ReadonlyArray<any>\n | number\n | string\n | bigint\n | boolean\n | symbol\n | undefined\n | null\n\nexport type ExtractPrimitives<TUnion> = TUnion extends MergeAllPrimitive\n ? TUnion\n : TUnion extends object\n ? never\n : TUnion\n\nexport type PartialMergeAll<TUnion> =\n | ExtractPrimitives<TUnion>\n | PartialMergeAllObject<TUnion>\n\nexport type Constrain<T, TConstraint, TDefault = TConstraint> =\n | (T extends TConstraint ? T : never)\n | TDefault\n\nexport type ConstrainLiteral<T, TConstraint, TDefault = TConstraint> =\n | (T & TConstraint)\n | TDefault\n\n/**\n * To be added to router types\n */\nexport type UnionToIntersection<T> = (\n T extends any ? (arg: T) => any : never\n) extends (arg: infer T) => any\n ? T\n : never\n\n/**\n * Merges everything in a union into one object.\n * This mapped type is homomorphic which means it preserves stuff! :)\n */\nexport type MergeAllObjects<\n TUnion,\n TIntersected = UnionToIntersection<ExtractObjects<TUnion>>,\n> = [keyof TIntersected] extends [never]\n ? never\n : {\n [TKey in keyof TIntersected]: TUnion extends any\n ? TUnion[TKey & keyof TUnion]\n : never\n }\n\nexport type MergeAll<TUnion> =\n | MergeAllObjects<TUnion>\n | ExtractPrimitives<TUnion>\n\nexport type ValidateJSON<T> = ((...args: Array<any>) => any) extends T\n ? unknown extends T\n ? never\n : 'Function is not serializable'\n : { [K in keyof T]: ValidateJSON<T[K]> }\n\nexport type LooseReturnType<T> = T extends (\n ...args: Array<any>\n) => infer TReturn\n ? TReturn\n : never\n\nexport type LooseAsyncReturnType<T> = T extends (\n ...args: Array<any>\n) => infer TReturn\n ? TReturn extends Promise<infer TReturn>\n ? TReturn\n : TReturn\n : never\n\n/**\n * Return the last element of an array.\n * Intended for non-empty arrays used within router internals.\n */\nexport function last<T>(arr: ReadonlyArray<T>) {\n return arr[arr.length - 1]\n}\n\nfunction isFunction(d: any): d is Function {\n return typeof d === 'function'\n}\n\n/**\n * Apply a value-or-updater to a previous value.\n * Accepts either a literal value or a function of the previous value.\n */\nexport function functionalUpdate<TPrevious, TResult = TPrevious>(\n updater: Updater<TPrevious, TResult> | NonNullableUpdater<TPrevious, TResult>,\n previous: TPrevious,\n): TResult {\n if (isFunction(updater)) {\n return updater(previous)\n }\n\n return updater\n}\n\nconst hasOwn = Object.prototype.hasOwnProperty\nconst isEnumerable = Object.prototype.propertyIsEnumerable\n\nconst createNull = () => Object.create(null)\nexport const nullReplaceEqualDeep: typeof replaceEqualDeep = (prev, next) =>\n replaceEqualDeep(prev, next, createNull)\n\n/**\n * This function returns `prev` if `_next` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between immutable JSON values for example.\n * Do not use this with signals\n */\nexport function replaceEqualDeep<T>(\n prev: any,\n _next: T,\n _makeObj = () => ({}),\n _depth = 0,\n): T {\n if (isServer) {\n return _next\n }\n if (prev === _next) {\n return prev\n }\n\n if (_depth > 500) return _next\n\n const next = _next as any\n\n const array = isPlainArray(prev) && isPlainArray(next)\n\n if (!array && !(isPlainObject(prev) && isPlainObject(next))) return next\n\n const prevItems = array ? prev : getEnumerableOwnKeys(prev)\n if (!prevItems) return next\n const nextItems = array ? next : getEnumerableOwnKeys(next)\n if (!nextItems) return next\n const prevSize = prevItems.length\n const nextSize = nextItems.length\n const copy: any = array ? new Array(nextSize) : _makeObj()\n\n let equalItems = 0\n\n for (let i = 0; i < nextSize; i++) {\n const key = array ? i : (nextItems[i] as any)\n const p = prev[key]\n const n = next[key]\n\n if (p === n) {\n copy[key] = p\n if (array ? i < prevSize : hasOwn.call(prev, key)) equalItems++\n continue\n }\n\n if (\n p === null ||\n n === null ||\n typeof p !== 'object' ||\n typeof n !== 'object'\n ) {\n copy[key] = n\n continue\n }\n\n const v = replaceEqualDeep(p, n, _makeObj, _depth + 1)\n copy[key] = v\n if (v === p) equalItems++\n }\n\n return prevSize === nextSize && equalItems === prevSize ? prev : copy\n}\n\n/**\n * Equivalent to `Reflect.ownKeys`, but ensures that objects are \"clone-friendly\":\n * will return false if object has any non-enumerable properties.\n *\n * Optimized for the common case where objects have no symbol properties.\n */\nfunction getEnumerableOwnKeys(o: object) {\n const names = Object.getOwnPropertyNames(o)\n\n // Fast path: check all string property names are enumerable\n for (const name of names) {\n if (!isEnumerable.call(o, name)) return false\n }\n\n // Only check symbols if the object has any (most plain objects don't)\n const symbols = Object.getOwnPropertySymbols(o)\n\n // Fast path: no symbols, return names directly (avoids array allocation/concat)\n if (symbols.length === 0) return names\n\n // Slow path: has symbols, need to check and merge\n const keys: Array<string | symbol> = names\n for (const symbol of symbols) {\n if (!isEnumerable.call(o, symbol)) return false\n keys.push(symbol)\n }\n return keys\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\nexport function isPlainObject(o: any) {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has modified constructor\n const ctor = o.constructor\n if (typeof ctor === 'undefined') {\n return true\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\nfunction hasObjectPrototype(o: any) {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n\n/**\n * Check if a value is a \"plain\" array (no extra enumerable keys).\n */\nexport function isPlainArray(value: unknown): value is Array<unknown> {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\n/**\n * Perform a deep equality check with options for partial comparison and\n * ignoring `undefined` values. Optimized for router state comparisons.\n */\nexport function deepEqual(\n a: any,\n b: any,\n opts?: { partial?: boolean; ignoreUndefined?: boolean },\n): boolean {\n if (a === b) {\n return true\n }\n\n if (typeof a !== typeof b) {\n return false\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false\n for (let i = 0, l = a.length; i < l; i++) {\n if (!deepEqual(a[i], b[i], opts)) return false\n }\n return true\n }\n\n if (isPlainObject(a) && isPlainObject(b)) {\n const ignoreUndefined = opts?.ignoreUndefined ?? true\n\n if (opts?.partial) {\n for (const k in b) {\n if (!ignoreUndefined || b[k] !== undefined) {\n if (!deepEqual(a[k], b[k], opts)) return false\n }\n }\n return true\n }\n\n let aCount = 0\n if (!ignoreUndefined) {\n aCount = Object.keys(a).length\n } else {\n for (const k in a) {\n if (a[k] !== undefined) aCount++\n }\n }\n\n let bCount = 0\n for (const k in b) {\n if (!ignoreUndefined || b[k] !== undefined) {\n bCount++\n if (bCount > aCount || !deepEqual(a[k], b[k], opts)) return false\n }\n }\n\n return aCount === bCount\n }\n\n return false\n}\n\nexport type StringLiteral<T> = T extends string\n ? string extends T\n ? string\n : T\n : never\n\nexport type ThrowOrOptional<T, TThrow extends boolean> = TThrow extends true\n ? T\n : T | undefined\n\nexport type StrictOrFrom<\n TRouter extends AnyRouter,\n TFrom,\n TStrict extends boolean = true,\n> = TStrict extends false\n ? {\n from?: never\n strict: TStrict\n }\n : {\n from: ConstrainLiteral<TFrom, RouteIds<TRouter['routeTree']>>\n strict?: TStrict\n }\n\nexport type ThrowConstraint<\n TStrict extends boolean,\n TThrow extends boolean,\n> = TStrict extends false ? (TThrow extends true ? never : TThrow) : TThrow\n\nexport type ControlledPromise<T> = Promise<T> & {\n resolve: (value: T) => void\n reject: (value: any) => void\n status: 'pending' | 'resolved' | 'rejected'\n value?: T\n}\n\n/**\n * Create a promise with exposed resolve/reject and status fields.\n * Useful for coordinating async router lifecycle operations.\n */\nexport function createControlledPromise<T>(onResolve?: (value: T) => void) {\n let resolveLoadPromise!: (value: T) => void\n let rejectLoadPromise!: (value: any) => void\n\n const controlledPromise = new Promise<T>((resolve, reject) => {\n resolveLoadPromise = resolve\n rejectLoadPromise = reject\n }) as ControlledPromise<T>\n\n controlledPromise.status = 'pending'\n\n controlledPromise.resolve = (value: T) => {\n controlledPromise.status = 'resolved'\n controlledPromise.value = value\n resolveLoadPromise(value)\n onResolve?.(value)\n }\n\n controlledPromise.reject = (e) => {\n controlledPromise.status = 'rejected'\n rejectLoadPromise(e)\n }\n\n return controlledPromise\n}\n\n/**\n * Heuristically detect dynamic import \"module not found\" errors\n * across major browsers for lazy route component handling.\n */\nexport function isModuleNotFoundError(error: any): boolean {\n // chrome: \"Failed to fetch dynamically imported module: http://localhost:5173/src/routes/posts.index.tsx?tsr-split\"\n // firefox: \"error loading dynamically imported module: http://localhost:5173/src/routes/posts.index.tsx?tsr-split\"\n // safari: \"Importing a module script failed.\"\n if (typeof error?.message !== 'string') return false\n return (\n error.message.startsWith('Failed to fetch dynamically imported module') ||\n error.message.startsWith('error loading dynamically imported module') ||\n error.message.startsWith('Importing a module script failed')\n )\n}\n\nexport function isPromise<T>(\n value: Promise<Awaited<T>> | T,\n): value is Promise<Awaited<T>> {\n return Boolean(\n value &&\n typeof value === 'object' &&\n typeof (value as Promise<T>).then === 'function',\n )\n}\n\nexport function findLast<T>(\n array: ReadonlyArray<T>,\n predicate: (item: T) => boolean,\n): T | undefined {\n for (let i = array.length - 1; i >= 0; i--) {\n const item = array[i]!\n if (predicate(item)) return item\n }\n return undefined\n}\n\n/**\n * Remove control characters that can cause open redirect vulnerabilities.\n * Characters like \\r (CR) and \\n (LF) can trick URL parsers into interpreting\n * paths like \"/\\r/evil.com\" as \"http://evil.com\".\n */\nfunction sanitizePathSegment(segment: string): string {\n // Remove ASCII control characters (0x00-0x1F) and DEL (0x7F)\n // These include CR (\\r = 0x0D), LF (\\n = 0x0A), and other potentially dangerous characters\n // eslint-disable-next-line no-control-regex\n return segment.replace(/[\\x00-\\x1f\\x7f]/g, '')\n}\n\nfunction decodeSegment(segment: string): string {\n let decoded: string\n try {\n decoded = decodeURI(segment)\n } catch {\n // if the decoding fails, try to decode the various parts leaving the malformed tags in place\n decoded = segment.replaceAll(/%[0-9A-F]{2}/gi, (match) => {\n try {\n return decodeURI(match)\n } catch {\n return match\n }\n })\n }\n return sanitizePathSegment(decoded)\n}\n\n/**\n * Default list of URL protocols to allow in links, redirects, and navigation.\n * Any absolute URL protocol not in this list is treated as dangerous by default.\n */\nexport const DEFAULT_PROTOCOL_ALLOWLIST = [\n // Standard web navigation\n 'http:',\n 'https:',\n\n // Common browser-safe actions\n 'mailto:',\n 'tel:',\n]\n\n/**\n * Check if a URL string uses a protocol that is not in the allowlist.\n * Returns true for blocked protocols like javascript:, blob:, data:, etc.\n *\n * The URL constructor correctly normalizes:\n * - Mixed case (JavaScript: → javascript:)\n * - Whitespace/control characters (java\\nscript: → javascript:)\n * - Leading whitespace\n *\n * For relative URLs (no protocol), returns false (safe).\n *\n * @param url - The URL string to check\n * @param allowlist - Set of protocols to allow\n * @returns true if the URL uses a protocol that is not allowed\n */\nexport function isDangerousProtocol(\n url: string,\n allowlist: Set<string>,\n): boolean {\n if (!url) return false\n\n try {\n // Use the URL constructor - it correctly normalizes protocols\n // per WHATWG URL spec, handling all bypass attempts automatically\n const parsed = new URL(url)\n return !allowlist.has(parsed.protocol)\n } catch {\n // URL constructor throws for relative URLs (no protocol)\n // These are safe - they can't execute scripts\n return false\n }\n}\n\n// This utility is based on https://github.com/zertosh/htmlescape\n// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE\nconst HTML_ESCAPE_LOOKUP: { [match: string]: string } = {\n '&': '\\\\u0026',\n '>': '\\\\u003e',\n '<': '\\\\u003c',\n '\\u2028': '\\\\u2028',\n '\\u2029': '\\\\u2029',\n}\n\nconst HTML_ESCAPE_REGEX = /[&><\\u2028\\u2029]/g\n\n/**\n * Escape HTML special characters in a string to prevent XSS attacks\n * when embedding strings in script tags during SSR.\n *\n * This is essential for preventing XSS vulnerabilities when user-controlled\n * content is embedded in inline scripts.\n */\nexport function escapeHtml(str: string): string {\n return str.replace(HTML_ESCAPE_REGEX, (match) => HTML_ESCAPE_LOOKUP[match]!)\n}\n\nexport function decodePath(path: string) {\n if (!path) return { path, handledProtocolRelativeURL: false }\n\n // Fast path: most paths are already decoded and safe.\n // Only fall back to the slower scan/regex path when we see a '%' (encoded),\n // a backslash (explicitly handled), a control character, or a protocol-relative\n // prefix which needs collapsing.\n // eslint-disable-next-line no-control-regex\n if (!/[%\\\\\\x00-\\x1f\\x7f]/.test(path) && !path.startsWith('//')) {\n return { path, handledProtocolRelativeURL: false }\n }\n\n const re = /%25|%5C/gi\n let cursor = 0\n let result = ''\n let match\n while (null !== (match = re.exec(path))) {\n result += decodeSegment(path.slice(cursor, match.index)) + match[0]\n cursor = re.lastIndex\n }\n result = result + decodeSegment(cursor ? path.slice(cursor) : path)\n\n // Prevent open redirect via protocol-relative URLs (e.g. \"//evil.com\")\n // After sanitizing control characters, paths like \"/\\r/evil.com\" become \"//evil.com\"\n // Collapse leading double slashes to a single slash\n let handledProtocolRelativeURL = false\n if (result.startsWith('//')) {\n handledProtocolRelativeURL = true\n result = '/' + result.replace(/^\\/+/, '')\n }\n\n return { path: result, handledProtocolRelativeURL }\n}\n\n/**\n * Encodes a path the same way `new URL()` would, but without the overhead of full URL parsing.\n *\n * This function encodes:\n * - Whitespace characters (spaces → %20, tabs → %09, etc.)\n * - Non-ASCII/Unicode characters (emojis, accented characters, etc.)\n *\n * It preserves:\n * - Already percent-encoded sequences (won't double-encode %2F, %25, etc.)\n * - ASCII special characters valid in URL paths (@, $, &, +, etc.)\n * - Forward slashes as path separators\n *\n * Used to generate proper href values for SSR without constructing URL objects.\n *\n * @example\n * encodePathLikeUrl('/path/file name.pdf') // '/path/file%20name.pdf'\n * encodePathLikeUrl('/path/日本語') // '/path/%E6%97%A5%E6%9C%AC%E8%AA%9E'\n * encodePathLikeUrl('/path/already%20encoded') // '/path/already%20encoded' (preserved)\n */\nexport function encodePathLikeUrl(path: string): string {\n // Encode whitespace and non-ASCII characters that browsers encode in URLs\n\n // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional ASCII range check\n // eslint-disable-next-line no-control-regex\n if (!/\\s|[^\\u0000-\\u007F]/.test(path)) return path\n // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional ASCII range check\n // eslint-disable-next-line no-control-regex\n return path.replace(/\\s|[^\\u0000-\\u007F]/gu, encodeURIComponent)\n}\n\n/**\n * Builds the dev-mode CSS styles URL for route-scoped CSS collection.\n * Used by HeadContent components in all framework implementations to construct\n * the URL for the `/@tanstack-start/styles.css` endpoint.\n *\n * @param basepath - The router's basepath (may or may not have leading slash)\n * @param routeIds - Array of matched route IDs to include in the CSS collection\n * @returns The full URL path for the dev styles CSS endpoint\n */\nexport function buildDevStylesUrl(\n basepath: string,\n routeIds: Array<string>,\n): string {\n // Trim all leading and trailing slashes from basepath\n const trimmedBasepath = basepath.replace(/^\\/+|\\/+$/g, '')\n // Build normalized basepath: empty string for root, or '/path' for non-root\n const normalizedBasepath = trimmedBasepath === '' ? '' : `/${trimmedBasepath}`\n return `${normalizedBasepath}/@tanstack-start/styles.css?routes=${encodeURIComponent(routeIds.join(','))}`\n}\n\nexport function arraysEqual<T>(a: Array<T>, b: Array<T>) {\n if (a === b) return true\n if (a.length !== b.length) return false\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false\n }\n return true\n}\n"],"mappings":";;;;;;AA+LA,SAAgB,KAAQ,KAAuB;AAC7C,QAAO,IAAI,IAAI,SAAS;;AAG1B,SAAS,WAAW,GAAuB;AACzC,QAAO,OAAO,MAAM;;;;;;AAOtB,SAAgB,iBACd,SACA,UACS;AACT,KAAI,WAAW,QAAQ,CACrB,QAAO,QAAQ,SAAS;AAG1B,QAAO;;AAGT,IAAM,SAAS,OAAO,UAAU;AAChC,IAAM,eAAe,OAAO,UAAU;AAEtC,IAAM,mBAAmB,OAAO,OAAO,KAAK;AAC5C,IAAa,wBAAiD,MAAM,SAClE,iBAAiB,MAAM,MAAM,WAAW;;;;;;;AAQ1C,SAAgB,iBACd,MACA,OACA,kBAAkB,EAAE,GACpB,SAAS,GACN;AACH,KAAI,SACF,QAAO;AAET,KAAI,SAAS,MACX,QAAO;AAGT,KAAI,SAAS,IAAK,QAAO;CAEzB,MAAM,OAAO;CAEb,MAAM,QAAQ,aAAa,KAAK,IAAI,aAAa,KAAK;AAEtD,KAAI,CAAC,SAAS,EAAE,cAAc,KAAK,IAAI,cAAc,KAAK,EAAG,QAAO;CAEpE,MAAM,YAAY,QAAQ,OAAO,qBAAqB,KAAK;AAC3D,KAAI,CAAC,UAAW,QAAO;CACvB,MAAM,YAAY,QAAQ,OAAO,qBAAqB,KAAK;AAC3D,KAAI,CAAC,UAAW,QAAO;CACvB,MAAM,WAAW,UAAU;CAC3B,MAAM,WAAW,UAAU;CAC3B,MAAM,OAAY,QAAQ,IAAI,MAAM,SAAS,GAAG,UAAU;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O;AAE5B,QAAO"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../../src/utils.ts"],"sourcesContent":["import { isServer } from '@benjavicente/router-core/isServer'\nimport type { RouteIds } from './routeInfo'\nimport type { AnyRouter } from './router'\n\nexport type Awaitable<T> = T | Promise<T>\nexport type NoInfer<T> = [T][T extends any ? 0 : never]\nexport type IsAny<TValue, TYesResult, TNoResult = TValue> = 1 extends 0 & TValue\n ? TYesResult\n : TNoResult\n\nexport type PickAsRequired<TValue, TKey extends keyof TValue> = Omit<\n TValue,\n TKey\n> &\n Required<Pick<TValue, TKey>>\n\nexport type PickRequired<T> = {\n [K in keyof T as undefined extends T[K] ? never : K]: T[K]\n}\n\nexport type PickOptional<T> = {\n [K in keyof T as undefined extends T[K] ? K : never]: T[K]\n}\n\n// from https://stackoverflow.com/a/76458160\nexport type WithoutEmpty<T> = T extends any ? ({} extends T ? never : T) : never\n\nexport type Expand<T> = T extends object\n ? T extends infer O\n ? O extends Function\n ? O\n : { [K in keyof O]: O[K] }\n : never\n : T\n\nexport type DeepPartial<T> = T extends object\n ? {\n [P in keyof T]?: DeepPartial<T[P]>\n }\n : T\n\nexport type MakeDifferenceOptional<TLeft, TRight> = keyof TLeft &\n keyof TRight extends never\n ? TRight\n : Omit<TRight, keyof TLeft & keyof TRight> & {\n [K in keyof TLeft & keyof TRight]?: TRight[K]\n }\n\n// from https://stackoverflow.com/a/53955431\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport type IsUnion<T, U extends T = T> = (\n T extends any ? (U extends T ? false : true) : never\n) extends false\n ? false\n : true\n\nexport type IsNonEmptyObject<T> = T extends object\n ? keyof T extends never\n ? false\n : true\n : false\n\nexport type Assign<TLeft, TRight> = TLeft extends any\n ? TRight extends any\n ? IsNonEmptyObject<TLeft> extends false\n ? TRight\n : IsNonEmptyObject<TRight> extends false\n ? TLeft\n : keyof TLeft & keyof TRight extends never\n ? TLeft & TRight\n : Omit<TLeft, keyof TRight> & TRight\n : never\n : never\n\nexport type IntersectAssign<TLeft, TRight> = TLeft extends any\n ? TRight extends any\n ? IsNonEmptyObject<TLeft> extends false\n ? TRight\n : IsNonEmptyObject<TRight> extends false\n ? TLeft\n : TRight & TLeft\n : never\n : never\n\nexport type Timeout = ReturnType<typeof setTimeout>\n\nexport type Updater<TPrevious, TResult = TPrevious> =\n | TResult\n | ((prev?: TPrevious) => TResult)\n\nexport type NonNullableUpdater<TPrevious, TResult = TPrevious> =\n | TResult\n | ((prev: TPrevious) => TResult)\n\nexport type ExtractObjects<TUnion> = TUnion extends MergeAllPrimitive\n ? never\n : TUnion\n\nexport type PartialMergeAllObject<TUnion> =\n ExtractObjects<TUnion> extends infer TObj\n ? [TObj] extends [never]\n ? never\n : {\n [TKey in TObj extends any ? keyof TObj : never]?: TObj extends any\n ? TKey extends keyof TObj\n ? TObj[TKey]\n : never\n : never\n }\n : never\n\nexport type MergeAllPrimitive =\n | ReadonlyArray<any>\n | number\n | string\n | bigint\n | boolean\n | symbol\n | undefined\n | null\n\nexport type ExtractPrimitives<TUnion> = TUnion extends MergeAllPrimitive\n ? TUnion\n : TUnion extends object\n ? never\n : TUnion\n\nexport type PartialMergeAll<TUnion> =\n | ExtractPrimitives<TUnion>\n | PartialMergeAllObject<TUnion>\n\nexport type Constrain<T, TConstraint, TDefault = TConstraint> =\n | (T extends TConstraint ? T : never)\n | TDefault\n\nexport type ConstrainLiteral<T, TConstraint, TDefault = TConstraint> =\n | (T & TConstraint)\n | TDefault\n\n/**\n * To be added to router types\n */\nexport type UnionToIntersection<T> = (\n T extends any ? (arg: T) => any : never\n) extends (arg: infer T) => any\n ? T\n : never\n\n/**\n * Merges everything in a union into one object.\n * This mapped type is homomorphic which means it preserves stuff! :)\n */\nexport type MergeAllObjects<\n TUnion,\n TIntersected = UnionToIntersection<ExtractObjects<TUnion>>,\n> = [keyof TIntersected] extends [never]\n ? never\n : {\n [TKey in keyof TIntersected]: TUnion extends any\n ? TUnion[TKey & keyof TUnion]\n : never\n }\n\nexport type MergeAll<TUnion> =\n | MergeAllObjects<TUnion>\n | ExtractPrimitives<TUnion>\n\nexport type ValidateJSON<T> = ((...args: Array<any>) => any) extends T\n ? unknown extends T\n ? never\n : 'Function is not serializable'\n : { [K in keyof T]: ValidateJSON<T[K]> }\n\nexport type LooseReturnType<T> = T extends (\n ...args: Array<any>\n) => infer TReturn\n ? TReturn\n : never\n\nexport type LooseAsyncReturnType<T> = T extends (\n ...args: Array<any>\n) => infer TReturn\n ? TReturn extends Promise<infer TReturn>\n ? TReturn\n : TReturn\n : never\n\n/**\n * Return the last element of an array.\n * Intended for non-empty arrays used within router internals.\n */\nexport function last<T>(arr: ReadonlyArray<T>) {\n return arr[arr.length - 1]\n}\n\nfunction isFunction(d: any): d is Function {\n return typeof d === 'function'\n}\n\n/**\n * Apply a value-or-updater to a previous value.\n * Accepts either a literal value or a function of the previous value.\n */\nexport function functionalUpdate<TPrevious, TResult = TPrevious>(\n updater: Updater<TPrevious, TResult> | NonNullableUpdater<TPrevious, TResult>,\n previous: TPrevious,\n): TResult {\n if (isFunction(updater)) {\n return updater(previous)\n }\n\n return updater\n}\n\nconst hasOwn = Object.prototype.hasOwnProperty\nconst isEnumerable = Object.prototype.propertyIsEnumerable\n\nexport function hasKeys(obj: Record<string, unknown>) {\n for (const key in obj) {\n if (hasOwn.call(obj, key)) return true\n }\n return false\n}\n\nconst createNull = () => Object.create(null)\nexport const nullReplaceEqualDeep: typeof replaceEqualDeep = (prev, next) =>\n replaceEqualDeep(prev, next, createNull)\n\n/**\n * This function returns `prev` if `_next` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between immutable JSON values for example.\n * Do not use this with signals\n */\nexport function replaceEqualDeep<T>(\n prev: any,\n _next: T,\n _makeObj = () => ({}),\n _depth = 0,\n): T {\n if (isServer) {\n return _next\n }\n if (prev === _next) {\n return prev\n }\n\n if (_depth > 500) return _next\n\n const next = _next as any\n\n const array = isPlainArray(prev) && isPlainArray(next)\n\n if (!array && !(isPlainObject(prev) && isPlainObject(next))) return next\n\n const prevItems = array ? prev : getEnumerableOwnKeys(prev)\n if (!prevItems) return next\n const nextItems = array ? next : getEnumerableOwnKeys(next)\n if (!nextItems) return next\n const prevSize = prevItems.length\n const nextSize = nextItems.length\n const copy: any = array ? new Array(nextSize) : _makeObj()\n\n let equalItems = 0\n\n for (let i = 0; i < nextSize; i++) {\n const key = array ? i : (nextItems[i] as any)\n const p = prev[key]\n const n = next[key]\n\n if (p === n) {\n copy[key] = p\n if (array ? i < prevSize : hasOwn.call(prev, key)) equalItems++\n continue\n }\n\n if (\n p === null ||\n n === null ||\n typeof p !== 'object' ||\n typeof n !== 'object'\n ) {\n copy[key] = n\n continue\n }\n\n const v = replaceEqualDeep(p, n, _makeObj, _depth + 1)\n copy[key] = v\n if (v === p) equalItems++\n }\n\n return prevSize === nextSize && equalItems === prevSize ? prev : copy\n}\n\n/**\n * Equivalent to `Reflect.ownKeys`, but ensures that objects are \"clone-friendly\":\n * will return false if object has any non-enumerable properties.\n *\n * Optimized for the common case where objects have no symbol properties.\n */\nfunction getEnumerableOwnKeys(o: object) {\n const names = Object.getOwnPropertyNames(o)\n\n // Fast path: check all string property names are enumerable\n for (const name of names) {\n if (!isEnumerable.call(o, name)) return false\n }\n\n // Only check symbols if the object has any (most plain objects don't)\n const symbols = Object.getOwnPropertySymbols(o)\n\n // Fast path: no symbols, return names directly (avoids array allocation/concat)\n if (symbols.length === 0) return names\n\n // Slow path: has symbols, need to check and merge\n const keys: Array<string | symbol> = names\n for (const symbol of symbols) {\n if (!isEnumerable.call(o, symbol)) return false\n keys.push(symbol)\n }\n return keys\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\nexport function isPlainObject(o: any) {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has modified constructor\n const ctor = o.constructor\n if (typeof ctor === 'undefined') {\n return true\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\nfunction hasObjectPrototype(o: any) {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n\n/**\n * Check if a value is a \"plain\" array (no extra enumerable keys).\n */\nexport function isPlainArray(value: unknown): value is Array<unknown> {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\n/**\n * Perform a deep equality check with options for partial comparison and\n * ignoring `undefined` values. Optimized for router state comparisons.\n */\nexport function deepEqual(\n a: any,\n b: any,\n opts?: { partial?: boolean; ignoreUndefined?: boolean },\n): boolean {\n if (a === b) {\n return true\n }\n\n if (typeof a !== typeof b) {\n return false\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false\n for (let i = 0, l = a.length; i < l; i++) {\n if (!deepEqual(a[i], b[i], opts)) return false\n }\n return true\n }\n\n if (isPlainObject(a) && isPlainObject(b)) {\n const ignoreUndefined = opts?.ignoreUndefined ?? true\n\n if (opts?.partial) {\n for (const k in b) {\n if (!ignoreUndefined || b[k] !== undefined) {\n if (!deepEqual(a[k], b[k], opts)) return false\n }\n }\n return true\n }\n\n let aCount = 0\n if (!ignoreUndefined) {\n aCount = Object.keys(a).length\n } else {\n for (const k in a) {\n if (a[k] !== undefined) aCount++\n }\n }\n\n let bCount = 0\n for (const k in b) {\n if (!ignoreUndefined || b[k] !== undefined) {\n bCount++\n if (bCount > aCount || !deepEqual(a[k], b[k], opts)) return false\n }\n }\n\n return aCount === bCount\n }\n\n return false\n}\n\nexport type StringLiteral<T> = T extends string\n ? string extends T\n ? string\n : T\n : never\n\nexport type ThrowOrOptional<T, TThrow extends boolean> = TThrow extends true\n ? T\n : T | undefined\n\nexport type StrictOrFrom<\n TRouter extends AnyRouter,\n TFrom,\n TStrict extends boolean = true,\n> = TStrict extends false\n ? {\n from?: never\n strict: TStrict\n }\n : {\n from: ConstrainLiteral<TFrom, RouteIds<TRouter['routeTree']>>\n strict?: TStrict\n }\n\nexport type ThrowConstraint<\n TStrict extends boolean,\n TThrow extends boolean,\n> = TStrict extends false ? (TThrow extends true ? never : TThrow) : TThrow\n\nexport type ControlledPromise<T> = Promise<T> & {\n resolve: (value: T) => void\n reject: (value: any) => void\n status: 'pending' | 'resolved' | 'rejected'\n value?: T\n}\n\n/**\n * Create a promise with exposed resolve/reject and status fields.\n * Useful for coordinating async router lifecycle operations.\n */\nexport function createControlledPromise<T>(onResolve?: (value: T) => void) {\n let resolveLoadPromise!: (value: T) => void\n let rejectLoadPromise!: (value: any) => void\n\n const controlledPromise = new Promise<T>((resolve, reject) => {\n resolveLoadPromise = resolve\n rejectLoadPromise = reject\n }) as ControlledPromise<T>\n\n controlledPromise.status = 'pending'\n\n controlledPromise.resolve = (value: T) => {\n controlledPromise.status = 'resolved'\n controlledPromise.value = value\n resolveLoadPromise(value)\n onResolve?.(value)\n }\n\n controlledPromise.reject = (e) => {\n controlledPromise.status = 'rejected'\n rejectLoadPromise(e)\n }\n\n return controlledPromise\n}\n\n/**\n * Heuristically detect dynamic import \"module not found\" errors\n * across major browsers for lazy route component handling.\n */\nexport function isModuleNotFoundError(error: any): boolean {\n // chrome: \"Failed to fetch dynamically imported module: http://localhost:5173/src/routes/posts.index.tsx?tsr-split\"\n // firefox: \"error loading dynamically imported module: http://localhost:5173/src/routes/posts.index.tsx?tsr-split\"\n // safari: \"Importing a module script failed.\"\n if (typeof error?.message !== 'string') return false\n return (\n error.message.startsWith('Failed to fetch dynamically imported module') ||\n error.message.startsWith('error loading dynamically imported module') ||\n error.message.startsWith('Importing a module script failed')\n )\n}\n\nexport function isPromise<T>(\n value: Promise<Awaited<T>> | T,\n): value is Promise<Awaited<T>> {\n return Boolean(\n value &&\n typeof value === 'object' &&\n typeof (value as Promise<T>).then === 'function',\n )\n}\n\nexport function findLast<T>(\n array: ReadonlyArray<T>,\n predicate: (item: T) => boolean,\n): T | undefined {\n for (let i = array.length - 1; i >= 0; i--) {\n const item = array[i]!\n if (predicate(item)) return item\n }\n return undefined\n}\n\n/**\n * Remove control characters that can cause open redirect vulnerabilities.\n * Characters like \\r (CR) and \\n (LF) can trick URL parsers into interpreting\n * paths like \"/\\r/evil.com\" as \"http://evil.com\".\n */\nfunction sanitizePathSegment(segment: string): string {\n // Remove ASCII control characters (0x00-0x1F) and DEL (0x7F)\n // These include CR (\\r = 0x0D), LF (\\n = 0x0A), and other potentially dangerous characters\n // eslint-disable-next-line no-control-regex\n return segment.replace(/[\\x00-\\x1f\\x7f]/g, '')\n}\n\nfunction decodeSegment(segment: string): string {\n let decoded: string\n try {\n decoded = decodeURI(segment)\n } catch {\n // if the decoding fails, try to decode the various parts leaving the malformed tags in place\n decoded = segment.replaceAll(/%[0-9A-F]{2}/gi, (match) => {\n try {\n return decodeURI(match)\n } catch {\n return match\n }\n })\n }\n return sanitizePathSegment(decoded)\n}\n\n/**\n * Default list of URL protocols to allow in links, redirects, and navigation.\n * Any absolute URL protocol not in this list is treated as dangerous by default.\n */\nexport const DEFAULT_PROTOCOL_ALLOWLIST = [\n // Standard web navigation\n 'http:',\n 'https:',\n\n // Common browser-safe actions\n 'mailto:',\n 'tel:',\n]\n\n/**\n * Check if a URL string uses a protocol that is not in the allowlist.\n * Returns true for blocked protocols like javascript:, blob:, data:, etc.\n *\n * The URL constructor correctly normalizes:\n * - Mixed case (JavaScript: → javascript:)\n * - Whitespace/control characters (java\\nscript: → javascript:)\n * - Leading whitespace\n *\n * For relative URLs (no protocol), returns false (safe).\n *\n * @param url - The URL string to check\n * @param allowlist - Set of protocols to allow\n * @returns true if the URL uses a protocol that is not allowed\n */\nexport function isDangerousProtocol(\n url: string,\n allowlist: Set<string>,\n): boolean {\n if (!url) return false\n\n try {\n // Use the URL constructor - it correctly normalizes protocols\n // per WHATWG URL spec, handling all bypass attempts automatically\n const parsed = new URL(url)\n return !allowlist.has(parsed.protocol)\n } catch {\n // URL constructor throws for relative URLs (no protocol)\n // These are safe - they can't execute scripts\n return false\n }\n}\n\n// This utility is based on https://github.com/zertosh/htmlescape\n// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE\nconst HTML_ESCAPE_LOOKUP: { [match: string]: string } = {\n '&': '\\\\u0026',\n '>': '\\\\u003e',\n '<': '\\\\u003c',\n '\\u2028': '\\\\u2028',\n '\\u2029': '\\\\u2029',\n}\n\nconst HTML_ESCAPE_REGEX = /[&><\\u2028\\u2029]/g\n\n/**\n * Escape HTML special characters in a string to prevent XSS attacks\n * when embedding strings in script tags during SSR.\n *\n * This is essential for preventing XSS vulnerabilities when user-controlled\n * content is embedded in inline scripts.\n */\nexport function escapeHtml(str: string): string {\n return str.replace(HTML_ESCAPE_REGEX, (match) => HTML_ESCAPE_LOOKUP[match]!)\n}\n\nexport function decodePath(path: string) {\n if (!path) return { path, handledProtocolRelativeURL: false }\n\n // Fast path: most paths are already decoded and safe.\n // Only fall back to the slower scan/regex path when we see a '%' (encoded),\n // a backslash (explicitly handled), a control character, or a protocol-relative\n // prefix which needs collapsing.\n // eslint-disable-next-line no-control-regex\n if (!/[%\\\\\\x00-\\x1f\\x7f]/.test(path) && !path.startsWith('//')) {\n return { path, handledProtocolRelativeURL: false }\n }\n\n const re = /%25|%5C/gi\n let cursor = 0\n let result = ''\n let match\n while (null !== (match = re.exec(path))) {\n result += decodeSegment(path.slice(cursor, match.index)) + match[0]\n cursor = re.lastIndex\n }\n result = result + decodeSegment(cursor ? path.slice(cursor) : path)\n\n // Prevent open redirect via protocol-relative URLs (e.g. \"//evil.com\")\n // After sanitizing control characters, paths like \"/\\r/evil.com\" become \"//evil.com\"\n // Collapse leading double slashes to a single slash\n let handledProtocolRelativeURL = false\n if (result.startsWith('//')) {\n handledProtocolRelativeURL = true\n result = '/' + result.replace(/^\\/+/, '')\n }\n\n return { path: result, handledProtocolRelativeURL }\n}\n\n/**\n * Encodes a path the same way `new URL()` would, but without the overhead of full URL parsing.\n *\n * This function encodes:\n * - Whitespace characters (spaces → %20, tabs → %09, etc.)\n * - Non-ASCII/Unicode characters (emojis, accented characters, etc.)\n *\n * It preserves:\n * - Already percent-encoded sequences (won't double-encode %2F, %25, etc.)\n * - ASCII special characters valid in URL paths (@, $, &, +, etc.)\n * - Forward slashes as path separators\n *\n * Used to generate proper href values for SSR without constructing URL objects.\n *\n * @example\n * encodePathLikeUrl('/path/file name.pdf') // '/path/file%20name.pdf'\n * encodePathLikeUrl('/path/日本語') // '/path/%E6%97%A5%E6%9C%AC%E8%AA%9E'\n * encodePathLikeUrl('/path/already%20encoded') // '/path/already%20encoded' (preserved)\n */\nexport function encodePathLikeUrl(path: string): string {\n // Encode whitespace and non-ASCII characters that browsers encode in URLs\n\n // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional ASCII range check\n // eslint-disable-next-line no-control-regex\n if (!/\\s|[^\\u0000-\\u007F]/.test(path)) return path\n // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional ASCII range check\n // eslint-disable-next-line no-control-regex\n return path.replace(/\\s|[^\\u0000-\\u007F]/gu, encodeURIComponent)\n}\n\n/**\n * Builds the dev-mode CSS styles URL for route-scoped CSS collection.\n * Used by HeadContent components in all framework implementations to construct\n * the URL for the `/@tanstack-start/styles.css` endpoint.\n *\n * @param basepath - The router's basepath (may or may not have leading slash)\n * @param routeIds - Array of matched route IDs to include in the CSS collection\n * @returns The full URL path for the dev styles CSS endpoint\n */\nexport function buildDevStylesUrl(\n basepath: string,\n routeIds: Array<string>,\n): string {\n // Trim all leading and trailing slashes from basepath\n const trimmedBasepath = basepath.replace(/^\\/+|\\/+$/g, '')\n // Build normalized basepath: empty string for root, or '/path' for non-root\n const normalizedBasepath = trimmedBasepath === '' ? '' : `/${trimmedBasepath}`\n return `${normalizedBasepath}/@tanstack-start/styles.css?routes=${encodeURIComponent(routeIds.join(','))}`\n}\n\nexport function arraysEqual<T>(a: Array<T>, b: Array<T>) {\n if (a === b) return true\n if (a.length !== b.length) return false\n for (let i = 0; i < a.length;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version": "1.169.2",
|
|
4
4
|
"description": "Modern and scalable routing for React applications",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -167,21 +167,17 @@
|
|
|
167
167
|
"node": ">=20.19"
|
|
168
168
|
},
|
|
169
169
|
"dependencies": {
|
|
170
|
-
"cookie-es": "^
|
|
171
|
-
"seroval": "^1.4
|
|
172
|
-
"seroval-plugins": "^1.4
|
|
170
|
+
"cookie-es": "^3.0.0",
|
|
171
|
+
"seroval": "^1.5.4",
|
|
172
|
+
"seroval-plugins": "^1.5.4",
|
|
173
173
|
"@benjavicente/history": "1.161.6"
|
|
174
174
|
},
|
|
175
175
|
"devDependencies": {
|
|
176
|
-
"@tanstack/intent": "^0.0.14",
|
|
177
176
|
"@tanstack/store": "^0.9.3",
|
|
178
177
|
"@types/node": "25.0.9",
|
|
179
178
|
"esbuild": "^0.27.4",
|
|
180
179
|
"vite": "*"
|
|
181
180
|
},
|
|
182
|
-
"bin": {
|
|
183
|
-
"intent": "./bin/intent.js"
|
|
184
|
-
},
|
|
185
181
|
"scripts": {
|
|
186
182
|
"clean": "rimraf ./dist && rimraf ./coverage",
|
|
187
183
|
"test:eslint": "eslint ./src",
|
|
@@ -21,6 +21,10 @@ sources:
|
|
|
21
21
|
|
|
22
22
|
# Auth and Guards
|
|
23
23
|
|
|
24
|
+
> **This skill covers the routing side of auth.** For the **server-side primitives** — session cookies (`HttpOnly`/`Secure`/`SameSite`), `useSession`-style helpers, OAuth `state` + PKCE, password-reset enumeration defense, CSRF, rate limiting — see [start-core/auth-server-primitives](../../../../start-client-core/skills/start-core/auth-server-primitives/SKILL.md). The two skills are designed to be used together.
|
|
25
|
+
>
|
|
26
|
+
> **CRITICAL**: A route guard (`beforeLoad`) does NOT protect a `createServerFn` declared on that route. Server functions are RPC endpoints reachable by direct POST regardless of which route renders them. See "Route guards do not protect server functions" below.
|
|
27
|
+
|
|
24
28
|
## Setup
|
|
25
29
|
|
|
26
30
|
Protect routes with `beforeLoad` + `redirect()` in a pathless layout route (`_authenticated`):
|
|
@@ -371,6 +375,41 @@ export const Route = createFileRoute('/_authenticated')({
|
|
|
371
375
|
|
|
372
376
|
## Common Mistakes
|
|
373
377
|
|
|
378
|
+
### CRITICAL: Route guards do not protect server functions
|
|
379
|
+
|
|
380
|
+
A `beforeLoad` redirect protects the **route's UI**, not the **server functions** declared on it. `createServerFn` produces an RPC endpoint reachable by direct POST regardless of which route renders the calling UI. An attacker doesn't have to load `/_authenticated/orders` — they can curl the RPC endpoint directly.
|
|
381
|
+
|
|
382
|
+
```tsx
|
|
383
|
+
// WRONG — handler has no auth check; the route guard doesn't help
|
|
384
|
+
import { createServerFn } from '@benjavicente/react-start'
|
|
385
|
+
import { createFileRoute, redirect } from '@benjavicente/react-router'
|
|
386
|
+
|
|
387
|
+
const getMyOrders = createServerFn({ method: 'GET' }).handler(async () => {
|
|
388
|
+
return db.orders.findMany() // ← anyone can hit the RPC
|
|
389
|
+
})
|
|
390
|
+
|
|
391
|
+
export const Route = createFileRoute('/_authenticated/orders')({
|
|
392
|
+
beforeLoad: ({ context }) => {
|
|
393
|
+
if (!context.auth.isAuthenticated) throw redirect({ to: '/login' })
|
|
394
|
+
},
|
|
395
|
+
loader: () => getMyOrders(),
|
|
396
|
+
})
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
```tsx
|
|
400
|
+
// CORRECT — auth enforced on the handler itself, via middleware
|
|
401
|
+
import { createServerFn } from '@benjavicente/react-start'
|
|
402
|
+
import { authMiddleware } from '~/server/auth-middleware'
|
|
403
|
+
|
|
404
|
+
const getMyOrders = createServerFn({ method: 'GET' })
|
|
405
|
+
.middleware([authMiddleware])
|
|
406
|
+
.handler(async ({ context }) => {
|
|
407
|
+
return db.orders.findMany({ where: { userId: context.session.userId } })
|
|
408
|
+
})
|
|
409
|
+
```
|
|
410
|
+
|
|
411
|
+
Rule of thumb: every `createServerFn` that touches user data needs `authMiddleware` (or an equivalent in-handler check). The route guard is for the page experience; the RPC guard is for the data. See [start-core/auth-server-primitives](../../../../start-client-core/skills/start-core/auth-server-primitives/SKILL.md) for the full session/middleware pattern.
|
|
412
|
+
|
|
374
413
|
### HIGH: Auth check in component instead of beforeLoad
|
|
375
414
|
|
|
376
415
|
Component-level auth checks cause a **flash of protected content** before the redirect:
|
|
@@ -456,3 +495,5 @@ Place protected routes as children of the `_authenticated` layout route. Public
|
|
|
456
495
|
## Cross-References
|
|
457
496
|
|
|
458
497
|
- See also: **router-core/data-loading/SKILL.md** — `beforeLoad` runs before `loader`; auth context flows into loader via route context
|
|
498
|
+
- See also: **start-core/auth-server-primitives/SKILL.md** — server-side session cookies, OAuth state + PKCE, CSRF, password-reset hardening, rate limiting (the server half of authentication)
|
|
499
|
+
- See also: **start-core/middleware/SKILL.md** — `authMiddleware` factory pattern for protecting individual `createServerFn` calls
|
|
@@ -391,22 +391,74 @@ component: () => {
|
|
|
391
391
|
}
|
|
392
392
|
```
|
|
393
393
|
|
|
394
|
-
### 3. CRITICAL: Generating Next.js or
|
|
394
|
+
### 3. CRITICAL: Generating Next.js, Remix, or React Router DOM patterns
|
|
395
395
|
|
|
396
|
-
TanStack Router does NOT use `getServerSideProps`, `getStaticProps`, App Router `page.tsx`,
|
|
396
|
+
TanStack Router does NOT use `getServerSideProps`, `getStaticProps`, App Router `page.tsx`, Remix-style server-only `loader` exports, or anything from `react-router-dom`.
|
|
397
|
+
|
|
398
|
+
#### Wrong file structures
|
|
399
|
+
|
|
400
|
+
```text
|
|
401
|
+
WRONG (Next.js Pages Router):
|
|
402
|
+
src/pages/index.tsx
|
|
403
|
+
src/pages/_app.tsx
|
|
404
|
+
src/pages/posts/[id].tsx
|
|
405
|
+
|
|
406
|
+
WRONG (Next.js App Router):
|
|
407
|
+
app/layout.tsx
|
|
408
|
+
app/page.tsx
|
|
409
|
+
app/posts/[id]/page.tsx
|
|
410
|
+
|
|
411
|
+
WRONG (Next.js custom App):
|
|
412
|
+
_app/index.tsx
|
|
413
|
+
pages/_app.tsx, pages/_document.tsx
|
|
414
|
+
|
|
415
|
+
CORRECT (TanStack Router file-based routing):
|
|
416
|
+
src/routes/__root.tsx
|
|
417
|
+
src/routes/index.tsx
|
|
418
|
+
src/routes/posts/$postId.tsx
|
|
419
|
+
```
|
|
420
|
+
|
|
421
|
+
#### Wrong imports
|
|
397
422
|
|
|
398
423
|
```tsx
|
|
399
|
-
// WRONG —
|
|
424
|
+
// WRONG — react-router-dom is a different library
|
|
425
|
+
import {
|
|
426
|
+
Link,
|
|
427
|
+
useNavigate,
|
|
428
|
+
BrowserRouter,
|
|
429
|
+
Route,
|
|
430
|
+
Routes,
|
|
431
|
+
} from 'react-router-dom'
|
|
432
|
+
|
|
433
|
+
// WRONG — Next.js Link/router
|
|
434
|
+
import Link from 'next/link'
|
|
435
|
+
import { useRouter } from 'next/router' // Pages Router
|
|
436
|
+
import { useRouter } from 'next/navigation' // App Router
|
|
437
|
+
|
|
438
|
+
// CORRECT — everything routing-related lives in @benjavicente/react-router
|
|
439
|
+
import {
|
|
440
|
+
Link,
|
|
441
|
+
useNavigate,
|
|
442
|
+
useRouter,
|
|
443
|
+
useLocation,
|
|
444
|
+
redirect,
|
|
445
|
+
} from '@benjavicente/react-router'
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
#### Wrong loader/data-fetching patterns
|
|
449
|
+
|
|
450
|
+
```tsx
|
|
451
|
+
// WRONG — Next.js Pages Router
|
|
400
452
|
export async function getServerSideProps() {
|
|
401
453
|
return { props: { data: await fetchData() } }
|
|
402
454
|
}
|
|
403
455
|
|
|
404
|
-
// WRONG — Remix
|
|
456
|
+
// WRONG — Remix
|
|
405
457
|
export async function loader({ request }: LoaderFunctionArgs) {
|
|
406
458
|
return json({ data: await fetchData() })
|
|
407
459
|
}
|
|
408
460
|
|
|
409
|
-
// CORRECT — TanStack Router
|
|
461
|
+
// CORRECT — TanStack Router
|
|
410
462
|
export const Route = createFileRoute('/data')({
|
|
411
463
|
loader: async () => {
|
|
412
464
|
const data = await fetchData()
|
|
@@ -421,6 +473,8 @@ function DataPage() {
|
|
|
421
473
|
}
|
|
422
474
|
```
|
|
423
475
|
|
|
476
|
+
If you see `src/pages/`, `app/layout.tsx`, `react-router-dom`, or any of the above in agent output, the agent is generating for the wrong framework. The build will either fail or produce duplicate `/` routes that conflict at runtime.
|
|
477
|
+
|
|
424
478
|
## Tension: Client-First Loaders vs SSR
|
|
425
479
|
|
|
426
480
|
TanStack Router loaders are client-first by design. When SSR is enabled, they run in both environments. This means:
|
|
@@ -313,7 +313,9 @@ export function NavItem(props: NavItemProps): React.ReactNode {
|
|
|
313
313
|
<NavItem label="Post" linkOptions={{ to: '/posts/$postId', params: { postId: '1' } }} />
|
|
314
314
|
```
|
|
315
315
|
|
|
316
|
-
### `ValidateNavigateOptions`
|
|
316
|
+
### `ValidateNavigateOptions` and `ValidateRedirectOptions`
|
|
317
|
+
|
|
318
|
+
Same pattern as `ValidateLinkOptions` above, for `useNavigate` and `redirect`. Declare a generic public overload plus a non-generic implementation signature so the call site stays narrowed and the body works without casts:
|
|
317
319
|
|
|
318
320
|
```tsx
|
|
319
321
|
import {
|
|
@@ -332,45 +334,15 @@ export function useDelayedNavigate<
|
|
|
332
334
|
export function useDelayedNavigate(
|
|
333
335
|
options: ValidateNavigateOptions,
|
|
334
336
|
delayMs: number,
|
|
335
|
-
)
|
|
337
|
+
) {
|
|
336
338
|
const navigate = useNavigate()
|
|
337
339
|
return () => {
|
|
338
340
|
setTimeout(() => navigate(options), delayMs)
|
|
339
341
|
}
|
|
340
342
|
}
|
|
341
|
-
|
|
342
|
-
// Usage — type-safe
|
|
343
|
-
const go = useDelayedNavigate(
|
|
344
|
-
{ to: '/posts/$postId', params: { postId: '1' } },
|
|
345
|
-
500,
|
|
346
|
-
)
|
|
347
343
|
```
|
|
348
344
|
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
```tsx
|
|
352
|
-
import {
|
|
353
|
-
redirect,
|
|
354
|
-
type RegisteredRouter,
|
|
355
|
-
type ValidateRedirectOptions,
|
|
356
|
-
} from '@benjavicente/react-router'
|
|
357
|
-
|
|
358
|
-
export async function fetchOrRedirect<
|
|
359
|
-
TRouter extends RegisteredRouter = RegisteredRouter,
|
|
360
|
-
TOptions = unknown,
|
|
361
|
-
>(
|
|
362
|
-
url: string,
|
|
363
|
-
redirectOptions: ValidateRedirectOptions<TRouter, TOptions>,
|
|
364
|
-
): Promise<unknown>
|
|
365
|
-
export async function fetchOrRedirect(
|
|
366
|
-
url: string,
|
|
367
|
-
redirectOptions: ValidateRedirectOptions,
|
|
368
|
-
): Promise<unknown> {
|
|
369
|
-
const response = await fetch(url)
|
|
370
|
-
if (!response.ok && response.status === 401) throw redirect(redirectOptions)
|
|
371
|
-
return response.json()
|
|
372
|
-
}
|
|
373
|
-
```
|
|
345
|
+
`ValidateRedirectOptions` works identically — declare a generic overload accepting `ValidateRedirectOptions<TRouter, TOptions>` and an impl signature accepting `ValidateRedirectOptions`, then call `redirect(options)` in the body.
|
|
374
346
|
|
|
375
347
|
### Render Props for Maximum Performance
|
|
376
348
|
|
|
@@ -477,21 +449,44 @@ declare module '@benjavicente/react-router' {
|
|
|
477
449
|
}
|
|
478
450
|
```
|
|
479
451
|
|
|
480
|
-
### 5. CRITICAL (cross-skill):
|
|
452
|
+
### 5. CRITICAL (cross-skill): Wrong-framework imports and file structure
|
|
453
|
+
|
|
454
|
+
Wrong-framework code looks plausible (it's React) but breaks the build or produces conflicting `/` routes at runtime.
|
|
481
455
|
|
|
482
456
|
```tsx
|
|
483
|
-
// WRONG —
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
457
|
+
// WRONG — react-router-dom and next/* are different libraries
|
|
458
|
+
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
|
|
459
|
+
import Link from 'next/link'
|
|
460
|
+
import { useRouter, useParams } from 'next/navigation'
|
|
487
461
|
|
|
488
|
-
// CORRECT —
|
|
462
|
+
// CORRECT — all routing exports come from @benjavicente/react-router
|
|
463
|
+
import {
|
|
464
|
+
Link,
|
|
465
|
+
Outlet,
|
|
466
|
+
useNavigate,
|
|
467
|
+
useRouter,
|
|
468
|
+
useLocation,
|
|
469
|
+
useParams,
|
|
470
|
+
redirect,
|
|
471
|
+
} from '@benjavicente/react-router'
|
|
472
|
+
```
|
|
473
|
+
|
|
474
|
+
```tsx
|
|
475
|
+
// WRONG file structures + APIs:
|
|
476
|
+
// src/pages/*.tsx with getServerSideProps / getStaticProps (Next.js Pages Router)
|
|
477
|
+
// app/layout.tsx + app/page.tsx (Next.js App Router)
|
|
478
|
+
// _app/index.tsx, pages/_app.tsx, pages/_document.tsx (Next.js custom App)
|
|
479
|
+
// loader/action exports (Remix)
|
|
480
|
+
|
|
481
|
+
// CORRECT — TanStack file-based routing at src/routes/*.tsx
|
|
489
482
|
export const Route = createFileRoute('/posts')({
|
|
490
|
-
loader: async () => { ... },
|
|
491
|
-
validateSearch: zodValidator(schema),
|
|
483
|
+
loader: async () => { ... },
|
|
484
|
+
validateSearch: zodValidator(schema),
|
|
492
485
|
component: PostsComponent,
|
|
493
486
|
})
|
|
494
|
-
const search = Route.useSearch()
|
|
487
|
+
const search = Route.useSearch()
|
|
495
488
|
```
|
|
496
489
|
|
|
490
|
+
If a build error mentions `react-router-dom`, `next/`, `pages/_app`, or duplicate `/` routes, fix the import — don't paper over with type assertions.
|
|
491
|
+
|
|
497
492
|
See also: router-core (Register setup), router-core/navigation (from narrowing), router-core/code-splitting (getRouteApi).
|
package/src/hash-scroll.ts
CHANGED
|
@@ -7,7 +7,7 @@ import type { AnyRouter } from './router'
|
|
|
7
7
|
*/
|
|
8
8
|
export function handleHashScroll(router: AnyRouter) {
|
|
9
9
|
if (typeof document !== 'undefined' && (document as any).querySelector) {
|
|
10
|
-
const location = router.stores.location.
|
|
10
|
+
const location = router.stores.location.get()
|
|
11
11
|
const hashScrollIntoViewOptions =
|
|
12
12
|
location.state.__hashScrollIntoViewOptions ?? true
|
|
13
13
|
|
package/src/index.ts
CHANGED
|
@@ -75,7 +75,13 @@ export type {
|
|
|
75
75
|
AssetCrossOriginConfig,
|
|
76
76
|
ManifestAssetLink,
|
|
77
77
|
} from './manifest'
|
|
78
|
-
export {
|
|
78
|
+
export {
|
|
79
|
+
createInlineCssStyleAsset,
|
|
80
|
+
getAssetCrossOrigin,
|
|
81
|
+
getStylesheetHref,
|
|
82
|
+
isInlinableStylesheet,
|
|
83
|
+
resolveManifestAssetLink,
|
|
84
|
+
} from './manifest'
|
|
79
85
|
export { isMatch } from './Matches'
|
|
80
86
|
export type {
|
|
81
87
|
AnyMatchAndValue,
|
|
@@ -285,6 +291,7 @@ export type { OptionalStructuralSharing } from './structuralSharing'
|
|
|
285
291
|
|
|
286
292
|
export {
|
|
287
293
|
functionalUpdate,
|
|
294
|
+
hasKeys,
|
|
288
295
|
replaceEqualDeep,
|
|
289
296
|
isPlainObject,
|
|
290
297
|
isPlainArray,
|
|
@@ -437,7 +444,6 @@ export type {
|
|
|
437
444
|
AnySerializationAdapter,
|
|
438
445
|
SerializationAdapter,
|
|
439
446
|
ValidateSerializableInput,
|
|
440
|
-
ValidateSerializableInputResult,
|
|
441
447
|
SerializerExtensions,
|
|
442
448
|
ValidateSerializable,
|
|
443
449
|
RegisteredSerializableInput,
|
|
@@ -446,6 +452,7 @@ export type {
|
|
|
446
452
|
Serializable,
|
|
447
453
|
TSR_SERIALIZABLE,
|
|
448
454
|
TsrSerializable,
|
|
455
|
+
SerializationError,
|
|
449
456
|
} from './ssr/serializer/transformer'
|
|
450
457
|
|
|
451
458
|
export {
|
package/src/load-matches.ts
CHANGED
|
@@ -45,15 +45,13 @@ const triggerOnReady = (inner: InnerLoadContext): void | Promise<void> => {
|
|
|
45
45
|
}
|
|
46
46
|
|
|
47
47
|
const hasForcePendingActiveMatch = (router: AnyRouter): boolean => {
|
|
48
|
-
return router.stores.matchesId.
|
|
49
|
-
return router.stores.
|
|
48
|
+
return router.stores.matchesId.get().some((matchId) => {
|
|
49
|
+
return router.stores.matchStores.get(matchId)?.get()._forcePending
|
|
50
50
|
})
|
|
51
51
|
}
|
|
52
52
|
|
|
53
53
|
const resolvePreload = (inner: InnerLoadContext, matchId: string): boolean => {
|
|
54
|
-
return !!(
|
|
55
|
-
inner.preload && !inner.router.stores.activeMatchStoresById.has(matchId)
|
|
56
|
-
)
|
|
54
|
+
return !!(inner.preload && !inner.router.stores.matchStores.has(matchId))
|
|
57
55
|
}
|
|
58
56
|
|
|
59
57
|
/**
|
|
@@ -138,9 +136,11 @@ const handleRedirectAndNotFound = (
|
|
|
138
136
|
...prev,
|
|
139
137
|
status: isRedirect(err)
|
|
140
138
|
? 'redirected'
|
|
141
|
-
:
|
|
142
|
-
? '
|
|
143
|
-
: prev.status
|
|
139
|
+
: isNotFound(err)
|
|
140
|
+
? 'notFound'
|
|
141
|
+
: prev.status === 'pending'
|
|
142
|
+
? 'success'
|
|
143
|
+
: prev.status,
|
|
144
144
|
context: buildMatchContext(inner, match.index),
|
|
145
145
|
isFetching: false,
|
|
146
146
|
error: err,
|
|
@@ -713,7 +713,7 @@ const runLoader = async (
|
|
|
713
713
|
const pendingPromise = match._nonReactive.minPendingPromise
|
|
714
714
|
if (pendingPromise) await pendingPromise
|
|
715
715
|
|
|
716
|
-
// Last but not least, wait for the
|
|
716
|
+
// Last but not least, wait for the components
|
|
717
717
|
// to be preloaded before we resolve the match
|
|
718
718
|
if (route._componentsPromise) await route._componentsPromise
|
|
719
719
|
inner.updateMatch(matchId, (prev) => ({
|
|
@@ -879,17 +879,16 @@ const loadRouteMatch = async (
|
|
|
879
879
|
}
|
|
880
880
|
} else {
|
|
881
881
|
const prevMatch = inner.router.getMatch(matchId)! // This is where all of the stale-while-revalidate magic happens
|
|
882
|
-
const activeIdAtIndex = inner.router.stores.matchesId.
|
|
882
|
+
const activeIdAtIndex = inner.router.stores.matchesId.get()[index]
|
|
883
883
|
const activeAtIndex =
|
|
884
884
|
(activeIdAtIndex &&
|
|
885
|
-
inner.router.stores.
|
|
885
|
+
inner.router.stores.matchStores.get(activeIdAtIndex)) ||
|
|
886
886
|
null
|
|
887
887
|
const previousRouteMatchId =
|
|
888
888
|
activeAtIndex?.routeId === routeId
|
|
889
889
|
? activeIdAtIndex
|
|
890
|
-
: inner.router.stores.
|
|
891
|
-
|
|
892
|
-
)?.id
|
|
890
|
+
: inner.router.stores.matches.get().find((d) => d.routeId === routeId)
|
|
891
|
+
?.id
|
|
893
892
|
const preload = resolvePreload(inner, matchId)
|
|
894
893
|
|
|
895
894
|
// there is a loaderPromise, so we are in the middle of a load
|
|
@@ -923,7 +922,7 @@ const loadRouteMatch = async (
|
|
|
923
922
|
}
|
|
924
923
|
} else {
|
|
925
924
|
const nextPreload =
|
|
926
|
-
preload && !inner.router.stores.
|
|
925
|
+
preload && !inner.router.stores.matchStores.has(matchId)
|
|
927
926
|
const match = inner.router.getMatch(matchId)!
|
|
928
927
|
match._nonReactive.loaderPromise = createControlledPromise<void>()
|
|
929
928
|
if (nextPreload !== match.preload) {
|
package/src/manifest.ts
CHANGED
|
@@ -35,6 +35,9 @@ export function resolveManifestAssetLink(link: ManifestAssetLink) {
|
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
export type Manifest = {
|
|
38
|
+
inlineCss?: {
|
|
39
|
+
styles: Record<string, string>
|
|
40
|
+
}
|
|
38
41
|
routes: Record<
|
|
39
42
|
string,
|
|
40
43
|
{
|
|
@@ -65,4 +68,47 @@ export type RouterManagedTag =
|
|
|
65
68
|
tag: 'style'
|
|
66
69
|
attrs?: Record<string, any>
|
|
67
70
|
children?: string
|
|
71
|
+
inlineCss?: true
|
|
68
72
|
}
|
|
73
|
+
|
|
74
|
+
export function getStylesheetHref(asset: RouterManagedTag) {
|
|
75
|
+
if (asset.tag !== 'link') return undefined
|
|
76
|
+
|
|
77
|
+
const rel = asset.attrs?.rel
|
|
78
|
+
const href = asset.attrs?.href
|
|
79
|
+
if (typeof href !== 'string') return undefined
|
|
80
|
+
|
|
81
|
+
const relTokens = typeof rel === 'string' ? rel.split(/\s+/) : []
|
|
82
|
+
if (!relTokens.includes('stylesheet')) return undefined
|
|
83
|
+
|
|
84
|
+
return href
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function isInlinableStylesheet(
|
|
88
|
+
manifest: Manifest | undefined,
|
|
89
|
+
asset: RouterManagedTag,
|
|
90
|
+
) {
|
|
91
|
+
const href = getStylesheetHref(asset)
|
|
92
|
+
return !!href && manifest?.inlineCss?.styles[href] !== undefined
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function createInlineCssStyleAsset(css: string): RouterManagedTag {
|
|
96
|
+
return {
|
|
97
|
+
tag: 'style',
|
|
98
|
+
attrs: {
|
|
99
|
+
suppressHydrationWarning: true,
|
|
100
|
+
},
|
|
101
|
+
inlineCss: true,
|
|
102
|
+
children: css,
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function createInlineCssPlaceholderAsset(): RouterManagedTag {
|
|
107
|
+
return {
|
|
108
|
+
tag: 'style',
|
|
109
|
+
attrs: {
|
|
110
|
+
suppressHydrationWarning: true,
|
|
111
|
+
},
|
|
112
|
+
inlineCss: true,
|
|
113
|
+
}
|
|
114
|
+
}
|