UNPKG

safelinkify

Version:

NodeJS anonymizer external links into outbound page. Anonymize external links to outbound page redirector for SEO.

63 lines (62 loc) 1.37 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isValidHttpUrl = isValidHttpUrl; exports.fixUrl = fixUrl; exports.default = toURL; /** * is url valid * @param string * @returns */ function isValidHttpUrl(string) { var url; try { url = new URL(string); } catch (_) { return false; } return url.protocol === 'http:' || url.protocol === 'https:'; } /** * fix url * * doubled slashes * @param url * @returns */ function fixUrl(url) { var str; if (typeof url === 'string') { str = url; } else { str = url.toString(); } return str.replace(/([^:]\/)\/+/g, '$1'); } /** * transform url string to {@link Nullable}<{@link URL}> * @param url * @returns */ function toURL(url) { try { if (url.startsWith('/') || url.startsWith('?')) { // url is pathname or query return new URL('http://not-actually-domain.com/' + url.replace(/^\/+/, '')); } else if (url.match(/^https?:\/\//)) { // test full url with protocol:// return new URL(url); } else { // Not a valid URL for our use case return null; } } catch (error) { if (error instanceof Error) console.log(url, error.message); return null; } }