@adobe/aio-commerce-lib-core 0.6.1 → 1.1.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,449 @@
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};
1
+ /**
2
+ * @license
3
+ *
4
+ * Copyright 2026 Adobe. All rights reserved.
5
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License. You may obtain a copy
7
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
8
+ *
9
+ * Unless required by applicable law or agreed to in writing, software distributed under
10
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
11
+ * OF ANY KIND, either express or implied. See the License for the specific language
12
+ * governing permissions and limitations under the License.
13
+ */
14
+
15
+ import { t as CommerceSdkValidationError } from "../error-dCuAZfGs.mjs";
16
+ import { literal, nonEmpty, object, pipe, rawCheck, rawTransform, record, safeParse, string, trim, undefined as undefined$1, union } from "valibot";
17
+ import camelcase from "camelcase";
18
+
19
+ //#region source/headers/helpers.ts
20
+ /**
21
+ * Extracts a header value from an object with case-insensitive lookup.
22
+ * This is useful for handling HTTP headers which can be case-insensitive per RFC 7230.
23
+ *
24
+ * When enabled via options, comma-separated header values (per RFC 9110) can be
25
+ * automatically split into an array. This is useful when multiple header values
26
+ * are combined into a single comma-separated string.
27
+ *
28
+ * @param headers The headers object to search in.
29
+ * @param name The header name to look for (case-insensitive).
30
+ * @param options Optional settings to control header value processing.
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * const headers = { authorization: "Bearer token123" };
35
+ * const auth = getHeader(headers, "Authorization"); // "Bearer token123"
36
+ * ```
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * // Comma-separated string can be split when enabled (per RFC 9110)
41
+ * const headers = { "Example-Field": "Foo, Bar" };
42
+ * const value = getHeader(headers, "Example-Field", { splitCommaSeparated: true }); // ["Foo", "Bar"]
43
+ * ```
44
+ *
45
+ * @see https://datatracker.ietf.org/doc/html/rfc7230 - HTTP/1.1 Message Syntax and Routing
46
+ * @see https://datatracker.ietf.org/doc/html/rfc9110#name-field-lines-and-combined-fi - HTTP Semantics: Field Lines and Combined Field Values
47
+ */
48
+ function getHeader(headers, name, options) {
49
+ const { splitCommaSeparated = false } = options ?? {};
50
+ let value;
51
+ if (Object.hasOwn(headers, name)) value = headers[name];
52
+ else {
53
+ const lowerName = name.toLowerCase();
54
+ for (const key in headers) if (Object.hasOwn(headers, key) && key.toLowerCase() === lowerName) {
55
+ value = headers[key];
56
+ break;
57
+ }
58
+ }
59
+ if (splitCommaSeparated && typeof value === "string" && value.includes(",")) value = value.split(",").map((v) => v.trim());
60
+ return value;
61
+ }
62
+ /**
63
+ * Extracts the `__ow_headers` object from App Builder runtime action parameters.
64
+ *
65
+ * @param params The action parameters from App Builder runtime.
66
+ * @throws {CommerceSdkValidationError} If `__ow_headers` is missing or not an object.
67
+ *
68
+ * @example
69
+ * ```typescript
70
+ * export async function main(params) {
71
+ * const headers = getHeadersFromParams(params);
72
+ * const apiKey = headers["x-api-key"];
73
+ * }
74
+ * ```
75
+ */
76
+ function getHeadersFromParams(params) {
77
+ const parsed = safeParse(object({ __ow_headers: record(string(), union([string(), undefined$1()])) }), params);
78
+ if (!parsed.success) throw new CommerceSdkValidationError("Missing __ow_headers in action params", { issues: parsed.issues });
79
+ return parsed.output.__ow_headers;
80
+ }
81
+
82
+ //#endregion
83
+ //#region source/headers/validation.ts
84
+ /**
85
+ * Returns an array of missing or empty headers using Valibot validation.
86
+ * Case-insensitive by default.
87
+ *
88
+ * Unlike {@link assertRequiredHeaders}, this function does not throw an error.
89
+ * Instead, it returns an array of header names that are missing or empty.
90
+ * This is useful when you need to check headers without immediately failing.
91
+ *
92
+ * @param headers The headers object to validate.
93
+ * @param requiredHeaders Array of required header names.
94
+ * @returns Array of header names that are missing or empty. Empty array if all headers are present and non-empty.
95
+ *
96
+ * @example
97
+ * ```typescript
98
+ * const headers = { "x-api-key": "key123" };
99
+ * const missing = getMissingOrEmptyHeaders(headers, ["x-api-key", "Authorization"]);
100
+ * // Returns: ["Authorization"]
101
+ * ```
102
+ *
103
+ * @example
104
+ * ```typescript
105
+ * const headers = { "x-api-key": "", "Authorization": "Bearer token" };
106
+ * const missing = getMissingOrEmptyHeaders(headers, ["x-api-key", "Authorization"]);
107
+ * // Returns: ["x-api-key"] (empty string is considered missing)
108
+ * ```
109
+ */
110
+ function getMissingOrEmptyHeaders(headers, requiredHeaders) {
111
+ const normalized = {};
112
+ if (headers && typeof headers === "object" && !Array.isArray(headers)) for (const key of Object.keys(headers)) {
113
+ const value = headers[key];
114
+ if (value !== void 0 && value !== null) normalized[key.toLowerCase()] = value;
115
+ }
116
+ const parsed = safeParse(buildHeadersSchema(requiredHeaders.map((h) => literal(h))), normalized);
117
+ if (parsed.success) return [];
118
+ const lookup = new Map(requiredHeaders.map((h) => [h.toLowerCase(), h]));
119
+ return parsed.issues.flatMap((issue) => {
120
+ const key = issue.path?.[0]?.key;
121
+ const original = typeof key === "string" ? lookup.get(key.toLowerCase()) : null;
122
+ return original ? [original] : [];
123
+ });
124
+ }
125
+ /**
126
+ * Builds a Valibot schema that checks:
127
+ * - Required headers exist (case-insensitive)
128
+ * - Each required header has a non-empty string value
129
+ */
130
+ function buildHeadersSchema(requiredHeaders) {
131
+ const buildSchema = () => pipe(string("Expected a string value for the header"), rawCheck(({ dataset, addIssue }) => {
132
+ if (!dataset.typed) return;
133
+ const value = dataset.value;
134
+ if (value.trim() === "") {
135
+ addIssue({
136
+ expected: "a non-empty string value",
137
+ received: `"${value}"`,
138
+ message: "Header value cannot be empty or contain only whitespace"
139
+ });
140
+ return;
141
+ }
142
+ if (value.includes(",")) {
143
+ const parts = value.split(",").map((part) => part.trim());
144
+ if (!parts.some((part) => part !== "")) addIssue({
145
+ expected: "at least one non-empty value in comma-separated list",
146
+ received: `[${parts.join(", ")}]`,
147
+ message: "Header value contains only empty or whitespace values when split by comma"
148
+ });
149
+ }
150
+ }));
151
+ const shape = {};
152
+ for (const schema of requiredHeaders) shape[schema.literal.toLowerCase()] = buildSchema();
153
+ return object(shape);
154
+ }
155
+ /**
156
+ * Validates that required headers are present in the headers object.
157
+ * Case-insensitive by default (HTTP standard).
158
+ *
159
+ * This is an advanced validation function that accepts Valibot `LiteralSchema` objects
160
+ * instead of plain strings. Use {@link assertRequiredHeaders} for the simpler string-based API.
161
+ *
162
+ * @param headers The headers object to validate.
163
+ * @param requiredHeaders Array of required header names as Valibot `LiteralSchema` objects.
164
+ * @throws {CommerceSdkValidationError} If validation fails.
165
+ *
166
+ * @example
167
+ * ```typescript
168
+ * import { literal } from "valibot";
169
+ * import { assertRequiredHeadersSchema } from "@adobe/aio-commerce-lib-core/headers";
170
+ *
171
+ * const headers = getHeadersFromParams(params);
172
+ * assertRequiredHeadersSchema(headers, [
173
+ * literal("x-api-key"),
174
+ * literal("Authorization"),
175
+ * ]);
176
+ * ```
177
+ */
178
+ function assertRequiredHeadersSchema(headers, requiredHeaders) {
179
+ const normalized = {};
180
+ if (headers && typeof headers === "object" && !Array.isArray(headers)) for (const key of Object.keys(headers)) {
181
+ const value = headers[key];
182
+ if (value !== void 0 && value !== null) normalized[key.toLowerCase()] = value;
183
+ }
184
+ const parsed = safeParse(buildHeadersSchema(requiredHeaders), normalized);
185
+ if (!parsed.success) throw new CommerceSdkValidationError("The headers object does not match the required headers (case-insensitive)", { issues: parsed.issues });
186
+ }
187
+ /**
188
+ * Validates that required headers are present and non-empty in the headers object.
189
+ * Performs case-insensitive validation with {@link getHeader}.
190
+ *
191
+ * @param headers The headers object to validate.
192
+ * @param requiredHeaders Array of required header names.
193
+ * @throws {CommerceSdkValidationError} If any required headers are missing or empty.
194
+ *
195
+ * @example
196
+ * ```typescript
197
+ * const headers = { "x-api-key": "key123", "Authorization": "Bearer token" };
198
+ * assertRequiredHeaders(headers, ["x-api-key", "Authorization"]);
199
+ * // Headers are validated, use getHeader() for safe access
200
+ * const apiKey = getHeader(headers, "x-api-key")!;
201
+ * ```
202
+ *
203
+ * @example
204
+ * ```typescript
205
+ * try {
206
+ * assertRequiredHeaders({}, ["x-api-key", "Authorization"]);
207
+ * } catch (error) {
208
+ * console.error(error.display());
209
+ * // "The headers object does not match the required headers (case-insensitive)"
210
+ * // ├── Schema validation error at x-api-key → Expected a non-empty string value
211
+ * // └── Schema validation error at Authorization → Expected a non-empty string value
212
+ * }
213
+ * ```
214
+ */
215
+ function assertRequiredHeaders(headers, requiredHeaders) {
216
+ assertRequiredHeadersSchema(headers, requiredHeaders.map((header) => literal(header)));
217
+ }
218
+
219
+ //#endregion
220
+ //#region source/headers/accessor.ts
221
+ const LEADING_UNDERSCORES = /^_+/;
222
+ /**
223
+ * Converts a header name to a camelCase key aligned with `type-fest`'s `CamelCase` type.
224
+ *
225
+ * `camelcase` v9+ preserves leading underscores (e.g. `_foo_bar` → `_fooBar`), but
226
+ * `type-fest`'s `CamelCase` — used by `HttpHeaderAccessorMap` — drops them
227
+ * (e.g. `_foo_bar` → `fooBar`). Without stripping them first, runtime keys would diverge
228
+ * from the inferred TypeScript type.
229
+ *
230
+ * @remarks This function must be removed and replaced with a bare `camelcase(header)` call
231
+ * once the two helpers agree on leading-underscore handling. That cleanup is a breaking
232
+ * change and must land in a major release.
233
+ */
234
+ function toHeaderCamelKey(header) {
235
+ return camelcase(header.replace(LEADING_UNDERSCORES, ""));
236
+ }
237
+ /**
238
+ * Creates a type-safe header accessor object with validated required headers.
239
+ * Header names are normalized to camelCase for consistent access.
240
+ *
241
+ * @param headers The headers object from runtime params.
242
+ * @param requiredHeaders Array of required header names.
243
+ * @param options Optional settings to control header value processing (e.g., `splitCommaSeparated`).
244
+ * @throws {CommerceSdkValidationError} If any required headers are missing or empty.
245
+ *
246
+ * @example
247
+ * ```typescript
248
+ * const headers = getHeadersFromParams(params);
249
+ * const accessor = createHeaderAccessor(headers, ["x-api-key", "Authorization"]);
250
+ *
251
+ * // TypeScript knows these are non-empty strings (normalized to camelCase)
252
+ * const apiKey = accessor.xApiKey; // string
253
+ * const auth = accessor.authorization; // string
254
+ * ```
255
+ *
256
+ * @example
257
+ * ```typescript
258
+ * // With options to enable comma-separated value splitting
259
+ * const accessor = createHeaderAccessor(
260
+ * headers,
261
+ * ["cache-control"],
262
+ * { splitCommaSeparated: true }
263
+ * );
264
+ * // accessor.cacheControl may be string | string[] depending on comma presence
265
+ * ```
266
+ */
267
+ function createHeaderAccessor(headers, requiredHeaders, options) {
268
+ assertRequiredHeaders(headers, requiredHeaders);
269
+ const accessor = {};
270
+ for (const header of requiredHeaders) {
271
+ const camelKey = toHeaderCamelKey(header);
272
+ accessor[camelKey] = getHeader(headers, header, options);
273
+ }
274
+ return accessor;
275
+ }
276
+
277
+ //#endregion
278
+ //#region source/headers/auth.ts
279
+ /**
280
+ * Type guard to check if authorization is Bearer type.
281
+ */
282
+ function isBearerAuth(auth) {
283
+ return auth.scheme === "Bearer";
284
+ }
285
+ /**
286
+ * Type guard to check if authorization is Basic type.
287
+ */
288
+ function isBasicAuth(auth) {
289
+ return auth.scheme === "Basic";
290
+ }
291
+ /**
292
+ * Type guard to check if authorization is OAuth type.
293
+ */
294
+ function isOAuth(auth) {
295
+ return auth.scheme === "OAuth";
296
+ }
297
+ /**
298
+ * Parses key="value" or key=value parameters from a string.
299
+ * Used for OAuth and other schemes with comma-separated key-value pairs.
300
+ *
301
+ * @param parametersString The parameters string.
302
+ */
303
+ function parseKeyValueParameters(parametersString) {
304
+ const params = {};
305
+ const paramPattern = /(\w+)=(?:"([^"]*)"|([^,\s]+))/g;
306
+ let match = paramPattern.exec(parametersString);
307
+ while (match !== null) {
308
+ const [, key, quotedValue, unquotedValue] = match;
309
+ params[key] = quotedValue === void 0 ? unquotedValue : quotedValue;
310
+ match = paramPattern.exec(parametersString);
311
+ }
312
+ return params;
313
+ }
314
+ const authorizationSchema = pipe(string("Expected a string value"), trim(), nonEmpty("Expected a non-empty string value"), rawTransform(({ dataset: { value: authorization }, addIssue, NEVER }) => {
315
+ const spaceIndex = authorization.indexOf(" ");
316
+ if (spaceIndex === -1) {
317
+ addIssue({ message: "Invalid Authorization header format" });
318
+ return NEVER;
319
+ }
320
+ return {
321
+ scheme: authorization.slice(0, spaceIndex),
322
+ parameters: authorization.slice(spaceIndex + 1).trim()
323
+ };
324
+ }));
325
+ /**
326
+ * Parses an Authorization header value into its scheme and parameters.
327
+ *
328
+ * @param authorization The Authorization header value.
329
+ * @throws {CommerceSdkValidationError} If the authorization header is malformed.
330
+ *
331
+ * @example
332
+ * ```typescript
333
+ * const auth = parseAuthorization("Bearer token123");
334
+ * // { scheme: "Bearer", token: "token123" }
335
+ * ```
336
+ *
337
+ * @example
338
+ * ```typescript
339
+ * const auth = parseAuthorization("Basic dXNlcjpwYXNz");
340
+ * // { scheme: "Basic", credentials: "dXNlcjpwYXNz" }
341
+ * ```
342
+ *
343
+ * @example
344
+ * ```typescript
345
+ * const auth = parseAuthorization('OAuth oauth_consumer_key="key", oauth_token="token"');
346
+ * // { scheme: "OAuth", parameters: { oauth_consumer_key: "key", oauth_token: "token" } }
347
+ * ```
348
+ *
349
+ * @example
350
+ * ```typescript
351
+ * const auth = parseAuthorization('Digest realm="Example", nonce="abc"');
352
+ * // { scheme: "Digest", rawParameters: 'realm="Example", nonce="abc"' }
353
+ *
354
+ * const parameters = auth.parseParameters();
355
+ * // { realm: "Example", nonce: "abc" }
356
+ * ```
357
+ */
358
+ function parseAuthorization(authorization) {
359
+ const parsed = safeParse(authorizationSchema, authorization);
360
+ if (!parsed.success) throw new CommerceSdkValidationError("Invalid Authorization header format", { issues: parsed.issues });
361
+ const { scheme, parameters } = parsed.output;
362
+ if (scheme === "Bearer") return {
363
+ scheme: "Bearer",
364
+ token: parameters
365
+ };
366
+ if (scheme === "Basic") return {
367
+ scheme: "Basic",
368
+ credentials: parameters
369
+ };
370
+ if (scheme === "OAuth") return {
371
+ scheme: "OAuth",
372
+ parameters: parseKeyValueParameters(parameters)
373
+ };
374
+ return {
375
+ scheme,
376
+ rawParameters: parameters,
377
+ parseParameters: () => parseKeyValueParameters(parameters)
378
+ };
379
+ }
380
+ const bearerSchema = object({ scheme: literal("Bearer") });
381
+ /**
382
+ * Parses and validates a Bearer authorization header.
383
+ *
384
+ * @param authorization The Authorization header value.
385
+ * @throws {CommerceSdkValidationError} If the authorization header is not a Bearer token or if the token is empty.
386
+ *
387
+ * @example
388
+ * ```typescript
389
+ * const auth = parseBearerToken("Bearer eyJhbGci...");
390
+ * console.log(auth.token); // "eyJhbGci..."
391
+ * ```
392
+ *
393
+ * @example
394
+ * ```typescript
395
+ * try {
396
+ * parseBearerToken("Basic dXNlcjpwYXNz");
397
+ * } catch (error) {
398
+ * console.error(error.message); // "Authorization header must be a Bearer token"
399
+ * }
400
+ * ```
401
+ */
402
+ function parseBearerToken(authorization) {
403
+ const auth = parseAuthorization(authorization);
404
+ const parsed = safeParse(bearerSchema, auth);
405
+ if (!parsed.success) throw new CommerceSdkValidationError("Authorization header must be a Bearer token", { issues: parsed.issues });
406
+ return auth;
407
+ }
408
+ const basicSchema = object({ scheme: literal("Basic") });
409
+ /**
410
+ * Parses and validates a Basic authorization header.
411
+ *
412
+ * @param authorization The Authorization header value.
413
+ * @throws {CommerceSdkValidationError} If the authorization header is not Basic auth.
414
+ *
415
+ * @example
416
+ * ```typescript
417
+ * const auth = parseBasicToken("Basic dXNlcjpwYXNz");
418
+ * console.log(auth.credentials); // "dXNlcjpwYXNz"
419
+ * ```
420
+ */
421
+ function parseBasicToken(authorization) {
422
+ const auth = parseAuthorization(authorization);
423
+ const parsed = safeParse(basicSchema, auth);
424
+ if (!parsed.success) throw new CommerceSdkValidationError("Authorization header must be Basic authentication", { issues: parsed.issues });
425
+ return auth;
426
+ }
427
+ const oauthSchema = object({ scheme: literal("OAuth") });
428
+ /**
429
+ * Parses and validates an OAuth 1.0 authorization header.
430
+ *
431
+ * @param authorization The Authorization header value.
432
+ * @throws {CommerceSdkValidationError} If the authorization header is not OAuth.
433
+ *
434
+ * @example
435
+ * ```typescript
436
+ * const auth = parseOAuthToken('OAuth oauth_consumer_key="key", oauth_token="token"');
437
+ * console.log(auth.parameters.oauth_consumer_key); // "key"
438
+ * console.log(auth.parameters.oauth_token); // "token"
439
+ * ```
440
+ */
441
+ function parseOAuthToken(authorization) {
442
+ const auth = parseAuthorization(authorization);
443
+ const parsed = safeParse(oauthSchema, auth);
444
+ if (!parsed.success) throw new CommerceSdkValidationError("Authorization header must be OAuth", { issues: parsed.issues });
445
+ return auth;
446
+ }
447
+
448
+ //#endregion
449
+ export { assertRequiredHeaders, createHeaderAccessor, getHeader, getHeadersFromParams, getMissingOrEmptyHeaders, isBasicAuth, isBearerAuth, isOAuth, parseAuthorization, parseBasicToken, parseBearerToken, parseOAuthToken };
@@ -1,3 +1,17 @@
1
+ /**
2
+ * @license
3
+ *
4
+ * Copyright 2026 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
15
  //#region source/params/helpers.d.ts
2
16
  /**
3
17
  * Checks if the given runtime action input value is non-empty.
@@ -27,15 +41,10 @@ type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTION
27
41
  type HttpMethodLowercase = Lowercase<HttpMethod>;
28
42
  /** The type of the runtime action parameters. */
29
43
  type RuntimeActionParams = {
30
- /** If the runtime action is invoked via HTTP, this will be the headers of the request. */
31
- __ow_headers?: Record<string, string | undefined>;
32
- /** If the runtime action is invoked via HTTP, this will be the HTTP method of the request. */
33
- __ow_method?: HttpMethodLowercase;
34
- /** If the runtime action is invoked via HTTP, this will be the unmatched path of the request (matching stops after consuming the action extension) */
35
- __ow_path?: string;
36
- /** If the runtime action is invoked via HTTP, this will be the request body entity, as a base64-encoded string when its content is binary or JSON object/array, or as a plain string otherwise */
37
- __ow_body?: string;
38
- /** If the runtime action is invoked via HTTP, this will be the query parameters of the request, as an unparsed string. */
44
+ /** If the runtime action is invoked via HTTP, this will be the headers of the request. */__ow_headers?: Record<string, string | undefined>; /** If the runtime action is invoked via HTTP, this will be the HTTP method of the request. */
45
+ __ow_method?: HttpMethodLowercase; /** If the runtime action is invoked via HTTP, this will be the unmatched path of the request (matching stops after consuming the action extension) */
46
+ __ow_path?: string; /** If the runtime action is invoked via HTTP, this will be the request body entity, as a base64-encoded string when its content is binary or JSON object/array, or as a plain string otherwise */
47
+ __ow_body?: string; /** If the runtime action is invoked via HTTP, this will be the query parameters of the request, as an unparsed string. */
39
48
  __ow_query?: string;
40
49
  [key: string]: unknown;
41
50
  };
@@ -1,2 +1,16 @@
1
- import { a as nonEmpty, i as allNonEmpty, n as HttpMethodLowercase, r as RuntimeActionParams, t as HttpMethod } from "../index-CPYhPt8X.mjs";
1
+ /**
2
+ * @license
3
+ *
4
+ * Copyright 2026 Adobe. All rights reserved.
5
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License. You may obtain a copy
7
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
8
+ *
9
+ * Unless required by applicable law or agreed to in writing, software distributed under
10
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
11
+ * OF ANY KIND, either express or implied. See the License for the specific language
12
+ * governing permissions and limitations under the License.
13
+ */
14
+
15
+ import { a as nonEmpty, i as allNonEmpty, n as HttpMethodLowercase, r as RuntimeActionParams, t as HttpMethod } from "../index-2lCs6JZP.mjs";
2
16
  export { HttpMethod, HttpMethodLowercase, RuntimeActionParams, allNonEmpty, nonEmpty };
@@ -1 +1,38 @@
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};
1
+ /**
2
+ * @license
3
+ *
4
+ * Copyright 2026 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
+ //#region source/params/helpers.ts
16
+ /**
17
+ * Checks if the given runtime action input value is non-empty.
18
+ *
19
+ * @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.
20
+ * @param value - The value of the parameter.
21
+ */
22
+ function nonEmpty(name, value) {
23
+ if (value === void 0 || value === null) return false;
24
+ const v = String(value)?.trim();
25
+ return !!v && v !== `$${name}`;
26
+ }
27
+ /**
28
+ * Checks if all required parameters are non-empty.
29
+ *
30
+ * @param params - The action input parameters.
31
+ * @param required - The list of required parameter names.
32
+ */
33
+ function allNonEmpty(params, required) {
34
+ return required.every((name) => nonEmpty(name, params[name]));
35
+ }
36
+
37
+ //#endregion
38
+ export { allNonEmpty, nonEmpty };
@@ -1,3 +1,17 @@
1
+ /**
2
+ * @license
3
+ *
4
+ * Copyright 2026 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
15
  //#region source/responses/helpers.d.ts
2
16
  type HeadersRecord = Record<string, string>;
3
17
  type BodyRecord = Record<string, unknown>;