/
entries.ts
56 lines (46 loc) · 1.63 KB
/
entries.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
import * as path from 'path'
import chokidar from 'chokidar'
import equal from 'fast-deep-equal'
import { Params, State } from '../DataServer'
import { Entries, EntryMap, fromTemplates } from '../Entries'
import { Config } from '../commands/args'
import { touch, compiled } from '../utils/fs'
import * as paths from '../config/paths'
const writeImports = async (map: EntryMap): Promise<void> => {
const imports = await compiled(fromTemplates('imports.tpl.js'))
const rawImportsJs = imports({ entries: Object.values(map) })
await touch(path.join(paths.app, 'imports.js'), rawImportsJs)
}
const updateEntries = (entries: Entries) => async (p: Params) => {
const old = p.state.entries
const map = await entries.get()
if (map && !equal(old, map)) {
await writeImports(map)
p.setState('entries', map)
}
}
export const state = (entries: Entries, config: Config): State => {
const src = path.relative(paths.root, config.src)
const files = path.join(src, config.files)
const watcher = chokidar.watch(files, {
cwd: paths.root,
ignored: /(((^|[\/\\])\..+)|(node_modules))/,
persistent: true,
})
const handleClose = () => watcher.close()
return {
init: updateEntries(entries),
close: handleClose,
update: async params => {
const update = updateEntries(entries)
watcher.on('change', async () => update(params))
watcher.on('unlink', async () => update(params))
watcher.on('raw', async (event: string, path: string, details: any) => {
if (details.event === 'moved' && details.type === 'directory') {
await update(params)
}
})
return handleClose
},
}
}