@adobe/aio-commerce-lib-core 0.2.0 → 0.4.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # @adobe/aio-commerce-lib-core
2
2
 
3
+ ## 0.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#46](https://github.com/adobe/aio-commerce-sdk/pull/46) [`4b75585`](https://github.com/adobe/aio-commerce-sdk/commit/4b75585c0d27bd472de3277be5ddaf6a977664de) Thanks [@iivvaannxx](https://github.com/iivvaannxx)! - Removed namespaced exports for index module
8
+
9
+ ## 0.3.0
10
+
11
+ ### Minor Changes
12
+
13
+ - [#22](https://github.com/adobe/aio-commerce-sdk/pull/22) [`9885eee`](https://github.com/adobe/aio-commerce-sdk/commit/9885eee5849ba7939b2067d3357e677beced3774) Thanks [@iivvaannxx](https://github.com/iivvaannxx)! - Changes include:
14
+ - Removed the `Result` utilities.
15
+ - Removed the `Validation` utilities.
16
+ - Added `CommerceSdkValidationError` and `CommerceSdkErrorBase` as new error types for better error handling
17
+
3
18
  ## 0.2.0
4
19
 
5
20
  ### Minor Changes
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  > [!WARNING]
4
4
  > This package is a work in progress and is not yet ready for use yet. You may be able to install it, but if you do, expect breaking changes.
5
5
 
6
- This package provides core utilities for the Adobe Commerce SDK libraries.
6
+ This package provides core utilities used across the Adobe Commerce SDK.
7
7
 
8
8
  ## Installation
9
9
 
@@ -11,143 +11,9 @@ This package provides core utilities for the Adobe Commerce SDK libraries.
11
11
  pnpm install @adobe/aio-commerce-lib-core
12
12
  ```
13
13
 
14
- ## Overview
15
-
16
- This package provides core utilities for the Adobe Commerce SDK libraries.
17
-
18
- ### Current Utilities
19
-
20
- - **[`Result`](./source/lib/result.ts)**: A type-safe way to handle success and failure cases, without relying on exceptions. Inspired by the Rust [`Result` type](https://doc.rust-lang.org/std/result/).
21
- - **[`Validation`](./source/lib/validation.ts)**: A set of utilities regarding validation, such as creating and pretty-printing validation errors.
22
-
23
14
  ## Usage
24
15
 
25
- ### Result
26
-
27
- Within every AppBuilder action you can use the `Result<T, E>` type to handle success and failure cases. The `Result` type is a union type that can either be a success with a value of type `T` or a failure with an error of type `E` that extends `ErrorType`.
28
-
29
- #### Signatures
30
-
31
- - `isOk(result: Result<T, E>): result is { ok: true, value: T }`
32
- - `isErr(result: Result<T, E>): result is { ok: false, error: E }`
33
- - `unwrap(result: Result<T, E>): T throws Error`
34
- - `unwrapErr(result: Result<T, E>): E throws Error`
35
- - `ok(value: T): Result<T, E>`
36
- - `err(error: E): Result<T, E>`
37
-
38
- #### Use case
39
-
40
- - `isOk` and `isErr` are type guards that let you branch logic based on the result.
41
- - `unwrap` returns the value if the result is a success, otherwise it throws.
42
- - `unwrapErr` returns the error if the result is a failure, otherwise it throws.
43
- - `ok` and `err` are helpers to create success and failure results.
44
-
45
- <hr/>
46
-
47
- ```ts
48
- import {
49
- type Result,
50
- err,
51
- isOk,
52
- ok,
53
- unwrap,
54
- } from "@adobe/aio-commerce-lib-core/result";
55
-
56
- // Simulated function returning a Result
57
- const fetchProduct = async (id: string): Result<Product, Error> => {
58
- const response = await api.getProductById(id);
59
- if (response.statusCode === 200) {
60
- return ok(response.data);
61
- }
62
-
63
- return err({
64
- _tag: "ApiError",
65
- error: new Error(response.error),
66
- statusCode: response.statusCode,
67
- });
68
- };
69
-
70
- export const main = async function (params: Record<string, unknown>) {
71
- const result = fetchProduct("valid");
72
-
73
- // remaining business logic
74
- };
75
- ```
76
-
77
- ### Result - isOk
78
-
79
- Here you can use the isErr TypeGuard to check if the result is a failure, then handle the error by returning an appropriate response. Result is now typesafe, and you can access the value properties directly.
80
-
81
- ```ts
82
- export const main = async function (params: Record<string, unknown>) {
83
- // ... [PREVIOUS CODE]
84
- // Use a the isOk TypeGuard to check if the result is a success
85
- if (isOk(result)) {
86
- // typesafe access to the value properties
87
- const product = result.value;
88
- // product: { id: 'valid', name: 'Sample Product' }
89
- return {
90
- status: 200,
91
- body: product,
92
- };
93
- }
94
- };
95
- ```
96
-
97
- ### Result - isErr
98
-
99
- In another example you can use the isErr TypeGuard to check if the result is a failure, then handle the error by returning an appropriate response. Result is now typesafe, and you can access the error properties directly.
100
-
101
- ```ts
102
- export const main = async function (params: Record<string, unknown>) {
103
- // Further down within the same action you can
104
- // use a the isOk TypeGuard to check if the result is a success
105
- if (isErr(result)) {
106
- // typesafe access to the error properties
107
- const error = result.error;
108
- // error: {
109
- // _tag: "ApiError",
110
- // error: new Error(response.error),
111
- // statusCode: response.statusCode
112
- // }
113
- return {
114
- status: error.statusCode,
115
- body: {
116
- error: `CommerceApiError: ${error.error.message}`,
117
- },
118
- };
119
- }
120
- };
121
- ```
122
-
123
- ## Validation
124
-
125
- The summarize function helps you pretty-print validation errors for easier debugging.
126
-
127
- #### Signature
128
-
129
- - `summarizeValidationError(error: ValidationError): string` - Pretty-prints a validation error.
130
- - `makeValidationError(message: string, issues: [GenericIssue, ...GenericIssue[]]): ValidationError` - Creates a validation error.
131
-
132
- #### Use case
133
-
134
- This prints a readable summary of all validation issues from unknown input data.
135
-
136
- <hr/>
137
-
138
- ```ts
139
- import { summarize } from "@adobe/aio-commerce-lib-core/validation";
140
-
141
- const validationError = makeValidationError("Invalid input", [...issues]);
142
- console.error(summarizeValidationError(validationError));
143
-
144
- // Output:
145
- // Invalid input
146
- // ├── Schema validation error at AIO_COMMERCE_INTEGRATIONS_CONSUMER_KEY → Missing or invalid commerce integration parameter "AIO_COMMERCE_INTEGRATIONS_CONSUMER_KEY"
147
- // ├── Schema validation error at AIO_COMMERCE_INTEGRATIONS_CONSUMER_SECRET → Missing or invalid commerce integration parameter "AIO_COMMERCE_INTEGRATIONS_CONSUMER_SECRET"
148
- // ├── Schema validation error at AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN → Missing or invalid commerce integration parameter "AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN"
149
- // └── Schema validation error at AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN_SECRET → Missing or invalid commerce integration parameter "AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN_SECRET"
150
- ```
16
+ See the [Usage Guide](./docs/usage.md) for more information.
151
17
 
152
18
  ## Contributing
153
19
 
@@ -0,0 +1,98 @@
1
+ /**
2
+ * @license
3
+ *
4
+ * Copyright 2025 Adobe. All rights reserved.
5
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License. You may obtain a copy
7
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
8
+ *
9
+ * Unless required by applicable law or agreed to in writing, software distributed under
10
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
11
+ * OF ANY KIND, either express or implied. See the License for the specific language
12
+ * governing permissions and limitations under the License.
13
+ */
14
+ var __create = Object.create, __defProp = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __getOwnPropNames = Object.getOwnPropertyNames, __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty, __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from == "object" || typeof from == "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) key = keys[i], !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, {
16
+ get: ((k) => from[k]).bind(null, key),
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ return to;
20
+ }, __toESM = (mod, isNodeMode, target) => (target = mod == null ? {} : __create(__getProtoOf(mod)), __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
21
+ value: mod,
22
+ enumerable: !0
23
+ }) : target, mod));
24
+ const util = __toESM(require("util")), ansis = __toESM(require("ansis")), valibot = __toESM(require("valibot"));
25
+ var CommerceSdkErrorBase = class CommerceSdkErrorBase extends Error {
26
+ traceId;
27
+ constructor(message, options) {
28
+ let { traceId,...baseOptions } = options ?? {};
29
+ super(message, baseOptions), Object.setPrototypeOf(this, new.target.prototype), Error.captureStackTrace && Error.captureStackTrace(this, new.target), this.name = new.target.name || "CommerceSdkError", this.traceId = traceId;
30
+ }
31
+ static isSdkError(error) {
32
+ return error instanceof CommerceSdkErrorBase;
33
+ }
34
+ get fullStack() {
35
+ let out = this.stack ?? "", cause = this.cause;
36
+ for (; cause instanceof Error;) out += `\nCaused by: ${cause.stack ?? cause.message}`, cause = cause.cause;
37
+ return out;
38
+ }
39
+ get rootCause() {
40
+ let cause = this.cause;
41
+ for (; cause && typeof cause == "object" && cause && "cause" in cause;) cause = cause.cause;
42
+ return cause;
43
+ }
44
+ toJSON() {
45
+ return {
46
+ name: this.name,
47
+ message: this.message,
48
+ stack: this.fullStack,
49
+ cause: this.cause,
50
+ traceId: this.traceId
51
+ };
52
+ }
53
+ toString(inspect = !0) {
54
+ return inspect ? util.default.inspect(this, {
55
+ depth: null,
56
+ colors: !0,
57
+ sorted: !0,
58
+ maxStringLength: Infinity
59
+ }) : super.toString();
60
+ }
61
+ };
62
+ const LAST_RETURN_CHAR = "└── ", RETURN_CHAR = "├── ", ISSUE_KIND_TO_ERROR_TITLE = {
63
+ schema: "Schema validation error",
64
+ transformation: "Transformation error",
65
+ validation: "Input error"
66
+ };
67
+ function getReturnChar(isLastItem, withColor) {
68
+ let char = isLastItem ? LAST_RETURN_CHAR : RETURN_CHAR;
69
+ return withColor ? (0, ansis.cyanBright)(char) : char;
70
+ }
71
+ function getKindText(kind, withColor) {
72
+ let text = ISSUE_KIND_TO_ERROR_TITLE[kind] ?? "Unknown issue kind";
73
+ return withColor ? (0, ansis.yellowBright)(text) : text;
74
+ }
75
+ function getPathText(dotPath, withColor) {
76
+ return dotPath ? withColor ? `${(0, ansis.cyanBright)(dotPath)}${(0, ansis.whiteBright)((0, ansis.dim)(" →"))}` : `${dotPath} →` : "";
77
+ }
78
+ function issueToDisplay(issues, withColor = !0) {
79
+ let lines = issues?.map((issue, index) => {
80
+ let returnChar = getReturnChar(index === issues.length - 1, withColor), kindText = getKindText(issue.kind, withColor), path = getPathText((0, valibot.getDotPath)(issue), withColor), message = withColor ? (0, ansis.whiteBright)(issue.message) : issue.message, at = withColor ? (0, ansis.whiteBright)("at") : "at", issueLine = `${kindText} ${at} ${path} ${message}`;
81
+ return `${returnChar} ${issueLine}`;
82
+ });
83
+ return lines?.join("\n") ?? "";
84
+ }
85
+ function displayValidationError(error, withColor = !0) {
86
+ let display = issueToDisplay(error.issues, withColor), message = withColor ? (0, ansis.whiteBright)(error.message) : error.message;
87
+ return `${message}\n${display}`;
88
+ }
89
+ var CommerceSdkValidationError = class extends CommerceSdkErrorBase {
90
+ issues;
91
+ constructor(message, { issues,...options }) {
92
+ super(message, options), this.issues = issues;
93
+ }
94
+ display(withColor = !0) {
95
+ return displayValidationError(this, withColor);
96
+ }
97
+ };
98
+ exports.CommerceSdkErrorBase = CommerceSdkErrorBase, exports.CommerceSdkValidationError = CommerceSdkValidationError;
@@ -0,0 +1,133 @@
1
+ /**
2
+ * @license
3
+ *
4
+ * Copyright 2025 Adobe. All rights reserved.
5
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License. You may obtain a copy
7
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
8
+ *
9
+ * Unless required by applicable law or agreed to in writing, software distributed under
10
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
11
+ * OF ANY KIND, either express or implied. See the License for the specific language
12
+ * governing permissions and limitations under the License.
13
+ */
14
+
15
+ import { GenericIssue } from "valibot";
16
+
17
+ //#region source/error/base-error.d.ts
18
+ /** Defines the base options for {@link CommerceSdkErrorBase}. */
19
+ type CommerceSdkErrorBaseOptions = ErrorOptions & {
20
+ traceId?: string;
21
+ };
22
+ /**
23
+ * Helper type to define custom error options.
24
+ * @example
25
+ * ```ts
26
+ * type ValidationErrorOptions = CommerceSdkErrorOptions<{
27
+ * field: string;
28
+ * value: unknown;
29
+ * }>;
30
+ * ```
31
+ */
32
+ type CommerceSdkErrorOptions<T extends Record<string, unknown> = Record<string, unknown>> = CommerceSdkErrorBaseOptions & T;
33
+ /**
34
+ * Base class for all the errors in the AIO Commerce SDK.
35
+ * @example
36
+ * ```ts
37
+ * class ValidationError extends CommerceSdkErrorBase {
38
+ * constructor(message: string, options: ValidationErrorOptions) {
39
+ * super(message, options);
40
+ * }
41
+ * }
42
+ *
43
+ * const err = new ValidationError("Invalid value", {
44
+ * tag: "ValidationError",
45
+ * field: "name",
46
+ * value: "John Doe",
47
+ * });
48
+ *
49
+ * console.log(err.toJSON());
50
+ * ```
51
+ */
52
+ declare abstract class CommerceSdkErrorBase extends Error {
53
+ readonly traceId?: string;
54
+ /**
55
+ * Constructs a new CommerceSdkErrorBase instance. This is an abstract class so you
56
+ * should not instantiate it directly. Only invoke this constructor from a subclass.
57
+ *
58
+ * @param message - A human-friendly description of the error.
59
+ * @param options - Optional error options (additional information).
60
+ */
61
+ constructor(message: string, options?: CommerceSdkErrorBaseOptions);
62
+ /**
63
+ * Checks if the error is any CommerceSdkErrorBase instance.
64
+ * @example
65
+ * ```ts
66
+ * class ValidationError extends CommerceSdkErrorBase {}
67
+ * const err = new ValidationError("Invalid", {});
68
+ *
69
+ * CommerceSdkErrorBase.isSdkError(err); // true
70
+ * ValidationError.isSdkError(err); // true
71
+ * CommerceSdkErrorBase.isSdkError(new Error("Regular")); // false
72
+ * ```
73
+ */
74
+ static isSdkError(error: unknown): error is CommerceSdkErrorBase;
75
+ /** Returns the full stack trace of the error and its causes. */
76
+ get fullStack(): string;
77
+ /** Returns the root cause of the error. */
78
+ get rootCause(): unknown;
79
+ /** Converts the error to a JSON-like representation. */
80
+ toJSON(): {
81
+ name: string;
82
+ message: string;
83
+ stack: string;
84
+ cause: unknown;
85
+ traceId: string | undefined;
86
+ };
87
+ /**
88
+ * Returns a pretty string representation of the error.
89
+ * @param inspect - Whether to inspect the error (returns a more detailed string, useful for debugging).
90
+ */
91
+ toString(inspect?: boolean): string;
92
+ }
93
+ //#endregion
94
+ //#region source/error/validation-error.d.ts
95
+ /** Defines the base options for {@link CommerceSdkValidationError}. */
96
+ type CommerceSdkValidationErrorOptions = CommerceSdkErrorOptions<{
97
+ issues: GenericIssue[];
98
+ }>;
99
+ /**
100
+ * Represents a validation error in the Commerce SDK.
101
+ * This error should be thrown when an input does not conform to the expected schema.
102
+ * It contains a list of issues that describe the validation errors.
103
+ *
104
+ * @example
105
+ * ```ts
106
+ * const error = new CommerceSdkValidationError("Invalid input", {
107
+ * // `someIssues` is in scope, returned by some `valibot` operation.
108
+ * issues: someIssues
109
+ * });
110
+ *
111
+ * console.log(error.display());
112
+ * ```
113
+ */
114
+ declare class CommerceSdkValidationError extends CommerceSdkErrorBase {
115
+ readonly issues: GenericIssue[];
116
+ /**
117
+ * Constructs a new {@link CommerceSdkValidationError} instance.
118
+ *
119
+ * @param message - A human-friendly description of the validation error.
120
+ * @param options - Options for the validation error, including the issues that caused the error.
121
+ */
122
+ constructor(message: string, {
123
+ issues,
124
+ ...options
125
+ }: CommerceSdkValidationErrorOptions);
126
+ /**
127
+ * Returns a pretty string (and colored) representation of the validation error.
128
+ * @param withColor Whether to use color in the output.
129
+ */
130
+ display(withColor?: boolean): string;
131
+ }
132
+ //#endregion
133
+ export { CommerceSdkErrorBase, CommerceSdkValidationError };
@@ -1,15 +1,13 @@
1
- const require_result = require('./result-fxmTDycS.cjs');
2
- const require_validation = require('./validation-12iMy71C.cjs');
3
-
4
- Object.defineProperty(exports, 'Result', {
5
- enumerable: true,
6
- get: function () {
7
- return require_result.result_exports;
8
- }
9
- });
10
- Object.defineProperty(exports, 'Validation', {
11
- enumerable: true,
12
- get: function () {
13
- return require_validation.validation_exports;
14
- }
15
- });
1
+ /**
2
+ * @license
3
+ *
4
+ * Copyright 2025 Adobe. All rights reserved.
5
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License. You may obtain a copy
7
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
8
+ *
9
+ * Unless required by applicable law or agreed to in writing, software distributed under
10
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
11
+ * OF ANY KIND, either express or implied. See the License for the specific language
12
+ * governing permissions and limitations under the License.
13
+ */
@@ -1,3 +1 @@
1
- import { result_d_exports } from "./result-B_qN_g1r.cjs";
2
- import { validation_d_exports } from "./validation-BonM9W9Z.cjs";
3
- export { result_d_exports as Result, validation_d_exports as Validation };
1
+ export { };
@@ -0,0 +1,133 @@
1
+ /**
2
+ * @license
3
+ *
4
+ * Copyright 2025 Adobe. All rights reserved.
5
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License. You may obtain a copy
7
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
8
+ *
9
+ * Unless required by applicable law or agreed to in writing, software distributed under
10
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
11
+ * OF ANY KIND, either express or implied. See the License for the specific language
12
+ * governing permissions and limitations under the License.
13
+ */
14
+
15
+ import { GenericIssue } from "valibot";
16
+
17
+ //#region source/error/base-error.d.ts
18
+ /** Defines the base options for {@link CommerceSdkErrorBase}. */
19
+ type CommerceSdkErrorBaseOptions = ErrorOptions & {
20
+ traceId?: string;
21
+ };
22
+ /**
23
+ * Helper type to define custom error options.
24
+ * @example
25
+ * ```ts
26
+ * type ValidationErrorOptions = CommerceSdkErrorOptions<{
27
+ * field: string;
28
+ * value: unknown;
29
+ * }>;
30
+ * ```
31
+ */
32
+ type CommerceSdkErrorOptions<T extends Record<string, unknown> = Record<string, unknown>> = CommerceSdkErrorBaseOptions & T;
33
+ /**
34
+ * Base class for all the errors in the AIO Commerce SDK.
35
+ * @example
36
+ * ```ts
37
+ * class ValidationError extends CommerceSdkErrorBase {
38
+ * constructor(message: string, options: ValidationErrorOptions) {
39
+ * super(message, options);
40
+ * }
41
+ * }
42
+ *
43
+ * const err = new ValidationError("Invalid value", {
44
+ * tag: "ValidationError",
45
+ * field: "name",
46
+ * value: "John Doe",
47
+ * });
48
+ *
49
+ * console.log(err.toJSON());
50
+ * ```
51
+ */
52
+ declare abstract class CommerceSdkErrorBase extends Error {
53
+ readonly traceId?: string;
54
+ /**
55
+ * Constructs a new CommerceSdkErrorBase instance. This is an abstract class so you
56
+ * should not instantiate it directly. Only invoke this constructor from a subclass.
57
+ *
58
+ * @param message - A human-friendly description of the error.
59
+ * @param options - Optional error options (additional information).
60
+ */
61
+ constructor(message: string, options?: CommerceSdkErrorBaseOptions);
62
+ /**
63
+ * Checks if the error is any CommerceSdkErrorBase instance.
64
+ * @example
65
+ * ```ts
66
+ * class ValidationError extends CommerceSdkErrorBase {}
67
+ * const err = new ValidationError("Invalid", {});
68
+ *
69
+ * CommerceSdkErrorBase.isSdkError(err); // true
70
+ * ValidationError.isSdkError(err); // true
71
+ * CommerceSdkErrorBase.isSdkError(new Error("Regular")); // false
72
+ * ```
73
+ */
74
+ static isSdkError(error: unknown): error is CommerceSdkErrorBase;
75
+ /** Returns the full stack trace of the error and its causes. */
76
+ get fullStack(): string;
77
+ /** Returns the root cause of the error. */
78
+ get rootCause(): unknown;
79
+ /** Converts the error to a JSON-like representation. */
80
+ toJSON(): {
81
+ name: string;
82
+ message: string;
83
+ stack: string;
84
+ cause: unknown;
85
+ traceId: string | undefined;
86
+ };
87
+ /**
88
+ * Returns a pretty string representation of the error.
89
+ * @param inspect - Whether to inspect the error (returns a more detailed string, useful for debugging).
90
+ */
91
+ toString(inspect?: boolean): string;
92
+ }
93
+ //#endregion
94
+ //#region source/error/validation-error.d.ts
95
+ /** Defines the base options for {@link CommerceSdkValidationError}. */
96
+ type CommerceSdkValidationErrorOptions = CommerceSdkErrorOptions<{
97
+ issues: GenericIssue[];
98
+ }>;
99
+ /**
100
+ * Represents a validation error in the Commerce SDK.
101
+ * This error should be thrown when an input does not conform to the expected schema.
102
+ * It contains a list of issues that describe the validation errors.
103
+ *
104
+ * @example
105
+ * ```ts
106
+ * const error = new CommerceSdkValidationError("Invalid input", {
107
+ * // `someIssues` is in scope, returned by some `valibot` operation.
108
+ * issues: someIssues
109
+ * });
110
+ *
111
+ * console.log(error.display());
112
+ * ```
113
+ */
114
+ declare class CommerceSdkValidationError extends CommerceSdkErrorBase {
115
+ readonly issues: GenericIssue[];
116
+ /**
117
+ * Constructs a new {@link CommerceSdkValidationError} instance.
118
+ *
119
+ * @param message - A human-friendly description of the validation error.
120
+ * @param options - Options for the validation error, including the issues that caused the error.
121
+ */
122
+ constructor(message: string, {
123
+ issues,
124
+ ...options
125
+ }: CommerceSdkValidationErrorOptions);
126
+ /**
127
+ * Returns a pretty string (and colored) representation of the validation error.
128
+ * @param withColor Whether to use color in the output.
129
+ */
130
+ display(withColor?: boolean): string;
131
+ }
132
+ //#endregion
133
+ export { CommerceSdkErrorBase, CommerceSdkValidationError };
@@ -0,0 +1,90 @@
1
+ /**
2
+ * @license
3
+ *
4
+ * Copyright 2025 Adobe. All rights reserved.
5
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License. You may obtain a copy
7
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
8
+ *
9
+ * Unless required by applicable law or agreed to in writing, software distributed under
10
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
11
+ * OF ANY KIND, either express or implied. See the License for the specific language
12
+ * governing permissions and limitations under the License.
13
+ */
14
+ import util from "util";
15
+ import { cyanBright, dim, whiteBright, yellowBright } from "ansis";
16
+ import { getDotPath } from "valibot";
17
+ var CommerceSdkErrorBase = class CommerceSdkErrorBase extends Error {
18
+ traceId;
19
+ constructor(message, options) {
20
+ let { traceId,...baseOptions } = options ?? {};
21
+ super(message, baseOptions), Object.setPrototypeOf(this, new.target.prototype), Error.captureStackTrace && Error.captureStackTrace(this, new.target), this.name = new.target.name || "CommerceSdkError", this.traceId = traceId;
22
+ }
23
+ static isSdkError(error) {
24
+ return error instanceof CommerceSdkErrorBase;
25
+ }
26
+ get fullStack() {
27
+ let out = this.stack ?? "", cause = this.cause;
28
+ for (; cause instanceof Error;) out += `\nCaused by: ${cause.stack ?? cause.message}`, cause = cause.cause;
29
+ return out;
30
+ }
31
+ get rootCause() {
32
+ let cause = this.cause;
33
+ for (; cause && typeof cause == "object" && cause && "cause" in cause;) cause = cause.cause;
34
+ return cause;
35
+ }
36
+ toJSON() {
37
+ return {
38
+ name: this.name,
39
+ message: this.message,
40
+ stack: this.fullStack,
41
+ cause: this.cause,
42
+ traceId: this.traceId
43
+ };
44
+ }
45
+ toString(inspect = !0) {
46
+ return inspect ? util.inspect(this, {
47
+ depth: null,
48
+ colors: !0,
49
+ sorted: !0,
50
+ maxStringLength: Infinity
51
+ }) : super.toString();
52
+ }
53
+ };
54
+ const LAST_RETURN_CHAR = "└── ", RETURN_CHAR = "├── ", ISSUE_KIND_TO_ERROR_TITLE = {
55
+ schema: "Schema validation error",
56
+ transformation: "Transformation error",
57
+ validation: "Input error"
58
+ };
59
+ function getReturnChar(isLastItem, withColor) {
60
+ let char = isLastItem ? LAST_RETURN_CHAR : RETURN_CHAR;
61
+ return withColor ? cyanBright(char) : char;
62
+ }
63
+ function getKindText(kind, withColor) {
64
+ let text = ISSUE_KIND_TO_ERROR_TITLE[kind] ?? "Unknown issue kind";
65
+ return withColor ? yellowBright(text) : text;
66
+ }
67
+ function getPathText(dotPath, withColor) {
68
+ return dotPath ? withColor ? `${cyanBright(dotPath)}${whiteBright(dim(" →"))}` : `${dotPath} →` : "";
69
+ }
70
+ function issueToDisplay(issues, withColor = !0) {
71
+ let lines = issues?.map((issue, index) => {
72
+ let returnChar = getReturnChar(index === issues.length - 1, withColor), kindText = getKindText(issue.kind, withColor), path = getPathText(getDotPath(issue), withColor), message = withColor ? whiteBright(issue.message) : issue.message, at = withColor ? whiteBright("at") : "at", issueLine = `${kindText} ${at} ${path} ${message}`;
73
+ return `${returnChar} ${issueLine}`;
74
+ });
75
+ return lines?.join("\n") ?? "";
76
+ }
77
+ function displayValidationError(error, withColor = !0) {
78
+ let display = issueToDisplay(error.issues, withColor), message = withColor ? whiteBright(error.message) : error.message;
79
+ return `${message}\n${display}`;
80
+ }
81
+ var CommerceSdkValidationError = class extends CommerceSdkErrorBase {
82
+ issues;
83
+ constructor(message, { issues,...options }) {
84
+ super(message, options), this.issues = issues;
85
+ }
86
+ display(withColor = !0) {
87
+ return displayValidationError(this, withColor);
88
+ }
89
+ };
90
+ export { CommerceSdkErrorBase, CommerceSdkValidationError };
@@ -1,3 +1 @@
1
- import { result_d_exports } from "./result-BooxElIJ.js";
2
- import { validation_d_exports } from "./validation-B2JQpDTl.js";
3
- export { result_d_exports as Result, validation_d_exports as Validation };
1
+ export { };