-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbundler.js
164 lines (135 loc) · 4.02 KB
/
bundler.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
import fs from 'node:fs'
import os from 'node:os'
import url from 'node:url'
import path from 'node:path'
import chalk from 'chalk'
let __dirname = url.fileURLToPath(new URL('.', import.meta.url))
if (os.platform() === 'win32') __dirname = __dirname.replace(/\\/g, '/').replace(/^[A-Za-z]:\//, '/')
/**
* HACK to ensure modules are bundled in the correct order
* such that dependent modules are loaded after their dependencies
*/
let LOAD_ORDER = {
[path.resolve('packages/runtime/graphql')]: [
['util.lua'],
['types.lua'],
['query_util.lua'],
['introspection.lua'],
['validate_variables.lua'],
['init.lua', Infinity]
],
[path.resolve('packages/gateway')]: [
['utils.lua'],
['schema/sort_order.lua'],
['schema/connection.lua'],
['schema/block.lua'],
['schema/init.lua', 10001],
['api.lua', 10002],
['init.lua', Infinity]
]
}
LOAD_ORDER = Object.keys(LOAD_ORDER)
.reduce(
(acc, cur) => {
acc[cur] = LOAD_ORDER[cur]
.map(([f, ...rest]) => [path.resolve(cur, f), ...rest])
return acc
},
{}
)
function findLoadOrder ({ dir, files }) {
if (!LOAD_ORDER[dir]) return files
const order = LOAD_ORDER[dir]
function findLoadIndex (file) {
const [, idx] = order
.map(([f, explicit], implicit) => [f, explicit || implicit])
/**
* sufficiently large number to represent "somewhere in the middle"
* but not the absolute last (Infinity)
*
* This allows shimming files
* before (at most 9999 files before) or after this file
*/
.find(([f]) => file === f) || [file, 10000]
return idx
}
return files.sort((a, b) => findLoadIndex(a) - findLoadIndex(b))
}
// eslint-disable-next-line
const tap = (fn) => (arg) => {
try { fn(arg) } catch {}
return arg
}
function printUsage () {
console.log(`
Bundle Usage:
node bundler.js [name] [dir]
node bundler.js @tilla/graphql packages/runtime/graphql
`)
}
function mapArgs (args) {
const [name, dir] = args
if (!name) {
console.error('name not provided')
printUsage()
}
if (!dir) {
console.error('dir not provided')
printUsage()
}
return { name, dir: path.resolve(__dirname, dir) }
}
function findFiles ({ dir, extension, ignore }) {
let files = []
fs.readdirSync(dir).forEach((file) => {
const filePath = path.join(dir, file)
const stat = fs.statSync(filePath)
if (stat.isDirectory()) files = files.concat(findFiles({ dir: path.resolve(dir, file), extension, ignore }))
else if (stat.isFile() && file.endsWith(extension) && !ignore.includes(file)) files.push(filePath)
})
files = findLoadOrder({ dir, files })
return files
}
function fileToModule ({ dir, file }) {
const code = fs.readFileSync(file, 'utf-8')
return {
mod: file
.replace(`${dir}/`, '')
.replace(/\.lua$/, '')
.replace(/\//g, '.')
.replace(/-/g, '_'),
code
}
}
function moduleToLoadedModule ({ name, mod, code }) {
mod = mod
.replace(/-/g, '_')
const isEntry = mod === 'init'
const fn = `load_${mod.replace(/\./g, '_')}`
return `
local function ${fn}()
${code}
end
_G.package.loaded["${name}.${mod}"] = ${fn}()
${isEntry ? `_G.package.loaded["${name}"] = _G.package.loaded["${name}.${mod}"]` : ''}
`
}
function toBundle ({ dir, loadedModules }) {
const bundle = loadedModules.join('\n\n')
const dest = path.resolve(dir, 'bundle.lua')
fs.writeFileSync(dest, bundle)
return dest
}
function main (args) {
return Promise.resolve(args)
.then(mapArgs)
.then(({ name, dir }) =>
Promise.resolve(findFiles({ dir, extension: '.lua', ignore: ['bundle.lua'] }))
// .then(files => { console.log(files); return files })
.then((files) => files.map((file) => fileToModule({ dir, file })))
.then((mods) => mods.map((mod) => moduleToLoadedModule({ name, mod: mod.mod, code: mod.code })))
.then((loadedModules) => toBundle({ dir, loadedModules }))
.then((bundle) => console.log(chalk.green(`Created bundle for ${name}: ${bundle}`)))
)
}
main(process.argv.slice(2))