@ark/fs 0.1.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 +7 -0
- package/out/caller.d.ts +26 -0
- package/out/caller.js +55 -0
- package/out/fs.d.ts +50 -0
- package/out/fs.js +122 -0
- package/out/getCurrentLine.d.ts +69 -0
- package/out/getCurrentLine.js +163 -0
- package/out/index.d.ts +3 -0
- package/out/index.js +3 -0
- package/out/shell.d.ts +8 -0
- package/out/shell.js +16 -0
- package/package.json +30 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
Copyright 2023 ArkType
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
4
|
+
|
|
5
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/out/caller.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export type GetCallStackOptions = {
|
|
2
|
+
offset?: number;
|
|
3
|
+
};
|
|
4
|
+
export declare const getCallStack: ({ offset }?: GetCallStackOptions) => string[];
|
|
5
|
+
export type LinePosition = {
|
|
6
|
+
line: number;
|
|
7
|
+
char: number;
|
|
8
|
+
};
|
|
9
|
+
export type SourcePosition = LinePosition & {
|
|
10
|
+
file: string;
|
|
11
|
+
method: string;
|
|
12
|
+
};
|
|
13
|
+
export type CallerOfOptions = {
|
|
14
|
+
formatPath?: FormatFilePathOptions;
|
|
15
|
+
upStackBy?: number;
|
|
16
|
+
skip?: (position: SourcePosition) => boolean;
|
|
17
|
+
methodName?: string;
|
|
18
|
+
};
|
|
19
|
+
export type FormatFilePathOptions = {
|
|
20
|
+
relative?: string | boolean;
|
|
21
|
+
separator?: string;
|
|
22
|
+
};
|
|
23
|
+
export declare const positionToString: (position: SourcePosition) => string;
|
|
24
|
+
export declare const formatFilePath: (original: string, { relative, separator }: FormatFilePathOptions) => string;
|
|
25
|
+
export declare const caller: (options?: CallerOfOptions) => SourcePosition;
|
|
26
|
+
export declare const callsAgo: (num: number, options?: Omit<CallerOfOptions, "upStackBy">) => SourcePosition;
|
package/out/caller.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import * as process from "node:process";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { isDeepStrictEqual } from "node:util";
|
|
5
|
+
import { getCurrentLine, getFramesFromError } from "./getCurrentLine.js";
|
|
6
|
+
export const getCallStack = ({ offset = 0 } = {}) => {
|
|
7
|
+
const frames = getFramesFromError(new Error());
|
|
8
|
+
frames.splice(1, 1 + offset);
|
|
9
|
+
return frames;
|
|
10
|
+
};
|
|
11
|
+
const nonexistentCurrentLine = {
|
|
12
|
+
line: -1,
|
|
13
|
+
char: -1,
|
|
14
|
+
method: "",
|
|
15
|
+
file: ""
|
|
16
|
+
};
|
|
17
|
+
export const positionToString = (position) => `line ${position.line}, character ${position.char} at path '${position.file}'`;
|
|
18
|
+
export const formatFilePath = (original, { relative, separator }) => {
|
|
19
|
+
let formatted = original;
|
|
20
|
+
if (original.startsWith("file:///"))
|
|
21
|
+
formatted = fileURLToPath(original);
|
|
22
|
+
if (relative) {
|
|
23
|
+
formatted = path.relative(typeof relative === "string" ? relative : process.cwd(), formatted);
|
|
24
|
+
}
|
|
25
|
+
if (separator)
|
|
26
|
+
formatted = formatted.replace(new RegExp(`\\${path.sep}`, "g"), separator);
|
|
27
|
+
return formatted;
|
|
28
|
+
};
|
|
29
|
+
export const caller = (options = {}) => {
|
|
30
|
+
let upStackBy = options.upStackBy ?? 0;
|
|
31
|
+
if (!options.methodName && !options.upStackBy)
|
|
32
|
+
upStackBy = 3;
|
|
33
|
+
let match;
|
|
34
|
+
while (!match) {
|
|
35
|
+
const location = getCurrentLine({
|
|
36
|
+
method: options.methodName,
|
|
37
|
+
frames: upStackBy
|
|
38
|
+
});
|
|
39
|
+
if (!location || isDeepStrictEqual(location, nonexistentCurrentLine)) {
|
|
40
|
+
throw new Error(`No caller of '${options.methodName}' matches given options: ${JSON.stringify(options, null, 4)}.`);
|
|
41
|
+
}
|
|
42
|
+
const candidate = {
|
|
43
|
+
...location,
|
|
44
|
+
file: formatFilePath(location.file, options.formatPath ?? {})
|
|
45
|
+
};
|
|
46
|
+
if (options.skip?.(candidate))
|
|
47
|
+
upStackBy++;
|
|
48
|
+
else
|
|
49
|
+
match = candidate;
|
|
50
|
+
}
|
|
51
|
+
if (match.file.startsWith("file:///"))
|
|
52
|
+
match.file = fileURLToPath(match.file);
|
|
53
|
+
return match;
|
|
54
|
+
};
|
|
55
|
+
export const callsAgo = (num, options = {}) => caller({ methodName: "callsAgo", upStackBy: num, ...options });
|
package/out/fs.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export { rmSync } from "node:fs";
|
|
2
|
+
export declare const ensureDir: (path: string) => string;
|
|
3
|
+
export declare const readFile: (path: string) => string;
|
|
4
|
+
export declare const writeFile: (path: string, contents: string) => void;
|
|
5
|
+
export declare const readJson: (path: string) => any;
|
|
6
|
+
export declare const writeJson: (path: string, data: object) => void;
|
|
7
|
+
export declare const rmRf: (target: string) => void;
|
|
8
|
+
export declare const cpR: (from: string, to: string) => void;
|
|
9
|
+
export type JsonTransformer = (data: object) => object;
|
|
10
|
+
export declare const rewriteJson: (path: string, transform: JsonTransformer) => void;
|
|
11
|
+
export type WalkOptions = {
|
|
12
|
+
ignoreDirsMatching?: RegExp;
|
|
13
|
+
ignoreFilesMatching?: RegExp;
|
|
14
|
+
excludeFiles?: boolean;
|
|
15
|
+
excludeDirs?: boolean;
|
|
16
|
+
exclude?: (path: string) => boolean;
|
|
17
|
+
include?: (path: string) => boolean;
|
|
18
|
+
};
|
|
19
|
+
export declare const walkPaths: (dir: string, options?: WalkOptions) => string[];
|
|
20
|
+
/** Fetch the file and directory paths from a path, uri, or `import.meta.url` */
|
|
21
|
+
export declare const filePath: (path: string) => string;
|
|
22
|
+
export declare const fileName: () => string;
|
|
23
|
+
export declare const dirName: () => string;
|
|
24
|
+
export declare const fromHere: (...joinWith: string[]) => string;
|
|
25
|
+
export declare const fromCwd: (...joinWith: string[]) => string;
|
|
26
|
+
export declare const fromHome: (...joinWith: string[]) => string;
|
|
27
|
+
export declare const fsRoot: string;
|
|
28
|
+
export declare const findPackageRoot: (fromDir?: string) => string;
|
|
29
|
+
export declare const fromPackageRoot: (...joinWith: string[]) => string;
|
|
30
|
+
export declare const readPackageJson: (startDir?: string) => any;
|
|
31
|
+
export declare const getSourceControlPaths: () => string[];
|
|
32
|
+
export declare const tsFileMatcher: RegExp;
|
|
33
|
+
export declare const getSourceFilePaths: (dir?: string) => string[];
|
|
34
|
+
export type SourceFileEntry = [path: string, contents: string];
|
|
35
|
+
export declare const getSourceFileEntries: (dir?: string) => SourceFileEntry[];
|
|
36
|
+
export type ReplacementDictionary = Record<string, {
|
|
37
|
+
pattern: RegExp;
|
|
38
|
+
replacement: `"${string}"`;
|
|
39
|
+
}>;
|
|
40
|
+
export type Matchers = ReadonlyArray<Matcher>;
|
|
41
|
+
export type Matcher = {
|
|
42
|
+
pattern: RegExp;
|
|
43
|
+
replacement: string;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Given a directory and a set of {@link Matchers}, recursively walks
|
|
47
|
+
* the directory and applies every set of changes in the dictionary
|
|
48
|
+
* to all files except those matching `ignoreFilesMatching`.
|
|
49
|
+
*/
|
|
50
|
+
export declare const findReplaceAll: (matchDictionary: ReplacementDictionary, ignoreFilesMatching: RegExp) => (dirPath: string) => void;
|
package/out/fs.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, join, parse } from "node:path";
|
|
4
|
+
import * as process from "node:process";
|
|
5
|
+
import { URL, fileURLToPath } from "node:url";
|
|
6
|
+
import { caller } from "./caller.js";
|
|
7
|
+
import { getShellOutput } from "./shell.js";
|
|
8
|
+
export { rmSync } from "node:fs";
|
|
9
|
+
export const ensureDir = (path) => {
|
|
10
|
+
if (existsSync(path)) {
|
|
11
|
+
if (!statSync(path).isDirectory())
|
|
12
|
+
throw new Error(`${path} exists and is not a directory.`);
|
|
13
|
+
}
|
|
14
|
+
else
|
|
15
|
+
mkdirSync(path, { recursive: true });
|
|
16
|
+
return path;
|
|
17
|
+
};
|
|
18
|
+
export const readFile = (path) => readFileSync(path).toString();
|
|
19
|
+
export const writeFile = (path, contents) => writeFileSync(path, contents);
|
|
20
|
+
export const readJson = (path) => JSON.parse(readFileSync(path, { encoding: "utf8" }));
|
|
21
|
+
export const writeJson = (path, data) => writeFileSync(path, `${JSON.stringify(data, null, 4)}\n`);
|
|
22
|
+
export const rmRf = (target) => rmSync(target, { recursive: true, force: true });
|
|
23
|
+
export const cpR = (from, to) => cpSync(from, to, { recursive: true, force: true });
|
|
24
|
+
export const rewriteJson = (path, transform) => writeJson(path, transform(readJson(path)));
|
|
25
|
+
export const walkPaths = (dir, options = {}) => readdirSync(dir).reduce((paths, item) => {
|
|
26
|
+
const path = join(dir, item);
|
|
27
|
+
const isDir = lstatSync(path).isDirectory();
|
|
28
|
+
const isFile = lstatSync(path).isFile();
|
|
29
|
+
if (isDir && options.ignoreDirsMatching?.test(path))
|
|
30
|
+
return paths;
|
|
31
|
+
if (isFile && options.ignoreFilesMatching?.test(path))
|
|
32
|
+
return paths;
|
|
33
|
+
const excludeCurrent = (options.excludeDirs && isDir) ||
|
|
34
|
+
(options.excludeFiles && !isDir) ||
|
|
35
|
+
options.exclude?.(path) ||
|
|
36
|
+
(options.include && !options.include(path));
|
|
37
|
+
const nestedPaths = isDir ? walkPaths(path, options) : [];
|
|
38
|
+
paths.push(...(excludeCurrent ? [] : [path]), ...nestedPaths);
|
|
39
|
+
return paths;
|
|
40
|
+
}, []);
|
|
41
|
+
/** Fetch the file and directory paths from a path, uri, or `import.meta.url` */
|
|
42
|
+
export const filePath = (path) => {
|
|
43
|
+
let file;
|
|
44
|
+
if (path.includes("://")) {
|
|
45
|
+
// is a url, e.g. file://, or https://
|
|
46
|
+
const url = new URL(path);
|
|
47
|
+
file = url.protocol === "file:" ? fileURLToPath(url) : url.href;
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
// is already a typical path
|
|
51
|
+
file = path;
|
|
52
|
+
}
|
|
53
|
+
return file;
|
|
54
|
+
};
|
|
55
|
+
const fileOfCaller = () => filePath(caller({ methodName: "fileOfCaller", upStackBy: 1 }).file);
|
|
56
|
+
const dirOfCaller = () => dirname(filePath(caller({ methodName: "dirOfCaller", upStackBy: 1 }).file));
|
|
57
|
+
export const fileName = () => fileOfCaller();
|
|
58
|
+
export const dirName = () => dirOfCaller();
|
|
59
|
+
export const fromHere = (...joinWith) => join(dirOfCaller(), ...joinWith);
|
|
60
|
+
export const fromCwd = (...joinWith) => join(process.cwd(), ...joinWith);
|
|
61
|
+
export const fromHome = (...joinWith) => join(homedir(), ...joinWith);
|
|
62
|
+
export const fsRoot = parse(process.cwd()).root;
|
|
63
|
+
export const findPackageRoot = (fromDir) => {
|
|
64
|
+
const startDir = fromDir ?? dirOfCaller();
|
|
65
|
+
let dirToCheck = startDir;
|
|
66
|
+
while (dirToCheck !== fsRoot) {
|
|
67
|
+
try {
|
|
68
|
+
const contents = readJson(join(dirToCheck, "package.json"));
|
|
69
|
+
/*
|
|
70
|
+
* If the file is just a stub with no package name, don't consider
|
|
71
|
+
* it a package root
|
|
72
|
+
*/
|
|
73
|
+
if ("name" in contents)
|
|
74
|
+
return dirToCheck;
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
// If the file doesn't exist, go up another level
|
|
78
|
+
}
|
|
79
|
+
dirToCheck = join(dirToCheck, "..");
|
|
80
|
+
}
|
|
81
|
+
throw new Error(`${startDir} is not part of a node package.`);
|
|
82
|
+
};
|
|
83
|
+
export const fromPackageRoot = (...joinWith) => join(findPackageRoot(dirOfCaller()), ...joinWith);
|
|
84
|
+
export const readPackageJson = (startDir) => readJson(join(findPackageRoot(startDir), "package.json"));
|
|
85
|
+
export const getSourceControlPaths = () =>
|
|
86
|
+
// include tracked and untracked files as long as they are not ignored
|
|
87
|
+
getShellOutput("git ls-files --exclude-standard --cached --others")
|
|
88
|
+
.split("\n")
|
|
89
|
+
.filter(path => existsSync(path) && statSync(path).isFile());
|
|
90
|
+
export const tsFileMatcher = /^.*\.(c|m)?tsx?$/;
|
|
91
|
+
const inFileFilter = {
|
|
92
|
+
include: path => tsFileMatcher.test(path),
|
|
93
|
+
ignoreDirsMatching: /node_modules|out|dist|docgen/
|
|
94
|
+
};
|
|
95
|
+
export const getSourceFilePaths = (dir = ".") => walkPaths(dir, inFileFilter);
|
|
96
|
+
export const getSourceFileEntries = (dir = ".") => getSourceFilePaths(dir).map(path => [path, readFile(path)]);
|
|
97
|
+
/**
|
|
98
|
+
* Given a set of {@link Matchers} and an input string,
|
|
99
|
+
* replace all will replace
|
|
100
|
+
*/
|
|
101
|
+
const findReplace = matchers => input => matchers.reduce((acc, m) => acc.replaceAll(m.pattern, m.replacement), input);
|
|
102
|
+
/**
|
|
103
|
+
* Applies a set of {@link Matchers} to a list of files and rewrites
|
|
104
|
+
* each file's contents according to the provided `Matcher["find"]`
|
|
105
|
+
* and `Matcher["replace"]`.
|
|
106
|
+
*/
|
|
107
|
+
const findReplaceMany = (matchers) => (files = []) => void files.forEach(file => {
|
|
108
|
+
writeFile(file, findReplace(matchers)(readFile(file)));
|
|
109
|
+
});
|
|
110
|
+
/**
|
|
111
|
+
* Given a directory and a set of {@link Matchers}, recursively walks
|
|
112
|
+
* the directory and applies every set of changes in the dictionary
|
|
113
|
+
* to all files except those matching `ignoreFilesMatching`.
|
|
114
|
+
*/
|
|
115
|
+
export const findReplaceAll = (matchDictionary, ignoreFilesMatching) => (dirPath) => {
|
|
116
|
+
const files = walkPaths(dirPath, {
|
|
117
|
+
excludeDirs: true,
|
|
118
|
+
ignoreFilesMatching
|
|
119
|
+
});
|
|
120
|
+
const matchers = Object.values(matchDictionary);
|
|
121
|
+
findReplaceMany(matchers)(files);
|
|
122
|
+
};
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/** The combination of location information about the line that was executing at the time */
|
|
2
|
+
export type Location = {
|
|
3
|
+
/** the location of the line that was executing at the time */
|
|
4
|
+
line: number;
|
|
5
|
+
/** the location of the character that was executing at the time */
|
|
6
|
+
char: number;
|
|
7
|
+
/** the method name that was executing at the time */
|
|
8
|
+
method: string;
|
|
9
|
+
/** the file path that was executing at the time */
|
|
10
|
+
file: string;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* If provided, continue skipping until:
|
|
14
|
+
*
|
|
15
|
+
* 1. The file or method is found
|
|
16
|
+
* 2. Once found, will continue until neither the file nor method are found anymore
|
|
17
|
+
* 3. Once exited, the frame offset will then apply
|
|
18
|
+
*
|
|
19
|
+
* If you wish to capture the found method or the file, combine them with `frames: -1` or `immediate: true`.
|
|
20
|
+
*
|
|
21
|
+
* If you wish for more customisation than this, create an issue requesting passing a custom skip handler function, as more variance to this interface is too much customisation complexity.
|
|
22
|
+
*/
|
|
23
|
+
type Offset = {
|
|
24
|
+
/**
|
|
25
|
+
* if provided, continue until a method containing or matching this string is exited
|
|
26
|
+
* if provided alongside a file, will continue until neither the file nor method are found
|
|
27
|
+
* this allows file and method to act as fallbacks for each other, such that if one is not found, it doesn't skip everything
|
|
28
|
+
*/
|
|
29
|
+
method?: RegExp | string | null;
|
|
30
|
+
/**
|
|
31
|
+
* if provided, continue until a file containing or matching this string is exited
|
|
32
|
+
* if provided alongside a method, will continue until neither the file nor method are found
|
|
33
|
+
* this allows file and method to act as fallbacks for each other, such that if one is not found, it doesn't skip everything
|
|
34
|
+
*/
|
|
35
|
+
file?: RegExp | string | null;
|
|
36
|
+
/**
|
|
37
|
+
* once we have satisfied the found condition, if any, then apply this index offset to the frames
|
|
38
|
+
* e.g. 1 would mean next frame, and -1 would mean the previous frame
|
|
39
|
+
* Use -1 to go back to the found method or file
|
|
40
|
+
*/
|
|
41
|
+
frames?: number;
|
|
42
|
+
/**
|
|
43
|
+
* once we have satisfied the found condition, should we apply the frame offset immediately, or wait until the found condition has exited
|
|
44
|
+
*/
|
|
45
|
+
immediate?: boolean;
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* For an error instance, return its stack frames as an array.
|
|
49
|
+
*/
|
|
50
|
+
export declare const getFramesFromError: (error: Error) => string[];
|
|
51
|
+
/**
|
|
52
|
+
* Get the location information about the line that called this method.
|
|
53
|
+
* If no offset is provided, then continue until the caller of the `getCurrentLine` is found.
|
|
54
|
+
* @example Input
|
|
55
|
+
* ``` javascript
|
|
56
|
+
* console.log(getCurrentLine())
|
|
57
|
+
* ```
|
|
58
|
+
* @example Result
|
|
59
|
+
* ``` json
|
|
60
|
+
* {
|
|
61
|
+
* "line": "1",
|
|
62
|
+
* "char": "12",
|
|
63
|
+
* "method": "Object.<anonymous>",
|
|
64
|
+
* "file": "/Users/balupton/some-project/calling-file.js"
|
|
65
|
+
* }
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
68
|
+
export declare const getCurrentLine: (offset?: Offset) => Location;
|
|
69
|
+
export {};
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// Copied from unmaintained package https://github.com/bevry/get-current-line to fix imports
|
|
2
|
+
/**
|
|
3
|
+
* For an error instance, return its stack frames as an array.
|
|
4
|
+
*/
|
|
5
|
+
export const getFramesFromError = (error) => {
|
|
6
|
+
// Create an error
|
|
7
|
+
let stack, frames;
|
|
8
|
+
// And attempt to retrieve it's stack
|
|
9
|
+
// https://github.com/winstonjs/winston/issues/401#issuecomment-61913086
|
|
10
|
+
try {
|
|
11
|
+
stack = error.stack;
|
|
12
|
+
}
|
|
13
|
+
catch (error1) {
|
|
14
|
+
try {
|
|
15
|
+
/** @ts-expect-error https://github.com/winstonjs/winston/issues/401#issuecomment-61913086 */
|
|
16
|
+
const previous = err.__previous__ || err.__previous;
|
|
17
|
+
stack = previous && previous.stack;
|
|
18
|
+
}
|
|
19
|
+
catch (error2) {
|
|
20
|
+
stack = null;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
// Handle different stack formats
|
|
24
|
+
if (stack) {
|
|
25
|
+
if (Array.isArray(stack))
|
|
26
|
+
frames = Array(stack);
|
|
27
|
+
else
|
|
28
|
+
frames = stack.toString().split("\n");
|
|
29
|
+
}
|
|
30
|
+
else
|
|
31
|
+
frames = [];
|
|
32
|
+
// Parse our frames
|
|
33
|
+
return frames;
|
|
34
|
+
};
|
|
35
|
+
const lineRegex = /\s+at\s(?:(?<method>.+?)\s\()?(?<file>.+?):(?<line>\d+):(?<char>\d+)\)?\s*$/;
|
|
36
|
+
/**
|
|
37
|
+
* Get the locations from a list of error stack frames.
|
|
38
|
+
*/
|
|
39
|
+
const getLocationsFromFrames = (frames) => {
|
|
40
|
+
// Prepare
|
|
41
|
+
const locations = [];
|
|
42
|
+
// Cycle through the lines
|
|
43
|
+
for (const frame of frames) {
|
|
44
|
+
// ensure each line is a string
|
|
45
|
+
const line = (frame || "").toString();
|
|
46
|
+
// skip empty lines
|
|
47
|
+
if (line.length === 0)
|
|
48
|
+
continue;
|
|
49
|
+
// Error
|
|
50
|
+
// at file:///Users/balupton/Projects/active/get-current-line/asd.js:1:13
|
|
51
|
+
// at ModuleJob.run (internal/modules/esm/module_job.js:140:23)
|
|
52
|
+
// at async Loader.import (internal/modules/esm/loader.js:165:24)
|
|
53
|
+
// at async Object.loadESM (internal/process/esm_loader.js:68:5)
|
|
54
|
+
const match = line.match(lineRegex);
|
|
55
|
+
if (match && match.groups) {
|
|
56
|
+
locations.push({
|
|
57
|
+
method: match.groups.method || "",
|
|
58
|
+
file: match.groups.file || "",
|
|
59
|
+
line: Number(match.groups.line),
|
|
60
|
+
char: Number(match.groups.char)
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return locations;
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* If a location is not found, this is the result that is used.
|
|
68
|
+
*/
|
|
69
|
+
const failureLocation = {
|
|
70
|
+
line: -1,
|
|
71
|
+
char: -1,
|
|
72
|
+
method: "",
|
|
73
|
+
file: ""
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* From a list of locations, get the location that is determined by the offset.
|
|
77
|
+
* If none are found, return the failure location
|
|
78
|
+
*/
|
|
79
|
+
const getLocationWithOffset = (locations, offset) => {
|
|
80
|
+
// Continue
|
|
81
|
+
let found = !offset.file && !offset.method;
|
|
82
|
+
// use while loop so we can skip ahead
|
|
83
|
+
let i = 0;
|
|
84
|
+
while (i < locations.length) {
|
|
85
|
+
const location = locations[i];
|
|
86
|
+
// the current location matches the offset
|
|
87
|
+
if ((offset.file &&
|
|
88
|
+
(typeof offset.file === "string" ?
|
|
89
|
+
location.file.includes(offset.file)
|
|
90
|
+
: offset.file.test(location.file))) ||
|
|
91
|
+
(offset.method &&
|
|
92
|
+
(typeof offset.method === "string" ?
|
|
93
|
+
location.method.includes(offset.method)
|
|
94
|
+
: offset.method.test(location.method)))) {
|
|
95
|
+
// we are found, and we should exit immediatelyg, so return with the frame offset applied
|
|
96
|
+
if (offset.immediate) {
|
|
97
|
+
// apply frame offset
|
|
98
|
+
i += offset.frames || 0;
|
|
99
|
+
// and return the result
|
|
100
|
+
return locations[i];
|
|
101
|
+
}
|
|
102
|
+
// otherwise, continue until the found condition has exited
|
|
103
|
+
else {
|
|
104
|
+
found = true;
|
|
105
|
+
++i;
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
// has been found, and the found condition has exited, so return with the frame offset applied
|
|
110
|
+
else if (found) {
|
|
111
|
+
// apply frame offset
|
|
112
|
+
i += offset.frames || 0;
|
|
113
|
+
// and return the result
|
|
114
|
+
return locations[i];
|
|
115
|
+
}
|
|
116
|
+
// nothing has been found yet, so continue until we find the offset
|
|
117
|
+
else {
|
|
118
|
+
++i;
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
// return failure
|
|
123
|
+
return failureLocation;
|
|
124
|
+
};
|
|
125
|
+
/**
|
|
126
|
+
* Get each error stack frame's location information.
|
|
127
|
+
*/
|
|
128
|
+
const getLocationsFromError = (error) => {
|
|
129
|
+
const frames = getFramesFromError(error);
|
|
130
|
+
return getLocationsFromFrames(frames);
|
|
131
|
+
};
|
|
132
|
+
/**
|
|
133
|
+
* Get first determined location information that appears in the stack of the error.
|
|
134
|
+
* If no offset is provided, then the offset used will determine the first location information.
|
|
135
|
+
*/
|
|
136
|
+
const getLocationFromError = (error, offset = {
|
|
137
|
+
immediate: true
|
|
138
|
+
}) => {
|
|
139
|
+
const locations = getLocationsFromError(error);
|
|
140
|
+
return getLocationWithOffset(locations, offset);
|
|
141
|
+
};
|
|
142
|
+
/**
|
|
143
|
+
* Get the location information about the line that called this method.
|
|
144
|
+
* If no offset is provided, then continue until the caller of the `getCurrentLine` is found.
|
|
145
|
+
* @example Input
|
|
146
|
+
* ``` javascript
|
|
147
|
+
* console.log(getCurrentLine())
|
|
148
|
+
* ```
|
|
149
|
+
* @example Result
|
|
150
|
+
* ``` json
|
|
151
|
+
* {
|
|
152
|
+
* "line": "1",
|
|
153
|
+
* "char": "12",
|
|
154
|
+
* "method": "Object.<anonymous>",
|
|
155
|
+
* "file": "/Users/balupton/some-project/calling-file.js"
|
|
156
|
+
* }
|
|
157
|
+
* ```
|
|
158
|
+
*/
|
|
159
|
+
export const getCurrentLine = (offset = {
|
|
160
|
+
method: "getCurrentLine",
|
|
161
|
+
frames: 0,
|
|
162
|
+
immediate: false
|
|
163
|
+
}) => getLocationFromError(new Error(), offset);
|
package/out/index.d.ts
ADDED
package/out/index.js
ADDED
package/out/shell.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type ExecSyncOptions } from "node:child_process";
|
|
2
|
+
export type ShellOptions = Omit<ExecSyncOptions, "stdio"> & {
|
|
3
|
+
env?: Record<string, string | undefined>;
|
|
4
|
+
};
|
|
5
|
+
/** Run the cmd synchronously. Output goes to terminal. */
|
|
6
|
+
export declare const shell: (cmd: string, { env, ...otherOptions }?: ShellOptions) => void;
|
|
7
|
+
/** Run the cmd synchronously, returning output as a string */
|
|
8
|
+
export declare const getShellOutput: (cmd: string, { env, ...otherOptions }?: ShellOptions) => string;
|
package/out/shell.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { execSync } from "node:child_process";
|
|
2
|
+
import * as process from "node:process";
|
|
3
|
+
/** Run the cmd synchronously. Output goes to terminal. */
|
|
4
|
+
export const shell = (cmd, { env, ...otherOptions } = {}) => {
|
|
5
|
+
execSync(cmd, {
|
|
6
|
+
env: { ...process.env, ...env },
|
|
7
|
+
...otherOptions,
|
|
8
|
+
stdio: "inherit"
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
/** Run the cmd synchronously, returning output as a string */
|
|
12
|
+
export const getShellOutput = (cmd, { env, ...otherOptions } = {}) => execSync(cmd, {
|
|
13
|
+
env: { ...process.env, ...env },
|
|
14
|
+
...otherOptions,
|
|
15
|
+
stdio: "pipe"
|
|
16
|
+
}).toString();
|
package/package.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@ark/fs",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"author": {
|
|
5
|
+
"name": "David Blass",
|
|
6
|
+
"email": "david@arktype.io",
|
|
7
|
+
"url": "https://arktype.io"
|
|
8
|
+
},
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "https://github.com/arktypeio/arktype.git",
|
|
12
|
+
"directory": "ark/fs"
|
|
13
|
+
},
|
|
14
|
+
"type": "module",
|
|
15
|
+
"main": "./out/index.js",
|
|
16
|
+
"types": "./out/index.d.ts",
|
|
17
|
+
"exports": {
|
|
18
|
+
".": "./out/index.js",
|
|
19
|
+
"./internal/*": "./out/*"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"out"
|
|
23
|
+
],
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"scripts": {
|
|
28
|
+
"build": "tsx ../repo/build.ts"
|
|
29
|
+
}
|
|
30
|
+
}
|