-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (61 loc) · 1.75 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
const Semaphore = require('promaphore')
const Bundle = require('bare-bundle')
const traverse = require('bare-module-traverse')
module.exports = async function pack(entry, opts, readModule, listPrefix) {
if (typeof opts === 'function') {
listPrefix = readModule
readModule = opts
opts = {}
}
if (typeof listPrefix !== 'function') {
listPrefix = defaultListPrefix
}
const { concurrency = 1 } = opts
const semaphore = concurrency > 0 ? new Semaphore(concurrency) : null
const bundle = new Bundle()
const addons = []
const assets = []
await process(
traverse.module(
entry,
await readModule(entry),
{ addons, assets },
new Set(),
opts
)
)
bundle.addons = addons.map((url) => url.href)
bundle.assets = assets.map((url) => url.href)
return bundle
async function process(generator) {
if (semaphore !== null) await semaphore.wait()
const queue = []
let next = generator.next()
while (next.done !== true) {
const value = next.value
if (value.module) {
next = generator.next(await readModule(value.module))
} else if (value.prefix) {
const result = []
for await (const url of listPrefix(value.prefix)) {
result.push(url)
}
next = generator.next(result)
} else {
if (value.children) {
queue.push(value.children)
} else {
const { url, source, imports } = value.dependency
bundle.write(url.href, source, {
main: url.href === entry.href,
imports
})
}
next = generator.next()
}
}
if (semaphore !== null) semaphore.signal()
await Promise.all(queue.map(process))
}
}
function* defaultListPrefix() {}