2021-12-22 13:04:06 +00:00
|
|
|
import { promises as fsp } from 'fs'
|
|
|
|
import { resolve, join, dirname, basename } from 'upath'
|
|
|
|
import type { Plugin } from 'vite'
|
|
|
|
import Critters from 'critters'
|
|
|
|
import template from 'lodash.template'
|
2022-03-10 20:25:58 +00:00
|
|
|
import { genObjectFromRawEntries } from 'knitwork'
|
2021-12-22 13:04:06 +00:00
|
|
|
import htmlMinifier from 'html-minifier'
|
|
|
|
import { camelCase } from 'scule'
|
|
|
|
import genericMessages from '../templates/messages.json'
|
|
|
|
|
|
|
|
const r = (...path: string[]) => resolve(join(__dirname, '..', ...path))
|
|
|
|
|
|
|
|
const replaceAll = (input, search, replace) => input.split(search).join(replace)
|
|
|
|
|
|
|
|
export const RenderPlugin = () => {
|
2022-09-02 08:46:02 +00:00
|
|
|
return <Plugin> {
|
2021-12-22 13:04:06 +00:00
|
|
|
name: 'render',
|
|
|
|
enforce: 'post',
|
|
|
|
async writeBundle () {
|
|
|
|
const distDir = r('dist')
|
|
|
|
const critters = new Critters({ path: distDir })
|
2021-12-22 21:27:23 +00:00
|
|
|
const globby = await import('globby').then(r => r.globby)
|
|
|
|
const htmlFiles = await globby(r('dist/templates/**/*.html'))
|
2021-12-22 13:04:06 +00:00
|
|
|
|
|
|
|
const templateExports = []
|
|
|
|
|
|
|
|
for (const fileName of htmlFiles) {
|
|
|
|
// Infer template name
|
|
|
|
const templateName = basename(dirname(fileName))
|
|
|
|
|
|
|
|
// eslint-disable-next-line no-console
|
|
|
|
console.log('Processing', templateName)
|
|
|
|
|
|
|
|
// Read source template
|
|
|
|
let html = await fsp.readFile(fileName, 'utf-8')
|
2023-06-20 11:27:42 +00:00
|
|
|
const isCompleteHTML = html.includes('<!DOCTYPE html>')
|
2021-12-22 13:04:06 +00:00
|
|
|
|
2023-07-28 16:37:20 +00:00
|
|
|
if (html.includes('<html')) {
|
|
|
|
// Apply critters to inline styles
|
|
|
|
html = await critters.process(html)
|
|
|
|
}
|
2021-12-22 13:04:06 +00:00
|
|
|
// We no longer need references to external CSS
|
|
|
|
html = html.replace(/<link[^>]*>/g, '')
|
|
|
|
|
|
|
|
// Inline SVGs
|
|
|
|
const svgSources = Array.from(html.matchAll(/src="([^"]+)"|url([^)]+)/g))
|
|
|
|
.map(m => m[1])
|
|
|
|
.filter(src => src?.match(/\.svg$/))
|
|
|
|
|
|
|
|
for (const src of svgSources) {
|
|
|
|
const svg = await fsp.readFile(r('dist', src), 'utf-8')
|
|
|
|
const base64Source = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`
|
|
|
|
html = replaceAll(html, src, base64Source)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Inline our scripts
|
|
|
|
const scriptSources = Array.from(html.matchAll(/<script[^>]*src="(.*)"[^>]*>[\s\S]*?<\/script>/g))
|
|
|
|
.filter(([_block, src]) => src?.match(/^\/.*\.js$/))
|
|
|
|
|
|
|
|
for (const [scriptBlock, src] of scriptSources) {
|
|
|
|
let contents = await fsp.readFile(r('dist', src), 'utf-8')
|
|
|
|
contents = replaceAll(contents, '/* empty css */', '').trim()
|
|
|
|
html = html.replace(scriptBlock, contents.length ? `<script>${contents}</script>` : '')
|
|
|
|
}
|
|
|
|
|
|
|
|
// Minify HTML
|
|
|
|
html = htmlMinifier.minify(html, { collapseWhitespace: true })
|
|
|
|
|
2023-06-20 11:27:42 +00:00
|
|
|
if (!isCompleteHTML) {
|
|
|
|
html = html.replace('<html><head></head><body>', '')
|
|
|
|
html = html.replace('</body></html>', '')
|
|
|
|
}
|
|
|
|
|
2021-12-22 13:04:06 +00:00
|
|
|
// Load messages
|
|
|
|
const messages = JSON.parse(await fsp.readFile(r(`templates/${templateName}/messages.json`), 'utf-8'))
|
|
|
|
|
|
|
|
// Serialize into a js function
|
|
|
|
const jsCode = [
|
|
|
|
`const _messages = ${JSON.stringify({ ...genericMessages, ...messages })}`,
|
2022-05-07 17:58:08 +00:00
|
|
|
`const _render = ${template(html, { variable: '__var__', interpolate: /{{{?([\s\S]+?)}?}}/g }).toString().replace('__var__', '{ messages }')}`,
|
2021-12-22 13:04:06 +00:00
|
|
|
'const _template = (messages) => _render({ messages: { ..._messages, ...messages } })'
|
|
|
|
].join('\n').trim()
|
|
|
|
|
2022-03-10 20:25:58 +00:00
|
|
|
const templateContent = html
|
|
|
|
.match(/<body.*?>([\s\S]*)<\/body>/)?.[0]
|
|
|
|
.replace(/(?<=<|<\/)body/g, 'div')
|
|
|
|
.replace(/messages\./g, '')
|
2022-03-10 20:55:31 +00:00
|
|
|
.replace(/<script[^>]*>([\s\S]*?)<\/script>/g, '')
|
2022-03-10 22:27:16 +00:00
|
|
|
.replace(/<a href="(\/[^"]*)"([^>]*)>([\s\S]*)<\/a>/g, '<NuxtLink to="$1"$2>\n$3\n</NuxtLink>')
|
2022-09-02 08:46:02 +00:00
|
|
|
// eslint-disable-next-line no-template-curly-in-string
|
|
|
|
.replace(/<([^>]+) ([a-z]+)="([^"]*)({{\s*(\w+?)\s*}})([^"]*)"([^>]*)>/g, '<$1 :$2="`$3${$5}$6`"$7>')
|
2022-05-07 17:58:08 +00:00
|
|
|
.replace(/>{{\s*(\w+?)\s*}}<\/[\w-]*>/g, ' v-text="$1" />')
|
|
|
|
.replace(/>{{{\s*(\w+?)\s*}}}<\/[\w-]*>/g, ' v-html="$1" />')
|
2022-03-10 20:25:58 +00:00
|
|
|
// We are not matching <link> <script> and <meta> tags as these aren't used yet in nuxt/ui
|
|
|
|
// and should be taken care of wherever this SFC is used
|
|
|
|
const title = html.match(/<title.*?>([\s\S]*)<\/title>/)?.[1].replace(/{{([\s\S]+?)}}/g, (r) => {
|
|
|
|
return `\${${r.slice(2, -2)}}`.replace(/messages\./g, 'props.')
|
|
|
|
})
|
2022-03-10 22:23:54 +00:00
|
|
|
const styleContent = Array.from(html.matchAll(/<style[^>]*>([\s\S]*?)<\/style>/g)).map(block => block[1]).join('\n')
|
2022-08-09 21:25:46 +00:00
|
|
|
const globalStyles = styleContent.replace(/(\.[^{\d][^{]*?\{[^}]*?\})+.?/g, (r) => {
|
2022-07-20 14:48:53 +00:00
|
|
|
const lastChar = r[r.length - 1]
|
|
|
|
if (lastChar && !['}', '.', '@', '*', ':'].includes(lastChar)) {
|
|
|
|
return ';' + lastChar
|
|
|
|
}
|
|
|
|
return lastChar
|
2022-08-09 21:25:46 +00:00
|
|
|
}).replace(/@media[^{]*?\{\}/g, '')
|
2022-03-10 20:55:31 +00:00
|
|
|
const inlineScripts = Array.from(html.matchAll(/<script>([\s\S]*?)<\/script>/g))
|
|
|
|
.map(block => block[1])
|
|
|
|
.filter(i => !i.includes('const t=document.createElement("link")'))
|
2022-03-10 20:25:58 +00:00
|
|
|
const props = genObjectFromRawEntries(Object.entries({ ...genericMessages, ...messages }).map(([key, value]) => [key, {
|
|
|
|
type: typeof value === 'string' ? 'String' : typeof value === 'number' ? 'Number' : typeof value === 'boolean' ? 'Boolean' : 'undefined',
|
|
|
|
default: JSON.stringify(value)
|
|
|
|
}]))
|
|
|
|
const vueCode = [
|
2022-03-10 22:41:01 +00:00
|
|
|
'<script setup>',
|
2022-04-07 10:57:16 +00:00
|
|
|
title && 'import { useHead } from \'#imports\'',
|
2022-03-10 20:55:31 +00:00
|
|
|
`const props = defineProps(${props})`,
|
2022-04-07 10:57:16 +00:00
|
|
|
title && 'useHead(' + genObjectFromRawEntries([
|
2022-03-10 20:55:31 +00:00
|
|
|
['title', `\`${title}\``],
|
2022-03-10 22:23:54 +00:00
|
|
|
['script', inlineScripts.map(s => ({ children: `\`${s}\`` }))],
|
|
|
|
['style', [{ children: `\`${globalStyles}\`` }]]
|
2022-03-10 20:55:31 +00:00
|
|
|
]) + ')',
|
2022-03-10 20:25:58 +00:00
|
|
|
'</script>',
|
|
|
|
'<template>',
|
|
|
|
templateContent,
|
|
|
|
'</template>',
|
2022-03-10 22:23:54 +00:00
|
|
|
'<style scoped>',
|
|
|
|
styleContent.replace(globalStyles, ''),
|
2022-03-10 20:25:58 +00:00
|
|
|
'</style>'
|
|
|
|
].filter(Boolean).join('\n').trim()
|
|
|
|
|
2021-12-22 13:04:06 +00:00
|
|
|
// Generate types
|
|
|
|
const types = [
|
2023-07-26 09:08:47 +00:00
|
|
|
`export type DefaultMessages = Record<${Object.keys(messages).map(a => `"${a}"`).join(' | ') || 'string'}, string | boolean | number >`,
|
2021-12-22 13:04:06 +00:00
|
|
|
'declare const template: (data: Partial<DefaultMessages>) => string',
|
|
|
|
'export { template }'
|
|
|
|
].join('\n')
|
|
|
|
|
|
|
|
// Register exports
|
|
|
|
templateExports.push({
|
|
|
|
exportName: camelCase(templateName),
|
|
|
|
templateName,
|
|
|
|
types
|
|
|
|
})
|
|
|
|
|
|
|
|
// Write new template
|
|
|
|
await fsp.writeFile(fileName.replace('/index.html', '.mjs'), `${jsCode}\nexport const template = _template`)
|
2022-03-10 20:25:58 +00:00
|
|
|
await fsp.writeFile(fileName.replace('/index.html', '.vue'), vueCode)
|
2024-04-05 12:43:04 +00:00
|
|
|
await fsp.writeFile(fileName.replace('/index.html', '.d.mts'), `${types}`)
|
2021-12-22 13:04:06 +00:00
|
|
|
await fsp.writeFile(fileName.replace('/index.html', '.d.ts'), `${types}`)
|
|
|
|
|
|
|
|
// Remove original html file
|
|
|
|
await fsp.unlink(fileName)
|
|
|
|
await fsp.rmdir(dirname(fileName))
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write an index file with named exports for each template
|
|
|
|
const contents = templateExports.map(exp => `export { template as ${exp.exportName} } from './templates/${exp.templateName}.mjs'`).join('\n')
|
|
|
|
await fsp.writeFile(r('dist/index.mjs'), contents, 'utf8')
|
|
|
|
|
|
|
|
await fsp.writeFile(r('dist/index.d.ts'), replaceAll(contents, /\.mjs/g, ''), 'utf8')
|
2024-04-05 12:43:04 +00:00
|
|
|
await fsp.writeFile(r('dist/index.d.mts'), replaceAll(contents, /\.mjs/g, ''), 'utf8')
|
2021-12-22 13:04:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|