@adobe/aio-commerce-lib-core 0.5.1 → 0.6.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 +18 -0
- package/dist/cjs/error/index.cjs +1 -15
- package/dist/cjs/error/index.d.cts +0 -14
- package/dist/cjs/error-LUQPfUfP.cjs +2 -0
- package/dist/cjs/headers/index.cjs +1 -0
- package/dist/cjs/headers/index.d.cts +340 -0
- package/dist/cjs/index-2lCdMqhT.d.cts +43 -0
- package/dist/cjs/params/index.cjs +0 -13
- package/dist/cjs/params/index.d.cts +2 -17
- package/dist/cjs/responses/index.cjs +1 -14
- package/dist/cjs/responses/index.d.cts +35 -2
- package/dist/es/error/{index.d.ts → index.d.mts} +0 -14
- package/dist/es/error/index.mjs +1 -0
- package/dist/es/{error/index.js → error-LySQb5Bh.mjs} +1 -14
- package/dist/es/headers/index.d.mts +340 -0
- package/dist/es/headers/index.mjs +1 -0
- package/dist/es/index-CPYhPt8X.d.mts +43 -0
- package/dist/es/params/index.d.mts +2 -0
- package/dist/es/params/index.mjs +1 -0
- package/dist/es/responses/{index.d.ts → index.d.mts} +35 -2
- package/dist/es/responses/index.mjs +1 -0
- package/package.json +10 -6
- package/dist/es/params/index.d.ts +0 -17
- package/dist/es/params/index.js +0 -14
- package/dist/es/responses/index.js +0 -14
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# @adobe/aio-commerce-lib-core
|
|
2
2
|
|
|
3
|
+
## 0.6.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#246](https://github.com/adobe/aio-commerce-sdk/pull/246) [`b3b41f5`](https://github.com/adobe/aio-commerce-sdk/commit/b3b41f576cf0341bbb4a19bb534bfe35fb562aad) Thanks [@iivvaannxx](https://github.com/iivvaannxx)! - Add new `noContent` and `conflict` response presets
|
|
8
|
+
|
|
9
|
+
- [#246](https://github.com/adobe/aio-commerce-sdk/pull/246) [`b3b41f5`](https://github.com/adobe/aio-commerce-sdk/commit/b3b41f576cf0341bbb4a19bb534bfe35fb562aad) Thanks [@iivvaannxx](https://github.com/iivvaannxx)! - Split generics on `ActionResponse` type for appropriate inference
|
|
10
|
+
|
|
11
|
+
- [#245](https://github.com/adobe/aio-commerce-sdk/pull/245) [`b7fb4da`](https://github.com/adobe/aio-commerce-sdk/commit/b7fb4da5b8a9f468d4c33a25194dcc0a6e4d16a1) Thanks [@iivvaannxx](https://github.com/iivvaannxx)! - Enhance core type definitions.
|
|
12
|
+
|
|
13
|
+
## 0.6.0
|
|
14
|
+
|
|
15
|
+
### Minor Changes
|
|
16
|
+
|
|
17
|
+
- [#144](https://github.com/adobe/aio-commerce-sdk/pull/144) [`f2b6f34`](https://github.com/adobe/aio-commerce-sdk/commit/f2b6f34709a5adcca93b852b5855cb6b1c852312) Thanks [@iivvaannxx](https://github.com/iivvaannxx)! - Add various header utilities
|
|
18
|
+
|
|
19
|
+
- [#144](https://github.com/adobe/aio-commerce-sdk/pull/144) [`f2b6f34`](https://github.com/adobe/aio-commerce-sdk/commit/f2b6f34709a5adcca93b852b5855cb6b1c852312) Thanks [@iivvaannxx](https://github.com/iivvaannxx)! - Add a common type alias for `RuntimeActionParams`
|
|
20
|
+
|
|
3
21
|
## 0.5.1
|
|
4
22
|
|
|
5
23
|
### Patch Changes
|
package/dist/cjs/error/index.cjs
CHANGED
|
@@ -1,15 +1 @@
|
|
|
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)=>{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;
|
|
1
|
+
const require_error=require(`../error-LUQPfUfP.cjs`);exports.CommerceSdkErrorBase=require_error.n,exports.CommerceSdkValidationError=require_error.t;
|
|
@@ -1,17 +1,3 @@
|
|
|
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
1
|
import { GenericIssue } from "valibot";
|
|
16
2
|
|
|
17
3
|
//#region source/error/base-error.d.ts
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
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`),valibot=require(`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(`
|
|
2
|
+
`)??``}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)}};Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return CommerceSdkErrorBase}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return __toESM}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return CommerceSdkValidationError}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const require_error=require(`../error-LUQPfUfP.cjs`);let valibot=require(`valibot`),camelcase=require(`camelcase`);camelcase=require_error.r(camelcase);function getHeader(headers,name,options){let{splitCommaSeparated=!1}=options??{},value;if(Object.hasOwn(headers,name))value=headers[name];else{let lowerName=name.toLowerCase();for(let key in headers)if(Object.hasOwn(headers,key)&&key.toLowerCase()===lowerName){value=headers[key];break}}return splitCommaSeparated&&typeof value==`string`&&value.includes(`,`)&&(value=value.split(`,`).map(v=>v.trim())),value}function getHeadersFromParams(params){let parsed=(0,valibot.safeParse)((0,valibot.object)({__ow_headers:(0,valibot.record)((0,valibot.string)(),(0,valibot.union)([(0,valibot.string)(),(0,valibot.undefined)()]))}),params);if(!parsed.success)throw new require_error.t(`Missing __ow_headers in action params`,{issues:parsed.issues});return parsed.output.__ow_headers}function getMissingOrEmptyHeaders(headers,requiredHeaders){let normalized={};if(headers&&typeof headers==`object`&&!Array.isArray(headers))for(let key of Object.keys(headers)){let value=headers[key];value!=null&&(normalized[key.toLowerCase()]=value)}let parsed=(0,valibot.safeParse)(buildHeadersSchema(requiredHeaders.map(h=>(0,valibot.literal)(h))),normalized);if(parsed.success)return[];let lookup=new Map(requiredHeaders.map(h=>[h.toLowerCase(),h]));return parsed.issues.flatMap(issue=>{let key=issue.path?.[0]?.key,original=typeof key==`string`?lookup.get(key.toLowerCase()):null;return original?[original]:[]})}function buildHeadersSchema(requiredHeaders){let buildSchema=()=>(0,valibot.pipe)((0,valibot.string)(`Expected a string value for the header`),(0,valibot.rawCheck)(({dataset,addIssue})=>{if(!dataset.typed)return;let value=dataset.value;if(value.trim()===``){addIssue({expected:`a non-empty string value`,received:`"${value}"`,message:`Header value cannot be empty or contain only whitespace`});return}if(value.includes(`,`)){let parts=value.split(`,`).map(part=>part.trim());parts.some(part=>part!==``)||addIssue({expected:`at least one non-empty value in comma-separated list`,received:`[${parts.join(`, `)}]`,message:`Header value contains only empty or whitespace values when split by comma`})}})),shape={};for(let schema of requiredHeaders)shape[schema.literal.toLowerCase()]=buildSchema();return(0,valibot.object)(shape)}function assertRequiredHeadersSchema(headers,requiredHeaders){let normalized={};if(headers&&typeof headers==`object`&&!Array.isArray(headers))for(let key of Object.keys(headers)){let value=headers[key];value!=null&&(normalized[key.toLowerCase()]=value)}let parsed=(0,valibot.safeParse)(buildHeadersSchema(requiredHeaders),normalized);if(!parsed.success)throw new require_error.t(`The headers object does not match the required headers (case-insensitive)`,{issues:parsed.issues})}function assertRequiredHeaders(headers,requiredHeaders){assertRequiredHeadersSchema(headers,requiredHeaders.map(header=>(0,valibot.literal)(header)))}function createHeaderAccessor(headers,requiredHeaders,options){assertRequiredHeaders(headers,requiredHeaders);let accessor={};for(let header of requiredHeaders){let camelKey=(0,camelcase.default)(header);accessor[camelKey]=getHeader(headers,header,options)}return accessor}function isBearerAuth(auth){return auth.scheme===`Bearer`}function isBasicAuth(auth){return auth.scheme===`Basic`}function isOAuth(auth){return auth.scheme===`OAuth`}function parseKeyValueParameters(parametersString){let params={},paramPattern=/(\w+)=(?:"([^"]*)"|([^,\s]+))/g,match=paramPattern.exec(parametersString);for(;match!==null;){let[,key,quotedValue,unquotedValue]=match;params[key]=quotedValue===void 0?unquotedValue:quotedValue,match=paramPattern.exec(parametersString)}return params}const authorizationSchema=(0,valibot.pipe)((0,valibot.string)(`Expected a string value`),(0,valibot.trim)(),(0,valibot.nonEmpty)(`Expected a non-empty string value`),(0,valibot.rawTransform)(({dataset:{value:authorization},addIssue,NEVER})=>{let spaceIndex=authorization.indexOf(` `);return spaceIndex===-1?(addIssue({message:`Invalid Authorization header format`}),NEVER):{scheme:authorization.slice(0,spaceIndex),parameters:authorization.slice(spaceIndex+1).trim()}}));function parseAuthorization(authorization){let parsed=(0,valibot.safeParse)(authorizationSchema,authorization);if(!parsed.success)throw new require_error.t(`Invalid Authorization header format`,{issues:parsed.issues});let{scheme,parameters}=parsed.output;return scheme===`Bearer`?{scheme:`Bearer`,token:parameters}:scheme===`Basic`?{scheme:`Basic`,credentials:parameters}:scheme===`OAuth`?{scheme:`OAuth`,parameters:parseKeyValueParameters(parameters)}:{scheme,rawParameters:parameters,parseParameters:()=>parseKeyValueParameters(parameters)}}const bearerSchema=(0,valibot.object)({scheme:(0,valibot.literal)(`Bearer`)});function parseBearerToken(authorization){let auth=parseAuthorization(authorization),parsed=(0,valibot.safeParse)(bearerSchema,auth);if(!parsed.success)throw new require_error.t(`Authorization header must be a Bearer token`,{issues:parsed.issues});return auth}const basicSchema=(0,valibot.object)({scheme:(0,valibot.literal)(`Basic`)});function parseBasicToken(authorization){let auth=parseAuthorization(authorization),parsed=(0,valibot.safeParse)(basicSchema,auth);if(!parsed.success)throw new require_error.t(`Authorization header must be Basic authentication`,{issues:parsed.issues});return auth}const oauthSchema=(0,valibot.object)({scheme:(0,valibot.literal)(`OAuth`)});function parseOAuthToken(authorization){let auth=parseAuthorization(authorization),parsed=(0,valibot.safeParse)(oauthSchema,auth);if(!parsed.success)throw new require_error.t(`Authorization header must be OAuth`,{issues:parsed.issues});return auth}exports.assertRequiredHeaders=assertRequiredHeaders,exports.createHeaderAccessor=createHeaderAccessor,exports.getHeader=getHeader,exports.getHeadersFromParams=getHeadersFromParams,exports.getMissingOrEmptyHeaders=getMissingOrEmptyHeaders,exports.isBasicAuth=isBasicAuth,exports.isBearerAuth=isBearerAuth,exports.isOAuth=isOAuth,exports.parseAuthorization=parseAuthorization,exports.parseBasicToken=parseBasicToken,exports.parseBearerToken=parseBearerToken,exports.parseOAuthToken=parseOAuthToken;
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
import { r as RuntimeActionParams } from "../index-2lCdMqhT.cjs";
|
|
2
|
+
import { CamelCase } from "type-fest";
|
|
3
|
+
|
|
4
|
+
//#region source/headers/types.d.ts
|
|
5
|
+
|
|
6
|
+
/** The type of an HTTP header value. */
|
|
7
|
+
type HttpHeaderValue = string | string[] | undefined;
|
|
8
|
+
/** The type of an HTTP headers record. */
|
|
9
|
+
type HttpHeaders = Record<string, string | undefined>;
|
|
10
|
+
/** Options for controlling header value processing behavior in {@link getHeader} */
|
|
11
|
+
type GetHeaderOptions = {
|
|
12
|
+
/**
|
|
13
|
+
* If `true`, comma-separated header values (per RFC 9110) will be automatically
|
|
14
|
+
* split into an array. Defaults to `false`.
|
|
15
|
+
*
|
|
16
|
+
* @default false
|
|
17
|
+
*/
|
|
18
|
+
splitCommaSeparated?: boolean;
|
|
19
|
+
};
|
|
20
|
+
/** Return type for {@link getHeader} based on whether splitCommaSeparated is enabled. */
|
|
21
|
+
type GetHeaderReturn<T extends GetHeaderOptions | undefined> = T extends {
|
|
22
|
+
splitCommaSeparated: true;
|
|
23
|
+
} ? HttpHeaderValue : Exclude<HttpHeaderValue, string[]>;
|
|
24
|
+
/** The type of an HTTP header accessor object. */
|
|
25
|
+
type HttpHeaderAccessorMap<T extends string[], O extends GetHeaderOptions | undefined = undefined> = { [K in T[number] as CamelCase<K>]: Exclude<GetHeaderReturn<O>, undefined> };
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region source/headers/accessor.d.ts
|
|
28
|
+
/**
|
|
29
|
+
* Creates a type-safe header accessor object with validated required headers.
|
|
30
|
+
* Header names are normalized to camelCase for consistent access.
|
|
31
|
+
*
|
|
32
|
+
* @param headers The headers object from runtime params.
|
|
33
|
+
* @param requiredHeaders Array of required header names.
|
|
34
|
+
* @param options Optional settings to control header value processing (e.g., `splitCommaSeparated`).
|
|
35
|
+
* @throws {CommerceSdkValidationError} If any required headers are missing or empty.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```typescript
|
|
39
|
+
* const headers = getHeadersFromParams(params);
|
|
40
|
+
* const accessor = createHeaderAccessor(headers, ["x-api-key", "Authorization"]);
|
|
41
|
+
*
|
|
42
|
+
* // TypeScript knows these are non-empty strings (normalized to camelCase)
|
|
43
|
+
* const apiKey = accessor.xApiKey; // string
|
|
44
|
+
* const auth = accessor.authorization; // string
|
|
45
|
+
* ```
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```typescript
|
|
49
|
+
* // With options to enable comma-separated value splitting
|
|
50
|
+
* const accessor = createHeaderAccessor(
|
|
51
|
+
* headers,
|
|
52
|
+
* ["cache-control"],
|
|
53
|
+
* { splitCommaSeparated: true }
|
|
54
|
+
* );
|
|
55
|
+
* // accessor.cacheControl may be string | string[] depending on comma presence
|
|
56
|
+
* ```
|
|
57
|
+
*/
|
|
58
|
+
declare function createHeaderAccessor<const T extends string[], const O extends GetHeaderOptions | undefined = undefined>(headers: HttpHeaders, requiredHeaders: T, options?: O): HttpHeaderAccessorMap<T, O>;
|
|
59
|
+
//#endregion
|
|
60
|
+
//#region source/headers/auth.d.ts
|
|
61
|
+
/**
|
|
62
|
+
* Represents a Bearer authentication scheme (RFC 6750).
|
|
63
|
+
*/
|
|
64
|
+
type BearerAuthorization = {
|
|
65
|
+
scheme: "Bearer";
|
|
66
|
+
token: string;
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Represents a Basic authentication scheme (RFC 7617).
|
|
70
|
+
*/
|
|
71
|
+
type BasicAuthorization = {
|
|
72
|
+
scheme: "Basic";
|
|
73
|
+
credentials: string;
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* OAuth 1.0 parameters as defined in RFC 5849.
|
|
77
|
+
*/
|
|
78
|
+
type OAuth1Parameters = {
|
|
79
|
+
oauth_consumer_key: string;
|
|
80
|
+
oauth_token?: string;
|
|
81
|
+
oauth_signature_method: string;
|
|
82
|
+
oauth_signature: string;
|
|
83
|
+
oauth_timestamp: string;
|
|
84
|
+
oauth_nonce: string;
|
|
85
|
+
oauth_version?: string;
|
|
86
|
+
realm?: string;
|
|
87
|
+
[key: string]: string | undefined;
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* Represents an OAuth 1.0 authentication scheme (RFC 5849).
|
|
91
|
+
*/
|
|
92
|
+
type OAuth1Authorization = {
|
|
93
|
+
scheme: "OAuth";
|
|
94
|
+
parameters: OAuth1Parameters;
|
|
95
|
+
};
|
|
96
|
+
/**
|
|
97
|
+
* Represents a generic/unknown authentication scheme.
|
|
98
|
+
* The scheme must not be one of the known types (Bearer, Basic, OAuth).
|
|
99
|
+
*
|
|
100
|
+
* @remarks
|
|
101
|
+
* TypeScript cannot automatically narrow discriminated unions when `GenericAuthorization`
|
|
102
|
+
* has `scheme: string` because `string` includes all possible string literals including
|
|
103
|
+
* "Bearer", "Basic", and "OAuth". Use the provided type guards (`isBearerAuth`,
|
|
104
|
+
* `isBasicAuth`, `isOAuth`) for reliable type narrowing.
|
|
105
|
+
*/
|
|
106
|
+
type GenericAuthorization = {
|
|
107
|
+
scheme: string;
|
|
108
|
+
rawParameters: string;
|
|
109
|
+
parseParameters: () => Record<string, string>;
|
|
110
|
+
};
|
|
111
|
+
/**
|
|
112
|
+
* Discriminated union of all authorization types.
|
|
113
|
+
*
|
|
114
|
+
* @remarks
|
|
115
|
+
* **Type Narrowing Limitation**: TypeScript cannot automatically narrow this union based
|
|
116
|
+
* on `scheme === "Bearer"` checks when `GenericAuthorization` is in the union, because
|
|
117
|
+
* `GenericAuthorization.scheme` is `string`, which includes all string literals.
|
|
118
|
+
*
|
|
119
|
+
* **Recommended**: Use the provided type guards for reliable type narrowing:
|
|
120
|
+
* - `isBearerAuth(auth)` - narrows to `BearerAuthorization`
|
|
121
|
+
* - `isBasicAuth(auth)` - narrows to `BasicAuthorization`
|
|
122
|
+
* - `isOAuth(auth)` - narrows to `OAuth1Authorization`
|
|
123
|
+
*
|
|
124
|
+
* @example
|
|
125
|
+
* ```typescript
|
|
126
|
+
* const auth = parseAuthorization("Bearer token123");
|
|
127
|
+
*
|
|
128
|
+
* // ❌ This does NOT work - TypeScript cannot narrow automatically
|
|
129
|
+
* if (auth.scheme === "Bearer") {
|
|
130
|
+
* auth.token; // Error: Property 'token' does not exist
|
|
131
|
+
* }
|
|
132
|
+
*
|
|
133
|
+
* // ✅ Use type guards instead
|
|
134
|
+
* if (isBearerAuth(auth)) {
|
|
135
|
+
* auth.token; // ✅ Works - TypeScript knows auth is BearerAuthorization
|
|
136
|
+
* }
|
|
137
|
+
* ```
|
|
138
|
+
*/
|
|
139
|
+
type Authorization = BearerAuthorization | BasicAuthorization | OAuth1Authorization | GenericAuthorization;
|
|
140
|
+
/**
|
|
141
|
+
* Type guard to check if authorization is Bearer type.
|
|
142
|
+
*/
|
|
143
|
+
declare function isBearerAuth(auth: Authorization): auth is BearerAuthorization;
|
|
144
|
+
/**
|
|
145
|
+
* Type guard to check if authorization is Basic type.
|
|
146
|
+
*/
|
|
147
|
+
declare function isBasicAuth(auth: Authorization): auth is BasicAuthorization;
|
|
148
|
+
/**
|
|
149
|
+
* Type guard to check if authorization is OAuth type.
|
|
150
|
+
*/
|
|
151
|
+
declare function isOAuth(auth: Authorization): auth is OAuth1Authorization;
|
|
152
|
+
/**
|
|
153
|
+
* Parses an Authorization header value into its scheme and parameters.
|
|
154
|
+
*
|
|
155
|
+
* @param authorization The Authorization header value.
|
|
156
|
+
* @throws {CommerceSdkValidationError} If the authorization header is malformed.
|
|
157
|
+
*
|
|
158
|
+
* @example
|
|
159
|
+
* ```typescript
|
|
160
|
+
* const auth = parseAuthorization("Bearer token123");
|
|
161
|
+
* // { scheme: "Bearer", token: "token123" }
|
|
162
|
+
* ```
|
|
163
|
+
*
|
|
164
|
+
* @example
|
|
165
|
+
* ```typescript
|
|
166
|
+
* const auth = parseAuthorization("Basic dXNlcjpwYXNz");
|
|
167
|
+
* // { scheme: "Basic", credentials: "dXNlcjpwYXNz" }
|
|
168
|
+
* ```
|
|
169
|
+
*
|
|
170
|
+
* @example
|
|
171
|
+
* ```typescript
|
|
172
|
+
* const auth = parseAuthorization('OAuth oauth_consumer_key="key", oauth_token="token"');
|
|
173
|
+
* // { scheme: "OAuth", parameters: { oauth_consumer_key: "key", oauth_token: "token" } }
|
|
174
|
+
* ```
|
|
175
|
+
*
|
|
176
|
+
* @example
|
|
177
|
+
* ```typescript
|
|
178
|
+
* const auth = parseAuthorization('Digest realm="Example", nonce="abc"');
|
|
179
|
+
* // { scheme: "Digest", rawParameters: 'realm="Example", nonce="abc"' }
|
|
180
|
+
*
|
|
181
|
+
* const parameters = auth.parseParameters();
|
|
182
|
+
* // { realm: "Example", nonce: "abc" }
|
|
183
|
+
* ```
|
|
184
|
+
*/
|
|
185
|
+
declare function parseAuthorization(authorization: string): Authorization;
|
|
186
|
+
/**
|
|
187
|
+
* Parses and validates a Bearer authorization header.
|
|
188
|
+
*
|
|
189
|
+
* @param authorization The Authorization header value.
|
|
190
|
+
* @throws {CommerceSdkValidationError} If the authorization header is not a Bearer token or if the token is empty.
|
|
191
|
+
*
|
|
192
|
+
* @example
|
|
193
|
+
* ```typescript
|
|
194
|
+
* const auth = parseBearerToken("Bearer eyJhbGci...");
|
|
195
|
+
* console.log(auth.token); // "eyJhbGci..."
|
|
196
|
+
* ```
|
|
197
|
+
*
|
|
198
|
+
* @example
|
|
199
|
+
* ```typescript
|
|
200
|
+
* try {
|
|
201
|
+
* parseBearerToken("Basic dXNlcjpwYXNz");
|
|
202
|
+
* } catch (error) {
|
|
203
|
+
* console.error(error.message); // "Authorization header must be a Bearer token"
|
|
204
|
+
* }
|
|
205
|
+
* ```
|
|
206
|
+
*/
|
|
207
|
+
declare function parseBearerToken(authorization: string): BearerAuthorization;
|
|
208
|
+
/**
|
|
209
|
+
* Parses and validates a Basic authorization header.
|
|
210
|
+
*
|
|
211
|
+
* @param authorization The Authorization header value.
|
|
212
|
+
* @throws {CommerceSdkValidationError} If the authorization header is not Basic auth.
|
|
213
|
+
*
|
|
214
|
+
* @example
|
|
215
|
+
* ```typescript
|
|
216
|
+
* const auth = parseBasicToken("Basic dXNlcjpwYXNz");
|
|
217
|
+
* console.log(auth.credentials); // "dXNlcjpwYXNz"
|
|
218
|
+
* ```
|
|
219
|
+
*/
|
|
220
|
+
declare function parseBasicToken(authorization: string): BasicAuthorization;
|
|
221
|
+
/**
|
|
222
|
+
* Parses and validates an OAuth 1.0 authorization header.
|
|
223
|
+
*
|
|
224
|
+
* @param authorization The Authorization header value.
|
|
225
|
+
* @throws {CommerceSdkValidationError} If the authorization header is not OAuth.
|
|
226
|
+
*
|
|
227
|
+
* @example
|
|
228
|
+
* ```typescript
|
|
229
|
+
* const auth = parseOAuthToken('OAuth oauth_consumer_key="key", oauth_token="token"');
|
|
230
|
+
* console.log(auth.parameters.oauth_consumer_key); // "key"
|
|
231
|
+
* console.log(auth.parameters.oauth_token); // "token"
|
|
232
|
+
* ```
|
|
233
|
+
*/
|
|
234
|
+
declare function parseOAuthToken(authorization: string): OAuth1Authorization;
|
|
235
|
+
//#endregion
|
|
236
|
+
//#region source/headers/helpers.d.ts
|
|
237
|
+
/**
|
|
238
|
+
* Extracts a header value from an object with case-insensitive lookup.
|
|
239
|
+
* This is useful for handling HTTP headers which can be case-insensitive per RFC 7230.
|
|
240
|
+
*
|
|
241
|
+
* When enabled via options, comma-separated header values (per RFC 9110) can be
|
|
242
|
+
* automatically split into an array. This is useful when multiple header values
|
|
243
|
+
* are combined into a single comma-separated string.
|
|
244
|
+
*
|
|
245
|
+
* @param headers The headers object to search in.
|
|
246
|
+
* @param name The header name to look for (case-insensitive).
|
|
247
|
+
* @param options Optional settings to control header value processing.
|
|
248
|
+
*
|
|
249
|
+
* @example
|
|
250
|
+
* ```typescript
|
|
251
|
+
* const headers = { authorization: "Bearer token123" };
|
|
252
|
+
* const auth = getHeader(headers, "Authorization"); // "Bearer token123"
|
|
253
|
+
* ```
|
|
254
|
+
*
|
|
255
|
+
* @example
|
|
256
|
+
* ```typescript
|
|
257
|
+
* // Comma-separated string can be split when enabled (per RFC 9110)
|
|
258
|
+
* const headers = { "Example-Field": "Foo, Bar" };
|
|
259
|
+
* const value = getHeader(headers, "Example-Field", { splitCommaSeparated: true }); // ["Foo", "Bar"]
|
|
260
|
+
* ```
|
|
261
|
+
*
|
|
262
|
+
* @see https://datatracker.ietf.org/doc/html/rfc7230 - HTTP/1.1 Message Syntax and Routing
|
|
263
|
+
* @see https://datatracker.ietf.org/doc/html/rfc9110#name-field-lines-and-combined-fi - HTTP Semantics: Field Lines and Combined Field Values
|
|
264
|
+
*/
|
|
265
|
+
declare function getHeader<T extends GetHeaderOptions | undefined = undefined>(headers: HttpHeaders, name: string, options?: T): GetHeaderReturn<T>;
|
|
266
|
+
/**
|
|
267
|
+
* Extracts the `__ow_headers` object from App Builder runtime action parameters.
|
|
268
|
+
*
|
|
269
|
+
* @param params The action parameters from App Builder runtime.
|
|
270
|
+
* @throws {CommerceSdkValidationError} If `__ow_headers` is missing or not an object.
|
|
271
|
+
*
|
|
272
|
+
* @example
|
|
273
|
+
* ```typescript
|
|
274
|
+
* export async function main(params) {
|
|
275
|
+
* const headers = getHeadersFromParams(params);
|
|
276
|
+
* const apiKey = headers["x-api-key"];
|
|
277
|
+
* }
|
|
278
|
+
* ```
|
|
279
|
+
*/
|
|
280
|
+
declare function getHeadersFromParams(params: RuntimeActionParams): HttpHeaders;
|
|
281
|
+
//#endregion
|
|
282
|
+
//#region source/headers/validation.d.ts
|
|
283
|
+
/**
|
|
284
|
+
* Returns an array of missing or empty headers using Valibot validation.
|
|
285
|
+
* Case-insensitive by default.
|
|
286
|
+
*
|
|
287
|
+
* Unlike {@link assertRequiredHeaders}, this function does not throw an error.
|
|
288
|
+
* Instead, it returns an array of header names that are missing or empty.
|
|
289
|
+
* This is useful when you need to check headers without immediately failing.
|
|
290
|
+
*
|
|
291
|
+
* @param headers The headers object to validate.
|
|
292
|
+
* @param requiredHeaders Array of required header names.
|
|
293
|
+
* @returns Array of header names that are missing or empty. Empty array if all headers are present and non-empty.
|
|
294
|
+
*
|
|
295
|
+
* @example
|
|
296
|
+
* ```typescript
|
|
297
|
+
* const headers = { "x-api-key": "key123" };
|
|
298
|
+
* const missing = getMissingOrEmptyHeaders(headers, ["x-api-key", "Authorization"]);
|
|
299
|
+
* // Returns: ["Authorization"]
|
|
300
|
+
* ```
|
|
301
|
+
*
|
|
302
|
+
* @example
|
|
303
|
+
* ```typescript
|
|
304
|
+
* const headers = { "x-api-key": "", "Authorization": "Bearer token" };
|
|
305
|
+
* const missing = getMissingOrEmptyHeaders(headers, ["x-api-key", "Authorization"]);
|
|
306
|
+
* // Returns: ["x-api-key"] (empty string is considered missing)
|
|
307
|
+
* ```
|
|
308
|
+
*/
|
|
309
|
+
declare function getMissingOrEmptyHeaders(headers: HttpHeaders, requiredHeaders: string[]): string[];
|
|
310
|
+
/**
|
|
311
|
+
* Validates that required headers are present and non-empty in the headers object.
|
|
312
|
+
* Performs case-insensitive validation with {@link getHeader}.
|
|
313
|
+
*
|
|
314
|
+
* @param headers The headers object to validate.
|
|
315
|
+
* @param requiredHeaders Array of required header names.
|
|
316
|
+
* @throws {CommerceSdkValidationError} If any required headers are missing or empty.
|
|
317
|
+
*
|
|
318
|
+
* @example
|
|
319
|
+
* ```typescript
|
|
320
|
+
* const headers = { "x-api-key": "key123", "Authorization": "Bearer token" };
|
|
321
|
+
* assertRequiredHeaders(headers, ["x-api-key", "Authorization"]);
|
|
322
|
+
* // Headers are validated, use getHeader() for safe access
|
|
323
|
+
* const apiKey = getHeader(headers, "x-api-key")!;
|
|
324
|
+
* ```
|
|
325
|
+
*
|
|
326
|
+
* @example
|
|
327
|
+
* ```typescript
|
|
328
|
+
* try {
|
|
329
|
+
* assertRequiredHeaders({}, ["x-api-key", "Authorization"]);
|
|
330
|
+
* } catch (error) {
|
|
331
|
+
* console.error(error.display());
|
|
332
|
+
* // "The headers object does not match the required headers (case-insensitive)"
|
|
333
|
+
* // ├── Schema validation error at x-api-key → Expected a non-empty string value
|
|
334
|
+
* // └── Schema validation error at Authorization → Expected a non-empty string value
|
|
335
|
+
* }
|
|
336
|
+
* ```
|
|
337
|
+
*/
|
|
338
|
+
declare function assertRequiredHeaders(headers: HttpHeaders, requiredHeaders: string[]): void;
|
|
339
|
+
//#endregion
|
|
340
|
+
export { type Authorization, type BasicAuthorization, type BearerAuthorization, type GenericAuthorization, type HttpHeaderAccessorMap, type HttpHeaderValue, type HttpHeaders, type OAuth1Authorization, type OAuth1Parameters, assertRequiredHeaders, createHeaderAccessor, getHeader, getHeadersFromParams, getMissingOrEmptyHeaders, isBasicAuth, isBearerAuth, isOAuth, parseAuthorization, parseBasicToken, parseBearerToken, parseOAuthToken };
|
|
@@ -0,0 +1,43 @@
|
|
|
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
|
+
//#region source/params/types.d.ts
|
|
18
|
+
/**
|
|
19
|
+
* Standard HTTP methods supported by Adobe I/O Runtime.
|
|
20
|
+
* These are the methods that can be used when invoking runtime actions via HTTP.
|
|
21
|
+
*/
|
|
22
|
+
type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
|
|
23
|
+
/**
|
|
24
|
+
* Lowercase HTTP method as sent by OpenWhisk/Adobe I/O Runtime.
|
|
25
|
+
* OpenWhisk sends methods in lowercase (e.g., "get", "post").
|
|
26
|
+
*/
|
|
27
|
+
type HttpMethodLowercase = Lowercase<HttpMethod>;
|
|
28
|
+
/** The type of the runtime action parameters. */
|
|
29
|
+
type RuntimeActionParams = {
|
|
30
|
+
/** If the runtime action is invoked via HTTP, this will be the headers of the request. */
|
|
31
|
+
__ow_headers?: Record<string, string | undefined>;
|
|
32
|
+
/** If the runtime action is invoked via HTTP, this will be the HTTP method of the request. */
|
|
33
|
+
__ow_method?: HttpMethodLowercase;
|
|
34
|
+
/** If the runtime action is invoked via HTTP, this will be the unmatched path of the request (matching stops after consuming the action extension) */
|
|
35
|
+
__ow_path?: string;
|
|
36
|
+
/** If the runtime action is invoked via HTTP, this will be the request body entity, as a base64-encoded string when its content is binary or JSON object/array, or as a plain string otherwise */
|
|
37
|
+
__ow_body?: string;
|
|
38
|
+
/** If the runtime action is invoked via HTTP, this will be the query parameters of the request, as an unparsed string. */
|
|
39
|
+
__ow_query?: string;
|
|
40
|
+
[key: string]: unknown;
|
|
41
|
+
};
|
|
42
|
+
//#endregion
|
|
43
|
+
export { nonEmpty as a, allNonEmpty as i, HttpMethodLowercase as n, RuntimeActionParams as r, HttpMethod as t };
|
|
@@ -1,14 +1 @@
|
|
|
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
1
|
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;
|
|
@@ -1,17 +1,2 @@
|
|
|
1
|
-
|
|
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 };
|
|
1
|
+
import { a as nonEmpty, i as allNonEmpty, n as HttpMethodLowercase, r as RuntimeActionParams, t as HttpMethod } from "../index-2lCdMqhT.cjs";
|
|
2
|
+
export { HttpMethod, HttpMethodLowercase, RuntimeActionParams, allNonEmpty, nonEmpty };
|
|
@@ -1,14 +1 @@
|
|
|
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;
|
|
1
|
+
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_ACCEPTED=202,HTTP_NON_AUTHORITATIVE_INFORMATION=203,HTTP_NO_CONTENT=204,HTTP_BAD_REQUEST=400,HTTP_UNAUTHORIZED=401,HTTP_FORBIDDEN=403,HTTP_NOT_FOUND=404,HTTP_METHOD_NOT_ALLOWED=405,HTTP_CONFLICT=409,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),accepted=curryBuildSuccessResponse(202),nonAuthoritativeInformation=curryBuildSuccessResponse(203),noContent=()=>buildSuccessResponse(204),badRequest=curryBuildErrorResponse(400),unauthorized=curryBuildErrorResponse(401),forbidden=curryBuildErrorResponse(403),notFound=curryBuildErrorResponse(404),methodNotAllowed=curryBuildErrorResponse(405),conflict=curryBuildErrorResponse(409),internalServerError=curryBuildErrorResponse(500);exports.HTTP_ACCEPTED=202,exports.HTTP_BAD_REQUEST=400,exports.HTTP_CONFLICT=409,exports.HTTP_CREATED=201,exports.HTTP_FORBIDDEN=403,exports.HTTP_INTERNAL_SERVER_ERROR=500,exports.HTTP_METHOD_NOT_ALLOWED=405,exports.HTTP_NON_AUTHORITATIVE_INFORMATION=203,exports.HTTP_NOT_FOUND=404,exports.HTTP_NO_CONTENT=204,exports.HTTP_OK=200,exports.HTTP_UNAUTHORIZED=401,exports.accepted=accepted,exports.badRequest=badRequest,exports.buildErrorResponse=buildErrorResponse,exports.buildSuccessResponse=buildSuccessResponse,exports.conflict=conflict,exports.created=created,exports.forbidden=forbidden,exports.internalServerError=internalServerError,exports.methodNotAllowed=methodNotAllowed,exports.noContent=noContent,exports.nonAuthoritativeInformation=nonAuthoritativeInformation,exports.notFound=notFound,exports.ok=ok,exports.unauthorized=unauthorized;
|
|
@@ -36,7 +36,7 @@ type SuccessResponse<TBody extends BodyRecord = BodyRecord, THeaders extends Hea
|
|
|
36
36
|
* @template TBody - Response/error body properties
|
|
37
37
|
* @template THeaders - Custom response headers
|
|
38
38
|
*/
|
|
39
|
-
type ActionResponse<
|
|
39
|
+
type ActionResponse<TSuccessBody extends BodyRecord = BodyRecord, TErrorBody extends BodyRecordWithMessage = BodyRecordWithMessage, THeaders extends HeadersRecord = HeadersRecord> = SuccessResponse<TSuccessBody, THeaders> | ErrorResponse<TErrorBody, THeaders>;
|
|
40
40
|
/**
|
|
41
41
|
* Creates a standardized error response for runtime actions
|
|
42
42
|
* @see https://developer.adobe.com/app-builder/docs/guides/runtime_guides/creating-actions#unsuccessful-response
|
|
@@ -114,11 +114,15 @@ declare function buildSuccessResponse<TBody extends BodyRecord = BodyRecord, THe
|
|
|
114
114
|
//#region source/responses/presets.d.ts
|
|
115
115
|
declare const HTTP_OK = 200;
|
|
116
116
|
declare const HTTP_CREATED = 201;
|
|
117
|
+
declare const HTTP_ACCEPTED = 202;
|
|
117
118
|
declare const HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
|
|
119
|
+
declare const HTTP_NO_CONTENT = 204;
|
|
118
120
|
declare const HTTP_BAD_REQUEST = 400;
|
|
119
121
|
declare const HTTP_UNAUTHORIZED = 401;
|
|
120
122
|
declare const HTTP_FORBIDDEN = 403;
|
|
121
123
|
declare const HTTP_NOT_FOUND = 404;
|
|
124
|
+
declare const HTTP_METHOD_NOT_ALLOWED = 405;
|
|
125
|
+
declare const HTTP_CONFLICT = 409;
|
|
122
126
|
declare const HTTP_INTERNAL_SERVER_ERROR = 500;
|
|
123
127
|
/**
|
|
124
128
|
* Creates a success response with the HTTP status code 200.
|
|
@@ -136,6 +140,14 @@ declare const created: (payload?: string | {
|
|
|
136
140
|
body?: BodyRecord;
|
|
137
141
|
headers?: HeadersRecord;
|
|
138
142
|
}) => SuccessResponse<BodyRecord, HeadersRecord>;
|
|
143
|
+
/**
|
|
144
|
+
* Creates a success response with the HTTP status code 202.
|
|
145
|
+
* See {@link buildSuccessResponse} for details on the response payload.
|
|
146
|
+
*/
|
|
147
|
+
declare const accepted: (payload?: string | {
|
|
148
|
+
body?: BodyRecord;
|
|
149
|
+
headers?: HeadersRecord;
|
|
150
|
+
}) => SuccessResponse<BodyRecord, HeadersRecord>;
|
|
139
151
|
/**
|
|
140
152
|
* Creates a success response with the HTTP status code 203.
|
|
141
153
|
* See {@link buildSuccessResponse} for details on the response payload.
|
|
@@ -144,6 +156,11 @@ declare const nonAuthoritativeInformation: (payload?: string | {
|
|
|
144
156
|
body?: BodyRecord;
|
|
145
157
|
headers?: HeadersRecord;
|
|
146
158
|
}) => SuccessResponse<BodyRecord, HeadersRecord>;
|
|
159
|
+
/**
|
|
160
|
+
* Creates a success response with the HTTP status code 204 (No Content).
|
|
161
|
+
* This response has no body.
|
|
162
|
+
*/
|
|
163
|
+
declare const noContent: () => SuccessResponse<BodyRecord, HeadersRecord>;
|
|
147
164
|
/**
|
|
148
165
|
* Creates an error response with the HTTP status code 400.
|
|
149
166
|
* See {@link buildErrorResponse} for details on the response payload.
|
|
@@ -176,6 +193,22 @@ declare const notFound: (payload: string | {
|
|
|
176
193
|
body: BodyRecordWithMessage;
|
|
177
194
|
headers?: HeadersRecord;
|
|
178
195
|
}) => ErrorResponse<BodyRecordWithMessage, HeadersRecord>;
|
|
196
|
+
/**
|
|
197
|
+
* Creates an error response with the HTTP status code 405.
|
|
198
|
+
* See {@link buildErrorResponse} for details on the response payload.
|
|
199
|
+
*/
|
|
200
|
+
declare const methodNotAllowed: (payload: string | {
|
|
201
|
+
body: BodyRecordWithMessage;
|
|
202
|
+
headers?: HeadersRecord;
|
|
203
|
+
}) => ErrorResponse<BodyRecordWithMessage, HeadersRecord>;
|
|
204
|
+
/**
|
|
205
|
+
* Creates an error response with the HTTP status code 409.
|
|
206
|
+
* See {@link buildErrorResponse} for details on the response payload.
|
|
207
|
+
*/
|
|
208
|
+
declare const conflict: (payload: string | {
|
|
209
|
+
body: BodyRecordWithMessage;
|
|
210
|
+
headers?: HeadersRecord;
|
|
211
|
+
}) => ErrorResponse<BodyRecordWithMessage, HeadersRecord>;
|
|
179
212
|
/**
|
|
180
213
|
* Creates an error response with the HTTP status code 500.
|
|
181
214
|
* See {@link buildErrorResponse} for details on the response payload.
|
|
@@ -185,4 +218,4 @@ declare const internalServerError: (payload: string | {
|
|
|
185
218
|
headers?: HeadersRecord;
|
|
186
219
|
}) => ErrorResponse<BodyRecordWithMessage, HeadersRecord>;
|
|
187
220
|
//#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 };
|
|
221
|
+
export { type ActionResponse, type ErrorResponse, HTTP_ACCEPTED, HTTP_BAD_REQUEST, HTTP_CONFLICT, HTTP_CREATED, HTTP_FORBIDDEN, HTTP_INTERNAL_SERVER_ERROR, HTTP_METHOD_NOT_ALLOWED, HTTP_NON_AUTHORITATIVE_INFORMATION, HTTP_NOT_FOUND, HTTP_NO_CONTENT, HTTP_OK, HTTP_UNAUTHORIZED, type SuccessResponse, accepted, badRequest, buildErrorResponse, buildSuccessResponse, conflict, created, forbidden, internalServerError, methodNotAllowed, noContent, nonAuthoritativeInformation, notFound, ok, unauthorized };
|
|
@@ -1,17 +1,3 @@
|
|
|
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
1
|
import { GenericIssue } from "valibot";
|
|
16
2
|
|
|
17
3
|
//#region source/error/base-error.d.ts
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as CommerceSdkErrorBase,t as CommerceSdkValidationError}from"../error-LySQb5Bh.mjs";export{CommerceSdkErrorBase,CommerceSdkValidationError};
|
|
@@ -1,15 +1,2 @@
|
|
|
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
1
|
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};
|
|
2
|
+
`)??``}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 as n,CommerceSdkValidationError as t};
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
import { r as RuntimeActionParams } from "../index-CPYhPt8X.mjs";
|
|
2
|
+
import { CamelCase } from "type-fest";
|
|
3
|
+
|
|
4
|
+
//#region source/headers/types.d.ts
|
|
5
|
+
|
|
6
|
+
/** The type of an HTTP header value. */
|
|
7
|
+
type HttpHeaderValue = string | string[] | undefined;
|
|
8
|
+
/** The type of an HTTP headers record. */
|
|
9
|
+
type HttpHeaders = Record<string, string | undefined>;
|
|
10
|
+
/** Options for controlling header value processing behavior in {@link getHeader} */
|
|
11
|
+
type GetHeaderOptions = {
|
|
12
|
+
/**
|
|
13
|
+
* If `true`, comma-separated header values (per RFC 9110) will be automatically
|
|
14
|
+
* split into an array. Defaults to `false`.
|
|
15
|
+
*
|
|
16
|
+
* @default false
|
|
17
|
+
*/
|
|
18
|
+
splitCommaSeparated?: boolean;
|
|
19
|
+
};
|
|
20
|
+
/** Return type for {@link getHeader} based on whether splitCommaSeparated is enabled. */
|
|
21
|
+
type GetHeaderReturn<T extends GetHeaderOptions | undefined> = T extends {
|
|
22
|
+
splitCommaSeparated: true;
|
|
23
|
+
} ? HttpHeaderValue : Exclude<HttpHeaderValue, string[]>;
|
|
24
|
+
/** The type of an HTTP header accessor object. */
|
|
25
|
+
type HttpHeaderAccessorMap<T extends string[], O extends GetHeaderOptions | undefined = undefined> = { [K in T[number] as CamelCase<K>]: Exclude<GetHeaderReturn<O>, undefined> };
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region source/headers/accessor.d.ts
|
|
28
|
+
/**
|
|
29
|
+
* Creates a type-safe header accessor object with validated required headers.
|
|
30
|
+
* Header names are normalized to camelCase for consistent access.
|
|
31
|
+
*
|
|
32
|
+
* @param headers The headers object from runtime params.
|
|
33
|
+
* @param requiredHeaders Array of required header names.
|
|
34
|
+
* @param options Optional settings to control header value processing (e.g., `splitCommaSeparated`).
|
|
35
|
+
* @throws {CommerceSdkValidationError} If any required headers are missing or empty.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```typescript
|
|
39
|
+
* const headers = getHeadersFromParams(params);
|
|
40
|
+
* const accessor = createHeaderAccessor(headers, ["x-api-key", "Authorization"]);
|
|
41
|
+
*
|
|
42
|
+
* // TypeScript knows these are non-empty strings (normalized to camelCase)
|
|
43
|
+
* const apiKey = accessor.xApiKey; // string
|
|
44
|
+
* const auth = accessor.authorization; // string
|
|
45
|
+
* ```
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```typescript
|
|
49
|
+
* // With options to enable comma-separated value splitting
|
|
50
|
+
* const accessor = createHeaderAccessor(
|
|
51
|
+
* headers,
|
|
52
|
+
* ["cache-control"],
|
|
53
|
+
* { splitCommaSeparated: true }
|
|
54
|
+
* );
|
|
55
|
+
* // accessor.cacheControl may be string | string[] depending on comma presence
|
|
56
|
+
* ```
|
|
57
|
+
*/
|
|
58
|
+
declare function createHeaderAccessor<const T extends string[], const O extends GetHeaderOptions | undefined = undefined>(headers: HttpHeaders, requiredHeaders: T, options?: O): HttpHeaderAccessorMap<T, O>;
|
|
59
|
+
//#endregion
|
|
60
|
+
//#region source/headers/auth.d.ts
|
|
61
|
+
/**
|
|
62
|
+
* Represents a Bearer authentication scheme (RFC 6750).
|
|
63
|
+
*/
|
|
64
|
+
type BearerAuthorization = {
|
|
65
|
+
scheme: "Bearer";
|
|
66
|
+
token: string;
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Represents a Basic authentication scheme (RFC 7617).
|
|
70
|
+
*/
|
|
71
|
+
type BasicAuthorization = {
|
|
72
|
+
scheme: "Basic";
|
|
73
|
+
credentials: string;
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* OAuth 1.0 parameters as defined in RFC 5849.
|
|
77
|
+
*/
|
|
78
|
+
type OAuth1Parameters = {
|
|
79
|
+
oauth_consumer_key: string;
|
|
80
|
+
oauth_token?: string;
|
|
81
|
+
oauth_signature_method: string;
|
|
82
|
+
oauth_signature: string;
|
|
83
|
+
oauth_timestamp: string;
|
|
84
|
+
oauth_nonce: string;
|
|
85
|
+
oauth_version?: string;
|
|
86
|
+
realm?: string;
|
|
87
|
+
[key: string]: string | undefined;
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* Represents an OAuth 1.0 authentication scheme (RFC 5849).
|
|
91
|
+
*/
|
|
92
|
+
type OAuth1Authorization = {
|
|
93
|
+
scheme: "OAuth";
|
|
94
|
+
parameters: OAuth1Parameters;
|
|
95
|
+
};
|
|
96
|
+
/**
|
|
97
|
+
* Represents a generic/unknown authentication scheme.
|
|
98
|
+
* The scheme must not be one of the known types (Bearer, Basic, OAuth).
|
|
99
|
+
*
|
|
100
|
+
* @remarks
|
|
101
|
+
* TypeScript cannot automatically narrow discriminated unions when `GenericAuthorization`
|
|
102
|
+
* has `scheme: string` because `string` includes all possible string literals including
|
|
103
|
+
* "Bearer", "Basic", and "OAuth". Use the provided type guards (`isBearerAuth`,
|
|
104
|
+
* `isBasicAuth`, `isOAuth`) for reliable type narrowing.
|
|
105
|
+
*/
|
|
106
|
+
type GenericAuthorization = {
|
|
107
|
+
scheme: string;
|
|
108
|
+
rawParameters: string;
|
|
109
|
+
parseParameters: () => Record<string, string>;
|
|
110
|
+
};
|
|
111
|
+
/**
|
|
112
|
+
* Discriminated union of all authorization types.
|
|
113
|
+
*
|
|
114
|
+
* @remarks
|
|
115
|
+
* **Type Narrowing Limitation**: TypeScript cannot automatically narrow this union based
|
|
116
|
+
* on `scheme === "Bearer"` checks when `GenericAuthorization` is in the union, because
|
|
117
|
+
* `GenericAuthorization.scheme` is `string`, which includes all string literals.
|
|
118
|
+
*
|
|
119
|
+
* **Recommended**: Use the provided type guards for reliable type narrowing:
|
|
120
|
+
* - `isBearerAuth(auth)` - narrows to `BearerAuthorization`
|
|
121
|
+
* - `isBasicAuth(auth)` - narrows to `BasicAuthorization`
|
|
122
|
+
* - `isOAuth(auth)` - narrows to `OAuth1Authorization`
|
|
123
|
+
*
|
|
124
|
+
* @example
|
|
125
|
+
* ```typescript
|
|
126
|
+
* const auth = parseAuthorization("Bearer token123");
|
|
127
|
+
*
|
|
128
|
+
* // ❌ This does NOT work - TypeScript cannot narrow automatically
|
|
129
|
+
* if (auth.scheme === "Bearer") {
|
|
130
|
+
* auth.token; // Error: Property 'token' does not exist
|
|
131
|
+
* }
|
|
132
|
+
*
|
|
133
|
+
* // ✅ Use type guards instead
|
|
134
|
+
* if (isBearerAuth(auth)) {
|
|
135
|
+
* auth.token; // ✅ Works - TypeScript knows auth is BearerAuthorization
|
|
136
|
+
* }
|
|
137
|
+
* ```
|
|
138
|
+
*/
|
|
139
|
+
type Authorization = BearerAuthorization | BasicAuthorization | OAuth1Authorization | GenericAuthorization;
|
|
140
|
+
/**
|
|
141
|
+
* Type guard to check if authorization is Bearer type.
|
|
142
|
+
*/
|
|
143
|
+
declare function isBearerAuth(auth: Authorization): auth is BearerAuthorization;
|
|
144
|
+
/**
|
|
145
|
+
* Type guard to check if authorization is Basic type.
|
|
146
|
+
*/
|
|
147
|
+
declare function isBasicAuth(auth: Authorization): auth is BasicAuthorization;
|
|
148
|
+
/**
|
|
149
|
+
* Type guard to check if authorization is OAuth type.
|
|
150
|
+
*/
|
|
151
|
+
declare function isOAuth(auth: Authorization): auth is OAuth1Authorization;
|
|
152
|
+
/**
|
|
153
|
+
* Parses an Authorization header value into its scheme and parameters.
|
|
154
|
+
*
|
|
155
|
+
* @param authorization The Authorization header value.
|
|
156
|
+
* @throws {CommerceSdkValidationError} If the authorization header is malformed.
|
|
157
|
+
*
|
|
158
|
+
* @example
|
|
159
|
+
* ```typescript
|
|
160
|
+
* const auth = parseAuthorization("Bearer token123");
|
|
161
|
+
* // { scheme: "Bearer", token: "token123" }
|
|
162
|
+
* ```
|
|
163
|
+
*
|
|
164
|
+
* @example
|
|
165
|
+
* ```typescript
|
|
166
|
+
* const auth = parseAuthorization("Basic dXNlcjpwYXNz");
|
|
167
|
+
* // { scheme: "Basic", credentials: "dXNlcjpwYXNz" }
|
|
168
|
+
* ```
|
|
169
|
+
*
|
|
170
|
+
* @example
|
|
171
|
+
* ```typescript
|
|
172
|
+
* const auth = parseAuthorization('OAuth oauth_consumer_key="key", oauth_token="token"');
|
|
173
|
+
* // { scheme: "OAuth", parameters: { oauth_consumer_key: "key", oauth_token: "token" } }
|
|
174
|
+
* ```
|
|
175
|
+
*
|
|
176
|
+
* @example
|
|
177
|
+
* ```typescript
|
|
178
|
+
* const auth = parseAuthorization('Digest realm="Example", nonce="abc"');
|
|
179
|
+
* // { scheme: "Digest", rawParameters: 'realm="Example", nonce="abc"' }
|
|
180
|
+
*
|
|
181
|
+
* const parameters = auth.parseParameters();
|
|
182
|
+
* // { realm: "Example", nonce: "abc" }
|
|
183
|
+
* ```
|
|
184
|
+
*/
|
|
185
|
+
declare function parseAuthorization(authorization: string): Authorization;
|
|
186
|
+
/**
|
|
187
|
+
* Parses and validates a Bearer authorization header.
|
|
188
|
+
*
|
|
189
|
+
* @param authorization The Authorization header value.
|
|
190
|
+
* @throws {CommerceSdkValidationError} If the authorization header is not a Bearer token or if the token is empty.
|
|
191
|
+
*
|
|
192
|
+
* @example
|
|
193
|
+
* ```typescript
|
|
194
|
+
* const auth = parseBearerToken("Bearer eyJhbGci...");
|
|
195
|
+
* console.log(auth.token); // "eyJhbGci..."
|
|
196
|
+
* ```
|
|
197
|
+
*
|
|
198
|
+
* @example
|
|
199
|
+
* ```typescript
|
|
200
|
+
* try {
|
|
201
|
+
* parseBearerToken("Basic dXNlcjpwYXNz");
|
|
202
|
+
* } catch (error) {
|
|
203
|
+
* console.error(error.message); // "Authorization header must be a Bearer token"
|
|
204
|
+
* }
|
|
205
|
+
* ```
|
|
206
|
+
*/
|
|
207
|
+
declare function parseBearerToken(authorization: string): BearerAuthorization;
|
|
208
|
+
/**
|
|
209
|
+
* Parses and validates a Basic authorization header.
|
|
210
|
+
*
|
|
211
|
+
* @param authorization The Authorization header value.
|
|
212
|
+
* @throws {CommerceSdkValidationError} If the authorization header is not Basic auth.
|
|
213
|
+
*
|
|
214
|
+
* @example
|
|
215
|
+
* ```typescript
|
|
216
|
+
* const auth = parseBasicToken("Basic dXNlcjpwYXNz");
|
|
217
|
+
* console.log(auth.credentials); // "dXNlcjpwYXNz"
|
|
218
|
+
* ```
|
|
219
|
+
*/
|
|
220
|
+
declare function parseBasicToken(authorization: string): BasicAuthorization;
|
|
221
|
+
/**
|
|
222
|
+
* Parses and validates an OAuth 1.0 authorization header.
|
|
223
|
+
*
|
|
224
|
+
* @param authorization The Authorization header value.
|
|
225
|
+
* @throws {CommerceSdkValidationError} If the authorization header is not OAuth.
|
|
226
|
+
*
|
|
227
|
+
* @example
|
|
228
|
+
* ```typescript
|
|
229
|
+
* const auth = parseOAuthToken('OAuth oauth_consumer_key="key", oauth_token="token"');
|
|
230
|
+
* console.log(auth.parameters.oauth_consumer_key); // "key"
|
|
231
|
+
* console.log(auth.parameters.oauth_token); // "token"
|
|
232
|
+
* ```
|
|
233
|
+
*/
|
|
234
|
+
declare function parseOAuthToken(authorization: string): OAuth1Authorization;
|
|
235
|
+
//#endregion
|
|
236
|
+
//#region source/headers/helpers.d.ts
|
|
237
|
+
/**
|
|
238
|
+
* Extracts a header value from an object with case-insensitive lookup.
|
|
239
|
+
* This is useful for handling HTTP headers which can be case-insensitive per RFC 7230.
|
|
240
|
+
*
|
|
241
|
+
* When enabled via options, comma-separated header values (per RFC 9110) can be
|
|
242
|
+
* automatically split into an array. This is useful when multiple header values
|
|
243
|
+
* are combined into a single comma-separated string.
|
|
244
|
+
*
|
|
245
|
+
* @param headers The headers object to search in.
|
|
246
|
+
* @param name The header name to look for (case-insensitive).
|
|
247
|
+
* @param options Optional settings to control header value processing.
|
|
248
|
+
*
|
|
249
|
+
* @example
|
|
250
|
+
* ```typescript
|
|
251
|
+
* const headers = { authorization: "Bearer token123" };
|
|
252
|
+
* const auth = getHeader(headers, "Authorization"); // "Bearer token123"
|
|
253
|
+
* ```
|
|
254
|
+
*
|
|
255
|
+
* @example
|
|
256
|
+
* ```typescript
|
|
257
|
+
* // Comma-separated string can be split when enabled (per RFC 9110)
|
|
258
|
+
* const headers = { "Example-Field": "Foo, Bar" };
|
|
259
|
+
* const value = getHeader(headers, "Example-Field", { splitCommaSeparated: true }); // ["Foo", "Bar"]
|
|
260
|
+
* ```
|
|
261
|
+
*
|
|
262
|
+
* @see https://datatracker.ietf.org/doc/html/rfc7230 - HTTP/1.1 Message Syntax and Routing
|
|
263
|
+
* @see https://datatracker.ietf.org/doc/html/rfc9110#name-field-lines-and-combined-fi - HTTP Semantics: Field Lines and Combined Field Values
|
|
264
|
+
*/
|
|
265
|
+
declare function getHeader<T extends GetHeaderOptions | undefined = undefined>(headers: HttpHeaders, name: string, options?: T): GetHeaderReturn<T>;
|
|
266
|
+
/**
|
|
267
|
+
* Extracts the `__ow_headers` object from App Builder runtime action parameters.
|
|
268
|
+
*
|
|
269
|
+
* @param params The action parameters from App Builder runtime.
|
|
270
|
+
* @throws {CommerceSdkValidationError} If `__ow_headers` is missing or not an object.
|
|
271
|
+
*
|
|
272
|
+
* @example
|
|
273
|
+
* ```typescript
|
|
274
|
+
* export async function main(params) {
|
|
275
|
+
* const headers = getHeadersFromParams(params);
|
|
276
|
+
* const apiKey = headers["x-api-key"];
|
|
277
|
+
* }
|
|
278
|
+
* ```
|
|
279
|
+
*/
|
|
280
|
+
declare function getHeadersFromParams(params: RuntimeActionParams): HttpHeaders;
|
|
281
|
+
//#endregion
|
|
282
|
+
//#region source/headers/validation.d.ts
|
|
283
|
+
/**
|
|
284
|
+
* Returns an array of missing or empty headers using Valibot validation.
|
|
285
|
+
* Case-insensitive by default.
|
|
286
|
+
*
|
|
287
|
+
* Unlike {@link assertRequiredHeaders}, this function does not throw an error.
|
|
288
|
+
* Instead, it returns an array of header names that are missing or empty.
|
|
289
|
+
* This is useful when you need to check headers without immediately failing.
|
|
290
|
+
*
|
|
291
|
+
* @param headers The headers object to validate.
|
|
292
|
+
* @param requiredHeaders Array of required header names.
|
|
293
|
+
* @returns Array of header names that are missing or empty. Empty array if all headers are present and non-empty.
|
|
294
|
+
*
|
|
295
|
+
* @example
|
|
296
|
+
* ```typescript
|
|
297
|
+
* const headers = { "x-api-key": "key123" };
|
|
298
|
+
* const missing = getMissingOrEmptyHeaders(headers, ["x-api-key", "Authorization"]);
|
|
299
|
+
* // Returns: ["Authorization"]
|
|
300
|
+
* ```
|
|
301
|
+
*
|
|
302
|
+
* @example
|
|
303
|
+
* ```typescript
|
|
304
|
+
* const headers = { "x-api-key": "", "Authorization": "Bearer token" };
|
|
305
|
+
* const missing = getMissingOrEmptyHeaders(headers, ["x-api-key", "Authorization"]);
|
|
306
|
+
* // Returns: ["x-api-key"] (empty string is considered missing)
|
|
307
|
+
* ```
|
|
308
|
+
*/
|
|
309
|
+
declare function getMissingOrEmptyHeaders(headers: HttpHeaders, requiredHeaders: string[]): string[];
|
|
310
|
+
/**
|
|
311
|
+
* Validates that required headers are present and non-empty in the headers object.
|
|
312
|
+
* Performs case-insensitive validation with {@link getHeader}.
|
|
313
|
+
*
|
|
314
|
+
* @param headers The headers object to validate.
|
|
315
|
+
* @param requiredHeaders Array of required header names.
|
|
316
|
+
* @throws {CommerceSdkValidationError} If any required headers are missing or empty.
|
|
317
|
+
*
|
|
318
|
+
* @example
|
|
319
|
+
* ```typescript
|
|
320
|
+
* const headers = { "x-api-key": "key123", "Authorization": "Bearer token" };
|
|
321
|
+
* assertRequiredHeaders(headers, ["x-api-key", "Authorization"]);
|
|
322
|
+
* // Headers are validated, use getHeader() for safe access
|
|
323
|
+
* const apiKey = getHeader(headers, "x-api-key")!;
|
|
324
|
+
* ```
|
|
325
|
+
*
|
|
326
|
+
* @example
|
|
327
|
+
* ```typescript
|
|
328
|
+
* try {
|
|
329
|
+
* assertRequiredHeaders({}, ["x-api-key", "Authorization"]);
|
|
330
|
+
* } catch (error) {
|
|
331
|
+
* console.error(error.display());
|
|
332
|
+
* // "The headers object does not match the required headers (case-insensitive)"
|
|
333
|
+
* // ├── Schema validation error at x-api-key → Expected a non-empty string value
|
|
334
|
+
* // └── Schema validation error at Authorization → Expected a non-empty string value
|
|
335
|
+
* }
|
|
336
|
+
* ```
|
|
337
|
+
*/
|
|
338
|
+
declare function assertRequiredHeaders(headers: HttpHeaders, requiredHeaders: string[]): void;
|
|
339
|
+
//#endregion
|
|
340
|
+
export { type Authorization, type BasicAuthorization, type BearerAuthorization, type GenericAuthorization, type HttpHeaderAccessorMap, type HttpHeaderValue, type HttpHeaders, type OAuth1Authorization, type OAuth1Parameters, assertRequiredHeaders, createHeaderAccessor, getHeader, getHeadersFromParams, getMissingOrEmptyHeaders, isBasicAuth, isBearerAuth, isOAuth, parseAuthorization, parseBasicToken, parseBearerToken, parseOAuthToken };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as CommerceSdkValidationError}from"../error-LySQb5Bh.mjs";import{literal,nonEmpty,object,pipe,rawCheck,rawTransform,record,safeParse,string,trim,undefined as undefined$1,union}from"valibot";import camelcase from"camelcase";function getHeader(headers,name,options){let{splitCommaSeparated=!1}=options??{},value;if(Object.hasOwn(headers,name))value=headers[name];else{let lowerName=name.toLowerCase();for(let key in headers)if(Object.hasOwn(headers,key)&&key.toLowerCase()===lowerName){value=headers[key];break}}return splitCommaSeparated&&typeof value==`string`&&value.includes(`,`)&&(value=value.split(`,`).map(v=>v.trim())),value}function getHeadersFromParams(params){let parsed=safeParse(object({__ow_headers:record(string(),union([string(),undefined$1()]))}),params);if(!parsed.success)throw new CommerceSdkValidationError(`Missing __ow_headers in action params`,{issues:parsed.issues});return parsed.output.__ow_headers}function getMissingOrEmptyHeaders(headers,requiredHeaders){let normalized={};if(headers&&typeof headers==`object`&&!Array.isArray(headers))for(let key of Object.keys(headers)){let value=headers[key];value!=null&&(normalized[key.toLowerCase()]=value)}let parsed=safeParse(buildHeadersSchema(requiredHeaders.map(h=>literal(h))),normalized);if(parsed.success)return[];let lookup=new Map(requiredHeaders.map(h=>[h.toLowerCase(),h]));return parsed.issues.flatMap(issue=>{let key=issue.path?.[0]?.key,original=typeof key==`string`?lookup.get(key.toLowerCase()):null;return original?[original]:[]})}function buildHeadersSchema(requiredHeaders){let buildSchema=()=>pipe(string(`Expected a string value for the header`),rawCheck(({dataset,addIssue})=>{if(!dataset.typed)return;let value=dataset.value;if(value.trim()===``){addIssue({expected:`a non-empty string value`,received:`"${value}"`,message:`Header value cannot be empty or contain only whitespace`});return}if(value.includes(`,`)){let parts=value.split(`,`).map(part=>part.trim());parts.some(part=>part!==``)||addIssue({expected:`at least one non-empty value in comma-separated list`,received:`[${parts.join(`, `)}]`,message:`Header value contains only empty or whitespace values when split by comma`})}})),shape={};for(let schema of requiredHeaders)shape[schema.literal.toLowerCase()]=buildSchema();return object(shape)}function assertRequiredHeadersSchema(headers,requiredHeaders){let normalized={};if(headers&&typeof headers==`object`&&!Array.isArray(headers))for(let key of Object.keys(headers)){let value=headers[key];value!=null&&(normalized[key.toLowerCase()]=value)}let parsed=safeParse(buildHeadersSchema(requiredHeaders),normalized);if(!parsed.success)throw new CommerceSdkValidationError(`The headers object does not match the required headers (case-insensitive)`,{issues:parsed.issues})}function assertRequiredHeaders(headers,requiredHeaders){assertRequiredHeadersSchema(headers,requiredHeaders.map(header=>literal(header)))}function createHeaderAccessor(headers,requiredHeaders,options){assertRequiredHeaders(headers,requiredHeaders);let accessor={};for(let header of requiredHeaders){let camelKey=camelcase(header);accessor[camelKey]=getHeader(headers,header,options)}return accessor}function isBearerAuth(auth){return auth.scheme===`Bearer`}function isBasicAuth(auth){return auth.scheme===`Basic`}function isOAuth(auth){return auth.scheme===`OAuth`}function parseKeyValueParameters(parametersString){let params={},paramPattern=/(\w+)=(?:"([^"]*)"|([^,\s]+))/g,match=paramPattern.exec(parametersString);for(;match!==null;){let[,key,quotedValue,unquotedValue]=match;params[key]=quotedValue===void 0?unquotedValue:quotedValue,match=paramPattern.exec(parametersString)}return params}const authorizationSchema=pipe(string(`Expected a string value`),trim(),nonEmpty(`Expected a non-empty string value`),rawTransform(({dataset:{value:authorization},addIssue,NEVER})=>{let spaceIndex=authorization.indexOf(` `);return spaceIndex===-1?(addIssue({message:`Invalid Authorization header format`}),NEVER):{scheme:authorization.slice(0,spaceIndex),parameters:authorization.slice(spaceIndex+1).trim()}}));function parseAuthorization(authorization){let parsed=safeParse(authorizationSchema,authorization);if(!parsed.success)throw new CommerceSdkValidationError(`Invalid Authorization header format`,{issues:parsed.issues});let{scheme,parameters}=parsed.output;return scheme===`Bearer`?{scheme:`Bearer`,token:parameters}:scheme===`Basic`?{scheme:`Basic`,credentials:parameters}:scheme===`OAuth`?{scheme:`OAuth`,parameters:parseKeyValueParameters(parameters)}:{scheme,rawParameters:parameters,parseParameters:()=>parseKeyValueParameters(parameters)}}const bearerSchema=object({scheme:literal(`Bearer`)});function parseBearerToken(authorization){let auth=parseAuthorization(authorization),parsed=safeParse(bearerSchema,auth);if(!parsed.success)throw new CommerceSdkValidationError(`Authorization header must be a Bearer token`,{issues:parsed.issues});return auth}const basicSchema=object({scheme:literal(`Basic`)});function parseBasicToken(authorization){let auth=parseAuthorization(authorization),parsed=safeParse(basicSchema,auth);if(!parsed.success)throw new CommerceSdkValidationError(`Authorization header must be Basic authentication`,{issues:parsed.issues});return auth}const oauthSchema=object({scheme:literal(`OAuth`)});function parseOAuthToken(authorization){let auth=parseAuthorization(authorization),parsed=safeParse(oauthSchema,auth);if(!parsed.success)throw new CommerceSdkValidationError(`Authorization header must be OAuth`,{issues:parsed.issues});return auth}export{assertRequiredHeaders,createHeaderAccessor,getHeader,getHeadersFromParams,getMissingOrEmptyHeaders,isBasicAuth,isBearerAuth,isOAuth,parseAuthorization,parseBasicToken,parseBearerToken,parseOAuthToken};
|
|
@@ -0,0 +1,43 @@
|
|
|
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
|
+
//#region source/params/types.d.ts
|
|
18
|
+
/**
|
|
19
|
+
* Standard HTTP methods supported by Adobe I/O Runtime.
|
|
20
|
+
* These are the methods that can be used when invoking runtime actions via HTTP.
|
|
21
|
+
*/
|
|
22
|
+
type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
|
|
23
|
+
/**
|
|
24
|
+
* Lowercase HTTP method as sent by OpenWhisk/Adobe I/O Runtime.
|
|
25
|
+
* OpenWhisk sends methods in lowercase (e.g., "get", "post").
|
|
26
|
+
*/
|
|
27
|
+
type HttpMethodLowercase = Lowercase<HttpMethod>;
|
|
28
|
+
/** The type of the runtime action parameters. */
|
|
29
|
+
type RuntimeActionParams = {
|
|
30
|
+
/** If the runtime action is invoked via HTTP, this will be the headers of the request. */
|
|
31
|
+
__ow_headers?: Record<string, string | undefined>;
|
|
32
|
+
/** If the runtime action is invoked via HTTP, this will be the HTTP method of the request. */
|
|
33
|
+
__ow_method?: HttpMethodLowercase;
|
|
34
|
+
/** If the runtime action is invoked via HTTP, this will be the unmatched path of the request (matching stops after consuming the action extension) */
|
|
35
|
+
__ow_path?: string;
|
|
36
|
+
/** If the runtime action is invoked via HTTP, this will be the request body entity, as a base64-encoded string when its content is binary or JSON object/array, or as a plain string otherwise */
|
|
37
|
+
__ow_body?: string;
|
|
38
|
+
/** If the runtime action is invoked via HTTP, this will be the query parameters of the request, as an unparsed string. */
|
|
39
|
+
__ow_query?: string;
|
|
40
|
+
[key: string]: unknown;
|
|
41
|
+
};
|
|
42
|
+
//#endregion
|
|
43
|
+
export { nonEmpty as a, allNonEmpty as i, HttpMethodLowercase as n, RuntimeActionParams as r, HttpMethod as t };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
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};
|
|
@@ -36,7 +36,7 @@ type SuccessResponse<TBody extends BodyRecord = BodyRecord, THeaders extends Hea
|
|
|
36
36
|
* @template TBody - Response/error body properties
|
|
37
37
|
* @template THeaders - Custom response headers
|
|
38
38
|
*/
|
|
39
|
-
type ActionResponse<
|
|
39
|
+
type ActionResponse<TSuccessBody extends BodyRecord = BodyRecord, TErrorBody extends BodyRecordWithMessage = BodyRecordWithMessage, THeaders extends HeadersRecord = HeadersRecord> = SuccessResponse<TSuccessBody, THeaders> | ErrorResponse<TErrorBody, THeaders>;
|
|
40
40
|
/**
|
|
41
41
|
* Creates a standardized error response for runtime actions
|
|
42
42
|
* @see https://developer.adobe.com/app-builder/docs/guides/runtime_guides/creating-actions#unsuccessful-response
|
|
@@ -114,11 +114,15 @@ declare function buildSuccessResponse<TBody extends BodyRecord = BodyRecord, THe
|
|
|
114
114
|
//#region source/responses/presets.d.ts
|
|
115
115
|
declare const HTTP_OK = 200;
|
|
116
116
|
declare const HTTP_CREATED = 201;
|
|
117
|
+
declare const HTTP_ACCEPTED = 202;
|
|
117
118
|
declare const HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
|
|
119
|
+
declare const HTTP_NO_CONTENT = 204;
|
|
118
120
|
declare const HTTP_BAD_REQUEST = 400;
|
|
119
121
|
declare const HTTP_UNAUTHORIZED = 401;
|
|
120
122
|
declare const HTTP_FORBIDDEN = 403;
|
|
121
123
|
declare const HTTP_NOT_FOUND = 404;
|
|
124
|
+
declare const HTTP_METHOD_NOT_ALLOWED = 405;
|
|
125
|
+
declare const HTTP_CONFLICT = 409;
|
|
122
126
|
declare const HTTP_INTERNAL_SERVER_ERROR = 500;
|
|
123
127
|
/**
|
|
124
128
|
* Creates a success response with the HTTP status code 200.
|
|
@@ -136,6 +140,14 @@ declare const created: (payload?: string | {
|
|
|
136
140
|
body?: BodyRecord;
|
|
137
141
|
headers?: HeadersRecord;
|
|
138
142
|
}) => SuccessResponse<BodyRecord, HeadersRecord>;
|
|
143
|
+
/**
|
|
144
|
+
* Creates a success response with the HTTP status code 202.
|
|
145
|
+
* See {@link buildSuccessResponse} for details on the response payload.
|
|
146
|
+
*/
|
|
147
|
+
declare const accepted: (payload?: string | {
|
|
148
|
+
body?: BodyRecord;
|
|
149
|
+
headers?: HeadersRecord;
|
|
150
|
+
}) => SuccessResponse<BodyRecord, HeadersRecord>;
|
|
139
151
|
/**
|
|
140
152
|
* Creates a success response with the HTTP status code 203.
|
|
141
153
|
* See {@link buildSuccessResponse} for details on the response payload.
|
|
@@ -144,6 +156,11 @@ declare const nonAuthoritativeInformation: (payload?: string | {
|
|
|
144
156
|
body?: BodyRecord;
|
|
145
157
|
headers?: HeadersRecord;
|
|
146
158
|
}) => SuccessResponse<BodyRecord, HeadersRecord>;
|
|
159
|
+
/**
|
|
160
|
+
* Creates a success response with the HTTP status code 204 (No Content).
|
|
161
|
+
* This response has no body.
|
|
162
|
+
*/
|
|
163
|
+
declare const noContent: () => SuccessResponse<BodyRecord, HeadersRecord>;
|
|
147
164
|
/**
|
|
148
165
|
* Creates an error response with the HTTP status code 400.
|
|
149
166
|
* See {@link buildErrorResponse} for details on the response payload.
|
|
@@ -176,6 +193,22 @@ declare const notFound: (payload: string | {
|
|
|
176
193
|
body: BodyRecordWithMessage;
|
|
177
194
|
headers?: HeadersRecord;
|
|
178
195
|
}) => ErrorResponse<BodyRecordWithMessage, HeadersRecord>;
|
|
196
|
+
/**
|
|
197
|
+
* Creates an error response with the HTTP status code 405.
|
|
198
|
+
* See {@link buildErrorResponse} for details on the response payload.
|
|
199
|
+
*/
|
|
200
|
+
declare const methodNotAllowed: (payload: string | {
|
|
201
|
+
body: BodyRecordWithMessage;
|
|
202
|
+
headers?: HeadersRecord;
|
|
203
|
+
}) => ErrorResponse<BodyRecordWithMessage, HeadersRecord>;
|
|
204
|
+
/**
|
|
205
|
+
* Creates an error response with the HTTP status code 409.
|
|
206
|
+
* See {@link buildErrorResponse} for details on the response payload.
|
|
207
|
+
*/
|
|
208
|
+
declare const conflict: (payload: string | {
|
|
209
|
+
body: BodyRecordWithMessage;
|
|
210
|
+
headers?: HeadersRecord;
|
|
211
|
+
}) => ErrorResponse<BodyRecordWithMessage, HeadersRecord>;
|
|
179
212
|
/**
|
|
180
213
|
* Creates an error response with the HTTP status code 500.
|
|
181
214
|
* See {@link buildErrorResponse} for details on the response payload.
|
|
@@ -185,4 +218,4 @@ declare const internalServerError: (payload: string | {
|
|
|
185
218
|
headers?: HeadersRecord;
|
|
186
219
|
}) => ErrorResponse<BodyRecordWithMessage, HeadersRecord>;
|
|
187
220
|
//#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 };
|
|
221
|
+
export { type ActionResponse, type ErrorResponse, HTTP_ACCEPTED, HTTP_BAD_REQUEST, HTTP_CONFLICT, HTTP_CREATED, HTTP_FORBIDDEN, HTTP_INTERNAL_SERVER_ERROR, HTTP_METHOD_NOT_ALLOWED, HTTP_NON_AUTHORITATIVE_INFORMATION, HTTP_NOT_FOUND, HTTP_NO_CONTENT, HTTP_OK, HTTP_UNAUTHORIZED, type SuccessResponse, accepted, badRequest, buildErrorResponse, buildSuccessResponse, conflict, created, forbidden, internalServerError, methodNotAllowed, noContent, nonAuthoritativeInformation, notFound, ok, unauthorized };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
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_ACCEPTED=202,HTTP_NON_AUTHORITATIVE_INFORMATION=203,HTTP_NO_CONTENT=204,HTTP_BAD_REQUEST=400,HTTP_UNAUTHORIZED=401,HTTP_FORBIDDEN=403,HTTP_NOT_FOUND=404,HTTP_METHOD_NOT_ALLOWED=405,HTTP_CONFLICT=409,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),accepted=curryBuildSuccessResponse(202),nonAuthoritativeInformation=curryBuildSuccessResponse(203),noContent=()=>buildSuccessResponse(204),badRequest=curryBuildErrorResponse(400),unauthorized=curryBuildErrorResponse(401),forbidden=curryBuildErrorResponse(403),notFound=curryBuildErrorResponse(404),methodNotAllowed=curryBuildErrorResponse(405),conflict=curryBuildErrorResponse(409),internalServerError=curryBuildErrorResponse(500);export{HTTP_ACCEPTED,HTTP_BAD_REQUEST,HTTP_CONFLICT,HTTP_CREATED,HTTP_FORBIDDEN,HTTP_INTERNAL_SERVER_ERROR,HTTP_METHOD_NOT_ALLOWED,HTTP_NON_AUTHORITATIVE_INFORMATION,HTTP_NOT_FOUND,HTTP_NO_CONTENT,HTTP_OK,HTTP_UNAUTHORIZED,accepted,badRequest,buildErrorResponse,buildSuccessResponse,conflict,created,forbidden,internalServerError,methodNotAllowed,noContent,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.
|
|
5
|
+
"version": "0.6.1",
|
|
6
6
|
"private": false,
|
|
7
7
|
"engines": {
|
|
8
8
|
"node": ">=20 <=24"
|
|
@@ -27,14 +27,11 @@
|
|
|
27
27
|
"url": "git+https://github.com/adobe/aio-commerce-sdk.git",
|
|
28
28
|
"directory": "packages/aio-commerce-lib-core"
|
|
29
29
|
},
|
|
30
|
-
"main": "./dist/cjs/index.cjs",
|
|
31
|
-
"module": "./dist/es/index.js",
|
|
32
|
-
"types": "./dist/cjs/index.d.cts",
|
|
33
30
|
"exports": {
|
|
34
31
|
"./*": {
|
|
35
32
|
"import": {
|
|
36
|
-
"types": "./dist/es/*/index.d.
|
|
37
|
-
"default": "./dist/es/*/index.
|
|
33
|
+
"types": "./dist/es/*/index.d.mts",
|
|
34
|
+
"default": "./dist/es/*/index.mjs"
|
|
38
35
|
},
|
|
39
36
|
"require": {
|
|
40
37
|
"types": "./dist/cjs/*/index.d.cts",
|
|
@@ -43,6 +40,10 @@
|
|
|
43
40
|
},
|
|
44
41
|
"./package.json": "./package.json"
|
|
45
42
|
},
|
|
43
|
+
"imports": {
|
|
44
|
+
"#*": "./source/*.ts",
|
|
45
|
+
"#test/*": "./test/*.ts"
|
|
46
|
+
},
|
|
46
47
|
"files": [
|
|
47
48
|
"dist",
|
|
48
49
|
"package.json",
|
|
@@ -51,6 +52,7 @@
|
|
|
51
52
|
],
|
|
52
53
|
"dependencies": {
|
|
53
54
|
"ansis": "^4.1.0",
|
|
55
|
+
"camelcase": "^8.0.0",
|
|
54
56
|
"valibot": "^1.1.0"
|
|
55
57
|
},
|
|
56
58
|
"devDependencies": {
|
|
@@ -62,6 +64,8 @@
|
|
|
62
64
|
"sideEffects": false,
|
|
63
65
|
"scripts": {
|
|
64
66
|
"build": "tsdown",
|
|
67
|
+
"pack": "pnpm pack",
|
|
68
|
+
"publint": "publint",
|
|
65
69
|
"docs": "typedoc && prettier --write '**/*.md'",
|
|
66
70
|
"assist": "biome check --formatter-enabled=false --linter-enabled=false --assist-enabled=true --no-errors-on-unmatched",
|
|
67
71
|
"assist:apply": "biome check --write --formatter-enabled=false --linter-enabled=false --assist-enabled=true --no-errors-on-unmatched",
|
|
@@ -1,17 +0,0 @@
|
|
|
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 };
|
package/dist/es/params/index.js
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
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 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};
|
|
@@ -1,14 +0,0 @@
|
|
|
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};
|