/
util.ts
87 lines (78 loc) · 2.1 KB
/
util.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import {
createRequire as nodeCreateRequire,
createRequireFromPath as nodeCreateRequireFromPath,
} from 'module';
import type _createRequire from 'create-require';
import * as ynModule from 'yn';
/** @internal */
export const createRequire =
nodeCreateRequire ??
nodeCreateRequireFromPath ??
(require('create-require') as typeof _createRequire);
/**
* Wrapper around yn module that returns `undefined` instead of `null`.
* This is implemented by yn v4, but we're staying on v3 to avoid v4's node 10 requirement.
* @internal
*/
export function yn(value: string | undefined) {
return ynModule(value) ?? undefined;
}
/**
* Like `Object.assign`, but ignores `undefined` properties.
*
* @internal
*/
export function assign<T extends object>(
initialValue: T,
...sources: Array<T>
): T {
for (const source of sources) {
for (const key of Object.keys(source)) {
const value = (source as any)[key];
if (value !== undefined) (initialValue as any)[key] = value;
}
}
return initialValue;
}
/**
* Split a string array of values.
* @internal
*/
export function split(value: string | undefined) {
return typeof value === 'string' ? value.split(/ *, */g) : undefined;
}
/**
* Parse a string as JSON.
* @internal
*/
export function parse(value: string | undefined): object | undefined {
return typeof value === 'string' ? JSON.parse(value) : undefined;
}
const directorySeparator = '/';
const backslashRegExp = /\\/g;
/**
* Replace backslashes with forward slashes.
* @internal
*/
export function normalizeSlashes(value: string): string {
return value.replace(backslashRegExp, directorySeparator);
}
/**
* Cached fs operation wrapper.
*/
export function cachedLookup<T, R>(fn: (arg: T) => R): (arg: T) => R {
const cache = new Map<T, R>();
return (arg: T): R => {
if (!cache.has(arg)) {
const v = fn(arg);
cache.set(arg, v);
return v;
}
return cache.get(arg)!;
};
}
/**
* We do not support ts's `trace` option yet. In the meantime, rather than omit
* `trace` options in hosts, I am using this placeholder.
*/
export function trace(s: string): void {}