@adobe/aio-commerce-lib-core 0.6.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # @adobe/aio-commerce-lib-core
2
2
 
3
+ ## 1.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - [#294](https://github.com/adobe/aio-commerce-sdk/pull/294) [`6d5b16a`](https://github.com/adobe/aio-commerce-sdk/commit/6d5b16a7659ab0d83b251921ac478ff7faf0d4e5) Thanks [@iivvaannxx](https://github.com/iivvaannxx)! - General Availability (GA) release of the Adobe Commerce SDK and all libraries.
8
+
9
+ ### Patch Changes
10
+
11
+ - [#267](https://github.com/adobe/aio-commerce-sdk/pull/267) [`8642288`](https://github.com/adobe/aio-commerce-sdk/commit/8642288be4efd44b375d47e7cb75adb038c08334) Thanks [@jnatherley](https://github.com/jnatherley)! - Implements a rolldown plugin to correctly externalize transitive dependencies of private packages during build, but keep the source code of those same packages bundled.
12
+
13
+ ## 0.6.1
14
+
15
+ ### Patch Changes
16
+
17
+ - [#246](https://github.com/adobe/aio-commerce-sdk/pull/246) [`b3b41f5`](https://github.com/adobe/aio-commerce-sdk/commit/b3b41f576cf0341bbb4a19bb534bfe35fb562aad) Thanks [@iivvaannxx](https://github.com/iivvaannxx)! - Add new `noContent` and `conflict` response presets
18
+
19
+ - [#246](https://github.com/adobe/aio-commerce-sdk/pull/246) [`b3b41f5`](https://github.com/adobe/aio-commerce-sdk/commit/b3b41f576cf0341bbb4a19bb534bfe35fb562aad) Thanks [@iivvaannxx](https://github.com/iivvaannxx)! - Split generics on `ActionResponse` type for appropriate inference
20
+
21
+ - [#245](https://github.com/adobe/aio-commerce-sdk/pull/245) [`b7fb4da`](https://github.com/adobe/aio-commerce-sdk/commit/b7fb4da5b8a9f468d4c33a25194dcc0a6e4d16a1) Thanks [@iivvaannxx](https://github.com/iivvaannxx)! - Enhance core type definitions.
22
+
3
23
  ## 0.6.0
4
24
 
5
25
  ### Minor Changes
package/README.md CHANGED
@@ -1,14 +1,11 @@
1
1
  # `@adobe/aio-commerce-lib-core`
2
2
 
3
- > [!WARNING]
4
- > This package is a work in progress and is not yet ready for use yet. You may be able to install it, but if you do, expect breaking changes.
5
-
6
3
  This package provides core utilities used across the Adobe Commerce SDK.
7
4
 
8
5
  ## Installation
9
6
 
10
7
  ```shell
11
- pnpm install @adobe/aio-commerce-lib-core
8
+ npm install @adobe/aio-commerce-lib-core
12
9
  ```
13
10
 
14
11
  ## Usage
@@ -1 +1,5 @@
1
- const require_error=require(`../error-LUQPfUfP.cjs`);exports.CommerceSdkErrorBase=require_error.n,exports.CommerceSdkValidationError=require_error.t;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_validation_error = require('../validation-error-DuipISU5.cjs');
3
+
4
+ exports.CommerceSdkErrorBase = require_validation_error.CommerceSdkErrorBase;
5
+ exports.CommerceSdkValidationError = require_validation_error.CommerceSdkValidationError;
@@ -1 +1,432 @@
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;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_validation_error = require('../validation-error-DuipISU5.cjs');
3
+ let valibot = require("valibot");
4
+ let camelcase = require("camelcase");
5
+ camelcase = require_validation_error.__toESM(camelcase);
6
+
7
+ //#region source/headers/helpers.ts
8
+ /**
9
+ * Extracts a header value from an object with case-insensitive lookup.
10
+ * This is useful for handling HTTP headers which can be case-insensitive per RFC 7230.
11
+ *
12
+ * When enabled via options, comma-separated header values (per RFC 9110) can be
13
+ * automatically split into an array. This is useful when multiple header values
14
+ * are combined into a single comma-separated string.
15
+ *
16
+ * @param headers The headers object to search in.
17
+ * @param name The header name to look for (case-insensitive).
18
+ * @param options Optional settings to control header value processing.
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * const headers = { authorization: "Bearer token123" };
23
+ * const auth = getHeader(headers, "Authorization"); // "Bearer token123"
24
+ * ```
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * // Comma-separated string can be split when enabled (per RFC 9110)
29
+ * const headers = { "Example-Field": "Foo, Bar" };
30
+ * const value = getHeader(headers, "Example-Field", { splitCommaSeparated: true }); // ["Foo", "Bar"]
31
+ * ```
32
+ *
33
+ * @see https://datatracker.ietf.org/doc/html/rfc7230 - HTTP/1.1 Message Syntax and Routing
34
+ * @see https://datatracker.ietf.org/doc/html/rfc9110#name-field-lines-and-combined-fi - HTTP Semantics: Field Lines and Combined Field Values
35
+ */
36
+ function getHeader(headers, name, options) {
37
+ const { splitCommaSeparated = false } = options ?? {};
38
+ let value;
39
+ if (Object.hasOwn(headers, name)) value = headers[name];
40
+ else {
41
+ const lowerName = name.toLowerCase();
42
+ for (const key in headers) if (Object.hasOwn(headers, key) && key.toLowerCase() === lowerName) {
43
+ value = headers[key];
44
+ break;
45
+ }
46
+ }
47
+ if (splitCommaSeparated && typeof value === "string" && value.includes(",")) value = value.split(",").map((v) => v.trim());
48
+ return value;
49
+ }
50
+ /**
51
+ * Extracts the `__ow_headers` object from App Builder runtime action parameters.
52
+ *
53
+ * @param params The action parameters from App Builder runtime.
54
+ * @throws {CommerceSdkValidationError} If `__ow_headers` is missing or not an object.
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * export async function main(params) {
59
+ * const headers = getHeadersFromParams(params);
60
+ * const apiKey = headers["x-api-key"];
61
+ * }
62
+ * ```
63
+ */
64
+ function getHeadersFromParams(params) {
65
+ const 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);
66
+ if (!parsed.success) throw new require_validation_error.CommerceSdkValidationError("Missing __ow_headers in action params", { issues: parsed.issues });
67
+ return parsed.output.__ow_headers;
68
+ }
69
+
70
+ //#endregion
71
+ //#region source/headers/validation.ts
72
+ /**
73
+ * Returns an array of missing or empty headers using Valibot validation.
74
+ * Case-insensitive by default.
75
+ *
76
+ * Unlike {@link assertRequiredHeaders}, this function does not throw an error.
77
+ * Instead, it returns an array of header names that are missing or empty.
78
+ * This is useful when you need to check headers without immediately failing.
79
+ *
80
+ * @param headers The headers object to validate.
81
+ * @param requiredHeaders Array of required header names.
82
+ * @returns Array of header names that are missing or empty. Empty array if all headers are present and non-empty.
83
+ *
84
+ * @example
85
+ * ```typescript
86
+ * const headers = { "x-api-key": "key123" };
87
+ * const missing = getMissingOrEmptyHeaders(headers, ["x-api-key", "Authorization"]);
88
+ * // Returns: ["Authorization"]
89
+ * ```
90
+ *
91
+ * @example
92
+ * ```typescript
93
+ * const headers = { "x-api-key": "", "Authorization": "Bearer token" };
94
+ * const missing = getMissingOrEmptyHeaders(headers, ["x-api-key", "Authorization"]);
95
+ * // Returns: ["x-api-key"] (empty string is considered missing)
96
+ * ```
97
+ */
98
+ function getMissingOrEmptyHeaders(headers, requiredHeaders) {
99
+ const normalized = {};
100
+ if (headers && typeof headers === "object" && !Array.isArray(headers)) for (const key of Object.keys(headers)) {
101
+ const value = headers[key];
102
+ if (value !== void 0 && value !== null) normalized[key.toLowerCase()] = value;
103
+ }
104
+ const parsed = (0, valibot.safeParse)(buildHeadersSchema(requiredHeaders.map((h) => (0, valibot.literal)(h))), normalized);
105
+ if (parsed.success) return [];
106
+ const lookup = new Map(requiredHeaders.map((h) => [h.toLowerCase(), h]));
107
+ return parsed.issues.flatMap((issue) => {
108
+ const key = issue.path?.[0]?.key;
109
+ const original = typeof key === "string" ? lookup.get(key.toLowerCase()) : null;
110
+ return original ? [original] : [];
111
+ });
112
+ }
113
+ /**
114
+ * Builds a Valibot schema that checks:
115
+ * - Required headers exist (case-insensitive)
116
+ * - Each required header has a non-empty string value
117
+ */
118
+ function buildHeadersSchema(requiredHeaders) {
119
+ const buildSchema = () => (0, valibot.pipe)((0, valibot.string)("Expected a string value for the header"), (0, valibot.rawCheck)(({ dataset, addIssue }) => {
120
+ if (!dataset.typed) return;
121
+ const value = dataset.value;
122
+ if (value.trim() === "") {
123
+ addIssue({
124
+ expected: "a non-empty string value",
125
+ received: `"${value}"`,
126
+ message: "Header value cannot be empty or contain only whitespace"
127
+ });
128
+ return;
129
+ }
130
+ if (value.includes(",")) {
131
+ const parts = value.split(",").map((part) => part.trim());
132
+ if (!parts.some((part) => part !== "")) addIssue({
133
+ expected: "at least one non-empty value in comma-separated list",
134
+ received: `[${parts.join(", ")}]`,
135
+ message: "Header value contains only empty or whitespace values when split by comma"
136
+ });
137
+ }
138
+ }));
139
+ const shape = {};
140
+ for (const schema of requiredHeaders) shape[schema.literal.toLowerCase()] = buildSchema();
141
+ return (0, valibot.object)(shape);
142
+ }
143
+ /**
144
+ * Validates that required headers are present in the headers object.
145
+ * Case-insensitive by default (HTTP standard).
146
+ *
147
+ * This is an advanced validation function that accepts Valibot `LiteralSchema` objects
148
+ * instead of plain strings. Use {@link assertRequiredHeaders} for the simpler string-based API.
149
+ *
150
+ * @param headers The headers object to validate.
151
+ * @param requiredHeaders Array of required header names as Valibot `LiteralSchema` objects.
152
+ * @throws {CommerceSdkValidationError} If validation fails.
153
+ *
154
+ * @example
155
+ * ```typescript
156
+ * import { literal } from "valibot";
157
+ * import { assertRequiredHeadersSchema } from "@adobe/aio-commerce-lib-core/headers";
158
+ *
159
+ * const headers = getHeadersFromParams(params);
160
+ * assertRequiredHeadersSchema(headers, [
161
+ * literal("x-api-key"),
162
+ * literal("Authorization"),
163
+ * ]);
164
+ * ```
165
+ */
166
+ function assertRequiredHeadersSchema(headers, requiredHeaders) {
167
+ const normalized = {};
168
+ if (headers && typeof headers === "object" && !Array.isArray(headers)) for (const key of Object.keys(headers)) {
169
+ const value = headers[key];
170
+ if (value !== void 0 && value !== null) normalized[key.toLowerCase()] = value;
171
+ }
172
+ const parsed = (0, valibot.safeParse)(buildHeadersSchema(requiredHeaders), normalized);
173
+ if (!parsed.success) throw new require_validation_error.CommerceSdkValidationError("The headers object does not match the required headers (case-insensitive)", { issues: parsed.issues });
174
+ }
175
+ /**
176
+ * Validates that required headers are present and non-empty in the headers object.
177
+ * Performs case-insensitive validation with {@link getHeader}.
178
+ *
179
+ * @param headers The headers object to validate.
180
+ * @param requiredHeaders Array of required header names.
181
+ * @throws {CommerceSdkValidationError} If any required headers are missing or empty.
182
+ *
183
+ * @example
184
+ * ```typescript
185
+ * const headers = { "x-api-key": "key123", "Authorization": "Bearer token" };
186
+ * assertRequiredHeaders(headers, ["x-api-key", "Authorization"]);
187
+ * // Headers are validated, use getHeader() for safe access
188
+ * const apiKey = getHeader(headers, "x-api-key")!;
189
+ * ```
190
+ *
191
+ * @example
192
+ * ```typescript
193
+ * try {
194
+ * assertRequiredHeaders({}, ["x-api-key", "Authorization"]);
195
+ * } catch (error) {
196
+ * console.error(error.display());
197
+ * // "The headers object does not match the required headers (case-insensitive)"
198
+ * // ├── Schema validation error at x-api-key → Expected a non-empty string value
199
+ * // └── Schema validation error at Authorization → Expected a non-empty string value
200
+ * }
201
+ * ```
202
+ */
203
+ function assertRequiredHeaders(headers, requiredHeaders) {
204
+ assertRequiredHeadersSchema(headers, requiredHeaders.map((header) => (0, valibot.literal)(header)));
205
+ }
206
+
207
+ //#endregion
208
+ //#region source/headers/accessor.ts
209
+ /**
210
+ * Creates a type-safe header accessor object with validated required headers.
211
+ * Header names are normalized to camelCase for consistent access.
212
+ *
213
+ * @param headers The headers object from runtime params.
214
+ * @param requiredHeaders Array of required header names.
215
+ * @param options Optional settings to control header value processing (e.g., `splitCommaSeparated`).
216
+ * @throws {CommerceSdkValidationError} If any required headers are missing or empty.
217
+ *
218
+ * @example
219
+ * ```typescript
220
+ * const headers = getHeadersFromParams(params);
221
+ * const accessor = createHeaderAccessor(headers, ["x-api-key", "Authorization"]);
222
+ *
223
+ * // TypeScript knows these are non-empty strings (normalized to camelCase)
224
+ * const apiKey = accessor.xApiKey; // string
225
+ * const auth = accessor.authorization; // string
226
+ * ```
227
+ *
228
+ * @example
229
+ * ```typescript
230
+ * // With options to enable comma-separated value splitting
231
+ * const accessor = createHeaderAccessor(
232
+ * headers,
233
+ * ["cache-control"],
234
+ * { splitCommaSeparated: true }
235
+ * );
236
+ * // accessor.cacheControl may be string | string[] depending on comma presence
237
+ * ```
238
+ */
239
+ function createHeaderAccessor(headers, requiredHeaders, options) {
240
+ assertRequiredHeaders(headers, requiredHeaders);
241
+ const accessor = {};
242
+ for (const header of requiredHeaders) {
243
+ const camelKey = (0, camelcase.default)(header);
244
+ accessor[camelKey] = getHeader(headers, header, options);
245
+ }
246
+ return accessor;
247
+ }
248
+
249
+ //#endregion
250
+ //#region source/headers/auth.ts
251
+ /**
252
+ * Type guard to check if authorization is Bearer type.
253
+ */
254
+ function isBearerAuth(auth) {
255
+ return auth.scheme === "Bearer";
256
+ }
257
+ /**
258
+ * Type guard to check if authorization is Basic type.
259
+ */
260
+ function isBasicAuth(auth) {
261
+ return auth.scheme === "Basic";
262
+ }
263
+ /**
264
+ * Type guard to check if authorization is OAuth type.
265
+ */
266
+ function isOAuth(auth) {
267
+ return auth.scheme === "OAuth";
268
+ }
269
+ /**
270
+ * Parses key="value" or key=value parameters from a string.
271
+ * Used for OAuth and other schemes with comma-separated key-value pairs.
272
+ *
273
+ * @param parametersString The parameters string.
274
+ */
275
+ function parseKeyValueParameters(parametersString) {
276
+ const params = {};
277
+ const paramPattern = /(\w+)=(?:"([^"]*)"|([^,\s]+))/g;
278
+ let match = paramPattern.exec(parametersString);
279
+ while (match !== null) {
280
+ const [, key, quotedValue, unquotedValue] = match;
281
+ params[key] = quotedValue !== void 0 ? quotedValue : unquotedValue;
282
+ match = paramPattern.exec(parametersString);
283
+ }
284
+ return params;
285
+ }
286
+ 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 }) => {
287
+ const spaceIndex = authorization.indexOf(" ");
288
+ if (spaceIndex === -1) {
289
+ addIssue({ message: "Invalid Authorization header format" });
290
+ return NEVER;
291
+ }
292
+ return {
293
+ scheme: authorization.slice(0, spaceIndex),
294
+ parameters: authorization.slice(spaceIndex + 1).trim()
295
+ };
296
+ }));
297
+ /**
298
+ * Parses an Authorization header value into its scheme and parameters.
299
+ *
300
+ * @param authorization The Authorization header value.
301
+ * @throws {CommerceSdkValidationError} If the authorization header is malformed.
302
+ *
303
+ * @example
304
+ * ```typescript
305
+ * const auth = parseAuthorization("Bearer token123");
306
+ * // { scheme: "Bearer", token: "token123" }
307
+ * ```
308
+ *
309
+ * @example
310
+ * ```typescript
311
+ * const auth = parseAuthorization("Basic dXNlcjpwYXNz");
312
+ * // { scheme: "Basic", credentials: "dXNlcjpwYXNz" }
313
+ * ```
314
+ *
315
+ * @example
316
+ * ```typescript
317
+ * const auth = parseAuthorization('OAuth oauth_consumer_key="key", oauth_token="token"');
318
+ * // { scheme: "OAuth", parameters: { oauth_consumer_key: "key", oauth_token: "token" } }
319
+ * ```
320
+ *
321
+ * @example
322
+ * ```typescript
323
+ * const auth = parseAuthorization('Digest realm="Example", nonce="abc"');
324
+ * // { scheme: "Digest", rawParameters: 'realm="Example", nonce="abc"' }
325
+ *
326
+ * const parameters = auth.parseParameters();
327
+ * // { realm: "Example", nonce: "abc" }
328
+ * ```
329
+ */
330
+ function parseAuthorization(authorization) {
331
+ const parsed = (0, valibot.safeParse)(authorizationSchema, authorization);
332
+ if (!parsed.success) throw new require_validation_error.CommerceSdkValidationError("Invalid Authorization header format", { issues: parsed.issues });
333
+ const { scheme, parameters } = parsed.output;
334
+ if (scheme === "Bearer") return {
335
+ scheme: "Bearer",
336
+ token: parameters
337
+ };
338
+ if (scheme === "Basic") return {
339
+ scheme: "Basic",
340
+ credentials: parameters
341
+ };
342
+ if (scheme === "OAuth") return {
343
+ scheme: "OAuth",
344
+ parameters: parseKeyValueParameters(parameters)
345
+ };
346
+ return {
347
+ scheme,
348
+ rawParameters: parameters,
349
+ parseParameters: () => parseKeyValueParameters(parameters)
350
+ };
351
+ }
352
+ const bearerSchema = (0, valibot.object)({ scheme: (0, valibot.literal)("Bearer") });
353
+ /**
354
+ * Parses and validates a Bearer authorization header.
355
+ *
356
+ * @param authorization The Authorization header value.
357
+ * @throws {CommerceSdkValidationError} If the authorization header is not a Bearer token or if the token is empty.
358
+ *
359
+ * @example
360
+ * ```typescript
361
+ * const auth = parseBearerToken("Bearer eyJhbGci...");
362
+ * console.log(auth.token); // "eyJhbGci..."
363
+ * ```
364
+ *
365
+ * @example
366
+ * ```typescript
367
+ * try {
368
+ * parseBearerToken("Basic dXNlcjpwYXNz");
369
+ * } catch (error) {
370
+ * console.error(error.message); // "Authorization header must be a Bearer token"
371
+ * }
372
+ * ```
373
+ */
374
+ function parseBearerToken(authorization) {
375
+ const auth = parseAuthorization(authorization);
376
+ const parsed = (0, valibot.safeParse)(bearerSchema, auth);
377
+ if (!parsed.success) throw new require_validation_error.CommerceSdkValidationError("Authorization header must be a Bearer token", { issues: parsed.issues });
378
+ return auth;
379
+ }
380
+ const basicSchema = (0, valibot.object)({ scheme: (0, valibot.literal)("Basic") });
381
+ /**
382
+ * Parses and validates a Basic authorization header.
383
+ *
384
+ * @param authorization The Authorization header value.
385
+ * @throws {CommerceSdkValidationError} If the authorization header is not Basic auth.
386
+ *
387
+ * @example
388
+ * ```typescript
389
+ * const auth = parseBasicToken("Basic dXNlcjpwYXNz");
390
+ * console.log(auth.credentials); // "dXNlcjpwYXNz"
391
+ * ```
392
+ */
393
+ function parseBasicToken(authorization) {
394
+ const auth = parseAuthorization(authorization);
395
+ const parsed = (0, valibot.safeParse)(basicSchema, auth);
396
+ if (!parsed.success) throw new require_validation_error.CommerceSdkValidationError("Authorization header must be Basic authentication", { issues: parsed.issues });
397
+ return auth;
398
+ }
399
+ const oauthSchema = (0, valibot.object)({ scheme: (0, valibot.literal)("OAuth") });
400
+ /**
401
+ * Parses and validates an OAuth 1.0 authorization header.
402
+ *
403
+ * @param authorization The Authorization header value.
404
+ * @throws {CommerceSdkValidationError} If the authorization header is not OAuth.
405
+ *
406
+ * @example
407
+ * ```typescript
408
+ * const auth = parseOAuthToken('OAuth oauth_consumer_key="key", oauth_token="token"');
409
+ * console.log(auth.parameters.oauth_consumer_key); // "key"
410
+ * console.log(auth.parameters.oauth_token); // "token"
411
+ * ```
412
+ */
413
+ function parseOAuthToken(authorization) {
414
+ const auth = parseAuthorization(authorization);
415
+ const parsed = (0, valibot.safeParse)(oauthSchema, auth);
416
+ if (!parsed.success) throw new require_validation_error.CommerceSdkValidationError("Authorization header must be OAuth", { issues: parsed.issues });
417
+ return auth;
418
+ }
419
+
420
+ //#endregion
421
+ exports.assertRequiredHeaders = assertRequiredHeaders;
422
+ exports.createHeaderAccessor = createHeaderAccessor;
423
+ exports.getHeader = getHeader;
424
+ exports.getHeadersFromParams = getHeadersFromParams;
425
+ exports.getMissingOrEmptyHeaders = getMissingOrEmptyHeaders;
426
+ exports.isBasicAuth = isBasicAuth;
427
+ exports.isBearerAuth = isBearerAuth;
428
+ exports.isOAuth = isOAuth;
429
+ exports.parseAuthorization = parseAuthorization;
430
+ exports.parseBasicToken = parseBasicToken;
431
+ exports.parseBearerToken = parseBearerToken;
432
+ exports.parseOAuthToken = parseOAuthToken;
@@ -1,8 +1,7 @@
1
- import { t as RuntimeActionParams } from "../index-DmOFyyVg.cjs";
1
+ import { r as RuntimeActionParams } from "../types-CfxNboCU.cjs";
2
2
  import { CamelCase } from "type-fest";
3
3
 
4
4
  //#region source/headers/types.d.ts
5
-
6
5
  /** The type of an HTTP header value. */
7
6
  type HttpHeaderValue = string | string[] | undefined;
8
7
  /** The type of an HTTP headers record. */
@@ -1 +1,27 @@
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
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+
3
+ //#region source/params/helpers.ts
4
+ /**
5
+ * Checks if the given runtime action input value is non-empty.
6
+ *
7
+ * @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.
8
+ * @param value - The value of the parameter.
9
+ */
10
+ function nonEmpty(name, value) {
11
+ if (value === void 0 || value === null) return false;
12
+ const v = String(value)?.trim();
13
+ return !!v && v !== `$${name}`;
14
+ }
15
+ /**
16
+ * Checks if all required parameters are non-empty.
17
+ *
18
+ * @param params - The action input parameters.
19
+ * @param required - The list of required parameter names.
20
+ */
21
+ function allNonEmpty(params, required) {
22
+ return required.every((name) => nonEmpty(name, params[name]));
23
+ }
24
+
25
+ //#endregion
26
+ exports.allNonEmpty = allNonEmpty;
27
+ exports.nonEmpty = nonEmpty;
@@ -1,2 +1,2 @@
1
- import { n as allNonEmpty, r as nonEmpty, t as RuntimeActionParams } from "../index-DmOFyyVg.cjs";
2
- export { RuntimeActionParams, allNonEmpty, nonEmpty };
1
+ import { a as nonEmpty, i as allNonEmpty, n as HttpMethodLowercase, r as RuntimeActionParams, t as HttpMethod } from "../types-CfxNboCU.cjs";
2
+ export { HttpMethod, HttpMethodLowercase, RuntimeActionParams, allNonEmpty, nonEmpty };