-
Notifications
You must be signed in to change notification settings - Fork 115
/
Copy pathindex.js
executable file
·413 lines (357 loc) · 11.1 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
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
"use strict";
/**
* Module dependencies.
*/
var fs = require("fs")
var path = require("path")
var clone = require("clone")
var resolve = require("resolve")
var postcss = require("postcss")
var helpers = require("postcss-message-helpers")
var hash = require("string-hash")
var glob = require("glob")
/**
* Constants
*/
var moduleDirectories = [
"web_modules",
"node_modules"
]
/**
* Expose the plugin.
*/
module.exports = AtImport
module.exports.postcss = function(styles) {
return module.exports()(styles)
}
/**
* Inline `@import`ed files
*
* @param {Object} options
*/
function AtImport(options) {
options = options || {}
options.root = options.root || process.cwd()
options.path = (
// convert string to an array of a single element
typeof options.path === "string" ?
[options.path] :
(options.path || []) // fallback to empty array
)
return function(styles) {
// auto add from option if possible
if (!options.from && styles && styles.nodes && styles.nodes[0] && styles.nodes[0].source && styles.nodes[0].source.input && styles.nodes[0].source.input.file) {
options.from = styles.nodes[0].source.input.file
}
// if from available, prepend from directory in the path array
addInputToPath(options)
// if we got nothing for the path, just use cwd
if (options.path.length === 0) {
options.path.push(process.cwd())
}
var importedFiles = {}
if (options.from) {
importedFiles[options.from] = {
"": true
}
}
var ignoredAtRules = []
var hashFiles = {}
parseStyles(styles, options, insertRules, importedFiles, ignoredAtRules, null, hashFiles)
addIgnoredAtRulesOnTop(styles, ignoredAtRules)
if (typeof options.onImport === "function") {
options.onImport(Object.keys(importedFiles))
}
}
}
/**
* lookup for @import rules
*
* @param {Object} styles
* @param {Object} options
*/
function parseStyles(styles, options, cb, importedFiles, ignoredAtRules, media, hashFiles) {
var imports = []
styles.eachAtRule("import", function checkAtRule(atRule) {
if (options.glob && glob.hasMagic(atRule.params)) {
imports = parseGlob(atRule, options, imports)
}
else {
imports.push(atRule)
}
})
imports.forEach(function(atRule) {
helpers.try(function transformAtImport() {
readAtImport(atRule, options, cb, importedFiles, ignoredAtRules, media, hashFiles)
}, atRule.source)
})
}
/**
* parse glob patterns (for relative paths only)
*
* @param {Object} atRule
* @param {Object} options
* @param {Array} imports
*/
function parseGlob(atRule, options, imports) {
var globPattern = atRule.params.replace(/['"]/g, "").replace(/(?:url\(|\))/g, "")
var paths = options.path.concat(moduleDirectories)
var files = []
var dir = options.source && options.source.input && options.source.input.file ?
path.dirname(path.resolve(options.root, options.source.input.file)) :
options.root
paths.forEach(function(p) {
p = path.resolve(dir, p)
var globbed = glob.sync(path.join(p, globPattern))
globbed.forEach(function(file) {
file = path.relative(p, file)
files.push(file)
});
});
files.forEach(function(file) {
var deglobbedAtRule = atRule.clone({
params: "\"" + file + "\""
})
if (deglobbedAtRule.source && deglobbedAtRule.source.input && deglobbedAtRule.source.input.css) {
deglobbedAtRule.source.input.css = atRule.source.input.css.replace(globPattern, file)
}
atRule.parent.insertBefore(atRule, deglobbedAtRule)
imports.push(deglobbedAtRule)
});
atRule.removeSelf()
return imports;
}
/**
* put back at the top ignored url (absolute url)
*
* @param {Object} styles
* @param {Array} ignoredAtRules
*/
function addIgnoredAtRulesOnTop(styles, ignoredAtRules) {
var i = ignoredAtRules.length
if (i) {
var first = styles.first
while (i--) {
var ignoredAtRule = ignoredAtRules[i][0]
ignoredAtRule.params = ignoredAtRules[i][1].fullUri + (ignoredAtRules[i][1].media ? " " + ignoredAtRules[i][1].media : "")
// keep ast ref
ignoredAtRule.parent = styles
// don't use prepend() to avoid weird behavior of normalize()
styles.nodes.unshift(ignoredAtRule)
}
// separate remote import a little with others rules if no newlines already
if (first && first.before.indexOf("\n") === -1) {
first.before = "\n\n" + first.before
}
}
}
/**
* parse @import rules & inline appropriate rules
*
* @param {Object} atRule postcss atRule
* @param {Object} options
*/
function readAtImport(atRule, options, cb, importedFiles, ignoredAtRules, media, hashFiles) {
// parse-import module parse entire line
// @todo extract what can be interesting from this one
var parsedAtImport = parseImport(atRule.params, atRule.source)
// adjust media according to current scope
media = parsedAtImport.media ? (media ? media + " and " : "") + parsedAtImport.media : (media ? media : null)
// just update protocol base uri (protocol://url) or protocol-relative (//url) if media needed
if (parsedAtImport.uri.match(/^(?:[a-z]+:)?\/\//i)) {
parsedAtImport.media = media
// save
ignoredAtRules.push([atRule, parsedAtImport])
// detach
detach(atRule)
return
}
addInputToPath(options)
var resolvedFilename = resolveFilename(parsedAtImport.uri, options.root, options.path, atRule.source)
// skip files already imported at the same scope
if (importedFiles[resolvedFilename] && importedFiles[resolvedFilename][media]) {
detach(atRule)
return
}
// save imported files to skip them next time
if (!importedFiles[resolvedFilename]) {
importedFiles[resolvedFilename] = {}
}
importedFiles[resolvedFilename][media] = true
readImportedContent(atRule, parsedAtImport, clone(options), resolvedFilename, cb, importedFiles, ignoredAtRules, media, hashFiles)
}
/**
* insert imported content at the right place
*
* @param {Object} atRule
* @param {Object} parsedAtImport
* @param {Object} options
* @param {String} resolvedFilename
* @param {Function} cb
*/
function readImportedContent(atRule, parsedAtImport, options, resolvedFilename, cb, importedFiles, ignoredAtRules, media, hashFiles) {
// add directory containing the @imported file in the paths
// to allow local import from this file
var dirname = path.dirname(resolvedFilename)
if (options.path.indexOf(dirname) === -1) {
options.path = options.path.slice()
options.path.unshift(dirname)
}
options.from = resolvedFilename
var fileContent = readFile(resolvedFilename, options.encoding, options.transform || function(value) { return value })
if (fileContent.trim() === "") {
console.log(helpers.message(resolvedFilename + " is empty", atRule.source))
detach(atRule)
return
}
// skip files wich only contain @import rules
var newFileContent = fileContent.replace(/@import (.*);/,"")
if (newFileContent.trim() !== "") {
var fileContentHash = hash(fileContent)
// skip files already imported at the same scope and same hash
if (hashFiles[fileContentHash] && hashFiles[fileContentHash][media]) {
detach(atRule)
return
}
// save hash files to skip them next time
if (!hashFiles[fileContentHash]) {
hashFiles[fileContentHash] = {}
}
hashFiles[fileContentHash][media] = true
}
var newStyles = postcss.parse(fileContent, options)
// recursion: import @import from imported file
parseStyles(newStyles, options, cb, importedFiles, ignoredAtRules, parsedAtImport.media, hashFiles)
cb(atRule, parsedAtImport, newStyles, resolvedFilename)
}
/**
* insert new imported rules at the right place
*
* @param {Object} atRule
* @param {Object} parsedAtImport
* @param {Object} newStyles
*/
function insertRules(atRule, parsedAtImport, newStyles) {
var newNodes = newStyles.nodes
// wrap rules if the @import have a media query
if (parsedAtImport.media && parsedAtImport.media.length) {
// better output
if (newStyles.nodes && newStyles.nodes.length) {
newStyles.nodes[0].before = newStyles.nodes[0].before || "\n"
// newStyles.nodes[newStyles.nodes.length - 1].after = (newStyles.nodes[newStyles.nodes.length - 1].after || "") + "\n"
}
// wrap new rules with media (media query)
var wrapper = postcss.atRule({
name: "media",
params: parsedAtImport.media
})
// keep AST clean
newNodes.forEach(function(node) {node.parent = wrapper})
wrapper.source = atRule.source
// copy code style
wrapper.before = atRule.before
wrapper.after = atRule.after
// move nodes
wrapper.nodes = newNodes
newNodes = [wrapper]
}
else if (newNodes && newNodes.length) {
newNodes[0].before = atRule.before
}
// keep AST clean
newNodes.forEach(function(node) {node.parent = atRule.parent})
// replace atRule by imported nodes
var nodes = atRule.parent.nodes
nodes.splice.apply(nodes, [nodes.indexOf(atRule), 0].concat(newNodes))
detach(atRule)
}
/**
* parse @import parameter
*/
function parseImport(str, source) {
var regex = /((?:url\s?\()?(?:'|")?([^)'"]+)(?:'|")?\)?)(?:(?:\s)(.*))?/gi
var matches = regex.exec(str)
if (matches === null) {
throw new Error("Unable to find uri in '" + str + "'", source)
}
return {
fullUri: matches[1],
uri: matches[2],
media: matches[3] ? matches[3] : null
}
}
/**
* Check if a file exists
*
* @param {String} name
*/
function resolveFilename(name, root, paths, source) {
var dir = source && source.input && source.input.file ? path.dirname(path.resolve(root, source.input.file)) : root
try {
var resolveOpts = {
basedir: dir,
moduleDirectory: moduleDirectories.concat(paths),
paths: paths,
extensions: [".css"],
packageFilter: function processPackage(pkg) {
pkg.main = pkg.style || "index.css"
return pkg
}
}
var file
try {
file = resolve.sync(name, resolveOpts)
}
catch (e) {
// fix to try relative files on windows with "./"
// if it's look like it doesn't start with a relative path already
// if (name.match(/^\.\.?/)) {throw e}
try {
file = resolve.sync("./" + name, resolveOpts)
}
catch (e) {
// LAST HOPE
if (!paths.some(function(dir) {
file = path.join(dir, name)
return fs.existsSync(file)
})) {
throw e
}
}
}
return path.normalize(file)
}
catch (e) {
throw new Error(
"Failed to find '" + name + "' from " + root +
"\n in [ " +
"\n " + paths.join(",\n ") +
"\n ]",
source
)
}
}
/**
* Read the contents of a file
*
* @param {String} file
*/
function readFile(file, encoding, transform) {
return transform(fs.readFileSync(file, encoding || "utf8"), file)
}
/**
* add `from` dirname to `path` if not already present
*
* @param {Object} options
*/
function addInputToPath(options) {
if (options.from) {
var fromDir = path.dirname(options.from)
if (options.path.indexOf(fromDir) === -1) {
options.path.unshift(fromDir)
}
}
}
function detach(node) {
node.parent.nodes.splice(node.parent.nodes.indexOf(node), 1)
}