-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathcreateRenderer.ts
More file actions
634 lines (578 loc) · 25.2 KB
/
Copy pathcreateRenderer.ts
File metadata and controls
634 lines (578 loc) · 25.2 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
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
import { dirname, relative as relPath, resolve } from 'node:path'
import { mkdirSync, writeFileSync, existsSync, rmSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { isLaravel } from '../utils/detect.ts'
import { rowSourceLocation } from './plugins/rowSourceLocation.ts'
import { rawExtract } from './plugins/rawExtract.ts'
import { codeBlockExtract } from './plugins/codeBlockExtract.ts'
import { markdownExtract } from './plugins/markdownExtract.ts'
import { createServer, mergeConfig, type InlineConfig, type Plugin } from 'vite'
import vue from '@vitejs/plugin-vue'
import Markdown from 'unplugin-vue-markdown/vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { unheadVueComposablesImports } from '@unhead/vue'
import { defu as merge } from 'defu'
import { glob, globSync } from 'tinyglobby'
import { createSSRApp } from 'vue'
import { renderToString } from 'vue/server-renderer'
import { createHead } from '@unhead/vue/server'
import { MaizzleConfigKey } from '../composables/useConfig.ts'
import { RenderContextKey } from '../composables/renderContext.ts'
import { componentNameFromPath, type NormalizedComponentSource } from '../utils/componentSources.ts'
import { shikiToCodeBlock } from '../components/utils.ts'
import type { Component, InjectionKey } from 'vue'
import type { MaizzleConfig, MarkdownConfig } from '../types/index.ts'
import type { MarkdownExit } from 'markdown-exit'
import type { RenderContext } from '../composables/renderContext.ts'
const __dirname = dirname(fileURLToPath(import.meta.url))
const vuePkgDir = dirname(fileURLToPath(import.meta.resolve('vue/package.json')))
const vueServerRendererPkgDir = dirname(fileURLToPath(import.meta.resolve('@vue/server-renderer/package.json')))
const unheadVuePkgDir = resolve(dirname(fileURLToPath(import.meta.resolve('@unhead/vue'))), '..')
const vueRouterPkgDir = dirname(fileURLToPath(import.meta.resolve('vue-router/package.json')))
export interface RenderedTemplate {
html: string
doctype?: string
templateConfig: MaizzleConfig
sfcEventHandlers: RenderContext['sfcEventHandlers']
plaintext?: RenderContext['plaintext']
outputPath?: RenderContext['outputPath']
tailwindBlocks?: RenderContext['tailwindBlocks']
}
export interface Renderer {
render(input: string | Component, config: MaizzleConfig, opts?: { source?: string; props?: Record<string, any> }): Promise<RenderedTemplate>
invalidate(filePath: string): Promise<void>
invalidateAll(): Promise<void>
close(): Promise<void>
}
export interface CreateRendererOptions {
/** Generate .d.ts files for auto-imports and components (default: false) */
dts?: boolean
/** Options passed to unplugin-vue-markdown */
markdown?: MarkdownConfig
/** Root directory for resolving user component dirs and .d.ts output */
root?: string
/**
* Additional component sources to register for auto-import. Already
* normalized — pass through `normalizeComponentSources()` first.
*/
componentDirs?: NormalizedComponentSource[]
/** User Vite config options to merge into the internal SSR server */
vite?: InlineConfig
}
/**
* Lightweight Vite SSR loader for rendering Vue SFC email templates.
*
* Uses only Vue + unplugin for component/auto-import resolution.
* Tailwind CSS compilation is handled by the transformer pipeline.
*/
export async function createRenderer(
options: CreateRendererOptions = {},
): Promise<Renderer> {
const { dts = false, markdown: markdownOptionsRaw, root = process.cwd(), componentDirs = [], vite: userViteConfig } = options
const { shikiTheme = 'github-light', markdownSetup: userMarkdownSetup, ...restMarkdownConfig } = markdownOptionsRaw ?? {}
/**
* Sources without an explicit prefix get registered via unplugin's `dirs`
* (folder name auto-namespaces). Sources with an explicit `prefix` are
* registered through a custom resolver below so we fully control naming.
*/
const dirSources = componentDirs.filter(s => s.prefix === undefined)
const prefixedSources = componentDirs.filter(s => s.prefix !== undefined)
/**
* Absolute component dirs — used to skip auto-wrapping `.md` files that
* are imported as reusable components (vs. entry-point email templates).
*/
const componentDirsAbs = [resolve(root, 'components'), ...componentDirs.map(s => s.path)]
const dtsDir = isLaravel()
? resolve(process.cwd(), 'resources/js/types/maizzle')
: resolve(root, '.maizzle')
/**
* Built-in framework components live at this path. When a user provides
* a top-level file with the same (PascalCased) basename, drop the
* built-in from unplugin's scan so the user's component is the only
* candidate. This avoids the "naming conflicts" warning and the
* alphabetical-glob ordering pitfall that decides who wins when
* both are present in `dirs`.
*/
const frameworkComponentsDir = resolve(__dirname, '../components')
function topLevelBasenamesLower(dir: string): Set<string> {
if (!existsSync(dir)) return new Set()
const files = globSync(['*.vue', '*.md'], { cwd: dir, absolute: false })
return new Set(files.map(f => f.replace(/\.(vue|md)$/, '').toLowerCase()))
}
const frameworkFiles = globSync(['*.vue', '*.md'], { cwd: frameworkComponentsDir, absolute: false })
const frameworkByLower = new Map(
frameworkFiles.map(f => [f.replace(/\.(vue|md)$/, '').toLowerCase(), f]),
)
const shadowedNames = new Set<string>()
for (const dir of [resolve(root, 'components'), ...dirSources.map(s => s.path)]) {
for (const lower of topLevelBasenamesLower(dir)) {
if (frameworkByLower.has(lower)) shadowedNames.add(lower)
}
}
const frameworkExcludes = [...shadowedNames]
.map(lower => `${frameworkComponentsDir}/${frameworkByLower.get(lower)}`)
/**
* Pre-scanned name → absolute-path map for prefixed sources. Rebuilt
* on file add/unlink via the watcher hook plugin further down. Drives
* the runtime resolver and the d.ts we emit for IDE autocompletion.
*/
const prefixedNameMap = new Map<string, string>()
async function scanPrefixedSources(): Promise<void> {
prefixedNameMap.clear()
const seen = new Map<string, string>()
for (const source of prefixedSources) {
const files = await glob(['**/*.vue', '**/*.md'], { cwd: source.path, absolute: true })
for (const file of files) {
const name = componentNameFromPath({
filePath: file,
dirRoot: source.path,
prefix: source.prefix,
pathPrefix: source.pathPrefix,
})
const existing = seen.get(name)
if (existing && existing !== file) {
throw new Error(
`[maizzle] Component name collision: "${name}" resolved from both "${existing}" and "${file}". `
+ 'Rename one of the files or split them into separate sources with distinct prefixes.',
)
}
seen.set(name, file)
prefixedNameMap.set(name, file)
}
}
}
await scanPrefixedSources()
const prefixedResolver = (name: string) => prefixedNameMap.get(name)
/**
* unplugin-vue-components' own d.ts only covers components found via
* `dirs`; its `types` option emits named-import entries which break
* for SFC `default` exports. Write a sibling d.ts for prefixed
* sources so editors get correct autocompletion via TypeScript
* interface merging on `vue.GlobalComponents`.
*/
const prefixedDtsPath = resolve(dtsDir, 'prefixed-components.d.ts')
function writePrefixedDts(): void {
if (!dts) return
if (prefixedNameMap.size === 0) {
if (existsSync(prefixedDtsPath)) rmSync(prefixedDtsPath)
return
}
const dtsBase = dirname(prefixedDtsPath)
mkdirSync(dtsBase, { recursive: true })
const lines = Array.from(prefixedNameMap.entries())
.sort(([a], [b]) => a.localeCompare(b))
.map(([name, file]) => {
const relativePath = relPath(dtsBase, file).replace(/\\/g, '/')
const importPath = relativePath.startsWith('.') ? relativePath : `./${relativePath}`
return ` ${name}: typeof import('${importPath}')['default']`
})
.join('\n')
writeFileSync(
prefixedDtsPath,
`/* eslint-disable */\n// @ts-nocheck\n// biome-ignore lint: disable\n// oxlint-disable\n// Generated by Maizzle for prefixed component sources\n\nexport {}\n\n/* prettier-ignore */\ndeclare module 'vue' {\n export interface GlobalComponents {\n${lines}\n }\n}\n`,
)
}
writePrefixedDts()
/**
* Watches prefixed source dirs and rebuilds {@link prefixedNameMap} when
* files are added/removed. Vite's watcher already covers `dirSources`
* via unplugin-vue-components' own filesystem hooks.
*/
const prefixedSourceWatcher: Plugin | null = prefixedSources.length > 0
? {
name: 'maizzle:prefixed-component-watcher',
configureServer(server) {
for (const source of prefixedSources) {
server.watcher.add(source.path)
}
const refresh = async (file: string) => {
if (!prefixedSources.some(s => file.startsWith(`${s.path}/`))) return
if (!/\.(vue|md)$/.test(file)) return
await scanPrefixedSources()
writePrefixedDts()
}
server.watcher.on('add', refresh)
server.watcher.on('unlink', refresh)
},
}
: null
const VIRTUAL_SFC_ID = 'virtual:maizzle-sfc.vue'
let virtualSfcSource = ''
/**
* Per-render source overrides keyed by absolute template path. Lets the
* build's beforeRender event rewrite a template's source before compile
* while keeping the real file id — so relative imports, asset URLs and
* component resolution still resolve against the actual file location
* (which the virtual-SFC path can't do).
*/
const sourceOverrides = new Map<string, string>()
/**
* Never load the host project's vite.config.ts here. Doing so pulls
* every host plugin (Nitro, TanStack Start, the Maizzle plugin
* itself, …) into this isolated SSR pipeline, where they override
* env factories, re-trigger configureServer hooks, and break
* Vite's hot channel wiring. Users who need extra Vite plugins
* for SSR pass them explicitly via the `vite` option.
*/
const maizzleConfig: InlineConfig = {
configFile: false,
plugins: [
rawExtract(),
codeBlockExtract(),
markdownExtract(),
rowSourceLocation(),
{
name: 'maizzle:virtual-sfc',
resolveId(id) {
if (id === VIRTUAL_SFC_ID) return id
},
load(id) {
if (id === VIRTUAL_SFC_ID) return virtualSfcSource
},
},
{
name: 'maizzle:source-override',
load(id) {
const override = sourceOverrides.get(id.split('?')[0])
if (override !== undefined) return override
},
},
vue({
include: [/\.vue$/, /\.md$/],
template: {
transformAssetUrls: false,
compilerOptions: {
/**
* Keep template whitespace intact — the default `condense`
* mode collapses/strips whitespace between tags,
* which can alter plaintext output.
*/
whitespace: 'preserve',
/**
* AMP4Email tags (<amp-carousel>, <amp-img>, <amp-list> ...)
* render verbatim — skip the component resolver. Users who
* want to wrap an amp tag in a Vue component should register
* it under a PascalCase name (e.g. `components/AmpCarousel.vue`
* → `<AmpCarousel>`).
*/
isCustomElement: (tag: string) => tag.startsWith('amp-'),
},
},
}),
Markdown(merge(restMarkdownConfig, {
headEnabled: true,
wrapperDiv: false,
wrapperClasses: 'prose',
wrapperComponent: (id: string, raw: string) => {
const fm = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/)?.[1]
const layout = fm?.match(/^[ \t]*layout[ \t]*:[ \t]*['"]?([A-Za-z][\w-]*|false|none)['"]?[ \t]*$/m)?.[1]
if (layout === 'false' || layout === 'none') return null
if (layout) return layout
/**
* No `layout:` set — default to the built-in `MarkdownLayout`
* for entry-template `.md` files. Skip for `.md` files inside
* component dirs, which are reusable fragments imported into
* other templates.
*/
const inComponentDir = componentDirsAbs.some(d => id === d || id.startsWith(`${d}/`))
return inComponentDir ? null : 'MarkdownLayout'
},
markdownOptions: {
async highlight(code: string, lang: string) {
const { codeToHtml } = await import('shiki')
try {
return await codeToHtml(code, { lang, theme: shikiTheme })
} catch {
return ''
}
},
},
/**
* Run the user's `markdownSetup` first (defu would otherwise drop the
* built-in one when both are functions), then always install the
* email-safe code-block wrapping on top — mirroring the `<Markdown>`
* component so `.md` templates and the component behave identically.
*/
async markdownSetup(md: MarkdownExit) {
// `md` is cast because unplugin-vue-markdown bundles its own
// markdown-exit copy, so its `MarkdownExit` is nominally distinct
// from ours despite being structurally identical.
await userMarkdownSetup?.(md as unknown as Parameters<NonNullable<typeof userMarkdownSetup>>[0])
const defaultFence = md.renderer.rules.fence!
md.renderer.rules.fence = (...args) =>
Promise.resolve(defaultFence(...args)).then(shikiToCodeBlock)
const defaultCodeBlock = md.renderer.rules.code_block!
md.renderer.rules.code_block = (...args) => shikiToCodeBlock(defaultCodeBlock(...args) as string)
},
})),
AutoImport({
dirs: [
resolve(__dirname, '../composables'),
resolve(__dirname, '../filters'),
],
imports: ['vue', unheadVueComposablesImports],
/**
* unplugin-auto-import's default `include` doesn't match `.md`, so
* auto-imports (Vue, unhead and Maizzle composables/filters) were
* never injected into Markdown templates — `useConfig()` and friends
* threw at runtime. Extend the default list with `.md` (and its
* `?vue` script sub-requests) to mirror the `.md` coverage the
* Components plugin already declares below.
*/
include: [/\.[jt]sx?$/, /\.vue$/, /\.vue\?vue/, /\.md$/, /\.md\?vue/],
dts: dts ? resolve(dtsDir, 'auto-imports.d.ts') : false,
}),
Components({
extensions: ['vue', 'md'],
include: [/\.vue$/, /\.vue\?vue/, /\.md$/],
dirs: [
frameworkComponentsDir,
resolve(root, 'components'),
...dirSources.map(s => s.path),
],
/**
* Drop built-in component files whose name the user has shadowed.
* This makes the user's version the only match — no "naming
* conflicts" warning, no glob-ordering games.
*/
globsExclude: frameworkExcludes,
directoryAsNamespace: true,
collapseSamePrefixes: true,
resolvers: prefixedSources.length > 0 ? [prefixedResolver] : undefined,
dts: dts ? resolve(dtsDir, 'components.d.ts') : false,
}),
...(prefixedSourceWatcher ? [prefixedSourceWatcher] : []),
],
resolve: {
alias: {
'vue/server-renderer': resolve(vueServerRendererPkgDir, 'dist/server-renderer.esm-bundler.js'),
'vue': resolve(vuePkgDir, 'dist/vue.runtime.esm-bundler.js'),
'vue-router': vueRouterPkgDir,
'@unhead/vue/server': resolve(unheadVuePkgDir, 'dist/server.mjs'),
'@unhead/vue': resolve(unheadVuePkgDir, 'dist/index.mjs'),
},
},
server: {
middlewareMode: true,
hmr: false,
/**
* Watcher is required so unplugin-vue-components and unplugin-auto-import
* detect added/removed component files and rewrite their .d.ts on the fly.
* (We only render via SSR — HMR is off, but chokidar still drives plugins.)
*/
fs: {
allow: [process.cwd(), root, ...componentDirs.map(s => s.path), vuePkgDir, vueServerRendererPkgDir, unheadVuePkgDir, vueRouterPkgDir],
},
},
appType: 'custom',
logLevel: 'silent',
optimizeDeps: {
noDiscovery: true,
},
}
/**
* Merge user's vite config (from config.vite) under Maizzle's config.
* mergeConfig(a, b) → b overrides a for scalars, arrays concatenate.
* This ensures Maizzle's critical settings (middlewareMode, appType,
* etc.) always win, while user plugins and other options remain.
*/
const finalConfig = userViteConfig
? mergeConfig(userViteConfig, maizzleConfig)
: maizzleConfig
const server = await createServer(finalConfig)
return {
async render(input: string | Component, config: MaizzleConfig, opts?: { source?: string; props?: Record<string, any> }): Promise<RenderedTemplate> {
let component: Component
let configKey: InjectionKey<MaizzleConfig>
let contextKey: InjectionKey<RenderContext>
if (typeof input === 'string') {
/**
* String input goes through Vite — must use ssrLoadModule for
* injection keys so they share the same module instance as SFC.
*/
const configModule = await server.ssrLoadModule(resolve(__dirname, '../composables/useConfig'))
const contextModule = await server.ssrLoadModule(resolve(__dirname, '../composables/renderContext'))
configKey = configModule.MaizzleConfigKey
contextKey = contextModule.RenderContextKey
if (input.includes('<template') || input.includes('<script')) {
virtualSfcSource = input
const mod = server.moduleGraph.getModuleById(VIRTUAL_SFC_ID)
if (mod) server.moduleGraph.invalidateModule(mod)
component = (await server.ssrLoadModule(VIRTUAL_SFC_ID)).default
} else {
/**
* A beforeRender handler may have rewritten the source. Register it
* under the real path id and invalidate so ssrLoadModule compiles
* the override; clear + invalidate afterwards so the override never
* leaks into a later render of the same path.
*/
const hasOverride = opts?.source !== undefined
if (hasOverride) {
sourceOverrides.set(input, opts!.source!)
const mod = await server.moduleGraph.getModuleByUrl(input)
if (mod) server.moduleGraph.invalidateModule(mod)
}
try {
component = (await server.ssrLoadModule(input)).default
} finally {
if (hasOverride) {
sourceOverrides.delete(input)
const mod = await server.moduleGraph.getModuleByUrl(input)
if (mod) server.moduleGraph.invalidateModule(mod)
}
}
}
} else {
// Pre-compiled component — use directly imported keys
component = input
configKey = MaizzleConfigKey
contextKey = RenderContextKey
}
const renderContext: RenderContext = {
doctype: undefined,
sfcConfig: undefined,
sfcEventHandlers: [],
}
const head = createHead({ disableDefaults: true })
const app = createSSRApp(component, opts?.props)
app.use(head)
// Register user Vue plugins, directives, and global properties
if (config.vue) {
const plugins = typeof config.vue.plugins === 'function'
? config.vue.plugins()
: config.vue.plugins ?? []
for (const plugin of plugins) {
app.use(plugin)
}
for (const [name, directive] of Object.entries(config.vue.directives ?? {})) {
app.directive(name, directive)
}
Object.assign(app.config.globalProperties, config.vue.globalProperties)
}
app.provide(configKey, config)
app.provide(contextKey, renderContext)
const ssrContext: Record<string, any> = {}
let html: string = await renderToString(app, ssrContext)
const { headTags, bodyTags, bodyTagsOpen, htmlAttrs, bodyAttrs } = head.render()
// Inject head entries into the rendered HTML
if (htmlAttrs) {
html = html.replace(/<html([^>]*)>/, `<html$1 ${htmlAttrs}>`)
}
if (headTags) {
html = html.replace('</head>', `${headTags}\n</head>`)
}
if (bodyAttrs) {
html = html.replace(/<body([^>]*)>/, `<body$1 ${bodyAttrs}>`)
}
if (bodyTagsOpen) {
html = html.replace(/<body([^>]*)>/, `<body$1>\n${bodyTagsOpen}`)
}
if (bodyTags) {
html = html.replace('</body>', `${bodyTags}\n</body>`)
}
// Inject SSR teleport content into their target elements
const hasTeleports = ssrContext.teleports && Object.keys(ssrContext.teleports).length > 0
const hasFonts = (renderContext.fonts?.length ?? 0) > 0
if (hasTeleports || hasFonts) {
const { parse: parseDom, serialize: serializeDom, walk } = await import('../utils/ast/index.ts')
let dom = parseDom(html)
if (hasTeleports) {
for (const [rawTarget, content] of Object.entries(ssrContext.teleports) as [string, string][]) {
if (!content) continue
const prepend = rawTarget.endsWith(':start')
const target = prepend ? rawTarget.slice(0, -6) : rawTarget
const targetChildren = parseDom(content)
walk(dom, (node) => {
const el = node as import('domhandler').Element
if (!el.name) return
const matched
= target === el.name
|| (target.startsWith('#') && el.attribs?.id === target.slice(1))
|| (target.startsWith('.') && el.attribs?.class?.split(/\s+/).includes(target.slice(1)))
if (matched) {
for (const child of targetChildren) {
child.parent = el as any
}
el.children = prepend
? [...targetChildren, ...(el.children || [])] as any
: [...(el.children || []), ...targetChildren] as any
}
})
}
}
if (hasFonts) {
const { injectFonts } = await import('./injectFonts.ts')
injectFonts(dom, renderContext.fonts!, parseDom, walk)
}
html = serializeDom(dom)
}
// Inject preheader text from usePreheader() composable
if (renderContext.preheader) {
const { text, fillerCount } = renderContext.preheader
const filler = '\u2007\uFEFF\u034F '.repeat(fillerCount)
const previewHtml = `<div style="display:none">${text}${filler}\u00A0</div>`
html = html.replace(/<body([^>]*)>/, `<body$1>${previewHtml}`)
}
/**
* Strip Vue SSR fragment markers + teleport anchor comments. These
* are rendering hygiene, not transformer concerns — must run
* regardless of `useTransformers` state. Fragment markers contain
* `-->`, which would prematurely terminate MSO conditional
* comments downstream.
*/
html = html
.replaceAll('<!--[-->', '')
.replaceAll('<!--]-->', '')
.replaceAll('<!--teleport start anchor-->', '')
.replaceAll('<!--teleport anchor-->', '')
.replaceAll('<!--teleport start-->', '')
.replaceAll('<!--teleport end-->', '')
return {
html,
doctype: renderContext.doctype,
/**
* Layer sfcConfig over config — sfcConfig is a partial override
* emitted by composables (defineConfig, useTransformers, etc.).
* A naive replacement (`sfcConfig ?? config`) drops defaults
* from the resolved config when the SFC only sets a single
* key, since the composables' inject() of globalConfig can
* return `{}` in dev when ssrLoadModule and the SFC's
* auto-imported module resolve to different module
* instances (different Symbols).
*/
templateConfig: renderContext.sfcConfig ? merge(renderContext.sfcConfig, config) : config,
sfcEventHandlers: renderContext.sfcEventHandlers,
plaintext: renderContext.plaintext,
outputPath: renderContext.outputPath,
tailwindBlocks: renderContext.tailwindBlocks,
}
},
async invalidate(filePath: string): Promise<void> {
const mod = await server.moduleGraph.getModuleByUrl(filePath)
if (mod) {
server.moduleGraph.invalidateModule(mod)
}
},
async invalidateAll(): Promise<void> {
for (const mod of server.moduleGraph.idToModuleMap.values()) {
server.moduleGraph.invalidateModule(mod)
}
},
async close(): Promise<void> {
await server.close()
/**
* unplugin-auto-import schedules a 500ms-throttled, fire-and-forget
* d.ts write on its first scan. server.close() doesn't drain that
* pending write, so callers tearing down the working dir right
* after close (tests, ephemeral build pipelines) can race the
* mkdir against a missing parent directory. Wait one throttle
* window past close so the lingering write resolves while
* the dir still exists.
*/
if (dts) {
await new Promise(resolve => setTimeout(resolve, 600))
}
},
}
}