-
Notifications
You must be signed in to change notification settings - Fork 170
/
ssr.ts
316 lines (294 loc) · 9.56 KB
/
ssr.ts
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
import { createBlankRouterURL, RouteModule } from '../framework/core/routing.ts'
import { dirname, basename } from 'https://deno.land/std@0.92.0/path/mod.ts'
import log from '../shared/log.ts'
import util from '../shared/util.ts'
import type { RouterURL } from '../types.ts'
import type { Application } from './app.ts'
export type SSRData = {
expires: number
value: any
}
export type SSROutput = {
html: string
data: Record<string, SSRData> | null
}
/** The framework render result of SSR. */
export type FrameworkRenderResult = {
head: string[]
body: string
scripts: Record<string, any>[]
data: Record<string, SSRData> | null
}
/** The framework renderer for SSR. */
export type FrameworkRenderer = {
render(
url: RouterURL,
AppComponent: any,
nestedPageComponents: { url: string, Component?: any }[],
styles: Record<string, string>
): Promise<FrameworkRenderResult>
}
/** The renderer class for aleph server. */
export class Renderer {
#app: Application
#renderer: FrameworkRenderer
#cache: Map<string, Map<string, SSROutput>>
constructor(app: Application) {
this.#app = app
this.#renderer = { render: async () => { throw new Error("framework renderer is undefined") } }
this.#cache = new Map()
}
setFrameworkRenderer(renderer: FrameworkRenderer) {
this.#renderer = renderer
}
async useCache(
namespace: string,
key: string,
render: () => Promise<[string, Record<string, SSRData> | null]>
): Promise<[string, any]> {
let cache = this.#cache.get(namespace)
if (cache === undefined) {
cache = new Map()
this.#cache.set(namespace, cache)
}
if (cache.has(key)) {
const { html, data } = cache.get(key)!
let expires = 0
if (data !== null) {
Object.values(data).forEach(({ expires: _expires }) => {
if (expires === 0 || (_expires > 0 && _expires < expires)) {
expires = _expires
}
})
}
if (expires === 0 || Date.now() < expires) {
return [html, data]
}
cache.delete(key)
}
let [html, data] = await render()
if (namespace !== '-') {
this.#app.getCodeInjects('ssr')?.forEach(transform => {
html = transform(key, html)
})
}
cache.set(key, { html, data })
return [html, data]
}
clearCache(namespace?: string) {
if (namespace) {
this.#cache.delete(namespace)
} else {
this.#cache.clear()
}
}
/** render page base the given location. */
async renderPage(url: RouterURL, nestedModules: RouteModule[]): Promise<[string, Record<string, SSRData> | null]> {
const start = performance.now()
const isDev = this.#app.isDev
const state = { entryFile: '' }
const appModule = this.#app.findModuleByName('app')
const { default: App } = appModule ? await import(`file://${appModule.jsFile}#${appModule.hash.slice(0, 6)}`) : {} as any
const nestedPageComponents = await Promise.all(nestedModules
.filter(({ url }) => this.#app.getModule(url) !== null)
.map(async ({ url }) => {
const { jsFile, hash } = this.#app.getModule(url)!
const { default: Component } = await import(`file://${jsFile}#${hash.slice(0, 6)}`)
state.entryFile = dirname(url) + '/' + basename(jsFile)
return {
url,
Component
}
})
)
const styles = await this.lookupStyleModules(...[
appModule ? appModule.url : [],
nestedModules.map(({ url }) => url)
].flat())
const { head, body, data, scripts } = await this.#renderer.render(
url,
App,
nestedPageComponents,
styles
)
if (isDev) {
log.info(`render '${url.pathname}' in ${Math.round(performance.now() - start)}ms`)
}
return [
createHtml({
lang: url.locale,
head: head,
scripts: [
data ? {
id: 'ssr-data',
type: 'application/json',
innerText: JSON.stringify(data, undefined, isDev ? 2 : 0),
} : '',
...this.#app.getSSRHTMLScripts(state.entryFile),
...scripts.map((script: Record<string, any>) => {
if (script.innerText && !isDev) {
return { ...script, innerText: script.innerText }
}
return script
})
],
body: `<div id="__aleph">${body}</div>`,
minify: !isDev
}),
data
]
}
/** render custom 404 page. */
async render404Page(url: RouterURL): Promise<string> {
const appModule = this.#app.findModuleByName('app')
const e404Module = this.#app.findModuleByName('404')
const { default: App } = appModule ? await import(`file://${appModule.jsFile}#${appModule.hash.slice(0, 6)}`) : {} as any
const { default: E404 } = e404Module ? await import(`file://${e404Module.jsFile}#${e404Module.hash.slice(0, 6)}`) : {} as any
const styles = await this.lookupStyleModules(...[
appModule ? appModule.url : [],
e404Module ? e404Module.url : []
].flat())
const { head, body, data, scripts } = await this.#renderer.render(
url,
App,
e404Module ? [{ url: e404Module.url, Component: E404 }] : [],
styles
)
return createHtml({
lang: url.locale,
head,
scripts: [
data ? {
id: 'ssr-data',
type: 'application/json',
innerText: JSON.stringify(data, undefined, this.#app.isDev ? 2 : 0),
} : '',
...this.#app.getSSRHTMLScripts(),
...scripts.map((script: Record<string, any>) => {
if (script.innerText && !this.#app.isDev) {
return { ...script, innerText: script.innerText }
}
return script
})
],
body: `<div id="__aleph">${body}</div>`,
minify: !this.#app.isDev
})
}
/** render custom loading page for SPA mode. */
async renderSPAIndexPage(): Promise<string> {
const { baseUrl, defaultLocale } = this.#app.config
const loadingModule = this.#app.findModuleByName('loading')
if (loadingModule) {
const { default: Loading } = await import(`file://${loadingModule.jsFile}#${loadingModule.hash.slice(0, 6)}`)
const styles = await this.lookupStyleModules(loadingModule.url)
const {
head,
body,
scripts
} = await this.#renderer.render(
createBlankRouterURL(baseUrl, defaultLocale),
undefined,
[{ url: loadingModule.url, Component: Loading }],
styles
)
return createHtml({
lang: defaultLocale,
head,
scripts: [
...this.#app.getSSRHTMLScripts(),
...scripts.map((script: Record<string, any>) => {
if (script.innerText && !this.#app.isDev) {
return { ...script, innerText: script.innerText }
}
return script
})
],
body: `<div id="__aleph">${body}</div>`,
minify: !this.#app.isDev
})
}
return createHtml({
lang: defaultLocale,
head: [],
scripts: this.#app.getSSRHTMLScripts(),
body: '<div id="__aleph"></div>',
minify: !this.#app.isDev
})
}
private async lookupStyleModules(...urls: string[]): Promise<Record<string, string>> {
return (await Promise.all(this.#app.lookupStyleModules(...urls).map(async ({ jsFile, hash }) => {
const { default: { __url$: url, __css$: css } } = await import(`file://${jsFile}#${hash.slice(0, 6)}`)
return { url, css }
}))).reduce((styles, mod) => {
styles[mod.url] = mod.css
return styles
}, {} as Record<string, string>)
}
}
/** create html content by given arguments */
function createHtml({
body,
lang = 'en',
head = [],
className,
scripts = [],
minify = false
}: {
body: string,
lang?: string,
head?: string[],
className?: string,
scripts?: (string | { id?: string, type?: string, src?: string, innerText?: string, async?: boolean, preload?: boolean, nomodule?: boolean })[],
minify?: boolean
}) {
const eol = minify ? '' : '\n'
const indent = minify ? '' : ' '.repeat(2)
const headTags = head.map(tag => tag.trim()).concat(scripts.map(v => {
if (!util.isString(v) && util.isNEString(v.src)) {
if (v.type === 'module') {
return `<link rel="modulepreload" href=${JSON.stringify(util.cleanPath(v.src))} />`
} else if (!v.nomodule) {
return `<link rel="preload" href=${JSON.stringify(util.cleanPath(v.src))} as="script" />`
}
}
return ''
})).filter(Boolean)
const scriptTags = scripts.map(v => {
if (util.isString(v)) {
return `<script>${v}</script>`
} else if (util.isNEString(v.innerText)) {
const { innerText, ...rest } = v
return `<script${formatAttrs(rest)}>${eol}${innerText}${eol}${indent}</script>`
} else if (util.isNEString(v.src) && !v.preload) {
return `<script${formatAttrs({ ...v, src: util.cleanPath(v.src) })}></script>`
} else {
return ''
}
}).filter(Boolean)
if (!head.some(tag => tag.trimLeft().startsWith('<meta') && tag.includes('name="viewport"'))) {
headTags.unshift('<meta name="viewport" content="width=device-width" />')
}
return [
'<!DOCTYPE html>',
`<html lang="${lang}">`,
'<head>',
indent + '<meta charSet="utf-8" />',
...headTags.map(tag => indent + tag),
'</head>',
className ? `<body class="${className}">` : '<body>',
indent + body,
...scriptTags.map(tag => indent + tag),
'</body>',
'</html>'
].join(eol)
}
function formatAttrs(v: any): string {
return Object.keys(v).filter(k => !!v[k]).map(k => {
if (v[k] === true) {
return ` ${k}`
} else {
return ` ${k}=${JSON.stringify(String(v[k]))}`
}
}).join('')
}