@apify/utilities 2.10.5 → 2.10.6

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.
package/esm/index.mjs CHANGED
@@ -1,15 +1,12 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
3
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
4
- var __publicField = (obj, key, value) => {
5
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
6
- return value;
7
- };
4
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
8
5
 
9
6
  // src/utilities.ts
10
7
  import crypto from "crypto";
11
- import log, { LoggerJson, LogLevel } from "@apify/log";
12
8
  import { ANONYMOUS_USERNAME, APIFY_ID_REGEX } from "@apify/consts";
9
+ import log, { LoggerJson, LogLevel } from "@apify/log";
13
10
  function cryptoRandomObjectId(length = 17) {
14
11
  const chars = "abcdefghijklmnopqrstuvwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ0123456789";
15
12
  const bytes = crypto.randomBytes(length);
@@ -36,7 +33,7 @@ function parseDateFromJson(date) {
36
33
  return date;
37
34
  }
38
35
  __name(parseDateFromJson, "parseDateFromJson");
39
- function delayPromise(millis) {
36
+ async function delayPromise(millis) {
40
37
  return new Promise((resolve) => {
41
38
  if (millis > 0) {
42
39
  setTimeout(() => resolve(), millis);
@@ -77,8 +74,7 @@ function betterSetInterval(func, delay) {
77
74
  func(callback);
78
75
  }, "funcWrapper");
79
76
  callback = /* @__PURE__ */ __name(function() {
80
- if (isRunning)
81
- timeoutId = setTimeout(funcWrapper, delay);
77
+ if (isRunning) timeoutId = setTimeout(funcWrapper, delay);
82
78
  }, "callback");
83
79
  funcWrapper();
84
80
  return {
@@ -106,8 +102,7 @@ __name(escapeRegExp, "escapeRegExp");
106
102
  function leftpad(str, len, ch = " ") {
107
103
  str = String(str);
108
104
  let i = -1;
109
- if (!ch && ch !== 0)
110
- ch = " ";
105
+ if (!ch && ch !== 0) ch = " ";
111
106
  len -= str.length;
112
107
  while (++i < len) {
113
108
  str = ch + str;
@@ -935,8 +930,7 @@ function isForbiddenUsername(username) {
935
930
  }
936
931
  __name(isForbiddenUsername, "isForbiddenUsername");
937
932
  async function sequentializePromises(promises) {
938
- if (!promises.length)
939
- return [];
933
+ if (!promises.length) return [];
940
934
  const results = [];
941
935
  for (const promiseOrFunc of promises) {
942
936
  const promise = promiseOrFunc instanceof Function ? promiseOrFunc() : promiseOrFunc;
@@ -946,15 +940,13 @@ async function sequentializePromises(promises) {
946
940
  }
947
941
  __name(sequentializePromises, "sequentializePromises");
948
942
  function checkParamPrototypeOrThrow(paramVal, paramName, prototypes, prototypeName, isOptional = false) {
949
- if (isOptional && (paramVal === void 0 || paramVal === null))
950
- return;
943
+ if (isOptional && (paramVal === void 0 || paramVal === null)) return;
951
944
  const hasCorrectPrototype = prototypes instanceof Array ? prototypes.some((prototype) => paramVal instanceof prototype) : paramVal instanceof prototypes;
952
- if (!hasCorrectPrototype)
953
- throw new Error(`Parameter "${paramName}" must be an instance of ${prototypeName}`);
945
+ if (!hasCorrectPrototype) throw new Error(`Parameter "${paramName}" must be an instance of ${prototypeName}`);
954
946
  }
955
947
  __name(checkParamPrototypeOrThrow, "checkParamPrototypeOrThrow");
956
948
  function promisifyServerListen(server) {
957
- return (port) => {
949
+ return async (port) => {
958
950
  return new Promise((resolve, reject) => {
959
951
  const onError = /* @__PURE__ */ __name((err) => {
960
952
  removeListeners();
@@ -986,17 +978,15 @@ function configureLogger(givenLog, isProduction) {
986
978
  }
987
979
  }
988
980
  __name(configureLogger, "configureLogger");
989
- function timeoutPromise(promise, timeoutMillis, errorMessage = "Promise has timed-out") {
981
+ async function timeoutPromise(promise, timeoutMillis, errorMessage = "Promise has timed-out") {
990
982
  return new Promise((resolve, reject) => {
991
983
  let timeout;
992
984
  let hasFulfilled = false;
993
985
  const callback = /* @__PURE__ */ __name((err, result) => {
994
- if (hasFulfilled)
995
- return;
986
+ if (hasFulfilled) return;
996
987
  clearTimeout(timeout);
997
988
  hasFulfilled = true;
998
- if (err)
999
- return reject(err);
989
+ if (err) return reject(err);
1000
990
  resolve(result);
1001
991
  }, "callback");
1002
992
  promise.then((result) => callback(null, result), callback);
@@ -1051,8 +1041,7 @@ function getOrdinalSuffix(num) {
1051
1041
  }
1052
1042
  __name(getOrdinalSuffix, "getOrdinalSuffix");
1053
1043
  function parseUrl(str) {
1054
- if (typeof str !== "string")
1055
- return {};
1044
+ if (typeof str !== "string") return {};
1056
1045
  const o = {
1057
1046
  strictMode: false,
1058
1047
  key: [
@@ -1085,18 +1074,15 @@ function parseUrl(str) {
1085
1074
  const m = o.parser[o.strictMode ? "strict" : "loose"].exec(str);
1086
1075
  const uri = {};
1087
1076
  let i = o.key.length;
1088
- while (i--)
1089
- uri[o.key[i]] = m[i] || "";
1077
+ while (i--) uri[o.key[i]] = m[i] || "";
1090
1078
  uri[o.q.name] = {};
1091
1079
  uri[o.key[12]].replace(o.q.parser, ($0, $1, $2) => {
1092
- if ($1)
1093
- uri[o.q.name][$1] = $2;
1080
+ if ($1) uri[o.q.name][$1] = $2;
1094
1081
  });
1095
1082
  uri.fragmentKey = {};
1096
1083
  if (uri.fragment) {
1097
1084
  uri.fragment.replace(o.q.parser, ($0, $1, $2) => {
1098
- if ($1)
1099
- uri.fragmentKey[$1] = $2;
1085
+ if ($1) uri.fragmentKey[$1] = $2;
1100
1086
  });
1101
1087
  }
1102
1088
  return uri;
@@ -1143,15 +1129,13 @@ function markedDecreaseHeadsLevel(text, level) {
1143
1129
  }
1144
1130
  __name(markedDecreaseHeadsLevel, "markedDecreaseHeadsLevel");
1145
1131
  function buildOrVersionNumberIntToStr(int) {
1146
- if (typeof int !== "number" || !(int >= 0))
1147
- return null;
1132
+ if (typeof int !== "number" || !(int >= 0)) return null;
1148
1133
  const major = Math.floor(int / VERSION_INT_MAJOR_BASE);
1149
1134
  const remainder = int % VERSION_INT_MAJOR_BASE;
1150
1135
  const minor = Math.floor(remainder / VERSION_INT_MINOR_BASE);
1151
1136
  const build = remainder % VERSION_INT_MINOR_BASE;
1152
1137
  let str = `${major}.${minor}`;
1153
- if (build > 0)
1154
- str += `.${build}`;
1138
+ if (build > 0) str += `.${build}`;
1155
1139
  return str;
1156
1140
  }
1157
1141
  __name(buildOrVersionNumberIntToStr, "buildOrVersionNumberIntToStr");
@@ -1191,15 +1175,13 @@ function unescapePropertyName(name) {
1191
1175
  }
1192
1176
  __name(unescapePropertyName, "unescapePropertyName");
1193
1177
  function traverseObject(obj, clone, transformFunc) {
1194
- if (obj === null || typeof obj !== "object" || Object.prototype.toString.call(obj) === "[object Date]" || isBuffer(obj))
1195
- return obj;
1178
+ if (obj === null || typeof obj !== "object" || Object.prototype.toString.call(obj) === "[object Date]" || isBuffer(obj)) return obj;
1196
1179
  let result;
1197
1180
  if (Array.isArray(obj)) {
1198
1181
  result = clone ? new Array(obj.length) : obj;
1199
1182
  for (let i = 0; i < obj.length; i++) {
1200
1183
  const val = traverseObject(obj[i], clone, transformFunc);
1201
- if (clone)
1202
- result[i] = val;
1184
+ if (clone) result[i] = val;
1203
1185
  }
1204
1186
  return result;
1205
1187
  }
@@ -1208,12 +1190,10 @@ function traverseObject(obj, clone, transformFunc) {
1208
1190
  const val = traverseObject(obj[key], clone, transformFunc);
1209
1191
  const [transformedKey, transformedVal] = transformFunc(key, val);
1210
1192
  if (key === transformedKey) {
1211
- if (clone || val !== transformedVal)
1212
- result[key] = transformedVal;
1193
+ if (clone || val !== transformedVal) result[key] = transformedVal;
1213
1194
  } else {
1214
1195
  result[transformedKey] = transformedVal;
1215
- if (!clone)
1216
- delete obj[key];
1196
+ if (!clone) delete obj[key];
1217
1197
  }
1218
1198
  }
1219
1199
  return result;
@@ -1239,8 +1219,7 @@ function isBadForMongo(obj) {
1239
1219
  return [key, value];
1240
1220
  });
1241
1221
  } catch (e) {
1242
- if (!isBad)
1243
- throw e;
1222
+ if (!isBad) throw e;
1244
1223
  }
1245
1224
  return isBad;
1246
1225
  }
@@ -1256,13 +1235,11 @@ var _JsonVariable = class _JsonVariable {
1256
1235
  __name(_JsonVariable, "JsonVariable");
1257
1236
  var JsonVariable = _JsonVariable;
1258
1237
  function jsonStringifyExtended(value, replacer, space = 0) {
1259
- if (replacer && !(replacer instanceof Function))
1260
- throw new Error('Parameter "replacer" of jsonStringifyExtended() must be a function!');
1238
+ if (replacer && !(replacer instanceof Function)) throw new Error('Parameter "replacer" of jsonStringifyExtended() must be a function!');
1261
1239
  const replacements = {};
1262
1240
  const extendedReplacer = /* @__PURE__ */ __name((key, val) => {
1263
1241
  val = replacer ? replacer(key, val) : val;
1264
- if (val instanceof Function)
1265
- return val.toString();
1242
+ if (val instanceof Function) return val.toString();
1266
1243
  if (val instanceof JsonVariable) {
1267
1244
  const randomToken = `<<<REPLACEMENT_TOKEN::${Math.random()}>>>`;
1268
1245
  replacements[randomToken] = val.getToken();
@@ -1278,8 +1255,7 @@ function jsonStringifyExtended(value, replacer, space = 0) {
1278
1255
  }
1279
1256
  __name(jsonStringifyExtended, "jsonStringifyExtended");
1280
1257
  function splitFullName(fullName) {
1281
- if (typeof fullName !== "string")
1282
- return [null, null];
1258
+ if (typeof fullName !== "string") return [null, null];
1283
1259
  const names = (fullName || "").trim().split(" ");
1284
1260
  const nonEmptyNames = names.filter((val) => val);
1285
1261
  if (nonEmptyNames.length === 0) {
@@ -1372,8 +1348,7 @@ var _HealthChecker = class _HealthChecker {
1372
1348
  mongoDbWriteTestCollection = "healthCheckPlayground",
1373
1349
  mongoDbWriteTestRemoveOlderThanSecs = 15
1374
1350
  } = options;
1375
- if (!Array.isArray(checks))
1376
- throw new Error('Parameter "check" must be an array');
1351
+ if (!Array.isArray(checks)) throw new Error('Parameter "check" must be an array');
1377
1352
  checks.map((check) => this._validateCheck(check));
1378
1353
  this.checks = checks;
1379
1354
  this.redisPrefix = redisPrefix;
@@ -1394,12 +1369,10 @@ var _HealthChecker = class _HealthChecker {
1394
1369
  }
1395
1370
  }
1396
1371
  _validateCheck(check) {
1397
- if (!(check.type in CHECK_TYPES))
1398
- throw new Error(`Check type "${check.type}" is invalid`);
1399
- if (typeof check.client !== "object")
1400
- throw new Error(`Check client must be an object got "${typeof check.client}" instead`);
1372
+ if (!(check.type in CHECK_TYPES)) throw new Error(`Check type "${check.type}" is invalid`);
1373
+ if (typeof check.client !== "object") throw new Error(`Check client must be an object got "${typeof check.client}" instead`);
1401
1374
  }
1402
- _performCheck(check) {
1375
+ async _performCheck(check) {
1403
1376
  switch (check.type) {
1404
1377
  case "MONGODB_PING" /* MONGODB_PING */:
1405
1378
  return this._testMongoDbPing(check);
@@ -1418,13 +1391,11 @@ var _HealthChecker = class _HealthChecker {
1418
1391
  }
1419
1392
  async _testMongoDbPing({ client }) {
1420
1393
  const response = await client.command({ ping: 1 });
1421
- if (response.ok !== 1)
1422
- throw new Error(`Got ${response.ok} instead of 1!`);
1394
+ if (response.ok !== 1) throw new Error(`Got ${response.ok} instead of 1!`);
1423
1395
  }
1424
1396
  async _testMongoDbRead({ client }) {
1425
1397
  const response = await client.listCollections().toArray();
1426
- if (!Array.isArray(response))
1427
- throw new Error(`Got ${typeof response} instead of an array!`);
1398
+ if (!Array.isArray(response)) throw new Error(`Got ${typeof response} instead of an array!`);
1428
1399
  }
1429
1400
  async _testMongoDbWrite({ client }) {
1430
1401
  const id = cryptoRandomObjectId();
@@ -1439,21 +1410,18 @@ var _HealthChecker = class _HealthChecker {
1439
1410
  createdAt: /* @__PURE__ */ new Date()
1440
1411
  });
1441
1412
  const retrieved = await collection.findOne({ _id: id });
1442
- if (!retrieved)
1443
- throw new Error(`Item with ID "${id}" not found!`);
1413
+ if (!retrieved) throw new Error(`Item with ID "${id}" not found!`);
1444
1414
  }
1445
1415
  async _testRedisPing({ client }) {
1446
1416
  const response = await client.ping();
1447
- if (response !== "PONG")
1448
- throw new Error(`Got "${response}" instead of "PONG"!`);
1417
+ if (response !== "PONG") throw new Error(`Got "${response}" instead of "PONG"!`);
1449
1418
  }
1450
1419
  async _testRedisWrite({ client }) {
1451
1420
  const key = `${this.redisPrefix}:${cryptoRandomObjectId()}`;
1452
1421
  const expected = "OK";
1453
1422
  await client.set(key, expected, "EX", this.redisTtlSecs);
1454
1423
  const given = await client.get(key);
1455
- if (given !== expected)
1456
- throw new Error(`Returned value "${given}" is not equal to "${expected}"!`);
1424
+ if (given !== expected) throw new Error(`Returned value "${given}" is not equal to "${expected}"!`);
1457
1425
  }
1458
1426
  };
1459
1427
  __name(_HealthChecker, "HealthChecker");
@@ -1582,8 +1550,7 @@ var _WebhookPayloadTemplate = class _WebhookPayloadTemplate {
1582
1550
  */
1583
1551
  static parse(payloadTemplate, allowedVariables = null, context = {}, options = {}) {
1584
1552
  const type = typeof payloadTemplate;
1585
- if (type !== "string")
1586
- throw new Error(`Cannot parse a ${type} payload template.`);
1553
+ if (type !== "string") throw new Error(`Cannot parse a ${type} payload template.`);
1587
1554
  const template = new _WebhookPayloadTemplate(payloadTemplate, allowedVariables, context);
1588
1555
  const data = template._parse();
1589
1556
  if (options.interpolateStrings) {
@@ -1598,8 +1565,7 @@ var _WebhookPayloadTemplate = class _WebhookPayloadTemplate {
1598
1565
  */
1599
1566
  static stringify(objectTemplate, replacer, indent = 2) {
1600
1567
  const type = typeof objectTemplate;
1601
- if (!objectTemplate || type !== "object")
1602
- throw new Error(`Cannot stringify a ${type} payload template.`);
1568
+ if (!objectTemplate || type !== "object") throw new Error(`Cannot stringify a ${type} payload template.`);
1603
1569
  return jsonStringifyExtended(objectTemplate, replacer, indent);
1604
1570
  }
1605
1571
  /**
@@ -1685,8 +1651,7 @@ var _WebhookPayloadTemplate = class _WebhookPayloadTemplate {
1685
1651
  const openBraceIndex = this.payload.indexOf("{{", startIndex);
1686
1652
  const closeBraceIndex = this.payload.indexOf("}}", openBraceIndex) + 1;
1687
1653
  const someVariableMaybeExists = openBraceIndex > -1 && closeBraceIndex > -1;
1688
- if (!someVariableMaybeExists)
1689
- return null;
1654
+ if (!someVariableMaybeExists) return null;
1690
1655
  const isInsideString = this._isVariableInsideString(openBraceIndex);
1691
1656
  return { isInsideString, openBraceIndex, closeBraceIndex };
1692
1657
  }
@@ -1714,19 +1679,16 @@ var _WebhookPayloadTemplate = class _WebhookPayloadTemplate {
1714
1679
  this.payload = this.payload.substring(0, openBraceIndex) + replacement + this.payload.substring(closeBraceIndex + 1);
1715
1680
  }
1716
1681
  _validateVariableName(variableName) {
1717
- if (this.allowedVariables === null)
1718
- return;
1682
+ if (this.allowedVariables === null) return;
1719
1683
  const [variable] = variableName.split(".");
1720
1684
  const isVariableValid = this.allowedVariables.has(variable);
1721
- if (!isVariableValid)
1722
- throw new InvalidVariableError(variableName);
1685
+ if (!isVariableValid) throw new InvalidVariableError(variableName);
1723
1686
  }
1724
1687
  _getVariableValue(variableName) {
1725
1688
  const [variable, ...properties] = variableName.split(".");
1726
1689
  const context = this.context[variable];
1727
1690
  const value = properties.reduce((ctx, prop) => {
1728
- if (!ctx || typeof ctx !== "object")
1729
- return null;
1691
+ if (!ctx || typeof ctx !== "object") return null;
1730
1692
  return ctx[prop];
1731
1693
  }, context);
1732
1694
  return value;