@smbcheeky/error-object-from-payload 1.1.5

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/dist/index.js ADDED
@@ -0,0 +1,597 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __spreadValues = (a, b) => {
12
+ for (var prop in b || (b = {}))
13
+ if (__hasOwnProp.call(b, prop))
14
+ __defNormalProp(a, prop, b[prop]);
15
+ if (__getOwnPropSymbols)
16
+ for (var prop of __getOwnPropSymbols(b)) {
17
+ if (__propIsEnum.call(b, prop))
18
+ __defNormalProp(a, prop, b[prop]);
19
+ }
20
+ return a;
21
+ };
22
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
23
+ var __export = (target, all) => {
24
+ for (var name in all)
25
+ __defProp(target, name, { get: all[name], enumerable: true });
26
+ };
27
+ var __copyProps = (to, from, except, desc) => {
28
+ if (from && typeof from === "object" || typeof from === "function") {
29
+ for (let key of __getOwnPropNames(from))
30
+ if (!__hasOwnProp.call(to, key) && key !== except)
31
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
32
+ }
33
+ return to;
34
+ };
35
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
36
+
37
+ // src/index.ts
38
+ var src_exports = {};
39
+ __export(src_exports, {
40
+ DEFAULT_BUILD_OPTIONS: () => DEFAULT_BUILD_OPTIONS,
41
+ addPrefixPathVariants: () => addPrefixPathVariants,
42
+ fromPayload: () => fromPayload
43
+ });
44
+ module.exports = __toCommonJS(src_exports);
45
+ var import_error_object2 = require("@smbcheeky/error-object");
46
+
47
+ // src/builder/index.ts
48
+ var import_error_object = require("@smbcheeky/error-object");
49
+
50
+ // src/utils.ts
51
+ var addPrefixPathVariants = (prefix, array) => {
52
+ if (typeof prefix === "string") {
53
+ return array.concat(
54
+ array.map((s) => typeof s === "string" ? `${prefix}.${s}` : s)
55
+ );
56
+ }
57
+ if (Array.isArray(prefix) && prefix.length > 0 && typeof (prefix == null ? void 0 : prefix[0]) === "string") {
58
+ const result = [...array];
59
+ for (const p of prefix) {
60
+ const temp = array.map((s) => typeof s === "string" ? `${p}.${s}` : s);
61
+ result.push(...temp);
62
+ }
63
+ return result;
64
+ }
65
+ return array;
66
+ };
67
+ var DEFAULT_BUILD_OPTIONS = {
68
+ pathToErrors: ["errors", "errs"],
69
+ pathToCode: addPrefixPathVariants("error", [
70
+ "code",
71
+ "err_code",
72
+ "errorCode",
73
+ "error_code"
74
+ ]),
75
+ pathToNumberCode: addPrefixPathVariants("error", [
76
+ "numberCode",
77
+ "err_number_code",
78
+ "errorNumberCode",
79
+ "error_number_code"
80
+ ]),
81
+ pathToMessage: addPrefixPathVariants("error", [
82
+ "message",
83
+ "err_message",
84
+ "errorMessage",
85
+ "error_message"
86
+ ]),
87
+ pathToDetails: addPrefixPathVariants("error", [
88
+ "details",
89
+ "err_details",
90
+ "errorDetails",
91
+ "error_details"
92
+ ]),
93
+ pathToDomain: addPrefixPathVariants("error", [
94
+ "domain",
95
+ "errorDomain",
96
+ "error_domain",
97
+ "err_domain",
98
+ "type"
99
+ ]),
100
+ transform: (beforeTransform) => {
101
+ let newCode = beforeTransform.code;
102
+ if (beforeTransform.code === void 0 || beforeTransform.code === null) {
103
+ const value = beforeTransform.numberCode;
104
+ if (value !== void 0 && value !== null) {
105
+ newCode = value.toString();
106
+ }
107
+ }
108
+ return __spreadProps(__spreadValues({}, beforeTransform), {
109
+ code: newCode
110
+ });
111
+ }
112
+ };
113
+
114
+ // src/builder/valuesFromPaths.ts
115
+ var __processAllValuesFromPaths = (objectToParse, options) => {
116
+ let codeBeforeTransform;
117
+ let codePath;
118
+ if (!("pathToCode" in options)) {
119
+ return "pathToCodeIsInvalid";
120
+ }
121
+ if (!Array.isArray(options.pathToCode)) {
122
+ return "pathToCodeIsNotAnArray";
123
+ }
124
+ for (const path of options.pathToCode) {
125
+ if (typeof path !== "string") {
126
+ return "pathToCodeValuesAreNotStrings";
127
+ }
128
+ const found = findNestedValueForPath(objectToParse, path);
129
+ if (found !== void 0 && found !== null) {
130
+ if (typeof found === "string") {
131
+ codePath = path;
132
+ codeBeforeTransform = found;
133
+ break;
134
+ }
135
+ if (Array.isArray(found) || typeof found === "object") {
136
+ codePath = path;
137
+ codeBeforeTransform = JSON.stringify(found);
138
+ break;
139
+ }
140
+ }
141
+ }
142
+ let numberCodeBeforeTransform;
143
+ let numberCodePath;
144
+ if (!("pathToNumberCode" in options)) {
145
+ return "pathToNumberCodeIsInvalid";
146
+ }
147
+ if (!Array.isArray(options.pathToNumberCode)) {
148
+ return "pathToNumberCodeIsNotAnArray";
149
+ }
150
+ for (const path of options.pathToNumberCode) {
151
+ if (typeof path !== "string") {
152
+ return "pathToNumberCodeValuesAreNotStrings";
153
+ }
154
+ const found = findNestedValueForPath(objectToParse, path);
155
+ if (found !== void 0 && found !== null && typeof found === "number" && !isNaN(found)) {
156
+ numberCodePath = path;
157
+ numberCodeBeforeTransform = found;
158
+ break;
159
+ }
160
+ }
161
+ let messageBeforeTransform;
162
+ let messagePath;
163
+ if (!("pathToMessage" in options)) {
164
+ return "pathToMessageIsInvalid";
165
+ }
166
+ if (!Array.isArray(options.pathToMessage)) {
167
+ return "pathToMessageIsNotAnArray";
168
+ }
169
+ for (const path of options.pathToMessage) {
170
+ if (typeof path !== "string") {
171
+ return "pathToMessageValuesAreNotStrings";
172
+ }
173
+ const found = findNestedValueForPath(objectToParse, path);
174
+ if (found !== void 0 && found !== null) {
175
+ if (typeof found === "string") {
176
+ messagePath = path;
177
+ messageBeforeTransform = found;
178
+ break;
179
+ }
180
+ if (Array.isArray(found) || typeof found === "object") {
181
+ messagePath = path;
182
+ messageBeforeTransform = JSON.stringify(found);
183
+ break;
184
+ }
185
+ }
186
+ }
187
+ let detailsBeforeTransform;
188
+ let detailsPath;
189
+ if (!("pathToDetails" in options)) {
190
+ return "pathToDetailsIsInvalid";
191
+ }
192
+ if (!Array.isArray(options.pathToDetails)) {
193
+ return "pathToDetailsIsNotAnArray";
194
+ }
195
+ for (const path of options.pathToDetails) {
196
+ if (typeof path !== "string") {
197
+ return "pathToDetailsValuesAreNotStrings";
198
+ }
199
+ const found = findNestedValueForPath(objectToParse, path);
200
+ if (found !== void 0 && found !== null) {
201
+ if (typeof found === "string") {
202
+ detailsPath = path;
203
+ detailsBeforeTransform = found;
204
+ break;
205
+ }
206
+ if (Array.isArray(found) || typeof found === "object") {
207
+ detailsPath = path;
208
+ detailsBeforeTransform = JSON.stringify(found);
209
+ break;
210
+ }
211
+ }
212
+ }
213
+ let domainBeforeTransform;
214
+ let domainPath;
215
+ if (!("pathToDomain" in options)) {
216
+ return "pathToDomainIsInvalid";
217
+ }
218
+ if (!Array.isArray(options.pathToDomain)) {
219
+ return "pathToDomainIsNotAnArray";
220
+ }
221
+ for (const path of options.pathToDomain) {
222
+ if (typeof path !== "string") {
223
+ return "pathToDomainValuesAreNotStrings";
224
+ }
225
+ const found = findNestedValueForPath(objectToParse, path);
226
+ if (found !== void 0 && found !== null) {
227
+ if (typeof found === "string") {
228
+ domainPath = path;
229
+ domainBeforeTransform = found;
230
+ break;
231
+ }
232
+ if (Array.isArray(found) || typeof found === "object") {
233
+ domainPath = path;
234
+ domainBeforeTransform = JSON.stringify(found);
235
+ break;
236
+ }
237
+ }
238
+ }
239
+ return {
240
+ codeBeforeTransform,
241
+ codePath,
242
+ numberCodeBeforeTransform,
243
+ numberCodePath,
244
+ messageBeforeTransform,
245
+ messagePath,
246
+ detailsBeforeTransform,
247
+ detailsPath,
248
+ domainBeforeTransform,
249
+ domainPath
250
+ };
251
+ };
252
+
253
+ // src/builder/index.ts
254
+ var buildSummariesFromObject = (input, withOptions) => {
255
+ try {
256
+ const options = withOptions != null ? withOptions : __spreadValues({}, DEFAULT_BUILD_OPTIONS);
257
+ if (input === void 0 || input === null) {
258
+ return ["isNullish"];
259
+ }
260
+ if (typeof input !== "object") {
261
+ return ["isNotAnObject"];
262
+ }
263
+ let errors = [];
264
+ let errorsPath;
265
+ let didDetectErrorsArray = false;
266
+ if ("pathToErrors" in options) {
267
+ if (!Array.isArray(options.pathToErrors)) {
268
+ return ["pathToErrorsIsNotAnArray"];
269
+ }
270
+ for (const path of options.pathToErrors) {
271
+ if (typeof path !== "string") {
272
+ return ["pathToErrorsValuesAreNotStrings"];
273
+ }
274
+ const found = findNestedValueForPath(input, path);
275
+ if (found && Array.isArray(found)) {
276
+ errors = found;
277
+ errorsPath = path;
278
+ didDetectErrorsArray = true;
279
+ break;
280
+ }
281
+ }
282
+ }
283
+ if (errors.length === 0) {
284
+ errors = [input];
285
+ }
286
+ let summaries = [];
287
+ for (const errorMaybeObject of errors) {
288
+ const summary = buildSummaryFromObject(
289
+ errorMaybeObject,
290
+ errorsPath,
291
+ didDetectErrorsArray,
292
+ options
293
+ );
294
+ summaries.push(summary);
295
+ }
296
+ return summaries;
297
+ } catch (generalError) {
298
+ import_error_object.ErrorObject.SHOW_ERROR_LOGS && console.log(
299
+ "[ErrorObject]",
300
+ "Error during buildSummariesFromObject():",
301
+ generalError
302
+ );
303
+ return ["generalBuildSummariesFromObjectError"];
304
+ }
305
+ };
306
+ var buildSummaryFromObject = (maybeObject, errorsPath, didDetectErrorsArray, withOptions) => {
307
+ try {
308
+ const options = withOptions != null ? withOptions : __spreadValues({}, DEFAULT_BUILD_OPTIONS);
309
+ if (maybeObject === void 0 || maybeObject === null) {
310
+ return "buildSummaryIsNullish";
311
+ }
312
+ let objectToParse;
313
+ if (typeof maybeObject === "string") {
314
+ try {
315
+ const json = JSON.parse(maybeObject);
316
+ if (json !== void 0 && json !== null && typeof json === "object") {
317
+ objectToParse = json;
318
+ }
319
+ } catch (e) {
320
+ }
321
+ if (objectToParse === maybeObject) {
322
+ objectToParse = { code: "unknown", message: maybeObject };
323
+ }
324
+ }
325
+ if (objectToParse === void 0 || objectToParse === null) {
326
+ objectToParse = maybeObject;
327
+ }
328
+ if (typeof objectToParse !== "object") {
329
+ return "buildSummaryIsNotAnObject";
330
+ }
331
+ const valuesResult = __processAllValuesFromPaths(objectToParse, options);
332
+ if (typeof valuesResult === "string") {
333
+ return valuesResult;
334
+ }
335
+ const {
336
+ codeBeforeTransform,
337
+ codePath,
338
+ numberCodeBeforeTransform,
339
+ numberCodePath,
340
+ messageBeforeTransform,
341
+ messagePath,
342
+ detailsBeforeTransform,
343
+ detailsPath,
344
+ domainBeforeTransform,
345
+ domainPath
346
+ } = valuesResult;
347
+ if ("transform" in options && typeof options.transform !== "function") {
348
+ return "transformIsNotAFunction";
349
+ }
350
+ const beforeTransform = {
351
+ code: codeBeforeTransform,
352
+ numberCode: numberCodeBeforeTransform,
353
+ message: messageBeforeTransform,
354
+ details: detailsBeforeTransform,
355
+ domain: domainBeforeTransform
356
+ };
357
+ const values = options.transform ? options.transform(beforeTransform, objectToParse) : beforeTransform;
358
+ if (values === void 0 || values === null || typeof values !== "object") {
359
+ return "transformResultIsNotAValidObject";
360
+ }
361
+ if (values.code && typeof values.code !== "string") {
362
+ return "transformCodeResultIsNotString";
363
+ }
364
+ if (values.numberCode !== void 0 && values.numberCode !== null && typeof values.numberCode !== "number") {
365
+ return "transformNumberCodeResultIsNotNumber";
366
+ }
367
+ if (values.numberCode !== void 0 && values.numberCode !== null && isNaN(values.numberCode)) {
368
+ return "transformNumberCodeResultIsNaN";
369
+ }
370
+ if (values.message && typeof values.message !== "string") {
371
+ return "transformMessageResultIsNotString";
372
+ }
373
+ if (values.details && typeof values.details !== "string") {
374
+ return "transformDetailsResultIsNotString";
375
+ }
376
+ if (values.domain && typeof values.domain !== "string") {
377
+ return "transformDomainResultIsNotString";
378
+ }
379
+ return {
380
+ didDetectErrorsArray: didDetectErrorsArray ? true : void 0,
381
+ input: objectToParse,
382
+ path: errorsPath,
383
+ value: {
384
+ code: codePath || codeBeforeTransform || values.code ? {
385
+ path: codePath,
386
+ beforeTransform: codeBeforeTransform,
387
+ value: values.code
388
+ } : void 0,
389
+ numberCode: numberCodePath || numberCodeBeforeTransform !== void 0 && numberCodeBeforeTransform !== null || values.numberCode !== void 0 && values.numberCode !== null ? {
390
+ path: numberCodePath,
391
+ beforeTransform: numberCodeBeforeTransform,
392
+ value: values.numberCode
393
+ } : void 0,
394
+ message: messagePath || messageBeforeTransform || values.message ? {
395
+ path: messagePath,
396
+ beforeTransform: messageBeforeTransform,
397
+ value: values.message
398
+ } : void 0,
399
+ details: detailsPath || detailsBeforeTransform || values.details ? {
400
+ path: detailsPath,
401
+ beforeTransform: detailsBeforeTransform,
402
+ value: values.details
403
+ } : void 0,
404
+ domain: domainPath || domainBeforeTransform || values.domain ? {
405
+ path: domainPath,
406
+ beforeTransform: domainBeforeTransform,
407
+ value: values.domain
408
+ } : void 0
409
+ }
410
+ };
411
+ } catch (generalError) {
412
+ import_error_object.ErrorObject.SHOW_ERROR_LOGS && console.log(
413
+ "[ErrorObject]",
414
+ "Error during buildSummaryFromObject():",
415
+ generalError
416
+ );
417
+ return "generalBuildSummaryFromObjectError";
418
+ }
419
+ };
420
+ var findNestedValueForPath = (value, path) => {
421
+ var _a;
422
+ if (!path || !value) {
423
+ return void 0;
424
+ }
425
+ const normalizedPath = (_a = path == null ? void 0 : path.replace("[", "")) == null ? void 0 : _a.replace("]", "");
426
+ return !normalizedPath ? void 0 : normalizedPath.split(".").reduce((acc, key) => {
427
+ if (key.length === 0) {
428
+ return acc;
429
+ }
430
+ const numericKey = Number(key);
431
+ const resolvedKey = isNaN(numericKey) ? key : numericKey;
432
+ return acc && typeof acc === "object" ? acc[resolvedKey] : void 0;
433
+ }, value);
434
+ };
435
+
436
+ // src/index.ts
437
+ var checkInputForInitialObject = (input, withOptions) => {
438
+ try {
439
+ const options = withOptions != null ? withOptions : __spreadValues({}, DEFAULT_BUILD_OPTIONS);
440
+ if (input === void 0 || input === null) {
441
+ return "checkIsNullish";
442
+ }
443
+ if (typeof input !== "object") {
444
+ return "checkIsNotAnObject";
445
+ }
446
+ if ("checkInputObjectForValues" in options) {
447
+ if (typeof options.checkInputObjectForValues !== "object") {
448
+ return "checkInputObjectForValuesIsNotAnObject";
449
+ }
450
+ const checkInputObjectForValues = Object.entries(
451
+ options.checkInputObjectForValues
452
+ );
453
+ for (const [key, rule] of checkInputObjectForValues) {
454
+ const foundValue = findNestedValueForPath(input, key);
455
+ if (rule.exists ? foundValue !== rule.value : foundValue === rule.value) {
456
+ return "checkInputObjectForValuesFailed";
457
+ }
458
+ }
459
+ }
460
+ if ("checkInputObjectForTypes" in options) {
461
+ if (typeof options.checkInputObjectForTypes !== "object") {
462
+ return "checkInputObjectForTypesIsNotAnObject";
463
+ }
464
+ const checkInputObjectForTypes = Object.entries(
465
+ options.checkInputObjectForTypes
466
+ );
467
+ for (const [key, rule] of checkInputObjectForTypes) {
468
+ const foundValue = findNestedValueForPath(input, key);
469
+ if (rule.valueIsArray) {
470
+ if (rule.exists ? !Array.isArray(foundValue) : Array.isArray(foundValue)) {
471
+ return "checkInputObjectForTypesValueIsArrayFailed";
472
+ }
473
+ }
474
+ if (rule.exists ? typeof foundValue !== rule.type : typeof foundValue === rule.type) {
475
+ return "checkInputObjectForTypesFailed";
476
+ }
477
+ }
478
+ }
479
+ if ("checkInputObjectForKeys" in options) {
480
+ if (typeof options.checkInputObjectForKeys !== "object") {
481
+ return "checkInputObjectForKeysIsNotAnObject";
482
+ }
483
+ const checkInputObjectForKeys = Object.entries(
484
+ options.checkInputObjectForKeys
485
+ );
486
+ for (const [key, rule] of checkInputObjectForKeys) {
487
+ const foundValue = findNestedValueForPath(input, key);
488
+ if (rule.exists ? !foundValue : foundValue) {
489
+ return "checkInputObjectForKeysFailed";
490
+ }
491
+ }
492
+ }
493
+ } catch (error) {
494
+ import_error_object2.ErrorObject.SHOW_ERROR_LOGS && console.log(
495
+ "[ErrorObject]",
496
+ "Error during checkInputForInitialObject():",
497
+ error
498
+ );
499
+ }
500
+ return void 0;
501
+ };
502
+ var processErrorObjectResult = (summaries, raw, fallbackError) => {
503
+ const processingErrors = [];
504
+ try {
505
+ const validErrors = summaries.filter((summary) => {
506
+ var _a, _b;
507
+ if (typeof summary === "string") {
508
+ processingErrors.push({ errorCode: summary, summary: void 0 });
509
+ return false;
510
+ }
511
+ if (typeof summary !== "object") {
512
+ processingErrors.push({
513
+ errorCode: "invalidSummary",
514
+ summary: void 0
515
+ });
516
+ return false;
517
+ }
518
+ const code = (_a = summary.value.code) == null ? void 0 : _a.value;
519
+ const message = (_b = summary.value.message) == null ? void 0 : _b.value;
520
+ if (code !== void 0 && code !== null && typeof code === "string") {
521
+ if (message !== void 0 && message !== null && typeof message === "string") {
522
+ return true;
523
+ }
524
+ }
525
+ processingErrors.push({ errorCode: "unknownCodeOrMessage", summary });
526
+ return false;
527
+ }).map((s) => {
528
+ var _a, _b, _c, _d, _e;
529
+ const summary = s;
530
+ const code = (_a = summary.value.code) == null ? void 0 : _a.value;
531
+ const numberCode = (_b = summary.value.numberCode) == null ? void 0 : _b.value;
532
+ const message = (_c = summary.value.message) == null ? void 0 : _c.value;
533
+ const details = (_d = summary.value.details) == null ? void 0 : _d.value;
534
+ const domain = (_e = summary.value.domain) == null ? void 0 : _e.value;
535
+ if (code !== void 0 && code !== null && typeof code === "string") {
536
+ if (message !== void 0 && message !== null && typeof message === "string") {
537
+ return new import_error_object2.ErrorObject({
538
+ code,
539
+ message,
540
+ numberCode,
541
+ details,
542
+ domain,
543
+ summary,
544
+ processingErrors
545
+ });
546
+ }
547
+ }
548
+ return null;
549
+ }).filter(
550
+ (s) => s !== null && s !== void 0 && s instanceof import_error_object2.ErrorObject
551
+ );
552
+ if (validErrors.length > 0) {
553
+ const [firstError, ...nextErrors] = validErrors;
554
+ const error = firstError.setNextErrors((nextErrors == null ? void 0 : nextErrors.length) > 0 ? nextErrors : void 0).setRaw(raw);
555
+ return {
556
+ error,
557
+ force: error != null ? error : fallbackError.setProcessingErrors(processingErrors)
558
+ };
559
+ }
560
+ } catch (error) {
561
+ import_error_object2.ErrorObject.SHOW_ERROR_LOGS && console.log(
562
+ "[ErrorObject]",
563
+ "Error during processErrorObjectResult():",
564
+ error
565
+ );
566
+ }
567
+ return {
568
+ error: void 0,
569
+ force: processingErrors.length > 0 ? fallbackError.setProcessingErrors(processingErrors) : fallbackError
570
+ };
571
+ };
572
+ var fromPayload = (value, withOptions) => {
573
+ const options = __spreadValues(__spreadValues({}, DEFAULT_BUILD_OPTIONS), withOptions != null ? withOptions : {});
574
+ const fallbackError = import_error_object2.ErrorObject.fallback().setRaw(value);
575
+ const checksFailed = checkInputForInitialObject(value, options);
576
+ if (checksFailed !== void 0) {
577
+ return {
578
+ error: void 0,
579
+ force: fallbackError.setProcessingErrors([
580
+ { errorCode: checksFailed, summary: void 0 }
581
+ ])
582
+ };
583
+ }
584
+ let summaries;
585
+ if ("pathToErrors" in options) {
586
+ summaries = buildSummariesFromObject(value, options);
587
+ } else {
588
+ summaries = [buildSummaryFromObject(value, void 0, false, options)];
589
+ }
590
+ return processErrorObjectResult(summaries, value, fallbackError);
591
+ };
592
+ // Annotate the CommonJS export names for ESM import in node:
593
+ 0 && (module.exports = {
594
+ DEFAULT_BUILD_OPTIONS,
595
+ addPrefixPathVariants,
596
+ fromPayload
597
+ });