@reliverse/pathkit 1.3.3 → 2.2.7

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.
@@ -1,5 +1,5 @@
1
1
  import type { PlatformPath } from "node:path";
2
- import { getFileImportsExports, type ImportExportInfo, type ImportExportSpecifier, type GetFileImportsExportsOptions } from "./impl/getFileImportsExports.js";
2
+ import { type GetFileImportsExportsOptions, getFileImportsExports, type ImportExportInfo, type ImportExportSpecifier } from "./utils/get-imports-exports.js";
3
3
  declare const normalizedAliasSymbol: unique symbol;
4
4
  export declare const IMPORT_EXPORT_REGEX: RegExp;
5
5
  interface NormalizedRecord extends Record<string, string> {
@@ -1,7 +1,7 @@
1
- import fs from "node:fs/promises";
1
+ import * as fs from "node:fs/promises";
2
2
  import {
3
3
  getFileImportsExports
4
- } from "./impl/getFileImportsExports.js";
4
+ } from "./utils/get-imports-exports.js";
5
5
  const regularLogger = (msg) => {
6
6
  const message = typeof msg === "function" ? msg() : msg;
7
7
  console.log(`\x1B[2m${message}\x1B[0m`);
@@ -23,7 +23,7 @@ const BACK_SLASH = "\\";
23
23
  const DOT = ".";
24
24
  const DOUBLE_DOT = "..";
25
25
  const EMPTY = "";
26
- const normalizedAliasSymbol = Symbol.for("pathkit:normalizedAlias");
26
+ const normalizedAliasSymbol = /* @__PURE__ */ Symbol.for("pathkit:normalizedAlias");
27
27
  const DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
28
28
  const DRIVE_LETTER_RE = /^[A-Za-z]:$/;
29
29
  const UNC_REGEX = /^[/\\]{2}/;
@@ -583,12 +583,6 @@ async function convertImportsAliasToRelative({
583
583
  displayLogs = false
584
584
  }) {
585
585
  const normalizedAlias = aliasToReplace.endsWith("/*") ? aliasToReplace : `${aliasToReplace}/*`;
586
- regularLogger(
587
- `Converting aliased imports starting with '${aliasToReplace}' to relative paths in "${targetDir}"...`
588
- );
589
- regularLogger(
590
- ` (Assuming "${normalizedAlias}" resolves relative to "${targetDir}")`
591
- );
592
586
  const results = await processAllFiles({
593
587
  srcDir: targetDir,
594
588
  aliasToReplace: normalizedAlias,
@@ -607,7 +601,6 @@ async function convertImportsAliasToRelative({
607
601
  }
608
602
  }
609
603
  }
610
- regularLogger("Import/export path conversion process complete.");
611
604
  return results;
612
605
  }
613
606
  async function convertImportsExt({
package/package.json CHANGED
@@ -1,26 +1,22 @@
1
1
  {
2
- "dependencies": {
3
- "@reliverse/cfg": "^1.7.20"
4
- },
5
- "description": "@reliverse/pathkit is a slash‑consistent, cross‑platform path manipulation, with POSIX forward slash, drop‑in for node:path and unjs/pathe. This library extends the node:path module with a set of functions for manipulating file paths.",
6
- "homepage": "https://docs.reliverse.org",
7
- "license": "MIT",
8
2
  "name": "@reliverse/pathkit",
3
+ "description": "Path manipulation and resolution utilities for Reliverse ecosystem",
4
+ "author": "reliverse",
5
+ "version": "2.2.7",
6
+ "private": false,
9
7
  "type": "module",
10
- "version": "1.3.3",
11
- "devDependencies": {},
12
8
  "exports": {
13
- ".": "./bin/mod.js"
9
+ ".": {
10
+ "types": "./dist/mod.d.ts",
11
+ "default": "./dist/mod.js"
12
+ }
14
13
  },
15
- "files": [
16
- "bin",
17
- "package.json",
18
- "README.md",
19
- "LICENSE"
20
- ],
21
- "main": "./bin/mod.js",
22
- "module": "./bin/mod.js",
23
14
  "publishConfig": {
24
15
  "access": "public"
25
- }
26
- }
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "package.json"
20
+ ],
21
+ "license": "MIT"
22
+ }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- # MIT License
2
-
3
- Copyright (c) Nazar Kornienko (blefnk), Reliverse
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 DELETED
@@ -1,510 +0,0 @@
1
- # pathkit • cross‑platform path manipulation
2
-
3
- > @reliverse/pathkit is a slash‑consistent, cross‑platform path manipulation, with POSIX forward slash, drop‑in for node:path and unjs/pathe. This library extends the node:path module with a set of functions for manipulating file paths.
4
-
5
- [sponsor](https://github.com/sponsors/blefnk) • [discord](https://discord.gg/Pb8uKbwpsJ) • [npm](https://npmjs.com/package/@reliverse/pathkit) • [repo](https://github.com/reliverse/pathkit)
6
-
7
- ## Key Features
8
-
9
- - 🔹 **drop in** and replace `node:path` and `unjs/pathe` instantly
10
- - ➕ **`unjs/pathe` on steroids** – alias resolution, import parsing, and more
11
- - 🌀 **always `/`** – posix separators 100% of the time (buh‑bye `\\`)
12
- - ⚙️ **node.js api compatible** – familiar methods, no learning curve
13
- - 🚀 **modern & fast** – typescript, pure esm, bun & node‑ready
14
- - 🧠 **predictable & testable** – deterministic output across windows / macos / linux
15
- - 🧼 **no dependencies** – just better path api + couple of cool utilities = [4kB](https://bundlephobia.com/package/@reliverse/pathkit@latest)
16
-
17
- ## Installation
18
-
19
- ```bash
20
- # bun • pnpm • yarn • npm
21
- bun add @reliverse/pathkit
22
- ```
23
-
24
- **Migrate**:
25
-
26
- ```bash
27
- # soon:
28
- # bun add -D @reliverse/dler
29
- # bun dler migrate --lib path-to-pathkit
30
- # bun dler migrate --lib pathe-to-pathkit
31
- ```
32
-
33
- ### `unjs/pathe` vs `@reliverse/pathkit`
34
-
35
- | Package | What you get | When to use |
36
- |---------|--------------|-------------|
37
- | **`pathe`** | Path API only (with POSIX everywhere) | You only need a drop‑in for `node:path` |
38
- | **`pathkit`** | Everything in `pathe` **+** advanced utilities | You need alias resolution, import transforms, etc. |
39
-
40
- ## Why Pathkit? — The Problem with Native Paths
41
-
42
- Native `node:path` flips behavior between operating systems, spurring subtle bugs and OS checks.
43
-
44
- ```js
45
- // With node:path – the same call may yield different separators on each OS
46
- import path from "node:path";
47
-
48
- const project = "users/blefnk/project";
49
- const full = path.join("C:\\", project);
50
- console.log(full); // "C:\\users\\blefnk\\project" (Windows) vs ??? (others)
51
- ```
52
-
53
- ### ✅ The `pathkit` Fix
54
-
55
- ```js
56
- import { join } from "@reliverse/pathkit";
57
-
58
- const full = join("C:", "users", "blefnk", "project");
59
- console.log(full); // "C:/users/blefnk/project" on **every** OS 🎉
60
- ```
61
-
62
- | Pain Point | `@reliverse/pathkit` Solution |
63
- | :----------------------------- | :--------------------------- |
64
- | Inconsistent separators | ✅ Always `/` |
65
- | OS‑specific work‑arounds | ✅ One code path |
66
- | Needs TypeScript + ESM | ✅ Built‑in |
67
- | Works in Bun / Deno / Node | ✅ Out of the box |
68
-
69
- ## Quick Start
70
-
71
- ```ts
72
- import { resolve, join, normalize } from "@reliverse/pathkit";
73
-
74
- // Mixed slashes & dot‑segments? No problem.
75
- const messy = "src\\..\\./dist///file.js";
76
- console.log(resolve(messy)); // → "dist/file.js"
77
-
78
- // Join is predictable everywhere:
79
- console.log(join("users", "blefnk")); // → "users/blefnk"
80
- ```
81
-
82
- **Side‑by‑Side Demo**:
83
-
84
- | Code | Windows Output | macOS / Linux Output |
85
- |------|----------------|----------------------|
86
- | `join("a", "b")` | `a/b` | `a/b` |
87
- | `resolve("..", "x")` | `x` | `x` |
88
-
89
- Say goodbye to `process.platform` conditionals 👋.
90
-
91
- ## pathkit advanced features
92
-
93
- `@reliverse/pathkit` extends the core functionality of `node:path` with powerful utilities for working with imports, aliases, and more.
94
-
95
- ### Import/Export Analysis
96
-
97
- The `getFileImportsExports` function provides detailed analysis of ES module imports and exports in your code:
98
-
99
- ```ts
100
- import { getFileImportsExports } from "@reliverse/pathkit";
101
-
102
- const code = `
103
- import { ref } from "vue";
104
- import utils from "@/utils";
105
- import type { Config } from "./types";
106
- import * as React from "react";
107
- import { Button as UIButton } from "./components";
108
- export { default as MyComponent } from "./MyComponent";
109
- export type { Props } from "./types";
110
- `;
111
-
112
- const analysis = getFileImportsExports(code, {
113
- kind: "all", // "import" | "export" | "all"
114
- pathTypes: ["alias"], // Filter by path types: "alias" | "relative" | "absolute" | "bare" | "module"
115
- limitPerType: 2 // Limit results per type
116
- });
117
- ```
118
-
119
- The analysis provides rich information about each import/export statement:
120
-
121
- ```ts
122
- interface ImportExportInfo {
123
- statement: string; // Full original statement
124
- type: "static" | "dynamic"; // Import type (static or dynamic import())
125
- kind: "import" | "export"; // Statement kind
126
- source?: string; // Import/export source path
127
- pathType?: "alias" | "relative" | "absolute" | "bare" | "module";
128
- pathTypeSymbol?: string; // Path prefix (e.g., "@/", "~/")
129
- isTypeOnly?: boolean; // Type-only import/export
130
- specifiers?: { // Imported/exported items
131
- type: "named" | "default" | "namespace" | "all";
132
- name: string;
133
- alias?: string;
134
- isType?: boolean;
135
- }[];
136
- start: number; // Position in source
137
- end: number;
138
- importExt?: string; // Extension as written in import/export statement
139
- realFileExt?: string; // Likely actual file extension (e.g., .ts for .js imports)
140
- }
141
- ```
142
-
143
- Features:
144
-
145
- - ✨ **Comprehensive Syntax Support**
146
- - Static imports (`import x from "y"`)
147
- - Dynamic imports (`import("y")`)
148
- - Named imports/exports (`import { x } from "y"`)
149
- - Default imports/exports (`import x from "y"`)
150
- - Namespace imports (`import * as x from "y"`)
151
- - Re-exports (`export * from "y"`)
152
- - Type imports/exports (`import type { x } from "y"`)
153
-
154
- - 🔍 **Path Analysis**
155
- - Detects path types (alias, relative, absolute, bare, module)
156
- - Extracts path prefixes (e.g., `@/`, `~/`)
157
- - Preserves original path format
158
- - Tracks both import statement extensions and likely real file extensions
159
- - Handles TypeScript/JavaScript extension conversion (e.g., `.js` → `.ts`)
160
-
161
- - 🎯 **Specifier Details**
162
- - Named imports/exports with aliases
163
- - Default imports/exports
164
- - Namespace imports
165
- - Type-only imports/exports
166
- - Mixed type and value imports
167
-
168
- - 📊 **Filtering Options**
169
- - Filter by statement kind (import/export)
170
- - Filter by path types
171
- - Limit results per type
172
- - Preserve statement order
173
-
174
- - 🛡️ **Type Safety**
175
- - Full TypeScript support
176
- - Detailed type definitions
177
- - Null-safe operations
178
-
179
- Example output:
180
-
181
- ```ts
182
- [
183
- {
184
- statement: 'import { ref } from "vue"',
185
- type: "static",
186
- kind: "import",
187
- source: "vue",
188
- pathType: "bare",
189
- specifiers: [{
190
- type: "named",
191
- name: "ref"
192
- }],
193
- start: 0,
194
- end: 24,
195
- importExt: "",
196
- realFileExt: ""
197
- },
198
- {
199
- statement: 'import type { Config } from "./types.js"',
200
- type: "static",
201
- kind: "import",
202
- source: "./types.js",
203
- pathType: "relative",
204
- isTypeOnly: true,
205
- specifiers: [{
206
- type: "named",
207
- name: "Config",
208
- isType: true
209
- }],
210
- start: 45,
211
- end: 85,
212
- importExt: ".js",
213
- realFileExt: ".ts"
214
- }
215
- ]
216
- ```
217
-
218
- ### Path Transformation
219
-
220
- Convert between different path formats:
221
-
222
- ```ts
223
- import { convertImportPaths } from "@reliverse/pathkit";
224
-
225
- await convertImportPaths({
226
- baseDir: "./src",
227
- fromType: "relative", // "./components/Button"
228
- toType: "alias", // "@/components/Button"
229
- aliasPrefix: "@/",
230
- generateSourceMap: true
231
- });
232
- ```
233
-
234
- ### Extension Conversion
235
-
236
- ```ts
237
- import { convertImportsExt } from "@reliverse/pathkit";
238
-
239
- // Basic usage - convert all relative imports to .ts
240
- await convertImportsExt({
241
- targetDir: "./src",
242
- extFrom: "none",
243
- extTo: "ts"
244
- });
245
-
246
- // Convert .js to .ts
247
- await convertImportsExt({
248
- targetDir: "./src",
249
- extFrom: "js",
250
- extTo: "ts"
251
- });
252
-
253
- // Remove extensions
254
- await convertImportsExt({
255
- targetDir: "./src",
256
- extFrom: "ts",
257
- extTo: "none"
258
- });
259
-
260
- // Handle alias paths (e.g. @/components)
261
- await convertImportsExt({
262
- targetDir: "./src",
263
- extFrom: "none",
264
- extTo: "ts",
265
- alias: "@" // or "@/*"
266
- });
267
- ```
268
-
269
- The function intelligently handles different import types:
270
-
271
- - ✅ Relative imports (`./file`, `../file`)
272
- - ✅ Alias imports (when alias is specified)
273
- - ✅ Package imports (`lodash`, `@scope/pkg`)
274
- - ✅ Node built-ins (`node:path`, `node:fs`)
275
- - ✅ URLs (`http://`, `https://`)
276
- - ✅ Already processed paths
277
-
278
- Features:
279
-
280
- - 🔄 Recursively processes directories
281
- - 🎯 Preserves package imports
282
- - 🛡️ Safe for code generation
283
- - 📝 Detailed change logging
284
- - 🎨 Supports custom aliases
285
-
286
- ### Path Segment Manipulation
287
-
288
- Manipulate path segments in import statements:
289
-
290
- ```ts
291
- import {
292
- stripPathSegments,
293
- stripPathSegmentsInDirectory,
294
- attachPathSegments,
295
- attachPathSegmentsInDirectory
296
- } from "@reliverse/pathkit";
297
-
298
- // Strip segments from a path
299
- stripPathSegments("src/components/Button.tsx", 1); // "components/Button.tsx"
300
-
301
- // Strip segments from imports in a directory
302
- await stripPathSegmentsInDirectory({
303
- targetDir: "./src",
304
- segmentsToStrip: 1,
305
- alias: "@" // Optional: preserve alias prefix
306
- });
307
-
308
- // Attach segments to a path
309
- attachPathSegments("Button.tsx", "components", {
310
- position: "before", // "before" | "after"
311
- normalize: true, // Normalize the path
312
- ensureSlash: true, // Ensure slash between segments
313
- preserveRoot: true, // Preserve root in absolute paths
314
- preserveAlias: "@" // Optional: preserve alias prefix
315
- });
316
-
317
- // Attach segments to imports in a directory
318
- await attachPathSegmentsInDirectory({
319
- targetDir: "./src",
320
- segments: "components",
321
- options: {
322
- position: "before",
323
- preserveAlias: "@"
324
- }
325
- });
326
- ```
327
-
328
- ### Alias Resolution
329
-
330
- Advanced alias handling and resolution:
331
-
332
- ```ts
333
- import {
334
- normalizeAliases,
335
- resolveAlias,
336
- reverseResolveAlias
337
- } from "@reliverse/pathkit";
338
-
339
- const aliases = { "@/": "/src/", "~/": "/home/user/" };
340
-
341
- // Normalize alias config
342
- console.log(normalizeAliases(aliases));
343
-
344
- // Resolve alias to absolute path
345
- console.log(resolveAlias("@/components", aliases)); // "/src/components"
346
-
347
- // Convert absolute path back to alias
348
- console.log(reverseResolveAlias("/src/utils", aliases)); // "@/utils"
349
- ```
350
-
351
- ```ts
352
- import {
353
- normalizeAliases,
354
- resolveAlias,
355
- reverseResolveAlias,
356
- findAliasMatch
357
- } from "@reliverse/pathkit";
358
-
359
- // Normalize and optimize alias configurations
360
- const aliases = {
361
- "@/": "/src/",
362
- "~/": "/home/user/",
363
- "@/components/": "/src/components/" // Nested alias
364
- };
365
- const normalized = normalizeAliases(aliases);
366
-
367
- // Resolve aliased paths
368
- resolveAlias("@/components/Button", aliases); // "/src/components/Button"
369
-
370
- // Convert absolute paths back to aliases
371
- reverseResolveAlias("/src/utils", aliases); // ["@/utils"]
372
-
373
- // Find matching alias in tsconfig-style paths
374
- const paths = {
375
- "@/*": ["./src/*"],
376
- "~/*": ["./home/*"]
377
- };
378
- findAliasMatch("@/components/Button", paths);
379
- ```
380
-
381
- ### Path Conversion
382
-
383
- Convert between different path formats:
384
-
385
- ```ts
386
- import {
387
- convertStringAliasRelative,
388
- convertImportsAliasToRelative
389
- } from "@reliverse/pathkit";
390
-
391
- // Convert a single aliased path to relative
392
- await convertStringAliasRelative({
393
- importPath: "@/components/Button",
394
- importerFile: "src/pages/Home.tsx",
395
- pathPattern: "@/*",
396
- targetDir: "src"
397
- });
398
-
399
- // Convert all aliased imports to relative in a directory
400
- await convertImportsAliasToRelative({
401
- targetDir: "./src",
402
- aliasToReplace: "@",
403
- pathExtFilter: "js-ts-none" // "js" | "ts" | "none" | "js-ts-none"
404
- });
405
- ```
406
-
407
- ### Platform-Specific Features
408
-
409
- Handle platform-specific path operations:
410
-
411
- ```ts
412
- import { posix, win32 } from "@reliverse/pathkit";
413
-
414
- // Use platform-specific path handling
415
- const path = process.platform === "win32" ? win32 : posix;
416
-
417
- // Windows-specific features
418
- win32.toNamespacedPath("C:\\path\\to\\file"); // "\\\\?\\C:\\path\\to\\file"
419
- win32.delimiter; // ";"
420
-
421
- // POSIX-specific features
422
- posix.delimiter; // ":"
423
- ```
424
-
425
- ### Utility Functions
426
-
427
- ```ts
428
- import {
429
- filename, // Strip extension
430
- normalizeQuotes, // Standardize quote style
431
- matchesGlob // Test glob patterns
432
- } from "@reliverse/pathkit";
433
-
434
- console.log(filename("/path/component.vue")); // "component"
435
- console.log(normalizeQuotes("import 'pkg'")); // 'import "pkg"'
436
- console.log(matchesGlob("file.ts", "**/*.ts")); // true
437
- ```
438
-
439
- ```ts
440
- import {
441
- filename,
442
- normalizeWindowsPath,
443
- replaceAllInString
444
- } from "@reliverse/pathkit";
445
-
446
- // Get filename without extension
447
- filename("/path/to/file.ts"); // "file"
448
-
449
- // Normalize Windows paths
450
- normalizeWindowsPath("C:\\path\\to\\file"); // "C:/path/to/file"
451
-
452
- // Replace strings while tracking position
453
- replaceAllInString("import x from 'y'", "'y'", "'z'");
454
- ```
455
-
456
- ### Supported File Extensions
457
-
458
- The library supports the following file extensions by default:
459
-
460
- ```ts
461
- const EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];
462
- ```
463
-
464
- ### Type Definitions
465
-
466
- ```ts
467
- type PathExtFilter = "js" | "ts" | "none" | "js-ts-none";
468
- type ImportExtType = "js" | "ts" | "none";
469
- ```
470
-
471
- ## Use Cases / Ideal For
472
-
473
- - 🛠️ **CLI tools**
474
- - 🌍 **Cross‑platform dev environments**
475
- - 🔄 **Bundlers, linters, compilers**
476
- - 🏗️ **Framework & library authors**
477
- - 📜 **Scripts / test runners**
478
- - …anywhere file‑paths roam!
479
-
480
- ## Examples & Contributing
481
-
482
- ```bash
483
- git clone https://github.com/reliverse/pathkit.git
484
- cd pathkit
485
- bun install
486
- bun dev
487
- ```
488
-
489
- Bug reports & PRs are warmly welcome—come on in!
490
-
491
- ## Related
492
-
493
- - [`@reliverse/rempts`](https://npmjs.com/package/@reliverse/rempts) – Terminal Prompts Engine
494
-
495
- ## Community
496
-
497
- - ⭐ **Star** the repo if this helped you.
498
- - 💖 **Sponsor** [@blefnk](https://github.com/sponsors/blefnk) to keep the lights on.
499
- - 💬 **Chat** with us on [Discord](https://discord.gg/Pb8uKbwpsJ).
500
-
501
- ## License
502
-
503
- [MIT](LICENSE) © [Nazar Kornienko (blefnk)](https://github.com/blefnk), [Reliverse](https://github.com/reliverse)
504
-
505
- ## Badges
506
-
507
- [![npm](https://img.shields.io/npm/v/@reliverse/pathkit?label=npm%20v)](https://npmjs.com/package/@reliverse/pathkit)
508
- [![downloads](https://img.shields.io/npm/dm/@reliverse/pathkit.svg?color=brightgreen)](https://npmjs.com/package/@reliverse/pathkit)
509
- [![typescript](https://img.shields.io/badge/typed-%E2%9C%85-blue)](https://github.com/reliverse/pathkit)
510
- [![license](https://img.shields.io/npm/l/@reliverse/pathkit.svg)](LICENSE)