Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

parse-url

Package Overview
Dependencies
Maintainers
1
Versions
44
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

parse-url - npm Package Compare versions

Comparing version 8.0.0 to 8.1.0

index.d.ts

286

dist/index.js
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var parsePath = require('parse-path');
var normalizeUrl = require('normalize-url');
function _interopDefaultLegacy(e) {
return e && (typeof e === 'undefined' ? 'undefined' : _typeof(e)) === 'object' && 'default' in e ? e : { 'default': e };
}
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var parsePath__default = /*#__PURE__*/_interopDefaultLegacy(parsePath);
var normalizeUrl__default = /*#__PURE__*/_interopDefaultLegacy(normalizeUrl);
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
const DATA_URL_DEFAULT_MIME_TYPE = 'text/plain';
const DATA_URL_DEFAULT_CHARSET = 'us-ascii';
const testParameter = (name, filters) => filters.some(filter => filter instanceof RegExp ? filter.test(name) : filter === name);
const normalizeDataURL = (urlString, {stripHash}) => {
const match = /^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(urlString);
if (!match) {
throw new Error(`Invalid URL: ${urlString}`);
}
let {type, data, hash} = match.groups;
const mediaType = type.split(';');
hash = stripHash ? '' : hash;
let isBase64 = false;
if (mediaType[mediaType.length - 1] === 'base64') {
mediaType.pop();
isBase64 = true;
}
// Lowercase MIME type
const mimeType = (mediaType.shift() || '').toLowerCase();
const attributes = mediaType
.map(attribute => {
let [key, value = ''] = attribute.split('=').map(string => string.trim());
// Lowercase `charset`
if (key === 'charset') {
value = value.toLowerCase();
if (value === DATA_URL_DEFAULT_CHARSET) {
return '';
}
}
return `${key}${value ? `=${value}` : ''}`;
})
.filter(Boolean);
const normalizedMediaType = [
...attributes,
];
if (isBase64) {
normalizedMediaType.push('base64');
}
if (normalizedMediaType.length > 0 || (mimeType && mimeType !== DATA_URL_DEFAULT_MIME_TYPE)) {
normalizedMediaType.unshift(mimeType);
}
return `data:${normalizedMediaType.join(';')},${isBase64 ? data.trim() : data}${hash ? `#${hash}` : ''}`;
};
function normalizeUrl(urlString, options) {
options = {
defaultProtocol: 'http:',
normalizeProtocol: true,
forceHttp: false,
forceHttps: false,
stripAuthentication: true,
stripHash: false,
stripTextFragment: true,
stripWWW: true,
removeQueryParameters: [/^utm_\w+/i],
removeTrailingSlash: true,
removeSingleSlash: true,
removeDirectoryIndex: false,
sortQueryParameters: true,
...options,
};
urlString = urlString.trim();
// Data URL
if (/^data:/i.test(urlString)) {
return normalizeDataURL(urlString, options);
}
if (/^view-source:/i.test(urlString)) {
throw new Error('`view-source:` is not supported as it is a non-standard protocol');
}
const hasRelativeProtocol = urlString.startsWith('//');
const isRelativeUrl = !hasRelativeProtocol && /^\.*\//.test(urlString);
// Prepend protocol
if (!isRelativeUrl) {
urlString = urlString.replace(/^(?!(?:\w+:)?\/\/)|^\/\//, options.defaultProtocol);
}
const urlObject = new URL(urlString);
if (options.forceHttp && options.forceHttps) {
throw new Error('The `forceHttp` and `forceHttps` options cannot be used together');
}
if (options.forceHttp && urlObject.protocol === 'https:') {
urlObject.protocol = 'http:';
}
if (options.forceHttps && urlObject.protocol === 'http:') {
urlObject.protocol = 'https:';
}
// Remove auth
if (options.stripAuthentication) {
urlObject.username = '';
urlObject.password = '';
}
// Remove hash
if (options.stripHash) {
urlObject.hash = '';
} else if (options.stripTextFragment) {
urlObject.hash = urlObject.hash.replace(/#?:~:text.*?$/i, '');
}
// Remove duplicate slashes if not preceded by a protocol
// NOTE: This could be implemented using a single negative lookbehind
// regex, but we avoid that to maintain compatibility with older js engines
// which do not have support for that feature.
if (urlObject.pathname) {
// TODO: Replace everything below with `urlObject.pathname = urlObject.pathname.replace(/(?<!\b[a-z][a-z\d+\-.]{1,50}:)\/{2,}/g, '/');` when Safari supports negative lookbehind.
// Split the string by occurrences of this protocol regex, and perform
// duplicate-slash replacement on the strings between those occurrences
// (if any).
const protocolRegex = /\b[a-z][a-z\d+\-.]{1,50}:\/\//g;
let lastIndex = 0;
let result = '';
for (;;) {
const match = protocolRegex.exec(urlObject.pathname);
if (!match) {
break;
}
const protocol = match[0];
const protocolAtIndex = match.index;
const intermediate = urlObject.pathname.slice(lastIndex, protocolAtIndex);
result += intermediate.replace(/\/{2,}/g, '/');
result += protocol;
lastIndex = protocolAtIndex + protocol.length;
}
const remnant = urlObject.pathname.slice(lastIndex, urlObject.pathname.length);
result += remnant.replace(/\/{2,}/g, '/');
urlObject.pathname = result;
}
// Decode URI octets
if (urlObject.pathname) {
try {
urlObject.pathname = decodeURI(urlObject.pathname);
} catch {}
}
// Remove directory index
if (options.removeDirectoryIndex === true) {
options.removeDirectoryIndex = [/^index\.[a-z]+$/];
}
if (Array.isArray(options.removeDirectoryIndex) && options.removeDirectoryIndex.length > 0) {
let pathComponents = urlObject.pathname.split('/');
const lastComponent = pathComponents[pathComponents.length - 1];
if (testParameter(lastComponent, options.removeDirectoryIndex)) {
pathComponents = pathComponents.slice(0, -1);
urlObject.pathname = pathComponents.slice(1).join('/') + '/';
}
}
if (urlObject.hostname) {
// Remove trailing dot
urlObject.hostname = urlObject.hostname.replace(/\.$/, '');
// Remove `www.`
if (options.stripWWW && /^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(urlObject.hostname)) {
// Each label should be max 63 at length (min: 1).
// Source: https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names
// Each TLD should be up to 63 characters long (min: 2).
// It is technically possible to have a single character TLD, but none currently exist.
urlObject.hostname = urlObject.hostname.replace(/^www\./, '');
}
}
// Remove query unwanted parameters
if (Array.isArray(options.removeQueryParameters)) {
// eslint-disable-next-line unicorn/no-useless-spread -- We are intentionally spreading to get a copy.
for (const key of [...urlObject.searchParams.keys()]) {
if (testParameter(key, options.removeQueryParameters)) {
urlObject.searchParams.delete(key);
}
}
}
if (options.removeQueryParameters === true) {
urlObject.search = '';
}
// Sort query parameters
if (options.sortQueryParameters) {
urlObject.searchParams.sort();
// Calling `.sort()` encodes the search parameters, so we need to decode them again.
try {
urlObject.search = decodeURIComponent(urlObject.search);
} catch {}
}
if (options.removeTrailingSlash) {
urlObject.pathname = urlObject.pathname.replace(/\/$/, '');
}
const oldUrlString = urlString;
// Take advantage of many of the Node `url` normalizations
urlString = urlObject.toString();
if (!options.removeSingleSlash && urlObject.pathname === '/' && !oldUrlString.endsWith('/') && urlObject.hash === '') {
urlString = urlString.replace(/\/$/, '');
}
// Remove ending `/` unless removeSingleSlash is false
if ((options.removeTrailingSlash || urlObject.pathname === '/') && urlObject.hash === '' && options.removeSingleSlash) {
urlString = urlString.replace(/\/$/, '');
}
// Restore relative protocol, if applicable
if (hasRelativeProtocol && !options.normalizeProtocol) {
urlString = urlString.replace(/^http:\/\//, '//');
}
// Remove http/https
if (options.stripProtocol) {
urlString = urlString.replace(/^(?:https?:)?\/\//, '');
}
return urlString;
}
// Dependencies

@@ -47,13 +288,11 @@

*/
var parseUrl = function parseUrl(url) {
var normalize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
const parseUrl = (url, normalize = false) => {
// Constants
var GIT_RE = /(^(git@|http(s)?:\/\/)([\w\.\-@]+)(\/|:))(([\~,\.\w,\-,\_,\/]+)(.git){0,1}((\/){0,1}))/;
const GIT_RE = /^(?:([a-z_][a-z0-9_-]{0,31})@|https?:\/\/)([\w\.\-@]+)[\/:]([\~,\.\w,\-,\_,\/]+?(?:\.git|\/)?)$/;
var throwErr = function throwErr(msg) {
var err = new Error(msg);
const throwErr = msg => {
const err = new Error(msg);
err.subject_url = url;
throw err;
throw err
};

@@ -70,3 +309,3 @@

if (normalize) {
if ((typeof normalize === 'undefined' ? 'undefined' : _typeof(normalize)) !== "object") {
if (typeof normalize !== "object") {
normalize = {

@@ -76,17 +315,18 @@ stripHash: false

}
url = normalizeUrl__default["default"](url, normalize);
url = normalizeUrl(url, normalize);
}
var parsed = parsePath__default["default"](url);
const parsed = parsePath__default["default"](url);
// Potential git-ssh urls
if (parsed.parse_failed) {
var matched = parsed.href.match(GIT_RE);
const matched = parsed.href.match(GIT_RE);
if (matched) {
parsed.protocols = ["ssh"];
parsed.protocol = "ssh";
parsed.resource = matched[4];
parsed.host = matched[4];
parsed.user = "git";
parsed.pathname = '/' + matched[6];
parsed.resource = matched[2];
parsed.host = matched[2];
parsed.user = matched[1];
parsed.pathname = `/${matched[3]}`;
parsed.parse_failed = false;

@@ -103,2 +343,2 @@ } else {

module.exports = parseUrl;
module.exports = parseUrl;

10

package.json
{
"name": "parse-url",
"version": "8.0.0",
"version": "8.1.0",
"description": "An advanced url parser supporting git urls too.",

@@ -39,8 +39,7 @@ "main": "./dist/index.js",

"devDependencies": {
"normalize-url": "^7.0.3",
"pkgroll": "^1.4.0",
"tester": "^1.3.1",
"normalize-url": "^7.0.3"
"tester": "^1.3.1"
},
"dependencies": {
"normalize-url": "^7.0.3",
"parse-path": "^7.0.0"

@@ -59,2 +58,3 @@ },

"index.js",
"index.d.ts",
"bloggify.js",

@@ -69,2 +69,2 @@ "bloggify.json",

}
}
}

@@ -22,3 +22,3 @@ <!-- Please do not edit this file. Edit the `blah` field in the `package.json` instead. If in doubt, open an issue. -->

[![Support me on Patreon][badge_patreon]][patreon] [![Buy me a book][badge_amazon]][amazon] [![PayPal][badge_paypal_donate]][paypal-donations] [![Ask me anything](https://img.shields.io/badge/ask%20me-anything-1abc9c.svg)](https://github.com/IonicaBizau/ama) [![Travis](https://img.shields.io/travis/IonicaBizau/parse-url.svg)](https://travis-ci.org/IonicaBizau/parse-url/) [![Version](https://img.shields.io/npm/v/parse-url.svg)](https://www.npmjs.com/package/parse-url) [![Downloads](https://img.shields.io/npm/dt/parse-url.svg)](https://www.npmjs.com/package/parse-url) [![Get help on Codementor](https://cdn.codementor.io/badges/get_help_github.svg)](https://www.codementor.io/johnnyb?utm_source=github&utm_medium=button&utm_term=johnnyb&utm_campaign=github)
[![Support me on Patreon][badge_patreon]][patreon] [![Buy me a book][badge_amazon]][amazon] [![PayPal][badge_paypal_donate]][paypal-donations] [![Ask me anything](https://img.shields.io/badge/ask%20me-anything-1abc9c.svg)](https://github.com/IonicaBizau/ama) [![Version](https://img.shields.io/npm/v/parse-url.svg)](https://www.npmjs.com/package/parse-url) [![Downloads](https://img.shields.io/npm/dt/parse-url.svg)](https://www.npmjs.com/package/parse-url) [![Get help on Codementor](https://cdn.codementor.io/badges/get_help_github.svg)](https://www.codementor.io/johnnyb?utm_source=github&utm_medium=button&utm_term=johnnyb&utm_campaign=github)

@@ -175,5 +175,2 @@ <a href="https://www.buymeacoffee.com/H96WwChMy" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/yellow_img.png" alt="Buy Me A Coffee"></a>

### `interopDefaultLegacy()`
#__PURE__
### `parseUrl(url, normalize)`

@@ -266,3 +263,2 @@ Parses the input url.

- `kakapo`
- `@pushrocks/smarturl`
- `parse-db-uri`

@@ -285,20 +281,21 @@ - `fuge-runner`

- `@notnuzzel/crawl`
- `native-kakao-login`
- `gitlab-backup-util-harduino`
- `miguelcostero-ng2-toasty`
- `native-kakao-login`
- `npm_one_1_2_3`
- `react-native-biometric-authenticate`
- `react-native-arunmeena1987`
- `react-native-biometric-authenticate`
- `react-native-contact-list`
- `react-native-payu-payment-testing`
- `react-native-is7`
- `react-native-payu-payment-testing`
- `react-native-my-first-try-arun-ramya`
- `react-native-kakao-maps`
- `react-native-my-first-try-arun-ramya`
- `react-native-ytximkit`
- `rn-adyen-dropin`
- `begg`
- `@positionex/position-sdk`
- `begg`
- `@corelmax/react-native-my2c2p-sdk`
- `@felipesimmi/react-native-datalogic-module`
- `@hawkingnetwork/react-native-tab-view`
- `@jprustv/sulla-hotfix`
- `@hawkingnetwork/react-native-tab-view`
- `@mergulhao/wa-automate`

@@ -310,27 +307,26 @@ - `cli-live-tutorial`

- `npm_qwerty`
- `ssh-host-manager`
- `soajs.repositories`
- `react-native-arunjeyam1987`
- `vrt-cli`
- `vue-cli-plugin-ice-builder`
- `react-native-arunjeyam1987`
- `soajs.repositories`
- `ssh-host-manager`
- `native-zip`
- `graphmilker`
- `native-zip`
- `react-native-flyy`
- `react-native-bubble-chart`
- `verify-aws-sns-signature`
- `@dataparty/api`
- `react-native-flyy`
- `@react-18-pdf/root`
- `@apardellass/react-native-audio-stream`
- `@geeky-apo/react-native-advanced-clipboard`
- `@hsui/plugin-wss`
- `blitzzz`
- `candlelabssdk`
- `@roshub/api`
- `@saad27/react-native-bottom-tab-tour`
- `@roshub/api`
- `candlelabssdk`
- `blitzzz`
- `generator-bootstrap-boilerplate-template`
- `react-native-dsphoto-module`
- `react-native-responsive-size`
- `react-native-sayhello-module`
- `npm_one_12_34_1_`
- `npm_one_2_2`
- `payutesting`
- `react-native-responsive-size`
- `vue-cli-plugin-ut-builder`

@@ -346,26 +342,26 @@ - `xbuilder-forms`

- `react-feedback-sdk`
- `@oiti/documentoscopy-react-native`
- `@snyk/sweater-comb`
- `@angga30prabu/wa-modified`
- `@hstech/utils`
- `birken-react-native-community-image-editor`
- `get-tarball-cli`
- `luojia-cli-dev`
- `reac-native-arun-ramya-test`
- `react-native-plugpag-wrapper`
- `react-native-pulsator-native`
- `react-native-arun-ramya-test`
- `react-native-arunramya151`
- `react-native-plugpag-wrapper`
- `react-native-pulsator-native`
- `react-native-transtracker-library`
- `workpad`
- `@angga30prabu/wa-modified`
- `@hstech/utils`
- `get-tarball-cli`
- `luojia-cli-dev`
- `birken-react-native-community-image-editor`
- `delta-screen`
- `microbe.js`
- `@lakutata-module/service`
- `ndla-source-map-resolver`
- `@screeb/react-native`
- `@jfilipe-sparta/react-native-module_2`
- `@jimengio/mocked-proxy`
- `cogoportutils`
- `@lakutata-module/service`
- `@buganto/client`
- `@mockswitch/cli`
- `angularvezba`
- `api-reach-react-native-fix`
- `angularvezba`
- `astra-ufo-sdk`
- `react-native-syan-photo-picker`

@@ -379,10 +375,9 @@ - `@wecraftapps/react-native-use-keyboard`

- `react-native-test-module-hhh`
- `react-native-jsi-device-info`
- `react-native-badge-control`
- `wander-cli`
- `react-native-badge-control`
- `react-native-jsi-device-info`
- `normalize-ssh-url`
- `heroku-wp-environment-sync`
- `hubot-will-it-connect`
- `normalize-ssh-url`
- `ba-js-cookie-banner`
- `@ndla/source-map-resolver`
- `ts-scraper`

@@ -392,2 +387,4 @@ - `electron-info`

- `native-date-picker-module`
- `@ndla/source-map-resolver`
- `@jimengio/mocked-proxy`

@@ -394,0 +391,0 @@

@@ -1,20 +0,5 @@

"use strict";
// Dependencies
import parsePath from "parse-path";
import normalizeUrl from "normalize-url";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; // Dependencies
var _parsePath = require("parse-path");
var _parsePath2 = _interopRequireDefault(_parsePath);
var _normalizeUrl = require("normalize-url");
var _normalizeUrl2 = _interopRequireDefault(_normalizeUrl);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**

@@ -50,47 +35,46 @@ * parseUrl

*/
var parseUrl = function parseUrl(url) {
var normalize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
const parseUrl = (url, normalize = false) => {
// Constants
var GIT_RE = /(^(git@|http(s)?:\/\/)([\w\.\-@]+)(\/|:))(([\~,\.\w,\-,\_,\/]+)(.git){0,1}((\/){0,1}))/;
const GIT_RE = /^(?:([a-z_][a-z0-9_-]{0,31})@|https?:\/\/)([\w\.\-@]+)[\/:]([\~,\.\w,\-,\_,\/]+?(?:\.git|\/)?)$/
var throwErr = function throwErr(msg) {
var err = new Error(msg);
err.subject_url = url;
throw err;
};
const throwErr = msg => {
const err = new Error(msg)
err.subject_url = url
throw err
}
if (typeof url !== "string" || !url.trim()) {
throwErr("Invalid url.");
throwErr("Invalid url.")
}
if (url.length > parseUrl.MAX_INPUT_LENGTH) {
throwErr("Input exceeds maximum length. If needed, change the value of parseUrl.MAX_INPUT_LENGTH.");
throwErr("Input exceeds maximum length. If needed, change the value of parseUrl.MAX_INPUT_LENGTH.")
}
if (normalize) {
if ((typeof normalize === "undefined" ? "undefined" : _typeof(normalize)) !== "object") {
if (typeof normalize !== "object") {
normalize = {
stripHash: false
};
}
}
url = (0, _normalizeUrl2.default)(url, normalize);
url = normalizeUrl(url, normalize)
}
var parsed = (0, _parsePath2.default)(url);
const parsed = parsePath(url)
// Potential git-ssh urls
if (parsed.parse_failed) {
var matched = parsed.href.match(GIT_RE);
const matched = parsed.href.match(GIT_RE)
if (matched) {
parsed.protocols = ["ssh"];
parsed.protocol = "ssh";
parsed.resource = matched[4];
parsed.host = matched[4];
parsed.user = "git";
parsed.pathname = "/" + matched[6];
parsed.parse_failed = false;
parsed.protocols = ["ssh"]
parsed.protocol = "ssh"
parsed.resource = matched[2]
parsed.host = matched[2]
parsed.user = matched[1]
parsed.pathname = `/${matched[3]}`
parsed.parse_failed = false
} else {
throwErr("URL parsing failed.");
throwErr("URL parsing failed.")
}

@@ -100,6 +84,6 @@ }

return parsed;
};
}
parseUrl.MAX_INPUT_LENGTH = 2048;
parseUrl.MAX_INPUT_LENGTH = 2048
exports.default = parseUrl;
export default parseUrl;

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc