polarity-integration-utils 0.1.0 → 2.0.8

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 (118) hide show
  1. package/README.md +30 -2
  2. package/dist/dts/errors/api-request-error.d.ts +10 -0
  3. package/dist/dts/errors/api-request-error.d.ts.map +1 -0
  4. package/dist/dts/errors/auth-request-error.d.ts +10 -0
  5. package/dist/dts/errors/auth-request-error.d.ts.map +1 -0
  6. package/dist/dts/errors/index.d.ts +8 -0
  7. package/dist/dts/errors/index.d.ts.map +1 -0
  8. package/dist/dts/errors/integration-error.d.ts +189 -0
  9. package/dist/dts/errors/integration-error.d.ts.map +1 -0
  10. package/dist/dts/errors/library-usage-error.d.ts +12 -0
  11. package/dist/dts/errors/library-usage-error.d.ts.map +1 -0
  12. package/dist/dts/errors/network-error.d.ts +11 -0
  13. package/dist/dts/errors/network-error.d.ts.map +1 -0
  14. package/dist/dts/errors/parse-error-to-readable-json.d.ts +7 -0
  15. package/dist/dts/errors/parse-error-to-readable-json.d.ts.map +1 -0
  16. package/dist/dts/errors/retry-request-error.d.ts +11 -0
  17. package/dist/dts/errors/retry-request-error.d.ts.map +1 -0
  18. package/dist/dts/index.d.ts +5 -0
  19. package/dist/dts/index.d.ts.map +1 -0
  20. package/dist/dts/index.docs.d.ts +9 -0
  21. package/dist/dts/index.docs.d.ts.map +1 -0
  22. package/dist/dts/internal/helpers/parallel-limit.d.ts +9 -0
  23. package/dist/dts/internal/helpers/parallel-limit.d.ts.map +1 -0
  24. package/dist/dts/internal/helpers/sanitize-object.d.ts +11 -0
  25. package/dist/dts/internal/helpers/sanitize-object.d.ts.map +1 -0
  26. package/dist/dts/logging/index.d.ts +2 -0
  27. package/dist/dts/logging/index.d.ts.map +1 -0
  28. package/dist/dts/logging/logger.d.ts +49 -0
  29. package/dist/dts/logging/logger.d.ts.map +1 -0
  30. package/dist/dts/requests/index.d.ts +3 -0
  31. package/dist/dts/requests/index.d.ts.map +1 -0
  32. package/dist/dts/requests/polarity-request.d.ts +411 -0
  33. package/dist/dts/requests/polarity-request.d.ts.map +1 -0
  34. package/dist/dts/requests/sanitize-request-options.d.ts +20 -0
  35. package/dist/dts/requests/sanitize-request-options.d.ts.map +1 -0
  36. package/dist/dts/types.d.ts +104 -0
  37. package/dist/dts/types.d.ts.map +1 -0
  38. package/dist/es/errors/api-request-error.js +15 -0
  39. package/dist/es/errors/auth-request-error.js +15 -0
  40. package/dist/es/errors/index.js +20 -8
  41. package/dist/es/errors/integration-error.js +116 -0
  42. package/dist/es/errors/library-usage-error.js +17 -0
  43. package/dist/es/errors/network-error.js +88 -0
  44. package/dist/es/errors/parse-error-to-readable-json.js +9 -0
  45. package/dist/es/errors/retry-request-error.js +16 -0
  46. package/dist/es/index.docs.js +24 -0
  47. package/dist/es/index.js +40 -14
  48. package/dist/es/internal/helpers/parallel-limit.js +36 -0
  49. package/dist/es/internal/helpers/sanitize-object.js +37 -0
  50. package/dist/es/logging/index.js +15 -2
  51. package/dist/es/logging/logger.js +41 -5
  52. package/dist/es/requests/index.js +15 -8
  53. package/dist/es/requests/polarity-request.js +426 -0
  54. package/dist/es/requests/sanitize-request-options.js +50 -0
  55. package/dist/lib/errors/api-request-error.js +15 -0
  56. package/dist/lib/errors/auth-request-error.js +15 -0
  57. package/dist/lib/errors/index.js +20 -8
  58. package/dist/lib/errors/integration-error.js +116 -0
  59. package/dist/lib/errors/library-usage-error.js +17 -0
  60. package/dist/lib/errors/network-error.js +88 -0
  61. package/dist/lib/errors/parse-error-to-readable-json.js +9 -0
  62. package/dist/lib/errors/retry-request-error.js +16 -0
  63. package/dist/lib/index.docs.js +24 -0
  64. package/dist/lib/index.js +40 -14
  65. package/dist/lib/internal/helpers/parallel-limit.js +36 -0
  66. package/dist/lib/internal/helpers/sanitize-object.js +37 -0
  67. package/dist/lib/logging/index.js +15 -2
  68. package/dist/lib/logging/logger.js +41 -5
  69. package/dist/lib/requests/index.js +15 -8
  70. package/dist/lib/requests/polarity-request.js +426 -0
  71. package/dist/lib/requests/sanitize-request-options.js +50 -0
  72. package/dist/polarity-integration-utils.d.ts +852 -0
  73. package/dist/tsdoc-metadata.json +11 -0
  74. package/package.json +59 -10
  75. package/dist/es/errors/RequestError.js +0 -12
  76. package/dist/es/errors/parseErrorToReadableJson.js +0 -4
  77. package/dist/es/helpers/async/index.js +0 -9
  78. package/dist/es/helpers/async/parallelLimit.js +0 -33
  79. package/dist/es/helpers/encodings/decodeBase64.js +0 -4
  80. package/dist/es/helpers/encodings/encodeBase64.js +0 -4
  81. package/dist/es/helpers/encodings/index.js +0 -11
  82. package/dist/es/helpers/index.js +0 -10
  83. package/dist/es/helpers/json/and.js +0 -4
  84. package/dist/es/helpers/json/filterObjectsContainingString.js +0 -10
  85. package/dist/es/helpers/json/index.js +0 -17
  86. package/dist/es/helpers/json/mapOverObject.js +0 -24
  87. package/dist/es/helpers/json/or.js +0 -4
  88. package/dist/es/helpers/json/transpose2dArray.js +0 -8
  89. package/dist/es/helpers/time/index.js +0 -11
  90. package/dist/es/helpers/time/millisecondsToHoursMinutesAndSeconds.js +0 -18
  91. package/dist/es/helpers/time/sleep.js +0 -13
  92. package/dist/es/requests/createRequestWithDefaults.js +0 -166
  93. package/dist/es/requests/createRequestsInParallel.js +0 -40
  94. package/dist/es/user-options/index.js +0 -9
  95. package/dist/es/user-options/validateUrlOption.js +0 -77
  96. package/dist/lib/errors/RequestError.js +0 -12
  97. package/dist/lib/errors/parseErrorToReadableJson.js +0 -4
  98. package/dist/lib/helpers/async/index.js +0 -9
  99. package/dist/lib/helpers/async/parallelLimit.js +0 -33
  100. package/dist/lib/helpers/encodings/decodeBase64.js +0 -4
  101. package/dist/lib/helpers/encodings/encodeBase64.js +0 -4
  102. package/dist/lib/helpers/encodings/index.js +0 -11
  103. package/dist/lib/helpers/index.js +0 -10
  104. package/dist/lib/helpers/json/and.js +0 -4
  105. package/dist/lib/helpers/json/filterObjectsContainingString.js +0 -10
  106. package/dist/lib/helpers/json/index.js +0 -17
  107. package/dist/lib/helpers/json/mapOverObject.js +0 -24
  108. package/dist/lib/helpers/json/or.js +0 -4
  109. package/dist/lib/helpers/json/transpose2dArray.js +0 -8
  110. package/dist/lib/helpers/time/index.js +0 -11
  111. package/dist/lib/helpers/time/millisecondsToHoursMinutesAndSeconds.js +0 -18
  112. package/dist/lib/helpers/time/sleep.js +0 -13
  113. package/dist/lib/requests/createRequestWithDefaults.js +0 -166
  114. package/dist/lib/requests/createRequestsInParallel.js +0 -40
  115. package/dist/lib/user-options/index.js +0 -9
  116. package/dist/lib/user-options/validateUrlOption.js +0 -77
  117. /package/dist/es/{requests/requestTypes.js → types.js} +0 -0
  118. /package/dist/lib/{requests/requestTypes.js → types.js} +0 -0
@@ -0,0 +1,11 @@
1
+ // This file is read by tools that parse documentation comments conforming to the TSDoc standard.
2
+ // It should be published with your NPM package. It should not be tracked by Git.
3
+ {
4
+ "tsdocVersion": "0.12",
5
+ "toolPackages": [
6
+ {
7
+ "packageName": "@microsoft/api-extractor",
8
+ "packageVersion": "7.52.13"
9
+ }
10
+ ]
11
+ }
package/package.json CHANGED
@@ -1,25 +1,62 @@
1
1
  {
2
2
  "name": "polarity-integration-utils",
3
- "version": "0.1.0",
3
+ "version": "2.0.8",
4
4
  "description": "A utility library for building Polarity Integrations",
5
5
  "files": [
6
6
  "dist"
7
7
  ],
8
8
  "main": "dist/lib/index.js",
9
9
  "module": "dist/es/index.js",
10
+ "types": "dist/polarity-integration-utils.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "import": "./dist/es/index.js",
14
+ "require": "./dist/lib/index.js"
15
+ },
16
+ "./logging": {
17
+ "import": "./dist/es/logging/index.js",
18
+ "require": "./dist/lib/logging/index.js"
19
+ },
20
+ "./requests": {
21
+ "import": "./dist/es/requests/index.js",
22
+ "require": "./dist/lib/requests/index.js"
23
+ },
24
+ "./errors": {
25
+ "import": "./dist/es/errors/index.js",
26
+ "require": "./dist/lib/errors/index.js"
27
+ },
28
+ "./user-options": {
29
+ "import": "./dist/es/user-options/index.js",
30
+ "require": "./dist/lib/user-options/index.js"
31
+ },
32
+ "./helpers": {
33
+ "import": "./dist/es/helpers/index.js",
34
+ "require": "./dist/lib/helpers/index.js"
35
+ }
36
+ },
10
37
  "scripts": {
11
- "test": "jest",
38
+ "test": "jest --coverageReporters=\"text-summary\"",
39
+ "coverage": "jest --coverage",
40
+ "coverage-lcov": "jest --coverage --coverageReporters=lcov",
12
41
  "ci": "npm run test",
13
42
  "clean": "rm -rf dist/*",
14
43
  "build:es": "tsc -p tsconfig.build.es.json --outDir dist/es",
15
44
  "build:lib": "tsc -p tsconfig.build.json --outDir dist/lib",
16
- "build": "npm run clean && npm run build:lib && npm run build:es",
45
+ "build:declarations": "npx api-extractor run --local --diagnostics",
46
+ "build:docs": "npx typedoc",
47
+ "build": "npm run clean && npm run build:lib && npm run build:es && npm run build:declarations && npm run build:docs",
48
+ "build:es:watch": "tsc --watch -p tsconfig.build.es.json --outDir dist/es",
49
+ "build:lib:watch": "tsc --watch -p tsconfig.build.json --outDir dist/lib",
17
50
  "prepublishOnly": "npm run ci && npm run build",
18
- "fullPublish": "npm run prepublishOnly && npm publish"
51
+ "fullPublish": "npm install && npm run prepublishOnly && npm publish",
52
+ "lint": "tsc --noEmit && eslint .",
53
+ "lint:fix": "eslint . --fix",
54
+ "lint:ts": "tsc --noEmit",
55
+ "lint:es": "eslint ."
19
56
  },
20
57
  "repository": {
21
58
  "type": "git",
22
- "url": "git+https://github.com/polarity-integration-utils/polarity-integration-utils.git"
59
+ "url": "https://github.com/polarityio/polarity-integration-utils"
23
60
  },
24
61
  "author": "Polarity IO <support@polarity.io>",
25
62
  "license": "MIT",
@@ -28,15 +65,27 @@
28
65
  },
29
66
  "homepage": "https://github.com/polarity-integration-utils/polarity-integration-utils#readme",
30
67
  "devDependencies": {
31
- "@types/jest": "^24.0.14",
32
- "nock": "^13.3.1",
33
- "ts-jest": "^29.1.0",
34
- "typescript": "^5.0.4"
68
+ "@eslint/js": "^9.36.0",
69
+ "@microsoft/api-extractor": "^7.52.13",
70
+ "@types/jest": "^30.0.0",
71
+ "@types/lodash": "^4.17.20",
72
+ "@types/node": "^20.14.8",
73
+ "@typescript-eslint/eslint-plugin": "^8.44.0",
74
+ "@typescript-eslint/parser": "^8.44.0",
75
+ "copy-paste": "^2.2.0",
76
+ "eslint": "^9.36.0",
77
+ "eslint-plugin-tsdoc": "^0.4.0",
78
+ "globals": "^16.4.0",
79
+ "jest": "^30.1.3",
80
+ "ts-jest": "^29.4.4",
81
+ "typedoc": "^0.28.13",
82
+ "typescript": "^5.9.2",
83
+ "typescript-eslint": "^8.44.0"
35
84
  },
36
85
  "dependencies": {
37
86
  "bottleneck": "^2.19.5",
38
87
  "lodash": "^4.17.21",
39
- "postman-request": "^2.88.1-postman.32"
88
+ "postman-request": "^2.88.1-postman.43"
40
89
  },
41
90
  "sideEffects": false
42
91
  }
@@ -1,12 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- class RequestError extends Error {
4
- constructor(message, status, description, requestOptions) {
5
- super();
6
- this.message = `Request Error${message ? ` -> ${message}` : ''}`;
7
- this.status = status;
8
- this.description = description;
9
- this.requestOptions = requestOptions;
10
- }
11
- }
12
- exports.default = RequestError;
@@ -1,4 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const parseErrorToReadableJson = (error) => JSON.parse(JSON.stringify(error, Object.getOwnPropertyNames(error)));
4
- exports.default = parseErrorToReadableJson;
@@ -1,9 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const parallelLimit_1 = __importDefault(require("./parallelLimit"));
7
- exports.default = {
8
- parallelLimit: parallelLimit_1.default
9
- };
@@ -1,33 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- const parallelLimit = (tasksQueue, simultaneousTaskRunningLimit, returnErrors = false) => __awaiter(void 0, void 0, void 0, function* () {
13
- const results = [];
14
- const runTasks = (tasksIterator) => __awaiter(void 0, void 0, void 0, function* () {
15
- for (const [index, task] of tasksIterator) {
16
- try {
17
- results[index] = yield task();
18
- }
19
- catch (error) {
20
- if (returnErrors)
21
- results[index] = error;
22
- else
23
- throw error;
24
- }
25
- }
26
- });
27
- const workers = new Array(simultaneousTaskRunningLimit)
28
- .fill(tasksQueue.entries())
29
- .map(runTasks);
30
- yield Promise.allSettled(workers);
31
- return results;
32
- });
33
- exports.default = parallelLimit;
@@ -1,4 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const decodeBase64 = (str) => str && Buffer.from(str, 'base64').toString('ascii');
4
- exports.default = decodeBase64;
@@ -1,4 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const encodeBase64 = (str) => str && Buffer.from(str).toString('base64');
4
- exports.default = encodeBase64;
@@ -1,11 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const encodeBase64_1 = __importDefault(require("./encodeBase64"));
7
- const decodeBase64_1 = __importDefault(require("./decodeBase64"));
8
- exports.default = {
9
- encodeBase64: encodeBase64_1.default,
10
- decodeBase64: decodeBase64_1.default
11
- };
@@ -1,10 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const time_1 = __importDefault(require("./time"));
7
- const json_1 = __importDefault(require("./json"));
8
- const encodings_1 = __importDefault(require("./encodings"));
9
- const async_1 = __importDefault(require("./async"));
10
- exports.default = Object.assign(Object.assign(Object.assign(Object.assign({}, time_1.default), json_1.default), encodings_1.default), async_1.default);
@@ -1,4 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const and = (...[func, ...funcs]) => (x) => !!func(x) && (funcs.length ? !!and.apply(null, funcs)(x) : true);
4
- exports.default = and;
@@ -1,10 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const fp_1 = require("lodash/fp");
4
- const filterObjectsContainingString = (0, fp_1.curry)((string, objs = []) => {
5
- const modifiedSearchString = (0, fp_1.flow)((0, fp_1.replace)(/[^\w]/g, ''), fp_1.toLower)(string);
6
- if (!modifiedSearchString)
7
- return [];
8
- return (0, fp_1.filter)((0, fp_1.flow)(JSON.stringify, (0, fp_1.replace)(/[^\w]/g, ''), fp_1.toLower, (0, fp_1.includes)(modifiedSearchString)), objs);
9
- });
10
- exports.default = filterObjectsContainingString;
@@ -1,17 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const transpose2dArray_1 = __importDefault(require("./transpose2dArray"));
7
- const mapOverObject_1 = __importDefault(require("./mapOverObject"));
8
- const filterObjectsContainingString_1 = __importDefault(require("./filterObjectsContainingString"));
9
- const and_1 = __importDefault(require("./and"));
10
- const or_1 = __importDefault(require("./or"));
11
- exports.default = {
12
- transpose2dArray: transpose2dArray_1.default,
13
- mapOverObject: mapOverObject_1.default,
14
- filterObjectsContainingString: filterObjectsContainingString_1.default,
15
- and: and_1.default,
16
- or: or_1.default
17
- };
@@ -1,24 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const fp_1 = require("lodash/fp");
7
- const and_1 = __importDefault(require("./and"));
8
- /**
9
- * Function to map over properties in an object.
10
- * This allows for transformations on both the keys and values of each properties.
11
- * This function also supports currying
12
- *
13
- * @param func - function that takes in `value` & `key' from each object property and
14
- * returns a new key and new value in an array of length 2
15
- * e.g. (value, key) => [newKey, newValue]
16
- * @param obj - JSON object which we wish to map over the properties of
17
- * e.g. { key1: value1, key2: value2 }
18
- * @returns - JSON object with the transformed keys and values for each property
19
- * e.g. { newKey1: newValue1, newKey2: newValue2 }
20
- */
21
- const mapOverObject = (0, fp_1.curry)((func, obj) => obj && (0, fp_1.isPlainObject)(obj)
22
- ? (0, fp_1.flow)(Object.entries, (0, fp_1.map)(([key, value]) => func(value, key)), (0, fp_1.filter)((0, and_1.default)((0, fp_1.negate)(fp_1.isEmpty), (0, fp_1.flow)(fp_1.size, (0, fp_1.eq)(2)))), Object.fromEntries)(obj)
23
- : obj);
24
- exports.default = mapOverObject;
@@ -1,4 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const or = (...[func, ...funcs]) => (x) => !!func(x) || (!!funcs.length && !!or.apply(null, funcs)(x));
4
- exports.default = or;
@@ -1,8 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const fp_1 = require("lodash/fp");
4
- const transpose2dArray = (twoDimensionalArray) => (0, fp_1.reduce)((agg, [key, value]) => [
5
- [...agg[0], key],
6
- [...agg[1], value]
7
- ], [[], []], twoDimensionalArray);
8
- exports.default = transpose2dArray;
@@ -1,11 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const sleep_1 = __importDefault(require("./sleep"));
7
- const millisecondsToHoursMinutesAndSeconds_1 = __importDefault(require("./millisecondsToHoursMinutesAndSeconds"));
8
- exports.default = {
9
- sleep: sleep_1.default,
10
- millisecondsToHoursMinutesAndSeconds: millisecondsToHoursMinutesAndSeconds_1.default
11
- };
@@ -1,18 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const millisecondsToHoursMinutesAndSeconds = (milliseconds = 0) => {
4
- if (typeof milliseconds !== 'number' || isNaN(milliseconds)) {
5
- throw new Error(`Cannot calculate Hours, Minutes, or Seconds from non-number input: \`${milliseconds}\``);
6
- }
7
- let remainingMilliseconds = milliseconds;
8
- const seconds = Math.floor((remainingMilliseconds / 1000) % 60);
9
- remainingMilliseconds -= seconds * 1000;
10
- const minutes = Math.floor((remainingMilliseconds / 60000) % 60);
11
- remainingMilliseconds -= minutes * 60000;
12
- const hours = Math.floor(remainingMilliseconds / 3600000);
13
- return ((hours ? `${hours} hours${minutes || seconds ? ', ' : ''}` : '') +
14
- (minutes ? `${minutes} minutes${seconds ? ', ' : ''}` : '') +
15
- (seconds ? `${seconds} seconds` : '') +
16
- (!hours && !minutes && !seconds ? `${milliseconds}ms` : ''));
17
- };
18
- exports.default = millisecondsToHoursMinutesAndSeconds;
@@ -1,13 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- const sleep = (ms = 2000) => __awaiter(void 0, void 0, void 0, function* () { return new Promise((r) => setTimeout(r, ms)); });
13
- exports.default = sleep;
@@ -1,166 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.requestWithDefaultsBuilder = void 0;
16
- const fs = require("fs");
17
- const postman_request_1 = __importDefault(require("postman-request"));
18
- const fp_1 = require("lodash/fp");
19
- const bottleneck_1 = __importDefault(require("bottleneck"));
20
- const logging_1 = __importDefault(require("../logging"));
21
- const errors_1 = __importDefault(require("../errors"));
22
- const _configFieldIsValid = (field) => typeof field === 'string' && field.length > 0;
23
- let limiter;
24
- function _setupLimiter(options) {
25
- limiter = new bottleneck_1.default({
26
- maxConcurrent: options.maxConcurrentRequests
27
- ? Number.parseInt(options.maxConcurrentRequests, 10)
28
- : 10,
29
- highWater: 50,
30
- strategy: bottleneck_1.default.strategy.OVERFLOW,
31
- minTime: options.minimumMillisecondsRequestWillTake
32
- ? Number.parseInt(options.minimumMillisecondsRequestWillTake, 10)
33
- : 200
34
- });
35
- }
36
- /**
37
- * @param interface CreateRequestFunctionArguments {
38
- * config?: type ConfigJs = {
39
- * request: {
40
- * ca?: string;
41
- * cert?: string;
42
- * key?: string;
43
- * passphrase?: string;
44
- * rejectUnauthorized?: string;
45
- * proxy?: string;
46
- * json?: boolean;
47
- * };
48
- * } | undefined;
49
- * * The entire config.js(on) object
50
- * roundedSuccessStatusCode?: number[];
51
- * * Defaults: [200]
52
- * * Status codes, rounded to the 100's place, that should not throw errors.
53
- * useLimiter?: boolean;
54
- * * Defaults: false
55
- * * Set limit params in options (options.maxConcurrentRequests [default 10] & options.minimumMillisecondsRequestWillTake [default 200]) passed when
56
- * using the RequestWithDefaultsFunction this function returns
57
- * which can be hardcoded or can come from the userOptions directly
58
- * requestOptionsToOmitFromLogsKeyPaths?: string[];
59
- * * Defaults: ['headers.Authorization']
60
- * * Key Paths on the Request Options you wish to not automatically log.
61
- * preprocessRequestOptions?: type PreprocessRequestOptionsFunction =
62
- * (requestOptions: RequestOptions) => Promise<object> | never | undefined;
63
- * postprocessRequestResponse?: type PostprocessRequestResponseFunction =
64
- * (response: any, requestOptions: RequestOptions) => Promise<any> | never | undefined;
65
- * postprocessRequestFailure?: type PostprocessRequestFailureFunction =
66
- * (error: Error, requestOptions: RequestOptions) => Promise<any> | never | undefined;
67
- * }
68
- * @returns type RequestWithDefaultsFunction = (requestOptions: RequestOptions) => Promise<any> | never
69
- * * Returns an async request function with the proxy defaults included in the request options
70
- * * type RequestOptions = {
71
- * url?: string;
72
- * headers?: object;
73
- * qs?: object;
74
- * options?: object;
75
- * entity?: object;
76
- * form?: object;
77
- * [key: string]: any;
78
- * }
79
- };
80
- */
81
- const createRequestWithDefaults = ({ config: { request: { ca, cert, key, passphrase, rejectUnauthorized, proxy, json } } = {
82
- request: {
83
- ca: '',
84
- cert: '',
85
- key: '',
86
- passphrase: '',
87
- proxy: '',
88
- rejectUnauthorized: false,
89
- json: true
90
- }
91
- }, roundedSuccessStatusCodes = [200], useLimiter = false, requestOptionsToOmitFromLogsKeyPaths = ['headers.Authorization'], preprocessRequestOptions = (requestOptions) => __awaiter(void 0, void 0, void 0, function* () { return ({}); }), postprocessRequestResponse = (response, requestOptions) => __awaiter(void 0, void 0, void 0, function* () { return response; }), postprocessRequestFailure = (error, requestOptions) => __awaiter(void 0, void 0, void 0, function* () {
92
- throw error;
93
- }) }) => {
94
- const defaultsProxyOptions = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (_configFieldIsValid(ca) && { ca: fs.readFileSync(ca) })), (_configFieldIsValid(cert) && { cert: fs.readFileSync(cert) })), (_configFieldIsValid(key) && { key: fs.readFileSync(key) })), (_configFieldIsValid(passphrase) && { passphrase })), (_configFieldIsValid(proxy) && { proxy })), (typeof rejectUnauthorized === 'boolean' && { rejectUnauthorized })), { json });
95
- const requestDefaultsWithInterceptors = (0, exports.requestWithDefaultsBuilder)(defaultsProxyOptions, roundedSuccessStatusCodes, useLimiter, requestOptionsToOmitFromLogsKeyPaths, preprocessRequestOptions, postprocessRequestResponse, postprocessRequestFailure);
96
- return requestDefaultsWithInterceptors;
97
- };
98
- const requestWithDefaultsBuilder = (defaultsProxyOptions, roundedSuccessStatusCodes, useLimiter, requestOptionsToOmitFromLogsKeyPaths, preprocessRequestOptions, postprocessRequestResponse, postprocessRequestFailure) => {
99
- const defaultsRequest = postman_request_1.default.defaults(defaultsProxyOptions);
100
- const _requestWithDefaults = (requestOptions) => new Promise((resolve, reject) => {
101
- defaultsRequest(requestOptions, (err, res) => {
102
- if (err)
103
- return reject(err);
104
- resolve(res);
105
- });
106
- });
107
- return (requestOptions) => __awaiter(void 0, void 0, void 0, function* () {
108
- if (useLimiter && !limiter)
109
- _setupLimiter(requestOptions.options);
110
- const preRequestFunctionResults = yield preprocessRequestOptions(requestOptions);
111
- const _requestOptions = Object.assign(Object.assign({}, requestOptions), preRequestFunctionResults);
112
- let postRequestFunctionResults, result;
113
- try {
114
- result = yield (useLimiter
115
- ? limiter.schedule(_requestWithDefaults, _requestOptions)
116
- : _requestWithDefaults(_requestOptions));
117
- checkForStatusError(result, _requestOptions, roundedSuccessStatusCodes, requestOptionsToOmitFromLogsKeyPaths);
118
- postRequestFunctionResults = yield postprocessRequestResponse(result, _requestOptions);
119
- }
120
- catch (error) {
121
- try {
122
- postRequestFunctionResults = yield postprocessRequestFailure(error, _requestOptions);
123
- }
124
- catch (error) {
125
- const err = errors_1.default.parseErrorToReadableJson(error);
126
- if (useLimiter) {
127
- error.maxRequestQueueLimitHit =
128
- ((0, fp_1.isEmpty)(err) && (0, fp_1.isEmpty)(result)) ||
129
- (err &&
130
- (err.message ===
131
- 'This job has been dropped by Bottleneck for going over API Limits' ||
132
- err instanceof bottleneck_1.default.BottleneckError));
133
- error.isConnectionReset =
134
- (0, fp_1.getOr)('', 'errors[0].meta.err.code', err) === 'ECONNRESET';
135
- }
136
- if (_requestOptions.entity)
137
- error.entity = JSON.stringify(_requestOptions.entity);
138
- throw error;
139
- }
140
- }
141
- return postRequestFunctionResults;
142
- });
143
- };
144
- exports.requestWithDefaultsBuilder = requestWithDefaultsBuilder;
145
- const checkForStatusError = ({ statusCode, body }, requestOptions, roundedSuccessStatusCodes, requestOptionsToOmitFromLogsKeyPaths) => {
146
- const Logger = logging_1.default.getLogger();
147
- const requestOptionsWithoutSensitiveData = (0, fp_1.omit)(requestOptionsToOmitFromLogsKeyPaths.concat('options'), requestOptions);
148
- Logger.trace({
149
- MESSAGE: 'Request Ran, Checking Status...',
150
- statusCode,
151
- requestOptions: requestOptionsWithoutSensitiveData,
152
- responseBody: body
153
- });
154
- const roundedStatus = Math.round(statusCode / 100) * 100;
155
- const statusCodeNotSuccessful = !roundedSuccessStatusCodes.includes(roundedStatus);
156
- const responseBodyError = (0, fp_1.get)('error', body);
157
- if (statusCodeNotSuccessful || responseBodyError) {
158
- const message = (0, fp_1.get)('message', responseBodyError);
159
- const status = statusCodeNotSuccessful ? statusCode : (0, fp_1.get)('code', responseBodyError);
160
- const description = JSON.stringify(body);
161
- const requestOptions = JSON.stringify(requestOptionsWithoutSensitiveData);
162
- const requestError = new errors_1.default.RequestError(message, status, description, requestOptions);
163
- throw requestError;
164
- }
165
- };
166
- exports.default = createRequestWithDefaults;
@@ -1,40 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __rest = (this && this.__rest) || function (s, e) {
12
- var t = {};
13
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
- t[p] = s[p];
15
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
- t[p[i]] = s[p[i]];
19
- }
20
- return t;
21
- };
22
- var __importDefault = (this && this.__importDefault) || function (mod) {
23
- return (mod && mod.__esModule) ? mod : { "default": mod };
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- const fp_1 = require("lodash/fp");
27
- const helpers_1 = __importDefault(require("../helpers"));
28
- const createRequestsInParallel = (requestWithDefaults) => (allRequestsOptions, responseGetPath = 'body', possibleSimultaneousRequests = 10, returnErrors = false) => __awaiter(void 0, void 0, void 0, function* () {
29
- const unexecutedRequestFunctions = (0, fp_1.map)((_a) => {
30
- var { entity } = _a, requestOptions = __rest(_a, ["entity"]);
31
- return () => __awaiter(void 0, void 0, void 0, function* () {
32
- const response = yield requestWithDefaults(requestOptions);
33
- const result = responseGetPath ? (0, fp_1.get)(responseGetPath, response) : response;
34
- return entity ? { entity, result } : result;
35
- });
36
- }, allRequestsOptions);
37
- const results = yield helpers_1.default.parallelLimit(unexecutedRequestFunctions, possibleSimultaneousRequests, returnErrors);
38
- return results;
39
- });
40
- exports.default = createRequestsInParallel;
@@ -1,9 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const validateUrlOption_1 = __importDefault(require("./validateUrlOption"));
7
- exports.default = {
8
- validateUrlOption: validateUrlOption_1.default
9
- };
@@ -1,77 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const fp_1 = require("lodash/fp");
4
- /**
5
- *
6
- * @param {object} options - User Options from the inside of validate options
7
- * e.g. each user option contains a metadata object including the value
8
- * { userOption1: { value: 'user option input' ...moreOptionMetadata } }
9
- * @param {string} urlKey - [ default='url' ] The key of the url inside of the user options
10
- * defined via the `./config/config.js(on)` `options.?.key` property value.
11
- * Generally if there is only 1 url user option, the `key` property should be set to
12
- * `url` so the default option here can be used. If there are more than 1 url in the
13
- * user options giving the `options.?.key` properties different value is expected.
14
- * @param {array<objects>} otherValidationErrors - [ default=[] ] Allows you to pass in
15
- * existing validation error objects that will have any new validation errors found
16
- * added onto the end before returned.
17
- * [
18
- * {
19
- * key: 'otherUserOptionKey',
20
- * message: 'Description of something wrong with the users input for this user option.'
21
- * }
22
- * ]
23
- *
24
- * @returns {array<objects> || throws} Any URL based Validation Error found in relation to the user option
25
- * for the `urlKey` param found on the `options param
26
- * [
27
- * ...otherValidationErrors
28
- * {
29
- * key: 'url',
30
- * message: '* Required'
31
- * },
32
- * // OR
33
- * {
34
- * key: 'url',
35
- * message: 'Your Url must not end with a //'
36
- * },
37
- * // OR
38
- * {
39
- * key: 'url',
40
- * message: 'What is currently provided is not a valid URL. You must provide a valid Instance URL.'
41
- * },
42
- * ]
43
- */
44
- const validateUrlOption = (options, urlKey = 'url', otherValidationErrors = []) => {
45
- const urlValue = (0, fp_1.get)([urlKey, 'value'], options);
46
- if (urlValue === undefined) {
47
- throw new Error(`User Option key \`${urlKey}\` is not defined in the config.js. ` +
48
- "It's also possible you need to change the package.json version for the client to pick up your `config/config.js` changes.");
49
- }
50
- let allValidationErrors = otherValidationErrors;
51
- // TODO: Add support & tests for non-required urls or remove the `required` input value check if the situation where desire for use of this feature is encountered
52
- if (!urlValue) {
53
- allValidationErrors = allValidationErrors.concat({
54
- key: urlKey,
55
- message: '* Required'
56
- });
57
- }
58
- if (urlValue.endsWith('//')) {
59
- allValidationErrors = allValidationErrors.concat({
60
- key: urlKey,
61
- message: 'Your Url must not end with a //'
62
- });
63
- }
64
- if (urlValue) {
65
- try {
66
- new URL(urlValue);
67
- }
68
- catch (_) {
69
- allValidationErrors = allValidationErrors.concat({
70
- key: urlKey,
71
- message: 'What is currently provided is not a valid URL. You must provide a valid Instance URL.'
72
- });
73
- }
74
- }
75
- return allValidationErrors;
76
- };
77
- exports.default = validateUrlOption;
@@ -1,12 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- class RequestError extends Error {
4
- constructor(message, status, description, requestOptions) {
5
- super();
6
- this.message = `Request Error${message ? ` -> ${message}` : ''}`;
7
- this.status = status;
8
- this.description = description;
9
- this.requestOptions = requestOptions;
10
- }
11
- }
12
- exports.default = RequestError;