UNPKG

2.52 kBJavaScriptView Raw
1var recursiveWatch = require('recursive-watch')
2var findup = require('findup')
3var Debug = require('debug')
4var path = require('path')
5
6// Figure out what directory the file is in.
7exports.dirname = function (pathname) {
8 return path.dirname(pathname)
9}
10
11// Figure out what directory the file is in.
12// Does nothing if a directory is passed.
13exports.basefile = function (pathname) {
14 if (!path.extname(pathname)) {
15 return path.join(pathname, 'index.js')
16 } else {
17 return pathname
18 }
19}
20
21// Watch the directory for changes to the entry file.
22// Does nothing if we're already watching.
23exports.watch = function (dirname, filenames, cb) {
24 var debug = Debug('bankai.utils.watch')
25 return recursiveWatch(dirname, function (filename) {
26 debug('watching files %s in %s', filenames, dirname)
27 if (filenames.indexOf(path.relative(dirname, filename)) !== -1) {
28 debug('%s changed', filename)
29 cb(filename)
30 }
31 })
32}
33
34// Watch a full directory for changes
35// Does nothing if we're already watching.
36exports.watchDirs = function (basedir, dirnames, cb) {
37 var debug = Debug('bankai.utils.watchDir')
38 debug('watching directories %s in %s', dirnames, basedir)
39
40 var regexes = dirnames.map(function (dirname) {
41 var relative = path.join(basedir, dirname)
42 return new RegExp('^' + relative)
43 })
44
45 return recursiveWatch(basedir, function (filename) {
46 var changed = regexes.some(function (regex) {
47 return regex.test(filename)
48 })
49
50 if (changed) {
51 debug('%s changed', filename)
52 cb(filename)
53 }
54 })
55}
56
57// Find the entry file.
58exports.find = function find (rootname, arr, done) {
59 if (!arr.length) return done(new Error('Could not find files'))
60 var filename = arr[0]
61 var newArr = arr.slice(1)
62 findup(rootname, filename, function (err, dirname) {
63 if (err) return find(rootname, newArr, done)
64 done(null, path.join(dirname, filename))
65 })
66}
67
68// Brotli compression: wasm for Node 8, emscriptened JS for older.
69var brotliCompress
70try {
71 var wasm = require('wasm-brotli')
72 brotliCompress = wasm.compress
73} catch (err) {
74 var compress = require('brotli/compress')
75 brotliCompress = function (buffer) {
76 return new Promise(function (resolve, reject) {
77 try {
78 var compressed = compress(buffer)
79 if (compressed) {
80 resolve(Buffer.from(compressed))
81 } else {
82 reject(new Error('could not compress buffer'))
83 }
84 } catch (err) {
85 reject(err)
86 }
87 })
88 }
89}
90exports.brotli = brotliCompress