@lokalise/node-core 12.5.1 → 13.0.0

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 (85) hide show
  1. package/dist/index.cjs +985 -0
  2. package/dist/index.cjs.map +1 -0
  3. package/dist/index.d.cts +404 -0
  4. package/dist/index.d.ts +404 -29
  5. package/dist/index.js +893 -78
  6. package/dist/index.js.map +1 -1
  7. package/package.json +13 -7
  8. package/dist/src/common/commonTypes.d.ts +0 -1
  9. package/dist/src/common/commonTypes.js +0 -3
  10. package/dist/src/common/commonTypes.js.map +0 -1
  11. package/dist/src/common/may-omit.d.ts +0 -1
  12. package/dist/src/common/may-omit.js +0 -3
  13. package/dist/src/common/may-omit.js.map +0 -1
  14. package/dist/src/config/ConfigScope.d.ts +0 -34
  15. package/dist/src/config/ConfigScope.js +0 -173
  16. package/dist/src/config/ConfigScope.js.map +0 -1
  17. package/dist/src/config/configTransformers.d.ts +0 -2
  18. package/dist/src/config/configTransformers.js +0 -15
  19. package/dist/src/config/configTransformers.js.map +0 -1
  20. package/dist/src/config/configTypes.d.ts +0 -30
  21. package/dist/src/config/configTypes.js +0 -3
  22. package/dist/src/config/configTypes.js.map +0 -1
  23. package/dist/src/config/configValidators.d.ts +0 -2
  24. package/dist/src/config/configValidators.js +0 -10
  25. package/dist/src/config/configValidators.js.map +0 -1
  26. package/dist/src/errors/InternalError.d.ts +0 -16
  27. package/dist/src/errors/InternalError.js +0 -29
  28. package/dist/src/errors/InternalError.js.map +0 -1
  29. package/dist/src/errors/PublicNonRecoverableError.d.ts +0 -21
  30. package/dist/src/errors/PublicNonRecoverableError.js +0 -34
  31. package/dist/src/errors/PublicNonRecoverableError.js.map +0 -1
  32. package/dist/src/errors/either.d.ts +0 -28
  33. package/dist/src/errors/either.js +0 -16
  34. package/dist/src/errors/either.js.map +0 -1
  35. package/dist/src/errors/errorReporterTypes.d.ts +0 -14
  36. package/dist/src/errors/errorReporterTypes.js +0 -3
  37. package/dist/src/errors/errorReporterTypes.js.map +0 -1
  38. package/dist/src/errors/errorTypeGuards.d.ts +0 -2
  39. package/dist/src/errors/errorTypeGuards.js +0 -8
  40. package/dist/src/errors/errorTypeGuards.js.map +0 -1
  41. package/dist/src/errors/globalErrorHandler.d.ts +0 -13
  42. package/dist/src/errors/globalErrorHandler.js +0 -77
  43. package/dist/src/errors/globalErrorHandler.js.map +0 -1
  44. package/dist/src/errors/publicErrors.d.ts +0 -27
  45. package/dist/src/errors/publicErrors.js +0 -66
  46. package/dist/src/errors/publicErrors.js.map +0 -1
  47. package/dist/src/errors/types.d.ts +0 -1
  48. package/dist/src/errors/types.js +0 -3
  49. package/dist/src/errors/types.js.map +0 -1
  50. package/dist/src/logging/commonLogger.d.ts +0 -17
  51. package/dist/src/logging/commonLogger.js +0 -3
  52. package/dist/src/logging/commonLogger.js.map +0 -1
  53. package/dist/src/logging/loggerConfigResolver.d.ts +0 -15
  54. package/dist/src/logging/loggerConfigResolver.js +0 -70
  55. package/dist/src/logging/loggerConfigResolver.js.map +0 -1
  56. package/dist/src/observability/MultiTransactionObservabilityManager.d.ts +0 -12
  57. package/dist/src/observability/MultiTransactionObservabilityManager.js +0 -30
  58. package/dist/src/observability/MultiTransactionObservabilityManager.js.map +0 -1
  59. package/dist/src/observability/observabilityTypes.d.ts +0 -23
  60. package/dist/src/observability/observabilityTypes.js +0 -3
  61. package/dist/src/observability/observabilityTypes.js.map +0 -1
  62. package/dist/src/utils/arrayUtils.d.ts +0 -14
  63. package/dist/src/utils/arrayUtils.js +0 -47
  64. package/dist/src/utils/arrayUtils.js.map +0 -1
  65. package/dist/src/utils/checksumUtils.d.ts +0 -5
  66. package/dist/src/utils/checksumUtils.js +0 -37
  67. package/dist/src/utils/checksumUtils.js.map +0 -1
  68. package/dist/src/utils/encryptionUtility.d.ts +0 -20
  69. package/dist/src/utils/encryptionUtility.js +0 -58
  70. package/dist/src/utils/encryptionUtility.js.map +0 -1
  71. package/dist/src/utils/hashUtils.d.ts +0 -9
  72. package/dist/src/utils/hashUtils.js +0 -19
  73. package/dist/src/utils/hashUtils.js.map +0 -1
  74. package/dist/src/utils/objectUtils.d.ts +0 -55
  75. package/dist/src/utils/objectUtils.js +0 -195
  76. package/dist/src/utils/objectUtils.js.map +0 -1
  77. package/dist/src/utils/streamUtils.d.ts +0 -37
  78. package/dist/src/utils/streamUtils.js +0 -85
  79. package/dist/src/utils/streamUtils.js.map +0 -1
  80. package/dist/src/utils/typeUtils.d.ts +0 -10
  81. package/dist/src/utils/typeUtils.js +0 -19
  82. package/dist/src/utils/typeUtils.js.map +0 -1
  83. package/dist/src/utils/waitUtils.d.ts +0 -1
  84. package/dist/src/utils/waitUtils.js +0 -34
  85. package/dist/src/utils/waitUtils.js.map +0 -1
package/dist/index.cjs ADDED
@@ -0,0 +1,985 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ AccessDeniedError: () => AccessDeniedError,
34
+ AuthFailedError: () => AuthFailedError,
35
+ ConfigScope: () => ConfigScope,
36
+ EncryptionUtility: () => EncryptionUtility,
37
+ EntityGoneError: () => EntityGoneError,
38
+ EntityNotFoundError: () => EntityNotFoundError,
39
+ FsReadableProvider: () => FsReadableProvider,
40
+ HashAlgorithm: () => HashAlgorithm,
41
+ HashEncoding: () => HashEncoding,
42
+ InternalError: () => InternalError,
43
+ MultiTransactionObservabilityManager: () => MultiTransactionObservabilityManager,
44
+ PublicNonRecoverableError: () => PublicNonRecoverableError,
45
+ RequestValidationError: () => RequestValidationError,
46
+ callChunked: () => callChunked,
47
+ chunk: () => chunk,
48
+ convertDateFieldsToIsoString: () => convertDateFieldsToIsoString,
49
+ copyWithoutEmpty: () => copyWithoutEmpty,
50
+ copyWithoutUndefined: () => copyWithoutUndefined,
51
+ createRangeValidator: () => createRangeValidator,
52
+ deepClone: () => deepClone,
53
+ ensureClosingSlashTransformer: () => ensureClosingSlashTransformer,
54
+ executeAndHandleGlobalErrors: () => executeAndHandleGlobalErrors,
55
+ executeAsyncAndHandleGlobalErrors: () => executeAsyncAndHandleGlobalErrors,
56
+ executeSettleAllAndHandleGlobalErrors: () => executeSettleAllAndHandleGlobalErrors,
57
+ failure: () => failure,
58
+ generateChecksumForBufferOrString: () => generateChecksumForBufferOrString,
59
+ generateChecksumForObject: () => generateChecksumForObject,
60
+ generateChecksumForReadable: () => generateChecksumForReadable,
61
+ generateHash: () => generateHash,
62
+ globalLogger: () => globalLogger,
63
+ groupBy: () => groupBy,
64
+ groupByPath: () => groupByPath,
65
+ groupByUnique: () => groupByUnique,
66
+ hasMessage: () => hasMessage,
67
+ isEmptyObject: () => isEmptyObject,
68
+ isEntityGoneError: () => isEntityGoneError,
69
+ isError: () => isError,
70
+ isFailure: () => isFailure,
71
+ isInternalError: () => isInternalError,
72
+ isObject: () => isObject,
73
+ isPublicNonRecoverableError: () => isPublicNonRecoverableError,
74
+ isStandardizedError: () => isStandardizedError,
75
+ isSuccess: () => isSuccess,
76
+ pick: () => pick,
77
+ pickWithoutUndefined: () => pickWithoutUndefined,
78
+ removeDuplicates: () => removeDuplicates,
79
+ removeFalsy: () => removeFalsy,
80
+ removeNullish: () => removeNullish,
81
+ resolveGlobalErrorLogObject: () => resolveGlobalErrorLogObject,
82
+ resolveLogger: () => resolveLogger,
83
+ resolveLoggerConfiguration: () => resolveLoggerConfiguration,
84
+ resolveMonorepoLogger: () => resolveMonorepoLogger,
85
+ resolveMonorepoLoggerConfiguration: () => resolveMonorepoLoggerConfiguration,
86
+ success: () => success,
87
+ waitAndRetry: () => waitAndRetry
88
+ });
89
+ module.exports = __toCommonJS(src_exports);
90
+
91
+ // src/utils/typeUtils.ts
92
+ function hasMessage(maybe) {
93
+ return isObject(maybe) && typeof maybe.message === "string";
94
+ }
95
+ function isObject(maybeObject) {
96
+ return typeof maybeObject === "object" && maybeObject !== null;
97
+ }
98
+ function isStandardizedError(error) {
99
+ return isObject(error) && typeof error.code === "string" && typeof error.message === "string";
100
+ }
101
+ function isError(maybeError) {
102
+ return maybeError instanceof Error || Object.prototype.toString.call(maybeError) === "[object Error]";
103
+ }
104
+
105
+ // src/errors/PublicNonRecoverableError.ts
106
+ var PUBLIC_NON_RECOVERABLE_ERROR_SYMBOL_KEY = "PUBLIC_NON_RECOVERABLE_ERROR_KEY";
107
+ var publicNonRecoverableErrorSymbol = Symbol.for(PUBLIC_NON_RECOVERABLE_ERROR_SYMBOL_KEY);
108
+ var PublicNonRecoverableError = class extends Error {
109
+ [publicNonRecoverableErrorSymbol] = true;
110
+ details;
111
+ errorCode;
112
+ httpStatusCode;
113
+ constructor(params) {
114
+ super(params.message, {
115
+ cause: params.cause
116
+ });
117
+ this.name = this.constructor.name;
118
+ this.details = params.details;
119
+ this.errorCode = params.errorCode;
120
+ this.httpStatusCode = params.httpStatusCode ?? 500;
121
+ }
122
+ };
123
+ function isPublicNonRecoverableError(error) {
124
+ return isError(error) && // biome-ignore lint/suspicious/noExplicitAny: checking for existence of prop outside or Error interface
125
+ (error[Symbol.for(PUBLIC_NON_RECOVERABLE_ERROR_SYMBOL_KEY)] === true || error.name === "PublicNonRecoverableError");
126
+ }
127
+
128
+ // src/errors/InternalError.ts
129
+ var INTERNAL_ERROR_SYMBOL_KEY = "INTERNAL_ERROR_KEY";
130
+ var internalErrorSymbol = Symbol.for(INTERNAL_ERROR_SYMBOL_KEY);
131
+ var InternalError = class extends Error {
132
+ [internalErrorSymbol] = true;
133
+ details;
134
+ errorCode;
135
+ constructor(params) {
136
+ super(params.message, {
137
+ cause: params.cause
138
+ });
139
+ this.name = this.constructor.name;
140
+ this.details = params.details;
141
+ this.errorCode = params.errorCode;
142
+ }
143
+ };
144
+ function isInternalError(error) {
145
+ return isError(error) && // biome-ignore lint/suspicious/noExplicitAny: checking for existence of prop outside or Error interface
146
+ (error[Symbol.for(INTERNAL_ERROR_SYMBOL_KEY)] === true || error.name === "InternalError");
147
+ }
148
+
149
+ // src/errors/errorTypeGuards.ts
150
+ function isEntityGoneError(entity) {
151
+ return isPublicNonRecoverableError(entity) && entity.httpStatusCode === 410;
152
+ }
153
+
154
+ // src/config/ConfigScope.ts
155
+ var ConfigScope = class {
156
+ env;
157
+ constructor(envOverride) {
158
+ this.env = envOverride ?? { ...process.env };
159
+ }
160
+ updateEnv() {
161
+ this.env = { ...process.env };
162
+ }
163
+ getMandatoryInteger(param) {
164
+ const rawValue = this.env[param];
165
+ if (!rawValue) {
166
+ throw new InternalError({
167
+ message: `Missing mandatory configuration parameter: ${param}`,
168
+ errorCode: "CONFIGURATION_ERROR"
169
+ });
170
+ }
171
+ return validateNumber(
172
+ Number.parseInt(rawValue),
173
+ `Configuration parameter ${param}\` must be a number, but was ${rawValue}`
174
+ );
175
+ }
176
+ getMandatory(param) {
177
+ const result = this.env[param];
178
+ if (!result) {
179
+ throw new InternalError({
180
+ message: `Missing mandatory configuration parameter: ${param}`,
181
+ errorCode: "CONFIGURATION_ERROR"
182
+ });
183
+ }
184
+ return result;
185
+ }
186
+ getMandatoryOneOf(param, supportedValues) {
187
+ const result = this.getMandatory(param);
188
+ return validateOneOf(
189
+ result,
190
+ supportedValues,
191
+ `Unsupported ${param}: ${result}. Supported values: ${supportedValues.toString()}`
192
+ );
193
+ }
194
+ getMandatoryValidatedInteger(param, validator) {
195
+ const value = this.getMandatoryInteger(param);
196
+ if (!validator(value)) {
197
+ throw new InternalError({
198
+ message: `Value ${value} is invalid for parameter ${param}`,
199
+ errorCode: "CONFIGURATION_ERROR"
200
+ });
201
+ }
202
+ return value;
203
+ }
204
+ getOptionalNullable(param, defaultValue) {
205
+ return this.env[param] || defaultValue;
206
+ }
207
+ getOptional(param, defaultValue) {
208
+ return this.env[param] || defaultValue;
209
+ }
210
+ getOptionalInteger(param, defaultValue) {
211
+ const rawValue = this.env[param];
212
+ if (!rawValue) {
213
+ return defaultValue;
214
+ }
215
+ return validateNumber(
216
+ Number.parseInt(rawValue),
217
+ `Configuration parameter ${param}\` must be a number, but was ${rawValue}`
218
+ );
219
+ }
220
+ getOptionalNullableInteger(param, defaultValue) {
221
+ const rawValue = this.env[param];
222
+ if (!rawValue) {
223
+ return defaultValue;
224
+ }
225
+ return validateNumber(
226
+ Number.parseInt(rawValue),
227
+ `Configuration parameter ${param}\` must be a number, but was ${rawValue}`
228
+ );
229
+ }
230
+ getOptionalOneOf(param, defaultValue, supportedValues) {
231
+ const result = this.getOptional(param, defaultValue);
232
+ return validateOneOf(
233
+ result,
234
+ supportedValues,
235
+ `Unsupported ${param}: ${result}. Supported values: ${supportedValues.toString()}`
236
+ );
237
+ }
238
+ getOptionalValidated(param, defaultValue, validator) {
239
+ const value = this.env[param] || defaultValue;
240
+ if (!validator(value)) {
241
+ throw new InternalError({
242
+ message: `Value ${value} is invalid for parameter ${param}`,
243
+ errorCode: "CONFIGURATION_ERROR"
244
+ });
245
+ }
246
+ return value;
247
+ }
248
+ getOptionalValidatedInteger(param, defaultValue, validator) {
249
+ const value = this.getOptionalInteger(param, defaultValue);
250
+ if (!validator(value)) {
251
+ throw new InternalError({
252
+ message: `Value ${value} is invalid for parameter ${param}`,
253
+ errorCode: "CONFIGURATION_ERROR"
254
+ });
255
+ }
256
+ return value;
257
+ }
258
+ getOptionalTransformed(param, defaultValue, transformer) {
259
+ const value = this.env[param] || defaultValue;
260
+ return transformer(value);
261
+ }
262
+ getOptionalNullableTransformed(param, defaultValue, transformer) {
263
+ const value = this.env[param] || defaultValue;
264
+ return transformer(value);
265
+ }
266
+ getMandatoryTransformed(param, transformer) {
267
+ const value = this.getMandatory(param);
268
+ return transformer(value);
269
+ }
270
+ getOptionalBoolean(param, defaultValue) {
271
+ const rawValue = this.env[param]?.toLowerCase();
272
+ if (rawValue === void 0 || rawValue === "") {
273
+ return defaultValue;
274
+ }
275
+ validateOneOf(rawValue, ["true", "false"]);
276
+ return rawValue === "true";
277
+ }
278
+ getMandatoryJsonObject(param, schema) {
279
+ const rawValue = this.getMandatory(param);
280
+ return this.validateSchema(
281
+ JSON.parse(rawValue),
282
+ schema,
283
+ `Configuration parameter ${param} must be a valid JSON meeting the given schema, but was ${rawValue}`
284
+ );
285
+ }
286
+ getOptionalNullableJsonObject(param, schema, defaultValue) {
287
+ const rawValue = this.getOptionalNullable(param, void 0);
288
+ if (!rawValue) {
289
+ return defaultValue;
290
+ }
291
+ return this.validateSchema(
292
+ JSON.parse(rawValue),
293
+ schema,
294
+ `Configuration parameter ${param} must be a valid JSON meeting the given schema, but was ${rawValue}`
295
+ );
296
+ }
297
+ getOptionalJsonObject(param, schema, defaultValue) {
298
+ return this.getOptionalNullableJsonObject(param, schema, defaultValue);
299
+ }
300
+ isProduction() {
301
+ return this.env.NODE_ENV === "production";
302
+ }
303
+ isDevelopment() {
304
+ return this.env.NODE_ENV !== "production";
305
+ }
306
+ isTest() {
307
+ return this.env.NODE_ENV === "test";
308
+ }
309
+ validateSchema(value, schema, errorMessage) {
310
+ const parsedValue = schema.safeParse(value);
311
+ if (!parsedValue.success) {
312
+ throw new InternalError({
313
+ message: errorMessage,
314
+ errorCode: "CONFIGURATION_ERROR",
315
+ details: parsedValue.error
316
+ });
317
+ }
318
+ return parsedValue.data;
319
+ }
320
+ };
321
+ function validateOneOf(validatedEntity, expectedOneOfEntities, errorText) {
322
+ if (!expectedOneOfEntities.includes(validatedEntity)) {
323
+ throw new InternalError({
324
+ message: errorText || // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
325
+ `Validated entity ${validatedEntity} is not one of: ${expectedOneOfEntities.toString()}`,
326
+ errorCode: "CONFIGURATION_ERROR"
327
+ });
328
+ }
329
+ return validatedEntity;
330
+ }
331
+ function validateNumber(validatedObject, errorText) {
332
+ if (!Number.isFinite(validatedObject)) {
333
+ throw new InternalError({
334
+ message: errorText,
335
+ errorCode: "CONFIGURATION_ERROR"
336
+ });
337
+ }
338
+ return validatedObject;
339
+ }
340
+
341
+ // src/config/configTransformers.ts
342
+ var ensureClosingSlashTransformer = (value) => {
343
+ if (!value) {
344
+ return "";
345
+ }
346
+ const lastChar = value.at(-1);
347
+ if (lastChar !== "/") {
348
+ return `${value}/`;
349
+ }
350
+ return value;
351
+ };
352
+
353
+ // src/config/configValidators.ts
354
+ var createRangeValidator = (greaterOrEqualThan, lessOrEqualThan) => {
355
+ return (value) => {
356
+ return value >= greaterOrEqualThan && value <= lessOrEqualThan;
357
+ };
358
+ };
359
+
360
+ // src/errors/either.ts
361
+ var isFailure = (e) => {
362
+ return e.error !== void 0;
363
+ };
364
+ var isSuccess = (e) => {
365
+ return e.result !== void 0;
366
+ };
367
+ var failure = (error) => ({ error });
368
+ var success = (result) => ({ result });
369
+
370
+ // src/utils/encryptionUtility.ts
371
+ var crypto = __toESM(require("crypto"), 1);
372
+ var algorithm = "aes-256-gcm";
373
+ var ivLength = 16;
374
+ var tagLength = 16;
375
+ var defaultEncoding = "hex";
376
+ var defaultSaltLength = 64;
377
+ var defaultPbkdf2Iterations = 1e5;
378
+ var EncryptionUtility = class {
379
+ secret;
380
+ saltLength;
381
+ encryptedPosition;
382
+ tagPosition;
383
+ pbkdf2Iterations;
384
+ encoding;
385
+ constructor(secret, options) {
386
+ this.secret = secret;
387
+ this.encoding = options?.encoding ?? defaultEncoding;
388
+ this.pbkdf2Iterations = options?.pbkdf2Iterations ?? defaultPbkdf2Iterations;
389
+ this.saltLength = options?.saltLength ?? defaultSaltLength;
390
+ this.tagPosition = this.saltLength + ivLength;
391
+ this.encryptedPosition = this.tagPosition + tagLength;
392
+ }
393
+ getKey(salt) {
394
+ return crypto.pbkdf2Sync(this.secret, salt, this.pbkdf2Iterations, 32, "sha512");
395
+ }
396
+ encrypt(value) {
397
+ const iv = crypto.randomBytes(ivLength);
398
+ const salt = crypto.randomBytes(this.saltLength);
399
+ const key = this.getKey(salt);
400
+ const cipher = crypto.createCipheriv(algorithm, key, iv);
401
+ const encrypted = Buffer.concat([cipher.update(String(value), "utf8"), cipher.final()]);
402
+ const tag = cipher.getAuthTag();
403
+ return Buffer.concat([salt, iv, tag, encrypted]).toString(this.encoding);
404
+ }
405
+ decrypt(value) {
406
+ const stringValue = Buffer.from(String(value), this.encoding);
407
+ const salt = stringValue.subarray(0, this.saltLength);
408
+ const iv = stringValue.subarray(this.saltLength, this.tagPosition);
409
+ const tag = stringValue.subarray(this.tagPosition, this.encryptedPosition);
410
+ const encrypted = stringValue.subarray(this.encryptedPosition);
411
+ const key = this.getKey(salt);
412
+ const decipher = crypto.createDecipheriv(algorithm, key, iv);
413
+ decipher.setAuthTag(tag);
414
+ return Buffer.concat([
415
+ decipher.update(encrypted),
416
+ Buffer.from(decipher.final("utf8"))
417
+ ]).toString("utf8");
418
+ }
419
+ };
420
+
421
+ // src/utils/arrayUtils.ts
422
+ function chunk(array, chunkSize) {
423
+ const length = array.length;
424
+ if (!length || chunkSize < 1) {
425
+ return [];
426
+ }
427
+ let index = 0;
428
+ let resIndex = 0;
429
+ const result = new Array(Math.ceil(length / chunkSize));
430
+ while (index < length) {
431
+ result[resIndex++] = array.slice(index, index += chunkSize);
432
+ }
433
+ return result;
434
+ }
435
+ async function callChunked(chunkSize, array, processFn) {
436
+ for (let i = 0; i < array.length; i += chunkSize) {
437
+ const arrayChunk = array.slice(i, i + chunkSize);
438
+ await processFn(arrayChunk);
439
+ }
440
+ }
441
+ function removeNullish(array) {
442
+ return array.filter((e) => e !== void 0 && e !== null);
443
+ }
444
+ function removeFalsy(array) {
445
+ return array.filter((e) => e);
446
+ }
447
+ function removeDuplicates(array) {
448
+ return [...new Set(array)];
449
+ }
450
+
451
+ // src/utils/objectUtils.ts
452
+ var import_dot_prop = __toESM(require("dot-prop"), 1);
453
+ function copyWithoutUndefined(originalValue) {
454
+ return Object.keys(originalValue).reduce(
455
+ (acc, key) => {
456
+ if (originalValue[key] !== void 0) {
457
+ acc[key] = originalValue[key];
458
+ }
459
+ return acc;
460
+ },
461
+ {}
462
+ );
463
+ }
464
+ function copyWithoutEmpty(originalValue) {
465
+ return Object.keys(originalValue).reduce(
466
+ (acc, key) => {
467
+ if (originalValue[key] !== void 0 && originalValue[key] !== null && // @ts-ignore
468
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
469
+ (typeof originalValue[key] !== "string" || originalValue[key].trim().length > 0)) {
470
+ acc[key] = originalValue[key];
471
+ }
472
+ return acc;
473
+ },
474
+ {}
475
+ );
476
+ }
477
+ function pick(source, propNames) {
478
+ const result = {};
479
+ let idx = 0;
480
+ while (idx < propNames.length) {
481
+ if (propNames[idx] in source) {
482
+ result[propNames[idx]] = source[propNames[idx]];
483
+ }
484
+ idx += 1;
485
+ }
486
+ return result;
487
+ }
488
+ function pickWithoutUndefined(source, propNames) {
489
+ const result = {};
490
+ let idx = 0;
491
+ while (idx < propNames.length) {
492
+ if (propNames[idx] in source && source[propNames[idx]] !== void 0) {
493
+ result[propNames[idx]] = source[propNames[idx]];
494
+ }
495
+ idx += 1;
496
+ }
497
+ return result;
498
+ }
499
+ function isEmptyObject(params) {
500
+ for (const key in params) {
501
+ if (Object.hasOwn(params, key) && params[key] !== void 0) {
502
+ return false;
503
+ }
504
+ }
505
+ return true;
506
+ }
507
+ function groupBy(array, selector) {
508
+ return array.reduce(
509
+ (acc, item) => {
510
+ const key = item[selector];
511
+ if (key === void 0 || key === null) {
512
+ return acc;
513
+ }
514
+ if (!acc[key]) {
515
+ acc[key] = [];
516
+ }
517
+ acc[key].push(item);
518
+ return acc;
519
+ },
520
+ {}
521
+ );
522
+ }
523
+ function groupByPath(array, selector) {
524
+ return array.reduce(
525
+ (acc, item) => {
526
+ const key = import_dot_prop.default.get(item, selector);
527
+ if (key === void 0 || key === null) {
528
+ return acc;
529
+ }
530
+ const strKeyPath = key;
531
+ if (!acc[strKeyPath]) {
532
+ acc[strKeyPath] = [];
533
+ }
534
+ acc[strKeyPath].push(item);
535
+ return acc;
536
+ },
537
+ {}
538
+ );
539
+ }
540
+ function groupByUnique(array, selector) {
541
+ return array.reduce(
542
+ (acc, item) => {
543
+ const key = item[selector];
544
+ if (key === void 0 || key === null) {
545
+ return acc;
546
+ }
547
+ if (acc[key] !== void 0) {
548
+ throw new InternalError({
549
+ message: `Duplicated item for selector ${selector.toString()} with value ${key.toString()}`,
550
+ errorCode: "DUPLICATED_ITEM",
551
+ details: { selector, value: key }
552
+ });
553
+ }
554
+ acc[key] = item;
555
+ return acc;
556
+ },
557
+ {}
558
+ );
559
+ }
560
+ function convertDateFieldsToIsoString(object) {
561
+ if (Array.isArray(object)) {
562
+ return object.map(convertDateFieldsToIsoStringAux);
563
+ }
564
+ return Object.entries(object).reduce(
565
+ (result, [key, value]) => {
566
+ result[key] = convertDateFieldsToIsoStringAux(value);
567
+ return result;
568
+ },
569
+ {}
570
+ );
571
+ }
572
+ function convertDateFieldsToIsoStringAux(item) {
573
+ if (item instanceof Date) {
574
+ return item.toISOString();
575
+ }
576
+ if (item && typeof item === "object") {
577
+ return convertDateFieldsToIsoString(item);
578
+ }
579
+ return item;
580
+ }
581
+ function deepClone(object) {
582
+ if (object === void 0 || object === null) {
583
+ return object;
584
+ }
585
+ return structuredClone(object);
586
+ }
587
+
588
+ // src/utils/hashUtils.ts
589
+ var import_node_crypto = require("crypto");
590
+ var HashEncoding = /* @__PURE__ */ ((HashEncoding2) => {
591
+ HashEncoding2["HEX"] = "hex";
592
+ HashEncoding2["BASE64"] = "base64";
593
+ return HashEncoding2;
594
+ })(HashEncoding || {});
595
+ var HashAlgorithm = /* @__PURE__ */ ((HashAlgorithm2) => {
596
+ HashAlgorithm2["SHA256"] = "sha256";
597
+ HashAlgorithm2["SHA512"] = "sha512";
598
+ return HashAlgorithm2;
599
+ })(HashAlgorithm || {});
600
+ function generateHash(algorithm2, data, encoding = "hex" /* HEX */) {
601
+ return (0, import_node_crypto.createHash)(algorithm2).update(data).digest(encoding);
602
+ }
603
+
604
+ // src/logging/loggerConfigResolver.ts
605
+ var import_pino = require("pino");
606
+ var import_pino_pretty = __toESM(require("pino-pretty"), 1);
607
+ function resolveMonorepoLogger(appConfig) {
608
+ if (appConfig.nodeEnv !== "development") {
609
+ return resolveLogger(appConfig);
610
+ }
611
+ const configuration = resolveMonorepoLoggerConfiguration(appConfig);
612
+ return (0, import_pino.pino)(configuration);
613
+ }
614
+ function resolveMonorepoLoggerConfiguration(appConfig) {
615
+ if (appConfig.nodeEnv !== "development") {
616
+ return resolveLoggerConfiguration(appConfig);
617
+ }
618
+ return {
619
+ level: appConfig.logLevel,
620
+ formatters: {
621
+ level: (label) => {
622
+ return { level: label };
623
+ }
624
+ },
625
+ redact: appConfig.redact,
626
+ transport: {
627
+ target: "pino/file",
628
+ options: {
629
+ destination: appConfig.targetFile ?? "./service.log",
630
+ mkdir: true,
631
+ append: appConfig.append ?? false
632
+ }
633
+ }
634
+ };
635
+ }
636
+ function resolveLogger(appConfig) {
637
+ if (appConfig.nodeEnv !== "production") {
638
+ return resolveLoggerConfiguration(appConfig);
639
+ }
640
+ const configuration = resolveLoggerConfiguration(appConfig);
641
+ return (0, import_pino.pino)(configuration);
642
+ }
643
+ function resolveLoggerConfiguration(appConfig) {
644
+ if (appConfig.nodeEnv !== "production") {
645
+ return (0, import_pino.pino)(
646
+ (0, import_pino_pretty.default)({
647
+ sync: true,
648
+ minimumLevel: appConfig.logLevel,
649
+ colorize: true,
650
+ translateTime: "SYS:standard",
651
+ ignore: "hostname,pid"
652
+ })
653
+ );
654
+ }
655
+ return {
656
+ level: appConfig.logLevel,
657
+ formatters: {
658
+ level: (_label, numericLevel) => {
659
+ const level = import_pino.levels.labels[numericLevel] || "unknown";
660
+ return { level };
661
+ }
662
+ },
663
+ redact: appConfig.redact
664
+ };
665
+ }
666
+
667
+ // src/errors/globalErrorHandler.ts
668
+ var import_node_util = require("util");
669
+ var import_pino2 = require("pino");
670
+ var globalLogger = (0, import_pino2.pino)({
671
+ formatters: {
672
+ level: (_label, numericLevel) => {
673
+ const level = import_pino2.levels.labels[numericLevel] || "unknown";
674
+ return { level };
675
+ }
676
+ }
677
+ });
678
+ function resolveGlobalErrorLogObject(err, correlationId) {
679
+ if (import_node_util.types.isNativeError(err)) {
680
+ return {
681
+ message: err.message,
682
+ error: import_pino2.stdSerializers.err(err),
683
+ "x-request-id": correlationId
684
+ };
685
+ }
686
+ if (hasMessage(err)) {
687
+ return {
688
+ message: err.message,
689
+ "x-request-id": correlationId
690
+ };
691
+ }
692
+ return {
693
+ message: "Unknown error",
694
+ "x-request-id": correlationId
695
+ };
696
+ }
697
+ function executeAndHandleGlobalErrors(operation) {
698
+ try {
699
+ const result = operation();
700
+ return result;
701
+ } catch (err) {
702
+ const logObject = resolveGlobalErrorLogObject(err);
703
+ globalLogger.error(logObject, logObject.message);
704
+ process.exit(1);
705
+ }
706
+ }
707
+ async function executeAsyncAndHandleGlobalErrors(operation, stopOnError = true) {
708
+ try {
709
+ const result = await operation();
710
+ return result;
711
+ } catch (err) {
712
+ const logObject = resolveGlobalErrorLogObject(err);
713
+ globalLogger.error(logObject, logObject.message);
714
+ if (stopOnError) {
715
+ process.exit(1);
716
+ }
717
+ }
718
+ }
719
+ async function executeSettleAllAndHandleGlobalErrors(promises, stopOnError = true) {
720
+ const result = await Promise.allSettled(promises);
721
+ let errorsHappened;
722
+ for (const entry of result) {
723
+ if (entry.status === "rejected") {
724
+ const logObject = resolveGlobalErrorLogObject(entry.reason);
725
+ globalLogger.error(logObject, logObject.message);
726
+ errorsHappened = true;
727
+ }
728
+ }
729
+ if (stopOnError && errorsHappened) {
730
+ process.exit(1);
731
+ }
732
+ return result;
733
+ }
734
+
735
+ // src/errors/publicErrors.ts
736
+ var import_node_http2 = require("http2");
737
+ var RequestValidationError = class extends PublicNonRecoverableError {
738
+ constructor(errors) {
739
+ super({
740
+ message: "Invalid params",
741
+ errorCode: "VALIDATION_ERROR",
742
+ httpStatusCode: import_node_http2.constants.HTTP_STATUS_BAD_REQUEST,
743
+ details: {
744
+ error: errors
745
+ }
746
+ });
747
+ }
748
+ };
749
+ var AccessDeniedError = class extends PublicNonRecoverableError {
750
+ constructor(params) {
751
+ super({
752
+ message: params.message,
753
+ errorCode: "ACCESS_DENIED",
754
+ httpStatusCode: import_node_http2.constants.HTTP_STATUS_FORBIDDEN,
755
+ details: params.details,
756
+ cause: params.cause
757
+ });
758
+ }
759
+ };
760
+ var EntityNotFoundError = class extends PublicNonRecoverableError {
761
+ constructor(params) {
762
+ super({
763
+ message: params.message,
764
+ errorCode: "ENTITY_NOT_FOUND",
765
+ httpStatusCode: import_node_http2.constants.HTTP_STATUS_NOT_FOUND,
766
+ details: params.details,
767
+ cause: params.cause
768
+ });
769
+ }
770
+ };
771
+ var EntityGoneError = class extends PublicNonRecoverableError {
772
+ constructor(params) {
773
+ super({
774
+ message: params.message,
775
+ errorCode: "ENTITY_GONE",
776
+ httpStatusCode: 410,
777
+ details: params.details
778
+ });
779
+ }
780
+ };
781
+ var AuthFailedError = class extends PublicNonRecoverableError {
782
+ constructor(params = {}) {
783
+ super({
784
+ message: params.message ?? "Authentication failed",
785
+ errorCode: "AUTH_FAILED",
786
+ httpStatusCode: import_node_http2.constants.HTTP_STATUS_UNAUTHORIZED,
787
+ details: params.details,
788
+ cause: params.cause
789
+ });
790
+ }
791
+ };
792
+
793
+ // src/utils/waitUtils.ts
794
+ var waitAndRetry = async (predicateFn, sleepTime = 20, maxRetryCount = 15) => {
795
+ return new Promise((resolve, reject) => {
796
+ let retryCount = 0;
797
+ function performCheck() {
798
+ if (maxRetryCount !== 0 && retryCount > maxRetryCount) {
799
+ resolve(predicateFn());
800
+ }
801
+ Promise.resolve().then(() => {
802
+ return predicateFn();
803
+ }).then((result) => {
804
+ if (result) {
805
+ resolve(result);
806
+ } else {
807
+ retryCount++;
808
+ setTimeout(performCheck, sleepTime);
809
+ }
810
+ }).catch((err) => {
811
+ reject(err);
812
+ });
813
+ }
814
+ performCheck();
815
+ });
816
+ };
817
+
818
+ // src/observability/MultiTransactionObservabilityManager.ts
819
+ var MultiTransactionObservabilityManager = class {
820
+ managers;
821
+ constructor(managers) {
822
+ this.managers = managers;
823
+ }
824
+ start(transactionName, uniqueTransactionKey) {
825
+ for (const manager of this.managers) {
826
+ manager.start(transactionName, uniqueTransactionKey);
827
+ }
828
+ }
829
+ startWithGroup(transactionName, uniqueTransactionKey, transactionGroup) {
830
+ for (const manager of this.managers) {
831
+ manager.startWithGroup(transactionName, uniqueTransactionKey, transactionGroup);
832
+ }
833
+ }
834
+ stop(uniqueTransactionKey, wasSuccessful) {
835
+ for (const manager of this.managers) {
836
+ manager.stop(uniqueTransactionKey, wasSuccessful);
837
+ }
838
+ }
839
+ };
840
+
841
+ // src/utils/checksumUtils.ts
842
+ var import_node_crypto2 = require("crypto");
843
+ var HASH_ALGORITHM = "md5";
844
+ function generateChecksumForBufferOrString(data) {
845
+ return (0, import_node_crypto2.createHash)(HASH_ALGORITHM).update(data).digest("hex");
846
+ }
847
+ function generateChecksumForObject(object) {
848
+ const objectAsString = JSON.stringify(object);
849
+ return generateChecksumForBufferOrString(objectAsString);
850
+ }
851
+ function generateChecksumForReadable(readable) {
852
+ return new Promise((resolve, reject) => {
853
+ const hashCreator = (0, import_node_crypto2.createHash)(HASH_ALGORITHM);
854
+ readable.on("data", (data) => {
855
+ if (Buffer.isBuffer(data)) {
856
+ hashCreator.update(data);
857
+ } else {
858
+ hashCreator.update(Buffer.from(data));
859
+ }
860
+ });
861
+ readable.on("end", () => {
862
+ const hash = hashCreator.digest("hex");
863
+ resolve(hash);
864
+ });
865
+ readable.on("error", (err) => {
866
+ reject(err);
867
+ });
868
+ });
869
+ }
870
+
871
+ // src/utils/streamUtils.ts
872
+ var import_node_constants = require("constants");
873
+ var import_node_fs = require("fs");
874
+ var import_promises = require("fs/promises");
875
+ var import_node_stream = require("stream");
876
+ var FsReadableProvider = class _FsReadableProvider {
877
+ storageFile;
878
+ constructor(options) {
879
+ this.storageFile = options.storageFile;
880
+ }
881
+ fileExists() {
882
+ return new Promise((resolve) => {
883
+ (0, import_node_fs.access)(this.storageFile, import_node_constants.F_OK, (err) => {
884
+ return resolve(!err);
885
+ });
886
+ });
887
+ }
888
+ async getContentLength() {
889
+ if (!await this.fileExists()) {
890
+ throw new Error(`File ${this.storageFile} was already deleted.`);
891
+ }
892
+ const stats = await (0, import_promises.stat)(this.storageFile);
893
+ return stats.size;
894
+ }
895
+ async createStream() {
896
+ if (!await this.fileExists()) {
897
+ throw new Error(`File ${this.storageFile} was already deleted.`);
898
+ }
899
+ return (0, import_node_fs.createReadStream)(this.storageFile);
900
+ }
901
+ async destroy() {
902
+ if (!await this.fileExists()) {
903
+ return;
904
+ }
905
+ return (0, import_promises.unlink)(this.storageFile);
906
+ }
907
+ async persist(sourceReadable) {
908
+ const writable = (0, import_node_fs.createWriteStream)(this.storageFile);
909
+ return new Promise((resolve, reject) => {
910
+ (0, import_node_stream.pipeline)(sourceReadable, writable, (err) => {
911
+ if (err) {
912
+ reject(err);
913
+ } else {
914
+ resolve();
915
+ }
916
+ });
917
+ });
918
+ }
919
+ static async persistReadableToFs(options) {
920
+ const provider = new _FsReadableProvider({
921
+ storageFile: options.targetFile
922
+ });
923
+ await provider.persist(options.sourceReadable);
924
+ return provider;
925
+ }
926
+ };
927
+ // Annotate the CommonJS export names for ESM import in node:
928
+ 0 && (module.exports = {
929
+ AccessDeniedError,
930
+ AuthFailedError,
931
+ ConfigScope,
932
+ EncryptionUtility,
933
+ EntityGoneError,
934
+ EntityNotFoundError,
935
+ FsReadableProvider,
936
+ HashAlgorithm,
937
+ HashEncoding,
938
+ InternalError,
939
+ MultiTransactionObservabilityManager,
940
+ PublicNonRecoverableError,
941
+ RequestValidationError,
942
+ callChunked,
943
+ chunk,
944
+ convertDateFieldsToIsoString,
945
+ copyWithoutEmpty,
946
+ copyWithoutUndefined,
947
+ createRangeValidator,
948
+ deepClone,
949
+ ensureClosingSlashTransformer,
950
+ executeAndHandleGlobalErrors,
951
+ executeAsyncAndHandleGlobalErrors,
952
+ executeSettleAllAndHandleGlobalErrors,
953
+ failure,
954
+ generateChecksumForBufferOrString,
955
+ generateChecksumForObject,
956
+ generateChecksumForReadable,
957
+ generateHash,
958
+ globalLogger,
959
+ groupBy,
960
+ groupByPath,
961
+ groupByUnique,
962
+ hasMessage,
963
+ isEmptyObject,
964
+ isEntityGoneError,
965
+ isError,
966
+ isFailure,
967
+ isInternalError,
968
+ isObject,
969
+ isPublicNonRecoverableError,
970
+ isStandardizedError,
971
+ isSuccess,
972
+ pick,
973
+ pickWithoutUndefined,
974
+ removeDuplicates,
975
+ removeFalsy,
976
+ removeNullish,
977
+ resolveGlobalErrorLogObject,
978
+ resolveLogger,
979
+ resolveLoggerConfiguration,
980
+ resolveMonorepoLogger,
981
+ resolveMonorepoLoggerConfiguration,
982
+ success,
983
+ waitAndRetry
984
+ });
985
+ //# sourceMappingURL=index.cjs.map