Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/build/lib/fetch.ts
3520 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import es from 'event-stream';
7
import VinylFile from 'vinyl';
8
import log from 'fancy-log';
9
import ansiColors from 'ansi-colors';
10
import crypto from 'crypto';
11
import through2 from 'through2';
12
import { Stream } from 'stream';
13
14
export interface IFetchOptions {
15
base?: string;
16
nodeFetchOptions?: RequestInit;
17
verbose?: boolean;
18
checksumSha256?: string;
19
}
20
21
export function fetchUrls(urls: string[] | string, options: IFetchOptions): es.ThroughStream {
22
if (options === undefined) {
23
options = {};
24
}
25
26
if (typeof options.base !== 'string' && options.base !== null) {
27
options.base = '/';
28
}
29
30
if (!Array.isArray(urls)) {
31
urls = [urls];
32
}
33
34
return es.readArray(urls).pipe(es.map<string, VinylFile | void>((data: string, cb) => {
35
const url = [options.base, data].join('');
36
fetchUrl(url, options).then(file => {
37
cb(undefined, file);
38
}, error => {
39
cb(error);
40
});
41
}));
42
}
43
44
export async function fetchUrl(url: string, options: IFetchOptions, retries = 10, retryDelay = 1000): Promise<VinylFile> {
45
const verbose = !!options.verbose || !!process.env['CI'] || !!process.env['BUILD_ARTIFACTSTAGINGDIRECTORY'] || !!process.env['GITHUB_WORKSPACE'];
46
try {
47
let startTime = 0;
48
if (verbose) {
49
log(`Start fetching ${ansiColors.magenta(url)}${retries !== 10 ? ` (${10 - retries} retry)` : ''}`);
50
startTime = new Date().getTime();
51
}
52
const controller = new AbortController();
53
const timeout = setTimeout(() => controller.abort(), 30 * 1000);
54
try {
55
const response = await fetch(url, {
56
...options.nodeFetchOptions,
57
signal: controller.signal as any /* Typings issue with lib.dom.d.ts */
58
});
59
if (verbose) {
60
log(`Fetch completed: Status ${response.status}. Took ${ansiColors.magenta(`${new Date().getTime() - startTime} ms`)}`);
61
}
62
if (response.ok && (response.status >= 200 && response.status < 300)) {
63
const contents = Buffer.from(await response.arrayBuffer());
64
if (options.checksumSha256) {
65
const actualSHA256Checksum = crypto.createHash('sha256').update(contents).digest('hex');
66
if (actualSHA256Checksum !== options.checksumSha256) {
67
throw new Error(`Checksum mismatch for ${ansiColors.cyan(url)} (expected ${options.checksumSha256}, actual ${actualSHA256Checksum}))`);
68
} else if (verbose) {
69
log(`Verified SHA256 checksums match for ${ansiColors.cyan(url)}`);
70
}
71
} else if (verbose) {
72
log(`Skipping checksum verification for ${ansiColors.cyan(url)} because no expected checksum was provided`);
73
}
74
if (verbose) {
75
log(`Fetched response body buffer: ${ansiColors.magenta(`${(contents as Buffer).byteLength} bytes`)}`);
76
}
77
return new VinylFile({
78
cwd: '/',
79
base: options.base,
80
path: url,
81
contents
82
});
83
}
84
let err = `Request ${ansiColors.magenta(url)} failed with status code: ${response.status}`;
85
if (response.status === 403) {
86
err += ' (you may be rate limited)';
87
}
88
throw new Error(err);
89
} finally {
90
clearTimeout(timeout);
91
}
92
} catch (e) {
93
if (verbose) {
94
log(`Fetching ${ansiColors.cyan(url)} failed: ${e}`);
95
}
96
if (retries > 0) {
97
await new Promise(resolve => setTimeout(resolve, retryDelay));
98
return fetchUrl(url, options, retries - 1, retryDelay);
99
}
100
throw e;
101
}
102
}
103
104
const ghApiHeaders: Record<string, string> = {
105
Accept: 'application/vnd.github.v3+json',
106
'User-Agent': 'VSCode Build',
107
};
108
if (process.env.GITHUB_TOKEN) {
109
ghApiHeaders.Authorization = 'Basic ' + Buffer.from(process.env.GITHUB_TOKEN).toString('base64');
110
}
111
const ghDownloadHeaders = {
112
...ghApiHeaders,
113
Accept: 'application/octet-stream',
114
};
115
116
export interface IGitHubAssetOptions {
117
version: string;
118
name: string | ((name: string) => boolean);
119
checksumSha256?: string;
120
verbose?: boolean;
121
}
122
123
/**
124
* @param repo for example `Microsoft/vscode`
125
* @param version for example `16.17.1` - must be a valid releases tag
126
* @param assetName for example (name) => name === `win-x64-node.exe` - must be an asset that exists
127
* @returns a stream with the asset as file
128
*/
129
export function fetchGithub(repo: string, options: IGitHubAssetOptions): Stream {
130
return fetchUrls(`/repos/${repo.replace(/^\/|\/$/g, '')}/releases/tags/v${options.version}`, {
131
base: 'https://api.github.com',
132
verbose: options.verbose,
133
nodeFetchOptions: { headers: ghApiHeaders }
134
}).pipe(through2.obj(async function (file, _enc, callback) {
135
const assetFilter = typeof options.name === 'string' ? (name: string) => name === options.name : options.name;
136
const asset = JSON.parse(file.contents.toString()).assets.find((a: { name: string }) => assetFilter(a.name));
137
if (!asset) {
138
return callback(new Error(`Could not find asset in release of ${repo} @ ${options.version}`));
139
}
140
try {
141
callback(null, await fetchUrl(asset.url, {
142
nodeFetchOptions: { headers: ghDownloadHeaders },
143
verbose: options.verbose,
144
checksumSha256: options.checksumSha256
145
}));
146
} catch (error) {
147
callback(error);
148
}
149
}));
150
}
151
152