-
Notifications
You must be signed in to change notification settings - Fork 921
/
hmr.js
161 lines (158 loc) · 3.84 KB
/
hmr.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
/**
* esm-hmr/runtime.ts
* A client-side implementation of the ESM-HMR spec, for reference.
*/
function debug(...args) {
console.debug('[ESM-HMR]', ...args);
}
function reload() {
location.reload(true);
}
let SOCKET_MESSAGE_QUEUE = [];
function _sendSocketMessage(msg) {
socket.send(JSON.stringify(msg));
}
function sendSocketMessage(msg) {
if (socket.readyState !== socket.OPEN) {
SOCKET_MESSAGE_QUEUE.push(msg);
} else {
_sendSocketMessage(msg);
}
}
const socketURL =
window.HMR_WEBSOCKET_URL ||
(location.protocol === 'http:' ? 'ws://' : 'wss://') + location.host + '/';
const socket = new WebSocket(socketURL, 'esm-hmr');
socket.addEventListener('open', () => {
SOCKET_MESSAGE_QUEUE.forEach(_sendSocketMessage);
SOCKET_MESSAGE_QUEUE = [];
});
const REGISTERED_MODULES = {};
class HotModuleState {
constructor(id) {
this.data = {};
this.isLocked = false;
this.isDeclined = false;
this.isAccepted = false;
this.acceptCallbacks = [];
this.disposeCallbacks = [];
this.id = id;
}
lock() {
this.isLocked = true;
}
dispose(callback) {
this.disposeCallbacks.push(callback);
}
invalidate() {
reload();
}
decline() {
this.isDeclined = true;
}
accept(_deps, callback = true) {
if (this.isLocked) {
return;
}
if (!this.isAccepted) {
sendSocketMessage({id: this.id, type: 'hotAccept'});
this.isAccepted = true;
}
if (!Array.isArray(_deps)) {
callback = _deps || callback;
_deps = [];
}
if (callback === true) {
callback = () => {};
}
const deps = _deps.map((dep) => {
const ext = dep.split('.').pop();
if (!ext) {
dep += '.js';
} else if (ext !== 'js') {
dep += '.proxy.js';
}
return new URL(dep, `${window.location.origin}${this.id}`).pathname;
});
this.acceptCallbacks.push({
deps,
callback,
});
}
}
export function createHotContext(fullUrl) {
const id = new URL(fullUrl).pathname;
const existing = REGISTERED_MODULES[id];
if (existing) {
existing.lock();
runModuleDispose(id);
return existing;
}
const state = new HotModuleState(id);
REGISTERED_MODULES[id] = state;
return state;
}
/** Called when a new module is loaded, to pass the updated module to the "active" module */
async function runModuleAccept(id) {
const state = REGISTERED_MODULES[id];
if (!state) {
return false;
}
if (state.isDeclined) {
return false;
}
const acceptCallbacks = state.acceptCallbacks;
const updateID = Date.now();
for (const {deps, callback: acceptCallback} of acceptCallbacks) {
const [module, ...depModules] = await Promise.all([
import(id + `?mtime=${updateID}`),
...deps.map((d) => import(d + `?mtime=${updateID}`)),
]);
acceptCallback({module, deps: depModules});
}
return true;
}
/** Called when a new module is loaded, to run cleanup on the old module (if needed) */
async function runModuleDispose(id) {
const state = REGISTERED_MODULES[id];
if (!state) {
return false;
}
if (state.isDeclined) {
return false;
}
const disposeCallbacks = state.disposeCallbacks;
state.disposeCallbacks = [];
state.data = {};
disposeCallbacks.map((callback) => callback());
return true;
}
socket.addEventListener('message', ({data: _data}) => {
if (!_data) {
return;
}
const data = JSON.parse(_data);
debug('message', data);
if (data.type === 'reload') {
debug('message: reload');
reload();
return;
}
if (data.type !== 'update') {
debug('message: unknown', data);
return;
}
debug('message: update', data);
debug(data.url, Object.keys(REGISTERED_MODULES));
runModuleAccept(data.url)
.then((ok) => {
if (!ok) {
reload();
}
})
.catch((err) => {
console.error(err);
reload();
});
});
debug('listening for file changes...');