@adobe/aio-commerce-lib-core 0.4.1 → 0.5.1

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,21 @@
1
1
  # @adobe/aio-commerce-lib-core
2
2
 
3
+ ## 0.5.1
4
+
5
+ ### Patch Changes
6
+
7
+ - [#143](https://github.com/adobe/aio-commerce-sdk/pull/143) [`f05b041`](https://github.com/adobe/aio-commerce-sdk/commit/f05b0413b06a4dea5579a1b16c293aaf8b64ffac) Thanks [@iivvaannxx](https://github.com/iivvaannxx)! - Add a new success response preset for HTTP 203 status code: `nonAuthoritativeInformation`
8
+
9
+ ## 0.5.0
10
+
11
+ ### Minor Changes
12
+
13
+ - [#116](https://github.com/adobe/aio-commerce-sdk/pull/116) [`176bd0f`](https://github.com/adobe/aio-commerce-sdk/commit/176bd0f793de8dbd11b1704a82dd722158f48e81) Thanks [@iivvaannxx](https://github.com/iivvaannxx)! - Add new `params` entrypoint for utilities related to runtime action params
14
+
15
+ - [#116](https://github.com/adobe/aio-commerce-sdk/pull/116) [`176bd0f`](https://github.com/adobe/aio-commerce-sdk/commit/176bd0f793de8dbd11b1704a82dd722158f48e81) Thanks [@iivvaannxx](https://github.com/iivvaannxx)! - Add new `responses` entrypoint for utilities related to runtime action responses
16
+
17
+ - [#122](https://github.com/adobe/aio-commerce-sdk/pull/122) [`493da95`](https://github.com/adobe/aio-commerce-sdk/commit/493da9595c06de304ecddbbc8295db124cb6fcba) Thanks [@obarcelonap](https://github.com/obarcelonap)! - Add new `./responses` export path providing response builder utilities (`buildErrorResponse`, `buildSuccessResponse`), response presets, and related types
18
+
3
19
  ## 0.4.1
4
20
 
5
21
  ### Patch Changes
package/README.md CHANGED
@@ -17,4 +17,4 @@ See the [Usage Guide](./docs/usage.md) for more information.
17
17
 
18
18
  ## Contributing
19
19
 
20
- This package is part of the Adobe Commerce SDK monorepo. See the [Contributing Guide](https://github.com/adobe/aio-commerce-sdk/blob/main/.github/CONTRIBUTING.md) and [Development Guide](https://github.com/adobe/aio-commerce-sdk/blob/main/.github/DEVELOPMENT.md) for development setup and guidelines.
20
+ This package is part of the Adobe Commerce SDK monorepo. Refer to the [Contributing Guide](https://github.com/adobe/aio-commerce-sdk/blob/main/.github/CONTRIBUTING.md) and [Development Guide](https://github.com/adobe/aio-commerce-sdk/blob/main/.github/DEVELOPMENT.md) for information on development setup and guidelines.
@@ -11,88 +11,5 @@
11
11
  * OF ANY KIND, either express or implied. See the License for the specific language
12
12
  * governing permissions and limitations under the License.
13
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;
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)=>{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,{get:(k=>from[k]).bind(null,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM=(mod,isNodeMode,target)=>(target=mod==null?{}:__create(__getProtoOf(mod)),__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,`default`,{value:mod,enumerable:!0}):target,mod));let util=require(`util`);util=__toESM(util);let ansis=require(`ansis`);ansis=__toESM(ansis);let valibot=require(`valibot`);valibot=__toESM(valibot);var CommerceSdkErrorBase=class CommerceSdkErrorBase extends Error{constructor(message,options){let{traceId,...baseOptions}=options??{};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}static isSdkError(error){return error instanceof CommerceSdkErrorBase}get fullStack(){let out=this.stack??``,cause=this.cause;for(;cause instanceof Error;)out+=`\nCaused by: ${cause.stack??cause.message}`,cause=cause.cause;return out}get rootCause(){let cause=this.cause;for(;cause&&typeof cause==`object`&&cause&&`cause`in cause;)cause=cause.cause;return cause}toJSON(){return{name:this.name,message:this.message,stack:this.fullStack,cause:this.cause,traceId:this.traceId}}toString(inspect=!0){return inspect?util.default.inspect(this,{depth:null,colors:!0,sorted:!0,maxStringLength:1/0}):super.toString()}};const LAST_RETURN_CHAR=`└── `,RETURN_CHAR=`├── `,ISSUE_KIND_TO_ERROR_TITLE={schema:`Schema validation error`,transformation:`Transformation error`,validation:`Input error`};function getReturnChar(isLastItem,withColor){let char=isLastItem?`└── `:`├── `;return withColor?(0,ansis.cyanBright)(char):char}function getKindText(kind,withColor){let text=ISSUE_KIND_TO_ERROR_TITLE[kind]??`Unknown issue kind`;return withColor?(0,ansis.yellowBright)(text):text}function getPathText(dotPath,withColor){return dotPath?withColor?`${(0,ansis.cyanBright)(dotPath)}${(0,ansis.whiteBright)((0,ansis.dim)(` →`))}`:`${dotPath} →`:``}function issueToDisplay(issues,withColor=!0){return(issues?.map((issue,index)=>{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;return`${returnChar} ${`${kindText} ${withColor?(0,ansis.whiteBright)(`at`):`at`} ${path} ${message}`}`}))?.join(`
15
+ `)??``}function displayValidationError(error,withColor=!0){let display=issueToDisplay(error.issues,withColor);return`${withColor?(0,ansis.whiteBright)(error.message):error.message}\n${display}`}var CommerceSdkValidationError=class extends CommerceSdkErrorBase{constructor(message,{issues,...options}){super(message,options),this.issues=issues}display(withColor=!0){return displayValidationError(this,withColor)}};exports.CommerceSdkErrorBase=CommerceSdkErrorBase,exports.CommerceSdkValidationError=CommerceSdkValidationError;
@@ -11,3 +11,4 @@
11
11
  * OF ANY KIND, either express or implied. See the License for the specific language
12
12
  * governing permissions and limitations under the License.
13
13
  */
14
+ function nonEmpty(name,value){if(value==null)return!1;let v=String(value)?.trim();return!!v&&v!==`$${name}`}function allNonEmpty(params,required){return required.every(name=>nonEmpty(name,params[name]))}exports.allNonEmpty=allNonEmpty,exports.nonEmpty=nonEmpty;
@@ -0,0 +1,17 @@
1
+ //#region source/params/helpers.d.ts
2
+ /**
3
+ * Checks if the given runtime action input value is non-empty.
4
+ *
5
+ * @param name - The name of the parameter. Required because of `aio app dev` compatibility: inputs mapped to undefined env vars come as $<input_name> in dev mode, but as '' in prod mode.
6
+ * @param value - The value of the parameter.
7
+ */
8
+ declare function nonEmpty(name: string, value: unknown): boolean;
9
+ /**
10
+ * Checks if all required parameters are non-empty.
11
+ *
12
+ * @param params - The action input parameters.
13
+ * @param required - The list of required parameter names.
14
+ */
15
+ declare function allNonEmpty<const T extends string[]>(params: Record<string, unknown>, required: T): params is Record<string, unknown> & Record<T[number], unknown>;
16
+ //#endregion
17
+ export { allNonEmpty, nonEmpty };
@@ -0,0 +1,14 @@
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
+ function buildErrorResponse(statusCode,payload){return{type:`error`,error:{...payload?.headers&&{headers:payload.headers},statusCode,body:payload.body}}}function buildSuccessResponse(statusCode,payload){return{type:`success`,statusCode,...payload?.headers&&{headers:payload.headers},...payload?.body&&{body:payload.body}}}const HTTP_OK=200,HTTP_CREATED=201,HTTP_NON_AUTHORITATIVE_INFORMATION=203,HTTP_BAD_REQUEST=400,HTTP_UNAUTHORIZED=401,HTTP_FORBIDDEN=403,HTTP_NOT_FOUND=404,HTTP_INTERNAL_SERVER_ERROR=500;function curryBuildSuccessResponse(code){return payload=>buildSuccessResponse(code,typeof payload==`string`?{body:{message:payload}}:payload)}function curryBuildErrorResponse(code){return payload=>buildErrorResponse(code,typeof payload==`string`?{body:{message:payload}}:payload)}const ok=curryBuildSuccessResponse(200),created=curryBuildSuccessResponse(201),nonAuthoritativeInformation=curryBuildSuccessResponse(203),badRequest=curryBuildErrorResponse(400),unauthorized=curryBuildErrorResponse(401),forbidden=curryBuildErrorResponse(403),notFound=curryBuildErrorResponse(404),internalServerError=curryBuildErrorResponse(500);exports.HTTP_BAD_REQUEST=400,exports.HTTP_CREATED=201,exports.HTTP_FORBIDDEN=403,exports.HTTP_INTERNAL_SERVER_ERROR=500,exports.HTTP_NON_AUTHORITATIVE_INFORMATION=203,exports.HTTP_NOT_FOUND=404,exports.HTTP_OK=200,exports.HTTP_UNAUTHORIZED=401,exports.badRequest=badRequest,exports.buildErrorResponse=buildErrorResponse,exports.buildSuccessResponse=buildSuccessResponse,exports.created=created,exports.forbidden=forbidden,exports.internalServerError=internalServerError,exports.nonAuthoritativeInformation=nonAuthoritativeInformation,exports.notFound=notFound,exports.ok=ok,exports.unauthorized=unauthorized;
@@ -0,0 +1,188 @@
1
+ //#region source/responses/helpers.d.ts
2
+ type HeadersRecord = Record<string, string>;
3
+ type BodyRecord = Record<string, unknown>;
4
+ type BodyRecordWithMessage = BodyRecord & {
5
+ message: string;
6
+ };
7
+ /**
8
+ * Common payload structure for runtime action responses
9
+ * @template TBody - Response body properties
10
+ * @template THeaders - Custom response headers
11
+ */
12
+ type ResponsePayload<TBody extends BodyRecord = BodyRecord, THeaders extends HeadersRecord = HeadersRecord> = {
13
+ statusCode: number;
14
+ body?: TBody;
15
+ headers?: THeaders;
16
+ };
17
+ /**
18
+ * Represents an error response from a runtime action
19
+ * @template TBody - Additional error body properties beyond the required message field
20
+ * @template THeaders - Custom response headers
21
+ */
22
+ type ErrorResponse<TBody extends BodyRecordWithMessage = BodyRecordWithMessage, THeaders extends HeadersRecord = HeadersRecord> = {
23
+ type: "error";
24
+ error: ResponsePayload<TBody, THeaders>;
25
+ };
26
+ /**
27
+ * Represents a successful response from a runtime action
28
+ * @template TBody - Response body properties
29
+ * @template THeaders - Custom response headers
30
+ */
31
+ type SuccessResponse<TBody extends BodyRecord = BodyRecord, THeaders extends HeadersRecord = HeadersRecord> = ResponsePayload<TBody, THeaders> & {
32
+ type: "success";
33
+ };
34
+ /**
35
+ * Union type representing either a successful or error response from a runtime action
36
+ * @template TBody - Response/error body properties
37
+ * @template THeaders - Custom response headers
38
+ */
39
+ type ActionResponse<TBody extends BodyRecordWithMessage = BodyRecordWithMessage, THeaders extends HeadersRecord = HeadersRecord> = SuccessResponse<TBody, THeaders> | ErrorResponse<TBody, THeaders>;
40
+ /**
41
+ * Creates a standardized error response for runtime actions
42
+ * @see https://developer.adobe.com/app-builder/docs/guides/runtime_guides/creating-actions#unsuccessful-response
43
+ *
44
+ * @template TBody - Additional error body properties beyond the required message field
45
+ * @template THeaders - Custom response headers
46
+ *
47
+ * @param statusCode - HTTP status code (e.g., 400, 404, 500)
48
+ * @param payload - Error response configuration
49
+ * @param payload.message - Human-readable error message (required)
50
+ * @param payload.body - Optional additional error details to include in the response body
51
+ * @param payload.headers - Optional custom response headers
52
+ *
53
+ * @returns Standardized error response object with type discriminator
54
+ *
55
+ * @example
56
+ * ```typescript
57
+ * // Simple error with just a message
58
+ * const error = buildErrorResponse(404, {
59
+ * message: 'Resource not found'
60
+ * });
61
+ *
62
+ * // Error with additional body data
63
+ * const error = buildErrorResponse(400, {
64
+ * message: 'Invalid request',
65
+ * body: { field: 'email', code: 'INVALID_FORMAT' }
66
+ * });
67
+ *
68
+ * // Error with custom headers
69
+ * const error = buildErrorResponse(429, {
70
+ * message: 'Rate limit exceeded',
71
+ * headers: { 'Retry-After': '60' }
72
+ * });
73
+ * ```
74
+ */
75
+ declare function buildErrorResponse<TBody extends BodyRecordWithMessage = BodyRecordWithMessage, THeaders extends HeadersRecord = HeadersRecord>(statusCode: number, payload: {
76
+ body: TBody;
77
+ headers?: THeaders;
78
+ }): ErrorResponse<TBody, THeaders>;
79
+ /**
80
+ * Creates a standardized success response for runtime actions
81
+ * @see https://developer.adobe.com/app-builder/docs/guides/runtime_guides/creating-actions#successful-response
82
+ *
83
+ * @template TBody - Response body properties
84
+ * @template THeaders - Custom response headers
85
+ *
86
+ * @param statusCode - HTTP status code (typically 200, 201, 204, etc.)
87
+ * @param payload - Success response configuration
88
+ * @param payload.message - Human-readable success message (required)
89
+ * @param payload.body - Optional additional response data to include in the response body
90
+ * @param payload.headers - Optional custom response headers
91
+ *
92
+ * @returns Standardized success response object with type discriminator
93
+ *
94
+ * @example
95
+ * ```typescript
96
+ * // Simple success response
97
+ * const response = buildSuccessResponse(200, {
98
+ * message: 'Operation successful'
99
+ * });
100
+ *
101
+ * // Success with additional body data
102
+ * const response = buildSuccessResponse(201, {
103
+ * message: 'Resource created',
104
+ * body: { id: '456', created: true },
105
+ * headers: { 'Location': '/api/resources/456' }
106
+ * });
107
+ * ```
108
+ */
109
+ declare function buildSuccessResponse<TBody extends BodyRecord = BodyRecord, THeaders extends HeadersRecord = HeadersRecord>(statusCode: number, payload?: {
110
+ body?: TBody;
111
+ headers?: THeaders;
112
+ }): SuccessResponse<TBody, THeaders>;
113
+ //#endregion
114
+ //#region source/responses/presets.d.ts
115
+ declare const HTTP_OK = 200;
116
+ declare const HTTP_CREATED = 201;
117
+ declare const HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
118
+ declare const HTTP_BAD_REQUEST = 400;
119
+ declare const HTTP_UNAUTHORIZED = 401;
120
+ declare const HTTP_FORBIDDEN = 403;
121
+ declare const HTTP_NOT_FOUND = 404;
122
+ declare const HTTP_INTERNAL_SERVER_ERROR = 500;
123
+ /**
124
+ * Creates a success response with the HTTP status code 200.
125
+ * See {@link buildSuccessResponse} for details on the response payload.
126
+ */
127
+ declare const ok: (payload?: string | {
128
+ body?: BodyRecord;
129
+ headers?: HeadersRecord;
130
+ }) => SuccessResponse<BodyRecord, HeadersRecord>;
131
+ /**
132
+ * Creates a success response with the HTTP status code 201.
133
+ * See {@link buildSuccessResponse} for details on the response payload.
134
+ */
135
+ declare const created: (payload?: string | {
136
+ body?: BodyRecord;
137
+ headers?: HeadersRecord;
138
+ }) => SuccessResponse<BodyRecord, HeadersRecord>;
139
+ /**
140
+ * Creates a success response with the HTTP status code 203.
141
+ * See {@link buildSuccessResponse} for details on the response payload.
142
+ */
143
+ declare const nonAuthoritativeInformation: (payload?: string | {
144
+ body?: BodyRecord;
145
+ headers?: HeadersRecord;
146
+ }) => SuccessResponse<BodyRecord, HeadersRecord>;
147
+ /**
148
+ * Creates an error response with the HTTP status code 400.
149
+ * See {@link buildErrorResponse} for details on the response payload.
150
+ */
151
+ declare const badRequest: (payload: string | {
152
+ body: BodyRecordWithMessage;
153
+ headers?: HeadersRecord;
154
+ }) => ErrorResponse<BodyRecordWithMessage, HeadersRecord>;
155
+ /**
156
+ * Creates an error response with the HTTP status code 401.
157
+ * See {@link buildErrorResponse} for details on the response payload.
158
+ */
159
+ declare const unauthorized: (payload: string | {
160
+ body: BodyRecordWithMessage;
161
+ headers?: HeadersRecord;
162
+ }) => ErrorResponse<BodyRecordWithMessage, HeadersRecord>;
163
+ /**
164
+ * Creates an error response with the HTTP status code 403.
165
+ * See {@link buildErrorResponse} for details on the response payload.
166
+ */
167
+ declare const forbidden: (payload: string | {
168
+ body: BodyRecordWithMessage;
169
+ headers?: HeadersRecord;
170
+ }) => ErrorResponse<BodyRecordWithMessage, HeadersRecord>;
171
+ /**
172
+ * Creates an error response with the HTTP status code 404.
173
+ * See {@link buildErrorResponse} for details on the response payload.
174
+ */
175
+ declare const notFound: (payload: string | {
176
+ body: BodyRecordWithMessage;
177
+ headers?: HeadersRecord;
178
+ }) => ErrorResponse<BodyRecordWithMessage, HeadersRecord>;
179
+ /**
180
+ * Creates an error response with the HTTP status code 500.
181
+ * See {@link buildErrorResponse} for details on the response payload.
182
+ */
183
+ declare const internalServerError: (payload: string | {
184
+ body: BodyRecordWithMessage;
185
+ headers?: HeadersRecord;
186
+ }) => ErrorResponse<BodyRecordWithMessage, HeadersRecord>;
187
+ //#endregion
188
+ export { type ActionResponse, type ErrorResponse, HTTP_BAD_REQUEST, HTTP_CREATED, HTTP_FORBIDDEN, HTTP_INTERNAL_SERVER_ERROR, HTTP_NON_AUTHORITATIVE_INFORMATION, HTTP_NOT_FOUND, HTTP_OK, HTTP_UNAUTHORIZED, type SuccessResponse, badRequest, buildErrorResponse, buildSuccessResponse, created, forbidden, internalServerError, nonAuthoritativeInformation, notFound, ok, unauthorized };
@@ -11,80 +11,5 @@
11
11
  * OF ANY KIND, either express or implied. See the License for the specific language
12
12
  * governing permissions and limitations under the License.
13
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 };
14
+ import util from"util";import{cyanBright,dim,whiteBright,yellowBright}from"ansis";import{getDotPath}from"valibot";var CommerceSdkErrorBase=class CommerceSdkErrorBase extends Error{constructor(message,options){let{traceId,...baseOptions}=options??{};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}static isSdkError(error){return error instanceof CommerceSdkErrorBase}get fullStack(){let out=this.stack??``,cause=this.cause;for(;cause instanceof Error;)out+=`\nCaused by: ${cause.stack??cause.message}`,cause=cause.cause;return out}get rootCause(){let cause=this.cause;for(;cause&&typeof cause==`object`&&cause&&`cause`in cause;)cause=cause.cause;return cause}toJSON(){return{name:this.name,message:this.message,stack:this.fullStack,cause:this.cause,traceId:this.traceId}}toString(inspect=!0){return inspect?util.inspect(this,{depth:null,colors:!0,sorted:!0,maxStringLength:1/0}):super.toString()}};const ISSUE_KIND_TO_ERROR_TITLE={schema:`Schema validation error`,transformation:`Transformation error`,validation:`Input error`};function getReturnChar(isLastItem,withColor){let char=isLastItem?`└── `:`├── `;return withColor?cyanBright(char):char}function getKindText(kind,withColor){let text=ISSUE_KIND_TO_ERROR_TITLE[kind]??`Unknown issue kind`;return withColor?yellowBright(text):text}function getPathText(dotPath,withColor){return dotPath?withColor?`${cyanBright(dotPath)}${whiteBright(dim(` →`))}`:`${dotPath} →`:``}function issueToDisplay(issues,withColor=!0){return(issues?.map((issue,index)=>{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;return`${returnChar} ${`${kindText} ${withColor?whiteBright(`at`):`at`} ${path} ${message}`}`}))?.join(`
15
+ `)??``}function displayValidationError(error,withColor=!0){let display=issueToDisplay(error.issues,withColor);return`${withColor?whiteBright(error.message):error.message}\n${display}`}var CommerceSdkValidationError=class extends CommerceSdkErrorBase{constructor(message,{issues,...options}){super(message,options),this.issues=issues}display(withColor=!0){return displayValidationError(this,withColor)}};export{CommerceSdkErrorBase,CommerceSdkValidationError};
@@ -0,0 +1,17 @@
1
+ //#region source/params/helpers.d.ts
2
+ /**
3
+ * Checks if the given runtime action input value is non-empty.
4
+ *
5
+ * @param name - The name of the parameter. Required because of `aio app dev` compatibility: inputs mapped to undefined env vars come as $<input_name> in dev mode, but as '' in prod mode.
6
+ * @param value - The value of the parameter.
7
+ */
8
+ declare function nonEmpty(name: string, value: unknown): boolean;
9
+ /**
10
+ * Checks if all required parameters are non-empty.
11
+ *
12
+ * @param params - The action input parameters.
13
+ * @param required - The list of required parameter names.
14
+ */
15
+ declare function allNonEmpty<const T extends string[]>(params: Record<string, unknown>, required: T): params is Record<string, unknown> & Record<T[number], unknown>;
16
+ //#endregion
17
+ export { allNonEmpty, nonEmpty };
@@ -11,3 +11,4 @@
11
11
  * OF ANY KIND, either express or implied. See the License for the specific language
12
12
  * governing permissions and limitations under the License.
13
13
  */
14
+ function nonEmpty(name,value){if(value==null)return!1;let v=String(value)?.trim();return!!v&&v!==`$${name}`}function allNonEmpty(params,required){return required.every(name=>nonEmpty(name,params[name]))}export{allNonEmpty,nonEmpty};
@@ -0,0 +1,188 @@
1
+ //#region source/responses/helpers.d.ts
2
+ type HeadersRecord = Record<string, string>;
3
+ type BodyRecord = Record<string, unknown>;
4
+ type BodyRecordWithMessage = BodyRecord & {
5
+ message: string;
6
+ };
7
+ /**
8
+ * Common payload structure for runtime action responses
9
+ * @template TBody - Response body properties
10
+ * @template THeaders - Custom response headers
11
+ */
12
+ type ResponsePayload<TBody extends BodyRecord = BodyRecord, THeaders extends HeadersRecord = HeadersRecord> = {
13
+ statusCode: number;
14
+ body?: TBody;
15
+ headers?: THeaders;
16
+ };
17
+ /**
18
+ * Represents an error response from a runtime action
19
+ * @template TBody - Additional error body properties beyond the required message field
20
+ * @template THeaders - Custom response headers
21
+ */
22
+ type ErrorResponse<TBody extends BodyRecordWithMessage = BodyRecordWithMessage, THeaders extends HeadersRecord = HeadersRecord> = {
23
+ type: "error";
24
+ error: ResponsePayload<TBody, THeaders>;
25
+ };
26
+ /**
27
+ * Represents a successful response from a runtime action
28
+ * @template TBody - Response body properties
29
+ * @template THeaders - Custom response headers
30
+ */
31
+ type SuccessResponse<TBody extends BodyRecord = BodyRecord, THeaders extends HeadersRecord = HeadersRecord> = ResponsePayload<TBody, THeaders> & {
32
+ type: "success";
33
+ };
34
+ /**
35
+ * Union type representing either a successful or error response from a runtime action
36
+ * @template TBody - Response/error body properties
37
+ * @template THeaders - Custom response headers
38
+ */
39
+ type ActionResponse<TBody extends BodyRecordWithMessage = BodyRecordWithMessage, THeaders extends HeadersRecord = HeadersRecord> = SuccessResponse<TBody, THeaders> | ErrorResponse<TBody, THeaders>;
40
+ /**
41
+ * Creates a standardized error response for runtime actions
42
+ * @see https://developer.adobe.com/app-builder/docs/guides/runtime_guides/creating-actions#unsuccessful-response
43
+ *
44
+ * @template TBody - Additional error body properties beyond the required message field
45
+ * @template THeaders - Custom response headers
46
+ *
47
+ * @param statusCode - HTTP status code (e.g., 400, 404, 500)
48
+ * @param payload - Error response configuration
49
+ * @param payload.message - Human-readable error message (required)
50
+ * @param payload.body - Optional additional error details to include in the response body
51
+ * @param payload.headers - Optional custom response headers
52
+ *
53
+ * @returns Standardized error response object with type discriminator
54
+ *
55
+ * @example
56
+ * ```typescript
57
+ * // Simple error with just a message
58
+ * const error = buildErrorResponse(404, {
59
+ * message: 'Resource not found'
60
+ * });
61
+ *
62
+ * // Error with additional body data
63
+ * const error = buildErrorResponse(400, {
64
+ * message: 'Invalid request',
65
+ * body: { field: 'email', code: 'INVALID_FORMAT' }
66
+ * });
67
+ *
68
+ * // Error with custom headers
69
+ * const error = buildErrorResponse(429, {
70
+ * message: 'Rate limit exceeded',
71
+ * headers: { 'Retry-After': '60' }
72
+ * });
73
+ * ```
74
+ */
75
+ declare function buildErrorResponse<TBody extends BodyRecordWithMessage = BodyRecordWithMessage, THeaders extends HeadersRecord = HeadersRecord>(statusCode: number, payload: {
76
+ body: TBody;
77
+ headers?: THeaders;
78
+ }): ErrorResponse<TBody, THeaders>;
79
+ /**
80
+ * Creates a standardized success response for runtime actions
81
+ * @see https://developer.adobe.com/app-builder/docs/guides/runtime_guides/creating-actions#successful-response
82
+ *
83
+ * @template TBody - Response body properties
84
+ * @template THeaders - Custom response headers
85
+ *
86
+ * @param statusCode - HTTP status code (typically 200, 201, 204, etc.)
87
+ * @param payload - Success response configuration
88
+ * @param payload.message - Human-readable success message (required)
89
+ * @param payload.body - Optional additional response data to include in the response body
90
+ * @param payload.headers - Optional custom response headers
91
+ *
92
+ * @returns Standardized success response object with type discriminator
93
+ *
94
+ * @example
95
+ * ```typescript
96
+ * // Simple success response
97
+ * const response = buildSuccessResponse(200, {
98
+ * message: 'Operation successful'
99
+ * });
100
+ *
101
+ * // Success with additional body data
102
+ * const response = buildSuccessResponse(201, {
103
+ * message: 'Resource created',
104
+ * body: { id: '456', created: true },
105
+ * headers: { 'Location': '/api/resources/456' }
106
+ * });
107
+ * ```
108
+ */
109
+ declare function buildSuccessResponse<TBody extends BodyRecord = BodyRecord, THeaders extends HeadersRecord = HeadersRecord>(statusCode: number, payload?: {
110
+ body?: TBody;
111
+ headers?: THeaders;
112
+ }): SuccessResponse<TBody, THeaders>;
113
+ //#endregion
114
+ //#region source/responses/presets.d.ts
115
+ declare const HTTP_OK = 200;
116
+ declare const HTTP_CREATED = 201;
117
+ declare const HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
118
+ declare const HTTP_BAD_REQUEST = 400;
119
+ declare const HTTP_UNAUTHORIZED = 401;
120
+ declare const HTTP_FORBIDDEN = 403;
121
+ declare const HTTP_NOT_FOUND = 404;
122
+ declare const HTTP_INTERNAL_SERVER_ERROR = 500;
123
+ /**
124
+ * Creates a success response with the HTTP status code 200.
125
+ * See {@link buildSuccessResponse} for details on the response payload.
126
+ */
127
+ declare const ok: (payload?: string | {
128
+ body?: BodyRecord;
129
+ headers?: HeadersRecord;
130
+ }) => SuccessResponse<BodyRecord, HeadersRecord>;
131
+ /**
132
+ * Creates a success response with the HTTP status code 201.
133
+ * See {@link buildSuccessResponse} for details on the response payload.
134
+ */
135
+ declare const created: (payload?: string | {
136
+ body?: BodyRecord;
137
+ headers?: HeadersRecord;
138
+ }) => SuccessResponse<BodyRecord, HeadersRecord>;
139
+ /**
140
+ * Creates a success response with the HTTP status code 203.
141
+ * See {@link buildSuccessResponse} for details on the response payload.
142
+ */
143
+ declare const nonAuthoritativeInformation: (payload?: string | {
144
+ body?: BodyRecord;
145
+ headers?: HeadersRecord;
146
+ }) => SuccessResponse<BodyRecord, HeadersRecord>;
147
+ /**
148
+ * Creates an error response with the HTTP status code 400.
149
+ * See {@link buildErrorResponse} for details on the response payload.
150
+ */
151
+ declare const badRequest: (payload: string | {
152
+ body: BodyRecordWithMessage;
153
+ headers?: HeadersRecord;
154
+ }) => ErrorResponse<BodyRecordWithMessage, HeadersRecord>;
155
+ /**
156
+ * Creates an error response with the HTTP status code 401.
157
+ * See {@link buildErrorResponse} for details on the response payload.
158
+ */
159
+ declare const unauthorized: (payload: string | {
160
+ body: BodyRecordWithMessage;
161
+ headers?: HeadersRecord;
162
+ }) => ErrorResponse<BodyRecordWithMessage, HeadersRecord>;
163
+ /**
164
+ * Creates an error response with the HTTP status code 403.
165
+ * See {@link buildErrorResponse} for details on the response payload.
166
+ */
167
+ declare const forbidden: (payload: string | {
168
+ body: BodyRecordWithMessage;
169
+ headers?: HeadersRecord;
170
+ }) => ErrorResponse<BodyRecordWithMessage, HeadersRecord>;
171
+ /**
172
+ * Creates an error response with the HTTP status code 404.
173
+ * See {@link buildErrorResponse} for details on the response payload.
174
+ */
175
+ declare const notFound: (payload: string | {
176
+ body: BodyRecordWithMessage;
177
+ headers?: HeadersRecord;
178
+ }) => ErrorResponse<BodyRecordWithMessage, HeadersRecord>;
179
+ /**
180
+ * Creates an error response with the HTTP status code 500.
181
+ * See {@link buildErrorResponse} for details on the response payload.
182
+ */
183
+ declare const internalServerError: (payload: string | {
184
+ body: BodyRecordWithMessage;
185
+ headers?: HeadersRecord;
186
+ }) => ErrorResponse<BodyRecordWithMessage, HeadersRecord>;
187
+ //#endregion
188
+ export { type ActionResponse, type ErrorResponse, HTTP_BAD_REQUEST, HTTP_CREATED, HTTP_FORBIDDEN, HTTP_INTERNAL_SERVER_ERROR, HTTP_NON_AUTHORITATIVE_INFORMATION, HTTP_NOT_FOUND, HTTP_OK, HTTP_UNAUTHORIZED, type SuccessResponse, badRequest, buildErrorResponse, buildSuccessResponse, created, forbidden, internalServerError, nonAuthoritativeInformation, notFound, ok, unauthorized };
@@ -0,0 +1,14 @@
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
+ function buildErrorResponse(statusCode,payload){return{type:`error`,error:{...payload?.headers&&{headers:payload.headers},statusCode,body:payload.body}}}function buildSuccessResponse(statusCode,payload){return{type:`success`,statusCode,...payload?.headers&&{headers:payload.headers},...payload?.body&&{body:payload.body}}}const HTTP_OK=200,HTTP_CREATED=201,HTTP_NON_AUTHORITATIVE_INFORMATION=203,HTTP_BAD_REQUEST=400,HTTP_UNAUTHORIZED=401,HTTP_FORBIDDEN=403,HTTP_NOT_FOUND=404,HTTP_INTERNAL_SERVER_ERROR=500;function curryBuildSuccessResponse(code){return payload=>buildSuccessResponse(code,typeof payload==`string`?{body:{message:payload}}:payload)}function curryBuildErrorResponse(code){return payload=>buildErrorResponse(code,typeof payload==`string`?{body:{message:payload}}:payload)}const ok=curryBuildSuccessResponse(200),created=curryBuildSuccessResponse(201),nonAuthoritativeInformation=curryBuildSuccessResponse(203),badRequest=curryBuildErrorResponse(400),unauthorized=curryBuildErrorResponse(401),forbidden=curryBuildErrorResponse(403),notFound=curryBuildErrorResponse(404),internalServerError=curryBuildErrorResponse(500);export{HTTP_BAD_REQUEST,HTTP_CREATED,HTTP_FORBIDDEN,HTTP_INTERNAL_SERVER_ERROR,HTTP_NON_AUTHORITATIVE_INFORMATION,HTTP_NOT_FOUND,HTTP_OK,HTTP_UNAUTHORIZED,badRequest,buildErrorResponse,buildSuccessResponse,created,forbidden,internalServerError,nonAuthoritativeInformation,notFound,ok,unauthorized};
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@adobe/aio-commerce-lib-core",
3
3
  "type": "module",
4
4
  "author": "Adobe Inc.",
5
- "version": "0.4.1",
5
+ "version": "0.5.1",
6
6
  "private": false,
7
7
  "engines": {
8
8
  "node": ">=20 <=24"
@@ -1 +0,0 @@
1
- export { };
@@ -1 +0,0 @@
1
- export { };