-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
93 lines (70 loc) · 2.58 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
const string = require('glsl-token-string')
const tokenize = require('glsl-tokenizer')
const resolve = require('glsl-resolve')
const path = require('path')
const fs = require('fs')
module.exports = glslifyImport
module.exports.sync = glslifyImport;
function glslifyImport (file, src, opts, done) {
const tokens = tokenize(src)
var total = 0
for (var i = 0; i < tokens.length; i++) (function (i) {
var token = tokens[i]
if (token.type !== 'preprocessor') return
var imported = /#pragma glslify:\s*import\(([^\)]+)\)/.exec(token.data)
if (!imported) return
if (!imported[1]) return
var target = imported[1]
.trim()
.replace(/^'|'$/g, '')
.replace(/^"|"$/g, '')
total++
var basedir = path.dirname(file)
if (typeof done === 'function') {
resolve(target, { basedir: basedir }, function (err, resolved) {
if (err) return done(err)
fs.readFile(resolved, 'utf8', function (err, contents) {
if (err) return done(err)
contents = modifyRequirePaths(contents, basedir, target)
glslifyImport(resolved, contents, opts, function (err, contents) {
if (err) return done(err)
token.data = contents
if (--total) return
done(null, string(tokens))
})
})
})
} else {
var resolved = resolve.sync(target, { basedir: basedir });
var contents = fs.readFileSync(resolved, 'utf8');
contents = modifyRequirePaths(contents, basedir, target);
token.data = glslifyImport(resolved, contents, opts);
total--;
}
})(i)
if (!total) return typeof done === 'function' ? done(null, src) : string(tokens);
}
function modifyRequirePaths (src, basedir, baseTarget) {
const tokens = tokenize(src)
var targetDir = path.dirname(path.resolve(basedir, baseTarget))
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i]
if (token.type !== 'preprocessor') continue
var required = /#pragma glslify:\s*([^=\s]+)\s*=\s*require\(([^\)]+)\)/.exec(token.data)
if (!required) continue
if (!required[2]) continue
var name = required[1]
var maps = required[2].split(/\s?,\s?/g)
var target = maps.shift()
.trim()
.replace(/^'|'$/g, '')
.replace(/^"|"$/g, '')
var resolvedTarget = path.resolve(targetDir, target)
if (name) {
token.data = '#pragma glslify: ' + name + ' = require("' + [resolvedTarget].concat(maps).join(', ') + '")'
} else {
token.data = '#pragma glslify: require("' + [resolvedTarget].concat(maps).join(', ') + '")'
}
}
return string(tokens)
}