forked from conventional-changelog/commitlint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathload-parser-opts.ts
83 lines (73 loc) · 2.08 KB
/
load-parser-opts.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
import {ParserPreset} from '@commitlint/types';
type Awaitable<T> = T | PromiseLike<T>;
function isObjectLike(obj: unknown): obj is Record<string, unknown> {
return Boolean(obj) && typeof obj === 'object'; // typeof null === 'object'
}
function isParserOptsFunction<T extends ParserPreset>(
obj: T
): obj is T & {
parserOpts: (
cb: (_: never, parserOpts: Record<string, unknown>) => unknown
) => Record<string, unknown> | undefined;
} {
return typeof obj.parserOpts === 'function';
}
export async function loadParserOpts(
pendingParser:
| string
| Awaitable<ParserPreset>
| (() => Awaitable<ParserPreset>)
| undefined
): Promise<ParserPreset | undefined> {
if (typeof pendingParser === 'function') {
return loadParserOpts(pendingParser());
}
if (!pendingParser || typeof pendingParser !== 'object') {
return undefined;
}
// Await for the module, loaded with require
const parser = await pendingParser;
// exit early, no opts to resolve
if (!parser.parserOpts) {
return parser;
}
// Pull nested parserOpts, might happen if overwritten with a module in main config
if (typeof parser.parserOpts === 'object') {
// Await parser opts if applicable
parser.parserOpts = await parser.parserOpts;
if (
isObjectLike(parser.parserOpts) &&
isObjectLike(parser.parserOpts.parserOpts)
) {
parser.parserOpts = parser.parserOpts.parserOpts;
}
return parser;
}
// Create parser opts from factory
if (
isParserOptsFunction(parser) &&
typeof parser.name === 'string' &&
parser.name.startsWith('conventional-changelog-')
) {
return new Promise((resolve) => {
const result = parser.parserOpts((_: never, opts) => {
resolve({
...parser,
parserOpts: opts?.parserOpts,
});
});
// If result has data or a promise, the parser doesn't support factory-init
// due to https://github.com/nodejs/promises-debugging/issues/16 it just quits, so let's use this fallback
if (result) {
Promise.resolve(result).then((opts) => {
resolve({
...parser,
parserOpts: opts?.parserOpts,
});
});
}
return;
});
}
return parser;
}