/
server.ts
204 lines (174 loc) · 5.35 KB
/
server.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
import { performance } from 'node:perf_hooks'
import { createServer as createViteServer } from 'vite'
import pc from 'picocolors'
import type { ServerStoryFile } from '@histoire/shared'
import { Context } from './context.js'
import { getViteConfigWithPlugins, RESOLVED_MARKDOWN_FILES, RESOLVED_SEARCH_TITLE_DATA_ID, RESOLVED_STORIES_ID } from './vite.js'
import { onStoryChange, onStoryListChange, watchStories } from './stories.js'
import { useCollectStories } from './collect/index.js'
import { DevPluginApi } from './plugin.js'
import { useModuleLoader } from './load.js'
import { wrapLogError } from './util/log.js'
import { createMarkdownFilesWatcher, onMarkdownListChange } from './markdown.js'
export interface CreateServerOptions {
port?: number
}
export async function createServer (ctx: Context, options: CreateServerOptions = {}) {
const getViteServer = async (collecting: boolean) => {
const server = await createViteServer(await getViteConfigWithPlugins(collecting, ctx))
await server.pluginContainer.buildStart({})
return server
}
const [
server,
nodeServer,
,
{ stop: stopMdFileWatcher },
] = await Promise.all([
getViteServer(false),
getViteServer(true),
watchStories(ctx),
createMarkdownFilesWatcher(ctx),
] as const)
const moduleLoader = useModuleLoader({
server: nodeServer,
})
const pluginOnCleanups: (() => void | Promise<void>)[] = []
for (const plugin of ctx.config.plugins) {
if (plugin.onDev) {
const api = new DevPluginApi(ctx, plugin, moduleLoader)
const onCleanup = (cb: () => void | Promise<void>) => {
pluginOnCleanups.push(cb)
}
await plugin.onDev(api, onCleanup)
}
}
// Wait for pre-bundling (in `listen()`)
await server.listen(options.port ?? server.config.server?.port)
const {
clearCache,
executeStoryFile,
destroy: destroyCollectStories,
clearInvalidates,
} = useCollectStories({
server: nodeServer,
mainServer: server,
}, ctx)
// onStoryChange debouncing
let queued = false
let queuedFiles: ServerStoryFile[] = []
let currentFiles: ServerStoryFile[] = []
let queueTimer
let collecting = false
let didAllStoriesYet = false
// Invalidate modules
const invalidateModule = (id: string) => {
const mod = server.moduleGraph.getModuleById(id)
if (!mod) {
return
}
server.moduleGraph.invalidateModule(mod)
// Send HMR update
const timestamp = Date.now()
mod.lastHMRTimestamp = timestamp
server.ws.send({
type: 'update',
updates: [
{
type: 'js-update',
acceptedPath: mod.url,
path: mod.url,
timestamp: timestamp,
},
],
})
}
onStoryChange(async (changedFile) => {
if (changedFile && !didAllStoriesYet) {
return
}
if (changedFile) {
if (!queuedFiles.includes(changedFile)) {
queuedFiles.push(changedFile)
}
} else {
queuedFiles = []
}
if (!queued) {
queued = true
if (!collecting) {
clearTimeout(queueTimer)
// Debounce
queueTimer = setTimeout(collect, 100)
} else if (!changedFile && !currentFiles.length) {
// Full collect in progress
queued = false
}
}
})
async function collect () {
collecting = true
clearCache()
currentFiles = queuedFiles.slice()
queuedFiles = []
queued = false
console.log('Collect stories start', currentFiles.length ? currentFiles.map(f => f.fileName).join(', ') : 'all')
const time = performance.now()
if (currentFiles.length) {
await Promise.all(currentFiles.map(async storyFile => {
await executeStoryFile(storyFile)
if (storyFile.story) {
await invalidateModule(`/__resolved__virtual:story-source:${storyFile.story.id}`)
}
}))
} else {
// Full update
// Progress tracking
const fileCount = ctx.storyFiles.length
let loadedFilesCount = 0
const sendProgress = () => {
server.ws.send('histoire:stories-loading-progress', {
loadedFileCount: loadedFilesCount,
totalFileCount: fileCount,
})
}
sendProgress()
await Promise.all(ctx.storyFiles.map(async storyFile => {
await executeStoryFile(storyFile)
loadedFilesCount++
sendProgress()
}))
didAllStoriesYet = true
server.ws.send('histoire:all-stories-loaded', {})
}
console.log(`Collect stories end ${pc.bold(pc.blue(Math.round(performance.now() - time)))}ms`)
clearInvalidates()
invalidateModule(RESOLVED_STORIES_ID)
invalidateModule(RESOLVED_SEARCH_TITLE_DATA_ID)
collecting = false
if (queued) {
await collect()
}
}
onStoryListChange(() => {
invalidateModule(RESOLVED_STORIES_ID)
invalidateModule(RESOLVED_SEARCH_TITLE_DATA_ID)
})
onMarkdownListChange(() => {
invalidateModule(RESOLVED_MARKDOWN_FILES)
})
async function close () {
for (const cb of pluginOnCleanups) {
await wrapLogError('plugin.onDev.onCleanup', () => cb())
}
await wrapLogError('server.close', () => server.close())
await wrapLogError('nodeServer', () => nodeServer.close())
await wrapLogError('destroyCollectStories', () => destroyCollectStories())
await wrapLogError('stopMdFileWatcher', () => stopMdFileWatcher())
}
collect()
return {
server,
close,
}
}