-
Notifications
You must be signed in to change notification settings - Fork 0
/
deno-build.ts
executable file
·230 lines (204 loc) · 6.14 KB
/
deno-build.ts
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
#!/usr/bin/env -S deno run --no-config --allow-env --allow-read --allow-write=. --allow-net --ext ts
import {
dirname,
join,
resolve,
toFileUrl,
} from 'https://deno.land/std@0.205.0/path/mod.ts'
import { Command } from 'https://deno.land/x/cliffy@v0.25.7/command/mod.ts'
import Spinner from 'https://deno.land/x/cli_spinners@v0.0.2/mod.ts'
import { format } from 'https://deno.land/std@0.205.0/datetime/format.ts'
import {
keypress,
KeyPressEvent,
} from 'https://deno.land/x/cliffy@v1.0.0-rc.2/keypress/mod.ts'
import * as esbuild from 'https://deno.land/x/esbuild@v0.19.4/wasm.js'
import { denoPlugins } from 'https://deno.land/x/esbuild_deno_loader@0.8.2/mod.ts'
async function closestFilePath(
dir: string,
searcher: (entry: Deno.DirEntry) => Promise<boolean> | boolean,
) {
let resolvedDir = resolve(dir)
while (resolvedDir !== '/') {
for await (const entry of Deno.readDir(resolvedDir)) {
if (entry.isFile && await searcher(entry)) {
return join(resolvedDir, entry.name)
}
}
resolvedDir = dirname(resolvedDir)
}
}
export async function getRebuilder(
filePath: string,
configPath: string | undefined,
option: {
minify: boolean
sourcemap: boolean | 'linked' | 'inline' | 'external' | 'both'
},
) {
const context = await esbuild.context({
plugins: [...denoPlugins({
nodeModulesDir: true,
configPath: configPath,
})],
entryPoints: [toFileUrl(resolve(filePath)).toString()],
jsx: 'transform',
jsxFactory: 'React.createElement',
jsxImportSource: 'react',
bundle: true,
metafile: true,
format: 'esm',
sourcemap: option.sourcemap,
minify: option.minify,
})
return [async function rebuild() {
return await context.rebuild()
.then((r) => ({
inputs: Object.keys(r.metafile.inputs),
outputFiles: r.outputFiles,
error: null,
}))
.catch((e) => ({ outputFiles: null, inputs: null, error: e }))
}, () => context.dispose()] as const
}
async function getWriter(filePath: string, destPath: string, option: {
minify: boolean
inlineSourcemap: boolean
}) {
const spinner = Spinner.getInstance()
const spinnerStartPromise = spinner.start('bundling')
const configPath = await closestFilePath(
dirname(filePath),
(entry) => Boolean(entry.name.match(/deno\.jsonc?/)),
).then((path) => path ? resolve(path) : path)
const [rebuild, stop] = await getRebuilder(filePath, configPath, {
minify: option.minify,
sourcemap: option.inlineSourcemap ? 'inline' : false,
})
return [
async function write() {
await spinnerStartPromise
const result = await rebuild()
const contents = result?.outputFiles?.[0]?.contents
if (contents) {
await spinner.succeed(
`[${format(new Date(), 'HH:mm:ss.SSS')}] bundled '${destPath}'`,
)
console.log('')
await Deno.writeFile(destPath, contents)
} else {
await spinner.fail(
`[${format(new Date(), 'HH:mm:ss.SSS')}] bundle failed`,
)
console.log('')
console.error(result?.error)
}
return result.inputs
},
() => stop(),
] as const
}
function createWatcherAndUpdater() {
const dummyWatcher = {
close() {},
async *[Symbol.asyncIterator]() {
// async iterator を deno が認識できてない?
// deno-lint-ignore no-await-in-sync-fn
await new Promise(() => {})
yield {
kind: 'any' as const,
paths: [],
}
},
}
// let filePathSet = new Set<string>()
let watcher: AsyncIterable<Deno.FsEvent> & { close: () => void } =
dummyWatcher
return [
async function* () {
while (true) {
for await (const event of watcher) {
yield event
}
}
},
(filePaths: string[]) => {
// const diffLength = filePathSet.size !== filePaths.length
// const hasNew =
// 0 < filePaths.filter((path) => !filePathSet.has(path)).length
// 何故か neovim で編集すると remove イベントが発生してそれ以降の modify を監視できなくなる
// そのため、modify ごとに watcher を作りなおす
// if (diffLength || hasNew) {
// filePathSet = new Set(filePaths)
watcher.close()
watcher = Deno.watchFs(filePaths)
// }
},
] as const
}
function resolveRelativeFiles(
inputs: string[] | null,
prevFilePaths: string[],
) {
if (!inputs) {
return prevFilePaths
}
return inputs
.filter((url) => !url.startsWith('http'))
.map((path) => '/' + path)
}
async function waitCtrlC() {
return await new Promise((resolve) =>
keypress().addEventListener('keydown', (event: KeyPressEvent) => {
if (event.ctrlKey && event.key === 'c') {
resolve(undefined)
keypress().dispose()
}
})
)
}
if (import.meta.main) {
new Command()
.name('deno-build')
.arguments('<target-file:string> [destination:string]')
.option('--watch', 'watch file modify')
.option('--no-inline-sourcemap', 'generate inline sourcemap')
.option('--no-minify', 'minify')
.action(
async function main(
{ watch = false, inlineSourcemap = true, minify = true },
filePath: string,
destPath?: string,
) {
destPath ??= filePath + '.bundled.js'
const [write, stop] = await getWriter(filePath, destPath, {
inlineSourcemap,
minify,
})
const inputs = await write()
waitCtrlC().then(async () => {
await stop()
Deno.exit(0)
})
const [watcher, updater] = createWatcherAndUpdater()
if (!inputs || !watch) {
Deno.exit(inputs ? 0 : 1)
}
let relativeFilePaths = resolveRelativeFiles(inputs, [])
updater(relativeFilePaths)
for await (const event of watcher()) {
if (!['create', 'modify', 'remove'].includes(event.kind)) {
continue
}
const inputs = await write()
relativeFilePaths = resolveRelativeFiles(
inputs,
relativeFilePaths,
)
updater(relativeFilePaths)
}
await stop()
},
)
.parse(Deno.args)
}