Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
titaniumnetwork-dev
GitHub Repository: titaniumnetwork-dev/Ludicrous
Path: blob/main/corrosion/lib/url.js
1223 views
1
// -------------------------------------------------------------
2
// WARNING: this file is used by both the client and the server.
3
// Do not use any browser or node-specific API!
4
// -------------------------------------------------------------
5
const codec = require('./codec');
6
const defaultConfig = {
7
prefix: '/service/',
8
codec: 'plain'
9
};
10
11
class URLWrapper {
12
constructor(config = defaultConfig) {
13
this.prefix = config.prefix || defaultConfig.prefix;
14
this.codec = codec[config.codec || 'plain'] || codec['plain'];
15
this.regex = /^(#|about:|data:|blob:|mailto:|javascript:)/;
16
};
17
wrap(val, config = {}) {
18
if (!val || this.regex.test(val)) return val;
19
let flags = '';
20
(config.flags || []).forEach(flag => flags += `${flag}_/`);
21
if (config.base) try {
22
if (!['http:', 'https:', 'ws:', 'wss:'].includes(new URL(val, config.base).protocol)) return val;
23
} catch(e) {
24
return val;
25
};
26
return (config.origin || '') + this.prefix + flags + this.codec.encode(config.base ? new URL(val, config.base) : val) + '/';
27
};
28
unwrap(val, config = {}) {
29
if (!val || this.regex.test(val)) return val;
30
let processed = val.slice((config.origin || '').length + this.prefix.length);
31
const flags = ('/' + processed).match(/(?<=\/)(.*?)(?=_\/)/g) || [];
32
flags.forEach(flag => processed = processed.slice(`${flag}_/`.length));
33
let [ url, leftovers ] = processed.split(/\/(.+)?/);
34
return config.flags ? { value: this.codec.decode((url || '')) + (config.leftovers && leftovers ? leftovers : ''), flags } : this.codec.decode((url || '')) + (config.leftovers && leftovers ? leftovers : '');
35
};
36
};
37
38
module.exports = URLWrapper;
39
40