@lwrjs/client-modules 0.7.0-alpha.13 → 0.7.0-alpha.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -34,14 +34,44 @@ function viewUpdate(payload, metadata) {
34
34
  }
35
35
  }
36
36
 
37
+ async function waitForSuccessfulPing(socketUrl) {
38
+ // eslint-disable-next-line no-constant-condition
39
+ while (true) {
40
+ try {
41
+ // Fetching for the socket URL reject with a network error if not available. If the dev
42
+ // server comes back online, it resolve with 404 HTTP response.
43
+ await fetch(`http://${socketUrl}`);
44
+ break;
45
+ } catch (error) {
46
+ await new Promise((resolve) => setTimeout(resolve, 1_000));
47
+ }
48
+ }
49
+ }
50
+
37
51
  export function initHMR(serverURI = '', metadata) {
38
52
  const normalizedMeta = {
39
53
  ...{ assetReferences: [], templates: [] },
40
54
  ...metadata,
41
55
  };
56
+
42
57
  // {apiVersion}/hmr/{format}/{compat}?debug
43
58
  const host = serverURI.startsWith('/') ? location.host : '';
44
- const socket = new WebSocket(`ws://${host}${serverURI}`);
59
+ const socketUrl = `${host}${serverURI}`;
60
+
61
+ const socket = new WebSocket(`ws://${socketUrl}`);
62
+
63
+ socket.addEventListener('close', async (evt) => {
64
+ // Don't do anything is the socket close event was initiated by the client.
65
+ if (evt.wasClean) {
66
+ return;
67
+ }
68
+
69
+ // Otherwise wait until the server comes back online and reload the page.
70
+ console.log('Lost connection with server, start polling...');
71
+ await waitForSuccessfulPing(socketUrl);
72
+ location.reload();
73
+ });
74
+
45
75
  socket.addEventListener('message', async ({ data }) => {
46
76
  const { eventType, payload } = JSON.parse(data);
47
77