-
-
Notifications
You must be signed in to change notification settings - Fork 880
/
Copy pathssr-client.tsx
218 lines (179 loc) · 5.45 KB
/
ssr-client.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import { isPlainObject } from '@tanstack/router-core'
import invariant from 'tiny-invariant'
import { startSerializer } from './serializer'
import type {
AnyRouter,
ControllablePromise,
MakeRouteMatch,
} from '@tanstack/react-router'
import type { DeferredPromiseState, Manifest } from '@tanstack/router-core'
declare global {
interface Window {
__TSR_SSR__?: StartSsrGlobal
}
}
export interface StartSsrGlobal {
matches: Array<SsrMatch>
streamedValues: Record<
string,
{
value: any
parsed: any
}
>
cleanScripts: () => void
dehydrated?: any
initMatch: (match: SsrMatch) => void
resolvePromise: (opts: {
matchId: string
id: number
promiseState: DeferredPromiseState<any>
}) => void
injectChunk: (opts: { matchId: string; id: number; chunk: string }) => void
closeStream: (opts: { matchId: string; id: number }) => void
}
export interface SsrMatch {
id: string
__beforeLoadContext: string
loaderData?: string
error?: string
extracted?: Array<ClientExtractedEntry>
updatedAt: MakeRouteMatch['updatedAt']
status: MakeRouteMatch['status']
}
export type ClientExtractedEntry =
| ClientExtractedStream
| ClientExtractedPromise
export interface ClientExtractedPromise extends ClientExtractedBaseEntry {
type: 'promise'
value?: ControllablePromise<any>
}
export interface ClientExtractedStream extends ClientExtractedBaseEntry {
type: 'stream'
value?: ReadableStream & { controller?: ReadableStreamDefaultController }
}
export interface ClientExtractedBaseEntry {
type: string
path: Array<string>
}
export interface ResolvePromiseState {
matchId: string
id: number
promiseState: DeferredPromiseState<any>
}
export interface DehydratedRouter {
manifest: Manifest | undefined
dehydratedData: any
}
export function hydrate(router: AnyRouter) {
invariant(
window.__TSR_SSR__?.dehydrated,
'Expected to find a dehydrated data on window.__TSR_SSR__.dehydrated... but we did not. Please file an issue!',
)
const { manifest, dehydratedData } = startSerializer.parse(
window.__TSR_SSR__.dehydrated,
) as DehydratedRouter
router.ssr = {
manifest,
serializer: startSerializer,
}
router.clientSsr = {
getStreamedValue: <T,>(key: string): T | undefined => {
if (router.isServer) {
return undefined
}
const streamedValue = window.__TSR_SSR__?.streamedValues[key]
if (!streamedValue) {
return
}
if (!streamedValue.parsed) {
streamedValue.parsed = router.ssr!.serializer.parse(streamedValue.value)
}
return streamedValue.parsed
},
}
// Hydrate the router state
const matches = router.matchRoutes(router.state.location)
// kick off loading the route chunks
const routeChunkPromise = Promise.all(
matches.map((match) => {
const route = router.looseRoutesById[match.routeId]!
return router.loadRouteChunk(route)
}),
)
matches.forEach((match) => {
const route = router.looseRoutesById[match.routeId]!
// Right after hydration and before the first render, we need to rehydrate each match
// This includes rehydrating the loaderData and also using the beforeLoadContext
// to reconstruct any context that was serialized on the server
const dehydratedMatch = window.__TSR_SSR__!.matches.find(
(d) => d.id === match.id,
)
if (dehydratedMatch) {
Object.assign(match, dehydratedMatch, {
dehydrated: true,
})
const parentMatch = matches[match.index - 1]
const parentContext = parentMatch?.context ?? router.options.context ?? {}
// Handle beforeLoadContext
if (dehydratedMatch.__beforeLoadContext) {
match.__beforeLoadContext = router.ssr!.serializer.parse(
dehydratedMatch.__beforeLoadContext,
) as any
match.context = {
...parentContext,
...match.__routeContext,
...match.__beforeLoadContext,
}
}
// Handle loaderData
if (dehydratedMatch.loaderData) {
match.loaderData = router.ssr!.serializer.parse(
dehydratedMatch.loaderData,
)
}
// Handle error
if (dehydratedMatch.error) {
match.error = router.ssr!.serializer.parse(dehydratedMatch.error)
}
// Handle extracted
;(match as unknown as SsrMatch).extracted?.forEach((ex) => {
deepMutableSetByPath(match, ['loaderData', ...ex.path], ex.value)
})
}
const assetContext = {
matches: router.state.matches,
match,
params: match.params,
loaderData: match.loaderData,
}
const headFnContent = route.options.head?.(assetContext)
const scripts = route.options.scripts?.(assetContext)
match.meta = headFnContent?.meta
match.links = headFnContent?.links
match.headScripts = headFnContent?.scripts
match.scripts = scripts
return match
})
router.__store.setState((s) => {
return {
...s,
matches,
}
})
// Allow the user to handle custom hydration data
router.options.hydrate?.(dehydratedData)
return routeChunkPromise
}
function deepMutableSetByPath<T>(obj: T, path: Array<string>, value: any) {
// mutable set by path retaining array and object references
if (path.length === 1) {
;(obj as any)[path[0]!] = value
}
const [key, ...rest] = path
if (Array.isArray(obj)) {
deepMutableSetByPath(obj[Number(key)], rest, value)
} else if (isPlainObject(obj)) {
deepMutableSetByPath((obj as any)[key!], rest, value)
}
}