-
Notifications
You must be signed in to change notification settings - Fork 2
/
at.js
46 lines (39 loc) · 997 Bytes
/
at.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
'use strict';
// Parser is a simple html a element that is used for parsing URL parts.
const parser = document.createElement('a');
// at takes care of encoding and decoding URLs to/from the AT format used by the
// bttn.
// For example:
// "http://example.com:8000/hello" -> "example.com,/hello,8000".
const at = {
encodeURL(url) {
if (!url.match(/^https?:\/\//)) {
url = 'http://' + url;
}
parser.href = url;
if (!parser.hostname) {
return '';
}
let port = parser.port;
if (parser.protocol === 'https:' && !port) {
port = 443;
}
let newURL = parser.hostname + ',' + parser.pathname;
if (port) {
newURL += ',' + port;
}
// Maximum URL length, as defined in firmware.
if (newURL.length > 200) {
throw new Error('URL too long: ' + url);
}
return newURL;
},
decodeURL(url) {
let [domain = '', search = '', port = ''] = url.split(',');
if (port) {
port = ':' + port;
}
return 'http://' + domain + port + search;
}
};
window.at = at;