-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.ts
More file actions
68 lines (58 loc) · 2.35 KB
/
sync.ts
File metadata and controls
68 lines (58 loc) · 2.35 KB
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
import BrowserSync from 'browser-sync'
import findProcess from 'find-process'
import { type IBuildContext } from './build_worker.ts'
import { IntegrityError } from '../common/errors.ts'
import { waitForTime } from '../common/support/async.ts'
export function initBrowserSync(socket: string): BrowserSync.BrowserSyncInstance {
if (!Number.isInteger(Number.parseInt(socket))) {
throw new IntegrityError('BrowserSync does not support proxying sockets')
}
const instance = BrowserSync.create()
instance.init({
open: false,
ghostMode: false,
snippetOptions: {
rule: {
match: /<\/head>/u,
fn(snippet, match) {
return '<script src="/code/client/browsersync_injection.js" type="module"></script>' + match
},
},
},
proxy: 'localhost:' + socket,
serveStatic: ['./build/public', './build/intermediate'],
})
return instance
}
export async function reloadServerData(contexts: IBuildContext[]) {
if (contexts.some(ctx => ctx.dest.startsWith('build/private'))) {
const processes = await findProcess('name', 'website')
for (const { pid } of processes) {
process.kill(pid, 'SIGUSR2')
}
}
}
export async function waitForServer(sync: BrowserSync.BrowserSyncInstance, contexts: IBuildContext[]): Promise<void> {
// For common code files, used also by node, BrowserSync hangs on reload unless we wait.
// It does not matter what files we tell BrowserSync to reload.
//
// I have figured that it may be a race condition with node's own reloading.
// Thus, I have tried polling to make sure the server is serving files. But BrowserSync still hanged.
//
// A simple wait seems to do the trick. With less than 200ms, however, BrowserSync still hangs, and sometimes even with 200ms.
if (contexts.some(ctx => ctx.src.startsWith('code/common'))) {
await waitForTime(750)
}
}
export async function reloadBrowserSync(sync: BrowserSync.BrowserSyncInstance, contexts: IBuildContext[]): Promise<void> {
const paths = contexts
.filter(ctx => ctx.dest.startsWith('intermediate/'))
.map(ctx => ctx.dest.slice('intermediate/'.length))
sync.notify('<div style="text-align: left"><b>Reloading</b><br />' + paths.join('<br />') + '</div>')
// BrowserSync only reloads the page if there is at least one path
if (paths.length > 0) {
sync.reload(paths)
} else {
sync.reload()
}
}