forked from nuxt/content
/
index.js
298 lines (259 loc) · 8.54 KB
/
index.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
const { join, resolve } = require('path')
const fs = require('graceful-fs').promises
const defu = require('defu')
const logger = require('consola').withScope('@nuxt/content')
const hash = require('hasha')
const middleware = require('./middleware')
const Database = require('./database')
const WS = require('./ws')
const { getDefaults, processMarkdownOptions } = require('./utils')
module.exports = async function (moduleOptions) {
const { nuxt } = this
const isSSG =
this.options.dev === false &&
(this.options.target === 'static' ||
this.options._generate ||
this.options.mode === 'spa')
const { content = {} } = Object.assign({}, this.options)
Object.assign(content, moduleOptions)
if (content.markdown && content.markdown.basePlugins) {
logger.warn(
'Using `markdown.basePlugins` is deprecated. Use `markdown.remarkPlugins` as a function instead.'
)
const basePlugins = [...content.markdown.basePlugins]
content.markdown.remarkPlugins = () => basePlugins
delete content.markdown.basePlugins
}
if (content.markdown && content.markdown.plugins) {
logger.warn(
'Using `markdown.plugins` is deprecated. Use `markdown.remarkPlugins` as an array instead.'
)
const plugins = [...content.markdown.plugins]
if (content.markdown.remarkPlugins) {
if (typeof content.markdown.remarkPlugins === 'function') {
const oldPlugins = [...content.markdown.remarkPlugins()]
content.markdown.remarkPlugins = () => oldPlugins.concat(plugins)
} else {
content.markdown.remarkPlugins = content.markdown.remarkPlugins.concat(
plugins
)
}
} else {
content.markdown.remarkPlugins = plugins
}
delete content.markdown.plugins
}
const defaults = getDefaults({ dev: this.options.dev })
const options = defu.arrayFn(content, defaults)
const relativeDir = options.dir
options.dir = resolve(this.options.srcDir, options.dir)
processMarkdownOptions(options, this.nuxt.resolver.resolvePath)
options.apiPrefixWithBase = options.apiPrefix
if (this.options.router.base) {
let baseRouter = this.options.router.base
if (baseRouter[0] === '/') {
baseRouter = baseRouter.substring(1)
}
options.apiPrefixWithBase = baseRouter + options.apiPrefix
}
nuxt.callHook('content:options', options)
// Nuxt hooks
const globalComponents = resolve(this.options.srcDir, 'components/global')
const dirStat = await fs.stat(globalComponents).catch(() => null)
if (dirStat && dirStat.isDirectory()) {
nuxt.hook('components:dirs', (dirs) => {
dirs.push({
path: '~/components/global',
global: true
})
})
} else {
// restart Nuxt on first component creation inside the dir
nuxt.options.watch.push(globalComponents)
}
this.nuxt.hook('generate:cache:ignore', ignore => ignore.push(relativeDir))
const ws = new WS({
apiPrefix: options.apiPrefixWithBase
})
this.nuxt.hook('listen', (server) => {
server.on('upgrade', (...args) => ws.callHook('upgrade', ...args))
})
const useCache = options.useCache && !this.options.dev && this.options.ssr
const database = new Database({
...options,
srcDir: this.options.srcDir,
buildDir: resolve(this.options.buildDir, 'content'),
useCache
})
if (useCache) {
this.nuxt.hook('builder:prepared', async () => {
await database.rebuildCache()
})
}
// Database hooks
database.hook('file:beforeInsert', item =>
this.nuxt.callHook('content:file:beforeInsert', item, database)
)
database.hook('file:beforeParse', file =>
this.nuxt.callHook('content:file:beforeParse', file)
)
database.hook('file:updated', event => ws.broadcast(event))
// Initialize database from file system
await database.init()
// close database when Nuxt closes
this.nuxt.hook('close', () => database.close())
// listen to nuxt server to updrag
const $content = function () {
let options
const paths = []
Array.from(arguments).forEach((argument) => {
if (typeof argument === 'string') {
paths.push(argument)
} else if (typeof argument === 'object') {
options = argument
}
})
const path = paths
.join('/')
.replace(/\/+/g, '/')
.replace(/^\//, '')
return database.query(`/${path}`, options)
}
$content.database = database
module.exports.$content = $content
// Call content:ready hook
await this.nuxt.callHook('content:ready', $content)
// Add $content reference to ssrContext
this.nuxt.hook('vue-renderer:context', (ssrContext) => {
ssrContext.$content = $content
})
// Add prism theme
if (options.markdown.prism.theme && !options.markdown.highlighter) {
this.nuxt.options.css.push(options.markdown.prism.theme)
}
// Add content server middleware
this.addServerMiddleware({
path: options.apiPrefix,
handler: middleware({
ws,
database,
dir: options.dir,
watch: options.watch
})
})
// Add server plugin
this.addPlugin({
fileName: 'content/plugin.server.js',
src: join(__dirname, '../templates/plugin.server.js'),
options: {
watch: options.watch,
liveEdit: options.liveEdit
}
})
/* istanbul ignore if */
if (isSSG) {
// Create a hash to fetch the database
const dbHash = hash(JSON.stringify(database.items._data)).substr(0, 8)
// Pass the hash to the publicRuntimeConfig to be used in client side
if (this.options.publicRuntimeConfig) {
this.options.publicRuntimeConfig.content = { dbHash }
} else {
this.nuxt.hook('vue-renderer:ssr:context', (renderContext) => {
renderContext.nuxt.content = { dbHash }
})
}
// Write db.json
this.nuxt.hook('generate:distRemoved', async () => {
const dir = resolve(this.options.buildDir, 'dist', 'client', 'content')
await database.save(dir, `db-${dbHash}.json`)
})
// Add client plugin
this.addTemplate({
fileName: 'content/plugin.client.lazy.js',
src: join(__dirname, '../templates/plugin.static.lazy.js'),
options: {
fullTextSearchFields: options.fullTextSearchFields,
dirs: database.dirs
}
})
let publicPath = this.options.build.publicPath // can be an url
let routerBasePath = this.options.router.base
/* istanbul ignore if */
if (publicPath[publicPath.length - 1] !== '/') {
publicPath += '/'
}
if (routerBasePath[routerBasePath.length - 1] === '/') {
routerBasePath = routerBasePath.slice(0, -1)
}
this.addPlugin({
fileName: 'content/plugin.client.js',
src: join(__dirname, '../templates/plugin.static.js'),
options: {
// if publicPath is an URL, use public path, if not, add basepath before it
dbPath: isUrl(publicPath)
? `${publicPath}content`
: `${routerBasePath}${publicPath}content`
}
})
} else {
this.addPlugin({
fileName: 'content/plugin.client.js',
src: join(__dirname, '../templates/plugin.client.js'),
options: {
apiPrefix: options.apiPrefixWithBase,
watch: options.watch,
liveEdit: options.liveEdit,
readyCallbackName: this.options.globals.readyCallback(
this.options.globalName
)
}
})
}
// Add client plugin QueryBuilder
this.addTemplate({
fileName: 'content/query-builder.js',
src: join(
__dirname,
isSSG ? 'query-builder.js' : '../templates/query-builder.js'
)
})
// Add client plugin component
this.addTemplate({
fileName: 'content/nuxt-content.js',
src: join(__dirname, '../templates/nuxt-content.js')
})
if (options.watch && options.liveEdit) {
// Add dev client plugin component
this.addTemplate({
fileName: 'content/nuxt-content.dev.vue',
src: join(__dirname, '../templates/nuxt-content.dev.vue'),
options: {
apiPrefix: options.apiPrefixWithBase,
editor: options.editor
}
})
// Add dev editor component
this.addTemplate({
fileName: 'content/editor.vue',
src: join(__dirname, '..', 'templates', 'editor.vue')
})
}
function isUrl (string) {
try {
// quick test if the string is an URL
// eslint-disable-next-line no-new
new URL(string)
} catch (_) {
return false
}
return true
}
}
module.exports.Database = Database
module.exports.middleware = middleware
module.exports.getOptions = (userOptions = {}) => {
const defaults = getDefaults({ dev: process.env.NODE_ENV !== 'production' })
const options = defu.arrayFn(userOptions, defaults)
processMarkdownOptions(options)
return options
}