httpUtil.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. "use strict";
  2. /**
  3. * Copyright 2023 Google Inc. All rights reserved.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  18. if (k2 === undefined) k2 = k;
  19. var desc = Object.getOwnPropertyDescriptor(m, k);
  20. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  21. desc = { enumerable: true, get: function() { return m[k]; } };
  22. }
  23. Object.defineProperty(o, k2, desc);
  24. }) : (function(o, m, k, k2) {
  25. if (k2 === undefined) k2 = k;
  26. o[k2] = m[k];
  27. }));
  28. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  29. Object.defineProperty(o, "default", { enumerable: true, value: v });
  30. }) : function(o, v) {
  31. o["default"] = v;
  32. });
  33. var __importStar = (this && this.__importStar) || function (mod) {
  34. if (mod && mod.__esModule) return mod;
  35. var result = {};
  36. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  37. __setModuleDefault(result, mod);
  38. return result;
  39. };
  40. Object.defineProperty(exports, "__esModule", { value: true });
  41. exports.getText = exports.getJSON = exports.downloadFile = exports.httpRequest = exports.headHttpRequest = void 0;
  42. const fs_1 = require("fs");
  43. const http = __importStar(require("http"));
  44. const https = __importStar(require("https"));
  45. const url_1 = require("url");
  46. const proxy_agent_1 = require("proxy-agent");
  47. function headHttpRequest(url) {
  48. return new Promise(resolve => {
  49. const request = httpRequest(url, 'HEAD', response => {
  50. resolve(response.statusCode === 200);
  51. }, false);
  52. request.on('error', () => {
  53. resolve(false);
  54. });
  55. });
  56. }
  57. exports.headHttpRequest = headHttpRequest;
  58. function httpRequest(url, method, response, keepAlive = true) {
  59. const options = {
  60. protocol: url.protocol,
  61. hostname: url.hostname,
  62. port: url.port,
  63. path: url.pathname + url.search,
  64. method,
  65. headers: keepAlive ? { Connection: 'keep-alive' } : undefined,
  66. auth: (0, url_1.urlToHttpOptions)(url).auth,
  67. agent: new proxy_agent_1.ProxyAgent(),
  68. };
  69. const requestCallback = (res) => {
  70. if (res.statusCode &&
  71. res.statusCode >= 300 &&
  72. res.statusCode < 400 &&
  73. res.headers.location) {
  74. httpRequest(new url_1.URL(res.headers.location), method, response);
  75. }
  76. else {
  77. response(res);
  78. }
  79. };
  80. const request = options.protocol === 'https:'
  81. ? https.request(options, requestCallback)
  82. : http.request(options, requestCallback);
  83. request.end();
  84. return request;
  85. }
  86. exports.httpRequest = httpRequest;
  87. /**
  88. * @internal
  89. */
  90. function downloadFile(url, destinationPath, progressCallback) {
  91. return new Promise((resolve, reject) => {
  92. let downloadedBytes = 0;
  93. let totalBytes = 0;
  94. function onData(chunk) {
  95. downloadedBytes += chunk.length;
  96. progressCallback(downloadedBytes, totalBytes);
  97. }
  98. const request = httpRequest(url, 'GET', response => {
  99. if (response.statusCode !== 200) {
  100. const error = new Error(`Download failed: server returned code ${response.statusCode}. URL: ${url}`);
  101. // consume response data to free up memory
  102. response.resume();
  103. reject(error);
  104. return;
  105. }
  106. const file = (0, fs_1.createWriteStream)(destinationPath);
  107. file.on('finish', () => {
  108. return resolve();
  109. });
  110. file.on('error', error => {
  111. return reject(error);
  112. });
  113. response.pipe(file);
  114. totalBytes = parseInt(response.headers['content-length'], 10);
  115. if (progressCallback) {
  116. response.on('data', onData);
  117. }
  118. });
  119. request.on('error', error => {
  120. return reject(error);
  121. });
  122. });
  123. }
  124. exports.downloadFile = downloadFile;
  125. async function getJSON(url) {
  126. const text = await getText(url);
  127. try {
  128. return JSON.parse(text);
  129. }
  130. catch {
  131. throw new Error('Could not parse JSON from ' + url.toString());
  132. }
  133. }
  134. exports.getJSON = getJSON;
  135. function getText(url) {
  136. return new Promise((resolve, reject) => {
  137. const request = httpRequest(url, 'GET', response => {
  138. let data = '';
  139. if (response.statusCode && response.statusCode >= 400) {
  140. return reject(new Error(`Got status code ${response.statusCode}`));
  141. }
  142. response.on('data', chunk => {
  143. data += chunk;
  144. });
  145. response.on('end', () => {
  146. try {
  147. return resolve(String(data));
  148. }
  149. catch {
  150. return reject(new Error('Chrome version not found'));
  151. }
  152. });
  153. }, false);
  154. request.on('error', err => {
  155. reject(err);
  156. });
  157. });
  158. }
  159. exports.getText = getText;
  160. //# sourceMappingURL=httpUtil.js.map