Skip to content

Instantly share code, notes, and snippets.

@charmander
Created June 28, 2018 11:30
Show Gist options
  • Save charmander/a30c21a5d7a9564b0fa682637ac46758 to your computer and use it in GitHub Desktop.
Save charmander/a30c21a5d7a9564b0fa682637ac46758 to your computer and use it in GitHub Desktop.
'use strict';
const {inspect} = require('util');
const readonly = value => ({
configurable: true,
value,
});
// Not to be considered a URL.
class URLPath extends URL {
constructor(text) {
if (text[0] !== '/' || text[1] === '/' || text[1] === '\\') {
const error = new Error('Not a host-relative URL: ' + inspect(text));
error.code = 'ERR_INVALID_URL';
throw error;
}
super(text, 'http://localhost/');
}
static tryCreate(text) {
try {
return new this(text);
} catch (error) {
if (error.code === 'ERR_INVALID_URL') {
return null;
}
throw error;
}
}
}
['href', 'origin', 'protocol', 'username', 'password', 'host', 'hostname', 'port']
.forEach(name => {
Object.defineProperty(URLPath.prototype, name, readonly(undefined));
});
['pathname', 'search', 'hash']
.forEach(name => {
Object.defineProperty(URLPath.prototype, name, {
...Object.getOwnPropertyDescriptor(URL.prototype, name),
set: undefined,
});
});
module.exports = URLPath;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment