@adobe/aio-commerce-lib-core 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -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/{es/params/index.d.ts → cjs/index-DmOFyyVg.d.cts} +11 -1
- 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 +10 -1
- 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-D8edNAiU.d.mts +27 -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} +10 -1
- package/dist/es/responses/index.mjs +1 -0
- package/package.json +9 -6
- package/dist/es/params/index.js +0 -14
- package/dist/es/responses/index.js +0 -14
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# @adobe/aio-commerce-lib-core
|
|
2
2
|
|
|
3
|
+
## 0.6.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#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
|
|
8
|
+
|
|
9
|
+
- [#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`
|
|
10
|
+
|
|
11
|
+
## 0.5.1
|
|
12
|
+
|
|
13
|
+
### Patch Changes
|
|
14
|
+
|
|
15
|
+
- [#143](https://github.com/adobe/aio-commerce-sdk/pull/143) [`f05b041`](https://github.com/adobe/aio-commerce-sdk/commit/f05b0413b06a4dea5579a1b16c293aaf8b64ffac) Thanks [@iivvaannxx](https://github.com/iivvaannxx)! - Add a new success response preset for HTTP 203 status code: `nonAuthoritativeInformation`
|
|
16
|
+
|
|
3
17
|
## 0.5.0
|
|
4
18
|
|
|
5
19
|
### Minor 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 { t as RuntimeActionParams } from "../index-DmOFyyVg.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 };
|
|
@@ -14,4 +14,14 @@ declare function nonEmpty(name: string, value: unknown): boolean;
|
|
|
14
14
|
*/
|
|
15
15
|
declare function allNonEmpty<const T extends string[]>(params: Record<string, unknown>, required: T): params is Record<string, unknown> & Record<T[number], unknown>;
|
|
16
16
|
//#endregion
|
|
17
|
-
|
|
17
|
+
//#region source/params/types.d.ts
|
|
18
|
+
/** The type of the runtime action parameters. */
|
|
19
|
+
type RuntimeActionParams = {
|
|
20
|
+
/** If the runtime action is invoked via HTTP, this will be the headers of the request. */
|
|
21
|
+
__ow_headers?: Record<string, string | undefined>;
|
|
22
|
+
/** If the runtime action is invoked via HTTP, this will be the HTTP method of the request. */
|
|
23
|
+
__ow_method?: string;
|
|
24
|
+
[key: string]: unknown;
|
|
25
|
+
};
|
|
26
|
+
//#endregion
|
|
27
|
+
export { allNonEmpty as n, nonEmpty as r, RuntimeActionParams 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 { n as allNonEmpty, r as nonEmpty, t as RuntimeActionParams } from "../index-DmOFyyVg.cjs";
|
|
2
|
+
export { 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_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),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_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.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_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;
|
|
@@ -114,6 +114,7 @@ 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_NON_AUTHORITATIVE_INFORMATION = 203;
|
|
117
118
|
declare const HTTP_BAD_REQUEST = 400;
|
|
118
119
|
declare const HTTP_UNAUTHORIZED = 401;
|
|
119
120
|
declare const HTTP_FORBIDDEN = 403;
|
|
@@ -135,6 +136,14 @@ declare const created: (payload?: string | {
|
|
|
135
136
|
body?: BodyRecord;
|
|
136
137
|
headers?: HeadersRecord;
|
|
137
138
|
}) => SuccessResponse<BodyRecord, HeadersRecord>;
|
|
139
|
+
/**
|
|
140
|
+
* Creates a success response with the HTTP status code 203.
|
|
141
|
+
* See {@link buildSuccessResponse} for details on the response payload.
|
|
142
|
+
*/
|
|
143
|
+
declare const nonAuthoritativeInformation: (payload?: string | {
|
|
144
|
+
body?: BodyRecord;
|
|
145
|
+
headers?: HeadersRecord;
|
|
146
|
+
}) => SuccessResponse<BodyRecord, HeadersRecord>;
|
|
138
147
|
/**
|
|
139
148
|
* Creates an error response with the HTTP status code 400.
|
|
140
149
|
* See {@link buildErrorResponse} for details on the response payload.
|
|
@@ -176,4 +185,4 @@ declare const internalServerError: (payload: string | {
|
|
|
176
185
|
headers?: HeadersRecord;
|
|
177
186
|
}) => ErrorResponse<BodyRecordWithMessage, HeadersRecord>;
|
|
178
187
|
//#endregion
|
|
179
|
-
export { type ActionResponse, type ErrorResponse, HTTP_BAD_REQUEST, HTTP_CREATED, HTTP_FORBIDDEN, HTTP_INTERNAL_SERVER_ERROR, HTTP_NOT_FOUND, HTTP_OK, HTTP_UNAUTHORIZED, type SuccessResponse, badRequest, buildErrorResponse, buildSuccessResponse, created, forbidden, internalServerError, notFound, ok, unauthorized };
|
|
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 };
|
|
@@ -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 { t as RuntimeActionParams } from "../index-D8edNAiU.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,27 @@
|
|
|
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
|
+
/** The type of the runtime action parameters. */
|
|
19
|
+
type RuntimeActionParams = {
|
|
20
|
+
/** If the runtime action is invoked via HTTP, this will be the headers of the request. */
|
|
21
|
+
__ow_headers?: Record<string, string | undefined>;
|
|
22
|
+
/** If the runtime action is invoked via HTTP, this will be the HTTP method of the request. */
|
|
23
|
+
__ow_method?: string;
|
|
24
|
+
[key: string]: unknown;
|
|
25
|
+
};
|
|
26
|
+
//#endregion
|
|
27
|
+
export { allNonEmpty as n, nonEmpty as r, RuntimeActionParams 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};
|
|
@@ -114,6 +114,7 @@ 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_NON_AUTHORITATIVE_INFORMATION = 203;
|
|
117
118
|
declare const HTTP_BAD_REQUEST = 400;
|
|
118
119
|
declare const HTTP_UNAUTHORIZED = 401;
|
|
119
120
|
declare const HTTP_FORBIDDEN = 403;
|
|
@@ -135,6 +136,14 @@ declare const created: (payload?: string | {
|
|
|
135
136
|
body?: BodyRecord;
|
|
136
137
|
headers?: HeadersRecord;
|
|
137
138
|
}) => SuccessResponse<BodyRecord, HeadersRecord>;
|
|
139
|
+
/**
|
|
140
|
+
* Creates a success response with the HTTP status code 203.
|
|
141
|
+
* See {@link buildSuccessResponse} for details on the response payload.
|
|
142
|
+
*/
|
|
143
|
+
declare const nonAuthoritativeInformation: (payload?: string | {
|
|
144
|
+
body?: BodyRecord;
|
|
145
|
+
headers?: HeadersRecord;
|
|
146
|
+
}) => SuccessResponse<BodyRecord, HeadersRecord>;
|
|
138
147
|
/**
|
|
139
148
|
* Creates an error response with the HTTP status code 400.
|
|
140
149
|
* See {@link buildErrorResponse} for details on the response payload.
|
|
@@ -176,4 +185,4 @@ declare const internalServerError: (payload: string | {
|
|
|
176
185
|
headers?: HeadersRecord;
|
|
177
186
|
}) => ErrorResponse<BodyRecordWithMessage, HeadersRecord>;
|
|
178
187
|
//#endregion
|
|
179
|
-
export { type ActionResponse, type ErrorResponse, HTTP_BAD_REQUEST, HTTP_CREATED, HTTP_FORBIDDEN, HTTP_INTERNAL_SERVER_ERROR, HTTP_NOT_FOUND, HTTP_OK, HTTP_UNAUTHORIZED, type SuccessResponse, badRequest, buildErrorResponse, buildSuccessResponse, created, forbidden, internalServerError, notFound, ok, unauthorized };
|
|
188
|
+
export { type ActionResponse, type ErrorResponse, HTTP_BAD_REQUEST, HTTP_CREATED, HTTP_FORBIDDEN, HTTP_INTERNAL_SERVER_ERROR, HTTP_NON_AUTHORITATIVE_INFORMATION, HTTP_NOT_FOUND, HTTP_OK, HTTP_UNAUTHORIZED, type SuccessResponse, badRequest, buildErrorResponse, buildSuccessResponse, created, forbidden, internalServerError, nonAuthoritativeInformation, notFound, ok, unauthorized };
|
|
@@ -0,0 +1 @@
|
|
|
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_NON_AUTHORITATIVE_INFORMATION=203,HTTP_BAD_REQUEST=400,HTTP_UNAUTHORIZED=401,HTTP_FORBIDDEN=403,HTTP_NOT_FOUND=404,HTTP_INTERNAL_SERVER_ERROR=500;function curryBuildSuccessResponse(code){return payload=>buildSuccessResponse(code,typeof payload==`string`?{body:{message:payload}}:payload)}function curryBuildErrorResponse(code){return payload=>buildErrorResponse(code,typeof payload==`string`?{body:{message:payload}}:payload)}const ok=curryBuildSuccessResponse(200),created=curryBuildSuccessResponse(201),nonAuthoritativeInformation=curryBuildSuccessResponse(203),badRequest=curryBuildErrorResponse(400),unauthorized=curryBuildErrorResponse(401),forbidden=curryBuildErrorResponse(403),notFound=curryBuildErrorResponse(404),internalServerError=curryBuildErrorResponse(500);export{HTTP_BAD_REQUEST,HTTP_CREATED,HTTP_FORBIDDEN,HTTP_INTERNAL_SERVER_ERROR,HTTP_NON_AUTHORITATIVE_INFORMATION,HTTP_NOT_FOUND,HTTP_OK,HTTP_UNAUTHORIZED,badRequest,buildErrorResponse,buildSuccessResponse,created,forbidden,internalServerError,nonAuthoritativeInformation,notFound,ok,unauthorized};
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@adobe/aio-commerce-lib-core",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"author": "Adobe Inc.",
|
|
5
|
-
"version": "0.
|
|
5
|
+
"version": "0.6.0",
|
|
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,7 @@
|
|
|
62
64
|
"sideEffects": false,
|
|
63
65
|
"scripts": {
|
|
64
66
|
"build": "tsdown",
|
|
67
|
+
"publint": "publint",
|
|
65
68
|
"docs": "typedoc && prettier --write '**/*.md'",
|
|
66
69
|
"assist": "biome check --formatter-enabled=false --linter-enabled=false --assist-enabled=true --no-errors-on-unmatched",
|
|
67
70
|
"assist:apply": "biome check --write --formatter-enabled=false --linter-enabled=false --assist-enabled=true --no-errors-on-unmatched",
|
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_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),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_NOT_FOUND,HTTP_OK,HTTP_UNAUTHORIZED,badRequest,buildErrorResponse,buildSuccessResponse,created,forbidden,internalServerError,notFound,ok,unauthorized};
|