Socket
Socket
Sign inDemoInstall

ufo

Package Overview
Dependencies
Maintainers
1
Versions
57
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ufo - npm Package Compare versions

Comparing version 1.3.2 to 1.4.0

414

dist/index.d.ts
type QueryValue = string | number | undefined | null | boolean | Array<QueryValue> | Record<string, any>;
type QueryObject = Record<string, QueryValue | QueryValue[]>;
type ParsedQuery = Record<string, string | string[]>;
/**
* Parses and decodes a query string into an object.
*
* input can be a query string with or without the leading `?`
*
* @note
* The `__proto__` and `constructor` keys are ignored to prevent prototype pollution.
*
* @group qeury
*/
declare function parseQuery<T extends ParsedQuery = ParsedQuery>(parametersString?: string): T;
/**
* Encodes a pair of key and value into a url query string value.
*
* If the value is an array, it will be encoded as multiple key-value pairs with the same key.
*
* @group qeury
*/
declare function encodeQueryItem(key: string, value: QueryValue | QueryValue[]): string;
/**
* Stringfies and encodes a query object into a query string.
*
* @group qeury
*/
declare function stringifyQuery(query: QueryObject): string;

@@ -12,3 +34,4 @@

*
* @internal
* @group encoding
*
* @param text - string to encode

@@ -21,2 +44,4 @@ * @returns encoded string

*
* @group encoding
*
* @param text - string to encode

@@ -30,2 +55,4 @@ * @returns encoded string

*
* @group encoding
*
* @param input - string to encode

@@ -36,4 +63,7 @@ * @returns encoded string

/**
* Like `encodeQueryValue` but also encodes the `=` character.
* Encode characters that need to be encoded query values on the query
* section of the URL and also encodes the `=` character.
*
* @group encoding
*
* @param text - string to encode

@@ -45,2 +75,4 @@ */

*
* @group encoding
*
* @param text - string to encode

@@ -52,5 +84,7 @@ * @returns encoded string

* Encode characters that need to be encoded on the path section of the URL as a
* param. This function encodes everything {@link encodePath} does plus the
* param. This function encodes everything `encodePath` does plus the
* slash (`/`) character.
*
* @group encoding
*
* @param text - string to encode

@@ -64,2 +98,4 @@ * @returns encoded string

*
* @group encoding
*
* @param text - string to decode

@@ -72,2 +108,4 @@ * @returns decoded string

*
* @group encoding
*
* @param text - string to decode

@@ -78,4 +116,6 @@ * @returns decoded string

/**
* Decode query key (consistent with encodeQueryKey for plus encoding).
* Created different method for decoding key to avoid future changes on value encode/decode.
* Decodes query key (consistent with `encodeQueryKey` for plus encoding).
*
* @group encoding
*
* @param text - string to decode

@@ -88,2 +128,4 @@ * @returns decoded string

*
* @group encoding
*
* @param text - string to decode

@@ -93,4 +135,10 @@ * @returns decoded string

declare function decodeQueryValue(text: string): string;
/**
* Encodes hostname with punycode encoding.
*
* @group encoding
*/
declare function encodeHost(name?: string): string;
declare const protocolRelative: unique symbol;
interface ParsedURL {

@@ -104,2 +152,3 @@ protocol?: string;

search: string;
[protocolRelative]?: boolean;
}

@@ -115,4 +164,19 @@ interface ParsedAuth {

/**
* It takes a URL string and returns an object with the URL's protocol, auth, host, pathname, search,
* and hash
* Takes a URL string and returns an object with the URL's `protocol`, `auth`, `host`, `pathname`, `search`, and `hash`.
*
* @example
*
* ```js
* parseURL("http://foo.com/foo?test=123#token");
* // { protocol: 'http:', auth: '', host: 'foo.com', pathname: '/foo', search: '?test=123', hash: '#token' }
*
* parseURL("foo.com/foo?test=123#token");
* // { pathname: 'foo.com/foo', search: '?test=123', hash: '#token' }
*
* parseURL("foo.com/foo?test=123#token", "https://");
* // { protocol: 'https:', auth: '', host: 'foo.com', pathname: '/foo', search: '?test=123', hash: '#token' }
* ```
*
* @group parsing
*
* @param [input] - The URL to parse.

@@ -124,3 +188,6 @@ * @param [defaultProto] - The default protocol to use if the input doesn't have one.

/**
* It splits the input string into three parts, and returns an object with those three parts
* Splits the input string into three parts, and returns an object with those three parts.
*
* @group parsing
*
* @param [input] - The URL to parse.

@@ -131,4 +198,7 @@ * @returns An object with three properties: `pathname`, `search`, and `hash`.

/**
* It takes a string of the form `username:password` and returns an object with the username and
* password decoded
* Takes a string of the form `username:password` and returns an object with the username and
* password decoded.
*
* @group parsing
*
* @param [input] - The URL to parse.

@@ -139,3 +209,6 @@ * @returns An object with two properties: username and password.

/**
* It takes a string, and returns an object with two properties: `hostname` and `port`
* Takes a string, and returns an object with two properties: `hostname` and `port`.
*
* @group parsing
*
* @param [input] - The URL to parse.

@@ -147,3 +220,15 @@ * @returns A function that takes a string and returns an object with two properties: `hostname` and

/**
* It takes a `ParsedURL` object and returns the stringified URL
* Takes a `ParsedURL` object and returns the stringified URL.
*
* @group parsing
*
* @example
*
* ```js
* const obj = parseURL("http://foo.com/foo?test=123#token");
* obj.host = "bar.com";
*
* stringifyParsedURL(obj); // "http://bar.com/foo?test=123#token"
* ```
*
* @param [parsed] - The parsed URL

@@ -153,2 +238,19 @@ * @returns A stringified URL.

declare function stringifyParsedURL(parsed: Partial<ParsedURL>): string;
/**
* Parses a url and returns last segment in path as filename.
*
* If `{ strict: true }` is passed as the second argument, it will only return the last segment only if ending with an extension.
*
* @group parsing
*
* @example
*
* ```js
* // Result: filename.ext
* parseFilename("http://example.com/path/to/filename.ext");
*
* // Result: undefined
* parseFilename("/path/to/.hidden-file", { strict: true });
* ```
*/
declare function parseFilename(input: string, { strict }: {

@@ -158,2 +260,5 @@ strict: any;

/**
* @deprecated use native URL with `new URL(input)` or `ufo.parseURL(input)`
*/
declare class $URL implements URL {

@@ -183,3 +288,17 @@ protocol: string;

}
/**
* @deprecated use native URL with `new URL(input)` or `ufo.parseURL(input)`
*/
declare function createURL(input: string): $URL;
/**
* Check if a path starts with `./` or `../`.
*
* @example
* ```js
* isRelative("./foo"); // true
* ```
*
* @group utils
*/
declare function isRelative(inputString: string): boolean;

@@ -190,30 +309,240 @@ interface HasProtocolOptions {

}
/**
* Checks if the input has a protocol.
*
* You can use `{ acceptRelative: true }` to accept relative URLs as valid protocol.
*
* @group utils
*/
declare function hasProtocol(inputString: string, opts?: HasProtocolOptions): boolean;
/** @deprecated Same as { hasProtocol(inputString, { acceptRelative: true }) */
declare function hasProtocol(inputString: string, acceptRelative: boolean): boolean;
/**
* @deprecated
* Same as { hasProtocol(inputString, { acceptRelative: true })
* Checks if the input protocol is any of the dangerous `blob:`, `data:`, `javascript`: or `vbscript:` protocols.
*
* @group utils
*/
declare function hasProtocol(inputString: string, acceptRelative: boolean): boolean;
declare function isScriptProtocol(protocol?: string): boolean;
/**
* Checks if the input has a trailing slash.
*
* @group utils
*/
declare function hasTrailingSlash(input?: string, respectQueryAndFragment?: boolean): boolean;
/**
* Removes trailing slash from the URL or pathname.
*
* If second argument is is true, it will only remove the trailing slash if it's not part of the query or fragment with cost of more expensive operations.
*
* @example
*
* ```js
* withoutTrailingSlash("/foo/"); // "/foo"
*
* withoutTrailingSlash("/path/?query=true", true); // "/path?query=true"
* ```
*
* @group utils
*/
declare function withoutTrailingSlash(input?: string, respectQueryAndFragment?: boolean): string;
/**
* Ensures url ends with a trailing slash.
*
* If seccond argument is `true`, it will only add the trailing slash if it's not part of the query or fragment with cost of more expensive operation.
*
* @example
*
* ```js
* withTrailingSlash("/foo"); // "/foo/"
*
* withTrailingSlash("/path?query=true", true); // "/path/?query=true"
* ```
*
* @group utils
*/
declare function withTrailingSlash(input?: string, respectQueryAndFragment?: boolean): string;
/**
* Checks if the input has a leading slash. (e.g. `/foo`)
*
* @group utils
*/
declare function hasLeadingSlash(input?: string): boolean;
/**
* Removes leading slash from the URL or pathname.
*
* @group utils
*/
declare function withoutLeadingSlash(input?: string): string;
/**
* Ensures the URL or pathname has a leading slash.
*
* @group utils
*/
declare function withLeadingSlash(input?: string): string;
/**
* Removes double slashes from the URL.
*
* @example
*
* ```js
* cleanDoubleSlashes("//foo//bar//"); // "/foo/bar/"
*
* cleanDoubleSlashes("http://example.com/analyze//http://localhost:3000//");
* // Returns "http://example.com/analyze/http://localhost:3000/"
* ```
*
* @group utils
*/
declare function cleanDoubleSlashes(input?: string): string;
/**
* Ensures the URL or pathname has a trailing slash.
*
* If input aleady start with base, it will not be added again.
*
* @group utils
*/
declare function withBase(input: string, base: string): string;
/**
* Removes the base from the URL or pathname.
*
* If input does not start with base, it will not be removed.
*
* @group utils
*/
declare function withoutBase(input: string, base: string): string;
/**
* Add/Replace the query section of the URL.
*
* @example
*
* ```js
* withQuery("/foo?page=a", { token: "secret" }); // "/foo?page=a&token=secret"
* ```
*
* @group utils
*/
declare function withQuery(input: string, query: QueryObject): string;
/**
* Parses and decods the query object of an input URL into an object.
*
* @example
*
* ```js
* getQuery("http://foo.com/foo?test=123&unicode=%E5%A5%BD");
* // { test: "123", unicode: "好" }
* ```
* @group utils
*/
declare function getQuery<T extends ParsedQuery = ParsedQuery>(input: string): T;
/**
* Checks if the input url is empty or `/`.
*
* @group utils
*/
declare function isEmptyURL(url: string): boolean;
/**
* Checks if the input url is not empty nor `/`.
*
* @group utils
*/
declare function isNonEmptyURL(url: string): boolean;
/**
* Joins multiple URL segments into a single URL.
*
* @example
*
* ```js
* joinURL("a", "/b", "/c"); // "a/b/c"
* ```
*
* @group utils
*/
declare function joinURL(base: string, ...input: string[]): string;
/**
* Adds or replaces url protocol to `http://`.
*
* @example
*
* ```js
* withHttp("https://example.com"); // http://example.com
* ```
*
* @group utils
*/
declare function withHttp(input: string): string;
/**
* Adds or replaces url protocol to `https://`.
*
* @example
*
* ```js
* withHttps("http://example.com"); // https://example.com
* ```
*
* @group utils
*/
declare function withHttps(input: string): string;
/**
* Removes the protocol from the input.
*
* @example
* ```js
* withoutProtocol("http://example.com"); // "example.com"
* ```
*/
declare function withoutProtocol(input: string): string;
/**
* Adds or Replaces protocol of the input URL.
*
* @example
* ```js
* withProtocol("http://example.com", "ftp://"); // "ftp://example.com"
* ```
*
* @group utils
*/
declare function withProtocol(input: string, protocol: string): string;
declare function createURL(input: string): $URL;
/**
* Normlizes inputed url:
*
* - Ensures url is properly encoded
* - Ensures pathname starts with slash
* - Preserves protocol/host if provided
*
* @example
*
* ```js
* normalizeURL("test?query=123 123#hash, test");
* // Returns "test?query=123%20123#hash,%20test"
*
* normalizeURL("http://localhost:3000");
* // Returns "http://localhost:3000"
* ```
*
* @group utils
*/
declare function normalizeURL(input: string): string;
declare function resolveURL(base: string, ...input: string[]): string;
/**
* Resolves multiple URL segments into a single URL.
*
* @example
*
* ```js
* resolveURL("http://foo.com/foo?test=123#token", "bar", "baz");
* // Returns "http://foo.com/foo/bar/baz?test=123#token"
* ```
*
* @group utils
*/
declare function resolveURL(base?: string, ...inputs: string[]): string;
/**
* Check two paths are equal or not. Trailing slash and encoding are normalized before comparison.
*
* @example
* ```js
* isSamePath("/foo", "/foo/"); // true
* ```
*
* @group utils
*/
declare function isSamePath(p1: string, p2: string): boolean;

@@ -225,4 +554,53 @@ interface CompareURLOptions {

}
/**
* Checks if two paths are equal regardless of encoding, trailing slash, and leading slash differences.
*
* You can make slash check strict by setting `{ trailingSlash: true, leadingSlash: true }` as options.
*
* You can make encoding check strict by setting `{ encoding: true }` as options.
*
* @example
*
* ```js
* isEqual("/foo", "foo"); // true
* isEqual("foo/", "foo"); // true
* isEqual("/foo bar", "/foo%20bar"); // true
*
* // Strict compare
* isEqual("/foo", "foo", { leadingSlash: true }); // false
* isEqual("foo/", "foo", { trailingSlash: true }); // false
* isEqual("/foo bar", "/foo%20bar", { encoding: true }); // false
* ```
*
* @group utils
*/
declare function isEqual(a: string, b: string, options?: CompareURLOptions): boolean;
/**
* Add/Replace the fragment section of the URL.
*
* @example
*
* ```js
* withFragment("/foo", "bar"); // "/foo#bar"
* withFragment("/foo#bar", "baz"); // "/foo#baz"
* withFragment("/foo#bar", ""); // "/foo"
* ```
*
* @group utils
*/
declare function withFragment(input: string, hash: string): string;
/**
* Removes the fragment section from the URL.
*
* @example
*
* ```js
* withoutFragment("http://example.com/foo?q=123#bar")
* // Returns "http://example.com/foo?q=123"
* ```
*
* @group utils
*/
declare function withoutFragment(input: string): string;
export { $URL, type HasProtocolOptions, type ParsedAuth, type ParsedHost, type ParsedQuery, type ParsedURL, type QueryObject, type QueryValue, cleanDoubleSlashes, createURL, decode, decodePath, decodeQueryKey, decodeQueryValue, encode, encodeHash, encodeHost, encodeParam, encodePath, encodeQueryItem, encodeQueryKey, encodeQueryValue, getQuery, hasLeadingSlash, hasProtocol, hasTrailingSlash, isEmptyURL, isEqual, isNonEmptyURL, isRelative, isSamePath, isScriptProtocol, joinURL, normalizeURL, parseAuth, parseFilename, parseHost, parsePath, parseQuery, parseURL, resolveURL, stringifyParsedURL, stringifyQuery, withBase, withHttp, withHttps, withLeadingSlash, withProtocol, withQuery, withTrailingSlash, withoutBase, withoutLeadingSlash, withoutProtocol, withoutTrailingSlash };
export { $URL, type HasProtocolOptions, type ParsedAuth, type ParsedHost, type ParsedQuery, type ParsedURL, type QueryObject, type QueryValue, cleanDoubleSlashes, createURL, decode, decodePath, decodeQueryKey, decodeQueryValue, encode, encodeHash, encodeHost, encodeParam, encodePath, encodeQueryItem, encodeQueryKey, encodeQueryValue, getQuery, hasLeadingSlash, hasProtocol, hasTrailingSlash, isEmptyURL, isEqual, isNonEmptyURL, isRelative, isSamePath, isScriptProtocol, joinURL, normalizeURL, parseAuth, parseFilename, parseHost, parsePath, parseQuery, parseURL, resolveURL, stringifyParsedURL, stringifyQuery, withBase, withFragment, withHttp, withHttps, withLeadingSlash, withProtocol, withQuery, withTrailingSlash, withoutBase, withoutFragment, withoutLeadingSlash, withoutProtocol, withoutTrailingSlash };

24

package.json
{
"name": "ufo",
"version": "1.3.2",
"version": "1.4.0",
"description": "URL utils for humans",

@@ -23,3 +23,4 @@ "repository": "unjs/ufo",

"scripts": {
"build": "unbuild",
"build": "automd && unbuild",
"automd": "automd",
"dev": "vitest",

@@ -30,16 +31,19 @@ "lint": "eslint --ext .ts . && prettier -c src test",

"release": "pnpm test && changelogen --release && npm publish && git push --follow-tags",
"test": "pnpm lint && vitest --run typecheck && vitest run"
"test": "pnpm lint && vitest run --typecheck"
},
"devDependencies": {
"@types/node": "^20.9.0",
"@vitest/coverage-v8": "^0.34.6",
"@types/node": "^20.11.16",
"@vitest/coverage-v8": "^1.2.2",
"automd": "^0.1.1",
"changelogen": "^0.5.5",
"eslint": "^8.53.0",
"eslint": "^8.56.0",
"eslint-config-unjs": "^0.2.1",
"prettier": "^3.1.0",
"typescript": "^5.2.2",
"jiti": "^1.21.0",
"prettier": "^3.2.5",
"typescript": "^5.3.3",
"unbuild": "^2.0.0",
"vitest": "^0.34.6"
"untyped": "^1.4.2",
"vitest": "^1.2.2"
},
"packageManager": "pnpm@8.10.5"
"packageManager": "pnpm@8.15.1"
}

@@ -1,2 +0,2 @@

# 👽 ufo
# ufo

@@ -7,4 +7,2 @@ [![npm version][npm-version-src]][npm-version-href]

[![Codecov][codecov-src]][codecov-href]
[![License][license-src]][license-href]
[![JSDocs][jsdocs-src]][jsdocs-href]

@@ -17,234 +15,409 @@ URL utils for humans.

```bash
npm i ufo
Install package:
```sh
# npm
npm install ufo
# yarn
yarn add ufo
# pnpm
pnpm install ufo
# bun
bun install ufo
```
Import:
Import utils:
```js
// ESM
import { normalizeURL, joinURL } from "ufo";
// CommonJS
const { normalizeURL, joinURL } = require('ufo')
const { normalizeURL, joinURL } = require("ufo");
// ESM
import { normalizeURL, joinURL } from 'ufo'
// Deno
import { parseURL } from 'https://unpkg.com/ufo/dist/index.mjs'
import { parseURL } from "https://unpkg.com/ufo/dist/index.mjs";
```
**Notice:** You may need to transpile package and add URL polyfill for legacy environments
# Utils
## Usage
<!-- AUTOMD_START generator="jsdocs" headingLevel="2" -->
### `normalizeURL`
## Encoding
- Ensures URL is properly encoded
- Ensures pathname starts with slash
- Preserves protocol/host if provided
### `decode(text)`
```ts
normalizeURL('test?query=123 123#hash, test')
// test?query=123%20123#hash,%20test
Decode text using `decodeURIComponent`. Returns the original text if it fails.
normalizeURL('http://localhost:3000')
// http://localhost:3000/
```
### `decodePath(text)`
### `joinURL`
Decode path section of URL (consistent with encodePath for slash encoding).
```ts
joinURL('a', '/b', '/c')
// a/b/c
```
### `decodeQueryKey(text)`
### `resolveURL`
Decodes query key (consistent with `encodeQueryKey` for plus encoding).
```ts
resolveURL('http://foo.com/foo?test=123#token', 'bar', 'baz')
// http://foo.com/foo/bar/baz?test=123#token
### `decodeQueryValue(text)`
Decode query value (consistent with encodeQueryValue for plus encoding).
### `encode(text)`
Encode characters that need to be encoded on the path, search and hash sections of the URL.
### `encodeHash(text)`
Encode characters that need to be encoded on the hash section of the URL.
### `encodeHost(name)`
Encodes hostname with punycode encoding.
### `encodeParam(text)`
Encode characters that need to be encoded on the path section of the URL as a param. This function encodes everything `encodePath` does plus the slash (`/`) character.
### `encodePath(text)`
Encode characters that need to be encoded on the path section of the URL.
### `encodeQueryKey(text)`
Encode characters that need to be encoded query values on the query section of the URL and also encodes the `=` character.
### `encodeQueryValue(input)`
Encode characters that need to be encoded query values on the query section of the URL.
## Parsing
### `parseAuth(input)`
Takes a string of the form `username:password` and returns an object with the username and password decoded.
### `parseFilename(input)`
Parses a url and returns last segment in path as filename.
If `{ strict: true }` is passed as the second argument, it will only return the last segment only if ending with an extension.
**Example:**
```js
// Result: filename.ext
parseFilename("http://example.com/path/to/filename.ext");
// Result: undefined
parseFilename("/path/to/.hidden-file", { strict: true });
```
### `parseURL`
### `parseHost(input)`
```ts
parseURL('http://foo.com/foo?test=123#token')
Takes a string, and returns an object with two properties: `hostname` and `port`.
### `parsePath(input)`
Splits the input string into three parts, and returns an object with those three parts.
### `parseURL(input, defaultProto)`
Takes a URL string and returns an object with the URL's `protocol`, `auth`, `host`, `pathname`, `search`, and `hash`.
**Example:**
```js
parseURL("http://foo.com/foo?test=123#token");
// { protocol: 'http:', auth: '', host: 'foo.com', pathname: '/foo', search: '?test=123', hash: '#token' }
parseURL('foo.com/foo?test=123#token')
parseURL("foo.com/foo?test=123#token");
// { pathname: 'foo.com/foo', search: '?test=123', hash: '#token' }
parseURL('foo.com/foo?test=123#token', 'https://')
parseURL("foo.com/foo?test=123#token", "https://");
// { protocol: 'https:', auth: '', host: 'foo.com', pathname: '/foo', search: '?test=123', hash: '#token' }
```
### `stringifyParsedURL`
### `stringifyParsedURL(parsed)`
```ts
const obj = parseURL('http://foo.com/foo?test=123#token')
obj.host = 'bar.com'
Takes a `ParsedURL` object and returns the stringified URL.
stringifyParsedURL(obj)
// http://bar.com/foo?test=123#token
**Example:**
```js
const obj = parseURL("http://foo.com/foo?test=123#token");
obj.host = "bar.com";
stringifyParsedURL(obj); // "http://bar.com/foo?test=123#token"
```
### `withQuery`
## Qeury
```ts
withQuery('/foo?page=a', { token: 'secret' })
// /foo?page=a&token=secret
### `encodeQueryItem(key, value)`
Encodes a pair of key and value into a url query string value.
If the value is an array, it will be encoded as multiple key-value pairs with the same key.
### `parseQuery(parametersString)`
Parses and decodes a query string into an object.
input can be a query string with or without the leading `?`
### `stringifyQuery(query)`
Stringfies and encodes a query object into a query string.
## Utils
### `cleanDoubleSlashes(input)`
Removes double slashes from the URL.
**Example:**
```js
cleanDoubleSlashes("//foo//bar//"); // "/foo/bar/"
cleanDoubleSlashes("http://example.com/analyze//http://localhost:3000//");
// Returns "http://example.com/analyze/http://localhost:3000/"
```
### `getQuery`
### `getQuery(input)`
```ts
getQuery('http://foo.com/foo?test=123&unicode=%E5%A5%BD')
// { test: '123', unicode: '好' }
Parses and decods the query object of an input URL into an object.
**Example:**
```js
getQuery("http://foo.com/foo?test=123&unicode=%E5%A5%BD");
// { test: "123", unicode: "好" }
```
### `parseFilename`
### `hasLeadingSlash(input)`
```ts
// Result: filename.ext
parseFilename('http://example.com/path/to/filename.ext')
Checks if the input has a leading slash. (e.g. `/foo`)
// Result: undefined
parseFilename('/path/to/.hidden-file', { strict: true })
### `hasTrailingSlash(input, respectQueryAndFragment)`
Checks if the input has a trailing slash.
### `isEmptyURL(url)`
Checks if the input url is empty or `/`.
### `isEqual(a, b, options)`
Checks if two paths are equal regardless of encoding, trailing slash, and leading slash differences.
You can make slash check strict by setting `{ trailingSlash: true, leadingSlash: true }` as options.
You can make encoding check strict by setting `{ encoding: true }` as options.
**Example:**
```js
isEqual("/foo", "foo"); // true
isEqual("foo/", "foo"); // true
isEqual("/foo bar", "/foo%20bar"); // true
// Strict compare
isEqual("/foo", "foo", { leadingSlash: true }); // false
isEqual("foo/", "foo", { trailingSlash: true }); // false
isEqual("/foo bar", "/foo%20bar", { encoding: true }); // false
```
### `$URL`
### `isNonEmptyURL(url)`
Implementing URL interface with improvements:
Checks if the input url is not empty nor `/`.
- Supporting schemeless and hostless URLs
- Supporting relative URLs
- Preserving trailing-slash status
- Decoded and mutable class properties (`protocol`, `host`, `auth`, `pathname`, `query`, `hash`)
- Consistent URL parser independent of environment
- Consistent encoding independent of environment
- Punycode support for host encoding
### `isRelative(inputString)`
```ts
new $URL('http://localhost:3000/hello?world=true')
// { protocol: 'http:', host: 'localhost:3000', auth: '', pathname: '/hello', query: { world: 'true' }, hash: '' }
Check if a path starts with `./` or `../`.
**Example:**
```js
isRelative("./foo"); // true
```
### `withTrailingSlash`
### `isSamePath(p1, p2)`
Ensures url ends with a trailing slash.
Check two paths are equal or not. Trailing slash and encoding are normalized before comparison.
```ts
withTrailingSlash('/foo')
// /foo/
**Example:**
```js
isSamePath("/foo", "/foo/"); // true
```
Set the second option to `true` to support query parameters:
### `isScriptProtocol(protocol)`
```ts
withTrailingSlash('/path?query=true', true)
// /path/?query=true
Checks if the input protocol is any of the dangerous `blob:`, `data:`, `javascript`: or `vbscript:` protocols.
### `joinURL(base)`
Joins multiple URL segments into a single URL.
**Example:**
```js
joinURL("a", "/b", "/c"); // "a/b/c"
```
### `withoutTrailingSlash`
### `normalizeURL(input)`
Ensures url does not ends with a trailing slash.
Normlizes inputed url:
```ts
withoutTrailingSlash('/foo/')
// /foo
- Ensures url is properly encoded - Ensures pathname starts with slash - Preserves protocol/host if provided
**Example:**
```js
normalizeURL("test?query=123 123#hash, test");
// Returns "test?query=123%20123#hash,%20test"
normalizeURL("http://localhost:3000");
// Returns "http://localhost:3000"
```
Set the second option to `true` to support query parameters:
### `resolveURL(base)`
```ts
withoutTrailingSlash('/path/?query=true', true)
// /path?query=true
Resolves multiple URL segments into a single URL.
**Example:**
```js
resolveURL("http://foo.com/foo?test=123#token", "bar", "baz");
// Returns "http://foo.com/foo/bar/baz?test=123#token"
```
### `cleanDoubleSlashes`
### `withBase(input, base)`
Ensures url does not have double slash (except for protocol).
Ensures the URL or pathname has a trailing slash.
```ts
cleanDoubleSlashes('//foo//bar//')
// /foo/bar/
If input aleady start with base, it will not be added again.
cleanDoubleSlashes('http://example.com/analyze//http://localhost:3000//')
// http://example.com/analyze/http://localhost:3000/
### `withFragment(input, hash)`
Add/Replace the fragment section of the URL.
**Example:**
```js
withFragment("/foo", "bar"); // "/foo#bar"
withFragment("/foo#bar", "baz"); // "/foo#baz"
withFragment("/foo#bar", ""); // "/foo"
```
### `isSamePath`
### `withHttp(input)`
Check two paths are equal or not. Trailing slash and encoding are normalized before comparison.
Adds or replaces url protocol to `http://`.
```ts
isSamePath('/foo', '/foo/')
// true
**Example:**
```js
withHttp("https://example.com"); // http://example.com
```
### `isRelative`
### `withHttps(input)`
Check if a path starts with `./` or `../`.
Adds or replaces url protocol to `https://`.
```ts
isRelative('./foo')
// true
**Example:**
```js
withHttps("http://example.com"); // https://example.com
```
### `withHttp`
### `withLeadingSlash(input)`
Ensures url protocol is `http`
Ensures the URL or pathname has a leading slash.
```ts
withHttp('https://example.com')
// http://example.com
### `withoutBase(input, base)`
Removes the base from the URL or pathname.
If input does not start with base, it will not be removed.
### `withoutFragment(input)`
Removes the fragment section from the URL.
**Example:**
```js
withoutFragment("http://example.com/foo?q=123#bar")
// Returns "http://example.com/foo?q=123"
```
### `withHttps`
### `withoutLeadingSlash(input)`
Ensures url protocol is `https`
Removes leading slash from the URL or pathname.
```ts
withHttps('http://example.com')
// https://example.com
### `withoutTrailingSlash(input, respectQueryAndFragment)`
Removes trailing slash from the URL or pathname.
If second argument is is true, it will only remove the trailing slash if it's not part of the query or fragment with cost of more expensive operations.
**Example:**
```js
withoutTrailingSlash("/foo/"); // "/foo"
withoutTrailingSlash("/path/?query=true", true); // "/path?query=true"
```
### `withProtocol`
### `withProtocol(input, protocol)`
Changes url protocol passed as second argument
Adds or Replaces protocol of the input URL.
```ts
withProtocol('http://example.com', 'ftp://')
// ftp://example.com
**Example:**
```js
withProtocol("http://example.com", "ftp://"); // "ftp://example.com"
```
### `withoutProtocol`
### `withQuery(input, query)`
Removes url protocol
Add/Replace the query section of the URL.
```ts
withoutProtocol('http://example.com')
// example.com
**Example:**
```js
withQuery("/foo?page=a", { token: "secret" }); // "/foo?page=a&token=secret"
```
### `isEqual`
### `withTrailingSlash(input, respectQueryAndFragment)`
Compare two URLs regardless of their slash condition or encoding:
Ensures url ends with a trailing slash.
```ts
isEqual('/foo', 'foo')
// true
isEqual('foo/', 'foo')
// true
isEqual('/foo bar', '/foo%20bar')
// true
If seccond argument is `true`, it will only add the trailing slash if it's not part of the query or fragment with cost of more expensive operation.
// Strict compare
isEqual('/foo', 'foo', { leadingSlash: true })
// false
isEqual('foo/', 'foo', { trailingSlash: true })
// false
isEqual('/foo bar', '/foo%20bar', { encoding: true })
// false
**Example:**
```js
withTrailingSlash("/foo"); // "/foo/"
withTrailingSlash("/path?query=true", true); // "/path/?query=true"
```
### `hasProtocol(inputString, opts)`
### `withoutProtocol(input)`
Removes the protocol from the input.
**Example:**
```js
withoutProtocol("http://example.com"); // "example.com"
```
<!-- AUTOMD_END -->
## License

@@ -257,2 +430,3 @@

<!-- Badges -->
[npm-version-src]: https://img.shields.io/npm/v/ufo?style=flat&colorA=18181B&colorB=F0DB4F

@@ -266,5 +440,1 @@ [npm-version-href]: https://npmjs.com/package/ufo

[bundle-href]: https://bundlephobia.com/result?p=ufo
[license-src]: https://img.shields.io/github/license/unjs/ufo.svg?style=flat&colorA=18181B&colorB=F0DB4F
[license-href]: https://github.com/unjs/ufo/blob/main/LICENSE
[jsdocs-src]: https://img.shields.io/badge/jsDocs.io-reference-18181B?style=flat&colorA=18181B&colorB=F0DB4F
[jsdocs-href]: https://www.jsdocs.io/package/ufo

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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