reactronic
Version:
Reactronic - Transactional Reactive State Management
68 lines (67 loc) • 2.77 kB
JavaScript
import { misuse } from "./Dbg.js";
export class Uri {
constructor(scheme, authority, path, query, fragment) {
this.scheme = scheme;
this.authority = authority !== null && authority !== void 0 ? authority : "";
this.path = path !== null && path !== void 0 ? path : "";
this.query = query !== null && query !== void 0 ? query : "";
this.fragment = fragment !== null && fragment !== void 0 ? fragment : "";
validateUri(this);
}
equalsTo(uri) {
return this.scheme === uri.scheme &&
this.authority === uri.authority &&
this.path === uri.path &&
this.query === uri.query &&
this.fragment === uri.fragment;
}
toString() {
let result = `${this.scheme}://${this.authority}${this.path}`;
if (this.query) {
result += `?${this.query}`;
}
if (this.fragment) {
result += `#${this.fragment}`;
}
return result;
}
static parse(value) {
var _a, _b, _c, _d, _e;
let result;
const match = Uri.regexp.exec(value);
if (!match) {
result = new Uri("");
}
else {
result = new Uri((_a = match[2]) !== null && _a !== void 0 ? _a : "", (_b = match[4]) !== null && _b !== void 0 ? _b : "", (_c = match[5]) !== null && _c !== void 0 ? _c : "", (_d = match[7]) !== null && _d !== void 0 ? _d : "", (_e = match[9]) !== null && _e !== void 0 ? _e : "");
}
return result;
}
static from(components) {
return new Uri(components.scheme, components.authority, components.path, components.query, components.fragment);
}
}
Uri.regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
const SCHEME_PATTERN = /^\w[\w\d+.-]*$/;
const SINGLE_SLASH_START = /^\//;
const DOUBLE_SLASH_START = /^\/\//;
function validateUri(uri, strict) {
if (!uri.scheme && strict) {
throw misuse(`Scheme is missing: {scheme: "", authority: "${uri.authority}", path: "${uri.path}", query: "${uri.query}", fragment: "${uri.fragment}"}`);
}
if (uri.scheme && !SCHEME_PATTERN.test(uri.scheme)) {
throw misuse("Scheme contains illegal characters.");
}
if (uri.path) {
if (uri.authority) {
if (!SINGLE_SLASH_START.test(uri.path)) {
throw misuse("If a URI contains an authority component, then the path component must either be empty or begin with a slash character ('/').");
}
}
else {
if (DOUBLE_SLASH_START.test(uri.path)) {
throw misuse("If a URI does not contain an authority component, then the path cannot begin with two slash characters ('//').");
}
}
}
}