ag-common 0.0.893 → 0.0.894

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 (92) hide show
  1. package/dist/api/helpers/acm.js +7 -17
  2. package/dist/api/helpers/api.js +28 -23
  3. package/dist/api/helpers/apigw.js +54 -71
  4. package/dist/api/helpers/cosmos/delete.js +81 -94
  5. package/dist/api/helpers/cosmos/get.js +170 -195
  6. package/dist/api/helpers/cosmos/index.js +23 -53
  7. package/dist/api/helpers/cosmos/write.js +88 -92
  8. package/dist/api/helpers/dynamo/delete.js +22 -52
  9. package/dist/api/helpers/dynamo/get.js +145 -135
  10. package/dist/api/helpers/dynamo/set.js +22 -29
  11. package/dist/api/helpers/enforceDynamoProvisionCap.js +5 -5
  12. package/dist/api/helpers/google/apikey.js +1 -2
  13. package/dist/api/helpers/google/gemini.js +26 -37
  14. package/dist/api/helpers/retryOnError.js +15 -26
  15. package/dist/api/helpers/s3.js +102 -121
  16. package/dist/api/helpers/ses.js +19 -26
  17. package/dist/api/helpers/sqs.js +5 -15
  18. package/dist/api/helpers/ssmInfra/dynamo.js +9 -5
  19. package/dist/api/helpers/sts.js +26 -37
  20. package/dist/api/helpers/validations.js +7 -17
  21. package/dist/api/helpers/zod.js +1 -2
  22. package/dist/common/helpers/async.js +27 -42
  23. package/dist/common/helpers/csv.js +1 -4
  24. package/dist/common/helpers/date.js +2 -2
  25. package/dist/common/helpers/fetch.js +42 -55
  26. package/dist/common/helpers/generator.js +11 -22
  27. package/dist/common/helpers/i18n.js +3 -5
  28. package/dist/common/helpers/log.js +4 -4
  29. package/dist/common/helpers/math.js +1 -2
  30. package/dist/common/helpers/node-cache.js +10 -2
  31. package/dist/common/helpers/random.js +2 -2
  32. package/dist/common/helpers/secondsInNearest.js +1 -2
  33. package/dist/common/helpers/stream.js +24 -35
  34. package/dist/common/helpers/string/redact.js +1 -2
  35. package/dist/common/helpers/withRetry.js +5 -14
  36. package/dist/common/helpers/xml.js +9 -22
  37. package/dist/node/helpers/fetch.js +22 -33
  38. package/dist/ui/components/DarkMode/Base.js +10 -5
  39. package/dist/ui/components/Markdown/index.js +4 -5
  40. package/dist/ui/components/shadcn/accordion.js +13 -36
  41. package/dist/ui/components/shadcn/alert.d.ts +1 -1
  42. package/dist/ui/components/shadcn/alert.js +3 -23
  43. package/dist/ui/components/shadcn/avatar.js +4 -24
  44. package/dist/ui/components/shadcn/button.d.ts +1 -1
  45. package/dist/ui/components/shadcn/button.js +2 -14
  46. package/dist/ui/components/shadcn/card.js +6 -35
  47. package/dist/ui/components/shadcn/checkbox.js +4 -18
  48. package/dist/ui/components/shadcn/dialog.js +17 -46
  49. package/dist/ui/components/shadcn/dropdown-list.js +2 -2
  50. package/dist/ui/components/shadcn/dropdown-menu.js +22 -58
  51. package/dist/ui/components/shadcn/input-selector.js +4 -5
  52. package/dist/ui/components/shadcn/input.js +2 -14
  53. package/dist/ui/components/shadcn/label.d.ts +1 -1
  54. package/dist/ui/components/shadcn/label.js +2 -16
  55. package/dist/ui/components/shadcn/popover.js +3 -17
  56. package/dist/ui/components/shadcn/radio-group.js +4 -17
  57. package/dist/ui/components/shadcn/scroll-area.js +9 -26
  58. package/dist/ui/components/shadcn/select.js +23 -55
  59. package/dist/ui/components/shadcn/sheet.d.ts +1 -1
  60. package/dist/ui/components/shadcn/sheet.js +13 -42
  61. package/dist/ui/components/shadcn/switch.js +3 -17
  62. package/dist/ui/components/shadcn/textarea.js +2 -14
  63. package/dist/ui/components/shadcn/toast.js +6 -4
  64. package/dist/ui/helpers/cookie/get.js +5 -1
  65. package/dist/ui/helpers/cookie/raw.js +1 -2
  66. package/dist/ui/helpers/cookie/set.js +2 -2
  67. package/dist/ui/helpers/cookie/use.js +19 -9
  68. package/dist/ui/helpers/date.js +3 -4
  69. package/dist/ui/helpers/debounce.js +1 -1
  70. package/dist/ui/helpers/extractAttributes.js +1 -2
  71. package/dist/ui/helpers/openDialog.js +1 -2
  72. package/dist/ui/helpers/routes.js +6 -4
  73. package/dist/ui/helpers/serviceWorker.js +7 -18
  74. package/dist/ui/helpers/useContextMenu.js +2 -3
  75. package/dist/ui/helpers/useElementAttribute.js +1 -1
  76. package/dist/ui/helpers/useGranularHook.js +2 -2
  77. package/dist/ui/helpers/useInterval.js +5 -7
  78. package/dist/ui/helpers/useLocalStorage.js +1 -1
  79. package/dist/ui/helpers/useOnClickOutside.js +2 -3
  80. package/dist/ui/helpers/useOnScroll.js +6 -8
  81. package/dist/ui/helpers/useOverloadPageSearch.js +1 -1
  82. package/dist/ui/helpers/useQueryString.js +2 -2
  83. package/dist/ui/helpers/useResize.js +1 -1
  84. package/dist/ui/helpers/useTimeout.js +1 -1
  85. package/dist/ui/helpers/useTooltip.js +8 -5
  86. package/dist/ui/icons/Checkmark.js +2 -5
  87. package/dist/ui/icons/Circle.js +2 -5
  88. package/dist/ui/icons/Magnify.js +2 -5
  89. package/dist/ui/icons/Sun.js +8 -11
  90. package/dist/ui/icons/Warning.js +7 -10
  91. package/dist/ui/styles/common.js +8 -20
  92. package/package.json +66 -65
@@ -5,11 +5,15 @@ const aws_cdk_lib_1 = require("aws-cdk-lib");
5
5
  const ssm_1 = require("../ssm");
6
6
  const generateTableRef = ({ stack, baseKey, hasStream, hasGSI, }) => {
7
7
  const tableArn = (0, ssm_1.loadSsmString)({ stack, path: `${baseKey}/arn` });
8
- const ret = aws_cdk_lib_1.aws_dynamodb.Table.fromTableAttributes(stack, baseKey, Object.assign(Object.assign({ tableArn }, (hasStream && {
9
- tableStreamArn: (0, ssm_1.loadSsmString)({ stack, path: `${baseKey}/streamArn` }),
10
- })), (hasGSI && {
11
- globalIndexes: (0, ssm_1.loadSsmStringList)({ stack, path: `${baseKey}/gsi` }),
12
- })));
8
+ const ret = aws_cdk_lib_1.aws_dynamodb.Table.fromTableAttributes(stack, baseKey, {
9
+ tableArn,
10
+ ...(hasStream && {
11
+ tableStreamArn: (0, ssm_1.loadSsmString)({ stack, path: `${baseKey}/streamArn` }),
12
+ }),
13
+ ...(hasGSI && {
14
+ globalIndexes: (0, ssm_1.loadSsmStringList)({ stack, path: `${baseKey}/gsi` }),
15
+ }),
16
+ });
13
17
  return ret;
14
18
  };
15
19
  exports.generateTableRef = generateTableRef;
@@ -1,13 +1,4 @@
1
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
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.sts = exports.setSts = void 0;
13
4
  exports.assumeRole = assumeRole;
@@ -23,34 +14,32 @@ exports.sts = (0, exports.setSts)('ap-southeast-2');
23
14
  * assume sts role
24
15
  * @returns {string} assumed accountId
25
16
  */
26
- function assumeRole(_a) {
27
- return __awaiter(this, arguments, void 0, function* ({ assumeRoleArn, region, }) {
28
- try {
29
- (0, log_1.info)(`assuming:${assumeRoleArn} in region:${region}`);
30
- const data = yield exports.sts.send(new client_sts_1.AssumeRoleCommand({
31
- RoleArn: assumeRoleArn,
32
- RoleSessionName: 'stssession',
33
- }));
34
- if (!data.Credentials) {
35
- return { error: 'aws assume role error' };
36
- }
37
- if (!data.Credentials.AccessKeyId ||
38
- !data.Credentials.SecretAccessKey ||
39
- !data.Credentials.SessionToken ||
40
- !data.Credentials.Expiration) {
41
- return { error: 'missing cred values error' };
42
- }
43
- return {
44
- data: {
45
- accessKeyId: data.Credentials.AccessKeyId,
46
- secretAccessKey: data.Credentials.SecretAccessKey,
47
- sessionToken: data.Credentials.SessionToken,
48
- expiration: data.Credentials.Expiration,
49
- },
50
- };
17
+ async function assumeRole({ assumeRoleArn, region, }) {
18
+ try {
19
+ (0, log_1.info)(`assuming:${assumeRoleArn} in region:${region}`);
20
+ const data = await exports.sts.send(new client_sts_1.AssumeRoleCommand({
21
+ RoleArn: assumeRoleArn,
22
+ RoleSessionName: 'stssession',
23
+ }));
24
+ if (!data.Credentials) {
25
+ return { error: 'aws assume role error' };
51
26
  }
52
- catch (e) {
53
- return { error: e.toString() };
27
+ if (!data.Credentials.AccessKeyId ||
28
+ !data.Credentials.SecretAccessKey ||
29
+ !data.Credentials.SessionToken ||
30
+ !data.Credentials.Expiration) {
31
+ return { error: 'missing cred values error' };
54
32
  }
55
- });
33
+ return {
34
+ data: {
35
+ accessKeyId: data.Credentials.AccessKeyId,
36
+ secretAccessKey: data.Credentials.SecretAccessKey,
37
+ sessionToken: data.Credentials.SessionToken,
38
+ expiration: data.Credentials.Expiration,
39
+ },
40
+ };
41
+ }
42
+ catch (e) {
43
+ return { error: e.toString() };
44
+ }
56
45
  }
@@ -1,13 +1,4 @@
1
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
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -18,7 +9,7 @@ const jwks_rsa_1 = __importDefault(require("jwks-rsa"));
18
9
  const log_1 = require("../../common/helpers/log");
19
10
  const api_1 = require("./api");
20
11
  let jwksClient;
21
- const jwtVerify = (_a) => __awaiter(void 0, [_a], void 0, function* ({ token, jwksUri, issuer, }) {
12
+ const jwtVerify = async ({ token, jwksUri, issuer, }) => {
22
13
  return new Promise((resolve, reject) => {
23
14
  (0, jsonwebtoken_1.verify)(token, (header, callback) => {
24
15
  if (!jwksClient) {
@@ -38,7 +29,7 @@ const jwtVerify = (_a) => __awaiter(void 0, [_a], void 0, function* ({ token, jw
38
29
  reject(msg);
39
30
  return;
40
31
  }
41
- const signingKey = (key === null || key === void 0 ? void 0 : key.publicKey) || (key === null || key === void 0 ? void 0 : key.rsaPublicKey) || undefined;
32
+ const signingKey = key?.publicKey || key?.rsaPublicKey || undefined;
42
33
  if (!signingKey) {
43
34
  const msg = `no key error`;
44
35
  (0, log_1.error)(msg);
@@ -59,10 +50,9 @@ const jwtVerify = (_a) => __awaiter(void 0, [_a], void 0, function* ({ token, jw
59
50
  resolve(decoded);
60
51
  });
61
52
  });
62
- });
53
+ };
63
54
  /** extracts user details from oauth token */
64
- const getAndValidateToken = (_a) => __awaiter(void 0, [_a], void 0, function* ({ tokenRaw, jwksRegion = 'ap-southeast-2', COGNITO_USER_POOL_ID, }) {
65
- var _b;
55
+ const getAndValidateToken = async ({ tokenRaw, jwksRegion = 'ap-southeast-2', COGNITO_USER_POOL_ID, }) => {
66
56
  const jwksUri = `https://cognito-idp.${jwksRegion}.amazonaws.com/${COGNITO_USER_POOL_ID}/.well-known/jwks.json`;
67
57
  const issuer = `https://cognito-idp.${jwksRegion}.amazonaws.com/${COGNITO_USER_POOL_ID}`;
68
58
  let token = '';
@@ -84,7 +74,7 @@ const getAndValidateToken = (_a) => __awaiter(void 0, [_a], void 0, function* ({
84
74
  }
85
75
  let subject;
86
76
  try {
87
- yield jwtVerify({ token, jwksUri, issuer });
77
+ await jwtVerify({ token, jwksUri, issuer });
88
78
  const decoded = (0, jsonwebtoken_1.decode)(token);
89
79
  (0, log_1.debug)(`decoded=${JSON.stringify(decoded, null, 2)}`);
90
80
  if (!decoded.email) {
@@ -101,7 +91,7 @@ const getAndValidateToken = (_a) => __awaiter(void 0, [_a], void 0, function* ({
101
91
  throw new Error(mess);
102
92
  }
103
93
  let { picture } = decoded;
104
- if (((_b = decoded.identities[0]) === null || _b === void 0 ? void 0 : _b.providerName) === 'Facebook') {
94
+ if (decoded.identities[0]?.providerName === 'Facebook') {
105
95
  picture = JSON.parse(decoded.picture).data.url;
106
96
  }
107
97
  const userId = decoded.email.toLowerCase();
@@ -132,5 +122,5 @@ const getAndValidateToken = (_a) => __awaiter(void 0, [_a], void 0, function* ({
132
122
  error: (0, api_1.returnCode)(403, m),
133
123
  };
134
124
  }
135
- });
125
+ };
136
126
  exports.getAndValidateToken = getAndValidateToken;
@@ -39,7 +39,6 @@ function getTypeName(zodType) {
39
39
  }
40
40
  /** Recursively convert a Zod type to its code representation. */
41
41
  function zodTypeToCode(zodType) {
42
- var _a;
43
42
  const description = zodType.description;
44
43
  const describeChain = description
45
44
  ? `.describe(${JSON.stringify(description)})`
@@ -91,7 +90,7 @@ function zodTypeToCode(zodType) {
91
90
  }
92
91
  // Record: _def.keyType + _def.valueType (valueType may be undefined for single-arg z.record(keyType))
93
92
  if (typeName === 'record') {
94
- const innerType = ((_a = def.valueType) !== null && _a !== void 0 ? _a : def.keyType);
93
+ const innerType = (def.valueType ?? def.keyType);
95
94
  return `z.record(${zodTypeToCode(innerType)})${describeChain}`;
96
95
  }
97
96
  // Tuple: _def.items is array of Zod types
@@ -1,13 +1,4 @@
1
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
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.asyncForEach = asyncForEach;
13
4
  exports.asyncMap = asyncMap;
@@ -17,21 +8,18 @@ const array_1 = require("./array");
17
8
  * @param array
18
9
  * @param callback
19
10
  */
20
- function asyncForEach(array, callback, opt) {
21
- return __awaiter(this, void 0, void 0, function* () {
22
- var _a;
23
- const maxConcurrency = (_a = opt === null || opt === void 0 ? void 0 : opt.maxConcurrency) !== null && _a !== void 0 ? _a : 1;
24
- let rem = array;
25
- let start = 0;
26
- while (rem.length > 0) {
27
- const { rest, part } = (0, array_1.take)(rem, maxConcurrency);
28
- rem = rest;
29
- const proms = part.map((p, i) => callback(p, start + i, array));
30
- start += part.length;
31
- // eslint-disable-next-line no-await-in-loop
32
- yield Promise.all(proms);
33
- }
34
- });
11
+ async function asyncForEach(array, callback, opt) {
12
+ const maxConcurrency = opt?.maxConcurrency ?? 1;
13
+ let rem = array;
14
+ let start = 0;
15
+ while (rem.length > 0) {
16
+ const { rest, part } = (0, array_1.take)(rem, maxConcurrency);
17
+ rem = rest;
18
+ const proms = part.map((p, i) => callback(p, start + i, array));
19
+ start += part.length;
20
+ // eslint-disable-next-line no-await-in-loop
21
+ await Promise.all(proms);
22
+ }
35
23
  }
36
24
  /**
37
25
  * run async map over all array items
@@ -39,22 +27,19 @@ function asyncForEach(array, callback, opt) {
39
27
  * @param callback
40
28
  * @returns
41
29
  */
42
- function asyncMap(array, callback, opt) {
43
- return __awaiter(this, void 0, void 0, function* () {
44
- var _a;
45
- const ret = [];
46
- const maxConcurrency = (_a = opt === null || opt === void 0 ? void 0 : opt.maxConcurrency) !== null && _a !== void 0 ? _a : 1;
47
- let rem = array;
48
- let start = 0;
49
- while (rem.length > 0) {
50
- const { rest, part } = (0, array_1.take)(rem, maxConcurrency);
51
- rem = rest;
52
- const proms = part.map((p, i) => callback(p, start + i, array));
53
- start += part.length;
54
- // eslint-disable-next-line no-await-in-loop
55
- const res = yield Promise.all(proms);
56
- ret.push(...res);
57
- }
58
- return ret;
59
- });
30
+ async function asyncMap(array, callback, opt) {
31
+ const ret = [];
32
+ const maxConcurrency = opt?.maxConcurrency ?? 1;
33
+ let rem = array;
34
+ let start = 0;
35
+ while (rem.length > 0) {
36
+ const { rest, part } = (0, array_1.take)(rem, maxConcurrency);
37
+ rem = rest;
38
+ const proms = part.map((p, i) => callback(p, start + i, array));
39
+ start += part.length;
40
+ // eslint-disable-next-line no-await-in-loop
41
+ const res = await Promise.all(proms);
42
+ ret.push(...res);
43
+ }
44
+ return ret;
60
45
  }
@@ -11,10 +11,7 @@ function loadCsvAsJson(p) {
11
11
  }
12
12
  const headers = lines[0]
13
13
  .split(sep)
14
- .map((s) => {
15
- var _a, _b, _c;
16
- return [s, (_c = (_b = (_a = p.opt) === null || _a === void 0 ? void 0 : _a.typeOverrides) === null || _b === void 0 ? void 0 : _b.find((s1) => s1.headerName === s)) === null || _c === void 0 ? void 0 : _c.type];
17
- });
14
+ .map((s) => [s, p.opt?.typeOverrides?.find((s1) => s1.headerName === s)?.type]);
18
15
  const jsonData = lines.slice(1).map((line) => {
19
16
  const values = [];
20
17
  let inQuote = false;
@@ -25,7 +25,7 @@ exports.lastDayInMonth = lastDayInMonth;
25
25
  * @returns
26
26
  */
27
27
  const dateDiff = (lowDate, highDate) => {
28
- const ticksSince = (highDate !== null && highDate !== void 0 ? highDate : new Date()).getTime() - lowDate.getTime();
28
+ const ticksSince = (highDate ?? new Date()).getTime() - lowDate.getTime();
29
29
  const totalMinutes = (0, math_1.toFixedDown)(ticksSince / 1000 / 60, 0);
30
30
  const totalHours = (0, math_1.toFixedDown)(totalMinutes / 60, 0);
31
31
  const totalDays = (0, math_1.toFixedDown)(totalHours / 24, 0);
@@ -54,7 +54,7 @@ exports.CSharpToJs = CSharpToJs;
54
54
  */
55
55
  const dateTimeToNearestMinute = (minutes, date) => {
56
56
  const coeff = 1000 * 60 * minutes;
57
- date !== null && date !== void 0 ? date : (date = new Date());
57
+ date ??= new Date();
58
58
  const rounded = new Date(Math.round(date.getTime() / coeff) * coeff);
59
59
  return rounded;
60
60
  };
@@ -1,13 +1,4 @@
1
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
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.fetchToMemory = fetchToMemory;
13
4
  exports.fetchExists = fetchExists;
@@ -15,54 +6,50 @@ const headers_1 = require("./headers");
15
6
  const log_1 = require("./log");
16
7
  const node_cache_1 = require("./node-cache");
17
8
  const withRetry_1 = require("./withRetry");
18
- function fetchToMemory(imageUrl) {
19
- return __awaiter(this, void 0, void 0, function* () {
20
- try {
21
- // Download the image
22
- const response = yield fetch(imageUrl, { headers: (0, headers_1.getFetchHeaders)() });
23
- if (!response.ok) {
24
- throw new Error(`HTTP error! status: ${response.status}`);
25
- }
26
- let type = response.headers.get('content-type') || 'image/jpeg';
27
- if (type.includes('octet')) {
28
- (0, log_1.debug)('forcing type to jpeg:' + imageUrl);
29
- type = 'image/jpeg';
30
- }
31
- // Get the image data as an ArrayBuffer
32
- const arraybuffer = yield response.arrayBuffer();
33
- return { type, arraybuffer };
9
+ async function fetchToMemory(imageUrl) {
10
+ try {
11
+ // Download the image
12
+ const response = await fetch(imageUrl, { headers: (0, headers_1.getFetchHeaders)() });
13
+ if (!response.ok) {
14
+ throw new Error(`HTTP error! status: ${response.status}`);
34
15
  }
35
- catch (e) {
36
- const em = e;
37
- (0, log_1.warn)('Error downloading image:', imageUrl, em.toString());
38
- return undefined;
16
+ let type = response.headers.get('content-type') || 'image/jpeg';
17
+ if (type.includes('octet')) {
18
+ (0, log_1.debug)('forcing type to jpeg:' + imageUrl);
19
+ type = 'image/jpeg';
39
20
  }
40
- });
21
+ // Get the image data as an ArrayBuffer
22
+ const arraybuffer = await response.arrayBuffer();
23
+ return { type, arraybuffer };
24
+ }
25
+ catch (e) {
26
+ const em = e;
27
+ (0, log_1.warn)('Error downloading image:', imageUrl, em.toString());
28
+ return undefined;
29
+ }
41
30
  }
42
31
  const imageExistsCache = new node_cache_1.TypedNodeCache({ stdTTL: 60 * 60 * 24 });
43
- function fetchExists(imageUrl) {
44
- return __awaiter(this, void 0, void 0, function* () {
45
- const cached = imageExistsCache.get(imageUrl);
46
- if (typeof cached === 'boolean') {
47
- return cached;
48
- }
49
- const response = yield (0, withRetry_1.withRetry)(() => __awaiter(this, void 0, void 0, function* () {
50
- const response = yield fetch(imageUrl, {
51
- method: 'HEAD',
52
- headers: (0, headers_1.getFetchHeaders)(),
53
- });
54
- if (response.status === 200)
55
- return true;
56
- if (response.status === 404)
57
- return false;
58
- throw new Error(`Unexpected status: ${response.status}`);
59
- }), 'imageExistsAtUrl');
60
- if (response === false) {
61
- imageExistsCache.set(imageUrl, false, 1);
62
- }
63
- else {
64
- imageExistsCache.set(imageUrl, true);
65
- }
66
- return response;
67
- });
32
+ async function fetchExists(imageUrl) {
33
+ const cached = imageExistsCache.get(imageUrl);
34
+ if (typeof cached === 'boolean') {
35
+ return cached;
36
+ }
37
+ const response = await (0, withRetry_1.withRetry)(async () => {
38
+ const response = await fetch(imageUrl, {
39
+ method: 'HEAD',
40
+ headers: (0, headers_1.getFetchHeaders)(),
41
+ });
42
+ if (response.status === 200)
43
+ return true;
44
+ if (response.status === 404)
45
+ return false;
46
+ throw new Error(`Unexpected status: ${response.status}`);
47
+ }, 'imageExistsAtUrl');
48
+ if (response === false) {
49
+ imageExistsCache.set(imageUrl, false, 1);
50
+ }
51
+ else {
52
+ imageExistsCache.set(imageUrl, true);
53
+ }
54
+ return response;
68
55
  }
@@ -1,26 +1,15 @@
1
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
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.runGenerator = runGenerator;
13
- function runGenerator(iter, partialRun) {
14
- return __awaiter(this, void 0, void 0, function* () {
15
- let curr;
16
- do {
17
- // eslint-disable-next-line no-await-in-loop
18
- curr = yield iter.next();
19
- if (curr.value.length === 0) {
20
- return;
21
- }
22
- // eslint-disable-next-line no-await-in-loop
23
- yield partialRun(curr.value);
24
- } while (!curr.done);
25
- });
4
+ async function runGenerator(iter, partialRun) {
5
+ let curr;
6
+ do {
7
+ // eslint-disable-next-line no-await-in-loop
8
+ curr = await iter.next();
9
+ if (curr.value.length === 0) {
10
+ return;
11
+ }
12
+ // eslint-disable-next-line no-await-in-loop
13
+ await partialRun(curr.value);
14
+ } while (!curr.done);
26
15
  }
@@ -11,22 +11,20 @@ const getValidatedLang = (raw) => {
11
11
  };
12
12
  exports.getValidatedLang = getValidatedLang;
13
13
  const t = (res, lang) => {
14
- var _a;
15
14
  if (res[lang] === null) {
16
15
  return '';
17
16
  }
18
- return (_a = res[lang]) !== null && _a !== void 0 ? _a : res.en;
17
+ return res[lang] ?? res.en;
19
18
  };
20
19
  exports.t = t;
21
20
  const useTranslation = (texts, lang) => {
22
21
  const ret = (lineText) => {
23
- var _a;
24
22
  const v1 = texts[lineText][lang];
25
23
  if (v1 || v1 === null) {
26
- return v1 !== null && v1 !== void 0 ? v1 : '';
24
+ return v1 ?? '';
27
25
  }
28
26
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
29
- return (_a = texts[lineText].en) !== null && _a !== void 0 ? _a : '???';
27
+ return texts[lineText].en ?? '???';
30
28
  };
31
29
  return ret;
32
30
  };
@@ -14,7 +14,7 @@ const SetLogShim = (ls) => {
14
14
  exports.SetLogShim = SetLogShim;
15
15
  let userLogLevel;
16
16
  const SetLogLevel = (l) => {
17
- const lu = (l !== null && l !== void 0 ? l : 'INFO').toUpperCase();
17
+ const lu = (l ?? 'INFO').toUpperCase();
18
18
  if ((0, exports.GetLogLevel)(lu) === -1) {
19
19
  return;
20
20
  }
@@ -25,7 +25,7 @@ function logprocess(type, args) {
25
25
  if (!userLogLevel) {
26
26
  (0, exports.SetLogLevel)(process.env.LOG_LEVEL);
27
27
  }
28
- const min = (0, exports.GetLogLevel)(userLogLevel !== null && userLogLevel !== void 0 ? userLogLevel : 'WARN');
28
+ const min = (0, exports.GetLogLevel)(userLogLevel ?? 'WARN');
29
29
  const typesLogLevel = (0, exports.GetLogLevel)(type);
30
30
  // env ignores it
31
31
  if (typesLogLevel < min) {
@@ -84,7 +84,6 @@ function logprocess(type, args) {
84
84
  }
85
85
  }
86
86
  function printStackTrace(...args) {
87
- var _a;
88
87
  const callstack = [];
89
88
  let isCallstackPopulated = false;
90
89
  try {
@@ -128,7 +127,8 @@ function printStackTrace(...args) {
128
127
  let currentFunction = args.callee.caller;
129
128
  while (currentFunction) {
130
129
  const fn = currentFunction.toString();
131
- const fname = (_a = fn.substring(fn.indexOf('function') + 8, fn.indexOf('('))) !== null && _a !== void 0 ? _a : 'anonymous';
130
+ const fname = fn.substring(fn.indexOf('function') + 8, fn.indexOf('(')) ??
131
+ 'anonymous';
132
132
  callstack.push(fname);
133
133
  currentFunction = currentFunction.caller;
134
134
  }
@@ -7,9 +7,8 @@ exports.sumArray = sumArray;
7
7
  exports.toFixedDown = toFixedDown;
8
8
  exports.rangePercentage = rangePercentage;
9
9
  const toFixed = (num, fixed) => {
10
- var _a;
11
10
  const re = new RegExp(`^-?\\d+(?:.\\d{0,${fixed || -1}})?`);
12
- const x = (_a = num.toString().match(re)) === null || _a === void 0 ? void 0 : _a[0];
11
+ const x = num.toString().match(re)?.[0];
13
12
  if (!x) {
14
13
  return num;
15
14
  }
@@ -7,8 +7,13 @@ exports.TypedNodeCache = void 0;
7
7
  const node_cache_1 = __importDefault(require("node-cache"));
8
8
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
9
9
  class TypedNodeCache {
10
+ cache;
10
11
  constructor(options = {}) {
11
- this.cache = new node_cache_1.default(Object.assign({ stdTTL: 3600, checkperiod: 120 }, options));
12
+ this.cache = new node_cache_1.default({
13
+ stdTTL: 3600, // 1 hour default
14
+ checkperiod: 120, // Check for expired keys every 2 minutes default
15
+ ...options,
16
+ });
12
17
  }
13
18
  /**
14
19
  * Normalizes the key to lowercase for case-insensitive operations
@@ -54,7 +59,10 @@ class TypedNodeCache {
54
59
  * Set multiple values in the cache
55
60
  */
56
61
  mset(keyValuePairs) {
57
- const normalizedPairs = keyValuePairs.map((pair) => (Object.assign(Object.assign({}, pair), { key: this.normalizeKey(pair.key) })));
62
+ const normalizedPairs = keyValuePairs.map((pair) => ({
63
+ ...pair,
64
+ key: this.normalizeKey(pair.key),
65
+ }));
58
66
  return this.cache.mset(normalizedPairs);
59
67
  }
60
68
  /**
@@ -5,14 +5,14 @@ exports.random = random;
5
5
  exports.shuffle = shuffle;
6
6
  /** random number up to max. seed defaults to now.getTime() */
7
7
  function random(max, seed) {
8
- seed = seed !== null && seed !== void 0 ? seed : new Date().getTime();
8
+ seed = seed ?? new Date().getTime();
9
9
  const ret = (seed * 9301 + 49297) % 233280;
10
10
  const rnd = ret / 233280;
11
11
  return Math.ceil(rnd * max);
12
12
  }
13
13
  /** between 0 and 1. seed defaults to now.getTime() */
14
14
  const randomDecimal = function (seed) {
15
- seed = seed !== null && seed !== void 0 ? seed : new Date().getTime();
15
+ seed = seed ?? new Date().getTime();
16
16
  const x = Math.sin((seed += 1)) * 10000;
17
17
  return x - Math.floor(x);
18
18
  };
@@ -2,9 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.secondsInNearest = void 0;
4
4
  const toFixed = (num, fixed) => {
5
- var _a;
6
5
  const re = new RegExp(`^-?\\d+(?:.\\d{0,${fixed || -1}})?`);
7
- const x = (_a = num.toString().match(re)) === null || _a === void 0 ? void 0 : _a[0];
6
+ const x = num.toString().match(re)?.[0];
8
7
  if (!x) {
9
8
  return num;
10
9
  }