-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
AppContext.js
308 lines (270 loc) Β· 8.2 KB
/
AppContext.js
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
'use strict'
/**
* Module dependencies.
*/
const path = require('path')
const createMarkdown = require('./createMarkdown')
const loadConfig = require('./loadConfig')
const loadTheme = require('./loadTheme')
const { fs, logger, chalk, globby, sort, datatypes: { isFunction }} = require('@vuepress/shared-utils')
const Page = require('./Page')
const ClientComputedMixin = require('./ClientComputedMixin')
const PluginAPI = require('../plugin-api/index')
/**
* Expose AppContext.
*/
module.exports = class AppContext {
/**
* Instantiate the app context with a new API
*
* @param {string} sourceDir
* @param {{
* isProd: boolean,
* plugins: pluginsConfig,
* theme: themeNameConfig
* temp: string
* }} options
*/
constructor (sourceDir, cliOptions = {}, isProd) {
this.sourceDir = sourceDir
this.cliOptions = cliOptions
this.isProd = isProd
const { tempPath, writeTemp } = createTemp(cliOptions.temp)
this.tempPath = tempPath
this.writeTemp = writeTemp
this.vuepressDir = path.resolve(sourceDir, '.vuepress')
this.siteConfig = loadConfig(this.vuepressDir)
if (isFunction(this.siteConfig)) {
this.siteConfig = this.siteConfig(this)
}
this.base = this.siteConfig.base || '/'
this.themeConfig = this.siteConfig.themeConfig || {}
this.outDir = this.siteConfig.dest
? path.resolve(this.siteConfig.dest)
: path.resolve(sourceDir, '.vuepress/dist')
this.pluginAPI = new PluginAPI(this)
this.pages = [] // Array<Page>
this.ClientComputedMixinConstructor = ClientComputedMixin(this.getSiteData())
}
/**
* Load pages, load plugins, apply plugins / plugin options, etc.
*
* @returns {Promise<void>}
* @api private
*/
async process () {
this.normalizeHeadTagUrls()
this.resolveTemplates()
await this.resolveTheme()
this.resolvePlugins()
this.markdown = createMarkdown(this)
await this.resolvePages()
await Promise.all(
this.pluginAPI.options.additionalPages.values.map(async (options) => {
await this.addPage(options)
})
)
await this.pluginAPI.options.ready.apply()
await this.pluginAPI.options.clientDynamicModules.apply(this)
await this.pluginAPI.options.globalUIComponents.apply(this)
await this.pluginAPI.options.enhanceAppFiles.apply(this)
}
/**
* Apply internal and user plugins
*
* @api private
*/
resolvePlugins () {
const themeConfig = this.themeConfig
const siteConfig = this.siteConfig
const shouldUseLastUpdated = (
themeConfig.lastUpdated ||
Object.keys(siteConfig.locales && themeConfig.locales || {})
.some(base => themeConfig.locales[base].lastUpdated)
)
this.pluginAPI
// internl core plugins
.use(Object.assign({}, siteConfig, { name: '@vuepress/internal-site-config' }))
.use(require('../internal-plugins/siteData'))
.use(require('../internal-plugins/routes'))
.use(require('../internal-plugins/rootMixins'))
.use(require('../internal-plugins/enhanceApp'))
.use(require('../internal-plugins/overrideCSS'))
.use(require('../internal-plugins/layoutComponents'))
.use(require('../internal-plugins/pageComponents'))
.use(require('../internal-plugins/transformModule'))
// user plugin
.useByPluginsConfig(this.cliOptions.plugins)
.useByPluginsConfig(this.siteConfig.plugins)
.useByPluginsConfig(this.themePlugins)
// built-in plugins
.use('@vuepress/last-updated', shouldUseLastUpdated)
.use('@vuepress/register-components', {
componentsDir: [
path.resolve(this.sourceDir, '.vuepress/components'),
path.resolve(this.themePath, 'components')
]
})
.apply()
}
/**
* normalize head tag urls for base
*
* @api private
*/
normalizeHeadTagUrls () {
if (this.base !== '/' && this.siteConfig.head) {
this.siteConfig.head.forEach(tag => {
const attrs = tag[1]
if (attrs) {
for (const name in attrs) {
if (name === 'src' || name === 'href') {
const value = attrs[name]
if (value.charAt(0) === '/') {
attrs[name] = this.base + value.slice(1)
}
}
}
}
})
}
}
/**
* Make template configurable
*
* @api private
*/
resolveTemplates () {
let { ssrTemplate, devTemplate } = this.siteConfig
const templateDir = path.resolve(this.vuepressDir, 'templates')
if (!devTemplate) {
devTemplate = path.resolve(templateDir, 'dev.html')
if (!fs.existsSync(devTemplate)) {
devTemplate = path.resolve(__dirname, '../app/index.dev.html')
}
}
if (!ssrTemplate) {
ssrTemplate = path.resolve(templateDir, 'ssr.html')
if (!fs.existsSync(ssrTemplate)) {
ssrTemplate = path.resolve(__dirname, '../app/index.ssr.html')
}
}
logger.debug('SSR Template File: ' + chalk.gray(ssrTemplate))
logger.debug('DEV Template File: ' + chalk.gray(devTemplate))
this.devTemplate = devTemplate
this.ssrTemplate = ssrTemplate
}
/**
* Find all page source files located in sourceDir
*
* @returns {Promise<void>}
* @api private
*/
async resolvePages () {
// resolve pageFiles
const patterns = ['**/*.md', '!.vuepress', '!node_modules']
if (this.siteConfig.dest) {
// #654 exclude dest folder when dest dir was set in
// sourceDir but not in '.vuepress'
const outDirRelative = path.relative(this.sourceDir, this.outDir)
if (!outDirRelative.includes('..')) {
patterns.push('!' + outDirRelative)
}
}
const pageFiles = sort(await globby(patterns, { cwd: this.sourceDir }))
await Promise.all(pageFiles.map(async (relative) => {
const filePath = path.resolve(this.sourceDir, relative)
await this.addPage({ filePath, relative })
}))
}
/**
* Add a page
*
* @returns {Promise<void>}
* @api public
*/
async addPage (options) {
options.permalinkPattern = this.siteConfig.permalink
const page = new Page(options, this)
await page.process({
markdown: this.markdown,
computed: new this.ClientComputedMixinConstructor(),
enhancers: this.pluginAPI.options.extendPageData.items
})
this.pages.push(page)
}
/**
* Resolve theme
*
* @returns {Promise<void>}
* @api private
*/
async resolveTheme () {
const theme = this.siteConfig.theme || this.cliOptions.theme
Object.assign(this, (await loadTheme(theme, this.sourceDir, this.vuepressDir)))
}
/**
* Get the data to be delivered to the client.
*
* @returns {{
* title: string,
* description: string,
* base: string,
* pages: Page[],
* themeConfig: ThemeConfig,
* locales: Locales
* }}
* @api public
*/
getSiteData () {
const { locales } = this.siteConfig
if (locales) {
Object.keys(locales).forEach(path => {
locales[path].path = path
})
}
return {
title: this.siteConfig.title || '',
description: this.siteConfig.description || '',
base: this.base,
pages: this.pages.map(page => page.toJson()),
themeConfig: this.siteConfig.themeConfig || {},
locales
}
}
}
/**
* Create a dynamic temp utility context that allow to lanuch
* multiple apps with isolated context at the same time.
* @param tempPath
* @returns {{
* writeTemp: (function(file: string, content: string): string),
* tempPath: string
* }}
*/
function createTemp (tempPath) {
if (!tempPath) {
tempPath = path.resolve(__dirname, '../../.temp')
} else {
tempPath = path.resolve(tempPath)
}
if (!fs.existsSync(tempPath)) {
fs.ensureDirSync(tempPath)
} else {
fs.emptyDirSync(tempPath)
}
logger.tip(`Temp directory: ${chalk.gray(tempPath)}`)
const tempCache = new Map()
async function writeTemp (file, content) {
const destPath = path.join(tempPath, file)
await fs.ensureDir(path.parse(destPath).dir)
// cache write to avoid hitting the dist if it didn't change
const cached = tempCache.get(file)
if (cached !== content) {
await fs.writeFile(destPath, content)
tempCache.set(file, content)
}
return destPath
}
return { writeTemp, tempPath }
}