/
StylusAsset.js
228 lines (201 loc) Β· 6.41 KB
/
StylusAsset.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
// const CSSAsset = require('./CSSAsset');
const Asset = require('../Asset');
const localRequire = require('../utils/localRequire');
const Resolver = require('../Resolver');
const fs = require('@parcel/fs');
const {dirname, resolve, relative} = require('path');
const {isGlob, glob} = require('../utils/glob');
const URL_RE = /^(?:url\s*\(\s*)?['"]?(?:[#/]|(?:https?:)?\/\/)/i;
class StylusAsset extends Asset {
constructor(name, options) {
super(name, options);
this.type = 'css';
}
async parse(code) {
// stylus should be installed locally in the module that's being required
let stylus = await localRequire('stylus', this.name);
let opts = await this.getConfig(['.stylusrc', '.stylusrc.js'], {
packageKey: 'stylus'
});
let style = stylus(code, opts);
style.set('filename', this.name);
style.set('include css', true);
// Setup a handler for the URL function so we add dependencies for linked assets.
style.define('url', node => {
let filename = this.addURLDependency(node.val, node.filename);
return new stylus.nodes.Literal(`url(${JSON.stringify(filename)})`);
});
style.set('Evaluator', await createEvaluator(code, this, style.options));
return style;
}
generate() {
return [
{
type: 'css',
value: this.ast.render(),
hasDependencies: false
}
];
}
generateErrorMessage(err) {
let index = err.message.indexOf('\n');
err.codeFrame = err.message.slice(index + 1);
err.message = err.message.slice(0, index);
return err;
}
}
async function getDependencies(
code,
filepath,
asset,
options,
seen = new Set()
) {
seen.add(filepath);
const [Parser, DepsResolver, nodes, utils] = await Promise.all(
['parser', 'visitor/deps-resolver', 'nodes', 'utils'].map(dep =>
localRequire('stylus/lib/' + dep, filepath)
)
);
nodes.filename = asset.name;
let parser = new Parser(code, options);
let ast = parser.parse();
let deps = new Map();
let resolver = new Resolver(
Object.assign({}, asset.options, {
extensions: ['.styl', '.css']
})
);
class ImportVisitor extends DepsResolver {
visitImport(imported) {
let path = imported.path.first.string;
if (!deps.has(path)) {
if (isGlob(path)) {
deps.set(
path,
glob(resolve(dirname(filepath), path), {
onlyFiles: true
}).then(entries =>
Promise.all(
entries.map(entry =>
resolver.resolve(
'./' + relative(dirname(filepath), entry),
filepath
)
)
)
)
);
} else {
deps.set(path, resolver.resolve(path, filepath));
}
}
}
}
new ImportVisitor(ast, options).visit(ast);
// Recursively process depdendencies, and return a map with all resolved paths.
let res = new Map();
await Promise.all(
Array.from(deps.entries()).map(async ([path, resolved]) => {
try {
resolved = await resolved;
resolved = Array.isArray(resolved)
? resolved.map(r => r.path)
: resolved.path;
} catch (err) {
resolved = null;
}
let found;
if (resolved) {
found = Array.isArray(resolved) ? resolved : [resolved];
res.set(path, resolved);
} else {
// If we couldn't resolve, try the normal stylus resolver.
// We just need to do this to keep track of the dependencies - stylus does the real work.
// support optional .styl
let originalPath = path;
if (!/\.styl$/i.test(path)) {
path += '.styl';
}
let paths = (options.paths || []).concat(dirname(filepath || '.'));
found = utils.find(path, paths, filepath);
if (!found) {
found = utils.lookupIndex(originalPath, paths, filepath);
}
if (!found) {
throw new Error('failed to locate file ' + originalPath);
}
}
// Recursively process resolved files as well to get nested deps
for (let resolved of found) {
if (!seen.has(resolved)) {
asset.addDependency(resolved, {includedInParent: true});
let code = await fs.readFile(resolved, 'utf8');
for (let [path, resolvedPath] of await getDependencies(
code,
resolved,
asset,
options,
seen
)) {
res.set(path, resolvedPath);
}
}
}
})
);
return res;
}
async function createEvaluator(code, asset, options) {
const deps = await getDependencies(code, asset.name, asset, options);
const Evaluator = await localRequire(
'stylus/lib/visitor/evaluator',
asset.name
);
// This is a custom stylus evaluator that extends stylus with support for the node
// require resolution algorithm. It also adds all dependencies to the parcel asset
// tree so the file watcher works correctly, etc.
class CustomEvaluator extends Evaluator {
visitImport(imported) {
let node = this.visit(imported.path).first;
let path = node.string;
if (node.name !== 'url' && path && !URL_RE.test(path)) {
let resolved = deps.get(path);
// First try resolving using the node require resolution algorithm.
// This allows stylus files in node_modules to be resolved properly.
// If we find something, update the AST so stylus gets the absolute path to load later.
if (resolved) {
if (!Array.isArray(resolved)) {
node.string = resolved;
} else {
// If the import resolves to multiple files (i.e. glob),
// replace it with a separate import node for each file
return mergeBlocks(
resolved.map(resolvedPath => {
node.string = resolvedPath;
return super.visitImport(imported.clone());
})
);
}
}
}
// Done. Let stylus do its thing.
return super.visitImport(imported);
}
}
return CustomEvaluator;
}
/**
* Puts the content of all given node blocks into the first one, essentially merging them.
*/
function mergeBlocks(blocks) {
let finalBlock;
for (const block of blocks) {
if (!finalBlock) finalBlock = block;
else {
block.nodes.forEach(node => finalBlock.push(node));
}
}
return finalBlock;
}
module.exports = StylusAsset;