From b3b5697f46c315fbed32618f2b7179358246dfee Mon Sep 17 00:00:00 2001 From: ExE Boss Date: Sat, 9 Oct 2021 15:40:00 +0200 Subject: [PATCH] =?UTF-8?q?Follow=C2=A0redirects=20when=C2=A0generating?= =?UTF-8?q?=C2=A0source=20for=C2=A0DefinitelyTyped?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/definitely-typed.ts | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/lib/definitely-typed.ts b/lib/definitely-typed.ts index e2cd325..b58b9be 100644 --- a/lib/definitely-typed.ts +++ b/lib/definitely-typed.ts @@ -1,5 +1,5 @@ import { existsSync, mkdirSync, writeFileSync } from 'fs'; -import { get, STATUS_CODES } from "http"; +import { get, IncomingMessage, STATUS_CODES } from "http"; import { homedir } from 'os'; import parseGitConfig = require('parse-git-config'); import { join as joinPaths } from "path"; @@ -131,15 +131,31 @@ interface Package { } function loadString(url: string): Promise { + // This is horrible, and it would be better to just use node-fetch or something: return new Promise((resolve, reject) => { - get(url, res => { + const doGet = (url: string) => { + get(url, onResponse).on('error', reject); + }; + + const onResponse = (res: IncomingMessage) => { if (res.statusCode !== 200) { + if (res.statusCode! >= 300 && res.statusCode! < 400) { + // Follow redirects: + const { location } = res.headers; + if (location) { + return doGet(location); + } + } + return reject( new Error(`HTTP Error ${res.statusCode}: ${STATUS_CODES[res.statusCode || 500]} for ${url}`)); } + let rawData = ""; res.on("data", (chunk: any) => rawData += chunk); res.on("end", () => resolve(rawData)); - }).on("error", (e: Error) => reject(e)); + }; + + return doGet(url); }); }