-
Notifications
You must be signed in to change notification settings - Fork 912
Expand file tree
/
Copy pathwatchPageFiles.ts
More file actions
196 lines (169 loc) · 5.94 KB
/
watchPageFiles.ts
File metadata and controls
196 lines (169 loc) · 5.94 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
import type { App, Page } from '@vuepress/core'
import { colors, logger, path, picomatch } from '@vuepress/utils'
import type { FSWatcher } from 'chokidar'
import chokidar from 'chokidar'
import { handlePageAdd } from './handlePageAdd.js'
import { handlePageChange } from './handlePageChange.js'
import { handlePageUnlink } from './handlePageUnlink.js'
import { createPageDepsHelper } from './pageDepsHelper.js'
type PageEventType = 'add' | 'change' | 'unlink'
/**
* Merge pending events into final operation.
*/
const mergeEvents = (events: PageEventType[]): PageEventType | null => {
if (events.length === 0) return null
if (events.length === 1) return events[0]
const first = events[0]
const last = events[events.length - 1]
// add + ... + remove: nothing
if (first === 'add' && last === 'unlink') return null
if (first === 'add') return 'add'
if (last === 'unlink') return 'unlink'
return 'change'
}
/**
* Watch page files and deps, return file watchers and cleanup function
*/
export const watchPageFiles = (
app: App,
): {
watchers: FSWatcher[]
cleanup: () => Promise<void>
} => {
// Track pending events per page - just event types, no I/O
const pendingEvents = new Map<string, PageEventType[]>()
// Track the last promise per page for serialization
const pagePromises = new Map<string, Promise<void>>()
// watch page deps
const depsWatcher = chokidar.watch([], {
ignoreInitial: true,
})
const depsHelper = createPageDepsHelper()
const addDeps = (page: Page): void => {
const depsToAdd = depsHelper.add(page)
depsWatcher.add(depsToAdd)
}
const removeDeps = (page: Page): void => {
const depsToRemove = depsHelper.remove(page)
depsWatcher.unwatch(depsToRemove)
}
// Process pending events for a page, merging them into one final operation
const processPageEvents = async (filePathRelative: string): Promise<void> => {
// Get and clear pending events for this page
const events = pendingEvents.get(filePathRelative) ?? []
pendingEvents.delete(filePathRelative)
// Merge events into final operation
const finalEvent = mergeEvents(events)
if (!finalEvent) return
const filePath = app.dir.source(filePathRelative)
if (finalEvent === 'add') {
logger.info(`page ${colors.magenta(filePathRelative)} is created`)
const page = await handlePageAdd(app, filePath)
if (page === null) return
addDeps(page)
return
}
if (finalEvent === 'change') {
logger.info(`page ${colors.magenta(filePathRelative)} is modified`)
const result = await handlePageChange(app, filePath)
if (result === null) return
const [pageOld, pageNew] = result
removeDeps(pageOld)
addDeps(pageNew)
return
}
// finalEvent is 'unlink'
logger.info(`page ${colors.magenta(filePathRelative)} is removed`)
const page = await handlePageUnlink(app, filePath)
if (page === null) return
removeDeps(page)
}
// Handle file events - just track them, no processing yet
const pageEventHandler = (
filePathRelative: string,
eventType: PageEventType,
): void => {
// Add event to pending list
let events = pendingEvents.get(filePathRelative)
if (!events) pendingEvents.set(filePathRelative, (events = []))
events.push(eventType)
// Chain to existing promise to ensure serialization
const existingPromise =
pagePromises.get(filePathRelative) ?? Promise.resolve()
const newPromise = (async () => {
await existingPromise
await processPageEvents(filePathRelative)
})()
pagePromises.set(filePathRelative, newPromise)
}
// When a dependency changes, find all pages that depend on it and trigger change event for them
const depsListener = (dep: string): void => {
const pagePaths = depsHelper.get(dep)
for (const filePathRelative of pagePaths) {
logger.info(
`dependency of page ${colors.magenta(filePathRelative)} is modified`,
)
pageEventHandler(filePathRelative, 'change')
}
}
depsWatcher.on('add', depsListener)
depsWatcher.on('change', depsListener)
depsWatcher.on('unlink', depsListener)
app.pages.forEach((page) => {
addDeps(page)
})
// watch page files
const pagePatterns: string[] = []
const ignorePatterns: string[] = []
for (const pattern of app.options.pagePatterns) {
if (pattern.startsWith('!')) {
ignorePatterns.push(pattern.slice(1))
} else {
pagePatterns.push(pattern)
}
}
const sourceDir = app.dir.source()
const tempDir = app.dir.temp()
const cacheDir = app.dir.cache()
const ignoreMatcher = picomatch(ignorePatterns, { cwd: sourceDir })
const pageMatcher = picomatch(pagePatterns, { cwd: sourceDir })
const pagesWatcher = chokidar.watch('.', {
cwd: sourceDir,
ignored: (filepath, stats) => {
const relative = path.relative(sourceDir, filepath)
// This is important so that folders like node_modules will be ignored immediately without traversing their children
if (ignoreMatcher(relative)) {
return true
}
// ignore internal temp and cache directories
if (filepath === tempDir || filepath === cacheDir) {
return true
}
// ignore non-matched files
return !!stats?.isFile() && !pageMatcher(relative)
},
ignoreInitial: true,
})
pagesWatcher.on('add', (filePathRelative) => {
pageEventHandler(filePathRelative, 'add')
})
pagesWatcher.on('change', (filePathRelative) => {
pageEventHandler(filePathRelative, 'change')
})
pagesWatcher.on('unlink', (filePathRelative) => {
pageEventHandler(filePathRelative, 'unlink')
})
// flush all pending page operations and reset
const cleanup = async (): Promise<void> => {
// clear pending events
pendingEvents.clear()
// wait for all pending page operations to finish
await Promise.all(pagePromises.values())
// clear pending promises
pagePromises.clear()
}
return {
watchers: [pagesWatcher, depsWatcher],
cleanup,
}
}