nice-path 0.1.1 → 3.0.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/.node-version ADDED
@@ -0,0 +1 @@
1
+ v18.18.2
package/LICENSE CHANGED
@@ -1,5 +1,5 @@
1
1
  The MIT License (MIT)
2
- Copyright (c) 2019 Lily Scott
2
+ Copyright (c) 2019-2024 Lily Skye
3
3
 
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
package/README.md CHANGED
@@ -1,46 +1,316 @@
1
1
  # nice-path
2
2
 
3
- `nice-path` is a replacement for the [Node.js](https://nodejs.org/) `path` builtin module.
3
+ `nice-path` provides a class that represents a filesystem path (POSIX-style or Win32-style), which has various nice methods on it that make it easy to work with. It can be used as a replacement for the Node.js `path` builtin module, where you pass around Path objects and stringify them before use, rather than passing around strings.
4
4
 
5
- ## The Problem
5
+ > `nice-path`'s code is derived from [yavascript](https://github.com/suchipi/yavascript).
6
6
 
7
- When using `path` in Node, paths are represented as strings. Because of this, it's easy to mix up absolute paths and relative paths, and when using Flow or TypeScript, it's hard to define and enforce whether a function you're writing needs absolute or relative paths. These problems mean there are a lot of things you need to remember to handle when working with paths.
7
+ ## Example
8
8
 
9
- Additionally, Node's `path` module cannot handle paths for OSes other than the one where it is running; if you use `path.join` on a Windows-style path on a Unix system, then it behaves incorrectly. This can be problematic when writing cross-platform applications, or when paths from one computer are used on another.
9
+ ```ts
10
+ import { Path } from "nice-path";
10
11
 
11
- ## This Solution
12
+ const here = new Path(__dirname);
13
+ console.log(here);
14
+ // Path {
15
+ // segments: ["", "home", "suchipi", "Code", "nice-path"],
16
+ // separator: "/"
17
+ // }
12
18
 
13
- This package treats paths as first-class objects, and distinguishes between absolute paths, relative paths, and "unqualified" paths (relative paths without any leading `./`). It can handle paths from Windows on Unix systems and vice versa (including UNC paths).
19
+ here.toString(); // "/home/suchipi/Code/nice-path"
20
+ here.isAbsolute(); // true
14
21
 
15
- ## Usage Example
22
+ const readme = here.concat("README.md");
23
+ console.log(readme);
24
+ // Path {
25
+ // segments: [
26
+ // "",
27
+ // "home",
28
+ // "suchipi",
29
+ // "Code",
30
+ // "nice-path",
31
+ // "README.md"
32
+ // ],
33
+ // separator: "/"
34
+ // }
35
+ readme.basename(); // "README.md"
36
+ readme.extname(); // ".md"
37
+ readme.dirname(); // Path object with same contents as 'here'
16
38
 
17
- ```ts
18
- import { Path, AbsolutePath } from "nice-path";
19
- import fs from "fs";
39
+ // normalize resolves . and .. components
40
+ const homeDir = here.concat("../../.").normalize();
41
+ console.log(homeDir);
42
+ // Path {
43
+ // segments: [
44
+ // "",
45
+ // "home",
46
+ // "suchipi"
47
+ // ],
48
+ // separator: "/"
49
+ // }
50
+
51
+ here.relativeTo(homeDir).toString(); // "./Code/nice-path"
52
+ readme.relativeTo(homeDir).toString(); // "./Code/nice-path/README.txt"
53
+
54
+ // There are also several other methods which aren't in this example.
55
+ ```
56
+
57
+ ## API Documentation
58
+
59
+ ### Overview
20
60
 
21
- const absolutePath = Path.fromAbsolutePathString("/tmp/some-folder/");
22
- absolutePath.raw; // "/tmp/some-folder/"
61
+ This package has one named export: "Path", which is a class.
23
62
 
24
- absolutePath.hasTrailingSlash(); // true
63
+ The "Path" class has the following instance properties:
25
64
 
26
- const newPath = absolutePath.removeTrailingSlash(); // AbsolutePath
65
+ - segments (Array of string)
66
+ - separator (string)
27
67
 
28
- const tmpDir = absolutePath.parentDirectory(); // AbsolutePath of "/tmp"
68
+ and the following instance methods:
29
69
 
30
- const someOtherFolder = tmpDir.append("some", "other-folder"); // AbsolutePath of "/tmp/some/other-folder"
70
+ - normalize
71
+ - concat
72
+ - isAbsolute
73
+ - clone
74
+ - relativeTo
75
+ - toString
76
+ - basename
77
+ - extname
78
+ - dirname
79
+ - startsWith
80
+ - endsWith
81
+ - indexOf
82
+ - includes
83
+ - replace
84
+ - replaceAll
85
+ - replaceLast
31
86
 
32
- function onlyWorksWithAbsolutePaths(path: AbsolutePath) {
33
- fs.writeFileSync(path.raw, "hi");
87
+ and the following static methods:
88
+
89
+ - splitToSegments
90
+ - detectSeparator
91
+ - normalize
92
+ - isAbsolute
93
+ - fromRaw
94
+
95
+ ### Details
96
+
97
+ #### Path (class)
98
+
99
+ An object that represents a filesystem path. It has the following constructor signature:
100
+
101
+ ```ts
102
+ class Path {
103
+ constructor(...inputs: Array<string | Path | Array<string | Path>>);
34
104
  }
105
+ ```
106
+
107
+ You can pass in zero or more arguments to the constructor, where each argument can be either a string, a Path object, or an array of strings and Path objects.
108
+
109
+ When multiple strings/Paths are provided to the constructor, they will be concatenated together in order, left-to-right.
110
+
111
+ The resulting object has two properties: `segments`, which is an array of strings containing all the non-slash portions of the Path, and `separator`, which is the slash string that those portions would have between them if this path were represented as a string.
112
+
113
+ #### `segments: Array<string>` (instance property of Path)
114
+
115
+ Each `Path` object has a `segments` property, which is an array of strings containing all the non-slash portions of the Path.
116
+
117
+ For example, given a path object `myPath = new Path("a/b/c/d")`, `myPath.segments` is an array of strings `["a", "b", "c", "d"]`.
118
+
119
+ You may freely mutate this array in order to add or remove segments, but I recommend you instead use instance methods on the Path object, which take a "separator-aware" approach to looking at path segments.
120
+
121
+ POSIX-style absolute paths start with a leading slash character, like "/a/b/c". A Path object representing that path, (ie `new Path("/a/b/c")`) would have the following path segments:
122
+
123
+ ```json
124
+ ["", "a", "b", "c"]
125
+ ```
126
+
127
+ That empty string in the first position represents the "left side" of the first slash. When you use `.toString()` on that Path object, it will become "/a/b/c" again, as expected.
128
+
129
+ Windows [UNC paths](https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats#unc-paths) have two empty strings at the beginning of the Array.
130
+
131
+ #### `separator: string` (instance property of Path)
132
+
133
+ Each `Path` object has a `separator` property, which is the slash string that those portions would have between them if this path were represented as a string. It's always either `/` (forward slash) or `\` (backward slash). If you change this property, the result of calling `.toString()` on the Path object will change:
134
+
135
+ ```ts
136
+ // The initial value of separator is inferred from the input path:
137
+ const myPath = new Path("hi/there/friend");
138
+ console.log(myPath.separator); // prints /
139
+
140
+ // Using toString() joins the path segments using the separator:
141
+ console.log(myPath.toString()); // prints hi/there/friend
142
+
143
+ // If you change the separator... (note: this is a single backslash character. It has to be "escaped" with another one, which is why there are two.)
144
+ myPath.separator = "\\";
145
+
146
+ // Then toString() uses the new separator instead:
147
+ console.log(myPath.toString()); // prints hi\there\friend
148
+ ```
149
+
150
+ The initial value of the `separator` property is inferred by searching the input string(s) the Path was constructed with for a slash character and using the first one found. If none is found, a forward slash (`/`) is used.
151
+
152
+ #### `normalize(): Path` (instance method of Path)
153
+
154
+ The `normalize` method returns a new Path with all non-leading `.` and `..` segments resolved.
155
+
156
+ ```ts
157
+ const myPath = new Path("/some/where/../why/over/./here");
158
+ const resolved = myPath.normalize();
159
+ console.log(resolved.toString()); // /some/why/over/here
160
+ ```
161
+
162
+ If you want to evaluate a relative path (a path with leading `.` or `..` segments) using a base directory, you can concatenate and then normalize them:
163
+
164
+ ```ts
165
+ const baseDir = new Path("/home/me");
166
+ const relativeDir = new Path("./somewhere/something/../blue");
167
+ const resolved = baseDir.concat(relativeDir).normalize();
168
+ console.log(resolved.toString()); // /home/me/something/blue
169
+ ```
170
+
171
+ #### `concat(...others): Path` (instance method of Path)
172
+
173
+ The `concat` method creates a new Path by appending additional path segments onto the end of the target Path's segments. The additional path segments are passed to the concat method as either strings, Paths, or Arrays of strings and Paths.
174
+
175
+ The new Path will use the separator from the target Path.
176
+
177
+ ```ts
178
+ const pathOne = new Path("a/one");
179
+ const withStuffAdded = pathOne.concat(
180
+ "two",
181
+ "three/four",
182
+ new Path("yeah\\yes"),
183
+ );
184
+
185
+ console.log(withStuffAdded.toString());
186
+ // "a/one/two/three/four/yeah/yes"
187
+ ```
188
+
189
+ #### `isAbsolute(): boolean` (instance method of Path)
190
+
191
+ The `isAbsolute` method returns whether the target Path is an absolute path; that is, whether it starts with either `/`, `\`, or a drive letter (ie `C:`).
192
+
193
+ #### `clone(): Path` (instance method of Path)
194
+
195
+ The `clone` method makes a second Path object containing the same segments and separator as the target.
35
196
 
36
- const relativePath = Path.fromRelativePathString("./data");
197
+ Note that although the new Path has the same segments as the target Path, it doesn't use the same Array instance.
37
198
 
38
- onlyWorksWithAbsolutePaths(relativePath); // TypeScript error
199
+ #### `relativeTo(dir, options?): Path` (instance method of Path)
39
200
 
40
- const absoluteData = relativePath.toAbsolute(absolutePath); // AbsolutePath of "/tmp/some-folder/data"
201
+ The `relativeTo` method expresses the target path as a relative path, relative to the `dir` argument.
202
+
203
+ The `options` argument, if present, should be an object with the property "noLeadingDot", which is a boolean. The noLeadingDot option controls whether the resulting relative path has a leading `.` segment or not. If this option isn't provided, the leading dot will be present. Note that if the resulting path starts with "..", that will always be present, regardless of the option.
204
+
205
+ #### `toString(): string` (instance method of Path)
206
+
207
+ The `toString` method returns a string representation of the target Path by joining its segments using its separator.
208
+
209
+ #### `basename(): string` (instance method of Path)
210
+
211
+ The `basename` method returns the final segment string of the target Path. If that Path has no segments, the empty string is returned.
212
+
213
+ #### `extname(options?): string` (instance method of Path)
214
+
215
+ The `extname` method returns the trailing extension of the target Path. Pass `{ full: true }` as the "options" argument to get a compound extension like ".d.ts", rather than the final extension (like ".ts").
216
+
217
+ If the Path doesn't have a trailing extension, the empty string (`""`) is returned.
218
+
219
+ #### `dirname(): Path` (instance method of Path)
220
+
221
+ The `dirname` method returns a new Path containing all of the segments in the target Path except for the last one; ie. the path to the directory that contains the target path.
222
+
223
+ #### `startsWith(value): boolean` (instance method of Path)
224
+
225
+ The `startsWith` method returns whether the target Path starts with the provided value (string, Path, or Array of string/Path), by comparing one path segment at a time, left-to-right.
226
+
227
+ The starting segment(s) of the target Path must _exactly_ match the segment(s) in the provided value.
228
+
229
+ This means that, given two Paths A and B:
41
230
 
42
- onlyWorksWithAbsolutePaths(absoluteData); // No error
43
231
  ```
232
+ A: Path { /home/user/.config }
233
+ B: Path { /home/user/.config2 }
234
+ ```
235
+
236
+ Path B does _not_ start with Path A, because `".config" !== ".config2"`.
237
+
238
+ #### `endsWith(value): boolean` (instance method of Path)
239
+
240
+ The `endsWith` method returns whether the target Path ends with the provided value (string, Path, or Array of string/Path), by comparing one path segment at a time, right-to-left.
241
+
242
+ The ending segment(s) of the target Path must _exactly_ match the segment(s) in the provided value.
243
+
244
+ This means that, given two Paths A and B:
245
+
246
+ ```
247
+ A: Path { /home/1user/.config }
248
+ B: Path { user/.config }
249
+ ```
250
+
251
+ Path A does _not_ end with Path B, because `"1user" !== "user"`.
252
+
253
+ #### `indexOf(value, fromIndex?): number;` (instance method of Path)
254
+
255
+ The `indexOf` method returns the path segment index (number) at which `value` (string, Path, or Array of string/Path) appears in the target Path, or `-1` if it doesn't appear.
256
+
257
+ If the provided value argument contains more than one path segment, the returned index will refer to the location of the value's first path segment.
258
+
259
+ The optional argument `fromIndex` can be provided to specify which index into the target Path's segments to begin the search at. If not provided, the search starts at the beginning (index 0).
260
+
261
+ #### `includes(value, fromIndex?): boolean;` (instance method of Path)
262
+
263
+ The `includes` method returns a boolean indicating whether `value` (string, Path, or Array of string/Path) appears in the target Path.
264
+
265
+ The optional argument `fromIndex` can be provided to specify which index into the target Path's segments to begin the search at. If not provided, the search starts at the beginning (index 0).
266
+
267
+ #### `replace(value, replacement): Path;` (instance method of Path)
268
+
269
+ The `replace` method returns a new `Path` object wherein the first occurrence of `value` (string, Path, or Array of string/Path) in the target Path has been replaced with `replacement` (string, Path, or Array of string/Path).
270
+
271
+ Note that only the first match is replaced; to replace multiple occurrences, use `replaceAll`.
272
+
273
+ If `value` is not present in the target Path, a clone of said Path is returned.
274
+
275
+ > Tip: To "replace with nothing", pass an empty array as the replacement.
276
+
277
+ #### `replaceAll(value, replacement): Path;` (instance method of Path)
278
+
279
+ The `replaceAll` method returns a new `Path` object wherein all occurrences of `value` (string, Path, or Array of string/Path) in the target Path have been replaced with `replacement` (string, Path, or Array of string/Path).
280
+
281
+ If you want to only replace the first occurrence, use `replace` instead.
282
+
283
+ If `value` is not present in the target Path, a clone of said Path is returned.
284
+
285
+ > Tip: To "replace with nothing", pass an empty array as the replacement.
286
+
287
+ #### `replaceLast(replacement): Path;` (instance method of Path)
288
+
289
+ The `replaceLast` method returns a copy of the target Path, but with its final segment replaced with `replacement` (string, Path, or Array of string/Path).
290
+
291
+ This method is most commonly used to modify the final (filename) part of a path.
292
+
293
+ If the target Path has no segments, the returned Path will contain exactly the segments from `replacement`.
294
+
295
+ #### `Path.splitToSegments(inputParts): Array<string>` (static method on Path)
296
+
297
+ Splits one or more path strings into an array of path segments. Used internally by the Path constructor.
298
+
299
+ #### `Path.detectSeparator(input, fallback)` (static method on Path)
300
+
301
+ Searches input (a string or Array of strings) for a path separator character (either forward slash or backslash), and returns it. If none is found, returns `fallback`.
302
+
303
+ #### `Path.normalize(...inputs): Path` (static method on Path)
304
+
305
+ Concatenates the input path(s) and then resolves all non-leading `.` and `..` segments. Shortcut for `new Path(...inputs).normalize()`.
306
+
307
+ #### `Path.isAbsolute(path)`: boolean (static method on Path)
308
+
309
+ Return whether the `path` argument (string or Path) is an absolute path; that is, whether it starts with either `/`, `\`, or a drive letter (ie `C:`).
310
+
311
+ #### `Path.fromRaw(segments, separator): Path` (static method on Path)
312
+
313
+ Creates a new Path object using the provided segments and separator.
44
314
 
45
315
  ## License
46
316
 
@@ -0,0 +1,182 @@
1
+ /** An object that represents a filesystem path. */
2
+ export declare class Path {
3
+ /** Split one or more path strings into an array of path segments. */
4
+ static splitToSegments(inputParts: Array<string> | string): Array<string>;
5
+ /**
6
+ * Search the provided path string or strings for a path separator character
7
+ * (either forward slash or backslash), and return it. If none is found,
8
+ * return `fallback`.
9
+ */
10
+ static detectSeparator<Fallback extends string | null = string>(input: Array<string> | string, fallback: Fallback): string | Fallback;
11
+ /**
12
+ * Concatenates the input path(s) and then resolves all non-leading `.` and
13
+ * `..` segments.
14
+ */
15
+ static normalize(...inputs: Array<string | Path | Array<string | Path>>): Path;
16
+ /**
17
+ * Return whether the provided path is absolute; that is, whether it
18
+ * starts with either `/`, `\`, or a drive letter (ie `C:`).
19
+ */
20
+ static isAbsolute(path: string | Path): boolean;
21
+ /**
22
+ * An array of the path segments that make up this path.
23
+ *
24
+ * For `/tmp/foo.txt`, it'd be `["", "tmp", "foo.txt"]`.
25
+ *
26
+ * For `C:\something\somewhere.txt`, it'd be `["C:", "something", "somewhere.txt"]`.
27
+ */
28
+ segments: Array<string>;
29
+ /**
30
+ * The path separator that should be used to turn this path into a string.
31
+ *
32
+ * Will be either `/` or `\`.
33
+ */
34
+ separator: string;
35
+ /** Create a new Path object using the provided input(s). */
36
+ constructor(...inputs: Array<string | Path | Array<string | Path>>);
37
+ /**
38
+ * Create a new Path object using the provided segments and, optionally,
39
+ * separator.
40
+ *
41
+ * NOTE: this doesn't set the `segments` directly; it passes them through a
42
+ * filtering step first, to remove any double-slashes or etc. To set the
43
+ * `.segments` directly, use {@link fromRaw}.
44
+ */
45
+ static from(segments: Array<string>, separator?: string): Path;
46
+ /**
47
+ * Create a new Path object using the provided segments and separator.
48
+ *
49
+ * NOTE: this method doesn't do any sort of validation on `segments`; as such,
50
+ * it can be used to construct an invalid Path object. Consider using
51
+ * {@link from} instead.
52
+ */
53
+ static fromRaw(segments: Array<string>, separator: string): Path;
54
+ /**
55
+ * Resolve all non-leading `.` and `..` segments in this path.
56
+ */
57
+ normalize(): Path;
58
+ /**
59
+ * Create a new Path by appending additional path segments onto the end of
60
+ * this Path's segments.
61
+ *
62
+ * The returned path will use this path's separator.
63
+ */
64
+ concat(...others: Array<string | Path | Array<string | Path>>): Path;
65
+ /**
66
+ * Return whether this path is absolute; that is, whether it starts with
67
+ * either `/`, `\`, or a drive letter (ie `C:`).
68
+ */
69
+ isAbsolute(): boolean;
70
+ /**
71
+ * Make a second Path object containing the same segments and separator as
72
+ * this one.
73
+ */
74
+ clone(): this;
75
+ /**
76
+ * Express this path relative to `dir`.
77
+ *
78
+ * @param dir - The directory to create a new path relative to.
79
+ * @param options - Options that affect the resulting path.
80
+ */
81
+ relativeTo(dir: Path | string, options?: {
82
+ noLeadingDot?: boolean;
83
+ }): Path;
84
+ /**
85
+ * Turn this path into a string by joining its segments using its separator.
86
+ */
87
+ toString(): string;
88
+ /**
89
+ * Return the final path segment of this path. If this path has no path
90
+ * segments, the empty string is returned.
91
+ */
92
+ basename(): string;
93
+ /**
94
+ * Return the trailing extension of this path. Set option `full` to `true` to
95
+ * get a compound extension like ".d.ts" instead of ".ts".
96
+ */
97
+ extname(options?: {
98
+ full?: boolean;
99
+ }): string;
100
+ /**
101
+ * Return a new Path containing all of the path segments in this one except
102
+ * for the last one; ie. the path to the directory that contains this path.
103
+ */
104
+ dirname(): Path;
105
+ /**
106
+ * Return whether this path starts with the provided value, by comparing one
107
+ * path segment at a time.
108
+ *
109
+ * The starting segments of this path must *exactly* match the segments in the
110
+ * provided value.
111
+ *
112
+ * This means that, given two Paths A and B:
113
+ *
114
+ * ```
115
+ * A: Path { /home/user/.config }
116
+ * B: Path { /home/user/.config2 }
117
+ * ```
118
+ *
119
+ * Path B does *not* start with Path A, because `".config" !== ".config2"`.
120
+ */
121
+ startsWith(value: string | Path | Array<string | Path>): boolean;
122
+ /**
123
+ * Return whether this path ends with the provided value, by comparing one
124
+ * path segment at a time.
125
+ *
126
+ * The ending segments of this path must *exactly* match the segments in the
127
+ * provided value.
128
+ *
129
+ * This means that, given two Paths A and B:
130
+ *
131
+ * ```
132
+ * A: Path { /home/1user/.config }
133
+ * B: Path { user/.config }
134
+ * ```
135
+ *
136
+ * Path A does *not* end with Path B, because `"1user" !== "user"`.
137
+ */
138
+ endsWith(value: string | Path | Array<string | Path>): boolean;
139
+ /**
140
+ * Return the path segment index at which `value` appears in this path, or
141
+ * `-1` if it doesn't appear in this path.
142
+ *
143
+ * @param value - The value to search for. If the value contains more than one path segment, the returned index will refer to the location of the value's first path segment.
144
+ * @param fromIndex - The index into this path's segments to begin searching at. Defaults to `0`.
145
+ */
146
+ indexOf(value: string | Path | Array<string | Path>, fromIndex?: number): number;
147
+ /**
148
+ * Return whether `value` appears in this path.
149
+ *
150
+ * @param value - The value to search for.
151
+ * @param fromIndex - The index into this path's segments to begin searching at. Defaults to `0`.
152
+ */
153
+ includes(value: string | Path | Array<string | Path>, fromIndex?: number): boolean;
154
+ /**
155
+ * Return a new Path wherein the segments in `value` have been replaced with
156
+ * the segments in `replacement`. If the segments in `value` are not present
157
+ * in this path, a clone of this path is returned.
158
+ *
159
+ * Note that only the first match is replaced.
160
+ *
161
+ * @param value - What should be replaced
162
+ * @param replacement - What it should be replaced with
163
+ *
164
+ * NOTE: to remove segments, use an empty Array for `replacement`.
165
+ */
166
+ replace(value: string | Path | Array<string | Path>, replacement: string | Path | Array<string | Path>): Path;
167
+ /**
168
+ * Return a new Path wherein all occurrences of the segments in `value` have
169
+ * been replaced with the segments in `replacement`. If the segments in
170
+ * `value` are not present in this path, a clone of this path is returned.
171
+ *
172
+ * @param value - What should be replaced
173
+ * @param replacement - What it should be replaced with
174
+ */
175
+ replaceAll(value: string | Path | Array<string | Path>, replacement: string | Path | Array<string | Path>): Path;
176
+ /**
177
+ * Return a copy of this path but with the final segment replaced with `replacement`
178
+ *
179
+ * @param replacement - The new final segment(s) for the returned Path
180
+ */
181
+ replaceLast(replacement: string | Path | Array<string | Path>): Path;
182
+ }