@cspell/url 8.9.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2017 Jason Dent
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,21 @@
1
+ # `@cspell/url`
2
+
3
+ A URL parsing and manipulation library for cspell.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install -S @cspell/url
9
+ ```
10
+
11
+ <!--- @@inject: ../../static/footer.md --->
12
+
13
+ <br/>
14
+
15
+ ---
16
+
17
+ <p align="center">Brought to you by<a href="https://streetsidesoftware.com" title="Street Side Software"><img width="16" alt="Street Side Software Logo" src="https://i.imgur.com/CyduuVY.png" /> Street Side Software</a></p>
18
+
19
+ <!--- @@inject-end: ../../static/footer.md --->
20
+
21
+ <!--- cspell:dictionaries typescript --->
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Try to determine the base name of a URL.
3
+ * @param url
4
+ * @returns the base name of a URL, including the trailing `/` if present.
5
+ */
6
+ export declare function urlBasename(url: string | URL): string;
7
+ export declare function isDataURL(url: string | URL): boolean;
8
+ //# sourceMappingURL=dataUrl.d.mts.map
@@ -0,0 +1,25 @@
1
+ import { basenameOfUrlPathname, hasProtocol, toURL } from './url.mjs';
2
+ const regMatchFilename = /filename=([^;,]*)/;
3
+ /**
4
+ * Try to determine the base name of a URL.
5
+ * @param url
6
+ * @returns the base name of a URL, including the trailing `/` if present.
7
+ */
8
+ export function urlBasename(url) {
9
+ function guessDataUrlName(header) {
10
+ const filenameMatch = header.match(regMatchFilename);
11
+ if (filenameMatch)
12
+ return filenameMatch[1];
13
+ const mime = header.split(';', 1)[0];
14
+ return mime.replaceAll(/\W/g, '.');
15
+ }
16
+ url = toURL(url);
17
+ if (url.protocol === 'data:') {
18
+ return guessDataUrlName(url.pathname.split(',', 1)[0]);
19
+ }
20
+ return basenameOfUrlPathname(url.pathname);
21
+ }
22
+ export function isDataURL(url) {
23
+ return hasProtocol(url, 'data:');
24
+ }
25
+ //# sourceMappingURL=dataUrl.mjs.map
@@ -0,0 +1,77 @@
1
+ /**
2
+ * @param url - URL or string to check if it is a file URL.
3
+ * @returns true if the URL is a file URL.
4
+ */
5
+ export declare function isFileURL(url: URL | string): boolean;
6
+ export interface PathInterface {
7
+ sep: string;
8
+ resolve(...paths: string[]): string;
9
+ }
10
+ export interface BuilderOptions {
11
+ windows?: boolean | undefined;
12
+ path?: PathInterface | undefined;
13
+ cwd?: URL | undefined;
14
+ }
15
+ export declare class FileUrlBuilder {
16
+ private windows;
17
+ private path;
18
+ private cwd;
19
+ constructor(options?: BuilderOptions);
20
+ /**
21
+ * Encode special characters in a file path to use in a URL.
22
+ * @param filepath
23
+ * @returns
24
+ */
25
+ encodePathChars(filepath: string): string;
26
+ /**
27
+ * Normalize a file path for use in a URL.
28
+ * ```js
29
+ * const url = new URL(normalizeFilePathForUrl('path\\to\\file.txt'), 'file:///Users/user/');
30
+ * // Result: file:///Users/user/path/to/file.txt
31
+ * ```
32
+ * @param filePath
33
+ * @returns a normalized file path for use as a relative path in a URL.
34
+ */
35
+ normalizeFilePathForUrl(filePath: string): string;
36
+ /**
37
+ * Try to make a file URL.
38
+ * - if filenameOrUrl is already a URL, it is returned as is.
39
+ * @param filenameOrUrl
40
+ * @param relativeTo - optional URL, if given, filenameOrUrl will be parsed as relative.
41
+ * @returns a URL
42
+ */
43
+ toFileURL(filenameOrUrl: string | URL, relativeTo?: string | URL): URL;
44
+ }
45
+ export declare function encodePathChars(filepath: string): string;
46
+ /**
47
+ * Normalize a file path for use in a URL.
48
+ * ```js
49
+ * const url = new URL(normalizeFilePathForUrl('path\\to\\file.txt'), 'file:///Users/user/');
50
+ * // Result: file:///Users/user/path/to/file.txt
51
+ * ```
52
+ * @param filePath
53
+ * @returns a normalized file path for use as a relative path in a URL.
54
+ */
55
+ export declare function normalizeFilePathForUrl(filePath: string): string;
56
+ /**
57
+ * Try to make a file URL.
58
+ * - if filenameOrUrl is already a URL, it is returned as is.
59
+ * -
60
+ * @param filenameOrUrl
61
+ * @param relativeTo - optional URL, if given, filenameOrUrl will be parsed as relative.
62
+ * @returns a URL
63
+ */
64
+ export declare function toFileURL(filenameOrUrl: string | URL, relativeTo?: string | URL): URL;
65
+ /**
66
+ * Convert a URL into a string. If it is a file URL, convert it to a path.
67
+ * @param url - URL
68
+ * @returns path or href
69
+ */
70
+ export declare function toFilePathOrHref(url: URL | string): string;
71
+ /**
72
+ * Converts a file path to a URL and adds a trailing slash.
73
+ * @param dir - url to a directory
74
+ * @returns a URL
75
+ */
76
+ export declare function toFileDirURL(dir: string | URL): URL;
77
+ //# sourceMappingURL=fileUrl.d.mts.map
@@ -0,0 +1,138 @@
1
+ import assert from 'node:assert';
2
+ import path from 'node:path';
3
+ import { fileURLToPath, pathToFileURL } from 'node:url';
4
+ import { addTrailingSlash, hasProtocol, isUrlLike } from './url.mjs';
5
+ const isWindows = process.platform === 'win32';
6
+ const isWindowsPathRegEx = /^[a-z]:[\\/]/i;
7
+ const percentRegEx = /%/g;
8
+ const backslashRegEx = /\\/g;
9
+ const newlineRegEx = /\n/g;
10
+ const carriageReturnRegEx = /\r/g;
11
+ const tabRegEx = /\t/g;
12
+ const questionRegex = /\?/g;
13
+ const hashRegex = /#/g;
14
+ /**
15
+ * @param url - URL or string to check if it is a file URL.
16
+ * @returns true if the URL is a file URL.
17
+ */
18
+ export function isFileURL(url) {
19
+ return hasProtocol(url, 'file:');
20
+ }
21
+ export class FileUrlBuilder {
22
+ windows;
23
+ path;
24
+ cwd;
25
+ constructor(options = {}) {
26
+ const sep = options.path?.sep;
27
+ this.windows = options.windows ?? (sep ? sep === '\\' : undefined) ?? isWindows;
28
+ this.path = options.path ?? this.windows ? path.win32 : path.posix;
29
+ this.cwd = options.cwd ?? pathToFileURL(this.path.resolve() + '/');
30
+ assert(this.path.sep === (this.windows ? '\\' : '/'));
31
+ }
32
+ /**
33
+ * Encode special characters in a file path to use in a URL.
34
+ * @param filepath
35
+ * @returns
36
+ */
37
+ encodePathChars(filepath) {
38
+ filepath = filepath.replaceAll(percentRegEx, '%25');
39
+ // In posix, backslash is a valid character in paths:
40
+ if (!this.windows && filepath.includes('\\'))
41
+ filepath = filepath.replaceAll(backslashRegEx, '%5C');
42
+ filepath = filepath.replaceAll(newlineRegEx, '%0A');
43
+ filepath = filepath.replaceAll(carriageReturnRegEx, '%0D');
44
+ filepath = filepath.replaceAll(tabRegEx, '%09');
45
+ return filepath;
46
+ }
47
+ /**
48
+ * Normalize a file path for use in a URL.
49
+ * ```js
50
+ * const url = new URL(normalizeFilePathForUrl('path\\to\\file.txt'), 'file:///Users/user/');
51
+ * // Result: file:///Users/user/path/to/file.txt
52
+ * ```
53
+ * @param filePath
54
+ * @returns a normalized file path for use as a relative path in a URL.
55
+ */
56
+ normalizeFilePathForUrl(filePath) {
57
+ filePath = this.encodePathChars(filePath);
58
+ filePath = filePath.replaceAll(questionRegex, '%3F');
59
+ filePath = filePath.replaceAll(hashRegex, '%23');
60
+ const pathname = filePath.replaceAll('\\', '/');
61
+ return pathname.replace(isWindowsPathRegEx, (drive) => `/${drive}`.toUpperCase());
62
+ }
63
+ /**
64
+ * Try to make a file URL.
65
+ * - if filenameOrUrl is already a URL, it is returned as is.
66
+ * @param filenameOrUrl
67
+ * @param relativeTo - optional URL, if given, filenameOrUrl will be parsed as relative.
68
+ * @returns a URL
69
+ */
70
+ toFileURL(filenameOrUrl, relativeTo) {
71
+ if (typeof filenameOrUrl !== 'string')
72
+ return filenameOrUrl;
73
+ if (isUrlLike(filenameOrUrl))
74
+ return new URL(filenameOrUrl);
75
+ relativeTo ??= this.cwd;
76
+ if (isUrlLike(relativeTo)) {
77
+ return new URL(this.normalizeFilePathForUrl(filenameOrUrl), relativeTo);
78
+ }
79
+ // Resolve removes the trailing slash, so we need to add it back.
80
+ const appendSlash = filenameOrUrl.endsWith('/')
81
+ ? '/'
82
+ : this.windows && filenameOrUrl.endsWith('\\')
83
+ ? '\\'
84
+ : '';
85
+ return pathToFileURL(this.path.resolve(relativeTo.toString(), filenameOrUrl) + appendSlash);
86
+ }
87
+ }
88
+ const fileUrlBuilder = new FileUrlBuilder();
89
+ export function encodePathChars(filepath) {
90
+ return fileUrlBuilder.encodePathChars(filepath);
91
+ }
92
+ /**
93
+ * Normalize a file path for use in a URL.
94
+ * ```js
95
+ * const url = new URL(normalizeFilePathForUrl('path\\to\\file.txt'), 'file:///Users/user/');
96
+ * // Result: file:///Users/user/path/to/file.txt
97
+ * ```
98
+ * @param filePath
99
+ * @returns a normalized file path for use as a relative path in a URL.
100
+ */
101
+ export function normalizeFilePathForUrl(filePath) {
102
+ return fileUrlBuilder.normalizeFilePathForUrl(filePath);
103
+ }
104
+ /**
105
+ * Try to make a file URL.
106
+ * - if filenameOrUrl is already a URL, it is returned as is.
107
+ * -
108
+ * @param filenameOrUrl
109
+ * @param relativeTo - optional URL, if given, filenameOrUrl will be parsed as relative.
110
+ * @returns a URL
111
+ */
112
+ export function toFileURL(filenameOrUrl, relativeTo) {
113
+ return fileUrlBuilder.toFileURL(filenameOrUrl, relativeTo);
114
+ }
115
+ /**
116
+ * Convert a URL into a string. If it is a file URL, convert it to a path.
117
+ * @param url - URL
118
+ * @returns path or href
119
+ */
120
+ export function toFilePathOrHref(url) {
121
+ return isFileURL(url) ? toFilePath(url) : url.toString();
122
+ }
123
+ function toFilePath(url) {
124
+ return windowsDriveLetterToUpper(fileURLToPath(url));
125
+ }
126
+ function windowsDriveLetterToUpper(absoluteFilePath) {
127
+ return absoluteFilePath.replace(/^([a-z]):\\/, (s) => s.toUpperCase());
128
+ }
129
+ /**
130
+ * Converts a file path to a URL and adds a trailing slash.
131
+ * @param dir - url to a directory
132
+ * @returns a URL
133
+ */
134
+ export function toFileDirURL(dir) {
135
+ const url = toFileURL(dir);
136
+ return addTrailingSlash(url);
137
+ }
138
+ //# sourceMappingURL=fileUrl.mjs.map
@@ -0,0 +1,5 @@
1
+ export { isDataURL, urlBasename } from './dataUrl.mjs';
2
+ export type { BuilderOptions, PathInterface } from './fileUrl.mjs';
3
+ export { encodePathChars, FileUrlBuilder, isFileURL, normalizeFilePathForUrl, toFileDirURL, toFilePathOrHref, toFileURL, } from './fileUrl.mjs';
4
+ export { addTrailingSlash, basenameOfUrlPathname, hasProtocol, isURL, isUrlLike, toURL, urlParent } from './url.mjs';
5
+ //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs ADDED
@@ -0,0 +1,4 @@
1
+ export { isDataURL, urlBasename } from './dataUrl.mjs';
2
+ export { encodePathChars, FileUrlBuilder, isFileURL, normalizeFilePathForUrl, toFileDirURL, toFilePathOrHref, toFileURL, } from './fileUrl.mjs';
3
+ export { addTrailingSlash, basenameOfUrlPathname, hasProtocol, isURL, isUrlLike, toURL, urlParent } from './url.mjs';
4
+ //# sourceMappingURL=index.mjs.map
package/dist/url.d.mts ADDED
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Try to make a URL.
3
+ * @param url
4
+ * @param relativeTo - optional URL, if given, url will be parsed as relative.
5
+ * @returns a URL
6
+ */
7
+ export declare function toURL(url: string | URL, relativeTo?: string | URL): URL;
8
+ /**
9
+ * Try to determine the parent directory URL of the uri.
10
+ * If it is not a hierarchical URL, then it will return the URL.
11
+ * @param url - url to extract the dirname from.
12
+ * @returns a URL
13
+ */
14
+ export declare function urlParent(url: string | URL): URL;
15
+ /**
16
+ * return the basename (last portion of the URL pathname) of a path. It does NOT remove the trailing slash.
17
+ * @param path - URL pathname to extract the basename from.
18
+ */
19
+ export declare function basenameOfUrlPathname(path: string): string;
20
+ /**
21
+ * @param filename - filename to check if it is a string containing a URL.
22
+ */
23
+ export declare function isUrlLike(filename: string): boolean;
24
+ export declare function isUrlLike(filename: URL): true;
25
+ /**
26
+ * @param filename - filename to check if it is a string containing a URL or a URL object.
27
+ */
28
+ export declare function isUrlLike(filename: string | URL): boolean;
29
+ /**
30
+ * Check if `url` is a URL instance.
31
+ * @returns
32
+ */
33
+ export declare function isURL(url: unknown): url is URL;
34
+ /**
35
+ *
36
+ * @param url - url to check
37
+ * @param protocol - protocol to check against - e.g. 'file:', 'http:', 'https:'
38
+ * @returns
39
+ */
40
+ export declare function hasProtocol(url: string | URL, protocol: string): boolean;
41
+ /**
42
+ * Attempts to add a trailing slash to the URL pathname if it does not already have one.
43
+ * Some If the pathname doesn't start with a `/`, a trailing slash is not added.
44
+ * @param url - a URL
45
+ * @returns
46
+ */
47
+ export declare function addTrailingSlash(url: URL): URL;
48
+ //# sourceMappingURL=url.d.mts.map
package/dist/url.mjs ADDED
@@ -0,0 +1,73 @@
1
+ const isURLRegEx = /^(\w[\w-]{1,63}:\/|data:|stdin:)/i;
2
+ /**
3
+ * Try to make a URL.
4
+ * @param url
5
+ * @param relativeTo - optional URL, if given, url will be parsed as relative.
6
+ * @returns a URL
7
+ */
8
+ export function toURL(url, relativeTo) {
9
+ return url instanceof URL ? url : new URL(url, relativeTo);
10
+ }
11
+ /**
12
+ * Try to determine the parent directory URL of the uri.
13
+ * If it is not a hierarchical URL, then it will return the URL.
14
+ * @param url - url to extract the dirname from.
15
+ * @returns a URL
16
+ */
17
+ export function urlParent(url) {
18
+ url = toURL(url);
19
+ if (url.protocol === 'data:') {
20
+ return url;
21
+ }
22
+ const hasTrailingSlash = url.pathname.endsWith('/');
23
+ if (!url.pathname.startsWith('/')) {
24
+ const parts = url.pathname.split('/').slice(0, hasTrailingSlash ? -2 : -1);
25
+ let pathname = parts.join('/');
26
+ pathname = (pathname && pathname + '/') || '';
27
+ return new URL(url.protocol + (url.host ? '//' + url.host : '') + pathname + url.search + url.hash);
28
+ }
29
+ return new URL(hasTrailingSlash ? '..' : '.', url);
30
+ }
31
+ /**
32
+ * return the basename (last portion of the URL pathname) of a path. It does NOT remove the trailing slash.
33
+ * @param path - URL pathname to extract the basename from.
34
+ */
35
+ export function basenameOfUrlPathname(path) {
36
+ const adj = path.endsWith('/') ? 2 : 0;
37
+ const idx = path.lastIndexOf('/', path.length - adj);
38
+ return idx >= 0 ? path.slice(idx + 1) : path;
39
+ }
40
+ export function isUrlLike(filename) {
41
+ return filename instanceof URL || isURLRegEx.test(filename);
42
+ }
43
+ /**
44
+ * Check if `url` is a URL instance.
45
+ * @returns
46
+ */
47
+ export function isURL(url) {
48
+ return url instanceof URL;
49
+ }
50
+ /**
51
+ *
52
+ * @param url - url to check
53
+ * @param protocol - protocol to check against - e.g. 'file:', 'http:', 'https:'
54
+ * @returns
55
+ */
56
+ export function hasProtocol(url, protocol) {
57
+ protocol = protocol.endsWith(':') ? protocol : protocol + ':';
58
+ return typeof url === 'string' ? url.startsWith(protocol) : url.protocol === protocol;
59
+ }
60
+ /**
61
+ * Attempts to add a trailing slash to the URL pathname if it does not already have one.
62
+ * Some If the pathname doesn't start with a `/`, a trailing slash is not added.
63
+ * @param url - a URL
64
+ * @returns
65
+ */
66
+ export function addTrailingSlash(url) {
67
+ if (url.pathname.endsWith('/'))
68
+ return url;
69
+ const urlWithSlash = new URL(url.href);
70
+ urlWithSlash.pathname += '/';
71
+ return urlWithSlash;
72
+ }
73
+ //# sourceMappingURL=url.mjs.map
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@cspell/url",
3
+ "publishConfig": {
4
+ "access": "public"
5
+ },
6
+ "version": "8.9.0-alpha.0",
7
+ "description": "URL parsing and manipulation utilities for cspell",
8
+ "keywords": [
9
+ "cspell",
10
+ "url"
11
+ ],
12
+ "author": "Jason Dent <jason@streetsidesoftware.nl>",
13
+ "homepage": "https://github.com/streetsidesoftware/cspell/tree/main/packages/cspell-url#readme",
14
+ "license": "MIT",
15
+ "type": "module",
16
+ "sideEffects": false,
17
+ "module": "./dist/index.mjs",
18
+ "types": "./dist/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "import": "./dist/index.mjs"
22
+ }
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "!**/*.tsbuildInfo",
27
+ "!**/__mocks__",
28
+ "!**/*.spec.*",
29
+ "!**/*.test.*",
30
+ "!**/test/**",
31
+ "!**/*.map"
32
+ ],
33
+ "scripts": {
34
+ "build": "tsc -p .",
35
+ "build:clean": "pnpm clean && pnpm build",
36
+ "clean": "shx rm -rf dist coverage",
37
+ "clean-build": "pnpm build:clean",
38
+ "coverage": "vitest run --coverage",
39
+ "test-watch": "vitest",
40
+ "test": "vitest run",
41
+ "watch": "tsc -p . --watch"
42
+ },
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "https://github.com/streetsidesoftware/cspell.git",
46
+ "directory": "packages/dynamic-import"
47
+ },
48
+ "bugs": {
49
+ "url": "https://github.com/streetsidesoftware/cspell"
50
+ },
51
+ "engines": {
52
+ "node": ">=18.0"
53
+ },
54
+ "gitHead": "700ed688420d2f3e784c05e2709ad33953aadadc"
55
+ }