-
Notifications
You must be signed in to change notification settings - Fork 47
/
transform.js
320 lines (276 loc) · 9.85 KB
/
transform.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
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
const isMemberExpression = require('estree-is-member-expression')
const cssResolve = require('style-resolve').sync
const transformAst = require('transform-ast')
const staticEval = require('static-eval')
const parse = require('fast-json-parse')
const findup = require('@choojs/findup')
const mapLimit = require('map-limit')
const through = require('through2')
const path = require('path')
const fs = require('fs')
const sheetify = require('./index')
const SUPPORTED_SYNONYMS = require('./lib/supported-synonyms')
module.exports = transform
function isBabelTemplateDefinition (node) {
return node.type === 'CallExpression' &&
node.callee.type === 'Identifier' && node.callee.name === '_taggedTemplateLiteral'
}
function isBubleTemplateDefinition (node) {
return node.type === 'CallExpression' &&
isMemberExpression(node.callee, 'Object.freeze') &&
node.arguments[0] && node.arguments[0].type === 'ArrayExpression' &&
node.arguments[0].elements.every(function (el) { return el.type === 'Literal' })
}
// inline sheetify transform for browserify
// obj -> (str, opts) -> str
function transform (filename, options) {
if (/\.json$/i.test(filename)) return through()
const opts = Object.assign({}, options || {
basedir: process.cwd(),
transform: [],
out: ''
})
opts.transform = [].concat(opts.transform || []).concat(opts.t || []).map(function (plugin) {
// resolve subarg syntax
if (typeof plugin === 'object' && Array.isArray(plugin._)) {
return [
plugin._[0],
plugin
]
}
return plugin
})
const bufs = []
const transformStream = through(write, end)
return transformStream
// aggregate all AST nodes
// (buf, str, fn) -> null
function write (buf, enc, next) {
bufs.push(buf)
next()
}
// parse and push AST nodes
// null -> null
function end () {
const self = this
// cool, you've made it this far. We know this is gross,
// but tough times call for tough measure. Please don't
// judge us too harshly, we'll work on perf ✨soon✨ -yw
const nodes = []
const babelTemplateDeclarations = {}
const bubleTemplateDeclarations = {}
const src = Buffer.concat(bufs).toString('utf8')
var mname = null
var ast
// Skip transforming any files that do not contain synonyms for sheetify
if (!SUPPORTED_SYNONYMS.some(name => src.includes(name))) {
self.push(src)
self.push(null)
return
}
findTransforms(filename, function (err, transforms) {
if (err) return self.emit('error', err)
opts.transform = transforms.concat(opts.transform || []).concat(opts.t || [])
try {
ast = transformAst(src, {
parser: require('acorn-node'),
inputFilename: path.basename(filename)
}, identifyModuleName)
ast.walk(extractNodes)
} catch (err) {
return self.emit('error', err)
}
// transform all detected nodes and
// close stream when done
mapLimit(nodes, Infinity, iterate, function (err) {
if (err) return self.emit('error', err)
self.push(ast.toString({
map: opts && opts._flags && opts._flags.debug
}))
self.push(null)
})
})
function identifyModuleName (node) {
if (mname) return
if (node.type === 'CallExpression' &&
node.callee && node.callee.name === 'require' &&
node.arguments.length === 1 &&
SUPPORTED_SYNONYMS.includes(node.arguments[0].value)) {
node.update('0')
mname = node.parent.id.name
}
}
function extractNodes (node) {
extractTemplateNodes(node)
extractImportNodes(node)
}
function extractTemplateNodes (node) {
var css
var elements
if (node.type === 'VariableDeclarator' && node.init) {
if (isBabelTemplateDefinition(node.init)) {
// Babel generates helper calls like
// _taggedTemplateLiteral([":host .class { color: hotpink; }"], [":host .class { color: hotpink; }"])
// we only keep the "cooked" part
babelTemplateDeclarations[node.id.name] = node
} else if (isBubleTemplateDefinition(node.init)) {
// Buble generates helper calls like
// Object.freeze([":host .class { color: hotpink; }"])
bubleTemplateDeclarations[node.id.name] = node
}
}
if (node.type === 'TemplateLiteral' && node.parent && node.parent.tag) {
if (node.parent.tag.name !== mname) return
css = [ node.quasis.map(cooked) ]
.concat(node.expressions.map(expr)).join('').trim()
nodes.push({
css: css,
filename: filename,
opts: Object.assign({}, opts),
node: node.parent
})
}
if (node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === mname) {
if (node.arguments[0] && node.arguments[0].type === 'ArrayExpression') {
// Buble generates code like
// sheetify([":host .class { color: hotpink; }"])
elements = node.arguments[0].elements
} else if (node.arguments[0] && node.arguments[0].type === 'Identifier') {
// Babel generates code like
// sheetify(_templateObject)
var arg = node.arguments[0].name
var templateDeclaration =
babelTemplateDeclarations[arg] || bubleTemplateDeclarations[arg]
if (templateDeclaration) {
var template = templateDeclaration.init.arguments[0]
elements = template.elements
/*
We want to remove transpiled var declaration for minification to work.
var ...,
_templateObject2 = _taggedTemplateLiteral(['.foo { color: blue; }'], ['.foo { color: blue; }']),
...;
*/
removeVariableDeclarator(templateDeclaration)
}
}
if (elements) {
nodes.push({
css: elements.map(function (part) { return part.value }).join(''),
filename: filename,
opts: Object.assign({}, opts),
node: node
})
}
}
}
function removeVariableDeclarator (node) {
/*
Remove `a` declaration from compound `var` statement:
var ...,
a = B,
...
*/
var parent = node.parent
var offset = parent.start
var at = parent.declarations.indexOf(node)
var total = parent.declarations.length
var str = parent.getSource()
var prevNode, nextNode
var stripped
if (total === 1) {
stripped = ' '.repeat(str.length) // remove whole "var ...;" statement
} else if (at < total - 1) { // not last
nextNode = parent.declarations[at + 1]
stripped =
str.slice(0, node.start - offset) +
' '.repeat(nextNode.start - node.start) +
str.slice(nextNode.start - offset)
} else { // last one
prevNode = parent.declarations[at - 1]
stripped =
str.slice(0, prevNode.end - offset) +
' '.repeat(node.end - prevNode.end) +
str.slice(node.end - offset)
}
parent.update(stripped)
}
function extractImportNodes (node) {
if (node.type !== 'CallExpression') return
if (!node.callee || node.callee.type !== 'Identifier') return
if (node.callee.name !== mname) return
if (!node.arguments[0] || !node.arguments[0].value) return
var pathOpts = { basedir: path.dirname(filename) }
try {
var resolvePath = cssResolve(node.arguments[0].value, pathOpts)
} catch (err) {
return self.emit('error', err)
}
const iOpts = node.arguments[1]
? Object.assign({}, opts, staticEval(node.arguments[1]))
: opts
transformStream.emit('file', resolvePath)
const val = {
filename: resolvePath,
opts: iOpts,
node: node
}
nodes.push(val)
}
}
// iterate over nodes, and apply sheetify transformation
// then replace the AST nodes with new values
// (obj, fn) -> null
function iterate (val, done) {
if (typeof val.css === 'string') return handleCss(val)
if (/\.js$/.test(val.filename)) {
delete require.cache[require.resolve(val.filename)]
val.css = require(val.filename)
handleCss(val)
} else {
fs.readFile(val.filename, 'utf8', function (err, css) {
if (err) return done(err)
val.css = css
handleCss(val)
})
}
function handleCss (val) {
sheetify(val.css, val.filename, val.opts, function (err, result, prefix) {
if (err) return done(err)
const str = [
"((require('sheetify/insert')(" + JSON.stringify(result.css) + ')',
' || true) && ' + JSON.stringify(prefix) + ')'
].join('')
const parentNodeType = val.node.parent.type
const lolSemicolon = parentNodeType === 'VariableDeclarator' ||
parentNodeType === 'AssignmentExpression'
? ''
: ';'
val.node.update(lolSemicolon + str)
result.files.forEach(function (includedFile) {
transformStream.emit('file', includedFile)
})
done()
})
}
}
function findTransforms (filename, done) {
findup(filename, 'package.json', function (err, pathname) {
// no package.json found - just run local transforms
if (err) return done(null, [])
var filename = path.join(pathname, 'package.json')
fs.readFile(filename, function (err, file) {
if (err) return done(err)
var parsed = parse(file)
if (parsed.err) return done(parsed.err)
var json = parsed.value
var d = json.sheetify
if (!d) return done(null, [])
var t = d.transform
if (!t || !Array.isArray(t)) return done(null, [])
return done(null, t)
})
})
}
}
function cooked (node) { return node.value.cooked }
function expr (ex) { return { _expr: ex.source() } }