/
wcHmrRuntime.js
197 lines (176 loc) · 5.92 KB
/
wcHmrRuntime.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
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
// @ts-nocheck
/* eslint-disable no-param-reassign, no-console */
// override global define to allow double registrations
const originalDefine = window.customElements.define;
window.customElements.define = (name, ...rest) => {
if (!window.customElements.get(name)) {
originalDefine.call(window.customElements, name, ...rest);
}
};
const proxiesForKeys = new Map();
const keysForClasses = new Map();
function trackConnectedElements(hmrClass) {
const connectedElements = new Set();
const originalCb = hmrClass.prototype.connectedCallback;
hmrClass.prototype.connectedCallback = function connectedCallback(...args) {
if (originalCb) {
originalCb.call(this, ...args);
}
connectedElements.add(this);
};
const originalDcb = hmrClass.prototype.disconnectedCallback;
hmrClass.prototype.disconnectedCallback = function disconnectedCallback(...args) {
if (originalDcb) {
originalDcb.call(this, ...args);
}
connectedElements.delete(this);
};
return connectedElements;
}
const proxyMethods = [
'construct',
'defineProperty',
'deleteProperty',
'getOwnPropertyDescriptor',
'getPrototypeOf',
'setPrototypeOf',
'isExtensible',
'ownKeys',
'preventExtensions',
'has',
'get',
'set',
];
/**
* Creates a proxy for the given target, and fowards any calls to the most up to the latest
* version of the target. (ex. the latest hot replaced class).
*/
function createProxy(originalTarget, getCurrentTarget) {
const proxyHandler = {};
for (const method of proxyMethods) {
proxyHandler[method] = (_, ...args) => {
if (method === 'get' && args[0] === 'prototype') {
// prototype must always return original target value
return Reflect[method](_, ...args);
}
return Reflect[method](getCurrentTarget(), ...args);
};
}
return new Proxy(originalTarget, proxyHandler);
}
/**
* Replaces all prototypes in the inheritance chain with a proxy
* that references the latest implementation
*/
function replacePrototypesWithProxies(instance) {
let previous = instance;
let proto = Object.getPrototypeOf(instance);
while (proto && proto.constructor !== HTMLElement) {
const key = keysForClasses.get(proto.constructor);
if (key) {
// this is a prototype that might be hot-replaced later
const getCurrentProto = () => proxiesForKeys.get(key).currentClass.prototype;
Object.setPrototypeOf(previous, createProxy(proto, getCurrentProto));
}
previous = proto;
proto = Object.getPrototypeOf(proto);
}
}
export class WebComponentHmr extends HTMLElement {
constructor() {
super();
const key = keysForClasses.get(this.constructor);
// check if the constructor is registered
if (key) {
const p = proxiesForKeys.get(key);
// replace the constructor with a proxy that references the latest implementation of this class
this.constructor = p.currentProxy;
}
// replace prototype chain with a proxy to the latest prototype implementation
replacePrototypesWithProxies(this);
}
}
window.WebComponentHmr = WebComponentHmr;
/**
* Injects the WebComponentHmr class into the inheritance chain
*/
function injectInheritsHmrClass(clazz) {
let parent = clazz;
let proto = Object.getPrototypeOf(clazz);
// walk prototypes until we reach HTMLElement
while (proto && proto !== HTMLElement) {
parent = proto;
proto = Object.getPrototypeOf(proto);
}
if (proto !== HTMLElement) {
// not a web component
return;
}
if (parent === WebComponentHmr) {
// class already inherits WebComponentHmr
return;
}
Object.setPrototypeOf(parent, WebComponentHmr);
}
/**
* Registers a web component class. Triggers a hot replacement if the
* class was already registered before.
*/
export function register(importMeta, name, clazz) {
const key = `${new URL(importMeta.url).pathname}:${name}`;
const existing = proxiesForKeys.get(key);
if (!existing) {
// this class was not yet registered,
// create a proxy that will forward to the latest implementation
const proxy = createProxy(clazz, () => proxiesForKeys.get(key).currentClass);
// inject a HMR class into the inheritance chain
injectInheritsHmrClass(clazz);
// keep track of all connected elements for this class
const connectedElements = trackConnectedElements(clazz);
proxiesForKeys.set(key, {
originalProxy: proxy,
currentProxy: proxy,
originalClass: clazz,
currentClass: clazz,
connectedElements,
});
keysForClasses.set(clazz, key);
return proxy;
}
// class was already registered before
// register new class, all calls will be proxied to this class
const previousProxy = existing.currentProxy;
const currentProxy = createProxy(clazz, () => proxiesForKeys.get(key).currentClass);
existing.currentClass = clazz;
existing.currentProxy = currentProxy;
Promise.resolve().then(() => {
// call optional HMR on the class if they exist, after next microtask to ensure
// module bodies have executed fully
if (clazz.hotReplacedCallback) {
try {
clazz.hotReplacedCallback();
} catch (error) {
console.error(error);
}
}
for (const element of existing.connectedElements) {
if (element.constructor === previousProxy) {
// we need to update the constructor of the element to match to newly created proxy
// but we should only do this for elements that was directly created with this class
// and not for elements that extend this
element.constructor = currentProxy;
}
if (element.hotReplacedCallback) {
try {
element.hotReplacedCallback();
} catch (error) {
console.error(error);
}
}
}
});
// the original proxy already forwards to the new class but we're return a new proxy
// because access to `prototype` must return the original value and we need to be able to
// manipulate the prototype on the new class
return currentProxy;
}