-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.js
130 lines (107 loc) · 2.58 KB
/
helper.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
import StackTrace from "stacktrace-js";
import kaboom from "kaboom";
window.kaboom = kaboom;
// report error to server
window.addEventListener("error", (e) => {
StackTrace
.fromError(e.error)
.then((stack) => {
fetch("/error", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
msg: e.error.message,
stack: stack.slice(0, 4).map((step) => {
return {
...step,
file: step.fileName.replace(location.origin + "/", ""),
line: step.lineNumber,
col: step.columnNumber,
};
}),
}),
});
})
.catch(() => console.error("failed to parse err"));
});
// listen for live reload msg
const wsp = location.protocol === "https:" ? "wss" : "ws";
const devws = new WebSocket(`${wsp}://${location.host}/devws`);
devws.onmessage = (e) => {
const msg = JSON.parse(e.data);
if (msg === "REFRESH") {
location.reload();
}
};
// replit auth
window.replit = {
user: null,
getUser() {
return fetch("/user")
.then((res) => res.json())
.then((user) => {
if (user) {
this.user = user;
return Promise.resolve(this.user);
} else {
return Promise.resolve(null);
}
});
},
authed() {
return this.user !== null;
},
auth() {
return new Promise((resolve, reject) => {
if (this.authed()) {
resolve(this.user);
return;
}
const authComplete = (e) => {
if (e.data !== "auth_complete") {
resolve(null);
return;
}
window.removeEventListener("message", authComplete);
authWindow.close();
this.getUser().then(resolve);
};
window.addEventListener("message", authComplete);
const w = 320;
const h = 480;
const left = (screen.width / 2) - (w / 2);
const top = (screen.height / 2) - (h / 2);
const authWindow = window.open(
`https://repl.it/auth_with_repl_site?domain=${location.host}`,
"_blank",
`modal=yes, toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=${w}, height=${h}, top=${top}, left=${left}`
);
});
},
};
// replit db
window.db = {
getData(key, def) {
return fetch(`/db/${key}`)
.then((res) => res.json())
.then((val) => {
// set default value if empty
if (val == null && def !== undefined) {
return this.setData(key, def);
}
return Promise.resolve(val);
});
},
setData(key, val) {
return fetch(`/db/${key}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(val),
}).then(() => Promise.resolve(val));
},
};
replit.getUser();