-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
host-rules.ts
103 lines (93 loc) · 2.67 KB
/
host-rules.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import {
GITHUB_API_USING_HOST_TYPES,
GITLAB_API_USING_HOST_TYPES,
PlatformId,
} from '../../constants';
import { logger } from '../../logger';
import { hasProxy } from '../../proxy';
import type { HostRule } from '../../types';
import * as hostRules from '../host-rules';
import type { GotOptions } from './types';
function findMatchingRules(options: GotOptions, url: string): HostRule {
const { hostType } = options;
let res = hostRules.find({ hostType, url });
if (res.token || res.username || res.password) {
// do not fallback if we already have auth infos
return res;
}
// Fallback to `github` hostType
if (
hostType &&
GITHUB_API_USING_HOST_TYPES.includes(hostType) &&
hostType !== PlatformId.Github
) {
res = {
...hostRules.find({
hostType: PlatformId.Github,
url,
}),
...res,
};
}
// Fallback to `gitlab` hostType
if (
hostType &&
GITLAB_API_USING_HOST_TYPES.includes(hostType) &&
hostType !== PlatformId.Gitlab
) {
res = {
...hostRules.find({
hostType: PlatformId.Gitlab,
url,
}),
...res,
};
}
return res;
}
// Apply host rules to requests
export function applyHostRules(url: string, inOptions: GotOptions): GotOptions {
const options: GotOptions = { ...inOptions };
const foundRules = findMatchingRules(options, url);
const { username, password, token, enabled, authType } = foundRules;
if (options.noAuth) {
logger.trace({ url }, `Authorization disabled`);
} else if (
options.headers?.authorization ||
options.password ||
options.token
) {
logger.trace({ url }, `Authorization already set`);
} else if (password !== undefined) {
logger.trace({ url }, `Applying Basic authentication`);
options.username = username;
options.password = password;
} else if (token) {
logger.trace({ url }, `Applying Bearer authentication`);
options.token = token;
options.context = { ...options.context, authType };
} else if (enabled === false) {
options.enabled = false;
}
// Apply optional params
if (foundRules.abortOnError) {
options.abortOnError = foundRules.abortOnError;
}
if (foundRules.abortIgnoreStatusCodes) {
options.abortIgnoreStatusCodes = foundRules.abortIgnoreStatusCodes;
}
if (foundRules.timeout) {
options.timeout = foundRules.timeout;
}
if (!hasProxy() && foundRules.enableHttp2 === true) {
options.http2 = true;
}
return options;
}
export function getRequestLimit(url: string): number | null {
const hostRule = hostRules.find({
url,
});
const limit = hostRule.concurrentRequestLimit;
return typeof limit === 'number' && limit > 0 ? limit : null;
}