forked from babel/sandboxes
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathREPLState.js
274 lines (252 loc) · 6.83 KB
/
REPLState.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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
const baseURL =
process.env.NODE_ENV === "production"
? `https://babel-sandbox.herokuapp.com`
: "";
// convert a Unicode string to a string in which
// each 16-bit unit occupies only one byte
// source: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa
function toBinary(string) {
const codeUnits = new Uint16Array(string.length);
for (let i = 0; i < codeUnits.length; i++) {
codeUnits[i] = string.charCodeAt(i);
}
return String.fromCharCode(...new Uint8Array(codeUnits.buffer));
}
// source: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa
function fromBinary(binary) {
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < bytes.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return String.fromCharCode(...new Uint16Array(bytes.buffer));
}
/**
* encodeToBase64 encodes any string to base64.
* @param {string} jsSource
* @returns {string} base64 js string.
*/
function encodeToBase64(jsSource) {
const binString = toBinary(jsSource);
return btoa(binString);
}
/**
* decodeBase64 decodes a base64 string to
* js code.
* @param {string} base64String
* @returns {string} the original js source.
*/
function decodeBase64(base64String) {
const decoded = atob(base64String);
return fromBinary(decoded);
}
class REPLState {
/**
* The REPLState constructor takes in what the App component provides with the exception of the configs.
* Those must be turned into strings before calling the constructor.
* @param {string} jsSource
* @param {string} pluginSource
* @param {string[]} configs
*/
constructor(jsSource, pluginSource, configs) {
this.jsSource = jsSource;
this.pluginSource = pluginSource;
this.configs = configs;
this.id = "";
}
/**
* Encode returns an encoded version of the REPL State
* as a string.
* @returns {string}
*/
Encode() {
return JSON.stringify({
source: encodeToBase64(this.jsSource),
plugin: encodeToBase64(this.pluginSource),
configs: this.configs.map(configSrc => {
return encodeToBase64(configSrc);
}),
});
}
/**
* Decode decodes the json string.
* @param {string} encodedState
* @returns {REPLState}
*/
static Decode(encodedState) {
let jsonState = JSON.parse(encodedState);
return new REPLState(
decodeBase64(jsonState.base64SourceKey || ""),
decodeBase64(jsonState.base64PluginKey || ""),
jsonState.configIDs.map(configs => {
return decodeBase64(configs || "");
})
);
}
/**
* list returns a list of names bases off the
* key. For internal use only.
* @param {string}key
* @returns {string[]} List of the desired key.
*/
list(key) {
const s = new Set();
const tConfigs = this.configs.map(conf => JSON.parse(conf));
tConfigs.forEach(conf => {
const arr = conf?.[key];
// Take advantage of JS short circuiting.
if (arr === undefined || !Array.isArray(arr) || arr.length < 1) {
return;
}
// For sure an array, grab each name.
arr.forEach(val => {
// Is this just a string?
if (typeof val === "string") {
s.add(val);
return;
}
// If this is an array then the plugin name is the first one.
if (Array.isArray(val) && val.length > 0) {
s.add(val[0]);
return;
}
// Otherwise check if it has a name property.
const name = val?.name;
if (name === undefined) {
return;
}
s.add(name);
});
});
return Array.from(s);
}
PluginList() {
return this.list("plugins");
}
PresetList() {
return this.list("presets");
}
/**
* Link gets the sharing the sharing link
* for the given REPL state and updates the id
* @returns {Promise<string>} String URL.
*/
async Link(id, setId) {
try {
let message;
if (!id) {
message = await this.New();
setId(message.id);
} else {
message = await this.Save(id);
}
// https://stackoverflow.com/questions/6941533/get-protocol-domain-and-port-from-url
return (
window.location.href.split("/").slice(0, 3).join("/") + message.url
);
} catch (err) {
console.error(err);
return err;
}
}
/**
* New saves the current REPL state as a new blob
* @returns {Promise<Object>} Blob representing the current state.
*/
async New() {
const url = baseURL + `/api/v1/blobs/create`;
try {
const resp = await fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: this.Encode(),
});
const json = resp.json();
return json;
} catch (err) {
console.error(err);
return err;
}
}
/**
* Save updates the corresponding blob with the current REPLState
* @returns {Promise<Object>} Blob representing the current state.
*/
async Save(ID) {
const url = baseURL + `/api/v1/blobs/update/${ID}`;
try {
const resp = await fetch(url, {
method: "PUT",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: this.Encode(),
});
const json = resp.json();
return json;
} catch (err) {
console.error(err);
return err;
}
}
/**
* Forks a configuration given a unique identifier
* @returns {Promise<Object>} Blob representing the new fork
*/
async Fork(ID) {
const url = baseURL + `/api/v1/blobs/fork/${ID}`;
try {
const resp = await fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
});
return resp.json();
} catch (err) {
console.error(err);
return err;
}
}
/**
* REPLState.GetBlob returns the blob given a unique identifier
* @param {string} ID
* @return {Promise<Object>}
*/
static async GetBlob(ID) {
const url = baseURL + `/api/v1/blobs/${ID}`;
try {
const resp = await fetch(url);
const json = await resp.json();
return json;
} catch (err) {
console.error(err);
return err;
}
}
/**
* REPLState.FromID returns a REPLState given a unique identifier.
* @param {string} ID
* @returns {Promise<REPLState | null>}
*/
static async FromID(ID) {
const url = baseURL + `/api/v1/blobs/${ID}`;
try {
const resp = await fetch(url);
const text = await resp.text();
// const json = await resp.json();
const replState = REPLState.Decode(text);
replState.id = ID;
replState.forks = JSON.parse(text).forks;
return replState;
} catch (err) {
console.error(err);
return null;
}
}
}
export default REPLState;