@adobe/aio-commerce-lib-auth 0.8.0 → 1.0.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.
@@ -1 +1,750 @@
1
- const require_chunk=require(`./chunk-YD6SZpHm.cjs`);let _adobe_aio_commerce_lib_core_headers=require(`@adobe/aio-commerce-lib-core/headers`),valibot=require(`valibot`);valibot=require_chunk.n(valibot);let _adobe_aio_commerce_lib_core_error=require(`@adobe/aio-commerce-lib-core/error`),_adobe_aio_lib_ims=require(`@adobe/aio-lib-ims`);_adobe_aio_lib_ims=require_chunk.n(_adobe_aio_lib_ims);let crypto=require(`crypto`);crypto=require_chunk.n(crypto);let oauth_1_0a=require(`oauth-1.0a`);oauth_1_0a=require_chunk.n(oauth_1_0a);let _adobe_aio_commerce_lib_core_params=require(`@adobe/aio-commerce-lib-core/params`);function stringValueSchema(name){return valibot.string(`Expected a string value for '${name}'`)}function parseOrThrow(schema,input,message){let result=valibot.safeParse(schema,input);if(!result.success)throw new _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError(message??`Invalid input`,{issues:result.issues});return result.output}const imsAuthParameter=name=>(0,valibot.pipe)((0,valibot.string)(`Expected a string value for the IMS auth parameter ${name}`),(0,valibot.nonEmpty)(`Expected a non-empty string value for the IMS auth parameter ${name}`)),stringArray=(name,minimumLength)=>(0,valibot.pipe)((0,valibot.array)((0,valibot.string)(),`Expected a string array value for the IMS auth parameter ${name}`),(0,valibot.minLength)(minimumLength,`Expected at least ${minimumLength} items for the IMS auth parameter ${name}`)),StringArrayTransformSchema=name=>(0,valibot.pipe)((0,valibot.union)([stringArray(name,1),(0,valibot.pipe)((0,valibot.string)(),(0,valibot.rawTransform)(({dataset:{value:v},addIssue,NEVER})=>{if(v.startsWith(`[`)&&v.endsWith(`]`))try{let parsed=JSON.parse(v);return Array.isArray(parsed)?parsed:(addIssue({received:v,message:`Expected a valid JSON array for the IMS auth parameter ${name}: ${v}`}),NEVER)}catch(error){let errorMessage=error.message;return addIssue({received:v,message:`Expected a valid JSON array for the IMS auth parameter ${name}: ${errorMessage}`}),NEVER}return[v]}))]),stringArray(`value`,1)),ImsAuthEnvSchema=(0,valibot.picklist)([`prod`,`stage`]),ImsAuthParamsSchema=(0,valibot.object)({clientId:imsAuthParameter(`clientId`),clientSecrets:stringArray(`clientSecrets`,1),technicalAccountId:imsAuthParameter(`technicalAccountId`),technicalAccountEmail:(0,valibot.pipe)((0,valibot.string)(`Expected a string value for the IMS auth parameter technicalAccountEmail`),(0,valibot.email)(`Expected a valid email format for technicalAccountEmail`)),imsOrgId:imsAuthParameter(`imsOrgId`),environment:(0,valibot.pipe)((0,valibot.optional)(ImsAuthEnvSchema)),context:(0,valibot.pipe)((0,valibot.optional)((0,valibot.string)())),scopes:stringArray(`scopes`,1)});function __transformStringArray(name,value){if(value===void 0)return;let result=(0,valibot.safeParse)(StringArrayTransformSchema(name),value);if(!result.success)throw new _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError(`Invalid ImsAuthProvider configuration`,{issues:result.issues});return result.output}function __parseImsAuthParams(config){let result=(0,valibot.safeParse)(ImsAuthParamsSchema,config);if(!result.success)throw new _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError(`Invalid ImsAuthProvider configuration`,{issues:result.issues});return result.output}function assertImsAuthParams(config){__parseImsAuthParams(config)}function resolveImsAuthParams(params){return __parseImsAuthParams({clientId:params.AIO_COMMERCE_AUTH_IMS_CLIENT_ID,clientSecrets:__transformStringArray(`AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS`,params.AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS),technicalAccountId:params.AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_ID,technicalAccountEmail:params.AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_EMAIL,imsOrgId:params.AIO_COMMERCE_AUTH_IMS_ORG_ID,scopes:__transformStringArray(`AIO_COMMERCE_AUTH_IMS_SCOPES`,params.AIO_COMMERCE_AUTH_IMS_SCOPES),environment:params.AIO_COMMERCE_AUTH_IMS_ENVIRONMENT,context:params.AIO_COMMERCE_AUTH_IMS_CONTEXT})}function buildImsHeaders(accessToken,apiKey){let imsHeaders={Authorization:`Bearer ${accessToken}`};return apiKey&&(imsHeaders[`x-api-key`]=apiKey),imsHeaders}const IMS_AUTH_TOKEN_PARAM=`AIO_COMMERCE_AUTH_IMS_TOKEN`,IMS_AUTH_API_KEY_PARAM=`AIO_COMMERCE_AUTH_IMS_API_KEY`,ImsAuthParamsInputSchema=valibot.looseObject({[IMS_AUTH_TOKEN_PARAM]:stringValueSchema(IMS_AUTH_TOKEN_PARAM),[IMS_AUTH_API_KEY_PARAM]:valibot.optional(stringValueSchema(IMS_AUTH_API_KEY_PARAM))}),ForwardedImsAuthSourceSchema=valibot.variant(`from`,[valibot.object({from:valibot.literal(`headers`),headers:valibot.record(valibot.string(),valibot.optional(valibot.string()))}),valibot.object({from:valibot.literal(`getter`),getHeaders:valibot.custom(input=>typeof input==`function`,`Expected a function for getHeaders`)}),valibot.object({from:valibot.literal(`params`),params:ImsAuthParamsInputSchema})]);function getForwardedImsAuthProvider(source){let validatedSource=parseOrThrow(ForwardedImsAuthSourceSchema,source,`Invalid forwarded IMS auth source`);switch(validatedSource.from){case`headers`:{let{authorization}=(0,_adobe_aio_commerce_lib_core_headers.createHeaderAccessor)(validatedSource.headers,[`Authorization`]),apiKey=(0,_adobe_aio_commerce_lib_core_headers.getHeader)(validatedSource.headers,`x-api-key`),{token}=(0,_adobe_aio_commerce_lib_core_headers.parseBearerToken)(authorization);return{getAccessToken:()=>token,getHeaders:()=>buildImsHeaders(token,apiKey)}}case`getter`:return{getHeaders:validatedSource.getHeaders,getAccessToken:async()=>{let{token}=(0,_adobe_aio_commerce_lib_core_headers.parseBearerToken)((await validatedSource.getHeaders()).Authorization);return token}};case`params`:{let{params}=validatedSource,accessToken=params[IMS_AUTH_TOKEN_PARAM],apiKey=params[IMS_AUTH_API_KEY_PARAM];return{getAccessToken:()=>accessToken,getHeaders:()=>buildImsHeaders(accessToken,apiKey)}}}}function forwardImsAuthProviderFromRequest(params){return getForwardedImsAuthProvider({from:`headers`,headers:(0,_adobe_aio_commerce_lib_core_headers.getHeadersFromParams)(params)})}function forwardImsAuthProviderFromParams(params){return getForwardedImsAuthProvider({from:`params`,params:parseOrThrow(ImsAuthParamsInputSchema,params,`Missing AIO_COMMERCE_AUTH_IMS_TOKEN in params`)})}function forwardImsAuthProvider(params){try{return forwardImsAuthProviderFromParams(params)}catch{}try{return forwardImsAuthProviderFromRequest(params)}catch{}throw Error(`Can't forward IMS authentication from the given params. Make sure your params contain an AIO_COMMERCE_AUTH_IMS_TOKEN input or an Authorization header with an IMS token.`)}const{context,getToken}=_adobe_aio_lib_ims.default;function toImsAuthConfig(config){return{scopes:config.scopes,env:config?.environment??`prod`,context:config.context??`aio-commerce-lib-auth-creds`,client_id:config.clientId,client_secrets:config.clientSecrets,technical_account_id:config.technicalAccountId,technical_account_email:config.technicalAccountEmail,ims_org_id:config.imsOrgId}}function isImsAuthProvider(provider){return typeof provider==`object`&&!!provider&&`getAccessToken`in provider&&`getHeaders`in provider&&typeof provider.getAccessToken==`function`&&typeof provider.getHeaders==`function`}function getImsAuthProvider(authParams){let getAccessToken=async()=>{let imsAuthConfig=toImsAuthConfig(authParams);return await context.set(imsAuthConfig.context,imsAuthConfig),getToken(imsAuthConfig.context,{})};return{getAccessToken,getHeaders:async()=>buildImsHeaders(await getAccessToken(),authParams.clientId)}}const integrationAuthParameter=name=>(0,valibot.pipe)((0,valibot.string)(`Expected a string value for the Commerce Integration parameter ${name}`),(0,valibot.nonEmpty)(`Expected a non-empty string value for the Commerce Integration parameter ${name}`)),BaseUrlSchema=(0,valibot.pipe)((0,valibot.string)(`Expected a string for the Adobe Commerce endpoint`),(0,valibot.nonEmpty)(`Expected a non-empty string for the Adobe Commerce endpoint`),(0,valibot.url)(`Expected a valid url for the Adobe Commerce endpoint`)),UrlSchema=(0,valibot.pipe)((0,valibot.union)([BaseUrlSchema,(0,valibot.instance)(URL)]),(0,valibot.transform)(url=>url instanceof URL?url.toString():url)),IntegrationAuthParamsSchema=(0,valibot.nonOptional)((0,valibot.object)({consumerKey:integrationAuthParameter(`consumerKey`),consumerSecret:integrationAuthParameter(`consumerSecret`),accessToken:integrationAuthParameter(`accessToken`),accessTokenSecret:integrationAuthParameter(`accessTokenSecret`)}));function isIntegrationAuthProvider(provider){return typeof provider==`object`&&!!provider&&`getHeaders`in provider&&typeof provider.getHeaders==`function`}function getIntegrationAuthProvider(authParams){let oauth=new oauth_1_0a.default({consumer:{key:authParams.consumerKey,secret:authParams.consumerSecret},signature_method:`HMAC-SHA256`,hash_function:(baseString,key)=>crypto.default.createHmac(`sha256`,key).update(baseString).digest(`base64`)}),oauthToken={key:authParams.accessToken,secret:authParams.accessTokenSecret};return{getHeaders:(method,url)=>{let urlString=(0,valibot.parse)(UrlSchema,url);return oauth.toHeader(oauth.authorize({url:urlString,method},oauthToken))}}}function __parseIntegrationAuthParams(config){let result=(0,valibot.safeParse)(IntegrationAuthParamsSchema,config);if(!result.success)throw new _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError(`Invalid IntegrationAuthProvider configuration`,{issues:result.issues});return result.output}function assertIntegrationAuthParams(config){__parseIntegrationAuthParams(config)}function resolveIntegrationAuthParams(params){return __parseIntegrationAuthParams({consumerKey:params.AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_KEY,consumerSecret:params.AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_SECRET,accessToken:params.AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN,accessTokenSecret:params.AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN_SECRET})}const IMS_AUTH_PARAMS=[`AIO_COMMERCE_AUTH_IMS_CLIENT_ID`,`AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS`,`AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_ID`,`AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_EMAIL`,`AIO_COMMERCE_AUTH_IMS_ORG_ID`,`AIO_COMMERCE_AUTH_IMS_SCOPES`],INTEGRATION_AUTH_PARAMS=[`AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_KEY`,`AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_SECRET`,`AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN`,`AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN_SECRET`];function resolveAuthParams(params){if((0,_adobe_aio_commerce_lib_core_params.allNonEmpty)(params,IMS_AUTH_PARAMS))return{...resolveImsAuthParams(params),strategy:`ims`};if((0,_adobe_aio_commerce_lib_core_params.allNonEmpty)(params,INTEGRATION_AUTH_PARAMS))return{...resolveIntegrationAuthParams(params),strategy:`integration`};throw Error(`Can't resolve authentication options for the given params. Please provide either IMS options (${IMS_AUTH_PARAMS.join(`, `)}) or Commerce integration options (${INTEGRATION_AUTH_PARAMS.join(`, `)}).`)}exports.assertImsAuthParams=assertImsAuthParams,exports.assertIntegrationAuthParams=assertIntegrationAuthParams,exports.forwardImsAuthProvider=forwardImsAuthProvider,exports.getForwardedImsAuthProvider=getForwardedImsAuthProvider,exports.getImsAuthProvider=getImsAuthProvider,exports.getIntegrationAuthProvider=getIntegrationAuthProvider,exports.isImsAuthProvider=isImsAuthProvider,exports.isIntegrationAuthProvider=isIntegrationAuthProvider,exports.resolveAuthParams=resolveAuthParams;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_chunk = require('./chunk-C0xms8kb.cjs');
3
+ let _adobe_aio_commerce_lib_core_headers = require("@adobe/aio-commerce-lib-core/headers");
4
+ let valibot = require("valibot");
5
+ valibot = require_chunk.__toESM(valibot);
6
+ let _adobe_aio_commerce_lib_core_error = require("@adobe/aio-commerce-lib-core/error");
7
+ let _adobe_aio_lib_ims = require("@adobe/aio-lib-ims");
8
+ _adobe_aio_lib_ims = require_chunk.__toESM(_adobe_aio_lib_ims);
9
+ let crypto = require("crypto");
10
+ crypto = require_chunk.__toESM(crypto);
11
+ let oauth_1_0a = require("oauth-1.0a");
12
+ oauth_1_0a = require_chunk.__toESM(oauth_1_0a);
13
+ let _adobe_aio_commerce_lib_core_params = require("@adobe/aio-commerce-lib-core/params");
14
+
15
+ //#region ../../packages-private/common-utils/source/valibot/schemas.ts
16
+ /**
17
+ * A schema for a string value.
18
+ * @param name The name of the field this schema refers to.
19
+ */
20
+ function stringValueSchema(name) {
21
+ return valibot.string(`Expected a string value for '${name}'`);
22
+ }
23
+
24
+ //#endregion
25
+ //#region ../../packages-private/common-utils/source/valibot/utils.ts
26
+ /**
27
+ * Parses the input using the provided schema and throws a {@link CommerceSdkValidationError} error if the input is invalid.
28
+ * @param schema - The schema to use for parsing.
29
+ * @param input - The input to parse.
30
+ * @param message - Optional custom error message for the validation error.
31
+ */
32
+ function parseOrThrow(schema, input, message) {
33
+ const result = valibot.safeParse(schema, input);
34
+ if (!result.success) throw new _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError(message ?? "Invalid input", { issues: result.issues });
35
+ return result.output;
36
+ }
37
+
38
+ //#endregion
39
+ //#region source/lib/ims-auth/schema.ts
40
+ /**
41
+ * Creates a validation schema for a required IMS auth string parameter.
42
+ * @param name The name of the parameter for error messages.
43
+ * @returns A validation pipeline that ensures the parameter is a non-empty string.
44
+ */
45
+ const imsAuthParameter = (name) => (0, valibot.pipe)((0, valibot.string)(`Expected a string value for the IMS auth parameter ${name}`), (0, valibot.nonEmpty)(`Expected a non-empty string value for the IMS auth parameter ${name}`));
46
+ /**
47
+ * Creates a validation schema for an IMS auth string array parameter.
48
+ * @param name The name of the parameter for error messages.
49
+ * @param minimumLength The minimum length of the array.
50
+ * @returns A validation pipeline that ensures the parameter is an array of strings.
51
+ */
52
+ const stringArray = (name, minimumLength) => {
53
+ return (0, valibot.pipe)((0, valibot.array)((0, valibot.string)(), `Expected a string array value for the IMS auth parameter ${name}`), (0, valibot.minLength)(minimumLength, `Expected at least ${minimumLength} items for the IMS auth parameter ${name}`));
54
+ };
55
+ /**
56
+ * Schema for transforming a value that may be a JSON string array or a single string into an array.
57
+ * This schema handles the transformation of App Builder action inputs that may come as JSON strings.
58
+ */
59
+ const StringArrayTransformSchema = (name) => (0, valibot.pipe)((0, valibot.union)([stringArray(name, 1), (0, valibot.pipe)((0, valibot.string)(), (0, valibot.rawTransform)(({ dataset: { value: v }, addIssue, NEVER }) => {
60
+ if (v.startsWith("[") && v.endsWith("]")) try {
61
+ const parsed = JSON.parse(v);
62
+ if (!Array.isArray(parsed)) {
63
+ addIssue({
64
+ received: v,
65
+ message: `Expected a valid JSON array for the IMS auth parameter ${name}: ${v}`
66
+ });
67
+ return NEVER;
68
+ }
69
+ return parsed;
70
+ } catch (error) {
71
+ const errorMessage = error.message;
72
+ addIssue({
73
+ received: v,
74
+ message: `Expected a valid JSON array for the IMS auth parameter ${name}: ${errorMessage}`
75
+ });
76
+ return NEVER;
77
+ }
78
+ return [v];
79
+ }))]), stringArray("value", 1));
80
+ /** Validation schema for IMS auth environment values. */
81
+ const ImsAuthEnvSchema = (0, valibot.picklist)(["prod", "stage"]);
82
+ /** Defines the schema to validate the necessary parameters for the IMS auth service. */
83
+ const ImsAuthParamsSchema = (0, valibot.object)({
84
+ clientId: imsAuthParameter("clientId"),
85
+ clientSecrets: stringArray("clientSecrets", 1),
86
+ technicalAccountId: imsAuthParameter("technicalAccountId"),
87
+ technicalAccountEmail: (0, valibot.pipe)((0, valibot.string)("Expected a string value for the IMS auth parameter technicalAccountEmail"), (0, valibot.email)("Expected a valid email format for technicalAccountEmail")),
88
+ imsOrgId: imsAuthParameter("imsOrgId"),
89
+ environment: (0, valibot.pipe)((0, valibot.optional)(ImsAuthEnvSchema)),
90
+ context: (0, valibot.pipe)((0, valibot.optional)((0, valibot.string)())),
91
+ scopes: stringArray("scopes", 1)
92
+ });
93
+
94
+ //#endregion
95
+ //#region source/lib/ims-auth/utils.ts
96
+ /**
97
+ * Transforms a value using the string array transformation schema.
98
+ * @param value - The value to transform (may be a JSON string, single string, or array).
99
+ * @throws {CommerceSdkValidationError} If the transformation fails.
100
+ *
101
+ * @internal
102
+ */
103
+ function __transformStringArray(name, value) {
104
+ if (value === void 0) return;
105
+ const result = (0, valibot.safeParse)(StringArrayTransformSchema(name), value);
106
+ if (!result.success) throw new _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError("Invalid ImsAuthProvider configuration", { issues: result.issues });
107
+ return result.output;
108
+ }
109
+ /**
110
+ * Parses the provided configuration for an {@link ImsAuthProvider}.
111
+ * @param config - The configuration to parse.
112
+ * @throws {CommerceSdkValidationError} If the configuration is invalid.
113
+ *
114
+ * @internal
115
+ */
116
+ function __parseImsAuthParams(config) {
117
+ const result = (0, valibot.safeParse)(ImsAuthParamsSchema, config);
118
+ if (!result.success) throw new _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError("Invalid ImsAuthProvider configuration", { issues: result.issues });
119
+ return result.output;
120
+ }
121
+ /**
122
+ * Asserts the provided configuration for an {@link ImsAuthProvider}.
123
+ * @param config The configuration to validate.
124
+ * @throws {CommerceSdkValidationError} If the configuration is invalid.
125
+ * @example
126
+ * ```typescript
127
+ * const config = {
128
+ * clientId: "your-client-id",
129
+ * clientSecrets: ["your-client-secret"],
130
+ * technicalAccountId: "your-technical-account-id",
131
+ * technicalAccountEmail: "your-account@example.com",
132
+ * imsOrgId: "your-ims-org-id@AdobeOrg",
133
+ * scopes: ["AdobeID", "openid"],
134
+ * environment: "prod", // or "stage"
135
+ * context: "my-app-context"
136
+ * };
137
+ *
138
+ * // This will validate the config and throw if invalid
139
+ * assertImsAuthParams(config);
140
+ *```
141
+ * @example
142
+ * ```typescript
143
+ * // Example of a failing assert:
144
+ * try {
145
+ * assertImsAuthParams({
146
+ * clientId: "valid-client-id",
147
+ * // Missing required fields like clientSecrets, technicalAccountId, etc.
148
+ * });
149
+ * } catch (error) {
150
+ * console.error(error.message); // "Invalid ImsAuthProvider configuration"
151
+ * console.error(error.issues); // Array of validation issues
152
+ * }
153
+ * ```
154
+ */
155
+ function assertImsAuthParams(config) {
156
+ __parseImsAuthParams(config);
157
+ }
158
+ /**
159
+ * Resolves an {@link ImsAuthParams} from the given App Builder action inputs.
160
+ * @param params The App Builder action inputs to resolve the IMS authentication parameters from.
161
+ * @throws {CommerceSdkValidationError} If the parameters are invalid and cannot be resolved.
162
+ *
163
+ * @example
164
+ * ```typescript
165
+ * // Some App Builder runtime action that needs IMS authentication
166
+ * export function main(params) {
167
+ * const imsAuthProvider = getImsAuthProvider(resolveImsAuthParams(params));
168
+ *
169
+ * // Get headers for API requests
170
+ * const headers = await authProvider.getHeaders();
171
+ * const response = await fetch('https://api.adobe.io/some-endpoint', {
172
+ * headers: await authProvider.getHeaders()
173
+ * });
174
+ * }
175
+ * ```
176
+ */
177
+ function resolveImsAuthParams(params) {
178
+ return __parseImsAuthParams({
179
+ clientId: params.AIO_COMMERCE_AUTH_IMS_CLIENT_ID,
180
+ clientSecrets: __transformStringArray("AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS", params.AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS),
181
+ technicalAccountId: params.AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_ID,
182
+ technicalAccountEmail: params.AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_EMAIL,
183
+ imsOrgId: params.AIO_COMMERCE_AUTH_IMS_ORG_ID,
184
+ scopes: __transformStringArray("AIO_COMMERCE_AUTH_IMS_SCOPES", params.AIO_COMMERCE_AUTH_IMS_SCOPES),
185
+ environment: params.AIO_COMMERCE_AUTH_IMS_ENVIRONMENT,
186
+ context: params.AIO_COMMERCE_AUTH_IMS_CONTEXT
187
+ });
188
+ }
189
+ /**
190
+ * Shorthand to build IMS authentication headers.
191
+ * @param accessToken - The token to use in the Authorization header.
192
+ * @param apiKey - The API key to include in the x-api-key header (optional).
193
+ */
194
+ function buildImsHeaders(accessToken, apiKey) {
195
+ const imsHeaders = { Authorization: `Bearer ${accessToken}` };
196
+ if (apiKey) imsHeaders["x-api-key"] = apiKey;
197
+ return imsHeaders;
198
+ }
199
+
200
+ //#endregion
201
+ //#region source/lib/ims-auth/forwarding.ts
202
+ const IMS_AUTH_TOKEN_PARAM = "AIO_COMMERCE_AUTH_IMS_TOKEN";
203
+ const IMS_AUTH_API_KEY_PARAM = "AIO_COMMERCE_AUTH_IMS_API_KEY";
204
+ const ImsAuthParamsInputSchema = valibot.looseObject({
205
+ [IMS_AUTH_TOKEN_PARAM]: stringValueSchema(IMS_AUTH_TOKEN_PARAM),
206
+ [IMS_AUTH_API_KEY_PARAM]: valibot.optional(stringValueSchema(IMS_AUTH_API_KEY_PARAM))
207
+ });
208
+ const ForwardedImsAuthSourceSchema = valibot.variant("from", [
209
+ valibot.object({
210
+ from: valibot.literal("headers"),
211
+ headers: valibot.record(valibot.string(), valibot.optional(valibot.string()))
212
+ }),
213
+ valibot.object({
214
+ from: valibot.literal("getter"),
215
+ getHeaders: valibot.custom((input) => typeof input === "function", "Expected a function for getHeaders")
216
+ }),
217
+ valibot.object({
218
+ from: valibot.literal("params"),
219
+ params: ImsAuthParamsInputSchema
220
+ })
221
+ ]);
222
+ /**
223
+ * Creates an {@link ImsAuthProvider} by forwarding authentication credentials from various sources.
224
+ *
225
+ * @param source The source of the credentials to forward, as a {@link ForwardedImsAuthSource}.
226
+ * @returns An {@link ImsAuthProvider} instance that returns the forwarded access token and headers.
227
+ *
228
+ * @throws {CommerceSdkValidationError} If the source object is invalid.
229
+ * @throws {CommerceSdkValidationError} If `from: "headers"` is used and the `Authorization` header is missing.
230
+ * @throws {CommerceSdkValidationError} If `from: "headers"` is used and the `Authorization` header is not in Bearer token format.
231
+ * @throws {CommerceSdkValidationError} If `from: "params"` is used and `AIO_COMMERCE_AUTH_IMS_TOKEN` is missing or empty.
232
+ *
233
+ * @example
234
+ * ```typescript
235
+ * import { getForwardedImsAuthProvider } from "@adobe/aio-commerce-lib-auth";
236
+ *
237
+ * // From raw headers (e.g. from an HTTP request).
238
+ * const provider1 = getForwardedImsAuthProvider({
239
+ * from: "headers",
240
+ * headers: params.__ow_headers,
241
+ * });
242
+ *
243
+ * // From async getter (e.g. fetch from secret manager)
244
+ * const provider2 = getForwardedImsAuthProvider({
245
+ * from: "getter",
246
+ * getHeaders: async () => {
247
+ * const token = await secretManager.getSecret("ims-token");
248
+ * return { Authorization: `Bearer ${token}` };
249
+ * },
250
+ * });
251
+ *
252
+ * // From a params object (using AIO_COMMERCE_AUTH_IMS_TOKEN and AIO_COMMERCE_AUTH_IMS_API_KEY keys)
253
+ * const provider3 = getForwardedImsAuthProvider({
254
+ * from: "params",
255
+ * params: actionParams,
256
+ * });
257
+ *
258
+ * // Use the provider
259
+ * const token = await provider1.getAccessToken();
260
+ * const headers = await provider1.getHeaders();
261
+ * ```
262
+ */
263
+ function getForwardedImsAuthProvider(source) {
264
+ const validatedSource = parseOrThrow(ForwardedImsAuthSourceSchema, source, "Invalid forwarded IMS auth source");
265
+ switch (validatedSource.from) {
266
+ case "headers": {
267
+ const { authorization } = (0, _adobe_aio_commerce_lib_core_headers.createHeaderAccessor)(validatedSource.headers, ["Authorization"]);
268
+ const apiKey = (0, _adobe_aio_commerce_lib_core_headers.getHeader)(validatedSource.headers, "x-api-key");
269
+ const { token } = (0, _adobe_aio_commerce_lib_core_headers.parseBearerToken)(authorization);
270
+ return {
271
+ getAccessToken: () => token,
272
+ getHeaders: () => buildImsHeaders(token, apiKey)
273
+ };
274
+ }
275
+ case "getter": return {
276
+ getHeaders: validatedSource.getHeaders,
277
+ getAccessToken: async () => {
278
+ const { token } = (0, _adobe_aio_commerce_lib_core_headers.parseBearerToken)((await validatedSource.getHeaders()).Authorization);
279
+ return token;
280
+ }
281
+ };
282
+ case "params": {
283
+ const { params } = validatedSource;
284
+ const accessToken = params[IMS_AUTH_TOKEN_PARAM];
285
+ const apiKey = params[IMS_AUTH_API_KEY_PARAM];
286
+ return {
287
+ getAccessToken: () => accessToken,
288
+ getHeaders: () => buildImsHeaders(accessToken, apiKey)
289
+ };
290
+ }
291
+ }
292
+ }
293
+ /**
294
+ * Creates an {@link ImsAuthProvider} by forwarding authentication credentials from incoming
295
+ * runtime action request headers.
296
+ *
297
+ * This is a convenience wrapper around {@link getForwardedImsAuthProvider} for the common case
298
+ * of forwarding credentials from Adobe I/O Runtime action parameters.
299
+ *
300
+ * @param params The runtime action parameters containing the `__ow_headers` object with authentication headers.
301
+ * @returns An {@link ImsAuthProvider} instance that returns the forwarded access token and headers.
302
+ *
303
+ * @throws {Error} If the `Authorization` header is missing from the request headers.
304
+ * @throws {Error} If the `Authorization` header is not in the correct Bearer token format.
305
+ *
306
+ * @example
307
+ * ```typescript
308
+ * import { forwardImsAuthProviderFromRequest } from "@adobe/aio-commerce-lib-auth";
309
+ *
310
+ * // In an Adobe I/O Runtime action
311
+ * async function main(params) {
312
+ * // params.__ow_headers contains: { Authorization: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9..."}
313
+ *
314
+ * // Forward the authentication from the incoming request
315
+ * const authProvider = forwardImsAuthProviderFromRequest(params);
316
+ *
317
+ * // Get the forwarded access token
318
+ * const token = await authProvider.getAccessToken();
319
+ * console.log(token); // "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9..."
320
+ *
321
+ * // Get headers for downstream API requests
322
+ * const headers = await authProvider.getHeaders();
323
+ * console.log(headers);
324
+ * // {
325
+ * // Authorization: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
326
+ * // "x-api-key": "client-id-from-request" // Only if present in original request
327
+ * // }
328
+ *
329
+ * // Use the forwarded credentials in downstream API calls
330
+ * const response = await fetch('...', {
331
+ * headers: await authProvider.getHeaders()
332
+ * });
333
+ *
334
+ * return { statusCode: 200, body: await response.json() };
335
+ * }
336
+ * ```
337
+ */
338
+ function forwardImsAuthProviderFromRequest(params) {
339
+ return getForwardedImsAuthProvider({
340
+ from: "headers",
341
+ headers: (0, _adobe_aio_commerce_lib_core_headers.getHeadersFromParams)(params)
342
+ });
343
+ }
344
+ /**
345
+ * Creates an {@link ImsAuthProvider} by forwarding authentication credentials from a params object.
346
+ *
347
+ * This is a convenience wrapper around {@link getForwardedImsAuthProvider} for the common case
348
+ * of forwarding credentials from runtime action parameters. It reads:
349
+ * - `AIO_COMMERCE_AUTH_IMS_TOKEN` for the access token (required)
350
+ * - `AIO_COMMERCE_AUTH_IMS_API_KEY` for the API key (optional)
351
+ *
352
+ * @param params The params object containing the authentication credentials.
353
+ * @returns An {@link ImsAuthProvider} instance that returns the access token and headers from the params.
354
+ *
355
+ * @throws {CommerceSdkValidationError} If `AIO_COMMERCE_AUTH_IMS_TOKEN` is not set or is empty.
356
+ *
357
+ * @example
358
+ * ```typescript
359
+ * import { forwardImsAuthProviderFromParams } from "@adobe/aio-commerce-lib-auth";
360
+ *
361
+ * // In an Adobe I/O Runtime action
362
+ * async function main(params) {
363
+ * // params contains: { AIO_COMMERCE_AUTH_IMS_TOKEN: "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9..." }
364
+ * const authProvider = forwardImsAuthProviderFromParams(params);
365
+ *
366
+ * // Get the access token
367
+ * const token = await authProvider.getAccessToken();
368
+ *
369
+ * // Get headers for downstream API requests
370
+ * const headers = await authProvider.getHeaders();
371
+ * // {
372
+ * // Authorization: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
373
+ * // "x-api-key": "my-api-key" // Only if AIO_COMMERCE_AUTH_IMS_API_KEY is set
374
+ * // }
375
+ * }
376
+ * ```
377
+ */
378
+ function forwardImsAuthProviderFromParams(params) {
379
+ return getForwardedImsAuthProvider({
380
+ from: "params",
381
+ params: parseOrThrow(ImsAuthParamsInputSchema, params, "Missing AIO_COMMERCE_AUTH_IMS_TOKEN in params")
382
+ });
383
+ }
384
+ /**
385
+ * Creates an {@link ImsAuthProvider} by forwarding authentication credentials from runtime action parameters.
386
+ *
387
+ * This function automatically detects the source of credentials by trying multiple strategies in order:
388
+ * 1. **Params token** - Looks for `AIO_COMMERCE_AUTH_IMS_TOKEN` (and optionally `AIO_COMMERCE_AUTH_IMS_API_KEY`) in the params object
389
+ * 2. **HTTP headers** - Falls back to extracting the `Authorization` header from `__ow_headers`
390
+ *
391
+ * Use this function when building actions that receive authenticated requests and need to forward
392
+ * those credentials to downstream services (proxy pattern).
393
+ *
394
+ * @param params The runtime action parameters object. Can contain either:
395
+ * - `AIO_COMMERCE_AUTH_IMS_TOKEN` and optionally `AIO_COMMERCE_AUTH_IMS_API_KEY` for direct token forwarding
396
+ * - `__ow_headers` with an `Authorization` header for HTTP request forwarding
397
+ * @returns An {@link ImsAuthProvider} instance that returns the forwarded access token and headers.
398
+ *
399
+ * @throws {Error} If neither a valid token param nor Authorization header is found.
400
+ *
401
+ * @example
402
+ * ```typescript
403
+ * import { forwardImsAuthProvider } from "@adobe/aio-commerce-lib-auth";
404
+ *
405
+ * export async function main(params: Record<string, unknown>) {
406
+ * // Automatically detects credentials from params or headers
407
+ * const authProvider = forwardImsAuthProvider(params);
408
+ *
409
+ * // Get the access token
410
+ * const token = await authProvider.getAccessToken();
411
+ *
412
+ * // Get headers for downstream API requests
413
+ * const headers = await authProvider.getHeaders();
414
+ * // {
415
+ * // Authorization: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
416
+ * // "x-api-key": "my-api-key" // Only if available
417
+ * // }
418
+ *
419
+ * // Use the forwarded credentials in downstream API calls
420
+ * const response = await fetch("https://api.adobe.io/some-endpoint", {
421
+ * headers,
422
+ * });
423
+ *
424
+ * return { statusCode: 200, body: await response.json() };
425
+ * }
426
+ * ```
427
+ */
428
+ function forwardImsAuthProvider(params) {
429
+ try {
430
+ return forwardImsAuthProviderFromParams(params);
431
+ } catch {}
432
+ try {
433
+ return forwardImsAuthProviderFromRequest(params);
434
+ } catch {}
435
+ throw new Error("Can't forward IMS authentication from the given params. Make sure your params contain an AIO_COMMERCE_AUTH_IMS_TOKEN input or an Authorization header with an IMS token.");
436
+ }
437
+
438
+ //#endregion
439
+ //#region source/lib/ims-auth/provider.ts
440
+ const { context, getToken } = _adobe_aio_lib_ims.default;
441
+ /**
442
+ * Converts IMS auth configuration properties to snake_case format.
443
+ * @param config The IMS auth configuration with camelCase properties.
444
+ * @returns The configuration with snake_case properties.
445
+ */
446
+ function toImsAuthConfig(config) {
447
+ return {
448
+ scopes: config.scopes,
449
+ env: config?.environment ?? "prod",
450
+ context: config.context ?? "aio-commerce-lib-auth-creds",
451
+ client_id: config.clientId,
452
+ client_secrets: config.clientSecrets,
453
+ technical_account_id: config.technicalAccountId,
454
+ technical_account_email: config.technicalAccountEmail,
455
+ ims_org_id: config.imsOrgId
456
+ };
457
+ }
458
+ /**
459
+ * Type guard to check if a value is an ImsAuthProvider instance.
460
+ *
461
+ * @param provider The value to check.
462
+ * @returns `true` if the value is an ImsAuthProvider, `false` otherwise.
463
+ *
464
+ * @example
465
+ * ```typescript
466
+ * import { getImsAuthProvider, isImsAuthProvider } from "@adobe/aio-commerce-lib-auth";
467
+ *
468
+ * // Imagine you have an object that it's not strictly typed as ImsAuthProvider.
469
+ * const provider = getImsAuthProvider({ ... }) as unknown;
470
+ *
471
+ * if (isImsAuthProvider(provider)) {
472
+ * // TypeScript knows provider is ImsAuthProvider
473
+ * const token = await provider.getAccessToken();
474
+ * }
475
+ * ```
476
+ */
477
+ function isImsAuthProvider(provider) {
478
+ return typeof provider === "object" && provider !== null && "getAccessToken" in provider && "getHeaders" in provider && typeof provider.getAccessToken === "function" && typeof provider.getHeaders === "function";
479
+ }
480
+ /**
481
+ * Creates an {@link ImsAuthProvider} based on the provided configuration.
482
+ * @param authParams An {@link ImsAuthParams} parameter that contains the configuration for the {@link ImsAuthProvider}.
483
+ * @returns An {@link ImsAuthProvider} instance that can be used to get access token and auth headers.
484
+ * @example
485
+ * ```typescript
486
+ * const config = {
487
+ * clientId: "your-client-id",
488
+ * clientSecrets: ["your-client-secret"],
489
+ * technicalAccountId: "your-technical-account-id",
490
+ * technicalAccountEmail: "your-account@example.com",
491
+ * imsOrgId: "your-ims-org-id@AdobeOrg",
492
+ * scopes: ["AdobeID", "openid"],
493
+ * environment: "prod",
494
+ * context: "my-app-context"
495
+ * };
496
+ *
497
+ * const authProvider = getImsAuthProvider(config);
498
+ *
499
+ * // Get access token
500
+ * const token = await authProvider.getAccessToken();
501
+ * console.log(token); // "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9..."
502
+ *
503
+ * // Get headers for API requests
504
+ * const headers = await authProvider.getHeaders();
505
+ * console.log(headers);
506
+ * // {
507
+ * // Authorization: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
508
+ * // "x-api-key": "your-client-id"
509
+ * // }
510
+ *
511
+ * // Use headers in API calls
512
+ * const response = await fetch('https://api.adobe.io/some-endpoint', {
513
+ * headers: await authProvider.getHeaders()
514
+ * });
515
+ * ```
516
+ */
517
+ function getImsAuthProvider(authParams) {
518
+ const getAccessToken = async () => {
519
+ const imsAuthConfig = toImsAuthConfig(authParams);
520
+ await context.set(imsAuthConfig.context, imsAuthConfig);
521
+ return getToken(imsAuthConfig.context, {});
522
+ };
523
+ const getHeaders = async () => {
524
+ return buildImsHeaders(await getAccessToken(), authParams.clientId);
525
+ };
526
+ return {
527
+ getAccessToken,
528
+ getHeaders
529
+ };
530
+ }
531
+
532
+ //#endregion
533
+ //#region source/lib/integration-auth/schema.ts
534
+ /**
535
+ * Creates a validation schema for a required Commerce Integration string parameter.
536
+ * @param name The name of the parameter for error messages.
537
+ * @returns A validation pipeline that ensures the parameter is a non-empty string.
538
+ */
539
+ const integrationAuthParameter = (name) => (0, valibot.pipe)((0, valibot.string)(`Expected a string value for the Commerce Integration parameter ${name}`), (0, valibot.nonEmpty)(`Expected a non-empty string value for the Commerce Integration parameter ${name}`));
540
+ /** Validation schema for the Adobe Commerce endpoint base URL. */
541
+ const BaseUrlSchema = (0, valibot.pipe)((0, valibot.string)("Expected a string for the Adobe Commerce endpoint"), (0, valibot.nonEmpty)("Expected a non-empty string for the Adobe Commerce endpoint"), (0, valibot.url)("Expected a valid url for the Adobe Commerce endpoint"));
542
+ /** Validation schema that accepts either a URL string or URL instance and normalizes to string. */
543
+ const UrlSchema = (0, valibot.pipe)((0, valibot.union)([BaseUrlSchema, (0, valibot.instance)(URL)]), (0, valibot.transform)((url) => {
544
+ if (url instanceof URL) return url.toString();
545
+ return url;
546
+ }));
547
+ /**
548
+ * The schema for the Commerce Integration parameters.
549
+ * This is used to validate the parameters passed to the Commerce Integration provider.
550
+ */
551
+ const IntegrationAuthParamsSchema = (0, valibot.nonOptional)((0, valibot.object)({
552
+ consumerKey: integrationAuthParameter("consumerKey"),
553
+ consumerSecret: integrationAuthParameter("consumerSecret"),
554
+ accessToken: integrationAuthParameter("accessToken"),
555
+ accessTokenSecret: integrationAuthParameter("accessTokenSecret")
556
+ }));
557
+
558
+ //#endregion
559
+ //#region source/lib/integration-auth/provider.ts
560
+ /**
561
+ * Type guard to check if a value is an IntegrationAuthProvider instance.
562
+ *
563
+ * @param provider The value to check.
564
+ * @returns `true` if the value is an IntegrationAuthProvider, `false` otherwise.
565
+ *
566
+ * @example
567
+ * ```typescript
568
+ * import { getIntegrationAuthProvider, isIntegrationAuthProvider } from "@adobe/aio-commerce-lib-auth";
569
+ *
570
+ * // Imagine you have an object that it's not strictly typed as IntegrationAuthProvider.
571
+ * const provider = getIntegrationAuthProvider({ ... }) as unknown;
572
+ *
573
+ * if (isIntegrationAuthProvider(provider)) {
574
+ * // TypeScript knows provider is IntegrationAuthProvider
575
+ * const headers = provider.getHeaders("GET", "https://api.example.com");
576
+ * }
577
+ * ```
578
+ */
579
+ function isIntegrationAuthProvider(provider) {
580
+ return typeof provider === "object" && provider !== null && "getHeaders" in provider && typeof provider.getHeaders === "function";
581
+ }
582
+ /**
583
+ * Creates an {@link IntegrationAuthProvider} based on the provided configuration.
584
+ * @param authParams The configuration for the integration.
585
+ * @returns An {@link IntegrationAuthProvider} instance that can be used to get auth headers.
586
+ * @example
587
+ * ```typescript
588
+ * const config = {
589
+ * consumerKey: "your-consumer-key",
590
+ * consumerSecret: "your-consumer-secret",
591
+ * accessToken: "your-access-token",
592
+ * accessTokenSecret: "your-access-token-secret"
593
+ * };
594
+ *
595
+ * const authProvider = getIntegrationAuthProvider(config);
596
+ *
597
+ * // Get OAuth headers for a REST API call
598
+ * const headers = authProvider.getHeaders("GET", "https://your-store.com/rest/V1/products");
599
+ * console.log(headers); // { Authorization: "OAuth oauth_consumer_key=..., oauth_signature=..." }
600
+ *
601
+ * // Can also be used with URL objects
602
+ * const url = new URL("https://your-store.com/rest/V1/customers");
603
+ * const postHeaders = authProvider.getHeaders("POST", url);
604
+ * ```
605
+ */
606
+ function getIntegrationAuthProvider(authParams) {
607
+ const oauth = new oauth_1_0a.default({
608
+ consumer: {
609
+ key: authParams.consumerKey,
610
+ secret: authParams.consumerSecret
611
+ },
612
+ signature_method: "HMAC-SHA256",
613
+ hash_function: (baseString, key) => crypto.default.createHmac("sha256", key).update(baseString).digest("base64")
614
+ });
615
+ const oauthToken = {
616
+ key: authParams.accessToken,
617
+ secret: authParams.accessTokenSecret
618
+ };
619
+ return { getHeaders: (method, url) => {
620
+ const urlString = (0, valibot.parse)(UrlSchema, url);
621
+ return oauth.toHeader(oauth.authorize({
622
+ url: urlString,
623
+ method
624
+ }, oauthToken));
625
+ } };
626
+ }
627
+
628
+ //#endregion
629
+ //#region source/lib/integration-auth/utils.ts
630
+ /**
631
+ * Parses the provided configuration for an {@link IntegrationAuthProvider}.
632
+ * @param config - The configuration to parse.
633
+ * @throws {CommerceSdkValidationError} If the configuration is invalid.
634
+ *
635
+ * @internal
636
+ */
637
+ function __parseIntegrationAuthParams(config) {
638
+ const result = (0, valibot.safeParse)(IntegrationAuthParamsSchema, config);
639
+ if (!result.success) throw new _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError("Invalid IntegrationAuthProvider configuration", { issues: result.issues });
640
+ return result.output;
641
+ }
642
+ /**
643
+ * Asserts the provided configuration for an Adobe Commerce {@link IntegrationAuthProvider}.
644
+ * @param config The configuration to validate.
645
+ * @throws {CommerceSdkValidationError} If the configuration is invalid.
646
+ * @example
647
+ * ```typescript
648
+ * const config = {
649
+ * consumerKey: "your-consumer-key",
650
+ * consumerSecret: "your-consumer-secret",
651
+ * accessToken: "your-access-token",
652
+ * accessTokenSecret: "your-access-token-secret"
653
+ * };
654
+ *
655
+ * // This will validate the config and throw if invalid
656
+ * assertIntegrationAuthParams(config);
657
+ * ```
658
+ * @example
659
+ * ```typescript
660
+ * // Example of a failing assert:
661
+ * try {
662
+ * assertIntegrationAuthParams({
663
+ * consumerKey: "valid-consumer-key",
664
+ * // Missing required fields like consumerSecret, accessToken, accessTokenSecret
665
+ * });
666
+ * } catch (error) {
667
+ * console.error(error.message); // "Invalid IntegrationAuthProvider configuration"
668
+ * console.error(error.issues); // Array of validation issues
669
+ * }
670
+ * ```
671
+ */
672
+ function assertIntegrationAuthParams(config) {
673
+ __parseIntegrationAuthParams(config);
674
+ }
675
+ /**
676
+ * Resolves an {@link IntegrationAuthParams} from the given App Builder action inputs.
677
+ * @param params The App Builder action inputs to resolve the Integration authentication parameters from.
678
+ * @throws {CommerceSdkValidationError} If the parameters are invalid and cannot be resolved.
679
+ *
680
+ * @example
681
+ * ```typescript
682
+ * export function main(params) {
683
+ * const resolvedParams = resolveIntegrationAuthParams(params);
684
+ * console.log(resolvedParams); // { consumerKey: "your-consumer-key", consumerSecret: "your-consumer-secret", accessToken: "your-access-token", accessTokenSecret: "your-access-token-secret" }
685
+ * }
686
+ * ```
687
+ */
688
+ function resolveIntegrationAuthParams(params) {
689
+ return __parseIntegrationAuthParams({
690
+ consumerKey: params.AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_KEY,
691
+ consumerSecret: params.AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_SECRET,
692
+ accessToken: params.AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN,
693
+ accessTokenSecret: params.AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN_SECRET
694
+ });
695
+ }
696
+
697
+ //#endregion
698
+ //#region source/lib/utils.ts
699
+ const IMS_AUTH_PARAMS = [
700
+ "AIO_COMMERCE_AUTH_IMS_CLIENT_ID",
701
+ "AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS",
702
+ "AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_ID",
703
+ "AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_EMAIL",
704
+ "AIO_COMMERCE_AUTH_IMS_ORG_ID",
705
+ "AIO_COMMERCE_AUTH_IMS_SCOPES"
706
+ ];
707
+ const INTEGRATION_AUTH_PARAMS = [
708
+ "AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_KEY",
709
+ "AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_SECRET",
710
+ "AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN",
711
+ "AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN_SECRET"
712
+ ];
713
+ /**
714
+ * Automatically detects and resolves authentication parameters from App Builder action inputs.
715
+ * Attempts to resolve IMS authentication first, then falls back to Integration authentication.
716
+ *
717
+ * @param params The App Builder action inputs containing authentication parameters.
718
+ * @throws {CommerceSdkValidationError} If the parameters are invalid.
719
+ * @throws {Error} If neither IMS nor Integration authentication parameters can be resolved.
720
+ * @example
721
+ * ```typescript
722
+ * // Automatic detection (will use IMS if IMS params are present, otherwise Integration)
723
+ * export function main(params) {
724
+ * const authProvider = resolveAuthParams(params);
725
+ * console.log(authProvider.strategy); // "ims" or "integration"
726
+ * }
727
+ * ```
728
+ */
729
+ function resolveAuthParams(params) {
730
+ if ((0, _adobe_aio_commerce_lib_core_params.allNonEmpty)(params, IMS_AUTH_PARAMS)) return {
731
+ ...resolveImsAuthParams(params),
732
+ strategy: "ims"
733
+ };
734
+ if ((0, _adobe_aio_commerce_lib_core_params.allNonEmpty)(params, INTEGRATION_AUTH_PARAMS)) return {
735
+ ...resolveIntegrationAuthParams(params),
736
+ strategy: "integration"
737
+ };
738
+ throw new Error(`Can't resolve authentication options for the given params. Please provide either IMS options (${IMS_AUTH_PARAMS.join(", ")}) or Commerce integration options (${INTEGRATION_AUTH_PARAMS.join(", ")}).`);
739
+ }
740
+
741
+ //#endregion
742
+ exports.assertImsAuthParams = assertImsAuthParams;
743
+ exports.assertIntegrationAuthParams = assertIntegrationAuthParams;
744
+ exports.forwardImsAuthProvider = forwardImsAuthProvider;
745
+ exports.getForwardedImsAuthProvider = getForwardedImsAuthProvider;
746
+ exports.getImsAuthProvider = getImsAuthProvider;
747
+ exports.getIntegrationAuthProvider = getIntegrationAuthProvider;
748
+ exports.isImsAuthProvider = isImsAuthProvider;
749
+ exports.isIntegrationAuthProvider = isIntegrationAuthProvider;
750
+ exports.resolveAuthParams = resolveAuthParams;