-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
170 lines (145 loc) · 5.09 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
import { relative, resolve } from 'node:path'
import fs from 'node:fs'
import lodash from 'lodash'
import Twig from 'twig'
import {
getPackageInfo,
merge,
pluginBundle,
pluginMiddleware,
pluginReload, pluginTransform,
processData
} from 'vituum/utils/common.js'
import { renameBuildEnd, renameBuildStart } from 'vituum/utils/build.js'
const { name } = getPackageInfo(import.meta.url)
/**
* @type {import('@vituum/vite-plugin-twig/types').PluginUserConfig}
*/
const defaultOptions = {
reload: true,
root: null,
filters: {},
functions: {},
extensions: [],
namespaces: {},
globals: {
format: 'twig'
},
data: ['src/data/**/*.json'],
formats: ['twig', 'json.twig', 'json'],
ignoredPaths: [],
options: {
compileOptions: {},
renderOptions: {}
}
}
const renderTemplate = async ({ filename, server, resolvedConfig }, content, options) => {
const initialFilename = filename.replace('.html', '')
const output = {}
const context = options.data
? processData({
paths: options.data,
root: resolvedConfig.root
}, options.globals)
: options.globals
if (initialFilename.endsWith('.json')) {
lodash.merge(context, JSON.parse(content))
if (!options.formats.includes(context.format)) {
return new Promise((resolve) => {
output.content = content
resolve(output)
})
}
content = '{% include template %}'
if (typeof context.template === 'undefined') {
const error = `${name}: template must be defined for file ${initialFilename}`
return new Promise((resolve) => {
output.error = error
resolve(output)
})
}
context.template = relative(resolvedConfig.root, context.template).startsWith(relative(resolvedConfig.root, options.root)) ? resolve(resolvedConfig.root, context.template) : resolve(options.root, context.template)
context.template = relative(options.root, context.template)
} else if (fs.existsSync(initialFilename + '.json')) {
lodash.merge(context, JSON.parse(fs.readFileSync(`${initialFilename}.json`).toString()))
}
Twig.cache(false)
if (!Array.isArray(options.extensions)) {
throw new TypeError('\'extensions\' needs to be an array of functions!')
} else {
options.extensions.forEach(name => {
// noinspection JSCheckFunctionSignatures
Twig.extend(name)
})
}
Object.keys(options.functions).forEach(name => {
if (typeof options.functions[name] !== 'function') {
throw new TypeError(`${name} needs to be a function!`)
}
Twig.extendFunction(name, options.functions[name])
})
Object.keys(options.filters).forEach(name => {
if (typeof options.filters[name] !== 'function') {
throw new TypeError(`${name} needs to be a function!`)
}
Twig.extendFilter(name, options.filters[name])
})
return new Promise((resolve) => {
const onError = (error) => {
output.error = error
resolve(output)
}
const onSuccess = (content) => {
output.content = content
resolve(output)
}
Twig.twig(Object.assign({
allowAsync: true,
data: content,
path: options.root + '/',
namespaces: options.namespaces,
rethrow: true
}, options.options.compileOptions)).renderAsync(context, options.options.renderOptions).catch(onError).then(onSuccess)
})
}
/**
* @param {import('@vituum/vite-plugin-twig/types').PluginUserConfig} options
* @returns [import('vite').Plugin]
*/
const plugin = (options = {}) => {
let resolvedConfig
let userEnv
options = merge(defaultOptions, options)
return [{
name,
config (userConfig, env) {
userEnv = env
},
configResolved (config) {
resolvedConfig = config
if (!options.root) {
options.root = config.root
}
},
buildStart: async () => {
if (userEnv.command !== 'build' || !resolvedConfig.build.rollupOptions.input) {
return
}
await renameBuildStart(resolvedConfig.build.rollupOptions.input, options.formats)
},
buildEnd: async () => {
if (userEnv.command !== 'build' || !resolvedConfig.build.rollupOptions.input) {
return
}
await renameBuildEnd(resolvedConfig.build.rollupOptions.input, options.formats)
},
transformIndexHtml: {
order: 'pre',
async handler (content, { path, filename, server }) {
return pluginTransform(content, { path, filename, server }, { name, options, resolvedConfig, renderTemplate })
}
},
handleHotUpdate: ({ file, server }) => pluginReload({ file, server }, options)
}, pluginBundle(options.formats), pluginMiddleware(name, options.formats)]
}
export default plugin