-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
262 lines (237 loc) · 7.28 KB
/
server.ts
File metadata and controls
262 lines (237 loc) · 7.28 KB
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
/* eslint-disable ts/no-require-imports */
import type { ViteDevServer } from 'vite'
import type { HTMLMinifierConfig } from './build-ssg.types'
import { Buffer } from 'node:buffer'
import { readFileSync } from 'node:fs'
import process from 'node:process'
import { minify as minifyHtml } from '@minify-html/node'
import devalue from '@nuxt/devalue'
import {
createApp,
eventHandler,
fromNodeMiddleware,
getRequestURL,
setHeader,
setResponseStatus,
toNodeListener,
// getQuery,
// getRouterParams,
} from 'h3'
import { minify as minifierTerser } from 'html-minifier-terser'
import { listen } from 'listhen'
import path from 'pathe'
const root = process.cwd()
const isTest = process.env.NODE_ENV === 'test' || !!process.env.VITE_TEST_BUILD
const isProd = process.env.NODE_ENV === 'production'
const resolve = (p: string) => path.resolve(__dirname, p)
// prevent non-ready SSR dependencies from throwing errors
// @ts-expect-error
globalThis.__VUE_PROD_DEVTOOLS__ = false
// @ts-expect-error
globalThis.__VUE_I18N_FULL_INSTALL__ = false
// @ts-expect-error
globalThis.__VUE_I18N_LEGACY_API__ = false
export const htmlMinifier: HTMLMinifierConfig = {
minifier: 'minify-html',
minifyHtmlOptions: {
keep_comments: true,
minify_js: true,
},
}
async function createServer() {
let vite: ViteDevServer
const app = createApp({
debug: !isProd,
})
const manifest = isProd
? require('./dist/client/.vite/ssr-manifest.json')
: {}
const indexProd = isProd
? readFileSync(resolve('dist/client/index.html'), 'utf-8')
: ''
if (!isProd) {
/**
* During dev, we use vite's connect instance as middleware
*
* @see https://vitejs.dev/guide/ssr.html#setting-up-the-dev-server
* @see https://vitejs.dev/config/server-options.html#server-middlewaremode
*/
vite = await import('vite').then(m =>
m.createServer({
root,
logLevel: isTest ? 'error' : 'info',
appType: 'custom',
server: {
middlewareMode: true,
watch: {
// During tests we edit the files too fast and sometimes chokidar
// misses change events, so enforce polling for consistency
usePolling: true,
interval: 100,
},
},
}),
)
// use vite's connect instance as middleware in h3 app
app.use(fromNodeMiddleware(vite.middlewares))
}
else {
/**
* Otherwise, we register compression and serve-static express handlers in h3
*
* @see https://github.com/expressjs/compression
* @see https://github.com/expressjs/serve-static
*/
app.use(fromNodeMiddleware(require('compression')()))
app.use(
fromNodeMiddleware(
require('serve-static')(resolve('dist/client'), {
index: false,
fallthrough: true,
maxAge: '1w',
}),
),
)
}
/**
* Using h3's eventHandler, we can register custom handlers for different routes
*
* @see https://github.com/unjs/h3#more-app-usage-examples
*/
// app.use('/api/hello/:name', eventHandler(async (event) => {
// const query = getQuery(event)
// const params = getRouterParams(event)
// return `Hello ${params.name}!`
// }))
/**
* Register the catch-all handler which will render our app
*/
app.use(
'*',
eventHandler(async (event) => {
try {
const url = getRequestURL(event)
// send empty error 404 if it's a static file
const ext = url.pathname.split('.')
if (ext.length > 1) {
setHeader(
event,
'Cache-Control',
'no-cache, no-store, must-revalidate',
)
return null
}
// load template and render function from vue app
let template, render
if (!isProd) {
// always read fresh template in dev
template = readFileSync(resolve('index.html'), 'utf-8')
template = await vite.transformIndexHtml(url.pathname, template)
render = (await vite.ssrLoadModule('/src/entry-server.ts')).render
}
else {
// use built template and render function in production
template = indexProd
render = require('./dist/server/entry-server.js').render
}
// render the vue app to HTML
const {
appHtml,
headTags,
htmlAttrs,
bodyAttrs,
bodyTags,
bodyTagsOpen,
preloadLinks,
initialState,
} = await render(event, url.pathname, manifest)
// inject the app-rendered HTML into the template
const html = template
.replace(`<html>`, `<html${htmlAttrs}>`)
.replace(`<head>`, `<head>${headTags}`)
.replace(`</head>`, `${preloadLinks}</head>`)
.replace(`<body>`, `<body${bodyAttrs}>${bodyTagsOpen}`)
.replace(`</body>`, `${bodyTags}</body>`)
.replace(
/<div id="app"([\s\w\-"'=[\]]*)><\/div>/,
`<div id="app" data-server-rendered="true"$1>${appHtml}</div><script>window.__vulk__=${devalue(
initialState,
)}</script>`,
)
// send minified page
setHeader(event, 'Content-Type', 'text/html')
let minified: Buffer | string = html
switch (htmlMinifier.minifier) {
case 'terser':
minified = await minifierTerser(html, htmlMinifier.terserOptions)
break
case 'minify-html':
minified = minifyHtml(
Buffer.from(html),
htmlMinifier.minifyHtmlOptions,
)
break
}
return minified
}
catch (error: any) {
// handle error 500 page
if (!isProd) {
setHeader(
event,
'Cache-Control',
'no-cache, no-store, must-revalidate',
)
setResponseStatus(event, 500)
vite?.ssrFixStacktrace(error)
console.error('[dev] [pageError] ', error)
const Youch = await import('youch').then(m => m.Youch)
const youch = new Youch()
return await youch.toHTML(error, {
title: 'An error occurred during Vulk server rendering',
})
}
else {
setHeader(
event,
'Cache-Control',
'no-cache, no-store, must-revalidate',
)
setResponseStatus(event, 500)
console.error(`[pageError] ${error}`)
return 'Internal Server Error'
}
}
}),
)
// @ts-expect-error
return { app, vite }
}
if (!isTest) {
// start h3 server
createServer()
.then(({ app }) =>
listen(toNodeListener(app), { port: process.env.PORT || 3000 }),
)
.catch((error) => {
if (!isProd) {
console.error('[dev] [serverError] ', error)
}
else {
console.error(`[serverError] ${error}`)
}
process.exit(1)
})
if (!isProd) {
process.on('unhandledRejection', error =>
console.error('[dev] [unhandledRejection]', error))
process.on('uncaughtException', error =>
console.error('[dev] [uncaughtException]', error))
}
else {
process.on('unhandledRejection', error =>
console.error(`[unhandledRejection] ${error}`))
process.on('uncaughtException', error =>
console.error(`[uncaughtException] ${error}`))
}
}