mini-url
Version:
Lightweight isomorphic url parser.
71 lines • 2.07 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var T = require("./_types");
exports.Types = T;
var url_1 = require("./url");
var parts_1 = require("./url/parts");
exports.parts = parts_1.default;
var separator = "~#~";
var cache = {};
exports.cache = cache;
/**
* @description
* Creates a browser style URL object.
* See: https://developer.mozilla.org/en-US/docs/Web/API/URL
*
* @example
* parse("http//google.ca") // { protocol: "http", hostname: "google", ... }
*
* @param url The url string to parse.
* @param base The base part of the url to resolve from.
*/
function parse(url, base) {
var key = url + separator + base;
// Try to return cached url.
var cached = cache[key];
if (cached) {
return cached;
}
// Parse url and cache result.
var parsed = base ? new url_1.URL(url, base) : new url_1.URL(url);
var result = { toString: toString };
// Make each part default to empty string for consistency.
for (var _i = 0, parts_2 = parts_1.default; _i < parts_2.length; _i++) {
var part = parts_2[_i];
var data = parsed[part];
if (data == null) {
data = "";
}
result[part] = data;
}
// Freeze object to maintain cache.
return (cache[key] = Object.freeze(result));
}
exports.parse = parse;
/**
* @description
* Converts a URL like object into an href.
*
* @param parsed A parsed url object containing.
*/
function stringify(parsed) {
if (typeof parsed !== "object" || parsed == null) {
throw new TypeError("URL must be an object.");
}
// istanbul ignore next
return ((parsed.protocol ? parsed.protocol + "//" : "") +
(parsed.host ||
(parsed.hostname || "") + (parsed.port ? ":" + parsed.port : "")) +
(parsed.pathname || "") +
(parsed.search || "") +
(parsed.hash || ""));
}
exports.stringify = stringify;
/**
* @description
* To string method for cloned urls.
*/
function toString() {
return this.href;
}
//# sourceMappingURL=index.js.map