@tanstack/router-core 0.0.1-beta.9 → 1.20.3-alpha.1

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.
Files changed (194) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +5 -0
  3. package/dist/cjs/Matches.cjs +13 -0
  4. package/dist/cjs/Matches.cjs.map +1 -0
  5. package/dist/cjs/Matches.d.cts +109 -0
  6. package/dist/cjs/RouterProvider.d.cts +26 -0
  7. package/dist/cjs/defer.cjs +25 -0
  8. package/dist/cjs/defer.cjs.map +1 -0
  9. package/dist/cjs/defer.d.cts +20 -0
  10. package/dist/cjs/fileRoute.d.cts +23 -0
  11. package/dist/cjs/history.d.cts +8 -0
  12. package/dist/cjs/index.cjs +80 -0
  13. package/dist/cjs/index.cjs.map +1 -0
  14. package/dist/cjs/index.d.cts +41 -0
  15. package/dist/cjs/link.cjs +5 -0
  16. package/dist/cjs/link.cjs.map +1 -0
  17. package/dist/cjs/link.d.cts +200 -0
  18. package/dist/cjs/location.d.cts +12 -0
  19. package/dist/cjs/manifest.d.cts +24 -0
  20. package/dist/cjs/not-found.cjs +13 -0
  21. package/dist/cjs/not-found.cjs.map +1 -0
  22. package/dist/cjs/not-found.d.cts +20 -0
  23. package/dist/cjs/path.cjs +412 -0
  24. package/dist/cjs/path.cjs.map +1 -0
  25. package/dist/cjs/path.d.cts +56 -0
  26. package/dist/cjs/qss.cjs +38 -0
  27. package/dist/cjs/qss.cjs.map +1 -0
  28. package/dist/cjs/qss.d.cts +22 -0
  29. package/dist/cjs/redirect.cjs +34 -0
  30. package/dist/cjs/redirect.cjs.map +1 -0
  31. package/dist/cjs/redirect.d.cts +38 -0
  32. package/dist/cjs/root.cjs +5 -0
  33. package/dist/cjs/root.cjs.map +1 -0
  34. package/dist/cjs/root.d.cts +2 -0
  35. package/dist/cjs/route.cjs +119 -0
  36. package/dist/cjs/route.cjs.map +1 -0
  37. package/dist/cjs/route.d.cts +422 -0
  38. package/dist/cjs/routeInfo.d.cts +54 -0
  39. package/dist/cjs/router.cjs +1800 -0
  40. package/dist/cjs/router.cjs.map +1 -0
  41. package/dist/cjs/router.d.cts +630 -0
  42. package/dist/cjs/scroll-restoration.cjs +196 -0
  43. package/dist/cjs/scroll-restoration.cjs.map +1 -0
  44. package/dist/cjs/scroll-restoration.d.cts +38 -0
  45. package/dist/cjs/searchMiddleware.cjs +42 -0
  46. package/dist/cjs/searchMiddleware.cjs.map +1 -0
  47. package/dist/cjs/searchMiddleware.d.cts +5 -0
  48. package/dist/cjs/searchParams.cjs +61 -0
  49. package/dist/cjs/searchParams.cjs.map +1 -0
  50. package/dist/cjs/searchParams.d.cts +7 -0
  51. package/dist/cjs/serializer.d.cts +22 -0
  52. package/dist/cjs/structuralSharing.d.cts +4 -0
  53. package/dist/cjs/typePrimitives.d.cts +65 -0
  54. package/dist/cjs/useLoaderData.d.cts +5 -0
  55. package/dist/cjs/useLoaderDeps.d.cts +5 -0
  56. package/dist/cjs/useNavigate.d.cts +3 -0
  57. package/dist/cjs/useParams.d.cts +5 -0
  58. package/dist/cjs/useRouteContext.d.cts +9 -0
  59. package/dist/cjs/useSearch.d.cts +5 -0
  60. package/dist/cjs/utils.cjs +160 -0
  61. package/dist/cjs/utils.cjs.map +1 -0
  62. package/dist/cjs/utils.d.cts +105 -0
  63. package/dist/cjs/validators.d.cts +51 -0
  64. package/dist/esm/Matches.d.ts +109 -0
  65. package/dist/esm/Matches.js +13 -0
  66. package/dist/esm/Matches.js.map +1 -0
  67. package/dist/esm/RouterProvider.d.ts +26 -0
  68. package/dist/esm/defer.d.ts +20 -0
  69. package/dist/esm/defer.js +25 -0
  70. package/dist/esm/defer.js.map +1 -0
  71. package/dist/esm/fileRoute.d.ts +23 -0
  72. package/dist/esm/history.d.ts +8 -0
  73. package/dist/esm/index.d.ts +41 -0
  74. package/dist/esm/index.js +80 -0
  75. package/dist/esm/index.js.map +1 -0
  76. package/dist/esm/link.d.ts +200 -0
  77. package/dist/esm/link.js +5 -0
  78. package/dist/esm/link.js.map +1 -0
  79. package/dist/esm/location.d.ts +12 -0
  80. package/dist/esm/manifest.d.ts +24 -0
  81. package/dist/esm/not-found.d.ts +20 -0
  82. package/dist/esm/not-found.js +13 -0
  83. package/dist/esm/not-found.js.map +1 -0
  84. package/dist/esm/path.d.ts +56 -0
  85. package/dist/esm/path.js +412 -0
  86. package/dist/esm/path.js.map +1 -0
  87. package/dist/esm/qss.d.ts +22 -0
  88. package/dist/esm/qss.js +38 -0
  89. package/dist/esm/qss.js.map +1 -0
  90. package/dist/esm/redirect.d.ts +38 -0
  91. package/dist/esm/redirect.js +34 -0
  92. package/dist/esm/redirect.js.map +1 -0
  93. package/dist/esm/root.d.ts +2 -0
  94. package/dist/esm/root.js +5 -0
  95. package/dist/esm/root.js.map +1 -0
  96. package/dist/esm/route.d.ts +422 -0
  97. package/dist/esm/route.js +119 -0
  98. package/dist/esm/route.js.map +1 -0
  99. package/dist/esm/routeInfo.d.ts +54 -0
  100. package/dist/esm/router.d.ts +630 -0
  101. package/dist/esm/router.js +1800 -0
  102. package/dist/esm/router.js.map +1 -0
  103. package/dist/esm/scroll-restoration.d.ts +38 -0
  104. package/dist/esm/scroll-restoration.js +196 -0
  105. package/dist/esm/scroll-restoration.js.map +1 -0
  106. package/dist/esm/searchMiddleware.d.ts +5 -0
  107. package/dist/esm/searchMiddleware.js +42 -0
  108. package/dist/esm/searchMiddleware.js.map +1 -0
  109. package/dist/esm/searchParams.d.ts +7 -0
  110. package/dist/esm/searchParams.js +61 -0
  111. package/dist/esm/searchParams.js.map +1 -0
  112. package/dist/esm/serializer.d.ts +22 -0
  113. package/dist/esm/structuralSharing.d.ts +4 -0
  114. package/dist/esm/typePrimitives.d.ts +65 -0
  115. package/dist/esm/useLoaderData.d.ts +5 -0
  116. package/dist/esm/useLoaderDeps.d.ts +5 -0
  117. package/dist/esm/useNavigate.d.ts +3 -0
  118. package/dist/esm/useParams.d.ts +5 -0
  119. package/dist/esm/useRouteContext.d.ts +9 -0
  120. package/dist/esm/useSearch.d.ts +5 -0
  121. package/dist/esm/utils.d.ts +105 -0
  122. package/dist/esm/utils.js +160 -0
  123. package/dist/esm/utils.js.map +1 -0
  124. package/dist/esm/validators.d.ts +51 -0
  125. package/package.json +36 -32
  126. package/src/Matches.ts +239 -0
  127. package/src/RouterProvider.ts +50 -0
  128. package/src/defer.ts +52 -0
  129. package/src/fileRoute.ts +140 -0
  130. package/src/history.ts +9 -0
  131. package/src/index.ts +421 -19
  132. package/src/link.ts +580 -286
  133. package/src/location.ts +13 -0
  134. package/src/manifest.ts +32 -0
  135. package/src/not-found.ts +29 -0
  136. package/src/path.ts +425 -49
  137. package/src/qss.ts +70 -41
  138. package/src/redirect.ts +100 -0
  139. package/src/root.ts +2 -0
  140. package/src/route.ts +1682 -218
  141. package/src/routeInfo.ts +224 -217
  142. package/src/router.ts +3100 -1073
  143. package/src/scroll-restoration.ts +340 -0
  144. package/src/searchMiddleware.ts +54 -0
  145. package/src/searchParams.ts +43 -20
  146. package/src/serializer.ts +32 -0
  147. package/src/structuralSharing.ts +7 -0
  148. package/src/typePrimitives.ts +181 -0
  149. package/src/useLoaderData.ts +20 -0
  150. package/src/useLoaderDeps.ts +13 -0
  151. package/src/useNavigate.ts +13 -0
  152. package/src/useParams.ts +20 -0
  153. package/src/useRouteContext.ts +39 -0
  154. package/src/useSearch.ts +20 -0
  155. package/src/utils.ts +369 -75
  156. package/src/validators.ts +121 -0
  157. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js +0 -33
  158. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js.map +0 -1
  159. package/build/cjs/node_modules/@babel/runtime/helpers/esm/extends.js +0 -33
  160. package/build/cjs/node_modules/@babel/runtime/helpers/esm/extends.js.map +0 -1
  161. package/build/cjs/node_modules/history/index.js +0 -815
  162. package/build/cjs/node_modules/history/index.js.map +0 -1
  163. package/build/cjs/node_modules/tiny-invariant/dist/esm/tiny-invariant.js +0 -30
  164. package/build/cjs/node_modules/tiny-invariant/dist/esm/tiny-invariant.js.map +0 -1
  165. package/build/cjs/packages/router-core/src/index.js +0 -58
  166. package/build/cjs/packages/router-core/src/index.js.map +0 -1
  167. package/build/cjs/packages/router-core/src/path.js +0 -222
  168. package/build/cjs/packages/router-core/src/path.js.map +0 -1
  169. package/build/cjs/packages/router-core/src/qss.js +0 -71
  170. package/build/cjs/packages/router-core/src/qss.js.map +0 -1
  171. package/build/cjs/packages/router-core/src/route.js +0 -150
  172. package/build/cjs/packages/router-core/src/route.js.map +0 -1
  173. package/build/cjs/packages/router-core/src/routeConfig.js +0 -69
  174. package/build/cjs/packages/router-core/src/routeConfig.js.map +0 -1
  175. package/build/cjs/packages/router-core/src/routeMatch.js +0 -266
  176. package/build/cjs/packages/router-core/src/routeMatch.js.map +0 -1
  177. package/build/cjs/packages/router-core/src/router.js +0 -822
  178. package/build/cjs/packages/router-core/src/router.js.map +0 -1
  179. package/build/cjs/packages/router-core/src/searchParams.js +0 -70
  180. package/build/cjs/packages/router-core/src/searchParams.js.map +0 -1
  181. package/build/cjs/packages/router-core/src/utils.js +0 -125
  182. package/build/cjs/packages/router-core/src/utils.js.map +0 -1
  183. package/build/esm/index.js +0 -2481
  184. package/build/esm/index.js.map +0 -1
  185. package/build/stats-html.html +0 -4034
  186. package/build/stats-react.json +0 -493
  187. package/build/types/index.d.ts +0 -618
  188. package/build/umd/index.development.js +0 -2514
  189. package/build/umd/index.development.js.map +0 -1
  190. package/build/umd/index.production.js +0 -12
  191. package/build/umd/index.production.js.map +0 -1
  192. package/src/frameworks.ts +0 -12
  193. package/src/routeConfig.ts +0 -495
  194. package/src/routeMatch.ts +0 -374
@@ -0,0 +1,340 @@
1
+ import { functionalUpdate } from './utils'
2
+ import type { AnyRouter } from './router'
3
+ import type { ParsedLocation } from './location'
4
+ import type { NonNullableUpdater } from './utils'
5
+
6
+ export type ScrollRestorationEntry = { scrollX: number; scrollY: number }
7
+
8
+ export type ScrollRestorationByElement = Record<string, ScrollRestorationEntry>
9
+
10
+ export type ScrollRestorationByKey = Record<string, ScrollRestorationByElement>
11
+
12
+ export type ScrollRestorationCache = {
13
+ state: ScrollRestorationByKey
14
+ set: (updater: NonNullableUpdater<ScrollRestorationByKey>) => void
15
+ }
16
+ export type ScrollRestorationOptions = {
17
+ getKey?: (location: ParsedLocation) => string
18
+ scrollBehavior?: ScrollToOptions['behavior']
19
+ }
20
+
21
+ export const storageKey = 'tsr-scroll-restoration-v1_3'
22
+ let sessionsStorage = false
23
+ try {
24
+ sessionsStorage =
25
+ typeof window !== 'undefined' && typeof window.sessionStorage === 'object'
26
+ } catch {}
27
+ const throttle = (fn: (...args: Array<any>) => void, wait: number) => {
28
+ let timeout: any
29
+ return (...args: Array<any>) => {
30
+ if (!timeout) {
31
+ timeout = setTimeout(() => {
32
+ fn(...args)
33
+ timeout = null
34
+ }, wait)
35
+ }
36
+ }
37
+ }
38
+ export const scrollRestorationCache: ScrollRestorationCache = sessionsStorage
39
+ ? (() => {
40
+ const state: ScrollRestorationByKey =
41
+ JSON.parse(window.sessionStorage.getItem(storageKey) || 'null') || {}
42
+
43
+ return {
44
+ state,
45
+ // This setter is simply to make sure that we set the sessionStorage right
46
+ // after the state is updated. It doesn't necessarily need to be a functional
47
+ // update.
48
+ set: (updater) => (
49
+ (scrollRestorationCache.state =
50
+ functionalUpdate(updater, scrollRestorationCache.state) ||
51
+ scrollRestorationCache.state),
52
+ window.sessionStorage.setItem(
53
+ storageKey,
54
+ JSON.stringify(scrollRestorationCache.state),
55
+ )
56
+ ),
57
+ }
58
+ })()
59
+ : (undefined as any)
60
+ /**
61
+ * The default `getKey` function for `useScrollRestoration`.
62
+ * It returns the `key` from the location state or the `href` of the location.
63
+ *
64
+ * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.
65
+ */
66
+
67
+ export const defaultGetScrollRestorationKey = (location: ParsedLocation) => {
68
+ return location.state.key! || location.href
69
+ }
70
+
71
+ export function getCssSelector(el: any): string {
72
+ const path = []
73
+ let parent
74
+ while ((parent = el.parentNode)) {
75
+ path.unshift(
76
+ `${el.tagName}:nth-child(${([].indexOf as any).call(parent.children, el) + 1})`,
77
+ )
78
+ el = parent
79
+ }
80
+ return `${path.join(' > ')}`.toLowerCase()
81
+ }
82
+
83
+ let ignoreScroll = false
84
+
85
+ // NOTE: This function must remain pure and not use any outside variables
86
+ // unless they are passed in as arguments. Why? Because we need to be able to
87
+ // toString() it into a script tag to execute as early as possible in the browser
88
+ // during SSR. Additionally, we also call it from within the router lifecycle
89
+ export function restoreScroll(
90
+ storageKey: string,
91
+ key: string | undefined,
92
+ behavior: ScrollToOptions['behavior'] | undefined,
93
+ shouldScrollRestoration: boolean | undefined,
94
+ scrollToTopSelectors: Array<string> | undefined,
95
+ ) {
96
+ let byKey: ScrollRestorationByKey
97
+
98
+ try {
99
+ byKey = JSON.parse(sessionStorage.getItem(storageKey) || '{}')
100
+ } catch (error: any) {
101
+ console.error(error)
102
+ return
103
+ }
104
+
105
+ const resolvedKey = key || window.history.state?.key
106
+ const elementEntries = byKey[resolvedKey]
107
+
108
+ //
109
+ ignoreScroll = true
110
+
111
+ //
112
+ ;(() => {
113
+ // If we have a cached entry for this location state,
114
+ // we always need to prefer that over the hash scroll.
115
+ if (shouldScrollRestoration && elementEntries) {
116
+ for (const elementSelector in elementEntries) {
117
+ const entry = elementEntries[elementSelector]!
118
+ if (elementSelector === 'window') {
119
+ window.scrollTo({
120
+ top: entry.scrollY,
121
+ left: entry.scrollX,
122
+ behavior,
123
+ })
124
+ } else if (elementSelector) {
125
+ const element = document.querySelector(elementSelector)
126
+ if (element) {
127
+ element.scrollLeft = entry.scrollX
128
+ element.scrollTop = entry.scrollY
129
+ }
130
+ }
131
+ }
132
+
133
+ return
134
+ }
135
+
136
+ // If we don't have a cached entry for the hash,
137
+ // Which means we've never seen this location before,
138
+ // we need to check if there is a hash in the URL.
139
+ // If there is, we need to scroll it's ID into view.
140
+ const hash = window.location.hash.split('#')[1]
141
+
142
+ if (hash) {
143
+ const hashScrollIntoViewOptions =
144
+ (window.history.state || {}).__hashScrollIntoViewOptions ?? true
145
+
146
+ if (hashScrollIntoViewOptions) {
147
+ const el = document.getElementById(hash)
148
+ if (el) {
149
+ el.scrollIntoView(hashScrollIntoViewOptions)
150
+ }
151
+ }
152
+
153
+ return
154
+ }
155
+
156
+ // If there is no cached entry for the hash and there is no hash in the URL,
157
+ // we need to scroll to the top of the page for every scrollToTop element
158
+ ;[
159
+ 'window',
160
+ ...(scrollToTopSelectors?.filter((d) => d !== 'window') ?? []),
161
+ ].forEach((selector) => {
162
+ const element =
163
+ selector === 'window' ? window : document.querySelector(selector)
164
+ if (element) {
165
+ element.scrollTo({
166
+ top: 0,
167
+ left: 0,
168
+ behavior,
169
+ })
170
+ }
171
+ })
172
+ })()
173
+
174
+ //
175
+ ignoreScroll = false
176
+ }
177
+
178
+ export function setupScrollRestoration(router: AnyRouter, force?: boolean) {
179
+ const shouldScrollRestoration =
180
+ force ?? router.options.scrollRestoration ?? false
181
+
182
+ if (shouldScrollRestoration) {
183
+ router.isScrollRestoring = true
184
+ }
185
+
186
+ if (typeof document === 'undefined' || router.isScrollRestorationSetup) {
187
+ return
188
+ }
189
+
190
+ router.isScrollRestorationSetup = true
191
+
192
+ //
193
+ ignoreScroll = false
194
+
195
+ const getKey =
196
+ router.options.getScrollRestorationKey || defaultGetScrollRestorationKey
197
+
198
+ window.history.scrollRestoration = 'manual'
199
+
200
+ // // Create a MutationObserver to monitor DOM changes
201
+ // const mutationObserver = new MutationObserver(() => {
202
+ // ;ignoreScroll = true
203
+ // requestAnimationFrame(() => {
204
+ // ;ignoreScroll = false
205
+
206
+ // // Attempt to restore scroll position on each dom
207
+ // // mutation until the user scrolls. We do this
208
+ // // because dynamic content may come in at different
209
+ // // ticks after the initial render and we want to
210
+ // // keep up with that content as much as possible.
211
+ // // As soon as the user scrolls, we no longer need
212
+ // // to attempt router.
213
+ // // console.log('mutation observer restoreScroll')
214
+ // restoreScroll(
215
+ // storageKey,
216
+ // getKey(router.state.location),
217
+ // router.options.scrollRestorationBehavior,
218
+ // )
219
+ // })
220
+ // })
221
+
222
+ // const observeDom = () => {
223
+ // // Observe changes to the entire document
224
+ // mutationObserver.observe(document, {
225
+ // childList: true, // Detect added or removed child nodes
226
+ // subtree: true, // Monitor all descendants
227
+ // characterData: true, // Detect text content changes
228
+ // })
229
+ // }
230
+
231
+ // const unobserveDom = () => {
232
+ // mutationObserver.disconnect()
233
+ // }
234
+
235
+ // observeDom()
236
+
237
+ const onScroll = (event: Event) => {
238
+ // unobserveDom()
239
+
240
+ if (ignoreScroll || !router.isScrollRestoring) {
241
+ return
242
+ }
243
+
244
+ let elementSelector = ''
245
+
246
+ if (event.target === document || event.target === window) {
247
+ elementSelector = 'window'
248
+ } else {
249
+ const attrId = (event.target as Element).getAttribute(
250
+ 'data-scroll-restoration-id',
251
+ )
252
+
253
+ if (attrId) {
254
+ elementSelector = `[data-scroll-restoration-id="${attrId}"]`
255
+ } else {
256
+ elementSelector = getCssSelector(event.target)
257
+ }
258
+ }
259
+
260
+ const restoreKey = getKey(router.state.location)
261
+
262
+ scrollRestorationCache.set((state) => {
263
+ const keyEntry = (state[restoreKey] =
264
+ state[restoreKey] || ({} as ScrollRestorationByElement))
265
+
266
+ const elementEntry = (keyEntry[elementSelector] =
267
+ keyEntry[elementSelector] || ({} as ScrollRestorationEntry))
268
+
269
+ if (elementSelector === 'window') {
270
+ elementEntry.scrollX = window.scrollX || 0
271
+ elementEntry.scrollY = window.scrollY || 0
272
+ } else if (elementSelector) {
273
+ const element = document.querySelector(elementSelector)
274
+ if (element) {
275
+ elementEntry.scrollX = element.scrollLeft || 0
276
+ elementEntry.scrollY = element.scrollTop || 0
277
+ }
278
+ }
279
+
280
+ return state
281
+ })
282
+ }
283
+
284
+ // Throttle the scroll event to avoid excessive updates
285
+ if (typeof document !== 'undefined') {
286
+ document.addEventListener('scroll', throttle(onScroll, 100), true)
287
+ }
288
+
289
+ router.subscribe('onRendered', (event) => {
290
+ // unobserveDom()
291
+
292
+ const cacheKey = getKey(event.toLocation)
293
+
294
+ // If the user doesn't want to restore the scroll position,
295
+ // we don't need to do anything.
296
+ if (!router.resetNextScroll) {
297
+ router.resetNextScroll = true
298
+ return
299
+ }
300
+
301
+ restoreScroll(
302
+ storageKey,
303
+ cacheKey,
304
+ router.options.scrollRestorationBehavior || undefined,
305
+ router.isScrollRestoring || undefined,
306
+ router.options.scrollToTopSelectors || undefined,
307
+ )
308
+
309
+ if (router.isScrollRestoring) {
310
+ // Mark the location as having been seen
311
+ scrollRestorationCache.set((state) => {
312
+ state[cacheKey] = state[cacheKey] || ({} as ScrollRestorationByElement)
313
+
314
+ return state
315
+ })
316
+ }
317
+ })
318
+ }
319
+
320
+ /**
321
+ * @internal
322
+ * Handles hash-based scrolling after navigation completes.
323
+ * To be used in framework-specific <Transitioner> components during the onResolved event.
324
+ *
325
+ * Provides hash scrolling for programmatic navigation when default browser handling is prevented.
326
+ * @param router The router instance containing current location and state
327
+ */
328
+ export function handleHashScroll(router: AnyRouter) {
329
+ if (typeof document !== 'undefined' && (document as any).querySelector) {
330
+ const hashScrollIntoViewOptions =
331
+ router.state.location.state.__hashScrollIntoViewOptions ?? true
332
+
333
+ if (hashScrollIntoViewOptions && router.state.location.hash !== '') {
334
+ const el = document.getElementById(router.state.location.hash)
335
+ if (el) {
336
+ el.scrollIntoView(hashScrollIntoViewOptions)
337
+ }
338
+ }
339
+ }
340
+ }
@@ -0,0 +1,54 @@
1
+ import { deepEqual } from './utils'
2
+ import type { NoInfer, PickOptional } from './utils'
3
+ import type { SearchMiddleware } from './route'
4
+ import type { IsRequiredParams } from './link'
5
+
6
+ export function retainSearchParams<TSearchSchema extends object>(
7
+ keys: Array<keyof TSearchSchema> | true,
8
+ ): SearchMiddleware<TSearchSchema> {
9
+ return ({ search, next }) => {
10
+ const result = next(search)
11
+ if (keys === true) {
12
+ return { ...search, ...result }
13
+ }
14
+ // add missing keys from search to result
15
+ keys.forEach((key) => {
16
+ if (!(key in result)) {
17
+ result[key] = search[key]
18
+ }
19
+ })
20
+ return result
21
+ }
22
+ }
23
+
24
+ export function stripSearchParams<
25
+ TSearchSchema,
26
+ TOptionalProps = PickOptional<NoInfer<TSearchSchema>>,
27
+ const TValues =
28
+ | Partial<NoInfer<TOptionalProps>>
29
+ | Array<keyof TOptionalProps>,
30
+ const TInput = IsRequiredParams<TSearchSchema> extends never
31
+ ? TValues | true
32
+ : TValues,
33
+ >(input: NoInfer<TInput>): SearchMiddleware<TSearchSchema> {
34
+ return ({ search, next }) => {
35
+ if (input === true) {
36
+ return {}
37
+ }
38
+ const result = next(search) as Record<string, unknown>
39
+ if (Array.isArray(input)) {
40
+ input.forEach((key) => {
41
+ delete result[key]
42
+ })
43
+ } else {
44
+ Object.entries(input as Record<string, unknown>).forEach(
45
+ ([key, value]) => {
46
+ if (deepEqual(result[key], value)) {
47
+ delete result[key]
48
+ }
49
+ },
50
+ )
51
+ }
52
+ return result as any
53
+ }
54
+ }
@@ -1,19 +1,22 @@
1
1
  import { decode, encode } from './qss'
2
- import { AnySearchSchema } from './routeConfig'
2
+ import type { AnySchema } from './validators'
3
3
 
4
4
  export const defaultParseSearch = parseSearchWith(JSON.parse)
5
- export const defaultStringifySearch = stringifySearchWith(JSON.stringify)
5
+ export const defaultStringifySearch = stringifySearchWith(
6
+ JSON.stringify,
7
+ JSON.parse,
8
+ )
6
9
 
7
10
  export function parseSearchWith(parser: (str: string) => any) {
8
- return (searchStr: string): AnySearchSchema => {
11
+ return (searchStr: string): AnySchema => {
9
12
  if (searchStr.substring(0, 1) === '?') {
10
13
  searchStr = searchStr.substring(1)
11
14
  }
12
15
 
13
- let query: Record<string, unknown> = decode(searchStr)
16
+ const query: Record<string, unknown> = decode(searchStr)
14
17
 
15
18
  // Try to parse any query params that might be json
16
- for (let key in query) {
19
+ for (const key in query) {
17
20
  const value = query[key]
18
21
  if (typeof value === 'string') {
19
22
  try {
@@ -28,27 +31,47 @@ export function parseSearchWith(parser: (str: string) => any) {
28
31
  }
29
32
  }
30
33
 
31
- export function stringifySearchWith(stringify: (search: any) => string) {
34
+ export function stringifySearchWith(
35
+ stringify: (search: any) => string,
36
+ parser?: (str: string) => any,
37
+ ) {
38
+ function stringifyValue(val: any) {
39
+ if (typeof val === 'object' && val !== null) {
40
+ try {
41
+ return stringify(val)
42
+ } catch (err) {
43
+ // silent
44
+ }
45
+ } else if (typeof val === 'string' && typeof parser === 'function') {
46
+ try {
47
+ // Check if it's a valid parseable string.
48
+ // If it is, then stringify it again.
49
+ parser(val)
50
+ return stringify(val)
51
+ } catch (err) {
52
+ // silent
53
+ }
54
+ }
55
+ return val
56
+ }
57
+
32
58
  return (search: Record<string, any>) => {
33
59
  search = { ...search }
34
60
 
35
- if (search) {
36
- Object.keys(search).forEach((key) => {
37
- const val = search[key]
38
- if (typeof val === 'undefined' || val === undefined) {
39
- delete search[key]
40
- } else if (val && typeof val === 'object' && val !== null) {
41
- try {
42
- search[key] = stringify(val)
43
- } catch (err) {
44
- // silent
45
- }
46
- }
47
- })
48
- }
61
+ Object.keys(search).forEach((key) => {
62
+ const val = search[key]
63
+ if (typeof val === 'undefined' || val === undefined) {
64
+ delete search[key]
65
+ } else {
66
+ search[key] = stringifyValue(val)
67
+ }
68
+ })
49
69
 
50
70
  const searchStr = encode(search as Record<string, string>).toString()
51
71
 
52
72
  return searchStr ? `?${searchStr}` : ''
53
73
  }
54
74
  }
75
+
76
+ export type SearchSerializer = (searchObj: Record<string, any>) => string
77
+ export type SearchParser = (searchStr: string) => Record<string, any>
@@ -0,0 +1,32 @@
1
+ export interface StartSerializer {
2
+ stringify: (obj: unknown) => string
3
+ parse: (str: string) => unknown
4
+ encode: <T>(value: T) => T
5
+ decode: <T>(value: T) => T
6
+ }
7
+
8
+ export type SerializerStringifyBy<T, TSerializable> = T extends TSerializable
9
+ ? T
10
+ : T extends (...args: Array<any>) => any
11
+ ? 'Function is not serializable'
12
+ : { [K in keyof T]: SerializerStringifyBy<T[K], TSerializable> }
13
+
14
+ export type SerializerParseBy<T, TSerializable> = T extends TSerializable
15
+ ? T
16
+ : unknown extends SerializerExtensions['ReadableStream']
17
+ ? { [K in keyof T]: SerializerParseBy<T[K], TSerializable> }
18
+ : T extends SerializerExtensions['ReadableStream']
19
+ ? ReadableStream
20
+ : { [K in keyof T]: SerializerParseBy<T[K], TSerializable> }
21
+
22
+ export interface DefaultSerializerExtensions {
23
+ ReadableStream: unknown
24
+ }
25
+
26
+ export interface SerializerExtensions extends DefaultSerializerExtensions {}
27
+
28
+ export type Serializable = Date | undefined | Error | FormData | bigint
29
+
30
+ export type SerializerStringify<T> = SerializerStringifyBy<T, Serializable>
31
+
32
+ export type SerializerParse<T> = SerializerParseBy<T, Serializable>
@@ -0,0 +1,7 @@
1
+ import type { Constrain } from './utils'
2
+
3
+ export interface OptionalStructuralSharing<TStructuralSharing, TConstraint> {
4
+ readonly structuralSharing?:
5
+ | Constrain<TStructuralSharing, TConstraint>
6
+ | undefined
7
+ }
@@ -0,0 +1,181 @@
1
+ import type {
2
+ FromPathOption,
3
+ NavigateOptions,
4
+ PathParamOptions,
5
+ SearchParamOptions,
6
+ ToPathOption,
7
+ } from './link'
8
+ import type { RedirectOptions } from './redirect'
9
+ import type { RouteIds } from './routeInfo'
10
+ import type { AnyRouter, RegisteredRouter } from './router'
11
+ import type { UseParamsResult } from './useParams'
12
+ import type { UseSearchResult } from './useSearch'
13
+ import type { Constrain, ConstrainLiteral } from './utils'
14
+
15
+ export type ValidateFromPath<
16
+ TRouter extends AnyRouter = RegisteredRouter,
17
+ TFrom = string,
18
+ > = FromPathOption<TRouter, TFrom>
19
+
20
+ export type ValidateToPath<
21
+ TRouter extends AnyRouter = RegisteredRouter,
22
+ TTo extends string | undefined = undefined,
23
+ TFrom extends string = string,
24
+ > = ToPathOption<TRouter, TFrom, TTo>
25
+
26
+ export type ValidateSearch<
27
+ TRouter extends AnyRouter = RegisteredRouter,
28
+ TTo extends string | undefined = undefined,
29
+ TFrom extends string = string,
30
+ > = SearchParamOptions<TRouter, TFrom, TTo>
31
+
32
+ export type ValidateParams<
33
+ TRouter extends AnyRouter = RegisteredRouter,
34
+ TTo extends string | undefined = undefined,
35
+ TFrom extends string = string,
36
+ > = PathParamOptions<TRouter, TFrom, TTo>
37
+
38
+ /**
39
+ * @internal
40
+ */
41
+ export type InferFrom<
42
+ TOptions,
43
+ TDefaultFrom extends string = string,
44
+ > = TOptions extends {
45
+ from: infer TFrom extends string
46
+ }
47
+ ? TFrom
48
+ : TDefaultFrom
49
+
50
+ /**
51
+ * @internal
52
+ */
53
+ export type InferTo<TOptions> = TOptions extends {
54
+ to: infer TTo extends string
55
+ }
56
+ ? TTo
57
+ : undefined
58
+
59
+ /**
60
+ * @internal
61
+ */
62
+ export type InferMaskTo<TOptions> = TOptions extends {
63
+ mask: { to: infer TTo extends string }
64
+ }
65
+ ? TTo
66
+ : ''
67
+
68
+ export type InferMaskFrom<TOptions> = TOptions extends {
69
+ mask: { from: infer TFrom extends string }
70
+ }
71
+ ? TFrom
72
+ : string
73
+
74
+ export type ValidateNavigateOptions<
75
+ TRouter extends AnyRouter = RegisteredRouter,
76
+ TOptions = unknown,
77
+ TDefaultFrom extends string = string,
78
+ > = Constrain<
79
+ TOptions,
80
+ NavigateOptions<
81
+ TRouter,
82
+ InferFrom<TOptions, TDefaultFrom>,
83
+ InferTo<TOptions>,
84
+ InferMaskFrom<TOptions>,
85
+ InferMaskTo<TOptions>
86
+ >
87
+ >
88
+
89
+ export type ValidateNavigateOptionsArray<
90
+ TRouter extends AnyRouter = RegisteredRouter,
91
+ TOptions extends ReadonlyArray<any> = ReadonlyArray<unknown>,
92
+ TDefaultFrom extends string = string,
93
+ > = {
94
+ [K in keyof TOptions]: ValidateNavigateOptions<
95
+ TRouter,
96
+ TOptions[K],
97
+ TDefaultFrom
98
+ >
99
+ }
100
+
101
+ export type ValidateRedirectOptions<
102
+ TRouter extends AnyRouter = RegisteredRouter,
103
+ TOptions = unknown,
104
+ TDefaultFrom extends string = string,
105
+ > = Constrain<
106
+ TOptions,
107
+ RedirectOptions<
108
+ TRouter,
109
+ InferFrom<TOptions, TDefaultFrom>,
110
+ InferTo<TOptions>,
111
+ InferMaskFrom<TOptions>,
112
+ InferMaskTo<TOptions>
113
+ >
114
+ >
115
+
116
+ export type ValidateRedirectOptionsArray<
117
+ TRouter extends AnyRouter = RegisteredRouter,
118
+ TOptions extends ReadonlyArray<any> = ReadonlyArray<unknown>,
119
+ TDefaultFrom extends string = string,
120
+ > = {
121
+ [K in keyof TOptions]: ValidateRedirectOptions<
122
+ TRouter,
123
+ TOptions[K],
124
+ TDefaultFrom
125
+ >
126
+ }
127
+
128
+ export type ValidateId<
129
+ TRouter extends AnyRouter = RegisteredRouter,
130
+ TId extends string = string,
131
+ > = ConstrainLiteral<TId, RouteIds<TRouter['routeTree']>>
132
+
133
+ /**
134
+ * @internal
135
+ */
136
+ export type InferStrict<TOptions> = TOptions extends {
137
+ strict: infer TStrict extends boolean
138
+ }
139
+ ? TStrict
140
+ : true
141
+
142
+ /**
143
+ * @internal
144
+ */
145
+ export type InferShouldThrow<TOptions> = TOptions extends {
146
+ shouldThrow: infer TShouldThrow extends boolean
147
+ }
148
+ ? TShouldThrow
149
+ : true
150
+
151
+ /**
152
+ * @internal
153
+ */
154
+ export type InferSelected<TOptions> = TOptions extends {
155
+ select: (...args: Array<any>) => infer TSelected
156
+ }
157
+ ? TSelected
158
+ : unknown
159
+
160
+ export type ValidateUseSearchResult<
161
+ TOptions,
162
+ TRouter extends AnyRouter = RegisteredRouter,
163
+ > = UseSearchResult<
164
+ TRouter,
165
+ InferFrom<TOptions>,
166
+ InferStrict<TOptions>,
167
+ InferSelected<TOptions>
168
+ >
169
+
170
+ export type ValidateUseParamsResult<
171
+ TOptions,
172
+ TRouter extends AnyRouter = RegisteredRouter,
173
+ > = Constrain<
174
+ TOptions,
175
+ UseParamsResult<
176
+ TRouter,
177
+ InferFrom<TOptions>,
178
+ InferStrict<TOptions>,
179
+ InferSelected<TOptions>
180
+ >
181
+ >