-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathfile-system-loader.js
73 lines (62 loc) · 2.17 KB
/
file-system-loader.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
import core from './index'
import { readFile } from 'fs'
import { dirname, resolve } from 'path'
// Sorts dependencies in the following way:
// AAA comes before AA and A
// AB comes after AA and before A
// All Bs come after all As
// This ensures that the files are always returned in the following order:
// - In the order they were required, except
// - After all their dependencies
const traceKeySorter = ( a, b ) => {
if ( a.length < b.length ) {
return a < b.substring( 0, a.length ) ? -1 : 1
} else if ( a.length > b.length ) {
return a.substring( 0, b.length ) <= b ? -1 : 1
} else {
return a < b ? -1 : 1
}
};
export default class FileSystemLoader {
constructor( options, processorOptions = {} ) {
this.processorOptions = processorOptions
this.core = core( options, this.fetch.bind(this) )
this.importNr = 0
this.sources = {}
this.tokensByFile = {}
this.trace = {}
}
fetch( to, from, depTrace ) {
return new Promise(( _resolve, _reject ) => {
const filename = /\w/i.test( to[0] )
? require.resolve( to )
: resolve( dirname( from ), to )
if ( this.tokensByFile[filename] ) {
return void _resolve( this.tokensByFile[filename] )
}
let trace = this.trace[from] || String.fromCharCode( this.importNr++ )
if (typeof depTrace === 'number') {
trace += String.fromCharCode( depTrace )
}
this.trace[filename] = trace
readFile( filename, 'utf8', (err, source) => {
if (err) {
return void _reject(err);
}
this.core.process( source, Object.assign( this.processorOptions, { from: filename } ) )
.then( result => {
this.sources[trace] = result.css
this.tokensByFile[filename] = result.root.tokens
// https://github.com/postcss/postcss/blob/master/docs/api.md#lazywarnings
result.warnings().forEach(message => console.warn(message.text));
_resolve( this.tokensByFile[filename] )
} )
.catch( _reject )
} )
})
}
get finalSource() {
return Object.keys( this.sources ).sort( traceKeySorter ).map( s => this.sources[s] )
.join( '' )
}
}