-
-
Notifications
You must be signed in to change notification settings - Fork 666
/
Copy pathmodule.ts
434 lines (397 loc) · 12.7 KB
/
module.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
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
import fs from 'fs'
import {
addPlugin,
defineNuxtModule,
resolveModule,
createResolver,
addAutoImport,
addComponentsDir,
templateUtils,
useLogger
} from '@nuxt/kit'
import defu from 'defu'
import { createStorage } from 'unstorage'
import { join } from 'pathe'
import type { Lang as ShikiLang, Theme as ShikiTheme } from 'shiki-es'
import { listen } from 'listhen'
import type { WatchEvent } from 'unstorage'
import { debounce } from 'perfect-debounce'
import { name, version } from '../package.json'
import {
createWebSocket,
getMountDriver,
MOUNT_PREFIX,
processMarkdownOptions,
PROSE_TAGS,
useContentMounts
} from './utils'
export type MountOptions = {
name: string
prefix?: string
driver: 'fs' | 'http' | string
[options: string]: any
}
export interface ModuleOptions {
/**
* Base route that will be used for content api
*
* @default '_content'
*/
base: string
/**
* Disable content watcher and hot content reload.
* Note: Watcher is a development feature and will not includes in the production.
*
* @default true
*/
watch: boolean
/**
* Contents can located in multiple places, in multiple directories or even in remote git repositories.
* Using sources option you can tell Content module where to look for contents.
*
* @default ['content']
*/
sources: Array<string | MountOptions>
/**
* List of ignore pattern that will be used for excluding content from parsing and rendering.
*
* @default ['\\.', '-']
*/
ignores: Array<string>
/**
* Content module uses `remark` and `rehype` under the hood to compile markdown files.
* You can modify this options to control its behavior.
*/
markdown: {
/**
* Whether MDC syntax should be supported or not.
*
* @default true
*/
mdc?: boolean
/**
* Control behavior of Table of Contents generation
*/
toc?: {
/**
* Maximum heading depth that includes in the table of contents.
*
* @default 2
*/
depth?: number
/**
* Maximum depth of nested tags to search for heading.
*
* @default 2
*/
searchDepth?: number
},
/**
* Tags will be used to replace markdown components and render custom components instead of default ones.
*
* @default {}
*/
tags?: Record<string, string>
/**
* Register custom remark plugin to provide new feature into your markdown contents.
* Checkout: https://github.com/remarkjs/remark/blob/main/doc/plugins.md
*
* @default []
*/
remarkPlugins?: Array<string | [string, any]>
/**
* Register custom remark plugin to provide new feature into your markdown contents.
* Checkout: https://github.com/rehypejs/rehype/blob/main/doc/plugins.md
*
* @default []
*/
rehypePlugins?: Array<string | [string, any]>
}
/**
* Content module uses `shiki` to highlight code blocks.
* You can configure Shiki options to control its behavior.
*/
highlight: false | {
/**
* Default theme that will be used for highlighting code blocks.
*/
theme: ShikiTheme,
/**
* Preloaded languages that will be available for highlighting code blocks.
*/
preload: ShikiLang[]
},
/**
* Options for yaml parser.
*
* @default {}
*/
yaml: false | Record<string, any>
/**
* Options for yaml parser.
*
* @default {}
*/
csv: false | Record<string, any>
/**
* Enable/Disable navigation.
*
* @defaul {}
*/
navigation: false | {
fields: Array<string>
}
/**
* List of locale codes.
* This codes will be used to detect contents locale.
*
* @default []
*/
locales: Array<string>
/**
* Default locale for top level contents.
*
* @default undefined
*/
defaultLocale: string
}
interface ContentContext extends ModuleOptions {
base: Readonly<string>
transformers: Array<string>
}
export interface ModuleHooks {
'content:context'(ctx: ContentContext): void
}
export default defineNuxtModule<ModuleOptions>({
meta: {
name,
version,
configKey: 'content',
compatibility: {
nuxt: '^3.0.0',
bridge: true
}
},
defaults: {
base: '_content',
watch: true,
sources: ['content'],
ignores: ['\\.', '-'],
locales: [],
defaultLocale: undefined,
highlight: false,
markdown: {
tags: Object.fromEntries(PROSE_TAGS.map(t => [t, `prose-${t}`]))
},
yaml: {},
csv: {},
navigation: {
fields: []
}
},
async setup (options, nuxt) {
const { resolve } = createResolver(import.meta.url)
const resolveRuntimeModule = (path: string) => resolveModule(path, { paths: resolve('./runtime') })
const logger = useLogger('@nuxt/content')
const contentContext: ContentContext = {
transformers: [
// Register internal content plugins
resolveRuntimeModule('./server/transformers/markdown'),
resolveRuntimeModule('./server/transformers/yaml'),
resolveRuntimeModule('./server/transformers/json'),
resolveRuntimeModule('./server/transformers/csv'),
resolveRuntimeModule('./server/transformers/path-meta')
],
...options
}
// Add Vite configurations
if (nuxt.options.vite !== false) {
nuxt.options.vite = defu(
nuxt.options.vite === true ? {} : nuxt.options.vite,
{
optimizeDeps: {
include: ['html-tags']
}
}
)
}
// Tell Nuxt to ignore content dir for app build
options.sources.forEach((source) => {
if (typeof source === 'string') {
nuxt.options.ignore.push(join('content', '**'))
}
// TODO: handle object format and make sure to ignore urls
})
// Add Content plugin
addPlugin(resolveRuntimeModule('./plugin'))
nuxt.hook('nitro:config', (nitroConfig) => {
// Add server handlers
nitroConfig.handlers = nitroConfig.handlers || []
nitroConfig.handlers.push({
method: 'get',
route: `/api/${options.base}/query/:query`,
handler: resolveRuntimeModule('./server/api/query')
})
nitroConfig.handlers.push({
method: 'get',
route: `/api/${options.base}/cache`,
handler: resolveRuntimeModule('./server/api/cache')
})
if (!nuxt.options.dev) {
nitroConfig.prerender.routes.push('/api/_content/cache')
}
// Register source storages
const sources = useContentMounts(nuxt, contentContext.sources || [])
nitroConfig.devStorage = Object.assign(
nitroConfig.devStorage || {},
sources
)
nitroConfig.bundledStorage = nitroConfig.bundledStorage || []
nitroConfig.bundledStorage.push('/cache/content')
nitroConfig.externals = defu(typeof nitroConfig.externals === 'object' ? nitroConfig.externals : {}, {
inline: [
// Inline module runtime in Nitro bundle
resolve('./runtime')
]
})
nitroConfig.autoImport = nitroConfig.autoImport || {}
nitroConfig.autoImport.imports = nitroConfig.autoImport.imports || []
nitroConfig.autoImport.imports.push(...[
{ name: 'parse', as: 'contentParse', from: resolveRuntimeModule('./server/transformers') },
{ name: 'transform', as: 'contentTransform', from: resolveRuntimeModule('./server/transformers') }
])
nitroConfig.virtual = nitroConfig.virtual || {}
nitroConfig.virtual['#content/virtual/transformers'] = [
// TODO: remove kit usage
templateUtils.importSources(contentContext.transformers),
`const transformers = [${contentContext.transformers.map(templateUtils.importName).join(', ')}]`,
'export const getParser = (ext) => transformers.find(p => ext.match(new RegExp(p.extentions.join("|"), "i")) && p.parse)',
'export const getTransformers = (ext) => transformers.filter(p => ext.match(new RegExp(p.extentions.join("|"), "i")) && p.transform)',
'export default () => {}'
].join('\n')
})
// Register composables
addAutoImport([
{ name: 'queryContent', as: 'queryContent', from: resolveRuntimeModule('./composables/query') },
{ name: 'withContentBase', as: 'withContentBase', from: resolveRuntimeModule('./composables/utils') },
{ name: 'useUnwrap', as: 'useUnwrap', from: resolveRuntimeModule('./composables/utils') }
])
// Register components
await addComponentsDir({
path: resolve('./runtime/components'),
pathPrefix: false,
prefix: '',
level: 999,
global: true
})
// Register user global components
const globalComponents = resolve(nuxt.options.srcDir, 'components/content')
const dirStat = await fs.promises.stat(globalComponents).catch(() => null)
if (dirStat && dirStat.isDirectory()) {
logger.success('Using `~/components/content` for components in Markdown')
nuxt.hook('components:dirs', (dirs) => {
// Unshift to make it before ~/components
dirs.unshift({
path: globalComponents,
global: true,
pathPrefix: false,
prefix: ''
})
})
} else {
const componentsDir = resolve(nuxt.options.srcDir, 'components/')
const componentsDirStat = await fs.promises.stat(componentsDir).catch(() => null)
if (componentsDirStat && componentsDirStat.isDirectory()) {
// TODO: watch for file creation and tell Nuxt to restart
// Not possible for now since directories are hard-coded: https://github.com/nuxt/framework/blob/5b63ae8ad54eeb3cb49479da8f32eacc1a743ca0/packages/nuxi/src/commands/dev.ts#L94
logger.info('Please create `~/components/content` and restart the Nuxt server to use components in Markdown')
}
}
// Register navigation
if (options.navigation) {
addAutoImport({ name: 'fetchContentNavigation', as: 'fetchContentNavigation', from: resolveRuntimeModule('./composables/navigation') })
nuxt.hook('nitro:config', (nitroConfig) => {
nitroConfig.handlers.push({
method: 'get',
route: `/api/${options.base}/navigation/:query`,
handler: resolveRuntimeModule('./server/api/navigation')
})
})
}
// Register highlighter
if (options.highlight) {
contentContext.transformers.push(resolveRuntimeModule('./server/transformers/shiki'))
nuxt.hook('nitro:config', (nitroConfig) => {
nitroConfig.handlers.push({
method: 'post',
route: `/api/${options.base}/highlight`,
handler: resolveRuntimeModule('./server/api/highlight')
})
})
}
// @ts-ignore
await nuxt.callHook('content:context', contentContext)
contentContext.defaultLocale = contentContext.defaultLocale || contentContext.locales[0]
// Process markdown plugins, resovle paths
contentContext.markdown = processMarkdownOptions(contentContext.markdown)
nuxt.options.runtimeConfig.public.content = {
base: options.base,
// Tags will use in markdown renderer for component replacement
tags: contentContext.markdown.tags as any,
highlight: options.highlight,
wsUrl: ''
}
// Context will use in server
nuxt.options.runtimeConfig.content = contentContext as any
// Setup content dev module
if (!nuxt.options.dev || !options.watch) {
return
}
// Create storage instance
const storage = createStorage()
const mounts = useContentMounts(nuxt, contentContext.sources || [])
for (const mount in mounts) {
storage.mount(mount, getMountDriver(mounts[mount]))
}
const ws = createWebSocket()
// Dispose storage on nuxt close
nuxt.hook('close', async () => {
await Promise.all([
storage.dispose(),
ws.close()
])
})
// Listen dev server
const { server, url } = await listen(() => 'Nuxt Content', { port: 4000, showURL: false })
server.on('upgrade', ws.serve)
// Register ws url
nuxt.options.runtimeConfig.public.content.wsUrl = url.replace('http', 'ws')
// Broadcast a message to the server to refresh the page
const broadcast = debounce((event: WatchEvent, key: string) => {
key = key.substring(MOUNT_PREFIX.length)
logger.info(`${key} ${event}d`)
ws.broadcast({ event, key })
}, 50)
// Watch contents
storage.watch(broadcast)
}
})
interface ModulePublicRuntimeConfig {
tags: Record<string, string>
base: string;
// Websocket server URL
wsUrl?: string;
// Shiki config
highlight: ModuleOptions['highlight']
}
interface ModulePrivateRuntimeConfig {}
declare module '@nuxt/schema' {
interface ConfigSchema {
publicRuntimeConfig?: {
content?: ModulePublicRuntimeConfig;
};
privateRuntimeConfig?: {
content?: ModulePrivateRuntimeConfig & ContentContext;
};
}
}