* replacing deprecated Request with Axios

* Implement post with axios, update authorization option

* appease tslint
This commit is contained in:
Haitham Shami 2021-12-14 10:03:11 -08:00 коммит произвёл GitHub
Родитель 4d26a795e8
Коммит 36c94bab40
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
8 изменённых файлов: 281 добавлений и 815 удалений

Просмотреть файл

@ -1,4 +1,8 @@
# Change Log
## 1.25.4 - 2021-12-15
### Changed
* Replaced deprecated 'Request' with axios for http requests.
## 1.25.3 - 2021-11-30
### Changed
* Added creation of CSharp Dev Container for new Solutions with a CSharp Function.

937
package-lock.json сгенерированный

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -2,7 +2,7 @@
"name": "azure-iot-edge",
"displayName": "Azure IoT Edge",
"description": "This extension is now a part of Azure IoT Tools extension pack. We highly recommend installing Azure IoT Tools to get full capabilities for Azure IoT development. Develop, deploy, debug, and manage your IoT Edge solution.",
"version": "1.25.3",
"version": "1.25.4",
"publisher": "vsciot-vscode",
"aiKey": "95b20d64-f54f-4de3-8ad5-165a75a6c6fe",
"icon": "logo.png",
@ -549,7 +549,6 @@
"@types/fs-extra": "^4.0.3",
"@types/mocha": "^9.0.0",
"@types/node": "^16.11.6",
"@types/request-promise": "^4.1.48",
"@types/semver": "^5.5.0",
"@types/sinon": "^7.0.13",
"@types/strip-json-comments": "0.0.30",
@ -571,6 +570,8 @@
"@azure/arm-containerregistry": "^8.1.1",
"@azure/arm-machinelearningservices": "^4.1.1",
"@azure/arm-streamanalytics": "^2.1.1",
"axios": "0.24.0",
"qs": "6.10.2",
"body-parser": "^1.18.2",
"dotenv": "^5.0.1",
"download-git-repo": "^1.0.2",
@ -579,8 +580,6 @@
"is-port-reachable": "^2.0.0",
"json-source-map": "^0.6.1",
"jsonc-parser": "^1.0.1",
"request": "^2.88.0",
"request-promise": "^4.2.2",
"semver": "^5.6.0",
"strip-json-comments": "^2.0.1",
"tmp": "0.0.33",

Просмотреть файл

@ -4,7 +4,7 @@
"use strict";
import { ContainerRegistryManagementClient, Registries } from "@azure/arm-containerregistry";
import { Registry, RegistryListCredentialsResult } from "@azure/arm-containerregistry/esm/models";
import * as request from "request-promise";
import axios from "axios";
import * as vscode from "vscode";
import { Constants } from "../common/constants";
import { UserCancelledError } from "../common/UserCancelledError";
@ -113,14 +113,10 @@ export class AcrManager {
this.acrRefreshToken = await this.acquireAcrRefreshToken(registryUrl, session.tenantId, aadRefreshToken, aadAccessToken);
const acrAccessToken = await this.acquireAcrAccessToken(registryUrl, "registry:catalog:*", this.acrRefreshToken);
const catalogResponse = await request.get(`https://${registryUrl}/v2/_catalog`, {
auth: {
bearer: acrAccessToken,
},
});
const catalogResponse = await axios.get(`https://${registryUrl}/v2/_catalog`, { headers: { Authorization: `bearer ${acrAccessToken}` } });
const repoItems: vscode.QuickPickItem[] = [];
const repos = JSON.parse(catalogResponse).repositories;
const repos = catalogResponse.data.repositories;
if (!repos) {
const error: any = new Error("There is no repository in the registry.");
@ -148,28 +144,39 @@ export class AcrManager {
}
private async acquireAcrRefreshToken(registryUrl: string, tenantId: string, aadRefreshToken: string, aadAccessToken: string): Promise<string> {
const acrRefreshTokenResponse = await request.post(`https://${registryUrl}/oauth2/exchange`, {
form: {
grant_type: "access_token_refresh_token",
service: registryUrl,
tenant: tenantId,
refresh_token: aadRefreshToken,
access_token: aadAccessToken,
},
const qs = require("qs");
const data = {
grant_type: "access_token_refresh_token",
service: registryUrl,
tenant: tenantId,
refresh_token: aadRefreshToken,
access_token: aadAccessToken,
};
const acrRefreshToken = await axios.post(`https://${registryUrl}/oauth2/exchange`, qs.stringify(data))
.then((res) => {
return res.data.refresh_token;
})
.catch((error) => {
throw error;
});
return JSON.parse(acrRefreshTokenResponse).refresh_token;
return acrRefreshToken;
}
private async acquireAcrAccessToken(registryUrl: string, scope: string, acrRefreshToken: string) {
const acrAccessTokenResponse = await request.post(`https://${registryUrl}/oauth2/token`, {
form: {
const qs = require("qs");
const acrAccessTokenResponse = await axios.post(`https://${registryUrl}/oauth2/token`,
qs.stringify({
grant_type: "refresh_token",
service: registryUrl,
scope,
refresh_token: acrRefreshToken,
},
});
return JSON.parse(acrAccessTokenResponse).access_token;
}),
);
return acrAccessTokenResponse.data.access_token;
}
private async selectAcrTag(registryUrl: string, repo: string): Promise<vscode.QuickPickItem> {
@ -181,14 +188,10 @@ export class AcrManager {
try {
const acrAccessToken = await this.acquireAcrAccessToken(registryUrl, `repository:${repo}:pull`, this.acrRefreshToken);
const tagsResponse = await request.get(`https://${registryUrl}/v2/${repo}/tags/list`, {
auth: {
bearer: acrAccessToken,
},
});
const tagsResponse = await axios.get(`https://${registryUrl}/v2/${repo}/tags/list`, { headers: { Authorization: `bearer ${acrAccessToken}` } });
const tagItems: vscode.QuickPickItem[] = [];
const tags = JSON.parse(tagsResponse).tags;
const tags = tagsResponse.data.tags;
tags.map((tag) => {
tagItems.push({
label: tag,

Просмотреть файл

@ -3,8 +3,8 @@
import { StreamAnalyticsManagementClient, StreamingJobs } from "@azure/arm-streamanalytics";
import { StreamingJob } from "@azure/arm-streamanalytics/esm/models";
import axios from "axios";
import * as fse from "fs-extra";
import * as request from "request-promise";
import * as vscode from "vscode";
import { Constants } from "../common/constants";
import { UserCancelledError } from "../common/UserCancelledError";
@ -101,12 +101,7 @@ export class StreamAnalyticsManager {
const curEtag = ASAInfo.ASAJobEtag;
const subscription = await this.getJobSubscription(ASAInfo);
const { aadAccessToken } = await Utility.acquireAadToken(subscription.session);
const jobInfo = await request.get(GetASAJobApiUrl, {
auth: {
bearer: aadAccessToken,
},
resolveWithFullResponse: true,
});
const jobInfo = await axios.get(GetASAJobApiUrl, { headers: { Authorization: `bearer ${aadAccessToken}` } });
const latestETag = jobInfo.headers.etag;
return latestETag !== curEtag;
@ -126,12 +121,7 @@ export class StreamAnalyticsManager {
const apiUrl: string = `https://management.azure.com${resourceId}/publishedgepackage?api-version=2019-06-01`;
const { aadAccessToken } = await Utility.acquireAadToken(session);
const publishResponse = await request.post(apiUrl, {
auth: {
bearer: aadAccessToken,
},
resolveWithFullResponse: true,
});
const publishResponse = await axios.post(apiUrl, { headers: { Authorization: `bearer ${aadAccessToken}` }, resolveWithFullResponse: true });
const operationResultUrl = publishResponse.headers.location;
@ -139,26 +129,21 @@ export class StreamAnalyticsManager {
while (true) {
await this.sleep(2000);
const jobInfoResult = await request.get(operationResultUrl, {
auth: {
bearer: aadAccessToken,
},
resolveWithFullResponse: true,
});
const jobInfoResult = await axios.get(operationResultUrl, { headers: { Authorization: `bearer ${aadAccessToken}` } });
if (token.isCancellationRequested) {
throw new UserCancelledError();
}
if (jobInfoResult.statusCode === 202) {
if (jobInfoResult.status === 202) {
if (retryTimes < this.MaximumRetryCount) {
retryTimes++;
continue;
} else {
throw new Error(Constants.queryASAJobInfoFailedMsg);
}
} else if (jobInfoResult.statusCode === 200) {
const result = JSON.parse(jobInfoResult.body);
} else if (jobInfoResult.status === 200) {
const result = jobInfoResult.data;
if (result.status === "Succeeded") {
const info = JSON.parse(result.manifest);
return info;
@ -166,7 +151,7 @@ export class StreamAnalyticsManager {
throw new Error(result.error.message);
}
} else {
throw new Error("http status code: " + jobInfoResult.statusCode);
throw new Error("http status code: " + jobInfoResult.status);
}
}
} catch (error) {

Просмотреть файл

@ -2,11 +2,12 @@
// Licensed under the MIT license.
"use strict";
import axios from "axios";
import * as dotenv from "dotenv";
import * as fse from "fs-extra";
import * as os from "os";
import * as path from "path";
import * as request from "request-promise";
import * as semver from "semver";
import * as unzipper from "unzipper";
import * as vscode from "vscode";
@ -213,8 +214,8 @@ export class Simulator {
if (!this.desiredSimulatorInfo) {
await RetryPolicy.retry(Simulator.maxRetryTimes, Simulator.retryInterval, outputChannel, async () => {
let version = Simulator.iotedgehubdevDefaultVersion;
const pipResponse = await request.get(Simulator.iotedgehubdevVersionUrl);
const releases = JSON.parse(pipResponse).releases;
const pipResponse = await axios.get(Simulator.iotedgehubdevVersionUrl);
const releases = pipResponse.data.releases;
const lockVersion = process.env[Simulator.iotedgehubdevLockVersionKey];
if (lockVersion !== undefined && lockVersion.trim() !== "") {
// Make sure the custom version is an existing release
@ -292,20 +293,14 @@ export class Simulator {
const version: string = info.version;
await RetryPolicy.retry(Simulator.maxRetryTimes, Simulator.retryInterval, outputChannel, async () => {
const res = await axios.get(binariesZipUrl, {responseType: "stream"});
await new Promise<void>((resolve, reject) => {
const req = request(binariesZipUrl);
req.on("response", (res) => {
if (res.statusCode === 200) {
req.pipe(unzipper.Extract({ path: Simulator.WindowsStandaloneSimulatorFolder }))
.on("close", () => resolve()).on("error", (e) => reject(new Error("Cannot extract simulator binaries from zip file: " + e.message)));
} else {
reject(new Error("Cannot download simulator with status code: " + res.statusCode));
}
});
req.on("error", (err) => {
reject(new Error("Cannot download simulator, please check your network connection: " + err.message));
});
if (res.status === 200) {
res.data.pipe(unzipper.Extract({ path: Simulator.WindowsStandaloneSimulatorFolder }))
.on("close", () => resolve()).on("error", (e) => reject(new Error("Cannot extract simulator binaries from zip file: " + e.message)));
} else {
reject(new Error("Cannot download simulator with status code: " + res.status));
}
});
try {

Просмотреть файл

@ -1,8 +1,8 @@
import axios from "axios";
import * as bodyParser from "body-parser";
import * as express from "express";
import * as http from "http";
import { AddressInfo } from "net";
import * as request from "request-promise";
import * as vscode from "vscode";
import { Utility } from "../common/utility";
@ -83,7 +83,7 @@ export class LocalServer {
let items = [];
const result = [];
while (apiUrl != null) {
const modulesList = JSON.parse(await request.get(apiUrl));
const modulesList = (await axios.get(apiUrl)).data;
apiUrl = modulesList.nextPageLink;
items = items.concat(modulesList.items);
}

Просмотреть файл

@ -10,9 +10,11 @@
const failOnErrorsPlugin = require('fail-on-errors-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');
/**@type {import('webpack').Configuration}*/
const config = {
mode: 'development',
target: 'node', // vscode extensions run in a Node.js-context 📖 -> https://webpack.js.org/configuration/node/
entry: './src/extension.ts', // the entry point of this extension, 📖 -> https://webpack.js.org/configuration/entry-context/
@ -74,4 +76,29 @@ const config = {
]
}
module.exports = config;
// in production mode, webpack decorates class constructor names.
// changing constructor names causes an issue for the following logic:
// if type.constructor.name !== 'AbortSignal'...
// this issue is present in the package node-fetch - version "2.6.0", which is
// used by the package @azure/ms-rest-js - version "2.6.0".
// the following setup works around the issue by preventing the 'optimization'
// for the one type that is causing our issue.
module.exports = (env, argv) => {
if (argv.mode === 'production') {
config.mode = 'production'
config.devtool = 'source-map'
config.optimization = {
...(config.optimization || {}),
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
keep_fnames: /AbortSignal/,
},
}),
],
}
}
return config
}