askui 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/cjs/core/annotation/annotation-json.d.ts +5 -0
  2. package/dist/cjs/core/annotation/annotation-json.js +2 -0
  3. package/dist/cjs/execution/config-error.d.ts +2 -0
  4. package/dist/cjs/execution/config-error.js +6 -0
  5. package/dist/cjs/execution/inference-client.d.ts +2 -1
  6. package/dist/cjs/execution/inference-client.js +9 -3
  7. package/dist/cjs/execution/ui-control-client.js +4 -2
  8. package/dist/cjs/execution/ui-controller-client-interface.d.ts +13 -0
  9. package/dist/cjs/lib/download-binaries.d.ts +7 -1
  10. package/dist/cjs/lib/download-binaries.js +2 -2
  11. package/dist/cjs/lib/ui-controller-args.d.ts +4 -0
  12. package/dist/cjs/lib/ui-controller-facade.js +4 -3
  13. package/dist/cjs/shared/proxy-agent-args.d.ts +35 -0
  14. package/dist/cjs/shared/proxy-agent-args.js +2 -0
  15. package/dist/cjs/utils/http/http-client-got.d.ts +11 -1
  16. package/dist/cjs/utils/http/http-client-got.js +5 -3
  17. package/dist/cjs/utils/proxy/proxy-builder.d.ts +4 -0
  18. package/dist/cjs/utils/proxy/proxy-builder.js +67 -0
  19. package/dist/esm/core/annotation/annotation-json.d.ts +5 -0
  20. package/dist/esm/core/annotation/annotation-json.js +1 -0
  21. package/dist/esm/execution/config-error.d.ts +2 -0
  22. package/dist/esm/execution/config-error.js +2 -0
  23. package/dist/esm/execution/inference-client.d.ts +2 -1
  24. package/dist/esm/execution/inference-client.js +9 -3
  25. package/dist/esm/execution/ui-control-client.js +4 -2
  26. package/dist/esm/execution/ui-controller-client-interface.d.ts +13 -0
  27. package/dist/esm/lib/download-binaries.d.ts +7 -1
  28. package/dist/esm/lib/download-binaries.js +2 -2
  29. package/dist/esm/lib/ui-controller-args.d.ts +4 -0
  30. package/dist/esm/lib/ui-controller-facade.js +4 -3
  31. package/dist/esm/shared/proxy-agent-args.d.ts +35 -0
  32. package/dist/esm/shared/proxy-agent-args.js +1 -0
  33. package/dist/esm/utils/http/http-client-got.d.ts +11 -1
  34. package/dist/esm/utils/http/http-client-got.js +5 -3
  35. package/dist/esm/utils/proxy/proxy-builder.d.ts +4 -0
  36. package/dist/esm/utils/proxy/proxy-builder.js +43 -0
  37. package/dist/example_projects_templates/typescript_jest/test/helper/jest.setup.ts +2 -2
  38. package/package.json +5 -2
@@ -0,0 +1,5 @@
1
+ import { DetectedElement } from '../model/annotation-result/detected-element';
2
+ export interface AnnotationJson {
3
+ image: string;
4
+ objects: DetectedElement[];
5
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ export declare class ConfigurationError extends Error {
2
+ }
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConfigurationError = void 0;
4
+ class ConfigurationError extends Error {
5
+ }
6
+ exports.ConfigurationError = ConfigurationError;
@@ -6,10 +6,11 @@ import { DetectedElement } from '../core/model/annotation-result/detected-elemen
6
6
  export declare class InferenceClient {
7
7
  baseUrl: string;
8
8
  httpClient: HttpClientGot;
9
+ resize?: number | undefined;
9
10
  readonly workspaceId?: string | undefined;
10
11
  apiVersion: string;
11
12
  url: string;
12
- constructor(baseUrl: string, httpClient: HttpClientGot, workspaceId?: string | undefined, apiVersion?: string);
13
+ constructor(baseUrl: string, httpClient: HttpClientGot, resize?: number | undefined, workspaceId?: string | undefined, apiVersion?: string);
13
14
  isImageRequired(instruction: string): Promise<boolean>;
14
15
  private resizeIfNeeded;
15
16
  inference(customElements?: CustomElement[], image?: string, instruction?: string): Promise<ControlCommand | Annotation>;
@@ -18,14 +18,20 @@ const ui_control_commands_1 = require("../core/ui-control-commands");
18
18
  const annotation_1 = require("../core/annotation/annotation");
19
19
  const transformations_1 = require("../utils/transformations");
20
20
  const inference_response_error_1 = require("./inference-response-error");
21
+ const config_error_1 = require("./config-error");
21
22
  class InferenceClient {
22
- constructor(baseUrl, httpClient, workspaceId, apiVersion = 'v3') {
23
+ constructor(baseUrl, httpClient, resize, workspaceId, apiVersion = 'v3') {
23
24
  this.baseUrl = baseUrl;
24
25
  this.httpClient = httpClient;
26
+ this.resize = resize;
25
27
  this.workspaceId = workspaceId;
26
28
  this.apiVersion = apiVersion;
27
29
  const versionedBaseUrl = (0, url_join_1.default)(this.baseUrl, 'api', this.apiVersion);
28
30
  this.url = workspaceId ? (0, url_join_1.default)(versionedBaseUrl, 'workspaces', workspaceId) : versionedBaseUrl;
31
+ if (this.resize !== undefined && this.resize <= 0) {
32
+ throw new config_error_1.ConfigurationError(`Resize must be a positive number. The current resize value "${this.resize}" is not valid.`);
33
+ }
34
+ this.resize = this.resize ? Math.ceil(this.resize) : this.resize;
29
35
  }
30
36
  isImageRequired(instruction) {
31
37
  return __awaiter(this, void 0, void 0, function* () {
@@ -40,10 +46,10 @@ class InferenceClient {
40
46
  // eslint-disable-next-line class-methods-use-this
41
47
  resizeIfNeeded(customElements, image) {
42
48
  return __awaiter(this, void 0, void 0, function* () {
43
- if (!(image) || customElements.length > 0) {
49
+ if (!(image) || customElements.length > 0 || this.resize === undefined) {
44
50
  return { base64Image: image, resizeRatio: 1 };
45
51
  }
46
- return (0, transformations_1.resizeBase64ImageWithSameRatio)(image);
52
+ return (0, transformations_1.resizeBase64ImageWithSameRatio)(image, this.resize);
47
53
  });
48
54
  }
49
55
  inference(customElements = [], image, instruction) {
@@ -23,6 +23,7 @@ const annotation_level_1 = require("./annotation-level");
23
23
  const ui_control_client_error_1 = require("./ui-control-client-error");
24
24
  const read_environment_credentials_1 = require("./read-environment-credentials");
25
25
  const analytics_1 = require("../utils/analytics");
26
+ const proxy_builder_1 = require("../utils/proxy/proxy-builder");
26
27
  const getClientArgsWithDefaults = (clientArgs = {}) => (Object.assign({ uiControllerUrl: 'http://127.0.0.1:6769', inferenceServerUrl: 'https://inference.askui.com', annotationLevel: annotation_level_1.AnnotationLevel.DISABLED }, clientArgs));
27
28
  class UiControlClient extends dsl_1.ApiCommands {
28
29
  constructor(httpClient, clientArgs, workspaceId) {
@@ -39,7 +40,8 @@ class UiControlClient extends dsl_1.ApiCommands {
39
40
  const analyticsCookies = yield analytics.getAnalyticsCookies();
40
41
  const cas = getClientArgsWithDefaults(clientArgs);
41
42
  const credentialArgs = cas.credentials || (0, read_environment_credentials_1.envCredentials)();
42
- const httpClient = new http_client_got_1.HttpClientGot(credentialArgs === null || credentialArgs === void 0 ? void 0 : credentialArgs.token, analyticsHeaders, analyticsCookies);
43
+ const proxyAgentArgs = cas.proxyAgents || (yield (0, proxy_builder_1.buildProxyAgentArgsFromEnvironment)());
44
+ const httpClient = new http_client_got_1.HttpClientGot(credentialArgs === null || credentialArgs === void 0 ? void 0 : credentialArgs.token, analyticsHeaders, analyticsCookies, proxyAgentArgs);
43
45
  return new UiControlClient(httpClient, cas, credentialArgs === null || credentialArgs === void 0 ? void 0 : credentialArgs.workspaceId);
44
46
  });
45
47
  }
@@ -50,7 +52,7 @@ class UiControlClient extends dsl_1.ApiCommands {
50
52
  return this._uiControllerClient;
51
53
  }
52
54
  get inferenceClient() {
53
- return new inference_client_1.InferenceClient(this.clientArgs.inferenceServerUrl, this.httpClient, this.workspaceId);
55
+ return new inference_client_1.InferenceClient(this.clientArgs.inferenceServerUrl, this.httpClient, this.clientArgs.resize, this.workspaceId);
54
56
  }
55
57
  get executionRuntime() {
56
58
  return new execution_runtime_1.ExecutionRuntime(this.uiControllerClient, this.inferenceClient);
@@ -1,10 +1,19 @@
1
1
  import { AnnotationLevel } from './annotation-level';
2
2
  import { CredentialArgs } from './credentials-args';
3
+ import { ProxyAgentArgs } from '../shared/proxy-agent-args';
3
4
  /**
4
5
  * Configuration options for the askui UI Control Client
5
6
  *
6
7
  * @param {string} uiControllerUrl - Default: http://127.0.0.1:6769
7
8
  * The adress of the askui UI Controller server.
9
+ * @param {(number | undefined)} resize - Default: undefined
10
+ * The resizing will be skipped if it's undefined.
11
+ * The side length of the target image to resize to in px.
12
+ * Your screenshot image will be resized with the original aspect ratio,
13
+ * and the lengths image side will be equal to this number.
14
+ * This can be used to reduce the inference time by reducing
15
+ * the request size in case of a bad internet connection.
16
+ * But it can cause a decrease in the prediction quality.
8
17
  * @param {string} inferenceClientUrl - Default: https://inference.askui.com`
9
18
  * Address of the askui Inference server.
10
19
  * @param {AnnotationLevel} annotationLevel - Default: AnnotationLevel.DISABLED
@@ -13,12 +22,16 @@ import { CredentialArgs } from './credentials-args';
13
22
  * You have three options: `DISABLED`, `ON_FAILURE`, `ALL`.
14
23
  * @param {CredentialArgs} credentials - We need to provide credentials for
15
24
  * the authentication of the askui Inference Server.
25
+ * You have three options: `DISABLED`, `ON_FAILURE`, `ALL`.
26
+ * @param {ProxyAgentArgs} proxyAgents - To configure the proxy agents for http(s) requests.
16
27
  */
17
28
  export interface ClientArgs {
18
29
  readonly uiControllerUrl?: string;
19
30
  readonly inferenceServerUrl?: string;
20
31
  readonly annotationLevel?: AnnotationLevel;
21
32
  readonly credentials?: CredentialArgs;
33
+ readonly proxyAgents?: ProxyAgentArgs;
34
+ readonly resize?: number;
22
35
  }
23
36
  export interface ClientArgsWithDefaults extends ClientArgs {
24
37
  readonly uiControllerUrl: string;
@@ -1,3 +1,6 @@
1
+ /// <reference types="node" />
2
+ import http from 'http';
3
+ import https from 'https';
1
4
  declare enum SupportedPlatform {
2
5
  LINUX = "linux",
3
6
  DARWIN = "darwin",
@@ -5,5 +8,8 @@ declare enum SupportedPlatform {
5
8
  }
6
9
  export declare function platform(): SupportedPlatform;
7
10
  export declare function getBinaryPath(version: string): string;
8
- export declare function downloadServerBinaries(binaryVersion: string): Promise<void>;
11
+ export declare function downloadServerBinaries(binaryVersion: string, proxyAgent?: {
12
+ http: http.Agent;
13
+ https: https.Agent;
14
+ }): Promise<void>;
9
15
  export {};
@@ -44,7 +44,7 @@ function getBinaryDownloadUrl(binaryVersion) {
44
44
  const arch = os_1.default.arch();
45
45
  return `${baseUrl}/${platform()}/${arch}/${binarySubPathsByPlatform[platform()][1]}`;
46
46
  }
47
- function downloadServerBinaries(binaryVersion) {
47
+ function downloadServerBinaries(binaryVersion, proxyAgent) {
48
48
  return new Promise((resolve, reject) => {
49
49
  const url = getBinaryDownloadUrl(binaryVersion);
50
50
  const binaryOutputPath = getBinaryPath(binaryVersion);
@@ -53,7 +53,7 @@ function downloadServerBinaries(binaryVersion) {
53
53
  if (!(fs_1.default.existsSync(binaryFolder))) {
54
54
  fs_1.default.mkdirSync(binaryFolder, { recursive: true });
55
55
  }
56
- const downloadStream = got_1.default.stream(url);
56
+ const downloadStream = got_1.default.stream(url, proxyAgent ? { agent: proxyAgent } : {});
57
57
  const fileWriterStream = fs_1.default.createWriteStream(binaryOutputPath);
58
58
  downloadStream.on('error', () => {
59
59
  reject();
@@ -1,3 +1,4 @@
1
+ import { ProxyAgentArgs } from '../shared/proxy-agent-args';
1
2
  import { LogLevels } from '../shared/log-levels';
2
3
  /**
3
4
  * Configuration options for the askui UI Controller
@@ -5,6 +6,7 @@ import { LogLevels } from '../shared/log-levels';
5
6
  * @param {number} display - Default: `0`
6
7
  * You can choose on which display you want to excecute all tests.
7
8
  * 0 is your main monitor.
9
+ *
8
10
  * If you want to use your second monitor you can change
9
11
  * the value to `1` (`2` for your third monitor etc.).
10
12
  * @param {string} binaryVersion - Default: `'latest'`
@@ -26,6 +28,7 @@ import { LogLevels } from '../shared/log-levels';
26
28
  * @param {string} logFilePath - Default: `'<temp-dir>/askui/askui-server.log'`
27
29
  * It is possible to specify a path for your log files.
28
30
  * Per default we create the askui-server.log file and askui folder in your temp folder.
31
+ * @param {ProxyAgentArgs} proxyAgents - To configure the proxy agents for our http(s) requests.
29
32
  */
30
33
  export interface UiControllerArgs {
31
34
  readonly display?: number;
@@ -37,6 +40,7 @@ export interface UiControllerArgs {
37
40
  readonly overWriteBinary?: boolean;
38
41
  readonly logLevel?: LogLevels;
39
42
  readonly logFilePath?: string;
43
+ readonly proxyAgents?: ProxyAgentArgs;
40
44
  }
41
45
  export interface UiControllerArgsWithDefaults extends UiControllerArgs {
42
46
  readonly display: number;
@@ -24,6 +24,7 @@ const download_binaries_1 = require("./download-binaries");
24
24
  const logger_1 = require("./logger");
25
25
  const timeout_error_1 = require("./timeout-error");
26
26
  const unkown_error_1 = require("./unkown-error");
27
+ const proxy_builder_1 = require("../utils/proxy/proxy-builder");
27
28
  class UiControllerFacade {
28
29
  constructor() {
29
30
  this.binaryPath = (0, download_binaries_1.getBinaryPath)('latest');
@@ -35,7 +36,7 @@ class UiControllerFacade {
35
36
  const argsWithDefaults = (0, ui_controller_args_1.createArgsWithDefaults)(args);
36
37
  const argsWithLogPath = this.serverLogFilePath(argsWithDefaults);
37
38
  this.binaryPath = (0, download_binaries_1.getBinaryPath)(argsWithLogPath.binaryVersion);
38
- yield this.getBinary(argsWithLogPath.binaryVersion, argsWithLogPath.overWriteBinary);
39
+ yield this.getBinary(argsWithLogPath.binaryVersion, argsWithLogPath.overWriteBinary, argsWithLogPath.proxyAgents || (yield (0, proxy_builder_1.buildProxyAgentArgsFromEnvironment)()));
39
40
  this.makeBinaryExecutable();
40
41
  logger_1.logger.debug(`UI Controller log path "${this.serverLogFile}"`);
41
42
  yield this.startWithDefaults(argsWithLogPath, maxWaitingForStartingInSeconds);
@@ -109,11 +110,11 @@ class UiControllerFacade {
109
110
  const binarysizeInMB = fs_extra_1.default.statSync(this.binaryPath).size / (1024 * 1024);
110
111
  return binarysizeInMB > sizeThresholdInMB;
111
112
  }
112
- getBinary(binaryVersion, overWriteBinary = false) {
113
+ getBinary(binaryVersion, overWriteBinary = false, proxyAgent) {
113
114
  return __awaiter(this, void 0, void 0, function* () {
114
115
  if (!fs_extra_1.default.existsSync(this.binaryPath) || overWriteBinary || !this.isBinaryValid()) {
115
116
  logger_1.logger.debug(`Currently, no binary of the UI Controller is available at "${this.binaryPath}"`);
116
- yield (0, download_binaries_1.downloadServerBinaries)(binaryVersion);
117
+ yield (0, download_binaries_1.downloadServerBinaries)(binaryVersion, proxyAgent);
117
118
  }
118
119
  else {
119
120
  logger_1.logger.debug(`Binary of UI Controller is already present at "${this.binaryPath}".`);
@@ -0,0 +1,35 @@
1
+ /// <reference types="node" />
2
+ import http from 'http';
3
+ import https from 'https';
4
+ /**
5
+ * Proxy agent configuration for HTTP(S) requests
6
+ *
7
+ * All modules which implement the `http.Agent`'s or `https.Agent`'s
8
+ * interface, respectively, can be used.
9
+ * We recommend to use [hpagent](https://github.com/delvedore/hpagent).
10
+ *
11
+ * Installation:
12
+ * ```shell
13
+ * npm install --save hpagent
14
+ * ```
15
+ *
16
+ * Configuration:
17
+ * ```typescript
18
+ * const httpProxyUrl = "http://your-proxy:3128";
19
+ * const httpsProxyUrl = "https://your-proxy:3129";
20
+ *
21
+ * const aui = await UiControlClient.build({
22
+ * proxyAgents: {
23
+ * http: new HttpProxyAgent({ proxy: httpProxyUrl }),
24
+ * https: new HttpsProxyAgent({ proxy: httpsProxyUrl }),
25
+ * },
26
+ * });
27
+ * ```
28
+ *
29
+ * @param {http.Agent} http - Agent for http requests
30
+ * @param {https.Agent} https - Agent for https requests
31
+ ** */
32
+ export interface ProxyAgentArgs {
33
+ http: http.Agent;
34
+ https: https.Agent;
35
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,10 +1,20 @@
1
1
  import { OptionsOfJSONResponseBody } from 'got';
2
+ import http from 'http';
3
+ import https from 'https';
2
4
  export declare class HttpClientGot {
3
5
  readonly token?: string | undefined;
4
6
  readonly customHeaders?: Record<string, string> | undefined;
5
7
  private readonly cookies;
8
+ readonly proxyAgents?: {
9
+ http: http.Agent;
10
+ https: https.Agent;
11
+ } | undefined;
6
12
  private headers;
7
- constructor(token?: string | undefined, customHeaders?: Record<string, string> | undefined, cookies?: Record<string, string>);
13
+ private askuiGot;
14
+ constructor(token?: string | undefined, customHeaders?: Record<string, string> | undefined, cookies?: Record<string, string>, proxyAgents?: {
15
+ http: http.Agent;
16
+ https: https.Agent;
17
+ } | undefined);
8
18
  private initHeaders;
9
19
  private injectHeadersAndCookies;
10
20
  post<T>(url: string, data: Record<string | number | symbol, unknown>): Promise<T>;
@@ -19,12 +19,14 @@ const lib_1 = require("../../lib");
19
19
  const credentials_1 = require("./credentials");
20
20
  const custom_errors_1 = require("./custom-errors");
21
21
  class HttpClientGot {
22
- constructor(token, customHeaders, cookies = {}) {
22
+ constructor(token, customHeaders, cookies = {}, proxyAgents) {
23
23
  this.token = token;
24
24
  this.customHeaders = customHeaders;
25
25
  this.cookies = cookies;
26
+ this.proxyAgents = proxyAgents;
26
27
  this.headers = {};
27
28
  this.initHeaders(token, customHeaders);
29
+ this.askuiGot = got_1.default.extend(proxyAgents ? { agent: proxyAgents } : {});
28
30
  }
29
31
  initHeaders(token, customHeaders = {}) {
30
32
  const credentials = token ? new credentials_1.Credentials(token) : undefined;
@@ -40,7 +42,7 @@ class HttpClientGot {
40
42
  post(url, data) {
41
43
  return __awaiter(this, void 0, void 0, function* () {
42
44
  const options = this.injectHeadersAndCookies(url, { json: data, responseType: 'json', throwHttpErrors: false });
43
- const { body, statusCode, headers } = yield got_1.default.post(url, options);
45
+ const { body, statusCode, headers } = yield this.askuiGot.post(url, options);
44
46
  if (headers['deprecation'] !== undefined) {
45
47
  lib_1.logger.warn(headers['deprecation']);
46
48
  }
@@ -52,7 +54,7 @@ class HttpClientGot {
52
54
  }
53
55
  get(url, options = { responseType: 'json' }) {
54
56
  return __awaiter(this, void 0, void 0, function* () {
55
- const response = yield got_1.default.get(url, this.injectHeadersAndCookies(url, options));
57
+ const response = yield this.askuiGot.get(url, this.injectHeadersAndCookies(url, options));
56
58
  return response.body;
57
59
  });
58
60
  }
@@ -0,0 +1,4 @@
1
+ import { ProxyAgentArgs } from '../../shared/proxy-agent-args';
2
+ export declare class ProxyImportError extends Error {
3
+ }
4
+ export declare function buildProxyAgentArgsFromEnvironment(): Promise<ProxyAgentArgs | undefined>;
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
22
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
23
+ return new (P || (P = Promise))(function (resolve, reject) {
24
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
25
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
26
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
27
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
28
+ });
29
+ };
30
+ Object.defineProperty(exports, "__esModule", { value: true });
31
+ exports.buildProxyAgentArgsFromEnvironment = exports.ProxyImportError = void 0;
32
+ const logger_1 = require("../../lib/logger");
33
+ class ProxyImportError extends Error {
34
+ }
35
+ exports.ProxyImportError = ProxyImportError;
36
+ function dynmicImportHpagent() {
37
+ return __awaiter(this, void 0, void 0, function* () {
38
+ try {
39
+ // eslint-disable-next-line import/no-extraneous-dependencies
40
+ return yield Promise.resolve().then(() => __importStar(require('hpagent')));
41
+ }
42
+ catch (err) {
43
+ throw new ProxyImportError('Can\'t find "hpagent" module to configure proxy! Please, install hpagent for proxy support with "npm install --save-dev hpagent".');
44
+ }
45
+ });
46
+ }
47
+ function buildProxyAgentArgsFromEnvironment() {
48
+ return __awaiter(this, void 0, void 0, function* () {
49
+ const httpProxyUrl = process.env['HTTP_PROXY'];
50
+ const httpsProxyUrl = process.env['HTTPS_PROXY'];
51
+ if (httpProxyUrl === undefined && httpsProxyUrl === undefined) {
52
+ logger_1.logger.debug('No proxy defined. "HTTPS_PROXY" and "HTTP_PROXY" environment variables are empty.');
53
+ return undefined;
54
+ }
55
+ const hpagent = yield dynmicImportHpagent();
56
+ logger_1.logger.info('Using proxy! One of following environment variables are defined: "HTTPS_PROXY", "https_proxy", "HTTP_PROXY" and "http_proxy"');
57
+ return {
58
+ http: new hpagent.HttpProxyAgent({
59
+ proxy: (httpProxyUrl || httpsProxyUrl),
60
+ }),
61
+ https: new hpagent.HttpsProxyAgent({
62
+ proxy: (httpsProxyUrl || httpProxyUrl),
63
+ }),
64
+ };
65
+ });
66
+ }
67
+ exports.buildProxyAgentArgsFromEnvironment = buildProxyAgentArgsFromEnvironment;
@@ -0,0 +1,5 @@
1
+ import { DetectedElement } from '../model/annotation-result/detected-element';
2
+ export interface AnnotationJson {
3
+ image: string;
4
+ objects: DetectedElement[];
5
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ export declare class ConfigurationError extends Error {
2
+ }
@@ -0,0 +1,2 @@
1
+ export class ConfigurationError extends Error {
2
+ }
@@ -6,10 +6,11 @@ import { DetectedElement } from '../core/model/annotation-result/detected-elemen
6
6
  export declare class InferenceClient {
7
7
  baseUrl: string;
8
8
  httpClient: HttpClientGot;
9
+ resize?: number | undefined;
9
10
  readonly workspaceId?: string | undefined;
10
11
  apiVersion: string;
11
12
  url: string;
12
- constructor(baseUrl: string, httpClient: HttpClientGot, workspaceId?: string | undefined, apiVersion?: string);
13
+ constructor(baseUrl: string, httpClient: HttpClientGot, resize?: number | undefined, workspaceId?: string | undefined, apiVersion?: string);
13
14
  isImageRequired(instruction: string): Promise<boolean>;
14
15
  private resizeIfNeeded;
15
16
  inference(customElements?: CustomElement[], image?: string, instruction?: string): Promise<ControlCommand | Annotation>;
@@ -12,14 +12,20 @@ import { ControlCommand, InferenceResponse } from '../core/ui-control-commands';
12
12
  import { Annotation } from '../core/annotation/annotation';
13
13
  import { resizeBase64ImageWithSameRatio } from '../utils/transformations';
14
14
  import { InferenceResponseError } from './inference-response-error';
15
+ import { ConfigurationError } from './config-error';
15
16
  export class InferenceClient {
16
- constructor(baseUrl, httpClient, workspaceId, apiVersion = 'v3') {
17
+ constructor(baseUrl, httpClient, resize, workspaceId, apiVersion = 'v3') {
17
18
  this.baseUrl = baseUrl;
18
19
  this.httpClient = httpClient;
20
+ this.resize = resize;
19
21
  this.workspaceId = workspaceId;
20
22
  this.apiVersion = apiVersion;
21
23
  const versionedBaseUrl = urljoin(this.baseUrl, 'api', this.apiVersion);
22
24
  this.url = workspaceId ? urljoin(versionedBaseUrl, 'workspaces', workspaceId) : versionedBaseUrl;
25
+ if (this.resize !== undefined && this.resize <= 0) {
26
+ throw new ConfigurationError(`Resize must be a positive number. The current resize value "${this.resize}" is not valid.`);
27
+ }
28
+ this.resize = this.resize ? Math.ceil(this.resize) : this.resize;
23
29
  }
24
30
  isImageRequired(instruction) {
25
31
  return __awaiter(this, void 0, void 0, function* () {
@@ -34,10 +40,10 @@ export class InferenceClient {
34
40
  // eslint-disable-next-line class-methods-use-this
35
41
  resizeIfNeeded(customElements, image) {
36
42
  return __awaiter(this, void 0, void 0, function* () {
37
- if (!(image) || customElements.length > 0) {
43
+ if (!(image) || customElements.length > 0 || this.resize === undefined) {
38
44
  return { base64Image: image, resizeRatio: 1 };
39
45
  }
40
- return resizeBase64ImageWithSameRatio(image);
46
+ return resizeBase64ImageWithSameRatio(image, this.resize);
41
47
  });
42
48
  }
43
49
  inference(customElements = [], image, instruction) {
@@ -20,6 +20,7 @@ import { AnnotationLevel } from './annotation-level';
20
20
  import { UiControlClientError } from './ui-control-client-error';
21
21
  import { envCredentials } from './read-environment-credentials';
22
22
  import { Analytics } from '../utils/analytics';
23
+ import { buildProxyAgentArgsFromEnvironment } from '../utils/proxy/proxy-builder';
23
24
  const getClientArgsWithDefaults = (clientArgs = {}) => (Object.assign({ uiControllerUrl: 'http://127.0.0.1:6769', inferenceServerUrl: 'https://inference.askui.com', annotationLevel: AnnotationLevel.DISABLED }, clientArgs));
24
25
  export class UiControlClient extends ApiCommands {
25
26
  constructor(httpClient, clientArgs, workspaceId) {
@@ -36,7 +37,8 @@ export class UiControlClient extends ApiCommands {
36
37
  const analyticsCookies = yield analytics.getAnalyticsCookies();
37
38
  const cas = getClientArgsWithDefaults(clientArgs);
38
39
  const credentialArgs = cas.credentials || envCredentials();
39
- const httpClient = new HttpClientGot(credentialArgs === null || credentialArgs === void 0 ? void 0 : credentialArgs.token, analyticsHeaders, analyticsCookies);
40
+ const proxyAgentArgs = cas.proxyAgents || (yield buildProxyAgentArgsFromEnvironment());
41
+ const httpClient = new HttpClientGot(credentialArgs === null || credentialArgs === void 0 ? void 0 : credentialArgs.token, analyticsHeaders, analyticsCookies, proxyAgentArgs);
40
42
  return new UiControlClient(httpClient, cas, credentialArgs === null || credentialArgs === void 0 ? void 0 : credentialArgs.workspaceId);
41
43
  });
42
44
  }
@@ -47,7 +49,7 @@ export class UiControlClient extends ApiCommands {
47
49
  return this._uiControllerClient;
48
50
  }
49
51
  get inferenceClient() {
50
- return new InferenceClient(this.clientArgs.inferenceServerUrl, this.httpClient, this.workspaceId);
52
+ return new InferenceClient(this.clientArgs.inferenceServerUrl, this.httpClient, this.clientArgs.resize, this.workspaceId);
51
53
  }
52
54
  get executionRuntime() {
53
55
  return new ExecutionRuntime(this.uiControllerClient, this.inferenceClient);
@@ -1,10 +1,19 @@
1
1
  import { AnnotationLevel } from './annotation-level';
2
2
  import { CredentialArgs } from './credentials-args';
3
+ import { ProxyAgentArgs } from '../shared/proxy-agent-args';
3
4
  /**
4
5
  * Configuration options for the askui UI Control Client
5
6
  *
6
7
  * @param {string} uiControllerUrl - Default: http://127.0.0.1:6769
7
8
  * The adress of the askui UI Controller server.
9
+ * @param {(number | undefined)} resize - Default: undefined
10
+ * The resizing will be skipped if it's undefined.
11
+ * The side length of the target image to resize to in px.
12
+ * Your screenshot image will be resized with the original aspect ratio,
13
+ * and the lengths image side will be equal to this number.
14
+ * This can be used to reduce the inference time by reducing
15
+ * the request size in case of a bad internet connection.
16
+ * But it can cause a decrease in the prediction quality.
8
17
  * @param {string} inferenceClientUrl - Default: https://inference.askui.com`
9
18
  * Address of the askui Inference server.
10
19
  * @param {AnnotationLevel} annotationLevel - Default: AnnotationLevel.DISABLED
@@ -13,12 +22,16 @@ import { CredentialArgs } from './credentials-args';
13
22
  * You have three options: `DISABLED`, `ON_FAILURE`, `ALL`.
14
23
  * @param {CredentialArgs} credentials - We need to provide credentials for
15
24
  * the authentication of the askui Inference Server.
25
+ * You have three options: `DISABLED`, `ON_FAILURE`, `ALL`.
26
+ * @param {ProxyAgentArgs} proxyAgents - To configure the proxy agents for http(s) requests.
16
27
  */
17
28
  export interface ClientArgs {
18
29
  readonly uiControllerUrl?: string;
19
30
  readonly inferenceServerUrl?: string;
20
31
  readonly annotationLevel?: AnnotationLevel;
21
32
  readonly credentials?: CredentialArgs;
33
+ readonly proxyAgents?: ProxyAgentArgs;
34
+ readonly resize?: number;
22
35
  }
23
36
  export interface ClientArgsWithDefaults extends ClientArgs {
24
37
  readonly uiControllerUrl: string;
@@ -1,3 +1,6 @@
1
+ /// <reference types="node" />
2
+ import http from 'http';
3
+ import https from 'https';
1
4
  declare enum SupportedPlatform {
2
5
  LINUX = "linux",
3
6
  DARWIN = "darwin",
@@ -5,5 +8,8 @@ declare enum SupportedPlatform {
5
8
  }
6
9
  export declare function platform(): SupportedPlatform;
7
10
  export declare function getBinaryPath(version: string): string;
8
- export declare function downloadServerBinaries(binaryVersion: string): Promise<void>;
11
+ export declare function downloadServerBinaries(binaryVersion: string, proxyAgent?: {
12
+ http: http.Agent;
13
+ https: https.Agent;
14
+ }): Promise<void>;
9
15
  export {};
@@ -36,7 +36,7 @@ function getBinaryDownloadUrl(binaryVersion) {
36
36
  const arch = os.arch();
37
37
  return `${baseUrl}/${platform()}/${arch}/${binarySubPathsByPlatform[platform()][1]}`;
38
38
  }
39
- export function downloadServerBinaries(binaryVersion) {
39
+ export function downloadServerBinaries(binaryVersion, proxyAgent) {
40
40
  return new Promise((resolve, reject) => {
41
41
  const url = getBinaryDownloadUrl(binaryVersion);
42
42
  const binaryOutputPath = getBinaryPath(binaryVersion);
@@ -45,7 +45,7 @@ export function downloadServerBinaries(binaryVersion) {
45
45
  if (!(fs.existsSync(binaryFolder))) {
46
46
  fs.mkdirSync(binaryFolder, { recursive: true });
47
47
  }
48
- const downloadStream = got.stream(url);
48
+ const downloadStream = got.stream(url, proxyAgent ? { agent: proxyAgent } : {});
49
49
  const fileWriterStream = fs.createWriteStream(binaryOutputPath);
50
50
  downloadStream.on('error', () => {
51
51
  reject();
@@ -1,3 +1,4 @@
1
+ import { ProxyAgentArgs } from '../shared/proxy-agent-args';
1
2
  import { LogLevels } from '../shared/log-levels';
2
3
  /**
3
4
  * Configuration options for the askui UI Controller
@@ -5,6 +6,7 @@ import { LogLevels } from '../shared/log-levels';
5
6
  * @param {number} display - Default: `0`
6
7
  * You can choose on which display you want to excecute all tests.
7
8
  * 0 is your main monitor.
9
+ *
8
10
  * If you want to use your second monitor you can change
9
11
  * the value to `1` (`2` for your third monitor etc.).
10
12
  * @param {string} binaryVersion - Default: `'latest'`
@@ -26,6 +28,7 @@ import { LogLevels } from '../shared/log-levels';
26
28
  * @param {string} logFilePath - Default: `'<temp-dir>/askui/askui-server.log'`
27
29
  * It is possible to specify a path for your log files.
28
30
  * Per default we create the askui-server.log file and askui folder in your temp folder.
31
+ * @param {ProxyAgentArgs} proxyAgents - To configure the proxy agents for our http(s) requests.
29
32
  */
30
33
  export interface UiControllerArgs {
31
34
  readonly display?: number;
@@ -37,6 +40,7 @@ export interface UiControllerArgs {
37
40
  readonly overWriteBinary?: boolean;
38
41
  readonly logLevel?: LogLevels;
39
42
  readonly logFilePath?: string;
43
+ readonly proxyAgents?: ProxyAgentArgs;
40
44
  }
41
45
  export interface UiControllerArgsWithDefaults extends UiControllerArgs {
42
46
  readonly display: number;
@@ -18,6 +18,7 @@ import { downloadServerBinaries, getBinaryPath } from './download-binaries';
18
18
  import { logger } from './logger';
19
19
  import { TimeoutError } from './timeout-error';
20
20
  import { UnkownError } from './unkown-error';
21
+ import { buildProxyAgentArgsFromEnvironment } from '../utils/proxy/proxy-builder';
21
22
  export class UiControllerFacade {
22
23
  constructor() {
23
24
  this.binaryPath = getBinaryPath('latest');
@@ -29,7 +30,7 @@ export class UiControllerFacade {
29
30
  const argsWithDefaults = createArgsWithDefaults(args);
30
31
  const argsWithLogPath = this.serverLogFilePath(argsWithDefaults);
31
32
  this.binaryPath = getBinaryPath(argsWithLogPath.binaryVersion);
32
- yield this.getBinary(argsWithLogPath.binaryVersion, argsWithLogPath.overWriteBinary);
33
+ yield this.getBinary(argsWithLogPath.binaryVersion, argsWithLogPath.overWriteBinary, argsWithLogPath.proxyAgents || (yield buildProxyAgentArgsFromEnvironment()));
33
34
  this.makeBinaryExecutable();
34
35
  logger.debug(`UI Controller log path "${this.serverLogFile}"`);
35
36
  yield this.startWithDefaults(argsWithLogPath, maxWaitingForStartingInSeconds);
@@ -103,11 +104,11 @@ export class UiControllerFacade {
103
104
  const binarysizeInMB = fs.statSync(this.binaryPath).size / (1024 * 1024);
104
105
  return binarysizeInMB > sizeThresholdInMB;
105
106
  }
106
- getBinary(binaryVersion, overWriteBinary = false) {
107
+ getBinary(binaryVersion, overWriteBinary = false, proxyAgent) {
107
108
  return __awaiter(this, void 0, void 0, function* () {
108
109
  if (!fs.existsSync(this.binaryPath) || overWriteBinary || !this.isBinaryValid()) {
109
110
  logger.debug(`Currently, no binary of the UI Controller is available at "${this.binaryPath}"`);
110
- yield downloadServerBinaries(binaryVersion);
111
+ yield downloadServerBinaries(binaryVersion, proxyAgent);
111
112
  }
112
113
  else {
113
114
  logger.debug(`Binary of UI Controller is already present at "${this.binaryPath}".`);
@@ -0,0 +1,35 @@
1
+ /// <reference types="node" />
2
+ import http from 'http';
3
+ import https from 'https';
4
+ /**
5
+ * Proxy agent configuration for HTTP(S) requests
6
+ *
7
+ * All modules which implement the `http.Agent`'s or `https.Agent`'s
8
+ * interface, respectively, can be used.
9
+ * We recommend to use [hpagent](https://github.com/delvedore/hpagent).
10
+ *
11
+ * Installation:
12
+ * ```shell
13
+ * npm install --save hpagent
14
+ * ```
15
+ *
16
+ * Configuration:
17
+ * ```typescript
18
+ * const httpProxyUrl = "http://your-proxy:3128";
19
+ * const httpsProxyUrl = "https://your-proxy:3129";
20
+ *
21
+ * const aui = await UiControlClient.build({
22
+ * proxyAgents: {
23
+ * http: new HttpProxyAgent({ proxy: httpProxyUrl }),
24
+ * https: new HttpsProxyAgent({ proxy: httpsProxyUrl }),
25
+ * },
26
+ * });
27
+ * ```
28
+ *
29
+ * @param {http.Agent} http - Agent for http requests
30
+ * @param {https.Agent} https - Agent for https requests
31
+ ** */
32
+ export interface ProxyAgentArgs {
33
+ http: http.Agent;
34
+ https: https.Agent;
35
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,10 +1,20 @@
1
1
  import { OptionsOfJSONResponseBody } from 'got';
2
+ import http from 'http';
3
+ import https from 'https';
2
4
  export declare class HttpClientGot {
3
5
  readonly token?: string | undefined;
4
6
  readonly customHeaders?: Record<string, string> | undefined;
5
7
  private readonly cookies;
8
+ readonly proxyAgents?: {
9
+ http: http.Agent;
10
+ https: https.Agent;
11
+ } | undefined;
6
12
  private headers;
7
- constructor(token?: string | undefined, customHeaders?: Record<string, string> | undefined, cookies?: Record<string, string>);
13
+ private askuiGot;
14
+ constructor(token?: string | undefined, customHeaders?: Record<string, string> | undefined, cookies?: Record<string, string>, proxyAgents?: {
15
+ http: http.Agent;
16
+ https: https.Agent;
17
+ } | undefined);
8
18
  private initHeaders;
9
19
  private injectHeadersAndCookies;
10
20
  post<T>(url: string, data: Record<string | number | symbol, unknown>): Promise<T>;
@@ -13,12 +13,14 @@ import { logger } from '../../lib';
13
13
  import { Credentials } from './credentials';
14
14
  import { httpClientErrorHandler } from './custom-errors';
15
15
  export class HttpClientGot {
16
- constructor(token, customHeaders, cookies = {}) {
16
+ constructor(token, customHeaders, cookies = {}, proxyAgents) {
17
17
  this.token = token;
18
18
  this.customHeaders = customHeaders;
19
19
  this.cookies = cookies;
20
+ this.proxyAgents = proxyAgents;
20
21
  this.headers = {};
21
22
  this.initHeaders(token, customHeaders);
23
+ this.askuiGot = got.extend(proxyAgents ? { agent: proxyAgents } : {});
22
24
  }
23
25
  initHeaders(token, customHeaders = {}) {
24
26
  const credentials = token ? new Credentials(token) : undefined;
@@ -34,7 +36,7 @@ export class HttpClientGot {
34
36
  post(url, data) {
35
37
  return __awaiter(this, void 0, void 0, function* () {
36
38
  const options = this.injectHeadersAndCookies(url, { json: data, responseType: 'json', throwHttpErrors: false });
37
- const { body, statusCode, headers } = yield got.post(url, options);
39
+ const { body, statusCode, headers } = yield this.askuiGot.post(url, options);
38
40
  if (headers['deprecation'] !== undefined) {
39
41
  logger.warn(headers['deprecation']);
40
42
  }
@@ -46,7 +48,7 @@ export class HttpClientGot {
46
48
  }
47
49
  get(url, options = { responseType: 'json' }) {
48
50
  return __awaiter(this, void 0, void 0, function* () {
49
- const response = yield got.get(url, this.injectHeadersAndCookies(url, options));
51
+ const response = yield this.askuiGot.get(url, this.injectHeadersAndCookies(url, options));
50
52
  return response.body;
51
53
  });
52
54
  }
@@ -0,0 +1,4 @@
1
+ import { ProxyAgentArgs } from '../../shared/proxy-agent-args';
2
+ export declare class ProxyImportError extends Error {
3
+ }
4
+ export declare function buildProxyAgentArgsFromEnvironment(): Promise<ProxyAgentArgs | undefined>;
@@ -0,0 +1,43 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { logger } from '../../lib/logger';
11
+ export class ProxyImportError extends Error {
12
+ }
13
+ function dynmicImportHpagent() {
14
+ return __awaiter(this, void 0, void 0, function* () {
15
+ try {
16
+ // eslint-disable-next-line import/no-extraneous-dependencies
17
+ return yield import('hpagent');
18
+ }
19
+ catch (err) {
20
+ throw new ProxyImportError('Can\'t find "hpagent" module to configure proxy! Please, install hpagent for proxy support with "npm install --save-dev hpagent".');
21
+ }
22
+ });
23
+ }
24
+ export function buildProxyAgentArgsFromEnvironment() {
25
+ return __awaiter(this, void 0, void 0, function* () {
26
+ const httpProxyUrl = process.env['HTTP_PROXY'];
27
+ const httpsProxyUrl = process.env['HTTPS_PROXY'];
28
+ if (httpProxyUrl === undefined && httpsProxyUrl === undefined) {
29
+ logger.debug('No proxy defined. "HTTPS_PROXY" and "HTTP_PROXY" environment variables are empty.');
30
+ return undefined;
31
+ }
32
+ const hpagent = yield dynmicImportHpagent();
33
+ logger.info('Using proxy! One of following environment variables are defined: "HTTPS_PROXY", "https_proxy", "HTTP_PROXY" and "http_proxy"');
34
+ return {
35
+ http: new hpagent.HttpProxyAgent({
36
+ proxy: (httpProxyUrl || httpsProxyUrl),
37
+ }),
38
+ https: new hpagent.HttpsProxyAgent({
39
+ proxy: (httpsProxyUrl || httpProxyUrl),
40
+ }),
41
+ };
42
+ });
43
+ }
@@ -31,9 +31,9 @@ beforeAll(async () => {
31
31
  });
32
32
 
33
33
  afterAll(async () => {
34
- await uiController.stop();
35
-
36
34
  aui.close();
35
+
36
+ await uiController.stop();
37
37
  });
38
38
 
39
39
  export { aui };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "askui",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "license": "MIT",
5
5
  "author": "askui GmbH <info@askui.com> (http://www.askui.com/)",
6
6
  "description": "Reliable, automated end-to-end-testing that depends on what is shown on your screen instead of the technology you are running on",
@@ -39,7 +39,7 @@
39
39
  "copyExampleProject": "shx cp -r example_projects_templates/ dist/ && shx cp -r bin/* dist/",
40
40
  "lint": "eslint --cache --fix --max-warnings 0 \"./**/*.{js,ts}\"",
41
41
  "lint:staged": "lint-staged",
42
- "test": "jest '/src'",
42
+ "test": "NODE_EXTRA_CA_CERTS='test/proxy/certs/unit_test.pem' jest '/src'",
43
43
  "postinstall": "node -e \"require('./bin/askui-postinstall')\""
44
44
  },
45
45
  "files": [
@@ -73,7 +73,10 @@
73
73
  "@types/url-join": "4.0.1",
74
74
  "@types/webrtc": "0.0.30",
75
75
  "@types/ws": "7.4.4",
76
+ "hpagent": "^1.2.0",
76
77
  "jest": "28.1.1",
78
+ "proxy": "^1.0.2",
79
+ "proxy-agent": "^5.0.0",
77
80
  "sharp": "0.30.6",
78
81
  "shx": "0.3.4",
79
82
  "ts-jest": "28.0.4",