-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
160 lines (136 loc) · 4.66 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
import { resolve } from 'node:path'
import fs from 'node:fs'
import lodash from 'lodash'
import { Liquid } from 'liquidjs'
import {
getPackageInfo,
pluginTransform,
pluginReload,
processData,
pluginBundle,
merge,
pluginMiddleware
} from 'vituum/utils/common.js'
import { renameBuildEnd, renameBuildStart } from 'vituum/utils/build.js'
const { name } = getPackageInfo(import.meta.url)
/**
* @type {import('@vituum/vite-plugin-liquid/types').PluginUserConfig}
*/
const defaultOptions = {
reload: true,
root: null,
filters: {},
tags: {},
globals: {
format: 'liquid'
},
data: ['src/data/**/*.json'],
formats: ['liquid', 'json.liquid', 'json'],
ignoredPaths: [],
options: {
liquidOptions: {},
renderOptions: {},
renderFileOptions: {}
}
}
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)
})
}
output.template = true
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 = resolve(options.root, context.template)
} else if (fs.existsSync(`${initialFilename}.json`)) {
lodash.merge(context, JSON.parse(fs.readFileSync(`${initialFilename}.json`).toString()))
}
const liquid = new Liquid(Object.assign({
root: options.root
}, options.options.liquidOptions))
Object.keys(options.filters).forEach(name => {
if (typeof options.filters[name] !== 'function') {
throw new TypeError(`${name} needs to be a function!`)
}
liquid.registerFilter(name, options.filters[name])
})
Object.keys(options.tags).forEach(name => {
if (typeof options.tags[name] !== 'object') {
throw new TypeError(`${name} needs to be an object!`)
}
liquid.registerTag(name, options.tags[name])
})
return new Promise((resolve) => {
const onError = (error) => {
output.error = error
resolve(output)
}
const onSuccess = (content) => {
output.content = content
resolve(output)
}
if (output.template) {
output.content = liquid.renderFile(context.template, context, options.options.renderFileOptions).catch(onError).then(onSuccess)
} else {
output.content = liquid.parseAndRender(content, context, options.options.renderOptions).catch(onError).then(onSuccess)
}
})
}
/**
* @param {import('@vituum/vite-plugin-liquid/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