@adobe-commerce/aio-toolkit 1.0.10 → 1.0.11

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 @@
1
- {"version":3,"sources":["../node_modules/tsup/assets/esm_shims.js","../src/framework/telemetry/helpers/input-error/index.ts","../src/framework/telemetry/new-relic/validator/index.ts","../src/framework/telemetry/helpers/resource-factory/index.ts","../src/framework/telemetry/helpers/success-checker/index.ts","../src/framework/telemetry/helpers/json-message-processor/index.ts","../src/framework/telemetry/new-relic/index.ts","../src/index.ts","../src/framework/index.ts","../src/framework/runtime-action/index.ts","../src/framework/runtime-action/response/index.ts","../src/framework/runtime-action/types.ts","../src/framework/runtime-action/validator/index.ts","../src/framework/telemetry/index.ts","../src/framework/runtime-action/response/types.ts","../src/framework/runtime-action/parameters/index.ts","../src/framework/event-consumer-action/index.ts","../src/framework/graphql-action/index.ts","../src/framework/openwhisk/index.ts","../src/framework/openwhisk-action/index.ts","../src/framework/repository/file-repository/index.ts","../src/framework/repository/file-repository/types.ts","../src/framework/publish-event/index.ts","../src/framework/custom-logger/index.ts","../src/framework/publish-event/types.ts","../src/framework/webhook-action/index.ts","../src/framework/webhook-action/response/index.ts","../src/framework/webhook-action/response/types.ts","../src/framework/webhook-action/types.ts","../src/framework/ims-token/index.ts","../src/commerce/adobe-auth/index.ts","../src/integration/bearer-token/index.ts","../src/framework/ims-token/types.ts","../src/framework/runtime-api-gateway-service/index.ts","../src/integration/rest-client/index.ts","../src/framework/telemetry/types.ts","../src/integration/index.ts","../src/integration/onboard-events/index.ts","../src/integration/onboard-events/create-providers/index.ts","../src/io-events/index.ts","../src/io-events/provider/index.ts","../src/io-events/provider/list/index.ts","../src/io-events/types.ts","../src/io-events/provider/get/index.ts","../src/io-events/provider/create/index.ts","../src/io-events/provider/delete/index.ts","../src/io-events/event-metadata/index.ts","../src/io-events/event-metadata/list/index.ts","../src/io-events/event-metadata/get/index.ts","../src/io-events/event-metadata/create/index.ts","../src/io-events/event-metadata/delete/index.ts","../src/io-events/registration/index.ts","../src/io-events/registration/create/index.ts","../src/io-events/registration/delete/index.ts","../src/io-events/registration/get/index.ts","../src/io-events/registration/list/index.ts","../src/integration/onboard-events/create-events/index.ts","../src/integration/onboard-events/create-registrations/index.ts","../src/integration/onboard-events/input-parser/index.ts","../src/integration/infinite-loop-breaker/index.ts","../src/integration/onboard-commerce/index.ts","../src/integration/onboard-commerce/configure-provider/index.ts","../src/commerce/index.ts","../src/commerce/adobe-commerce-client/index.ts","../src/commerce/adobe-commerce-client/basic-auth-connection/index.ts","../src/commerce/adobe-commerce-client/basic-auth-connection/generate-basic-auth-token/index.ts","../src/commerce/adobe-commerce-client/oauth1a-connection/index.ts","../src/commerce/adobe-commerce-client/ims-connection/index.ts","../src/commerce/shipping-carrier/index.ts","../src/commerce/shipping-carrier/method/index.ts","../src/commerce/shipping-carrier/response/index.ts","../src/experience/index.ts","../src/experience/admin-ui-sdk/index.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/*\n * <license header>\n */\n\n/**\n * Error thrown when input validation fails\n *\n * This error indicates that provided input does not meet validation requirements.\n * Common scenarios include:\n * - Missing required parameters\n * - Invalid parameter format\n * - Parameter value out of acceptable range\n * - Type mismatch\n *\n * @example\n * ```typescript\n * if (!params.SERVICE_NAME) {\n * throw new TelemetryInputError('SERVICE_NAME is required');\n * }\n *\n * if (typeof params.PORT !== 'number') {\n * throw new TelemetryInputError('PORT must be a number');\n * }\n * ```\n */\nexport class TelemetryInputError extends Error {\n /**\n * Creates a new TelemetryInputError\n *\n * @param message - Descriptive error message explaining the validation failure\n */\n constructor(message: string) {\n super(message);\n this.name = 'TelemetryInputError';\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, TelemetryInputError);\n }\n }\n}\n","/*\n * <license header>\n */\n\nimport { TelemetryInputError } from '../../helpers/input-error';\nimport type { BaseTelemetryValidator } from '../../types';\n\n/**\n * Validator for New Relic telemetry configuration\n *\n * Implements BaseTelemetryValidator interface to provide validation\n * for New Relic telemetry provider. Supports multi-provider telemetry\n * architecture by separating configuration detection from validation.\n *\n * @example\n * ```typescript\n * const validator = new NewRelicTelemetryValidator();\n * if (validator.isConfigured(params)) {\n * validator.validateConfiguration(params);\n * // Proceed with New Relic initialization\n * } else {\n * // Try next telemetry provider (e.g., Grafana)\n * }\n * ```\n */\nexport class NewRelicTelemetryValidator implements BaseTelemetryValidator {\n /**\n * Checks if New Relic telemetry is configured\n *\n * Returns true if:\n * - ENABLE_TELEMETRY is explicitly set to true\n * - NEW_RELIC_TELEMETRY is explicitly set to true\n *\n * This method does NOT validate the completeness of configuration,\n * it only checks if the provider is enabled.\n *\n * @param params - Runtime parameters to check\n * @returns true if New Relic telemetry is enabled, false otherwise\n *\n * @example\n * ```typescript\n * const validator = new NewRelicTelemetryValidator();\n * const params = { ENABLE_TELEMETRY: true, NEW_RELIC_TELEMETRY: true };\n * if (validator.isConfigured(params)) {\n * // New Relic is enabled, proceed with initialization\n * }\n * ```\n */\n public isConfigured(params: Record<string, unknown>): boolean {\n return params.ENABLE_TELEMETRY === true && params.NEW_RELIC_TELEMETRY === true;\n }\n\n /**\n * Validates New Relic specific parameters\n *\n * IMPORTANT: Only call this method after checking isConfigured() returns true.\n * This method assumes New Relic telemetry is enabled and validates that\n * all required parameters are present.\n *\n * Required parameters when New Relic is enabled:\n * - NEW_RELIC_SERVICE_NAME must be provided\n * - NEW_RELIC_LICENSE_KEY must be provided\n *\n * @param params - Runtime parameters to validate\n * @throws {TelemetryInputError} If NEW_RELIC_SERVICE_NAME is missing\n * @throws {TelemetryInputError} If NEW_RELIC_LICENSE_KEY is missing\n *\n * @example\n * ```typescript\n * const validator = new NewRelicTelemetryValidator();\n * const params = {\n * ENABLE_TELEMETRY: true,\n * NEW_RELIC_TELEMETRY: true,\n * NEW_RELIC_SERVICE_NAME: \"my-service\",\n * NEW_RELIC_LICENSE_KEY: \"license-key\"\n * };\n *\n * if (validator.isConfigured(params)) {\n * validator.validateConfiguration(params); // Validates required fields\n * }\n * ```\n */\n public validateConfiguration(params: Record<string, unknown>): void {\n if (\n params.NEW_RELIC_SERVICE_NAME === undefined ||\n params.NEW_RELIC_SERVICE_NAME === null ||\n params.NEW_RELIC_SERVICE_NAME === ''\n ) {\n throw new TelemetryInputError('NEW_RELIC_SERVICE_NAME is required');\n }\n\n if (\n params.NEW_RELIC_LICENSE_KEY === undefined ||\n params.NEW_RELIC_LICENSE_KEY === null ||\n params.NEW_RELIC_LICENSE_KEY === ''\n ) {\n throw new TelemetryInputError('NEW_RELIC_LICENSE_KEY is required');\n }\n }\n}\n","/*\n * <license header>\n */\n\nimport { getAioRuntimeResource } from '@adobe/aio-lib-telemetry';\nimport { Resource, resourceFromAttributes } from '@opentelemetry/resources';\n\n/**\n * Factory for creating OpenTelemetry resources with custom attributes\n *\n * Resources represent the entity producing telemetry data. This factory\n * creates resources based on Adobe I/O Runtime environment and enriches\n * them with custom attributes like environment name and request ID.\n *\n * Resources are attached to all telemetry signals (logs, traces, metrics)\n * and appear as filterable attributes in observability platforms.\n *\n * @example\n * ```typescript\n * const factory = new ResourceFactory();\n * const params = {\n * ENVIRONMENT: \"production\"\n * };\n * const resource = factory.createWithEnvironment(params);\n *\n * // This resource will include:\n * // - All Adobe I/O Runtime attributes (service.name, etc.)\n * // - environment: \"production\"\n * ```\n */\nexport class ResourceFactory {\n /**\n * Creates a resource with custom environment attributes\n *\n * Starts with the base Adobe I/O Runtime resource and optionally\n * merges environment attributes. These attributes are useful for\n * filtering and correlating telemetry data by deployment environment.\n *\n * Note: Request-specific data (like request IDs) should NOT be added to\n * Resources as they are created once and reused across all requests.\n * Use log attributes or span attributes for request-specific data.\n *\n * @param params - Runtime parameters containing optional ENVIRONMENT\n * @param params.ENVIRONMENT - Environment name (e.g., \"dev\", \"stage\", \"prod\")\n * @returns OpenTelemetry Resource with custom attributes if provided\n *\n * @example Without custom attributes\n * ```typescript\n * const factory = new ResourceFactory();\n * const resource = factory.createWithEnvironment({});\n * // Returns base Adobe I/O Runtime resource\n * ```\n *\n * @example With environment\n * ```typescript\n * const factory = new ResourceFactory();\n * const params = { ENVIRONMENT: \"production\" };\n * const resource = factory.createWithEnvironment(params);\n * // Returns resource with environment=\"production\" attribute\n * ```\n */\n public createWithEnvironment(params: Record<string, unknown>): Resource {\n const baseResource = getAioRuntimeResource();\n\n // Collect custom attributes\n const customAttributes: Record<string, unknown> = {};\n\n // Extract environment if provided\n if (params.ENVIRONMENT) {\n customAttributes.environment = params.ENVIRONMENT as string;\n }\n\n // If no custom attributes, return base resource as-is\n if (Object.keys(customAttributes).length === 0) {\n return baseResource;\n }\n\n // Create a new Resource with custom attributes and merge it\n const customResource = resourceFromAttributes(\n customAttributes as Record<string, string | number | boolean>\n );\n\n return baseResource.merge(customResource);\n }\n}\n","/*\n * <license header>\n */\n\nimport type { ActionResult } from './types';\n\n/**\n * Utility class to determine if an action execution was successful\n *\n * This class provides methods to validate action execution results\n * based on HTTP status codes and response body content.\n *\n * @example\n * ```typescript\n * const checker = new SuccessChecker();\n * const result = await executeAction(params);\n * if (checker.execute(result)) {\n * console.log('Action executed successfully');\n * } else {\n * console.error('Action execution failed');\n * }\n * ```\n */\nexport class SuccessChecker {\n /**\n * Determines if an action execution was successful\n *\n * Success criteria:\n * - Response has statusCode 200\n * - Body does not contain an exception operation\n *\n * @param result - The action execution result\n * @returns true if successful, false otherwise\n *\n * @example Success case\n * ```typescript\n * const checker = new SuccessChecker();\n * const result = { statusCode: 200, body: { data: 'success' } };\n * checker.execute(result); // true\n * ```\n *\n * @example Failure case - wrong status code\n * ```typescript\n * const checker = new SuccessChecker();\n * const result = { statusCode: 500, body: { error: 'Internal error' } };\n * checker.execute(result); // false\n * ```\n *\n * @example Failure case - exception in body\n * ```typescript\n * const checker = new SuccessChecker();\n * const result = { statusCode: 200, body: { op: 'exception', message: 'Error' } };\n * checker.execute(result); // false\n * ```\n */\n public execute(result: unknown): boolean {\n if (!result || typeof result !== 'object') {\n return false;\n }\n\n const actionResult = result as ActionResult;\n\n if (actionResult.statusCode !== 200) {\n return false;\n }\n\n // Check if body contains an error operation\n if (actionResult.body && typeof actionResult.body === 'object') {\n return actionResult.body.op !== 'exception';\n }\n\n return true;\n }\n}\n","/*\n * <license header>\n */\n\nimport type { LogRecordProcessor } from '@opentelemetry/sdk-logs';\n// @ts-expect-error - Type definitions may not match runtime implementation\nimport type { SdkLogRecord } from '@adobe/aio-lib-telemetry/otel';\n\n/**\n * Custom log record processor that parses JSON messages and merges\n * them into log attributes for better querying in observability platforms\n *\n * This processor implements the decorator pattern, wrapping another processor\n * and enhancing log records before passing them through. It intelligently\n * parses structured log messages (JSON, Winston format) and extracts their\n * properties as individual log attributes.\n *\n * Features:\n * - Extracts log level from severity (debug, info, warn, error, etc.)\n * - Parses JSON strings in log messages\n * - Handles Winston's JavaScript object notation (util.inspect format)\n * - Flattens nested objects into dot-notation keys for searchability\n * - Graceful error handling (silent failures, no partial extraction)\n * - Preserves message body while extracting attributes\n *\n * Parsing Strategy:\n * 1. Try standard JSON.parse() for proper JSON format\n * 2. Convert JavaScript object notation to JSON and parse\n * 3. If both fail, leave message unchanged (prevents data loss)\n *\n * @implements {LogRecordProcessor}\n *\n * @example Basic Usage\n * ```typescript\n * const baseProcessor = new SimpleLogRecordProcessor(\n * new OTLPLogExporterProto(config)\n * );\n * const processor = new JsonMessageProcessor(baseProcessor);\n *\n * // Use in telemetry configuration\n * const config = {\n * logRecordProcessors: [processor]\n * };\n * ```\n *\n * @example Log Transformation - Simple Object\n * ```typescript\n * // Input log:\n * logger.info({ message: \"User login\", userId: \"123\", success: true });\n *\n * // Processed output in New Relic:\n * // level: \"info\" (extracted from severity)\n * // message: \"User login\"\n * // userId: \"123\"\n * // success: true\n * // (all as separate, queryable attributes)\n * ```\n *\n * @example Log Transformation - Nested Objects (Flattened)\n * ```typescript\n * // Input log:\n * logger.debug({\n * message: \"ACTION_HEADERS\",\n * headers: {\n * accept: \"star/star\",\n * encoding: \"gzip\",\n * authorization: \"Bearer token\"\n * }\n * });\n *\n * // Processed output in New Relic (flattened with dot-notation):\n * // level: \"debug\"\n * // message: \"ACTION_HEADERS\"\n * // headers.accept: \"star/star\"\n * // headers.encoding: \"gzip\"\n * // headers.authorization: \"Bearer token\"\n * // (nested objects are flattened for better searchability)\n * ```\n */\nexport class JsonMessageProcessor implements LogRecordProcessor {\n /**\n * The wrapped log processor that receives the enhanced log records\n * @private\n */\n private readonly wrappedProcessor: LogRecordProcessor;\n\n /**\n * Creates a new JsonMessageProcessor\n *\n * @param wrappedProcessor - The log processor to wrap and enhance\n *\n * @example\n * ```typescript\n * const exporter = new OTLPLogExporterProto({\n * url: \"https://otlp.nr-data.net/v1/logs\",\n * headers: { \"api-key\": licenseKey }\n * });\n * const baseProcessor = new SimpleLogRecordProcessor(exporter);\n * const processor = new JsonMessageProcessor(baseProcessor);\n * ```\n */\n constructor(wrappedProcessor: LogRecordProcessor) {\n this.wrappedProcessor = wrappedProcessor;\n }\n\n /**\n * Parse JavaScript object notation and convert to proper object\n *\n * Handles Winston's util.inspect format which produces JavaScript\n * object literals instead of JSON strings.\n *\n * Examples:\n * - { key: 'value' } → {\"key\":\"value\"}\n * - { 'accept-encoding': 'gzip' } → {\"accept-encoding\":\"gzip\"}\n *\n * @param str - JavaScript object notation string\n * @returns Parsed object\n * @throws Error if parsing fails\n * @private\n */\n private parseJavaScriptObjectNotation(str: string): any {\n // Use Function constructor to safely evaluate JavaScript object literals\n // This is safer than eval() because we control the execution context\n // and it properly handles complex values with special characters\n //\n // The Function constructor can parse:\n // - { key: 'value' }\n // - { 'accept-encoding': 'gzip, deflate' }\n // - { authorization: 'Bearer eyJ...' }\n // - Nested objects and arrays\n //\n // Wrap in parentheses to ensure it's treated as an expression\n const func = new Function('return (' + str + ')');\n return func();\n }\n\n /**\n * Flatten nested objects into dot-notation keys\n *\n * Converts nested structures like:\n * { headers: { accept: '*' } }\n *\n * Into flat structure:\n * { 'headers.accept': '*' }\n *\n * This makes all attributes searchable in observability platforms.\n *\n * @param obj - Object to flatten\n * @param prefix - Current key prefix (used in recursion)\n * @returns Flattened object with dot-notation keys\n * @private\n */\n private flattenObject(obj: any, prefix: string = ''): Record<string, any> {\n const flattened: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value === null || value === undefined) {\n flattened[newKey] = value;\n } else if (Array.isArray(value)) {\n // Stringify arrays as they can't be flattened meaningfully\n flattened[newKey] = JSON.stringify(value);\n } else if (typeof value === 'object') {\n // Check if object is empty\n if (Object.keys(value).length === 0) {\n // Skip empty objects - they don't add any value as attributes\n continue;\n }\n // Recursively flatten nested objects\n const nested = this.flattenObject(value, newKey);\n Object.assign(flattened, nested);\n } else {\n // Primitive values (string, number, boolean)\n flattened[newKey] = value;\n }\n }\n\n return flattened;\n }\n\n /**\n * Processes a log record by parsing JSON messages and extracting attributes\n *\n * This method intercepts log records, attempts to parse structured data\n * from the message body, and merges extracted properties as attributes.\n * Additionally, it extracts the log level from the severity information\n * and adds it as a 'level' attribute for easier querying.\n *\n * The enhanced log record is then passed to the wrapped processor.\n *\n * @param logRecord - The log record to process\n *\n * @remarks\n * Processing steps:\n * 1. Extract log level from severityText or severityNumber\n * 2. Add 'level' attribute (debug, info, warn, error, etc.)\n * 3. Parse JSON bodies that start with '{'\n * 4. Extract properties as individual attributes\n * 5. Preserve 'message' field as primary log body\n *\n * Error handling:\n * - Silently handles parsing errors to avoid breaking the logging pipeline\n * - Failed parsing results in unmodified log record\n */\n onEmit(logRecord: SdkLogRecord): void {\n try {\n // Add log level as an attribute\n if (logRecord.severityText) {\n logRecord.setAttribute('level', logRecord.severityText.toLowerCase());\n } else if (logRecord.severityNumber !== undefined) {\n // Map severity number to level name if severityText is not available\n const levelName = this.mapSeverityNumberToLevel(logRecord.severityNumber);\n if (levelName) {\n logRecord.setAttribute('level', levelName);\n }\n }\n\n const body = logRecord.body;\n\n // Check if body is a string that might contain structured data\n if (typeof body === 'string' && body.trim().startsWith('{')) {\n let parsed: any = null;\n\n // Strategy 1: Try standard JSON.parse() for proper JSON\n try {\n parsed = JSON.parse(body);\n } catch {\n // Strategy 2: Convert JavaScript object notation to valid JSON\n // Winston's util.inspect produces: { key: 'value' } instead of {\"key\":\"value\"}\n try {\n parsed = this.parseJavaScriptObjectNotation(body);\n } catch {\n // If both parsing strategies fail, leave body as-is\n // This prevents partial/incorrect data extraction\n }\n }\n\n // If we successfully parsed the message, extract its properties\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n // Extract message field first (will be used as body)\n const messageValue = parsed.message;\n\n // Remove message from parsed object to avoid duplication\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { message, ...attributesObj } = parsed;\n\n // Flatten nested objects into dot-notation keys\n const flattenedAttributes = this.flattenObject(attributesObj);\n\n // Set flattened attributes on the log record\n Object.entries(flattenedAttributes).forEach(([key, value]) => {\n if (value !== undefined && value !== null) {\n logRecord.setAttribute(key, value as any);\n }\n });\n\n // If there's a 'message' field in the parsed object, use it as the body\n if (messageValue) {\n logRecord.body = messageValue;\n }\n }\n }\n } catch {\n // If any error occurs during processing, silently continue\n // to avoid breaking the logging pipeline\n }\n\n // Pass the modified log record to the wrapped processor\n this.wrappedProcessor.onEmit(logRecord);\n }\n\n /**\n * Maps OpenTelemetry severity number to log level name\n *\n * OpenTelemetry defines severity numbers from 1-24:\n * - 1-4: TRACE\n * - 5-8: DEBUG\n * - 9-12: INFO\n * - 13-16: WARN\n * - 17-20: ERROR\n * - 21-24: FATAL\n *\n * @param severityNumber - OpenTelemetry severity number\n * @returns Log level name (trace, debug, info, warn, error, fatal) or null\n * @private\n */\n private mapSeverityNumberToLevel(severityNumber: number): string | null {\n if (severityNumber >= 1 && severityNumber <= 4) return 'trace';\n if (severityNumber >= 5 && severityNumber <= 8) return 'debug';\n if (severityNumber >= 9 && severityNumber <= 12) return 'info';\n if (severityNumber >= 13 && severityNumber <= 16) return 'warn';\n if (severityNumber >= 17 && severityNumber <= 20) return 'error';\n if (severityNumber >= 21 && severityNumber <= 24) return 'fatal';\n return null;\n }\n\n /**\n * Forces the processor to flush any pending log records\n *\n * Delegates to the wrapped processor's forceFlush method.\n * Useful for ensuring logs are sent before application shutdown.\n *\n * @returns Promise that resolves when flush is complete\n *\n * @example\n * ```typescript\n * await processor.forceFlush();\n * console.log(\"All logs have been sent\");\n * ```\n */\n async forceFlush(): Promise<void> {\n return this.wrappedProcessor.forceFlush();\n }\n\n /**\n * Shuts down the processor and releases resources\n *\n * Delegates to the wrapped processor's shutdown method.\n * Should be called when the application is terminating.\n *\n * @returns Promise that resolves when shutdown is complete\n *\n * @example\n * ```typescript\n * await processor.shutdown();\n * console.log(\"Processor has been shut down\");\n * ```\n */\n async shutdown(): Promise<void> {\n return this.wrappedProcessor.shutdown();\n }\n}\n","/**\n * <license header>\n */\n\nimport type { BaseTelemetry } from '../types';\nimport {\n defineTelemetryConfig,\n EntrypointInstrumentationConfig,\n getPresetInstrumentations,\n instrumentEntrypoint,\n} from '@adobe/aio-lib-telemetry';\nimport { NewRelicTelemetryValidator } from './validator';\nimport { ResourceFactory } from '../helpers/resource-factory';\nimport { SuccessChecker } from '../helpers/success-checker';\nimport {\n OTLPLogExporterProto,\n OTLPMetricExporterProto,\n OTLPTraceExporterProto,\n PeriodicExportingMetricReader,\n SimpleLogRecordProcessor,\n // @ts-expect-error - Type definitions may not match runtime implementation\n} from '@adobe/aio-lib-telemetry/otel';\nimport { JsonMessageProcessor } from '../helpers/json-message-processor';\n\n/**\n * New Relic telemetry implementation for Adobe I/O Runtime actions\n *\n * Provides OpenTelemetry instrumentation configured specifically for New Relic.\n * Handles configuration of OTLP exporters for traces, metrics, and logs,\n * and wraps runtime actions with telemetry instrumentation.\n *\n * Features:\n * - Automatic trace collection for action executions\n * - Metric export via OTLP protocol\n * - Structured log forwarding with JSON attribute extraction\n * - Custom resource attributes (environment, service name)\n * - Action success/failure detection\n *\n * Required Environment Variables:\n * - ENABLE_TELEMETRY: Set to true to enable telemetry\n * - NEW_RELIC_TELEMETRY: Must be set to true to enable New Relic specific telemetry\n * - NEW_RELIC_SERVICE_NAME: Name of your service/action\n * - NEW_RELIC_LICENSE_KEY: Your New Relic license key\n * - NEW_RELIC_URL (optional): Custom New Relic OTLP endpoint (defaults to https://otlp.nr-data.net)\n * - ENVIRONMENT (optional): Environment name (dev, stage, prod) for filtering\n *\n * @implements {BaseTelemetry}\n *\n * @example Basic usage\n * ```typescript\n * import { Telemetry } from '@adobe-commerce/aio-toolkit';\n *\n * async function myAction(params) {\n * const logger = Telemetry.createLogger(\"my-action\", params);\n * logger.info(\"Action started\");\n *\n * return { statusCode: 200, body: { message: \"Success\" } };\n * }\n *\n * // Wrap action with telemetry\n * export const main = Telemetry.initialize(myAction);\n * ```\n *\n * @example Environment configuration\n * ```typescript\n * // In your .env or action configuration:\n * // ENABLE_TELEMETRY=true\n * // NEW_RELIC_TELEMETRY=true\n * // NEW_RELIC_SERVICE_NAME=my-commerce-action\n * // NEW_RELIC_LICENSE_KEY=your-license-key\n * // ENVIRONMENT=production\n *\n * // All telemetry will be tagged with environment=\"production\"\n * ```\n *\n * @example Multi-provider fallback (New Relic → Grafana → None)\n * ```typescript\n * // If NEW_RELIC_TELEMETRY is not true, the system will try\n * // the next telemetry provider (e.g., Grafana) automatically\n * // ENABLE_TELEMETRY=true\n * // GRAFANA_TELEMETRY=true // Falls back to Grafana if New Relic not configured\n * ```\n */\nclass NewRelicTelemetry implements BaseTelemetry {\n /**\n * Validator for New Relic telemetry configuration\n *\n * @private\n * @type {NewRelicTelemetryValidator}\n * @readonly\n * @memberof NewRelicTelemetry\n * @description Validator for New Relic telemetry configuration\n * @example\n * ```typescript\n * const validator = new NewRelicTelemetryValidator();\n * if (validator.isConfigured(params)) {\n * validator.validateConfiguration(params);\n * }\n * ```\n */\n private readonly validator: NewRelicTelemetryValidator;\n\n /**\n * Success checker for action execution results\n *\n * @private\n * @type {SuccessChecker}\n * @readonly\n * @memberof NewRelicTelemetry\n * @description Utility to determine if an action execution was successful\n */\n private readonly successChecker: SuccessChecker;\n\n /**\n * Resource factory for creating OpenTelemetry resources\n *\n * @private\n * @type {ResourceFactory}\n * @readonly\n * @memberof NewRelicTelemetry\n * @description Factory for creating resources with custom attributes\n */\n private readonly resourceFactory: ResourceFactory;\n\n /**\n * Constructor for New Relic telemetry\n *\n * @description Constructor for New Relic telemetry\n * @example\n * ```typescript\n * const telemetry = new NewRelicTelemetry();\n * ```\n */\n constructor() {\n this.validator = new NewRelicTelemetryValidator();\n this.successChecker = new SuccessChecker();\n this.resourceFactory = new ResourceFactory();\n }\n\n /**\n * Checks if New Relic telemetry can be initialized\n *\n * Determines if New Relic telemetry is properly configured without actually\n * attempting initialization. Useful for provider chain fallback logic.\n *\n * @param params - Runtime parameters to check\n * @returns true if New Relic is configured and can be initialized\n *\n * @example\n * ```typescript\n * const telemetry = new NewRelicTelemetry();\n * if (telemetry.canInitialize(params)) {\n * // New Relic is configured, use it\n * } else {\n * // Try next provider\n * }\n * ```\n */\n public canInitialize(params: Record<string, unknown>): boolean {\n return this.validator.isConfigured(params);\n }\n /**\n * Get the OpenTelemetry instrumentation configuration for New Relic\n *\n * Builds and returns the complete instrumentation configuration including:\n * - Service name and preset instrumentations\n * - Custom resource attributes (environment)\n * - OTLP exporters for traces, metrics, and logs\n * - Success/failure detection for actions\n *\n * This method is called internally by `instrumentEntrypoint` to configure\n * telemetry before wrapping the action.\n *\n * @returns Complete entrypoint instrumentation configuration\n * @throws {TelemetryInputError} If required parameters are missing (service name, license key)\n *\n * @example\n * ```typescript\n * const telemetry = new NewRelicTelemetry();\n * const config = telemetry.getConfig();\n * // Returns configuration with exporters, instrumentations, and resource attributes\n * ```\n */\n public getConfig(): EntrypointInstrumentationConfig {\n return {\n ...defineTelemetryConfig((params: Record<string, unknown>) => {\n // Check if New Relic telemetry is configured\n if (!this.validator.isConfigured(params)) {\n throw new Error('New Relic telemetry is not configured');\n }\n\n // Validate required parameters\n this.validator.validateConfiguration(params);\n\n const serviceName = params.NEW_RELIC_SERVICE_NAME as string;\n\n return {\n sdkConfig: {\n serviceName: serviceName,\n instrumentations: getPresetInstrumentations('simple'),\n resource: this.resourceFactory.createWithEnvironment(params),\n ...this.getExportersConfig(params),\n },\n };\n }),\n isSuccessful: this.successChecker.execute.bind(this.successChecker),\n };\n }\n\n /**\n * Configure New Relic exporters for traces, metrics, and logs\n *\n * Creates OTLP exporters for all three signal types (traces, metrics, logs)\n * and configures them to send data to New Relic. Log processors are wrapped\n * with JsonMessageProcessor for better attribute extraction.\n *\n * @param params - Runtime parameters containing NEW_RELIC_LICENSE_KEY and optional NEW_RELIC_URL\n * @returns Configuration object with traceExporter, metricReaders, and logRecordProcessors\n * @private\n */\n private getExportersConfig(params: Record<string, unknown>): {\n traceExporter: any;\n metricReaders: any[];\n logRecordProcessors: JsonMessageProcessor[];\n } {\n const licenseKey = params.NEW_RELIC_LICENSE_KEY as string;\n const newRelicUrl = (params.NEW_RELIC_URL as string) || 'https://otlp.nr-data.net';\n\n /**\n * Factory function to create OTLP exporter configuration\n * @param endpoint - New Relic endpoint path (e.g., \"v1/logs\", \"v1/traces\")\n */\n const makeExporterConfig = (\n endpoint: string\n ): { url: string; headers: { 'api-key': string } } => {\n return {\n url: `${newRelicUrl}/${endpoint}`,\n headers: {\n 'api-key': licenseKey,\n },\n };\n };\n\n return {\n traceExporter: new OTLPTraceExporterProto(makeExporterConfig('v1/traces')),\n metricReaders: [\n new PeriodicExportingMetricReader({\n exporter: new OTLPMetricExporterProto(makeExporterConfig('v1/metrics')),\n }),\n ],\n logRecordProcessors: [\n new JsonMessageProcessor(\n new SimpleLogRecordProcessor(new OTLPLogExporterProto(makeExporterConfig('v1/logs')))\n ),\n ],\n };\n }\n\n /**\n * Initialize telemetry instrumentation for a runtime action\n *\n * Wraps the provided action with OpenTelemetry instrumentation using\n * New Relic as the backend. The instrumented action will automatically:\n * - Create spans for the action execution\n * - Export metrics during runtime\n * - Forward logs to New Relic\n * - Track success/failure status\n *\n * This method delegates to `instrumentEntrypoint` from `@adobe/aio-lib-telemetry`,\n * passing the action and New Relic specific configuration.\n *\n * @param action - The runtime action function to instrument\n * @returns The instrumented action function with telemetry enabled\n * @throws {TelemetryInputError} If required configuration is missing\n *\n * @example\n * ```typescript\n * async function myAction(params: Record<string, unknown>) {\n * const logger = Telemetry.createLogger(\"my-action\", params);\n * logger.info(\"Processing request\");\n *\n * return { statusCode: 200, body: { success: true } };\n * }\n *\n * const telemetry = new NewRelicTelemetry();\n * const instrumentedAction = telemetry.initialize(myAction);\n *\n * // instrumentedAction now sends traces, metrics, and logs to New Relic\n * export const main = instrumentedAction;\n * ```\n */\n public initialize(\n action: (params: Record<string, unknown>) => any\n ): (params: Record<string, unknown>) => any {\n return instrumentEntrypoint(action, this.getConfig());\n }\n}\n\nexport default NewRelicTelemetry;\n","/**\n * <license header>\n */\n\n/**\n * App utilities and features for Adobe Commerce AIO Toolkit\n */\n\n// Export Framework utilities\nexport * from './framework';\nexport { SignatureVerification } from './framework';\n\n// Export Integration utilities\nexport * from './integration';\n\n// Export Commerce utilities\nexport * from './commerce';\n\n// Export I/O Events utilities\nexport * from './io-events';\n\n// Export Experience utilities\nexport * from './experience';\n","/**\n * Adobe App Builder framework utilities and classes\n *\n * <license header>\n */\n\n// Export RuntimeAction class, types and response utilities\nexport { default as RuntimeAction } from './runtime-action';\nexport { default as RuntimeActionResponse } from './runtime-action/response';\nexport * from './runtime-action/types';\nexport * from './runtime-action/response/types';\nexport { default as Parameters } from './runtime-action/parameters';\nexport { default as Validator } from './runtime-action/validator';\n\n// Export EventConsumerAction class\nexport { default as EventConsumerAction } from './event-consumer-action';\n\n// Export GraphQL utilities\nexport { default as GraphQlAction } from './graphql-action';\n\n// Export OpenWhisk classes\nexport { default as Openwhisk } from './openwhisk';\nexport { default as OpenwhiskAction } from './openwhisk-action';\n\n// Export Repository classes\nexport { default as FileRepository } from './repository/file-repository';\nexport * from './repository/file-repository/types';\n\n// Export PublishEvent component\nexport { default as PublishEvent } from './publish-event';\nexport * from './publish-event/types';\n\n// Export WebhookAction component\nexport { default as WebhookAction } from './webhook-action';\nexport { default as WebhookActionResponse } from './webhook-action/response';\nexport * from './webhook-action/response/types';\nexport * from './webhook-action/types';\n\n// Export ImsToken component\n// @deprecated ImsToken is deprecated due to caching issues. Use AdobeAuth from commerce package instead.\nexport { default as ImsToken } from './ims-token';\nexport * from './ims-token/types';\n\n// Export RuntimeApiGatewayService component\nexport { RuntimeApiGatewayService } from './runtime-api-gateway-service';\n\n// Export Telemetry component\nexport { default as Telemetry } from './telemetry';\nexport * from './telemetry/types';\nexport { TelemetryInputError } from './telemetry/helpers/input-error';\nexport { SuccessChecker } from './telemetry/helpers/success-checker';\nexport { JsonMessageProcessor } from './telemetry/helpers/json-message-processor';\n","/**\n * <license header>\n */\n\nimport RuntimeActionResponse from './response';\nimport Validator from './validator';\n\nimport { HttpStatus, HttpMethod } from './types';\nimport { RuntimeActionResponseType } from './response/types';\nimport Telemetry from '../telemetry';\n\n/**\n * RuntimeAction provides a standardized wrapper for Adobe I/O Runtime actions\n *\n * This class wraps user-defined actions with common runtime functionality including:\n * - Structured logging with telemetry integration\n * - Request validation (parameters, headers, HTTP methods)\n * - Error handling with appropriate HTTP status codes\n * - OpenTelemetry instrumentation for observability\n *\n * @example Basic Usage\n * ```typescript\n * const handler = RuntimeAction.execute(\n * 'myAction',\n * [HttpMethod.GET, HttpMethod.POST],\n * ['userId'],\n * ['authorization'],\n * async (params, { logger, headers }) => {\n * logger.info('Processing request');\n * return { statusCode: 200, body: { success: true } };\n * }\n * );\n *\n * export const main = handler;\n * ```\n */\nclass RuntimeAction {\n /**\n * Private static property to store the action type for logging\n * Can be set using setActionType() before calling execute()\n */\n private static actionType: string = 'runtime-action';\n\n /**\n * Sets the action type for the next action execution\n * This is used for logging to identify different action types\n * (runtime-action, webhook-action, event-consumer-action, etc.)\n *\n * @param type - The action type identifier\n */\n public static setActionType(type: string): void {\n RuntimeAction.actionType = type;\n }\n\n /**\n * Gets the current action type\n * @returns The current action type identifier\n */\n public static getActionType(): string {\n return RuntimeAction.actionType;\n }\n\n /**\n * Creates a runtime action handler with validation, logging, and telemetry\n *\n * Wraps a user-defined action function with standardized runtime functionality:\n * 1. Creates a structured logger with telemetry integration\n * 2. Logs action start, headers, and body at debug level\n * 3. Validates required parameters, headers, and HTTP methods\n * 4. Executes the user action with logger and headers context\n * 5. Logs the result and handles errors with appropriate status codes\n * 6. Integrates with OpenTelemetry for distributed tracing\n *\n * @param name - Action name used for logging and telemetry spans (default: 'main')\n * @param httpMethods - Allowed HTTP methods (GET, POST, etc.). Empty array allows all methods\n * @param requiredParams - Required parameter names in the request body\n * @param requiredHeaders - Required header names (case-insensitive)\n * @param action - User-defined action function that receives:\n * - params: All request parameters including __ow_* runtime parameters\n * - ctx: Context object with logger and headers\n * @returns Wrapped action function ready to be exported as Adobe I/O Runtime entrypoint\n *\n * @example With All Options\n * ```typescript\n * const handler = RuntimeAction.execute(\n * 'processOrder',\n * [HttpMethod.POST],\n * ['orderId', 'customerId'],\n * ['authorization', 'x-api-key'],\n * async (params, { logger, headers }) => {\n * const { orderId, customerId } = params;\n * logger.info({ message: 'Processing order', orderId, customerId });\n *\n * // Your business logic here\n * const result = await processOrderLogic(orderId, customerId);\n *\n * return {\n * statusCode: 200,\n * body: { orderId, status: 'processed', result }\n * };\n * }\n * );\n * ```\n *\n * @example Minimal Configuration\n * ```typescript\n * const handler = RuntimeAction.execute('simpleAction', [], [], [], async (params, { logger }) => {\n * logger.info('Simple action executed');\n * return { statusCode: 200, body: { message: 'Success' } };\n * });\n * ```\n */\n static execute(\n name: string = 'main',\n httpMethods: HttpMethod[] = [],\n requiredParams: string[] = [],\n requiredHeaders: string[] = [],\n action: (\n params: { [key: string]: any },\n ctx: { logger: any; headers: { [key: string]: any } }\n ) => Promise<RuntimeActionResponseType> = async (\n _params\n ): Promise<RuntimeActionResponseType> => {\n return { statusCode: HttpStatus.OK, body: {} };\n }\n ): (params: { [key: string]: any }) => Promise<RuntimeActionResponseType> {\n /**\n * Internal wrapped action that executes with full runtime support\n * This function is instrumented with telemetry and returned to the caller\n *\n * The logger automatically includes x-adobe-commerce-request-id (if present)\n * in all log messages through Winston's child logger mechanism.\n */\n const runtimeAction = async (params: {\n [key: string]: any;\n }): Promise<RuntimeActionResponseType> => {\n if (!params.action_type) {\n params.action_type = RuntimeAction.getActionType();\n }\n // Step 1: Create a structured logger with telemetry integration and request ID metadata\n // This ensures x-adobe-commerce-request-id is automatically added to ALL logs\n const logger = Telemetry.createLogger(name, params);\n\n try {\n // Step 2: Log action start with structured data for observability\n // (x-adobe-commerce-request-id is automatically added by the logger if present)\n logger.debug({\n message: `${name}-started`,\n action_name: name,\n });\n\n // Step 3: Log incoming headers for debugging and audit trails\n // These are flattened by JsonMessageProcessor for searchability\n logger.debug({\n message: `${name}-headers`,\n headers: params.__ow_headers || {},\n });\n\n // Step 4: Log request body for debugging\n logger.debug({\n message: `${name}-body`,\n body: params.__ow_body || {},\n });\n\n // Step 5: Validate request (params, headers, HTTP method)\n // Returns error response immediately if validation fails\n const validationError = RuntimeAction.validateRequest(\n params,\n requiredParams,\n requiredHeaders,\n httpMethods,\n logger,\n name\n );\n if (validationError) {\n return validationError;\n }\n\n // Step 6: Execute user's action with logger and headers context\n const result = await action(params, { logger: logger, headers: params.__ow_headers || {} });\n\n // Step 7: Log the result for observability\n logger.debug({\n message: `${name}-completed`,\n result: result,\n });\n\n return result;\n } catch (error) {\n // Step 8: Handle unexpected errors\n // Log the error for debugging and return 500 response\n if (error instanceof Error) {\n logger.error({\n message: `${name}-failed`,\n error: error.message,\n stack: error.stack,\n });\n } else {\n logger.error({\n message: `${name}-failed`,\n error: error,\n });\n }\n return RuntimeActionResponse.error(HttpStatus.INTERNAL_ERROR, 'server error');\n }\n };\n\n // Step 9: Initialize telemetry instrumentation (traces, metrics, logs)\n // This wraps the action with OpenTelemetry if configured\n return Telemetry.initialize(runtimeAction);\n }\n\n /**\n * Validates incoming request against required parameters, headers, and HTTP methods\n *\n * This private method performs comprehensive request validation:\n * 1. Checks for missing required parameters in the request body\n * 2. Checks for missing required headers (case-insensitive)\n * 3. Validates the HTTP method against allowed methods list\n *\n * @param params - Request parameters including __ow_* runtime parameters\n * @param requiredParams - List of required parameter names to validate\n * @param requiredHeaders - List of required header names to validate (case-insensitive)\n * @param httpMethods - Allowed HTTP methods. Empty array skips HTTP method validation\n * @param logger - Logger instance for error logging (child logger with request ID if present)\n * @param name - Action name for logging\n * @returns RuntimeActionResponseType with error details if validation fails, null if valid\n *\n * @private\n *\n * @example Validation Error Response\n * ```typescript\n * // Missing parameter returns:\n * {\n * statusCode: 400,\n * body: { error: 'Missing required parameter: userId' }\n * }\n *\n * // Invalid HTTP method returns:\n * {\n * statusCode: 405,\n * body: { error: 'Invalid HTTP method: DELETE. Allowed methods are: GET, POST' }\n * }\n * ```\n */\n private static validateRequest(\n params: { [key: string]: any },\n requiredParams: string[],\n requiredHeaders: string[],\n httpMethods: HttpMethod[],\n logger: any,\n name: string\n ): RuntimeActionResponseType | null {\n // check for missing request input parameters and headers\n const errorMessage =\n Validator.checkMissingRequestInputs(params, requiredParams, requiredHeaders) ?? '';\n if (errorMessage) {\n logger.error({\n message: `${name}-validation-failed`,\n error: errorMessage,\n });\n // return and log client errors\n return RuntimeActionResponse.error(HttpStatus.BAD_REQUEST, errorMessage);\n }\n\n // validate HTTP method\n const requestMethod = params.__ow_method?.toUpperCase();\n if (httpMethods.length > 0 && !httpMethods.includes(requestMethod)) {\n const errorMessage = `Invalid HTTP method: ${params.__ow_method}. Allowed methods are: ${httpMethods.join(', ')}`;\n logger.error({\n message: `${name}-validation-failed`,\n error: errorMessage,\n });\n return RuntimeActionResponse.error(HttpStatus.METHOD_NOT_ALLOWED, errorMessage);\n }\n\n return null;\n }\n}\n\nexport default RuntimeAction;\n","/**\n * <license header>\n */\n\nimport { HttpStatus } from '../types';\nimport { SuccessResponse, ErrorResponse } from './types';\n\nclass RuntimeActionResponse {\n /**\n * Returns a success response object, this method should be called on the handlers actions\n *\n * @param response a descriptive message of the result\n * e.g. 'missing xyz parameter'\n * @param headers optional headers to include in the response\n * @returns the response object, ready to be returned from the action main's function.\n */\n static success(\n response: object | string,\n headers: { [key: string]: string } = {}\n ): SuccessResponse {\n return {\n statusCode: HttpStatus.OK,\n body: response,\n headers: headers,\n };\n }\n\n /**\n * Returns an error response object, this method should be called on the handlers actions\n *\n * @param statusCode the status code.\n * e.g. 400\n * @param error a descriptive message of the result\n * e.g. 'missing xyz parameter'\n * @returns the response object, ready to be returned from the action main's function.\n */\n static error(statusCode: HttpStatus, error: string): ErrorResponse {\n return {\n error: {\n statusCode,\n body: {\n error: error,\n },\n },\n };\n }\n}\n\nexport default RuntimeActionResponse;\n","/**\n * <license header>\n */\n\nexport enum HttpStatus {\n OK = 200,\n BAD_REQUEST = 400,\n UNAUTHORIZED = 401,\n NOT_FOUND = 404,\n METHOD_NOT_ALLOWED = 405,\n INTERNAL_ERROR = 500,\n}\n\nexport enum HttpMethod {\n GET = 'GET',\n POST = 'POST',\n PUT = 'PUT',\n DELETE = 'DELETE',\n PATCH = 'PATCH',\n HEAD = 'HEAD',\n OPTIONS = 'OPTIONS',\n}\n","/**\n * <license header>\n */\n\nclass Validator {\n /**\n * Returns the list of missing keys given an object and its required keys.\n * A parameter is missing if its value is undefined or ''.\n * A value of 0 or null is not considered as missing.\n *\n * @param obj object to check.\n * @param required list of required keys.\n * Each element can be multi-level deep using a '.' separator e.g. 'myRequiredObj.myRequiredKey'\n *\n * @returns array\n * @private\n */\n static getMissingKeys(obj: { [key: string]: any }, required: string[]): string[] {\n return required.filter(r => {\n const splits = r.split('.');\n const last = splits[splits.length - 1];\n const traverse = splits.slice(0, -1).reduce((tObj, split) => tObj[split] || {}, obj);\n return last && (traverse[last] === undefined || traverse[last] === ''); // missing default params are empty string\n });\n }\n\n /**\n * Returns the list of missing keys given an object and its required keys.\n * A parameter is missing if its value is undefined or ''.\n * A value of 0 or null is not considered as missing.\n *\n * @param params action input parameters.\n * @param requiredHeaders list of required input headers.\n * @param requiredParams list of required input parameters.\n * Each element can be multi-level deep using a '.' separator e.g. 'myRequiredObj.myRequiredKey'.\n *\n * @returns string|null if the return value is not null, then it holds an error message describing the missing inputs.\n *\n */\n static checkMissingRequestInputs(\n params: { [key: string]: any },\n requiredParams: string[] = [],\n requiredHeaders: string[] = []\n ): string | null {\n let errorMessage: string | null = null;\n\n // input headers are always lowercase\n requiredHeaders = requiredHeaders.map(h => h.toLowerCase());\n // normalize header keys to lowercase for case-insensitive comparison\n const normalizedHeaders = Object.keys(params.__ow_headers || {}).reduce(\n (acc, key) => {\n acc[key.toLowerCase()] = params.__ow_headers?.[key];\n return acc;\n },\n {} as { [key: string]: any }\n );\n // check for missing headers\n const missingHeaders = Validator.getMissingKeys(normalizedHeaders, requiredHeaders);\n if (missingHeaders.length > 0) {\n errorMessage = `missing header(s) '${missingHeaders.join(', ')}'`;\n }\n\n // check for missing parameters\n const missingParams = Validator.getMissingKeys(params, requiredParams);\n if (missingParams.length > 0) {\n if (errorMessage) {\n errorMessage += ' and ';\n } else {\n errorMessage = '';\n }\n errorMessage += `missing parameter(s) '${missingParams.join(', ')}'`;\n }\n\n return errorMessage;\n }\n}\n\nexport default Validator;\n","/**\n * <license header>\n */\n\nimport { Core } from '@adobe/aio-sdk';\n\nimport RuntimeActionResponse from '../runtime-action/response';\nimport { HttpStatus } from '../runtime-action/types';\n\nclass Telemetry {\n /**\n * Create a logger with standard configuration and automatic metadata injection.\n *\n * This method creates a structured logger and wraps it to automatically add\n * contextual metadata to all log calls:\n * - `x-adobe-commerce-request-id`: Extracted from `__ow_headers` (when present)\n * - `action.type`: Extracted from `params.action_type` (when present)\n *\n * If ENABLE_TELEMETRY is true, uses OpenTelemetry logger (lazy-loaded); otherwise uses Core.Logger.\n * The environment from params.ENVIRONMENT is set at the resource level and will\n * automatically appear in all logs sent to New Relic if ENABLE_TELEMETRY is true.\n *\n * @param name - Logger name (typically action name)\n * @param params - Runtime parameters containing LOG_LEVEL, optional ENABLE_TELEMETRY, ENVIRONMENT, action_type, and __ow_headers\n * @returns Configured logger instance with automatic metadata injection\n *\n * @example Basic string message\n * ```typescript\n * const logger = Telemetry.createLogger(\"my-action\", params);\n * logger.info(\"Processing started\");\n * // Logs: \"Processing started\"\n * ```\n *\n * @example JSON object message with automatic metadata\n * ```typescript\n * const logger = Telemetry.createLogger(\"my-action\", {\n * ...params,\n * action_type: \"webhook\",\n * __ow_headers: { 'x-adobe-commerce-request-id': 'req-123' }\n * });\n * logger.info({\n * message: \"User action completed\",\n * user_id: \"123\"\n * });\n * // In New Relic: {\n * // message: \"User action completed\",\n * // user_id: \"123\",\n * // \"x-adobe-commerce-request-id\": \"req-123\",\n * // \"action.type\": \"webhook\",\n * // environment: \"development\",\n * // ...\n * // }\n * ```\n */\n public static createLogger(name: string, params: Record<string, unknown>): any {\n const logLevel = (params.LOG_LEVEL as string) || 'info';\n\n // If telemetry is not enabled, use Core.Logger directly\n if (!params.ENABLE_TELEMETRY) {\n const baseLogger = Core.Logger(name, { level: logLevel });\n return Telemetry.wrapLogger(baseLogger, params);\n }\n\n // For telemetry-enabled loggers, create a lazy-loading proxy\n // This allows us to dynamically import getLogger without blocking\n let telemetryLogger: any = null;\n let loadingPromise: Promise<void> | null = null;\n\n // Fallback logger while telemetry loads\n const fallbackLogger = Core.Logger(name, { level: logLevel });\n\n // Start loading telemetry logger asynchronously\n const loadTelemetryLogger = async (): Promise<void> => {\n /* istanbul ignore next - early return guard is tested via concurrent calls */\n if (telemetryLogger || loadingPromise) {\n return;\n }\n\n loadingPromise = (async (): Promise<void> => {\n try {\n const { getLogger } = await import('@adobe/aio-lib-telemetry');\n telemetryLogger = getLogger(name, { level: logLevel });\n } catch (error) {\n // If loading fails, stick with fallback logger\n // This ensures the app doesn't crash if telemetry package has issues\n /* istanbul ignore next - error path tested via mock failure */\n telemetryLogger = fallbackLogger;\n }\n })();\n\n await loadingPromise;\n };\n\n // Start loading immediately (fire and forget)\n /* istanbul ignore next - catch handler for fire-and-forget promise */\n loadTelemetryLogger().catch(() => {\n // Errors are handled in loadTelemetryLogger\n });\n\n // Create a proxy logger that forwards to the real logger once loaded\n const proxyLogger = {\n debug: (message: any): void => {\n const logger = telemetryLogger || fallbackLogger;\n logger.debug(message);\n },\n info: (message: any): void => {\n const logger = telemetryLogger || fallbackLogger;\n logger.info(message);\n },\n warn: (message: any): void => {\n const logger = telemetryLogger || fallbackLogger;\n logger.warn(message);\n },\n error: (message: any): void => {\n const logger = telemetryLogger || fallbackLogger;\n logger.error(message);\n },\n };\n\n // Wrap with metadata injection\n return Telemetry.wrapLogger(proxyLogger, params);\n }\n\n /**\n * Wrap a logger with automatic metadata injection\n *\n * @private\n * @param baseLogger - The base logger to wrap\n * @param params - Runtime parameters containing optional metadata\n * @returns Wrapped logger with metadata injection\n */\n private static wrapLogger(baseLogger: any, params: Record<string, unknown>): any {\n // Build metadata object with available context\n const metadata: Record<string, string> = {};\n\n // Extract request ID from headers\n const headers = params.__ow_headers as Record<string, unknown> | undefined;\n const requestId = headers?.['x-adobe-commerce-request-id'];\n if (requestId && requestId !== '') {\n metadata['x-adobe-commerce-request-id'] = requestId as string;\n }\n\n // Extract action type from params\n const actionType = params.action_type;\n if (actionType && actionType !== '') {\n metadata['action.type'] = actionType as string;\n }\n\n // If no metadata to add, return the base logger as-is\n if (Object.keys(metadata).length === 0) {\n return baseLogger;\n }\n\n // Create a wrapper that merges metadata into all log calls\n const wrapper = {\n debug: (message: any): void => {\n if (typeof message === 'object' && message !== null) {\n baseLogger.debug({ ...metadata, ...message });\n } else {\n baseLogger.debug(message);\n }\n },\n info: (message: any): void => {\n if (typeof message === 'object' && message !== null) {\n baseLogger.info({ ...metadata, ...message });\n } else {\n baseLogger.info(message);\n }\n },\n warn: (message: any): void => {\n if (typeof message === 'object' && message !== null) {\n baseLogger.warn({ ...metadata, ...message });\n } else {\n baseLogger.warn(message);\n }\n },\n error: (message: any): void => {\n if (typeof message === 'object' && message !== null) {\n baseLogger.error({ ...metadata, ...message });\n } else {\n baseLogger.error(message);\n }\n },\n };\n\n // Return a logger that includes the wrapper methods plus any other baseLogger methods\n return {\n ...baseLogger,\n ...wrapper,\n };\n }\n /**\n * Extract structured error information for logging\n *\n * Converts Error objects into a structured format suitable for logging\n * and telemetry systems like New Relic.\n *\n * @param error - Error object or unknown error value\n * @returns Structured error object with name, message, and stack trace\n *\n * @example\n * ```typescript\n * try {\n * // some operation\n * } catch (error) {\n * logger.error(\"Operation failed\", Telemetry.formatError(error));\n * }\n * ```\n */\n public static formatError(error: unknown): Record<string, unknown> {\n if (error instanceof Error) {\n return {\n error_name: error.name,\n error_message: error.message,\n error_stack: error.stack,\n };\n }\n return { error: String(error) };\n }\n\n /**\n * Initialize telemetry for a runtime action with provider fallback chain\n *\n * Attempts to initialize telemetry providers in the following order:\n * 1. New Relic (if NEW_RELIC_TELEMETRY=true)\n * 2. Grafana (if GRAFANA_TELEMETRY=true) - Future support\n * 3. Original action (no telemetry)\n *\n * Telemetry initialization is deferred to runtime when params are available.\n * This allows proper configuration detection and graceful fallback to the\n * next provider in the chain.\n *\n * **IMPORTANT**: If a provider is explicitly enabled (e.g., NEW_RELIC_TELEMETRY=true)\n * but has invalid configuration (missing API key, service name), a 500 error response\n * is returned to alert you of the misconfiguration. This prevents silently running\n * without telemetry when you expect it to be working.\n *\n * Environment Configuration:\n * Pass params.ENVIRONMENT to set the environment field in all logs.\n * This can be set via environment variables in your action configuration.\n *\n * @param action - The runtime action function to instrument\n * @returns The instrumented action ready for export\n *\n * @example Single provider (New Relic) - Valid configuration\n * ```typescript\n * // Environment:\n * // ENABLE_TELEMETRY=true\n * // NEW_RELIC_TELEMETRY=true\n * // NEW_RELIC_SERVICE_NAME=my-service\n * // NEW_RELIC_LICENSE_KEY=xxxxx\n *\n * export const main = Telemetry.initialize(myAction);\n * // ✅ Uses New Relic telemetry\n * ```\n *\n * @example New Relic enabled but misconfigured - Returns error response\n * ```typescript\n * // Environment:\n * // ENABLE_TELEMETRY=true\n * // NEW_RELIC_TELEMETRY=true\n * // NEW_RELIC_SERVICE_NAME=my-service\n * // Missing NEW_RELIC_LICENSE_KEY!\n *\n * export const main = Telemetry.initialize(myAction);\n * // ❌ Returns { error: { statusCode: 500, body: { error: \"Telemetry configuration error: NEW_RELIC_LICENSE_KEY is required\" } } }\n * // This is intentional - you want to know your telemetry config is broken!\n * ```\n *\n * @example Multi-provider fallback\n * ```typescript\n * // Environment:\n * // ENABLE_TELEMETRY=true\n * // NEW_RELIC_TELEMETRY=false // Skip New Relic\n * // GRAFANA_TELEMETRY=true // Use Grafana instead\n *\n * export const main = Telemetry.initialize(myAction);\n * // ✅ Skips New Relic, tries Grafana (when implemented)\n * ```\n *\n * @example No telemetry\n * ```typescript\n * // Environment:\n * // ENABLE_TELEMETRY=false (or not set)\n *\n * export const main = Telemetry.initialize(myAction);\n * // ✅ Returns original action without instrumentation\n * ```\n */\n public static initialize(\n action: (params: Record<string, unknown>) => any\n ): (params: Record<string, unknown>) => any {\n // Return a wrapper that initializes telemetry at runtime with actual params\n return async (params: Record<string, unknown>) => {\n // Only load telemetry when actually needed\n if (params.ENABLE_TELEMETRY && params.NEW_RELIC_TELEMETRY) {\n try {\n // Dynamic import - only loads when telemetry is enabled\n const { default: NewRelicTelemetry } = await import('./new-relic');\n const newRelicTelemetry = new NewRelicTelemetry();\n\n if (newRelicTelemetry.canInitialize(params)) {\n try {\n // New Relic is explicitly enabled, try to initialize it\n const instrumentedAction = newRelicTelemetry.initialize(action);\n return await instrumentedAction(params);\n } catch (error) {\n // Configuration error: New Relic is enabled but misconfigured\n // Return a proper error response instead of crashing\n const errorMessage =\n error instanceof Error ? error.message : 'Telemetry initialization failed';\n return RuntimeActionResponse.error(\n HttpStatus.INTERNAL_ERROR,\n `Telemetry configuration error: ${errorMessage}`\n );\n }\n }\n } catch (error) {\n // Failed to load telemetry module\n const errorMessage =\n error instanceof Error ? error.message : 'Failed to load telemetry module';\n return RuntimeActionResponse.error(\n HttpStatus.INTERNAL_ERROR,\n `Telemetry module error: ${errorMessage}`\n );\n }\n }\n\n // TODO: Try Grafana telemetry if configured\n // if (params.ENABLE_TELEMETRY && params.GRAFANA_TELEMETRY) {\n // try {\n // const { default: GrafanaTelemetry } = await import('./grafana');\n // const grafanaTelemetry = new GrafanaTelemetry();\n // if (grafanaTelemetry.canInitialize(params)) {\n // try {\n // const instrumentedAction = grafanaTelemetry.initialize(action);\n // return await instrumentedAction(params);\n // } catch (error) {\n // const errorMessage = error instanceof Error ? error.message : 'Telemetry initialization failed';\n // return RuntimeActionResponse.error(\n // HttpStatus.INTERNAL_ERROR,\n // `Telemetry configuration error: ${errorMessage}`\n // );\n // }\n // }\n // } catch (error) {\n // const errorMessage = error instanceof Error ? error.message : 'Failed to load telemetry module';\n // return RuntimeActionResponse.error(\n // HttpStatus.INTERNAL_ERROR,\n // `Telemetry module error: ${errorMessage}`\n // );\n // }\n // }\n\n // No telemetry configured, run original action without instrumentation\n return action(params);\n };\n }\n}\n\nexport default Telemetry;\n\nexport type { BaseTelemetry, EntrypointInstrumentationConfig } from './types';\n","/**\n * <license header>\n */\n\nimport { HttpStatus } from '../types';\n\nexport interface SuccessResponse {\n statusCode: HttpStatus;\n body: object | string;\n headers?: { [key: string]: string };\n}\n\nexport interface ErrorResponse {\n error: {\n statusCode: HttpStatus;\n body: {\n error: string;\n };\n };\n}\n\nexport type RuntimeActionResponseType = SuccessResponse | ErrorResponse;\n","/**\n * <license header>\n */\n\nclass Parameters {\n /**\n * Returns a log-ready string of the action input parameters.\n * The `Authorization` header content will be replaced by '<hidden>'.\n *\n * @param params action input parameters.\n *\n * @returns string\n */\n static stringify(params: { [key: string]: any }): string {\n // hide authorization token without overriding params\n let headers = params.__ow_headers || {};\n if (headers.authorization) {\n headers = { ...headers, authorization: '<hidden>' };\n }\n return JSON.stringify({ ...params, __ow_headers: headers });\n }\n}\n\nexport default Parameters;\n","/**\n * Adobe App Builder Event Consumer Action handler\n *\n * <license header>\n */\n\nimport RuntimeActionResponse from '../runtime-action/response';\nimport Validator from '../runtime-action/validator';\nimport Telemetry from '../telemetry';\n\nimport { HttpStatus } from '../runtime-action/types';\nimport { RuntimeActionResponseType } from '../runtime-action/response/types';\n\n/**\n * EventConsumerAction provides a standardized wrapper for Adobe I/O Runtime event consumer actions\n *\n * This class handles:\n * - Structured logging with automatic request ID correlation (x-adobe-commerce-request-id)\n * - Request validation (parameters and headers)\n * - OpenTelemetry instrumentation for traces, metrics, and logs\n * - Consistent error handling and response formatting\n *\n * @example Basic event consumer action\n * ```typescript\n * const handler = EventConsumerAction.execute(\n * 'order-processor',\n * ['orderId'],\n * ['x-signature'],\n * async (params, { logger }) => {\n * logger.info({ message: 'Processing order', orderId: params.orderId });\n * return { statusCode: 200, body: { success: true } };\n * }\n * );\n * ```\n */\nclass EventConsumerAction {\n /**\n * Creates an event consumer action handler with telemetry integration\n *\n * This method wraps a user-defined action with:\n * - Structured logging (all logs automatically include x-adobe-commerce-request-id if present)\n * - Request validation for required parameters and headers\n * - OpenTelemetry instrumentation\n * - Standardized error handling\n *\n * @param name - Action name for logging and observability\n * @param requiredParams - List of required parameter names to validate\n * @param requiredHeaders - List of required header names to validate (case-insensitive)\n * @param action - User's event consumer function that receives params and context\n * @returns Wrapped action handler ready for OpenWhisk runtime\n *\n * @example\n * ```typescript\n * const handler = EventConsumerAction.execute(\n * 'webhook-processor',\n * ['eventType', 'eventData'],\n * ['x-webhook-signature'],\n * async (params, { logger, headers }) => {\n * logger.info({\n * message: 'Processing webhook',\n * eventType: params.eventType\n * });\n * // Process event...\n * return { statusCode: 200, body: { processed: true } };\n * }\n * );\n * ```\n */\n static execute(\n name: string = 'main',\n requiredParams: string[] = [],\n requiredHeaders: string[] = [],\n action: (\n params: { [key: string]: any },\n ctx: { logger: any; headers: { [key: string]: any } }\n ) => Promise<RuntimeActionResponseType> = async (\n _params\n ): Promise<RuntimeActionResponseType> => {\n return { statusCode: HttpStatus.OK, body: {} };\n }\n ): (params: { [key: string]: any }) => Promise<RuntimeActionResponseType> {\n const eventConsumerAction = async (params: {\n [key: string]: any;\n }): Promise<RuntimeActionResponseType> => {\n params.action_type = 'event-consumer-action';\n // Step 1: Create a structured logger with telemetry integration and request ID metadata\n // This ensures x-adobe-commerce-request-id is automatically added to ALL logs\n const logger = Telemetry.createLogger(name, params);\n\n try {\n // Step 2: Log action start with structured data for observability\n // (x-adobe-commerce-request-id is automatically added by the logger if present)\n logger.debug({\n message: `${name}-started`,\n action_name: name,\n });\n\n // Step 3: Log incoming headers for debugging and audit trails\n // These are flattened by JsonMessageProcessor for searchability\n logger.debug({\n message: `${name}-headers`,\n headers: params.__ow_headers || {},\n });\n\n // Step 4: Log request body/parameters for debugging\n logger.debug({\n message: `${name}-parameters`,\n parameters: params,\n });\n\n // Step 5: Validate request (params and headers)\n // Returns error response immediately if validation fails\n const errorMessage =\n Validator.checkMissingRequestInputs(params, requiredParams, requiredHeaders) || '';\n if (errorMessage) {\n logger.error({\n message: `${name}-validation-failed`,\n error: errorMessage,\n });\n return RuntimeActionResponse.error(HttpStatus.BAD_REQUEST, errorMessage);\n }\n\n // Step 6: Execute user's event consumer action with logger and headers context\n const result = await action(params, { logger: logger, headers: params.__ow_headers || {} });\n\n // Step 7: Log the result for observability\n logger.debug({\n message: `${name}-completed`,\n result: result,\n });\n\n return result;\n } catch (error) {\n // Step 8: Handle unexpected errors\n // Log the error for debugging and return 500 response\n if (error instanceof Error) {\n logger.error({\n error: error.message,\n stack: error.stack,\n });\n } else {\n logger.error({ error });\n }\n return RuntimeActionResponse.error(HttpStatus.INTERNAL_ERROR, 'server error');\n }\n };\n\n // Step 9: Initialize telemetry instrumentation (traces, metrics, logs)\n // This wraps the action with OpenTelemetry if configured\n return Telemetry.initialize(eventConsumerAction);\n }\n}\n\nexport default EventConsumerAction;\n","/**\n * Adobe App Builder GraphQL framework utilities\n *\n * <license header>\n */\n\nimport { graphql, buildSchema, parse, validate } from 'graphql';\n\nimport RuntimeAction from '../runtime-action';\nimport RuntimeActionResponse from '../runtime-action/response';\n\nimport { HttpMethod, HttpStatus } from '../runtime-action/types';\nimport { RuntimeActionResponseType } from '../runtime-action/response/types';\n\nclass GraphQlAction {\n static execute(\n schema: string = `\n type Query {\n hello: String\n }\n `,\n resolvers: (ctx: {\n logger: any;\n headers: { [key: string]: any };\n params: { [key: string]: any };\n }) => Promise<any> = async (_params): Promise<any> => {\n return {\n hello: (): string => 'Hello World!',\n };\n },\n name: string = 'main',\n disableIntrospection: boolean = false\n ): (params: { [key: string]: any }) => Promise<RuntimeActionResponseType> {\n return RuntimeAction.execute(\n `graphql-${name}`,\n [HttpMethod.GET, HttpMethod.POST],\n ['query'],\n [],\n async (params, ctx) => {\n let graphqlSchema;\n try {\n graphqlSchema = buildSchema(schema);\n } catch (error) {\n return RuntimeActionResponse.error(HttpStatus.BAD_REQUEST, (error as Error).message);\n }\n const graphqlResolvers = await resolvers({\n ...ctx,\n ...{\n params,\n },\n });\n\n const context = {};\n const query = params.query;\n\n let parsedQuery;\n try {\n parsedQuery = parse(query);\n } catch (error) {\n return RuntimeActionResponse.error(HttpStatus.BAD_REQUEST, (error as Error).message);\n }\n\n const validationErrors = validate(graphqlSchema, parsedQuery);\n if (validationErrors.length) {\n return RuntimeActionResponse.error(\n HttpStatus.BAD_REQUEST,\n validationErrors.map(err => err.message).join(', ')\n );\n }\n\n if (disableIntrospection) {\n // Check for introspection queries\n const isIntrospectionQuery = parsedQuery.definitions.some((definition: any) =>\n definition.selectionSet.selections.some((selection: any) =>\n selection.name.value.startsWith('__')\n )\n );\n if (isIntrospectionQuery) {\n // return and log client errors\n return RuntimeActionResponse.error(\n HttpStatus.BAD_REQUEST,\n 'Introspection is disabled for security reasons.'\n );\n }\n }\n\n const variables =\n typeof params.variables === 'string' ? JSON.parse(params.variables) : params.variables;\n\n return RuntimeActionResponse.success(\n await graphql({\n schema: graphqlSchema,\n source: query,\n rootValue: graphqlResolvers,\n contextValue: context,\n variableValues: variables,\n operationName: params.operationName,\n })\n );\n }\n );\n }\n}\n\nexport default GraphQlAction;\n","/**\n * Adobe App Builder OpenWhisk client wrapper\n *\n * <license header>\n */\n\nimport openwhisk, { Activation, Dict } from 'openwhisk';\n\nclass Openwhisk {\n /**\n * @var openwhisk\n */\n openwhiskClient: ReturnType<typeof openwhisk>;\n\n /**\n * @param host\n * @param apiKey\n */\n constructor(host: string, apiKey: string) {\n this.openwhiskClient = openwhisk({ apihost: host, api_key: apiKey });\n }\n\n /**\n * @param action\n * @param params\n * @returns {Promise<Activation<Dict>>}\n */\n async execute(action: string, params: Dict): Promise<Activation<Dict>> {\n return await this.openwhiskClient.actions.invoke({\n name: action,\n blocking: true,\n params: params,\n });\n }\n}\n\nexport default Openwhisk;\n","/**\n * Adobe App Builder OpenWhisk Action handler\n *\n * <license header>\n */\n// OpenWhisk action handler - no direct client dependency needed\n\nimport RuntimeActionResponse from '../runtime-action/response';\n\nimport { HttpStatus } from '../runtime-action/types';\nimport { RuntimeActionResponseType } from '../runtime-action/response/types';\nimport Telemetry from '../telemetry';\n\n/**\n * OpenwhiskAction provides a standardized wrapper for Adobe I/O Runtime OpenWhisk-based webhook actions\n *\n * This class wraps user-defined webhook actions with common runtime functionality including:\n * - Structured logging with telemetry integration\n * - Error handling with appropriate HTTP status codes\n * - OpenTelemetry instrumentation for observability\n * - Automatic request ID tracking from headers\n *\n * @example Basic Usage\n * ```typescript\n * const handler = OpenwhiskAction.execute(\n * 'webhookHandler',\n * async (params, { logger, headers }) => {\n * logger.info({ message: 'Processing webhook', data: params });\n * return { statusCode: 200, body: { success: true } };\n * }\n * );\n *\n * export const main = handler;\n * ```\n */\nclass OpenwhiskAction {\n /**\n * Creates an OpenWhisk webhook action handler with logging and telemetry\n *\n * Wraps a user-defined action function with standardized runtime functionality:\n * 1. Creates a structured logger with telemetry integration\n * 2. Logs action start with structured data\n * 3. Logs request parameters at debug level\n * 4. Executes the user action with logger and headers context\n * 5. Logs the result and handles errors with appropriate status codes\n * 6. Integrates with OpenTelemetry for distributed tracing\n *\n * The logger automatically includes x-adobe-commerce-request-id and action.type\n * (if present) in all log messages.\n *\n * @param name - Action name used for logging and telemetry spans (default: 'main')\n * @param action - User-defined action function that receives:\n * - params: All request parameters including __ow_* runtime parameters\n * - ctx: Context object with logger and headers\n * @returns Wrapped action function ready to be exported as Adobe I/O Runtime entrypoint\n *\n * @example Complete Example\n * ```typescript\n * const handler = OpenwhiskAction.execute(\n * 'processWebhook',\n * async (params, { logger, headers }) => {\n * logger.info({ message: 'Webhook received', event: params.event });\n *\n * // Your webhook processing logic here\n * const result = await processWebhookData(params);\n *\n * return {\n * statusCode: 200,\n * body: { status: 'processed', result }\n * };\n * }\n * );\n * ```\n */\n static execute(\n name: string = 'main',\n action: (\n params: { [key: string]: any },\n ctx: { logger: any; headers: { [key: string]: any } }\n ) => Promise<RuntimeActionResponseType> = async (\n _params\n ): Promise<RuntimeActionResponseType> => {\n return { statusCode: HttpStatus.OK, body: {} };\n }\n ): (params: { [key: string]: any }) => Promise<RuntimeActionResponseType> {\n /**\n * Internal wrapped action that executes with full runtime support\n * This function is instrumented with telemetry and returned to the caller\n */\n const openwhiskAction = async (params: {\n [key: string]: any;\n }): Promise<RuntimeActionResponseType> => {\n // Always set action type to 'openwhisk-action'\n params.action_type = 'openwhisk-action';\n\n // Step 1: Create a structured logger with telemetry integration\n // This ensures x-adobe-commerce-request-id and action.type are automatically added to ALL logs\n const logger = Telemetry.createLogger(name, params);\n\n try {\n // Step 2: Log action start with structured data\n logger.debug({\n message: `${name}-started`,\n action_name: name,\n });\n\n // Step 3: Log parameters at debug level for troubleshooting\n logger.debug({\n message: `${name}-params`,\n params: params,\n });\n\n // Step 4: Execute user's action with logger and headers context\n const result = await action(params, { logger: logger, headers: params.__ow_headers || {} });\n\n // Step 5: Log the result for observability\n logger.debug({\n message: `${name}-completed`,\n result: result,\n });\n\n return result;\n } catch (error) {\n // Step 6: Handle unexpected errors\n // Log the error for debugging and return 500 response\n if (error instanceof Error) {\n logger.error({\n message: `${name}-failed`,\n error: error.message,\n stack: error.stack,\n });\n } else {\n logger.error({\n message: `${name}-failed`,\n error: error,\n });\n }\n return RuntimeActionResponse.error(HttpStatus.INTERNAL_ERROR, 'server error');\n }\n };\n\n // Step 7: Initialize telemetry instrumentation (traces, metrics, logs)\n // This wraps the action with OpenTelemetry if configured\n return Telemetry.initialize(openwhiskAction);\n }\n}\n\nexport default OpenwhiskAction;\n","/**\n * Copyright © Adobe, Inc. All rights reserved.\n */\n\nimport { Files } from '@adobe/aio-sdk';\nimport { FileRecord, FileMetadata } from './types';\n\n/**\n * FileRepository class for managing file-based storage operations\n * Provides CRUD operations for JSON files in a specified directory\n */\nclass FileRepository {\n private readonly filepath: string;\n private files: any = null;\n\n /**\n * Creates a new FileRepository instance\n * @param filepath - The base directory path for file operations\n */\n constructor(filepath: string) {\n this.filepath = filepath;\n }\n\n /**\n * Lists all files in the repository directory\n * @returns Promise<FileRecord[]> Array of file records\n */\n async list(): Promise<FileRecord[]> {\n const filesLib = await this.getFiles();\n const results: FileRecord[] = [];\n\n const existingFiles = (await this.metadata()) as FileMetadata[];\n if (existingFiles.length) {\n for (const file of existingFiles) {\n const buffer = await filesLib.read(`${file.name}`);\n const data = JSON.parse(buffer.toString());\n\n // Add file system timestamps\n results.push({\n ...data,\n createdAt: file.creationTime.toISOString(),\n updatedAt: file.lastModified.toISOString(),\n });\n }\n }\n\n return results;\n }\n\n /**\n * Lists file metadata without reading file contents\n * Provides a lightweight alternative to list() for performance-critical operations\n * @param id - Optional ID of a specific file to get metadata for\n * @returns Promise<FileMetadata | FileMetadata[]> Single file metadata if id provided, array of all files otherwise\n */\n async metadata(id?: string): Promise<FileMetadata | FileMetadata[]> {\n const filesLib = await this.getFiles();\n\n if (id) {\n const filepath = `${this.filepath}/${id}.json`;\n return await filesLib.getProperties(filepath);\n }\n\n return await filesLib.list(`${this.filepath}/`);\n }\n\n /**\n * Loads a specific file by ID\n * @param id - The ID of the file to load\n * @returns Promise<FileRecord> The loaded file record or empty object if not found\n */\n async load(id: string = ''): Promise<FileRecord> {\n const filepath = `${this.filepath}/${id}.json`;\n const filesLib = await this.getFiles();\n\n const existingFile = await filesLib.list(filepath);\n if (existingFile.length) {\n const buffer = await filesLib.read(filepath);\n const data = JSON.parse(buffer.toString());\n\n // Get file system properties to add timestamps\n const fileProps = await filesLib.getProperties(filepath);\n\n return {\n ...data,\n createdAt: fileProps.creationTime.toISOString(),\n updatedAt: fileProps.lastModified.toISOString(),\n };\n }\n\n return {} as FileRecord;\n }\n\n /**\n * Saves a file record to the repository\n * @param payload - The data to save\n * @param id - Optional ID for the file (sanitized to alphanumeric + underscore, takes precedence over payload.id)\n * @param overwrite - Optional flag to control file write behavior:\n * - true: Replace file entirely with payload (no merge)\n * - false (default): Merge payload with existing file content\n * @returns Promise<string | null> The filename on success, null on failure\n */\n async save(\n payload: Partial<FileRecord> = {},\n id?: string | null,\n overwrite: boolean = false\n ): Promise<string | null> {\n try {\n const filesLib = await this.getFiles();\n\n // ID parameter takes precedence, then payload.id, then timestamp\n let fileId: string;\n if (id) {\n fileId = this.sanitizeFileId(id);\n } else if ('id' in payload && payload.id !== undefined) {\n fileId = String(payload.id);\n } else {\n fileId = String(new Date().getTime());\n }\n\n const filepath = `${this.filepath}/${fileId}.json`;\n\n const existingFile = await filesLib.list(filepath);\n if (existingFile.length) {\n if (overwrite) {\n // Overwrite mode: Replace entirely with payload (no merge)\n console.log(`Overwriting existing file: ${filepath}`);\n payload = {\n id: fileId,\n ...payload,\n };\n } else {\n // Default mode: Merge with existing content\n const buffer = await filesLib.read(filepath);\n const existingData = JSON.parse(buffer.toString());\n\n payload = { ...existingData, ...payload };\n }\n // Note: No delete needed - write() will overwrite the file content\n // while preserving the file system's createdAt timestamp\n } else {\n payload = {\n id: fileId,\n ...payload,\n };\n }\n\n // Remove createdAt and updatedAt from payload before saving\n // (these will be added from file system properties when loading)\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { createdAt, updatedAt, ...payloadWithoutTimestamps } = payload as FileRecord;\n\n // Write the file\n await filesLib.write(filepath, JSON.stringify(payloadWithoutTimestamps));\n\n return fileId;\n } catch (error) {\n console.error('Error saving file:', error);\n return null;\n }\n }\n\n /**\n * Deletes files by their IDs\n * @param ids - Array of file IDs to delete\n * @returns Promise<FileRecord[]> Updated list of remaining files\n */\n async delete(ids: string[] = []): Promise<FileRecord[]> {\n const filesLib = await this.getFiles();\n\n for (const id of ids) {\n await filesLib.delete(`${this.filepath}/${id}.json`);\n }\n\n return await this.list();\n }\n\n /**\n * Sanitizes the file ID to contain only alphanumeric characters and underscores\n * @param id - The ID to sanitize\n * @returns Sanitized ID with invalid characters replaced by underscores\n */\n private sanitizeFileId(id: string): string {\n if (!id || typeof id !== 'string') {\n return String(new Date().getTime());\n }\n\n // Replace any non-alphanumeric characters (except underscore) with underscore\n const sanitized = id.replace(/[^a-zA-Z0-9_]/g, '_');\n\n // If the sanitized ID is empty or only underscores, use timestamp\n if (!sanitized || /^_+$/.test(sanitized)) {\n return String(new Date().getTime());\n }\n\n return sanitized;\n }\n\n /**\n * Initializes and returns the Files library instance\n * @returns Promise<any> Initialized Files library instance\n */\n private async getFiles(): Promise<any> {\n if (!this.files) {\n this.files = await Files.init();\n }\n return this.files;\n }\n}\n\nexport default FileRepository;\n","/**\n * Copyright © Adobe, Inc. All rights reserved.\n */\n\nexport interface FileRecord {\n id: string;\n createdAt: string;\n updatedAt: string;\n [key: string]: any;\n}\n\nexport interface FileMetadata {\n name: string;\n creationTime: Date;\n lastModified: Date;\n etag: string;\n contentLength: number;\n contentType: string;\n isDirectory: boolean;\n isPublic: boolean;\n url: string;\n}\n","/**\n * <license header>\n */\n\nimport { Events } from '@adobe/aio-sdk';\nimport { CloudEvent } from 'cloudevents';\nimport { v4 as uuidv4 } from 'uuid';\nimport CustomLogger from '../custom-logger';\nimport type { PublishEventResult } from './types';\n\n/**\n * PublishEvent component for Adobe I/O Event Publishing\n *\n * This component encapsulates the logic for publishing CloudEvents using Adobe I/O Events SDK.\n * It constructs CloudEvents with the provided payload and publishes them to the specified provider.\n *\n * @example\n * ```typescript\n * const publishEvent = new PublishEvent(\n * 'your-ims-org-id@AdobeOrg',\n * 'your-api-key',\n * 'your-access-token'\n * );\n *\n * // Publish an event\n * const result = await publishEvent.execute('provider-id', {\n * type: 'commerce.order.created',\n * data: {\n * orderId: 'ORD-123456',\n * customerId: 'CUST-789',\n * amount: 199.99\n * }\n * });\n * ```\n */\nclass PublishEvent {\n private readonly imsOrgId: string;\n private readonly apiKey: string;\n private readonly accessToken: string;\n private readonly customLogger: CustomLogger;\n\n /**\n * Creates a new PublishEvent instance\n *\n * @param imsOrgId - Adobe IMS Organization ID\n * @param apiKey - Adobe API Key (Client ID)\n * @param accessToken - Adobe Access Token\n * @param logger - Optional logger instance\n */\n constructor(imsOrgId: string, apiKey: string, accessToken: string, logger: any = null) {\n // Validate required parameters\n if (!imsOrgId?.trim()) {\n throw new Error('imsOrgId is required and cannot be empty');\n }\n if (!apiKey?.trim()) {\n throw new Error('apiKey is required and cannot be empty');\n }\n if (!accessToken?.trim()) {\n throw new Error('accessToken is required and cannot be empty');\n }\n\n this.imsOrgId = imsOrgId;\n this.apiKey = apiKey;\n this.accessToken = accessToken;\n this.customLogger = new CustomLogger(logger);\n\n this.customLogger.debug('PublishEvent initialized with valid configuration');\n }\n\n /**\n * Publishes a CloudEvent to Adobe I/O Events\n *\n * @param providerId - The Adobe I/O Events provider ID\n * @param eventCode - The event type identifier (e.g., 'commerce.order.created')\n * @param payload - The event payload data\n * @param subject - Optional subject for the event\n * @returns Promise<PublishEventResult> - The publish result\n *\n * @throws Error when providerId or eventCode is invalid or publishing fails\n */\n async execute(\n providerId: string,\n eventCode: string,\n payload: any,\n subject?: string\n ): Promise<PublishEventResult> {\n try {\n // Validate inputs\n if (!providerId?.trim()) {\n throw new Error('providerId is required and cannot be empty');\n }\n\n if (!eventCode?.trim()) {\n throw new Error('eventCode is required and cannot be empty');\n }\n\n if (payload === null || payload === undefined) {\n throw new Error('payload is required');\n }\n\n this.customLogger.info(`Publishing event to provider: ${providerId}`);\n\n // Generate unique event ID\n const eventId = uuidv4();\n\n // Construct CloudEvent using the cloudevents library\n const cloudEvent = new CloudEvent({\n id: eventId,\n source: `urn:uuid:${providerId}`,\n datacontenttype: 'application/json',\n type: eventCode,\n data: payload,\n ...(subject && { subject }),\n });\n\n this.customLogger.debug(`Constructed CloudEvent with ID: ${eventId}`);\n\n // Initialize Adobe I/O Events client\n const eventsClient = await Events.init(this.imsOrgId, this.apiKey, this.accessToken);\n\n this.customLogger.debug('Adobe I/O Events client initialized successfully');\n\n // Publish the event\n await eventsClient.publishEvent(cloudEvent);\n\n const publishedAt = new Date().toISOString();\n\n this.customLogger.info(`Event published successfully with ID: ${eventId}`);\n\n return {\n eventId,\n status: 'published',\n publishedAt,\n };\n } catch (error: any) {\n this.customLogger.error(`Failed to publish event: ${error.message}`);\n\n // Return error result instead of throwing\n return {\n eventId: uuidv4(), // Generate ID for tracking even failed events\n status: 'failed',\n publishedAt: new Date().toISOString(),\n error: error.message,\n };\n }\n }\n}\n\nexport default PublishEvent;\n","/**\n * <license header>\n */\n\n/**\n * Custom logger class that provides null-safe logging methods\n * This class is private to the package and should not be exported publicly\n */\nclass CustomLogger {\n private logger: any;\n\n /**\n * @param logger - External logger instance (can be null)\n */\n constructor(logger: any = null) {\n this.logger = logger;\n }\n\n /**\n * Log debug message if logger is available\n * @param message - Debug message to log\n * @param args - Additional arguments to pass to logger\n */\n debug(message: string, ...args: any[]): void {\n if (this.logger && typeof this.logger.debug === 'function') {\n this.logger.debug(message, ...args);\n }\n }\n\n /**\n * Log info message if logger is available\n * @param message - Info message to log\n * @param args - Additional arguments to pass to logger\n */\n info(message: string, ...args: any[]): void {\n if (this.logger && typeof this.logger.info === 'function') {\n this.logger.info(message, ...args);\n }\n }\n\n /**\n * Log error message if logger is available\n * @param message - Error message to log\n * @param args - Additional arguments to pass to logger\n */\n error(message: string, ...args: any[]): void {\n if (this.logger && typeof this.logger.error === 'function') {\n this.logger.error(message, ...args);\n }\n }\n\n /**\n * Get the underlying logger instance\n * @returns the logger instance or null\n */\n getLogger(): any {\n return this.logger;\n }\n}\n\nexport default CustomLogger;\n","/**\n * <license header>\n */\n\n/**\n * Event data for publishing\n */\nexport interface EventData {\n /** Event type identifier */\n type: string;\n /** Event payload data */\n data: any;\n /** Optional event subject */\n subject?: string;\n}\n\n/**\n * Result of event publishing operation\n */\nexport interface PublishEventResult {\n /** Generated event ID */\n eventId: string;\n /** Status of the publish operation */\n status: 'published' | 'failed';\n /** Timestamp when the event was published */\n publishedAt: string;\n /** Optional error message if publishing failed */\n error?: string;\n}\n","/**\n * <license header>\n */\n\nimport RuntimeAction from '../runtime-action';\nimport RuntimeActionResponse from '../runtime-action/response';\nimport WebhookActionResponse from './response';\nimport { HttpMethod } from '../runtime-action/types';\nimport { RuntimeActionResponseType } from '../runtime-action/response/types';\nimport { WebhookActionResponseType } from './response/types';\nimport { SignatureVerification } from './types';\nimport crypto from 'crypto';\nimport Validator from '../runtime-action/validator';\n\n/**\n * WebhookAction - Wrapper for RuntimeAction with webhook-specific functionality.\n *\n * Handles Adobe Commerce webhook requests with automatic signature verification,\n * parameter validation, and response formatting.\n */\nclass WebhookAction {\n /**\n * Execute a webhook action with validation and response handling.\n *\n * @param name - Name of the webhook action\n * @param requiredParams - Required parameters in the webhook payload\n * @param requiredHeaders - Required headers (e.g., signature headers)\n * @param signatureVerification - Enable/disable signature verification\n * @param action - Webhook action function returning WebhookActionResponse\n * @returns Function that handles the webhook HTTP request\n */\n static execute(\n name: string = 'webhook',\n requiredParams: string[] = [],\n requiredHeaders: string[] = [],\n signatureVerification: SignatureVerification = SignatureVerification.DISABLED,\n action: (\n params: { [key: string]: any },\n ctx: { logger: any; headers: { [key: string]: any } }\n ) => Promise<\n WebhookActionResponseType | WebhookActionResponseType[]\n > = async (): Promise<WebhookActionResponseType> => WebhookActionResponse.success()\n ): (params: { [key: string]: any }) => Promise<RuntimeActionResponseType> {\n // Webhooks typically use POST method\n const httpMethods: HttpMethod[] = [HttpMethod.POST];\n\n // Verify webhook signature using a public key and SHA256.\n const verifySignature = async (params: { [key: string]: any }): Promise<string | null> => {\n const signature = params.__ow_headers['x-adobe-commerce-webhook-signature'] || '';\n if (!signature) {\n return 'Header `x-adobe-commerce-webhook-signature` not found. Make sure Webhooks signature is enabled in the Commerce instance.';\n }\n\n const body = params.__ow_body;\n if (!body) {\n return 'Request body not found. Make sure the action is configured with `raw-http: true`.';\n }\n\n let publicKey = params.PUBLIC_KEY;\n if (!publicKey && params.PUBLIC_KEY_BASE64) {\n publicKey = atob(params.PUBLIC_KEY_BASE64);\n }\n\n if (!publicKey) {\n return 'Public key not found. Make sure the action is configured with the input `PUBLIC_KEY` or `PUBLIC_KEY_BASE64` and it is defined in .env file.';\n }\n\n try {\n const verifier = crypto.createVerify('SHA256');\n verifier.update(body);\n const isSignatureValid = verifier.verify(publicKey, signature, 'base64');\n\n if (!isSignatureValid) {\n return 'The signature is invalid.';\n }\n } catch (error) {\n return 'The signature is invalid.';\n }\n return null;\n };\n\n // Create a callback that wraps the webhook action response\n const callback = async (\n params: { [key: string]: any },\n ctx: { logger: any; headers: { [key: string]: any } }\n ): Promise<RuntimeActionResponseType> => {\n const { logger } = ctx;\n\n if (signatureVerification === SignatureVerification.ENABLED) {\n const verificationErrorMessage = await verifySignature(params);\n if (verificationErrorMessage) {\n logger.error({\n message: `${name}-signature-verification-failed`,\n error: verificationErrorMessage,\n });\n const verificationErrorResponse =\n WebhookActionResponse.exception(verificationErrorMessage);\n return RuntimeActionResponse.success(JSON.stringify(verificationErrorResponse));\n }\n\n params = {\n ...params,\n ...JSON.parse(atob(params.__ow_body)),\n };\n }\n\n // check for missing request input parameters and headers\n const errorMessage =\n Validator.checkMissingRequestInputs(params, requiredParams, requiredHeaders) ?? '';\n if (errorMessage) {\n logger.error({\n message: `${name}-validation-failed`,\n error: errorMessage,\n });\n const errorMessageResponse = WebhookActionResponse.exception(errorMessage);\n return RuntimeActionResponse.success(JSON.stringify(errorMessageResponse));\n }\n\n // Execute the webhook action\n const response = await action(params, ctx);\n\n // Wrap the webhook response in a successful HTTP response\n return RuntimeActionResponse.success(JSON.stringify(response));\n };\n\n // Delegate to RuntimeAction with webhook-specific defaults\n // Set action type to 'webhook-action' for proper logging identification\n RuntimeAction.setActionType('webhook-action');\n return RuntimeAction.execute(name, httpMethods, [], [], callback);\n }\n}\n\nexport default WebhookAction;\n","/**\n * <license header>\n */\n\nimport {\n WebhookActionOperation,\n WebhookActionSuccessResponse,\n WebhookActionExceptionResponse,\n WebhookActionAddResponse,\n WebhookActionReplaceResponse,\n WebhookActionRemoveResponse,\n} from './types';\n\n/**\n * WebhookActionResponse - Factory class for creating Adobe Commerce webhook responses\n *\n * This class provides static methods to create properly formatted responses for\n * Adobe Commerce webhooks. These responses can be used to signal success, report\n * exceptions, or modify webhook payloads by adding, replacing, or removing data.\n *\n * All methods return strongly-typed response objects that conform to Adobe Commerce's\n * webhook response specification.\n *\n * @example\n * ```typescript\n * // Return a success response\n * return WebhookActionResponse.success();\n *\n * // Report an exception\n * return WebhookActionResponse.exception('ValidationException', 'Invalid product data');\n *\n * // Add new data to the payload\n * return WebhookActionResponse.add('order.metadata', { processed: true });\n *\n * // Modify existing data\n * return WebhookActionResponse.replace('product.price', 29.99);\n *\n * // Remove data from the payload\n * return WebhookActionResponse.remove('customer.internal_notes');\n * ```\n *\n * @see https://developer.adobe.com/commerce/extensibility/webhooks/\n */\nclass WebhookActionResponse {\n /**\n * Creates a success response indicating the webhook was processed successfully.\n *\n * Use this method when the webhook has been processed without errors and\n * no modifications to the payload are needed.\n *\n * @returns A success response object\n *\n * @example\n * ```typescript\n * const handler = WebhookAction.execute('process-order', [], [], async (params) => {\n * // Process the order...\n * await processOrder(params.order);\n *\n * // Return success\n * return {\n * statusCode: 200,\n * body: WebhookActionResponse.success()\n * };\n * });\n * ```\n */\n static success(): WebhookActionSuccessResponse {\n return {\n op: WebhookActionOperation.SUCCESS,\n };\n }\n\n /**\n * Creates an exception response to report an error during webhook processing.\n *\n * Use this method to notify Adobe Commerce that an error occurred while\n * processing the webhook. This helps with debugging and error tracking.\n *\n * @param message - Optional error message describing what went wrong\n * @param exceptionClass - Optional exception class name for categorization (e.g., 'Magento\\\\Framework\\\\Exception\\\\LocalizedException')\n * @returns An exception response object\n *\n * @example\n * ```typescript\n * const handler = WebhookAction.execute('validate-product', [], [], async (params) => {\n * const product = await findProduct(params.sku);\n *\n * if (!product) {\n * return {\n * statusCode: 404,\n * body: WebhookActionResponse.exception(\n * `Product with SKU ${params.sku} not found`,\n * 'Magento\\\\Framework\\\\Exception\\\\NoSuchEntityException'\n * )\n * };\n * }\n *\n * return { statusCode: 200, body: WebhookActionResponse.success() };\n * });\n * ```\n */\n static exception(message?: string, exceptionClass?: string): WebhookActionExceptionResponse {\n const response: WebhookActionExceptionResponse = {\n op: WebhookActionOperation.EXCEPTION,\n };\n\n if (message !== undefined) {\n response.message = message;\n }\n if (exceptionClass !== undefined) {\n response.class = exceptionClass;\n }\n\n return response;\n }\n\n /**\n * Creates a response to add new data to the webhook payload.\n *\n * Use this method to inject additional data into the webhook payload that\n * will be processed by Adobe Commerce. The data is added at the specified\n * path using dot notation.\n *\n * @param path - Dot-notation path where the value should be added (e.g., 'order.items', 'customer.addresses')\n * @param value - The value to add at the specified path\n * @param instance - Optional instance identifier for tracking or reference purposes\n * @returns An add response object\n *\n * @example\n * ```typescript\n * const handler = WebhookAction.execute('enrich-order', [], [], async (params) => {\n * // Add loyalty points to the order\n * return {\n * statusCode: 200,\n * body: WebhookActionResponse.add(\n * 'order.loyalty',\n * { points: 150, tier: 'gold' },\n * params.order.id\n * )\n * };\n * });\n * ```\n */\n static add(path: string, value: any, instance?: string): WebhookActionAddResponse {\n const response: WebhookActionAddResponse = {\n op: WebhookActionOperation.ADD,\n path: path,\n value: value,\n };\n\n if (instance !== undefined) {\n response.instance = instance;\n }\n\n return response;\n }\n\n /**\n * Creates a response to replace existing data in the webhook payload.\n *\n * Use this method to modify existing fields in the webhook payload.\n * The existing value at the specified path will be replaced with the new value.\n *\n * @param path - Dot-notation path to the field that should be replaced (e.g., 'product.price', 'order.status')\n * @param value - The new value to replace the existing value\n * @param instance - Optional instance identifier for tracking or reference purposes\n * @returns A replace response object\n *\n * @example\n * ```typescript\n * const handler = WebhookAction.execute('adjust-price', [], [], async (params) => {\n * // Apply dynamic pricing\n * const newPrice = await calculateDiscountedPrice(params.product.price);\n *\n * return {\n * statusCode: 200,\n * body: WebhookActionResponse.replace(\n * 'product.price',\n * newPrice,\n * params.product.id\n * )\n * };\n * });\n * ```\n */\n static replace(path: string, value: any, instance?: string): WebhookActionReplaceResponse {\n const response: WebhookActionReplaceResponse = {\n op: WebhookActionOperation.REPLACE,\n path: path,\n value: value,\n };\n\n if (instance !== undefined) {\n response.instance = instance;\n }\n\n return response;\n }\n\n /**\n * Creates a response to remove data from the webhook payload.\n *\n * Use this method to remove fields from the webhook payload before it's\n * processed by Adobe Commerce. This is useful for filtering sensitive data\n * or removing unnecessary information.\n *\n * @param path - Dot-notation path to the field that should be removed (e.g., 'items.0', 'customer.internal_notes')\n * @returns A remove response object\n *\n * @example\n * ```typescript\n * const handler = WebhookAction.execute('sanitize-customer', [], [], async (params) => {\n * // Remove internal notes before processing\n * return {\n * statusCode: 200,\n * body: WebhookActionResponse.remove('customer.internal_notes')\n * };\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Remove an item from an array\n * return {\n * statusCode: 200,\n * body: WebhookActionResponse.remove('order.items.2')\n * };\n * ```\n */\n static remove(path: string): WebhookActionRemoveResponse {\n return {\n op: WebhookActionOperation.REMOVE,\n path: path,\n };\n }\n}\n\nexport default WebhookActionResponse;\n","/**\n * <license header>\n */\n\n/**\n * Webhook operation types for Adobe Commerce webhooks.\n *\n * These operations define the different types of responses that can be returned\n * from a webhook handler to modify the behavior or data in Adobe Commerce.\n *\n * @see https://developer.adobe.com/commerce/extensibility/webhooks/\n */\nexport enum WebhookActionOperation {\n /** Indicates successful webhook processing with no modifications */\n SUCCESS = 'success',\n /** Indicates an exception or error occurred during webhook processing */\n EXCEPTION = 'exception',\n /** Adds a new field or value to the webhook payload */\n ADD = 'add',\n /** Replaces an existing field or value in the webhook payload */\n REPLACE = 'replace',\n /** Removes a field from the webhook payload */\n REMOVE = 'remove',\n}\n\n/**\n * Response indicating successful webhook processing.\n *\n * Use this response when the webhook has been processed successfully\n * and no modifications to the payload are needed.\n *\n * @example\n * ```typescript\n * const response: WebhookActionSuccessResponse = {\n * op: WebhookActionOperation.SUCCESS\n * };\n * ```\n */\nexport interface WebhookActionSuccessResponse {\n /** Operation type */\n op: typeof WebhookActionOperation.SUCCESS;\n}\n\n/**\n * Response indicating an exception or error during webhook processing.\n *\n * Use this response to notify Adobe Commerce that an error occurred\n * during webhook processing. Optionally include the exception class\n * and error message for debugging purposes.\n *\n * @example\n * ```typescript\n * const response: WebhookActionExceptionResponse = {\n * op: WebhookActionOperation.EXCEPTION,\n * class: 'ProductNotFoundException',\n * message: 'Product with SKU ABC123 not found'\n * };\n * ```\n */\nexport interface WebhookActionExceptionResponse {\n /** Operation type */\n op: typeof WebhookActionOperation.EXCEPTION;\n /** Optional exception class name for categorization */\n class?: string;\n /** Optional error message describing what went wrong */\n message?: string;\n}\n\n/**\n * Response for adding a new field or value to the webhook payload.\n *\n * Use this response to inject new data into the webhook payload that will\n * be processed by Adobe Commerce. The path specifies where to add the data,\n * and value contains the data to add.\n *\n * @example\n * ```typescript\n * const response: WebhookActionAddResponse = {\n * op: WebhookActionOperation.ADD,\n * path: 'order.items',\n * value: { sku: 'PRODUCT-123', quantity: 2, price: 49.99 },\n * instance: 'order-12345'\n * };\n * ```\n */\nexport interface WebhookActionAddResponse {\n /** Operation type */\n op: typeof WebhookActionOperation.ADD;\n /** Dot-notation path where the value should be added (e.g., 'order.items', 'customer.addresses') */\n path: string;\n /** The value to add at the specified path */\n value: any;\n /** Optional instance identifier for tracking or reference */\n instance?: string;\n}\n\n/**\n * Response for replacing an existing field or value in the webhook payload.\n *\n * Use this response to modify existing data in the webhook payload.\n * The path specifies which field to replace, and value contains the new data.\n *\n * @example\n * ```typescript\n * const response: WebhookActionReplaceResponse = {\n * op: WebhookActionOperation.REPLACE,\n * path: 'product.price',\n * value: 29.99,\n * instance: 'product-456'\n * };\n * ```\n */\nexport interface WebhookActionReplaceResponse {\n /** Operation type */\n op: typeof WebhookActionOperation.REPLACE;\n /** Dot-notation path to the field that should be replaced (e.g., 'product.price', 'order.status') */\n path: string;\n /** The new value to replace the existing value */\n value: any;\n /** Optional instance identifier for tracking or reference */\n instance?: string;\n}\n\n/**\n * Response for removing a field from the webhook payload.\n *\n * Use this response to remove data from the webhook payload before\n * it's processed by Adobe Commerce.\n *\n * @example\n * ```typescript\n * const response: WebhookActionRemoveResponse = {\n * op: WebhookActionOperation.REMOVE,\n * path: 'customer.addresses.0'\n * };\n * ```\n */\nexport interface WebhookActionRemoveResponse {\n /** Operation type */\n op: typeof WebhookActionOperation.REMOVE;\n /** Dot-notation path to the field that should be removed (e.g., 'items.0', 'customer.email') */\n path: string;\n}\n\n/**\n * Union type representing all possible webhook action response types.\n *\n * This type can be used when you need to handle multiple response types\n * or want to ensure type safety across different webhook operations.\n *\n * @example\n * ```typescript\n * function handleResponse(response: WebhookActionResponseType) {\n * switch (response.op) {\n * case WebhookActionOperation.SUCCESS:\n * // Handle success\n * break;\n * case WebhookActionOperation.EXCEPTION:\n * // Handle exception\n * break;\n * // ... handle other operations\n * }\n * }\n * ```\n */\nexport type WebhookActionResponseType =\n | WebhookActionSuccessResponse\n | WebhookActionExceptionResponse\n | WebhookActionAddResponse\n | WebhookActionReplaceResponse\n | WebhookActionRemoveResponse;\n","/**\n * <license header>\n */\n\n/**\n * Signature verification options for webhook requests\n */\nexport enum SignatureVerification {\n /** Signature verification is enabled */\n ENABLED = 'enabled',\n /** Signature verification is disabled */\n DISABLED = 'disabled',\n}\n","/**\n * <license header>\n */\n\nimport { State } from '@adobe/aio-sdk';\n\nimport AdobeAuth from '../../commerce/adobe-auth';\nimport BearerToken from '../../integration/bearer-token';\nimport CustomLogger from '../custom-logger';\nimport { ImsTokenResult } from './types';\n\n/**\n * ImsToken for Adobe IMS Token Management\n *\n * @deprecated This class is deprecated due to issues with the built-in caching mechanism.\n *\n * **Deprecation Reasons:**\n * - The internal caching mechanism relies on Adobe I/O Runtime State API which has reliability issues\n * - Token caching should be managed at the application level for better control and flexibility\n * - The State API may not be available in all runtime environments\n * - TTL buffer calculations (10-minute buffer) are opinionated and may not suit all use cases\n *\n * **Migration Path:**\n * Use `AdobeAuth` class directly and implement caching in your application:\n *\n * @example\n * ```typescript\n * // OLD (Deprecated) - ImsToken with built-in caching\n * const imsToken = new ImsToken(\n * 'client-id',\n * 'client-secret',\n * 'tech-account-id',\n * 'tech@example.com',\n * 'org-id',\n * ['openid', 'AdobeID']\n * );\n * const token = await imsToken.execute();\n *\n * // NEW (Recommended) - AdobeAuth with application-level caching\n * import AdobeAuth from '../../commerce/adobe-auth';\n * import BearerToken from '../../integration/bearer-token';\n *\n * // Check your application cache first\n * let token = await yourAppCache.get('ims_token');\n *\n * if (!token || !BearerToken.info(token).isValid) {\n * // Generate new token using AdobeAuth\n * token = await AdobeAuth.getToken(\n * 'client-id',\n * 'client-secret',\n * 'tech-account-id',\n * 'tech@example.com',\n * 'org-id',\n * ['openid', 'AdobeID'],\n * 'your-context' // optional\n * );\n *\n * // Store in your application cache with appropriate TTL\n * const tokenInfo = BearerToken.info(token);\n * if (tokenInfo.isValid && tokenInfo.timeUntilExpiry) {\n * const ttl = Math.floor(tokenInfo.timeUntilExpiry / 1000) - 600; // 10-min buffer\n * await yourAppCache.set('ims_token', token, ttl);\n * }\n * }\n *\n * // Use the token\n * console.log('Token:', token);\n * ```\n *\n * **Benefits of Using AdobeAuth Directly:**\n * - Full control over caching strategy (Redis, Memcached, in-memory, etc.)\n * - Better error handling and retry logic\n * - Easier to test and mock\n * - No dependency on Adobe I/O Runtime State API\n * - More flexible TTL management based on your application needs\n *\n * This class handles Adobe IMS (Identity Management System) token operations\n * for authenticating API requests to Adobe services.\n */\nclass ImsToken {\n /** OAuth client ID for Adobe IMS authentication */\n private readonly clientId: string;\n\n /** OAuth client secret for Adobe IMS authentication */\n private readonly clientSecret: string;\n\n /** Technical account ID for service-to-service authentication */\n private readonly technicalAccountId: string;\n\n /** Technical account email for service-to-service authentication */\n private readonly technicalAccountEmail: string;\n\n /** IMS organization ID */\n private readonly imsOrgId: string;\n\n /** Array of scopes required for the token */\n private readonly scopes: Array<string>;\n\n /** Custom logger instance for logging operations */\n private readonly customLogger: CustomLogger;\n\n /** State property for managing token state */\n private state: any | undefined = undefined;\n\n /** Optional token context for additional authentication parameters */\n private readonly tokenContext: string;\n\n /** Key for storing token in state (State API only available in Adobe I/O Runtime) */\n private readonly key: string;\n\n /**\n * Creates an instance of ImsToken\n *\n * @deprecated Use `AdobeAuth.getToken()` directly and implement caching in your application.\n * See class documentation for migration examples.\n *\n * @param clientId - OAuth client ID for Adobe IMS authentication\n * @param clientSecret - OAuth client secret for Adobe IMS authentication\n * @param technicalAccountId - Technical account ID for service-to-service authentication\n * @param technicalAccountEmail - Technical account email for service-to-service authentication\n * @param imsOrgId - IMS organization ID\n * @param scopes - Array of scopes required for the token\n * @param logger - Optional logger instance for logging operations\n * @param cacheKey - Optional custom cache key for token storage (defaults to 'runtime_api_gateway_token')\n * @param tokenContext - Optional token context for authentication (defaults to 'runtime-api-gateway-context')\n */\n constructor(\n clientId: string,\n clientSecret: string,\n technicalAccountId: string,\n technicalAccountEmail: string,\n imsOrgId: string,\n scopes: Array<string>,\n logger: any = null,\n cacheKey?: string,\n tokenContext?: string\n ) {\n this.clientId = clientId;\n this.clientSecret = clientSecret;\n this.technicalAccountId = technicalAccountId;\n this.technicalAccountEmail = technicalAccountEmail;\n this.imsOrgId = imsOrgId;\n this.scopes = scopes;\n this.customLogger = new CustomLogger(logger);\n this.key = cacheKey || 'ims_token';\n this.tokenContext = tokenContext || 'ims-context';\n }\n\n /**\n * Executes IMS token generation or retrieves a cached token\n *\n * @deprecated Use `AdobeAuth.getToken()` directly and implement caching in your application.\n * The built-in caching mechanism has reliability issues with the State API.\n * See class documentation for migration examples.\n *\n * This method first checks for a cached token. If a valid cached token exists,\n * it returns that. Otherwise, it generates a new token, caches it, and returns it.\n *\n * @returns A promise that resolves to the IMS token string or null if generation fails\n * @example\n * ```typescript\n * const token = await imsToken.execute();\n * if (token) {\n * console.log('Token obtained:', token);\n * }\n * ```\n */\n async execute(): Promise<string | null> {\n try {\n this.customLogger.info('Starting IMS token generation/retrieval process');\n\n const currentValue = await this.getValue();\n if (currentValue !== null) {\n this.customLogger.info('Found cached IMS token, returning cached value');\n return currentValue;\n }\n\n this.customLogger.info('No cached token found, generating new IMS token');\n\n let result: ImsTokenResult = {\n token: null,\n expire_in: 86399, // Default fallback, will be overridden by actual token expiry\n };\n\n const response = await this.getImsToken();\n if (response !== null) {\n result = response;\n }\n\n if (result.token !== null) {\n this.customLogger.info(`Generated new IMS token, caching for ${result.expire_in} seconds`);\n await this.setValue(result);\n }\n\n return result.token;\n } catch (error: any) {\n this.customLogger.error(`Failed to execute IMS token generation: ${error.message}`);\n return null;\n }\n }\n\n /**\n * Generates a new IMS token from Adobe IMS service\n *\n * @returns A promise that resolves to ImsTokenResult or null if generation fails\n * @private\n */\n async getImsToken(): Promise<ImsTokenResult | null> {\n try {\n this.customLogger.debug(`Calling AdobeAuth.getToken with context: ${this.tokenContext}`);\n\n const token = await AdobeAuth.getToken(\n this.clientId,\n this.clientSecret,\n this.technicalAccountId,\n this.technicalAccountEmail,\n this.imsOrgId,\n this.scopes,\n this.tokenContext\n );\n\n if (token !== null && token !== undefined) {\n this.customLogger.debug('Received token from AdobeAuth, parsing with BearerToken.info');\n\n // Use BearerToken.info to extract actual expiration from JWT token\n const tokenInfo = BearerToken.info(token);\n\n if (!tokenInfo.isValid) {\n this.customLogger.error('Received invalid or expired token from IMS');\n return null;\n }\n\n // Calculate expire_in from timeUntilExpiry (convert milliseconds to seconds)\n const expireInSeconds = tokenInfo.timeUntilExpiry\n ? Math.floor(tokenInfo.timeUntilExpiry / 1000)\n : 86399; // Fallback to 24 hours if unable to determine\n\n this.customLogger.debug(`Token expires in ${expireInSeconds} seconds`);\n\n return {\n token: token,\n expire_in: expireInSeconds,\n };\n }\n\n this.customLogger.error('Received null or undefined token from IMS');\n return null;\n } catch (error: any) {\n this.customLogger.error(`Failed to get IMS token: ${error.message}`);\n return null;\n }\n }\n\n /**\n * Caches the IMS token in the state store with TTL\n *\n * @deprecated This method has issues with State API reliability. Use application-level caching instead.\n *\n * **Known Issues:**\n * - State API may not be available in all runtime environments\n * - Hard-coded 10-minute buffer may not suit all use cases\n * - Minimum 60-minute TTL is opinionated and inflexible\n * - No retry mechanism for State API failures\n *\n * @param result - The token result containing the token and expiration time\n * @returns A promise that resolves to true if caching succeeded, false otherwise\n * @private\n */\n async setValue(result: ImsTokenResult): Promise<boolean> {\n try {\n const state = await this.getState();\n if (state === null) {\n this.customLogger.info('State API not available, skipping token caching');\n // State API not available, skip caching\n return true; // Return true since token generation succeeded\n }\n\n // Apply 10-minute buffer (600 seconds) to prevent token expiry during usage\n const ttlWithBuffer = Math.max(result.expire_in - 600, 3600); // Minimum 60 minutes TTL\n\n this.customLogger.debug(\n `Caching IMS token with TTL: ${ttlWithBuffer} seconds (original: ${result.expire_in})`\n );\n\n await state.put(this.key, result.token, { ttl: ttlWithBuffer });\n return true;\n } catch (error: any) {\n this.customLogger.error(`Failed to cache IMS token: ${error.message}`);\n return true; // Return true since token generation succeeded\n }\n }\n\n /**\n * Retrieves a cached IMS token from the state store\n *\n * @deprecated This method has issues with State API reliability. Use application-level caching instead.\n *\n * **Known Issues:**\n * - State API may not be available in all runtime environments\n * - No validation of cached token expiry\n * - Silent failures may return null without proper error context\n *\n * @returns A promise that resolves to the cached token string or null if not found\n * @private\n */\n async getValue(): Promise<string | null> {\n try {\n this.customLogger.debug('Checking for cached IMS token');\n\n const state = await this.getState();\n if (state === null) {\n this.customLogger.debug('State API not available, cannot retrieve cached token');\n // State API not available, skip caching\n return null;\n }\n\n const value = await state.get(this.key);\n if (value !== undefined && value.value) {\n this.customLogger.debug('Found cached IMS token');\n return value.value;\n }\n\n this.customLogger.debug('No cached IMS token found');\n } catch (error: any) {\n this.customLogger.error(`Failed to retrieve cached IMS token: ${error.message}`);\n }\n\n return null;\n }\n\n /**\n * Initializes and returns the state store instance\n *\n * @deprecated This method relies on State API which has reliability issues.\n * Use application-level caching instead.\n *\n * **Known Issues:**\n * - State API initialization may fail silently\n * - Not available outside Adobe I/O Runtime environments\n * - Caches the state instance which may become stale\n *\n * @returns A promise that resolves to the state instance or null if initialization fails\n * @private\n */\n async getState(): Promise<any> {\n if (this.state === undefined) {\n try {\n this.customLogger.debug('Initializing State API for token caching');\n this.state = await State.init();\n } catch (error: any) {\n this.customLogger.error(`Failed to initialize State API: ${error.message}`);\n this.state = null;\n }\n }\n return this.state;\n }\n}\n\nexport default ImsToken;\n","/**\n * <license header>\n */\n\nimport * as aioLibIms from '@adobe/aio-lib-ims';\nimport { AdobeIMSConfig } from './types';\n\n/**\n * Class providing authentication functionality for Adobe IMS (Identity Management System)\n */\nclass AdobeAuth {\n /**\n * Retrieves an authentication token from Adobe IMS\n *\n * @param clientId - The client ID for the Adobe IMS integration\n * @param clientSecret - The client secret for the Adobe IMS integration\n * @param technicalAccountId - The technical account ID for the Adobe IMS integration\n * @param technicalAccountEmail - The technical account email for the Adobe IMS integration\n * @param imsOrgId - The IMS organization ID\n * @param scopes - Array of permission scopes to request for the token\n * @param currentContext - The context name for storing the configuration (defaults to 'onboarding-config')\n * @returns Promise<string> - A promise that resolves to the authentication token\n *\n * @example\n * const token = await AdobeAuth.getToken(\n * 'your-client-id',\n * 'your-client-secret',\n * 'your-technical-account-id',\n * 'your-technical-account-email',\n * 'your-ims-org-id',\n * ['AdobeID', 'openid', 'adobeio_api']\n * );\n */\n static async getToken(\n clientId: string,\n clientSecret: string,\n technicalAccountId: string,\n technicalAccountEmail: string,\n imsOrgId: string,\n scopes: string[],\n currentContext: string = 'onboarding-config'\n ): Promise<string> {\n const config: AdobeIMSConfig = {\n client_id: clientId,\n client_secrets: [clientSecret],\n technical_account_id: technicalAccountId,\n technical_account_email: technicalAccountEmail,\n ims_org_id: imsOrgId,\n scopes: scopes,\n };\n\n await aioLibIms.context.setCurrent(currentContext);\n await aioLibIms.context.set(currentContext, config);\n\n return await aioLibIms.getToken();\n }\n}\n\nexport default AdobeAuth;\n","/**\n * <license header>\n */\n\nimport type { BearerTokenInfo } from './types';\n\n/**\n * Utility class for extracting and handling Bearer tokens from HTTP request headers.\n * Supports both standard HTTP headers and OpenWhisk action parameter formats for maximum portability.\n */\nclass BearerToken {\n /**\n * Extracts the Bearer token from HTTP request headers and returns detailed token information.\n * Supports both standard HTTP headers and OpenWhisk action parameter formats.\n *\n * @param headersOrParams - Either a standard headers object or OpenWhisk action parameters\n * @returns Detailed token information object\n *\n * @example\n * // Standard HTTP headers approach\n * const headers = {\n * authorization: 'Bearer abc123token'\n * };\n * const tokenInfo = BearerToken.extract(headers);\n *\n * @example\n * // OpenWhisk action parameters (backward compatibility)\n * const params = {\n * __ow_headers: {\n * authorization: 'Bearer abc123token'\n * }\n * };\n * const tokenInfo = BearerToken.extract(params);\n *\n * @example\n * // Both return the same result:\n * // {\n * // token: 'abc123token',\n * // tokenLength: 11,\n * // isValid: true,\n * // expiry: '2024-01-01T12:00:00.000Z',\n * // timeUntilExpiry: 3600000\n * // }\n */\n static extract(headersOrParams: { [key: string]: any }): BearerTokenInfo {\n let token: string | null = null;\n\n // Try standard headers approach first (more portable)\n if (headersOrParams.authorization?.startsWith('Bearer ')) {\n token = headersOrParams.authorization.substring('Bearer '.length);\n }\n // Fall back to OpenWhisk format for backward compatibility\n else if (headersOrParams.__ow_headers?.authorization?.startsWith('Bearer ')) {\n token = headersOrParams.__ow_headers.authorization.substring('Bearer '.length);\n }\n\n return BearerToken.info(token);\n }\n\n /**\n * Analyzes a Bearer token and returns detailed information including validity and expiry.\n * Supports both JWT tokens (with automatic expiry detection) and plain tokens (24h default expiry).\n *\n * @param token - The Bearer token string (or null). Can be JWT or plain token.\n * @returns Detailed token information object\n *\n * @example\n * // Plain token (gets 24h default expiry)\n * const plainTokenInfo = BearerToken.info('abc123token');\n * // returns: {\n * // token: 'abc123token',\n * // tokenLength: 11,\n * // isValid: true,\n * // expiry: '2024-01-02T12:00:00.000Z', // 24h from now\n * // timeUntilExpiry: 86400000 // milliseconds until expiry\n * // }\n *\n * @example\n * // JWT token (automatic expiry detection from 'exp' or 'expires_in' claims)\n * const jwtToken = 'eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MDQ0Njc2MDB9.signature';\n * const jwtTokenInfo = BearerToken.info(jwtToken);\n * // returns: {\n * // token: 'eyJhbGciOiJIUzI1NiJ9...',\n * // tokenLength: 45,\n * // isValid: true, // false if expired\n * // expiry: '2024-01-05T12:00:00.000Z', // from JWT exp claim\n * // timeUntilExpiry: 172800000 // actual time until expiry\n * // }\n *\n * @example\n * // Null or invalid token\n * const nullTokenInfo = BearerToken.info(null);\n * // returns: {\n * // token: null,\n * // tokenLength: 0,\n * // isValid: false,\n * // expiry: null,\n * // timeUntilExpiry: null\n * // }\n */\n static info(token: string | null): BearerTokenInfo {\n const tokenExpiry = BearerToken._calculateExpiry(token);\n\n return {\n token: token,\n tokenLength: token ? token.length : 0,\n isValid: BearerToken._isTokenValid(token, tokenExpiry),\n expiry: tokenExpiry ? tokenExpiry.toISOString() : null,\n timeUntilExpiry: tokenExpiry ? Math.max(0, tokenExpiry.getTime() - Date.now()) : null,\n };\n }\n\n /**\n * Checks if the given token is valid and not expired\n * @private\n * @param token - The bearer token string\n * @param tokenExpiry - The token expiry date\n * @returns {boolean} True if token is valid\n */\n private static _isTokenValid(token: string | null, tokenExpiry: Date | null): boolean {\n if (!token) {\n return false;\n }\n\n if (tokenExpiry && Date.now() >= tokenExpiry.getTime()) {\n console.log('⏰ Token has expired');\n return false;\n }\n\n return true;\n }\n\n /**\n * Calculates token expiry from JWT token or uses default for non-JWT tokens\n * @private\n * @param token - The token string (JWT or plain token)\n * @returns Date object representing token expiry\n */\n private static _calculateExpiry(token: string | null): Date | null {\n // Handle empty tokens\n if (!token) {\n return null;\n }\n\n try {\n // Try to parse as JWT token\n const parts = token.split('.');\n if (parts.length === 3) {\n const payload = JSON.parse(Buffer.from(parts[1] || '', 'base64').toString());\n\n if (payload.expires_in) {\n // expires_in is in milliseconds\n return new Date(Date.now() + parseInt(payload.expires_in));\n }\n\n if (payload.exp) {\n // exp is Unix timestamp in seconds\n return new Date(payload.exp * 1000);\n }\n }\n\n // For non-JWT tokens or JWT tokens without expiry, default to 24 hours\n return new Date(Date.now() + 24 * 60 * 60 * 1000);\n } catch (error) {\n console.warn('[WARN] Could not parse token expiry, using default 24h');\n return new Date(Date.now() + 24 * 60 * 60 * 1000);\n }\n }\n}\n\nexport default BearerToken;\nexport type { BearerTokenInfo } from './types';\n","/**\n * <license header>\n */\n\n/**\n * Result interface for IMS token operations\n *\n * @deprecated This interface is part of the deprecated `ImsToken` class.\n * Use `AdobeAuth.getToken()` directly and implement your own caching with `BearerToken.info()`.\n *\n * For token validation and expiry information, use:\n * ```typescript\n * import BearerToken from '../../integration/bearer-token';\n *\n * const tokenInfo = BearerToken.info(token);\n * // tokenInfo.isValid\n * // tokenInfo.timeUntilExpiry (in milliseconds)\n * ```\n */\nexport interface ImsTokenResult {\n token: string | null;\n expire_in: number;\n}\n","/**\n * <license header>\n */\n\nimport RestClient from '../../integration/rest-client';\nimport CustomLogger from '../custom-logger';\n\n/**\n * RuntimeApiGatewayService for Adobe Runtime API Gateway\n *\n * This service provides a flexible way to interact with Adobe I/O Runtime API Gateway\n * endpoints with authentication and authorization support.\n *\n * Key Features:\n * - Built-in authentication headers\n * - Centralized error handling\n * - Support for common HTTP methods (GET, POST, PUT, DELETE)\n *\n * @example\n * ```typescript\n * const service = new RuntimeApiGatewayService(\n * 'test-namespace',\n * 'org-id@AdobeOrg',\n * 'bearer-token-string',\n * logger\n * );\n *\n * // GET request\n * const data = await service.get('v1/my-endpoint', { 'Custom-Header': 'value' });\n * ```\n */\nexport class RuntimeApiGatewayService {\n /** Base URL for the Adobe I/O Runtime APIs */\n private static readonly BASE_URL = 'https://adobeioruntime.net/apis';\n\n /** The namespace identifier for the Adobe I/O Runtime actions */\n private readonly namespace: string;\n\n /** IMS organization ID */\n private readonly imsOrgId: string;\n\n /** Bearer token for authentication */\n private readonly imsToken: string;\n\n /** RestClient instance for making HTTP requests */\n private readonly restClient: RestClient;\n\n /** CustomLogger instance for logging */\n private readonly customLogger: CustomLogger;\n\n /**\n * Creates an instance of RuntimeApiGatewayService\n *\n * @param namespace - The Adobe I/O Runtime namespace identifier\n * @param imsOrgId - IMS organization ID\n * @param imsToken - Bearer token string for authentication\n * @param logger - Optional logger instance for logging operations\n * @example\n * ```typescript\n * const service = new RuntimeApiGatewayService(\n * 'test-namespace',\n * 'org-id@AdobeOrg',\n * 'bearer-token-string',\n * logger\n * );\n * ```\n */\n constructor(namespace: string, imsOrgId: string, imsToken: string, logger: any = null) {\n this.namespace = namespace;\n this.imsOrgId = imsOrgId;\n this.imsToken = imsToken;\n this.restClient = new RestClient();\n this.customLogger = new CustomLogger(logger);\n }\n\n /**\n * Builds the complete API endpoint URL\n *\n * @param endpoint - API endpoint path (e.g., 'v1/my-endpoint')\n * @returns The fully constructed endpoint URL\n * @private\n */\n private buildEndpoint(endpoint: string): string {\n return `${RuntimeApiGatewayService.BASE_URL}/${this.namespace}/${endpoint}`;\n }\n\n /**\n * Gets the authenticated headers for API requests\n *\n * @returns Headers object including authentication\n * @private\n */\n private getAuthenticatedHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.imsToken}`,\n 'x-gw-ims-org-id': this.imsOrgId,\n };\n }\n\n /**\n * Performs a GET request to the Runtime API Gateway\n *\n * @param endpoint - API endpoint path (e.g., 'v1/my-endpoint')\n * @param additionalHeaders - Optional additional headers to include in the request\n * @returns A promise that resolves with the API response data\n * @throws {Error} If the API request fails\n * @example\n * ```typescript\n * const service = new RuntimeApiGatewayService(...);\n * const data = await service.get('v1/my-endpoint');\n *\n * // With additional headers\n * const data = await service.get('v1/my-endpoint', { 'Custom-Header': 'value' });\n * ```\n */\n async get(endpoint: string, additionalHeaders: Record<string, string> = {}): Promise<any> {\n try {\n const url = this.buildEndpoint(endpoint);\n this.customLogger.info(`Performing GET request to: ${url}`);\n const headers = { ...this.getAuthenticatedHeaders(), ...additionalHeaders };\n this.customLogger.debug(`GET headers: ${JSON.stringify(headers)}`);\n\n const response = await this.restClient.get(url, headers, false);\n this.customLogger.debug(`GET response: ${JSON.stringify(response)}`);\n this.customLogger.info('GET request completed successfully');\n return response;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n this.customLogger.error(`GET request failed: ${errorMessage}`);\n throw new Error(`Runtime API gateway GET request failed: ${errorMessage}`);\n }\n }\n\n /**\n * Performs a POST request to the Runtime API Gateway\n *\n * @param endpoint - API endpoint path (e.g., 'v1/my-endpoint')\n * @param payload - The data to send in the request body\n * @param additionalHeaders - Optional additional headers to include in the request\n * @returns A promise that resolves with the API response data\n * @throws {Error} If the API request fails\n * @example\n * ```typescript\n * const service = new RuntimeApiGatewayService(...);\n * const result = await service.post('v1/my-endpoint', { key: 'value' });\n *\n * // With additional headers\n * const result = await service.post('v1/my-endpoint', { key: 'value' }, { 'Custom-Header': 'value' });\n * ```\n */\n async post(\n endpoint: string,\n payload: any,\n additionalHeaders: Record<string, string> = {}\n ): Promise<any> {\n try {\n const url = this.buildEndpoint(endpoint);\n this.customLogger.info(`Performing POST request to: ${url}`);\n this.customLogger.debug(`POST payload: ${JSON.stringify(payload)}`);\n const headers = { ...this.getAuthenticatedHeaders(), ...additionalHeaders };\n this.customLogger.debug(`POST headers: ${JSON.stringify(headers)}`);\n\n const response = await this.restClient.post(url, headers, payload, false);\n this.customLogger.debug(`POST response: ${JSON.stringify(response)}`);\n this.customLogger.info('POST request completed successfully');\n return response;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n this.customLogger.error(`POST request failed: ${errorMessage}`);\n throw new Error(`Runtime API gateway POST request failed: ${errorMessage}`);\n }\n }\n\n /**\n * Performs a PUT request to the Runtime API Gateway\n *\n * @param endpoint - API endpoint path (e.g., 'v1/my-endpoint')\n * @param payload - The data to send in the request body\n * @param additionalHeaders - Optional additional headers to include in the request\n * @returns A promise that resolves with the API response data\n * @throws {Error} If the API request fails\n * @example\n * ```typescript\n * const service = new RuntimeApiGatewayService(...);\n * const updated = await service.put('v1/my-endpoint', { id: 1, name: 'updated' });\n *\n * // With additional headers\n * const updated = await service.put('v1/my-endpoint', { id: 1 }, { 'Custom-Header': 'value' });\n * ```\n */\n async put(\n endpoint: string,\n payload: any,\n additionalHeaders: Record<string, string> = {}\n ): Promise<any> {\n try {\n const url = this.buildEndpoint(endpoint);\n this.customLogger.info(`Performing PUT request to: ${url}`);\n this.customLogger.debug(`PUT payload: ${JSON.stringify(payload)}`);\n const headers = { ...this.getAuthenticatedHeaders(), ...additionalHeaders };\n this.customLogger.debug(`PUT headers: ${JSON.stringify(headers)}`);\n\n const response = await this.restClient.put(url, headers, payload, false);\n this.customLogger.debug(`PUT response: ${JSON.stringify(response)}`);\n this.customLogger.info('PUT request completed successfully');\n return response;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n this.customLogger.error(`PUT request failed: ${errorMessage}`);\n throw new Error(`Runtime API gateway PUT request failed: ${errorMessage}`);\n }\n }\n\n /**\n * Performs a DELETE request to the Runtime API Gateway\n *\n * @param endpoint - API endpoint path (e.g., 'v1/my-endpoint')\n * @param additionalHeaders - Optional additional headers to include in the request\n * @returns A promise that resolves with the API response data\n * @throws {Error} If the API request fails\n * @example\n * ```typescript\n * const service = new RuntimeApiGatewayService(...);\n * const deleted = await service.delete('v1/my-endpoint');\n *\n * // With additional headers\n * const deleted = await service.delete('v1/my-endpoint', { 'Custom-Header': 'value' });\n * ```\n */\n async delete(endpoint: string, additionalHeaders: Record<string, string> = {}): Promise<any> {\n try {\n const url = this.buildEndpoint(endpoint);\n this.customLogger.info(`Performing DELETE request to: ${url}`);\n const headers = { ...this.getAuthenticatedHeaders(), ...additionalHeaders };\n this.customLogger.debug(`DELETE headers: ${JSON.stringify(headers)}`);\n\n const response = await this.restClient.delete(url, headers, false);\n this.customLogger.debug(`DELETE response: ${JSON.stringify(response)}`);\n this.customLogger.info('DELETE request completed successfully');\n return response;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n this.customLogger.error(`DELETE request failed: ${errorMessage}`);\n throw new Error(`Runtime API gateway DELETE request failed: ${errorMessage}`);\n }\n }\n}\n","/**\n * <license header>\n */\n\nimport fetch, { RequestInit, Response } from 'node-fetch';\nimport { Headers } from './types';\n\nclass RestClient {\n /**\n * A completely raw method to make HTTP requests\n *\n * @param endpoint\n * @param method\n * @param headers\n * @param payload\n * @returns {Promise<Response>}\n */\n async makeRequest(\n endpoint: string,\n method: string = 'GET',\n headers: Headers = {},\n payload: any = null\n ): Promise<Response> {\n let options: RequestInit = {\n method: method,\n headers: headers,\n };\n\n if (payload !== null) {\n let body: any;\n let contentType: string | undefined;\n\n // Handle different payload types\n if (payload instanceof URLSearchParams) {\n // Form-encoded data\n body = payload.toString();\n contentType = headers['Content-Type'] || 'application/x-www-form-urlencoded';\n } else if (typeof FormData !== 'undefined' && payload instanceof FormData) {\n // Multipart form data - let browser set Content-Type with boundary\n body = payload;\n contentType = headers['Content-Type']; // Don't set default, browser handles this\n } else if (typeof payload === 'string') {\n // String payloads (text, XML, etc.)\n body = payload;\n contentType = headers['Content-Type'] || 'text/plain';\n } else if (\n payload instanceof Buffer ||\n payload instanceof ArrayBuffer ||\n (typeof Uint8Array !== 'undefined' && payload instanceof Uint8Array)\n ) {\n // Binary data\n body = payload;\n contentType = headers['Content-Type'] || 'application/octet-stream';\n } else {\n // Regular objects/primitives as JSON\n body = JSON.stringify(payload);\n contentType = headers['Content-Type'] || 'application/json';\n }\n\n // Build options with appropriate headers\n const requestHeaders = { ...headers };\n if (contentType) {\n requestHeaders['Content-Type'] = contentType;\n }\n\n options = {\n ...options,\n body,\n headers: requestHeaders,\n };\n }\n\n return await fetch(endpoint, options);\n }\n\n /**\n * A method to parse HTTP response\n *\n * @param response\n * @returns {Promise<any>}\n */\n async parseResponse(response: Response): Promise<any> {\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n // Handle responses with no content (like 204 No Content)\n if (response.status === 204 || response.headers?.get('content-length') === '0') {\n return null;\n }\n\n // Try JSON first (for both real responses and mocked responses)\n if (typeof response.json === 'function') {\n const contentType = response.headers?.get('content-type');\n // If no content-type header (mocked response) or JSON content-type, parse as JSON\n if (\n !contentType ||\n contentType.includes('application/json') ||\n contentType.includes('application/hal+json')\n ) {\n return await response.json();\n }\n }\n\n // For non-JSON responses, return text\n if (typeof response.text === 'function') {\n const text = await response.text();\n return text;\n }\n\n // Fallback for responses without text/json methods\n return null;\n }\n\n /**\n * A generic method to make GET rest call\n *\n * @param endpoint\n * @param headers\n * @param parsed\n * @returns {Promise<Response | any>}\n */\n async get(\n endpoint: string,\n headers: Headers = {},\n parsed: boolean = true\n ): Promise<Response | any> {\n const response = await this.makeRequest(endpoint, 'GET', headers);\n return parsed ? await this.parseResponse(response) : response;\n }\n\n /**\n * A generic method to make POST rest call\n *\n * @param endpoint\n * @param headers\n * @param payload\n * @param parsed\n * @returns {Promise<Response | any>}\n */\n async post(\n endpoint: string,\n headers: Headers = {},\n payload: any = null,\n parsed: boolean = true\n ): Promise<Response | any> {\n const response = await this.makeRequest(endpoint, 'POST', headers, payload);\n return parsed ? await this.parseResponse(response) : response;\n }\n\n /**\n * A generic method to make PUT rest call\n *\n * @param endpoint\n * @param headers\n * @param payload\n * @param parsed\n * @returns {Promise<Response | any>}\n */\n async put(\n endpoint: string,\n headers: Headers = {},\n payload: any = null,\n parsed: boolean = true\n ): Promise<Response | any> {\n const response = await this.makeRequest(endpoint, 'PUT', headers, payload);\n return parsed ? await this.parseResponse(response) : response;\n }\n\n /**\n * A generic method to make DELETE rest call\n *\n * @param endpoint\n * @param headers\n * @param parsed\n * @returns {Promise<Response | any>}\n */\n async delete(\n endpoint: string,\n headers: Headers = {},\n parsed: boolean = true\n ): Promise<Response | any> {\n const response = await this.makeRequest(endpoint, 'DELETE', headers);\n return parsed ? await this.parseResponse(response) : response;\n }\n\n /**\n * A generic method to make rest call\n *\n * @param endpoint\n * @param method\n * @param headers\n * @param payload\n * @returns {Promise<any>}\n * @deprecated Use makeRequest() and parseResponse() methods instead\n */\n async apiCall(\n endpoint: string,\n method: string = 'POST',\n headers: Headers = {},\n payload: any = null\n ): Promise<any> {\n let options: RequestInit = {\n method: method,\n headers: headers,\n };\n\n if (payload !== null) {\n options = {\n ...options,\n body: JSON.stringify(payload),\n headers: {\n ...headers,\n 'Content-Type': 'application/json',\n },\n };\n }\n\n const response: Response = await fetch(endpoint, options);\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n // Handle responses with no content (like 204 No Content)\n if (response.status === 204 || response.headers?.get('content-length') === '0') {\n return null;\n }\n\n // Try JSON first (for both real responses and mocked responses)\n if (typeof response.json === 'function') {\n const contentType = response.headers?.get('content-type');\n // If no content-type header (mocked response) or JSON content-type, parse as JSON\n if (\n !contentType ||\n contentType.includes('application/json') ||\n contentType.includes('application/hal+json')\n ) {\n return await response.json();\n }\n }\n\n // For non-JSON responses, return text\n if (typeof response.text === 'function') {\n const text = await response.text();\n return text;\n }\n\n // Fallback for responses without text/json methods\n return null;\n }\n}\n\nexport default RestClient;\n","/**\n * <license header>\n */\n\n/**\n * Configuration type for OpenTelemetry entrypoint instrumentation\n * Re-exported from @adobe/aio-lib-telemetry for type safety\n */\nexport type EntrypointInstrumentationConfig = any;\n\n/**\n * Base interface for telemetry validator implementations\n *\n * Defines the contract that all telemetry validators must implement to\n * validate and check configuration for their respective providers.\n *\n * Validators are responsible for:\n * - Checking if the provider is configured (enabled)\n * - Validating required configuration parameters\n *\n * @example Implementing a custom telemetry validator\n * ```typescript\n * class CustomTelemetryValidator implements BaseTelemetryValidator {\n * isConfigured(params: Record<string, unknown>): boolean {\n * return params.ENABLE_TELEMETRY === true &&\n * params.CUSTOM_TELEMETRY === true;\n * }\n *\n * validateConfiguration(params: Record<string, unknown>): void {\n * if (!params.CUSTOM_API_KEY) {\n * throw new TelemetryInputError('CUSTOM_API_KEY is required');\n * }\n * }\n * }\n * ```\n */\nexport interface BaseTelemetryValidator {\n /**\n * Check if the telemetry provider is configured\n *\n * Determines whether the provider is enabled based on runtime parameters.\n * This method does NOT validate configuration completeness, only checks\n * if the provider should be active.\n *\n * @param params - Runtime parameters to check\n * @returns true if provider is configured and enabled, false otherwise\n */\n isConfigured(params: Record<string, unknown>): boolean;\n\n /**\n * Validate the telemetry provider configuration\n *\n * Validates that all required configuration parameters are present and valid.\n * This method should only be called after isConfigured() returns true.\n *\n * @param params - Runtime parameters to validate\n * @throws {TelemetryInputError} If required configuration is missing or invalid\n */\n validateConfiguration(params: Record<string, unknown>): void;\n}\n\n/**\n * Base interface for telemetry provider implementations\n *\n * Defines the contract that all telemetry providers must implement to\n * integrate with the Adobe I/O Runtime action instrumentation system.\n *\n * Implementations should provide:\n * - Configuration for OpenTelemetry SDK (exporters, instrumentations, resources)\n * - Action initialization logic that wraps the action with telemetry\n *\n * @example Implementing a custom telemetry provider\n * ```typescript\n * class CustomTelemetry implements BaseTelemetry {\n * getConfig(): EntrypointInstrumentationConfig {\n * return defineTelemetryConfig((params) => ({\n * sdkConfig: {\n * serviceName: params.SERVICE_NAME as string,\n * instrumentations: getPresetInstrumentations('simple'),\n * }\n * }));\n * }\n *\n * initialize(action) {\n * return instrumentEntrypoint(action, this.getConfig());\n * }\n * }\n * ```\n */\nexport interface BaseTelemetry {\n /**\n * Check if this telemetry provider is configured and should be initialized\n *\n * Determines whether the telemetry provider is enabled based on runtime\n * parameters. Returns true if the provider should be initialized, false\n * to skip to the next provider in the chain.\n *\n * This method does NOT validate configuration completeness, it only checks\n * if the provider is enabled. Validation happens during initialization.\n *\n * @param params - Runtime parameters to check\n * @returns true if provider is configured and enabled, false otherwise\n *\n * @example\n * ```typescript\n * const params = { ENABLE_TELEMETRY: true, NEW_RELIC_TELEMETRY: true };\n * if (telemetry.canInitialize(params)) {\n * // Provider is enabled, proceed with initialization\n * }\n * ```\n */\n canInitialize(params: Record<string, unknown>): boolean;\n\n /**\n * Get the OpenTelemetry instrumentation configuration\n *\n * Returns configuration that defines how telemetry data should be collected\n * and exported. This includes:\n * - SDK configuration (service name, instrumentations, resource attributes)\n * - Exporters for traces, metrics, and logs\n * - Custom behavior (success detection, sampling, etc.)\n *\n * @returns Complete entrypoint instrumentation configuration for the provider\n *\n * @example\n * ```typescript\n * const config = telemetry.getConfig();\n * // config contains sdkConfig, isSuccessful callback, etc.\n * ```\n */\n getConfig(): EntrypointInstrumentationConfig;\n\n /**\n * Wrap a runtime action with telemetry instrumentation\n *\n * Takes an action function and returns an instrumented version that\n * automatically collects telemetry data (traces, metrics, logs) during\n * execution. The instrumented action has the same signature as the original.\n *\n * @param action - The runtime action function to instrument\n * @returns Instrumented action function with telemetry enabled\n *\n * @example\n * ```typescript\n * async function myAction(params) {\n * return { statusCode: 200, body: { success: true } };\n * }\n *\n * const instrumented = telemetry.initialize(myAction);\n * export const main = instrumented;\n * ```\n */\n initialize(\n action: (params: Record<string, unknown>) => any\n ): (params: Record<string, unknown>) => any;\n}\n","/**\n * <license header>\n */\n\n/**\n * Integration utilities for Adobe Commerce AIO Toolkit\n */\n\n// Export Bearer Token utility\nexport { default as BearerToken } from './bearer-token';\nexport type { BearerTokenInfo } from './bearer-token/types';\n\n// Export REST Client\nexport { default as RestClient } from './rest-client';\n\n// Export REST Client types\nexport type { Headers } from './rest-client/types';\n\n// Export Onboard Events\n/**\n * @deprecated Use OnboardIOEvents instead. This export will be removed in a future version.\n */\nexport { default as OnboardEvents } from './onboard-events';\nexport { default as OnboardIOEvents } from './onboard-events';\nexport { default as CreateEvents } from './onboard-events/create-events';\nexport { default as CreateRegistrations } from './onboard-events/create-registrations';\n\n// Export Onboard Events types\nexport type {\n OnboardEventsInput,\n OnboardEventsResponse,\n CreateProviderResult,\n CreateEventResult,\n CreateRegistrationResult,\n} from './onboard-events/types';\n\n// Export Infinite Loop Breaker\nexport { default as InfiniteLoopBreaker } from './infinite-loop-breaker';\n\n// Export Infinite Loop Breaker types\nexport type { InfiniteLoopData } from './infinite-loop-breaker/types';\n\n// Export OnboardCommerce\nexport { default as OnboardCommerce } from './onboard-commerce';\n\n// Export OnboardCommerce types\nexport type {\n OnboardCommerceConfig,\n OnboardCommerceResult,\n WorkspaceConfig,\n CommerceEventConfig,\n CommerceEvent,\n CommerceEventField,\n} from './onboard-commerce/types';\n","/**\n * <license header>\n */\n\nimport { Core, Logger } from '@adobe/aio-sdk';\nimport type { OnboardEventsInput, OnboardEventsResponse, OnboardEventsSummary } from './types';\nimport CreateProviders from './create-providers';\nimport CreateEvents from './create-events';\nimport CreateRegistrations from './create-registrations';\nimport InputParser from './input-parser';\n\n/**\n * Utility class for handling onboarding events in Adobe Commerce integrations\n *\n * @example\n * const onboardEvents = new OnboardEvents(\n * 'My Adobe Commerce Project',\n * 'your-consumer-id',\n * 'your-project-id',\n * 'your-workspace-id',\n * 'your-api-key',\n * 'your-access-token'\n * );\n *\n * // Get the configured logger for consistent logging\n * const logger = onboardEvents.getLogger();\n * logger.info('Custom logging with the same configuration');\n *\n * // Process onboard events input\n * await onboardEvents.process({ providers });\n */\nclass OnboardEvents {\n private readonly logger: Logger;\n private readonly createProviders: CreateProviders;\n private readonly createEvents: CreateEvents;\n private readonly createRegistrations: CreateRegistrations;\n\n /**\n * Creates a new OnboardEvents instance\n *\n * @param projectName - Name of the Adobe Commerce project\n * @param consumerId - Adobe I/O consumer ID\n * @param projectId - Adobe I/O project ID\n * @param workspaceId - Adobe I/O workspace ID\n * @param apiKey - API key for authentication\n * @param accessToken - Access token for API calls\n */\n constructor(\n private readonly projectName: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly apiKey: string,\n private readonly accessToken: string\n ) {\n if (!projectName) {\n throw new Error('Project name is required');\n }\n\n if (!consumerId) {\n throw new Error('Consumer ID is required');\n }\n\n if (!projectId) {\n throw new Error('Project ID is required');\n }\n\n if (!workspaceId) {\n throw new Error('Workspace ID is required');\n }\n\n if (!apiKey) {\n throw new Error('API key is required');\n }\n\n if (!accessToken) {\n throw new Error('Access token is required');\n }\n\n // create a Logger using project name\n const loggerName = projectName\n .toLowerCase()\n .replace(/[^a-z0-9\\s-_]/g, '') // Remove special characters except spaces, hyphens, underscores\n .replace(/\\s+/g, '-') // Replace spaces with hyphens\n .replace(/_{2,}/g, '_') // Replace multiple underscores with single\n .replace(/-{2,}/g, '-') // Replace multiple hyphens with single\n .trim()\n .concat('-onboard-events'); // Add suffix to identify as onboard events logger\n this.logger = Core.Logger(loggerName, { level: 'debug' });\n\n // Initialize CreateProviders instance\n this.createProviders = new CreateProviders(\n consumerId,\n projectId,\n workspaceId,\n apiKey,\n accessToken,\n this.logger\n );\n\n // Initialize CreateEvents instance\n this.createEvents = new CreateEvents(\n consumerId,\n projectId,\n workspaceId,\n apiKey, // Using apiKey as clientId\n accessToken,\n this.logger\n );\n\n // Initialize CreateRegistrations instance\n this.createRegistrations = new CreateRegistrations(\n consumerId,\n projectId,\n workspaceId,\n apiKey, // Using apiKey as clientId\n accessToken,\n this.logger\n );\n }\n\n /**\n * Gets the configured logger instance for consistent logging\n *\n * @returns The configured logger instance\n */\n getLogger(): Logger {\n return this.logger;\n }\n\n /**\n * Processes the onboarding events\n *\n * @param input - Onboard events input configuration containing providers, registrations, and events\n * @returns Promise resolving to processing result with created providers\n */\n async process(input: OnboardEventsInput): Promise<OnboardEventsResponse> {\n this.logger.debug(\n `[START] Processing onboard events for project: ${this.projectName} (${this.projectId}) with ${input.providers.length} providers`\n );\n\n const inputParser = new InputParser(input);\n const entities = inputParser.getEntities();\n\n // Use CreateProviders to create the providers\n const providerResults = await this.createProviders.process(\n entities.providers,\n this.projectName\n );\n\n // Use CreateEvents to create the events\n const eventResults = await this.createEvents.process(\n entities.events,\n providerResults,\n this.projectName\n );\n\n // Use CreateRegistrations to create the registrations\n const registrationResults = await this.createRegistrations.process(\n entities.registrations,\n entities.events,\n providerResults,\n this.projectName\n );\n\n const response = {\n createdProviders: providerResults,\n createdEvents: eventResults,\n createdRegistrations: registrationResults,\n };\n\n // Generate and log comprehensive summary\n const summary = this.generateSummary(response);\n this.logSummary(summary);\n\n return response;\n }\n\n /**\n * Generates a concise summary of onboard events processing results\n * @private\n * @param response - The response from the onboard events processing\n * @returns A concise summary with IDs and status information\n */\n private generateSummary(response: OnboardEventsResponse): OnboardEventsSummary {\n // Process providers\n const providerItems = response.createdProviders.map(result => ({\n id: result.provider.id,\n key: result.provider.key,\n label: result.provider.label,\n status: result.created\n ? ('created' as const)\n : result.skipped\n ? ('existing' as const)\n : ('failed' as const),\n error: result.error,\n }));\n\n const providerCounts = {\n created: response.createdProviders.filter(r => r.created).length,\n existing: response.createdProviders.filter(r => r.skipped).length,\n failed: response.createdProviders.filter(r => !r.created && !r.skipped).length,\n total: response.createdProviders.length,\n };\n\n // Process events\n const eventItems = response.createdEvents.map(result => ({\n id: result.event.id,\n eventCode: result.event.eventCode,\n label: result.event.eventCode,\n status: result.created\n ? ('created' as const)\n : result.skipped\n ? ('existing' as const)\n : ('failed' as const),\n provider: result.provider?.key,\n error: result.error,\n }));\n\n const eventCounts = {\n created: response.createdEvents.filter(r => r.created).length,\n existing: response.createdEvents.filter(r => r.skipped).length,\n failed: response.createdEvents.filter(r => !r.created && !r.skipped).length,\n total: response.createdEvents.length,\n };\n\n // Process registrations\n const registrationItems = response.createdRegistrations.map(result => ({\n id: result.registration.id,\n key: result.registration.key,\n label: result.registration.label,\n status: result.created\n ? ('created' as const)\n : result.skipped\n ? ('existing' as const)\n : ('failed' as const),\n provider: result.provider?.key,\n error: result.error,\n }));\n\n const registrationCounts = {\n created: response.createdRegistrations.filter(r => r.created).length,\n existing: response.createdRegistrations.filter(r => r.skipped).length,\n failed: response.createdRegistrations.filter(r => !r.created && !r.skipped).length,\n total: response.createdRegistrations.length,\n };\n\n // Calculate overall totals\n const overall = {\n totalProcessed: providerCounts.total + eventCounts.total + registrationCounts.total,\n totalCreated: providerCounts.created + eventCounts.created + registrationCounts.created,\n totalExisting: providerCounts.existing + eventCounts.existing + registrationCounts.existing,\n totalFailed: providerCounts.failed + eventCounts.failed + registrationCounts.failed,\n };\n\n return {\n providers: {\n items: providerItems,\n counts: providerCounts,\n },\n events: {\n items: eventItems,\n counts: eventCounts,\n },\n registrations: {\n items: registrationItems,\n counts: registrationCounts,\n },\n overall,\n };\n }\n\n /**\n * Logs a formatted summary of onboard events processing results\n * @private\n * @param summary - The summary to log\n */\n private logSummary(summary: OnboardEventsSummary): void {\n this.logger.info('='.repeat(60));\n this.logger.info(`📊 ONBOARD EVENTS SUMMARY - ${this.projectName}`);\n this.logger.info('='.repeat(60));\n\n this.logger.info('');\n // Overall summary\n this.logger.info(\n `📈 OVERALL: ${summary.overall.totalProcessed} processed | ${summary.overall.totalCreated} created | ${summary.overall.totalExisting} existing | ${summary.overall.totalFailed} failed`\n );\n this.logger.info('');\n\n // Providers summary\n if (summary.providers.counts.total > 0) {\n this.logger.info(`🏭 PROVIDERS (${summary.providers.counts.total}):`);\n summary.providers.items.forEach(item => {\n const status = item.status === 'created' ? '✅' : item.status === 'existing' ? '⏭️' : '❌';\n const id = item.id ? ` [ID: ${item.id}]` : '';\n const error = item.error ? ` - Error: ${item.error}` : '';\n this.logger.info(` ${status} ${item.key} - ${item.label}${id}${error}`);\n });\n this.logger.info('');\n }\n\n // Events summary\n if (summary.events.counts.total > 0) {\n this.logger.info(`📅 EVENTS (${summary.events.counts.total}):`);\n summary.events.items.forEach(item => {\n const status = item.status === 'created' ? '✅' : item.status === 'existing' ? '⏭️' : '❌';\n const id = item.id ? ` [ID: ${item.id}]` : '';\n const provider = item.provider ? ` (Provider: ${item.provider})` : '';\n const error = item.error ? ` - Error: ${item.error}` : '';\n this.logger.info(` ${status} ${item.eventCode}${provider}${id}${error}`);\n });\n this.logger.info('');\n }\n\n // Registrations summary\n if (summary.registrations.counts.total > 0) {\n this.logger.info(`📋 REGISTRATIONS (${summary.registrations.counts.total}):`);\n summary.registrations.items.forEach(item => {\n const status = item.status === 'created' ? '✅' : item.status === 'existing' ? '⏭️' : '❌';\n const id = item.id ? ` [ID: ${item.id}]` : '';\n const provider = item.provider ? ` (Provider: ${item.provider})` : '';\n const error = item.error ? ` - Error: ${item.error}` : '';\n this.logger.info(` ${status} ${item.key} - ${item.label}${provider}${id}${error}`);\n });\n this.logger.info('');\n }\n\n this.logger.info('='.repeat(60));\n }\n}\n\nexport default OnboardEvents;\n","/**\n * <license header>\n */\n\nimport type { Logger } from '@adobe/aio-sdk';\nimport type { ParsedProvider, CreateProviderResult } from '../types';\nimport { ProviderManager } from '../../../io-events';\nimport { randomUUID } from 'crypto';\n\n/**\n * Utility class for creating providers in Adobe Commerce onboarding integrations\n *\n * @example\n * const logger = Core.Logger('my-create-providers', { level: 'debug' });\n * const createProviders = new CreateProviders(\n * 'your-consumer-id',\n * 'your-project-id',\n * 'your-workspace-id',\n * 'your-api-key',\n * 'your-access-token',\n * logger\n * );\n *\n * // Process providers for creation\n * await createProviders.process(providers);\n */\nclass CreateProviders {\n private readonly logger: Logger;\n private providerManager: ProviderManager | null = null;\n\n /**\n * Creates a new CreateProviders instance\n *\n * @param consumerId - Adobe I/O consumer ID\n * @param projectId - Adobe I/O project ID\n * @param workspaceId - Adobe I/O workspace ID\n * @param apiKey - API key for authentication\n * @param accessToken - Access token for API calls\n * @param logger - Logger instance for consistent logging\n */\n constructor(\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly apiKey: string,\n private readonly accessToken: string,\n logger: Logger\n ) {\n // Validate configuration\n const config = {\n consumerId: this.consumerId,\n projectId: this.projectId,\n workspaceId: this.workspaceId,\n apiKey: this.apiKey,\n accessToken: this.accessToken,\n };\n const required = ['consumerId', 'projectId', 'workspaceId', 'apiKey', 'accessToken'];\n const missing = required.filter(\n key => !config[key as keyof typeof config] || config[key as keyof typeof config].trim() === ''\n );\n\n if (missing.length > 0) {\n throw new Error(`Missing required configuration: ${missing.join(', ')}`);\n }\n\n if (!logger) {\n throw new Error('Logger is required');\n }\n\n // Use the provided logger\n this.logger = logger;\n\n this.logger.debug(`[INIT] CreateProviders initialized with valid configuration`);\n }\n\n /**\n * Processes providers for creation in the Adobe Commerce integration\n *\n * @param providers - Array of parsed provider configurations to create\n * @param projectName - Name of the project for enhanced labeling\n * @returns Promise resolving to processing result\n */\n async process(\n providers: ParsedProvider[],\n projectName: string = 'Unknown Project'\n ): Promise<CreateProviderResult[]> {\n this.logger.debug(`[CREATE] Creating providers for project: ${projectName}`);\n this.logger.debug(`[INFO] Processing ${providers.length} provider(s)...`);\n\n try {\n // Fetch existing providers first\n const existingProviders = await this.getProviders();\n\n const results: CreateProviderResult[] = [];\n\n for (const provider of providers) {\n const result = await this.createProvider(provider, projectName, existingProviders);\n results.push(result);\n }\n\n this.logger.debug('[DONE] Provider creation completed');\n\n // Show provider IDs in results\n results.forEach(result => {\n if (result.provider.id) {\n this.logger.debug(\n `[ID] Provider ID: ${result.provider.id} (${result.provider.originalLabel})`\n );\n }\n });\n\n return results;\n } catch (error: any) {\n this.logger.error(`[ERROR] Provider creation failed: ${error.message}`);\n throw error;\n }\n }\n\n /**\n * Gets the Provider SDK instance from the framework\n * @private\n */\n private getProviderManager(): ProviderManager {\n if (!this.providerManager) {\n this.providerManager = new ProviderManager(\n this.apiKey,\n this.consumerId,\n this.projectId,\n this.workspaceId,\n this.accessToken\n );\n }\n\n return this.providerManager;\n }\n\n /**\n * Gets existing providers from Adobe I/O\n * @returns Promise<Map> Map of existing providers by label\n */\n private async getProviders(): Promise<Map<string, any>> {\n this.logger.debug('[FETCH] Fetching existing providers...');\n\n try {\n const providerManager = this.getProviderManager();\n const providerList = await providerManager.list();\n\n const existingProviders = new Map<string, any>();\n providerList.forEach((provider: any) => {\n existingProviders.set(provider.label, provider);\n });\n\n this.logger.debug(`[INFO] Found ${existingProviders.size} existing providers`);\n return existingProviders;\n } catch (error: any) {\n this.logger.error(`[ERROR] Failed to fetch existing providers: ${error.message}`);\n throw error;\n }\n }\n\n /**\n * Creates a single provider\n * @param providerData - Provider configuration data\n * @param projectName - Project name for enhanced labeling\n * @param existingProviders - Map of existing providers by label\n * @private\n */\n private async createProvider(\n providerData: ParsedProvider,\n projectName: string,\n existingProviders: Map<string, any>\n ): Promise<CreateProviderResult> {\n const enhancedLabel = `${projectName} - ${providerData.label}`;\n this.logger.debug(\n `[PROCESS] Processing provider: ${providerData.label} with enhanced label: ${enhancedLabel}`\n );\n\n // Check if provider already exists\n const existingProvider = existingProviders.get(enhancedLabel);\n\n if (existingProvider) {\n this.logger.debug(`[SKIP] Provider already exists - skipping creation`);\n this.logger.debug(`[ID] Existing ID: ${existingProvider.id}`);\n\n return {\n created: false,\n skipped: true,\n provider: {\n id: existingProvider.id,\n ...(existingProvider.instance_id && { instanceId: existingProvider.instance_id }),\n key: providerData.key,\n label: enhancedLabel,\n originalLabel: providerData.label,\n description: providerData.description,\n docsUrl: providerData.docsUrl,\n },\n reason: 'Already exists',\n raw: existingProvider,\n };\n }\n\n try {\n const providerInput = this.preparePayload(providerData, enhancedLabel);\n\n this.logger.debug(`[NEW] Creating new provider: ${enhancedLabel}`);\n\n const createdProvider = await this.getProviderManager().create(providerInput);\n\n this.logger.debug(\n `[INFO] Provider created successfully! ID: ${createdProvider.id}, Instance ID: ${createdProvider.instance_id}`\n );\n\n const result: CreateProviderResult = {\n created: true,\n skipped: false,\n provider: {\n id: createdProvider.id,\n ...(createdProvider.instance_id && { instanceId: createdProvider.instance_id }),\n key: providerData.key,\n label: createdProvider.label,\n originalLabel: providerData.label,\n description: providerData.description,\n docsUrl: providerData.docsUrl,\n },\n raw: createdProvider,\n };\n\n return result;\n } catch (error: any) {\n this.logger.error(`[ERROR] Failed to create provider \"${enhancedLabel}\": ${error.message}`);\n\n return {\n created: false,\n skipped: false,\n error: error.message,\n provider: {\n key: providerData.key,\n label: enhancedLabel,\n originalLabel: providerData.label,\n description: providerData.description,\n docsUrl: providerData.docsUrl,\n },\n };\n }\n }\n\n /**\n * Prepares payload object for Adobe I/O API\n * @param providerData - Provider configuration data\n * @param enhancedLabel - Enhanced provider label\n * @private\n */\n private preparePayload(providerData: ParsedProvider, enhancedLabel: string): any {\n const input: any = {\n label: enhancedLabel,\n };\n\n // Add description if provided\n if (providerData.description) {\n input.description = providerData.description;\n }\n\n // Add docs URL if provided\n if (providerData.docsUrl) {\n input.docs_url = providerData.docsUrl;\n }\n\n // Add special commerce provider metadata if needed\n if (this.isCommerceProvider(providerData)) {\n input.provider_metadata = 'dx_commerce_events';\n input.instance_id = randomUUID();\n }\n\n return input;\n }\n\n /**\n * Determines if provider is a commerce provider\n * @private\n */\n private isCommerceProvider(providerData: ParsedProvider): boolean {\n const commerceIndicators = ['commerce', 'magento', 'adobe commerce'];\n const key = providerData.key.toLowerCase();\n const label = providerData.label.toLowerCase();\n const description = (providerData.description || '').toLowerCase();\n\n return commerceIndicators.some(\n indicator =>\n key.includes(indicator) || label.includes(indicator) || description.includes(indicator)\n );\n }\n}\n\nexport default CreateProviders;\n","/**\n * <license header>\n */\n\n/**\n * Adobe I/O Events utilities for Adobe Commerce AIO Toolkit\n */\n\n// Export Provider utilities\nexport { default as ProviderManager } from './provider';\n\n// Export Event Metadata utilities\nexport { default as EventMetadataManager } from './event-metadata';\n\n// Export Registration utilities\nexport { default as RegistrationManager } from './registration';\n\n// Export types and error classes\nexport * from './types';\n\n// Export provider-specific types\nexport type { Provider } from './provider/types';\nexport type { ProviderInputModel, CreateProviderParams } from './provider/create/types';\nexport type { GetProviderQueryParams } from './provider/get/types';\nexport type { ListProvidersQueryParams } from './provider/list/types';\n\n// Export event metadata types\nexport type { EventMetadata } from './event-metadata/types';\nexport type { EventMetadataInputModel } from './event-metadata/create/types';\nexport type { EventMetadataListResponse } from './event-metadata/list/types';\n\n// Export registration-specific types\nexport type { Registration } from './registration/types';\nexport type { RegistrationCreateModel } from './registration/create/types';\nexport type { GetRegistrationQueryParams } from './registration/get/types';\nexport type {\n ListRegistrationQueryParams,\n RegistrationListResponse,\n} from './registration/list/types';\n","/**\n * <license header>\n */\n\nimport List from './list';\nimport Get from './get';\nimport Create from './create';\nimport Delete from './delete';\nimport { IOEventsApiError } from '../types';\nimport { Provider } from './types';\nimport { GetProviderQueryParams } from './get/types';\nimport { ListProvidersQueryParams } from './list/types';\nimport { ProviderInputModel } from './create/types';\n\n/**\n * Providers service for Adobe I/O Events\n *\n * This class provides methods to interact with event providers in Adobe I/O Events.\n * It handles authentication and provides a clean interface for provider operations.\n */\nclass ProviderManager {\n private readonly listService: List;\n private readonly getService: Get;\n private readonly createService: Create;\n private readonly deleteService: Delete;\n\n /**\n * Constructor for Providers service\n *\n * @param clientId - Client ID from Adobe Developer Console (x-api-key header)\n * @param consumerId - Project Organization ID from Adobe Developer Console\n * @param projectId - Project ID from Adobe Developer Console\n * @param workspaceId - Workspace ID from Adobe Developer Console\n * @param accessToken - IMS token for authentication (Bearer token)\n */\n constructor(\n private readonly clientId: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly accessToken: string\n ) {\n this.listService = new List(clientId, consumerId, projectId, workspaceId, accessToken);\n this.getService = new Get(clientId, consumerId, projectId, workspaceId, accessToken);\n this.createService = new Create(clientId, consumerId, projectId, workspaceId, accessToken);\n this.deleteService = new Delete(clientId, consumerId, projectId, workspaceId, accessToken);\n }\n\n /**\n * List all event providers entitled to the provided organization ID\n *\n * @param queryParams - Optional query parameters for filtering providers\n * @param queryParams.providerMetadataId - Filter by provider metadata id\n * @param queryParams.instanceId - Filter by instance id\n * @param queryParams.providerMetadataIds - List of provider metadata ids to filter (mutually exclusive with providerMetadataId)\n * @param queryParams.eventmetadata - Boolean to fetch provider's event metadata (default: false)\n * @returns Promise<Provider[]> - Array of providers\n * @throws IOEventsApiError - When API call fails with specific error details\n *\n * @example\n * ```typescript\n * // List all providers\n * const providers = await providersService.list();\n *\n * // Filter by provider metadata ID\n * const customProviders = await providersService.list({\n * providerMetadataId: '3rd_party_custom_events'\n * });\n *\n * // Include event metadata in response\n * const providersWithMetadata = await providersService.list({\n * eventmetadata: true\n * });\n * ```\n */\n async list(queryParams: ListProvidersQueryParams = {}): Promise<Provider[]> {\n try {\n return await this.listService.execute(queryParams);\n } catch (error) {\n // Re-throw IOEventsApiError as-is, or wrap other errors\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n throw new IOEventsApiError(\n `Unexpected error in providers list: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 500,\n 'UNEXPECTED_ERROR'\n );\n }\n }\n\n /**\n * Get a specific event provider by its ID\n *\n * @param providerId - The ID of the provider to retrieve\n * @param queryParams - Optional query parameters\n * @param queryParams.eventmetadata - Boolean to fetch provider's event metadata (default: false)\n * @returns Promise<Provider> - The provider details\n * @throws IOEventsApiError - When API call fails with specific error details\n *\n * @example\n * ```typescript\n * // Get basic provider details\n * const provider = await providersService.get('provider-123');\n *\n * // Get provider details with event metadata\n * const providerWithMetadata = await providersService.get('provider-123', {\n * eventmetadata: true\n * });\n * ```\n */\n async get(providerId: string, queryParams: GetProviderQueryParams = {}): Promise<Provider> {\n try {\n return await this.getService.execute(providerId, queryParams);\n } catch (error) {\n // Re-throw IOEventsApiError as-is, or wrap other errors\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n throw new IOEventsApiError(\n `Unexpected error in providers get: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 500,\n 'UNEXPECTED_ERROR'\n );\n }\n }\n\n /**\n * Create a new event provider\n *\n * @param providerData - Provider input data\n * @param providerData.label - The label of this event provider (required)\n * @param providerData.description - Optional description for the provider\n * @param providerData.docs_url - Optional documentation URL for the provider\n * @param providerData.provider_metadata - Optional provider metadata ID (defaults to '3rd_party_custom_events')\n * @param providerData.instance_id - Optional technical instance ID\n * @param providerData.data_residency_region - Optional data residency region (defaults to 'va6')\n * @returns Promise<Provider> - The created provider\n * @throws IOEventsApiError - When API call fails with specific error details\n *\n * @example\n * ```typescript\n * // Create a basic provider\n * const provider = await providersService.create({\n * label: 'My Event Provider'\n * });\n *\n * // Create a provider with custom details\n * const customProvider = await providersService.create({\n * label: 'My Custom Provider',\n * description: 'Provider for custom business events',\n * provider_metadata: '3rd_party_custom_events',\n * instance_id: 'production-instance'\n * });\n * ```\n */\n async create(providerData: ProviderInputModel): Promise<Provider> {\n try {\n return await this.createService.execute(providerData);\n } catch (error) {\n // Re-throw IOEventsApiError as-is, or wrap other errors\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n throw new IOEventsApiError(\n `Unexpected error in providers create: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 500,\n 'UNEXPECTED_ERROR'\n );\n }\n }\n\n /**\n * Delete an event provider by ID\n *\n * @param providerId - The ID of the provider to delete\n * @returns Promise<void> - Resolves when provider is successfully deleted\n * @throws IOEventsApiError - When API call fails with specific error details\n *\n * @example\n * ```typescript\n * // Delete a provider by ID\n * await providersService.delete('provider-123');\n * console.log('Provider deleted successfully');\n * ```\n */\n async delete(providerId: string): Promise<void> {\n try {\n return await this.deleteService.execute(providerId);\n } catch (error) {\n // Re-throw IOEventsApiError as-is, or wrap other errors\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n throw new IOEventsApiError(\n `Unexpected error in providers delete: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 500,\n 'UNEXPECTED_ERROR'\n );\n }\n }\n}\n\nexport default ProviderManager;\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IOEventsError, IoEventsGlobals } from '../../types';\nimport { Provider } from '../types';\nimport { ListProvidersQueryParams, ProvidersListResponse } from './types';\n\n/**\n * List providers for Adobe I/O Events\n *\n * This class handles the retrieval of event providers entitled to a specific organization ID.\n * It supports filtering by provider metadata ID, instance ID, and can optionally include\n * event metadata in the response.\n */\nclass List {\n private readonly endpoint: string = IoEventsGlobals.BASE_URL;\n private readonly restClient: RestClient;\n\n /**\n * Constructor for List providers service\n *\n * @param clientId - Client ID from Adobe Developer Console (x-api-key header)\n * @param consumerId - Project Organization ID from Adobe Developer Console\n * @param projectId - Project ID from Adobe Developer Console\n * @param workspaceId - Workspace ID from Adobe Developer Console\n * @param accessToken - IMS token for authentication (Bearer token)\n */\n constructor(\n private readonly clientId: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new Error('clientId is required and cannot be empty');\n }\n if (!consumerId?.trim()) {\n throw new Error('consumerId is required and cannot be empty');\n }\n if (!projectId?.trim()) {\n throw new Error('projectId is required and cannot be empty');\n }\n if (!workspaceId?.trim()) {\n throw new Error('workspaceId is required and cannot be empty');\n }\n if (!accessToken?.trim()) {\n throw new Error('accessToken is required and cannot be empty');\n }\n\n this.restClient = new RestClient();\n }\n\n /**\n * Execute the list providers API call with automatic pagination\n *\n * This method automatically handles pagination by following the `_links.next.href` from the HAL+JSON response.\n * It makes recursive API calls to fetch all pages and returns a complete array containing all providers\n * across all pages.\n *\n * @param queryParams - Optional query parameters for filtering providers\n * @param queryParams.providerMetadataId - Filter by provider metadata id\n * @param queryParams.instanceId - Filter by instance id\n * @param queryParams.providerMetadataIds - List of provider metadata ids to filter (mutually exclusive with providerMetadataId)\n * @param queryParams.eventmetadata - Boolean to fetch provider's event metadata (default: false)\n * @returns Promise<Provider[]> - Complete array of all providers across all pages\n * @throws IOEventsApiError - When API call fails with specific error details\n */\n async execute(queryParams: ListProvidersQueryParams = {}): Promise<Provider[]> {\n try {\n // Validate query parameters\n if (queryParams.providerMetadataId && queryParams.providerMetadataIds) {\n throw new Error('Cannot specify both providerMetadataId and providerMetadataIds');\n }\n\n // Build the API URL\n const url = `${this.endpoint}/events/${this.consumerId}/providers`;\n\n // Build query string if parameters are provided\n const queryString = this.buildQueryString(queryParams);\n const fullUrl = queryString ? `${url}?${queryString}` : url;\n\n // Prepare headers as required by the API\n const headers = {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n Accept: 'application/hal+json',\n };\n\n return await this.fetchAllPages(fullUrl, headers);\n } catch (error: any) {\n // Handle different types of errors\n this.handleError(error);\n }\n }\n\n /**\n * Recursively fetches all pages of providers using pagination links\n *\n * @param url - The URL to fetch (either initial URL or next page URL)\n * @param headers - Headers for the API request\n * @param accumulatedResults - Array to accumulate results across pages\n * @returns Promise<Provider[]> - Complete array of all providers\n * @private\n */\n private async fetchAllPages(\n url: string,\n headers: Record<string, string>,\n accumulatedResults: Provider[] = []\n ): Promise<Provider[]> {\n // Make the GET request\n const response: ProvidersListResponse = await this.restClient.get(url, headers);\n\n // Validate response format\n if (response === null || response === undefined) {\n throw new Error('Invalid response format: Expected object');\n }\n\n if (typeof response !== 'object') {\n throw new Error('Invalid response format: Expected object');\n }\n\n // Extract providers array\n const providers = response._embedded?.providers;\n\n if (providers !== undefined && !Array.isArray(providers)) {\n throw new Error('Invalid response format: providers should be an array');\n }\n\n // Get current page results\n const currentPageResults = providers || [];\n\n // Accumulate results from current page\n const allResults = [...accumulatedResults, ...currentPageResults];\n\n // Check if there's a next page\n const nextPageUrl = response._links?.next?.href;\n\n if (nextPageUrl) {\n // Recursively fetch the next page\n return await this.fetchAllPages(nextPageUrl, headers, allResults);\n }\n\n // No more pages, return all accumulated results\n return allResults;\n }\n\n /**\n * Handle and transform errors from the API call\n * @private\n * @param error - The caught error\n * @throws IOEventsApiError - Transformed error with proper details\n */\n private handleError(error: any): never {\n // Check if it's an HTTP error from RestClient (e.g., \"HTTP error! status: 404\")\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n // Check if error has response body with error details\n if (error.response?.body) {\n const errorBody: IOEventsError = error.response.body;\n const statusCode =\n error.response.statusCode || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n const message =\n errorBody.message || errorBody.error || this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(message, statusCode, errorBody.error_code, errorBody.details);\n }\n\n // Handle network errors\n if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {\n throw new IOEventsApiError(\n 'Network error: Unable to connect to Adobe I/O Events API. Please check your internet connection.',\n 0,\n 'NETWORK_ERROR'\n );\n }\n\n // Handle timeout errors\n if (error.code === 'ETIMEDOUT') {\n throw new IOEventsApiError(\n 'Request timeout: Adobe I/O Events API did not respond in time.',\n 0,\n 'TIMEOUT_ERROR'\n );\n }\n\n // Handle JSON parsing errors\n if (error.message?.includes('JSON') || error.name === 'SyntaxError') {\n throw new IOEventsApiError(\n 'Invalid response format: Unable to parse API response.',\n 0,\n 'PARSE_ERROR'\n );\n }\n\n // Handle validation errors\n if (\n error.message?.includes('Cannot specify both') ||\n error.message?.includes('Invalid response format')\n ) {\n throw new IOEventsApiError(\n error.message,\n IoEventsGlobals.STATUS_CODES.BAD_REQUEST,\n 'VALIDATION_ERROR'\n );\n }\n\n // Generic error fallback\n throw new IOEventsApiError(\n `Failed to list providers: ${error.message || 'Unknown error occurred'}`,\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'UNKNOWN_ERROR'\n );\n }\n\n /**\n * Extracts the status code from RestClient error message\n *\n * @param errorMessage - Error message like \"HTTP error! status: 404\"\n * @returns The HTTP status code\n */\n private extractStatusCodeFromMessage(errorMessage: string): number {\n const match = errorMessage.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Get user-friendly error message based on HTTP status code\n * @private\n * @param statusCode - HTTP status code\n * @returns string - User-friendly error message\n */\n private getErrorMessageForStatus(statusCode: number): string {\n switch (statusCode) {\n case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:\n return 'Unauthorized: Invalid or expired access token';\n case IoEventsGlobals.STATUS_CODES.FORBIDDEN:\n return 'Forbidden: Insufficient permissions or invalid API key';\n case IoEventsGlobals.STATUS_CODES.NOT_FOUND:\n return 'Not Found: Provider associated with the consumerOrgId, providerMetadataId or instanceID does not exist';\n case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:\n return 'Internal Server Error: Adobe I/O Events service is temporarily unavailable';\n default:\n return `API Error: HTTP ${statusCode}`;\n }\n }\n\n /**\n * Build query string from parameters\n * @private\n */\n private buildQueryString(params: ListProvidersQueryParams): string {\n const queryParts: string[] = [];\n\n // Add providerMetadataId if provided\n if (params.providerMetadataId) {\n queryParts.push(`providerMetadataId=${encodeURIComponent(params.providerMetadataId)}`);\n }\n\n // Add instanceId if provided\n if (params.instanceId) {\n queryParts.push(`instanceId=${encodeURIComponent(params.instanceId)}`);\n }\n\n // Add providerMetadataIds array if provided\n if (params.providerMetadataIds && Array.isArray(params.providerMetadataIds)) {\n params.providerMetadataIds.forEach((id: string) => {\n queryParts.push(`providerMetadataIds=${encodeURIComponent(id)}`);\n });\n }\n\n // Add eventmetadata boolean if provided\n if (typeof params.eventmetadata === 'boolean') {\n queryParts.push(`eventmetadata=${params.eventmetadata}`);\n }\n\n return queryParts.join('&');\n }\n}\n\nexport default List;\n","/**\n * <license header>\n */\n\n/**\n * Adobe I/O Events global constants\n */\nexport const IoEventsGlobals = {\n BASE_URL: 'https://api.adobe.io',\n STATUS_CODES: {\n OK: 200,\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n REQUEST_TIMEOUT: 408,\n TIMEOUT: 408,\n CONFLICT: 409,\n INTERNAL_SERVER_ERROR: 500,\n },\n HEADERS: {\n CONFLICTING_ID: 'x-conflicting-id',\n },\n} as const;\n\n/**\n * HAL (Hypertext Application Language) link structure\n */\nexport interface HALLink {\n href: string;\n templated?: boolean;\n type?: string;\n title?: string;\n}\n\n/**\n * Error response from Adobe I/O Events API\n */\nexport interface IOEventsError {\n error?: string;\n message?: string;\n error_code?: string;\n details?: string;\n}\n\n/**\n * Custom error class for Adobe I/O Events API errors\n */\nexport class IOEventsApiError extends Error {\n public readonly statusCode: number;\n public readonly errorCode: string | undefined;\n public readonly details: string | undefined;\n\n constructor(message: string, statusCode: number, errorCode?: string, details?: string) {\n super(message);\n this.name = 'IOEventsApiError';\n this.statusCode = statusCode;\n this.errorCode = errorCode;\n this.details = details;\n }\n}\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\nimport { Provider } from '../types';\nimport { GetProviderQueryParams } from './types';\n\n/**\n * Get provider by ID for Adobe I/O Events\n *\n * This class handles the retrieval of a specific event provider by its ID.\n * It supports including event metadata in the response.\n */\nclass Get {\n private readonly endpoint: string = IoEventsGlobals.BASE_URL;\n private readonly restClient: RestClient;\n\n /**\n * Constructor for Get provider service\n *\n * @param clientId - Client ID from Adobe Developer Console (x-api-key header)\n * @param consumerId - Project Organization ID from Adobe Developer Console\n * @param projectId - Project ID from Adobe Developer Console\n * @param workspaceId - Workspace ID from Adobe Developer Console\n * @param accessToken - IMS token for authentication (Bearer token)\n */\n constructor(\n private readonly clientId: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new Error('clientId is required and cannot be empty');\n }\n if (!consumerId?.trim()) {\n throw new Error('consumerId is required and cannot be empty');\n }\n if (!projectId?.trim()) {\n throw new Error('projectId is required and cannot be empty');\n }\n if (!workspaceId?.trim()) {\n throw new Error('workspaceId is required and cannot be empty');\n }\n if (!accessToken?.trim()) {\n throw new Error('accessToken is required and cannot be empty');\n }\n\n this.restClient = new RestClient();\n }\n\n /**\n * Execute the get provider by ID API call\n *\n * @param providerId - The ID of the provider to retrieve\n * @param queryParams - Optional query parameters\n * @param queryParams.eventmetadata - Boolean to fetch provider's event metadata (default: false)\n * @returns Promise<Provider> - The provider details\n * @throws IOEventsApiError - When API call fails with specific error details\n *\n * @example\n * ```typescript\n * // Get basic provider details\n * const provider = await getService.execute('provider-123');\n *\n * // Get provider details with event metadata\n * const providerWithMetadata = await getService.execute('provider-123', {\n * eventmetadata: true\n * });\n * ```\n */\n async execute(providerId: string, queryParams: GetProviderQueryParams = {}): Promise<Provider> {\n try {\n // Validate provider ID\n if (!providerId?.trim()) {\n throw new Error('Provider ID is required and cannot be empty');\n }\n\n // Build the API URL\n const url = `${this.endpoint}/events/providers/${encodeURIComponent(providerId)}`;\n\n // Build query string if parameters are provided\n const queryString = this.buildQueryString(queryParams);\n const fullUrl = queryString ? `${url}?${queryString}` : url;\n\n // Prepare headers as required by the API\n const headers = {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n Accept: 'application/hal+json',\n };\n\n // Make the GET request\n const response: Provider = await this.restClient.get(fullUrl, headers);\n\n // Validate response format\n if (response === null || response === undefined) {\n throw new Error('Invalid response format: Expected provider object');\n }\n if (typeof response !== 'object') {\n throw new Error('Invalid response format: Expected provider object');\n }\n\n return response;\n } catch (error: any) {\n this.handleError(error);\n }\n }\n\n /**\n * Build query string from parameters\n */\n private buildQueryString(queryParams: GetProviderQueryParams): string {\n const params = new URLSearchParams();\n\n // Handle eventmetadata parameter\n if (queryParams.eventmetadata !== undefined) {\n params.append('eventmetadata', String(queryParams.eventmetadata));\n }\n\n return params.toString();\n }\n\n /**\n * Handle and transform errors into IOEventsApiError\n */\n private handleError(error: any): never {\n // Check if it's an HTTP error from RestClient (e.g., \"HTTP error! status: 404\")\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n // Handle HTTP errors from RestClient\n if (error.response) {\n const status = this.extractStatusCode(error);\n const errorMessage = this.getErrorMessageForStatus(status);\n throw new IOEventsApiError(errorMessage, status, 'API_ERROR');\n }\n\n // Handle network errors\n if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {\n throw new IOEventsApiError(\n 'Network error: Unable to connect to Adobe I/O Events API',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'NETWORK_ERROR'\n );\n }\n\n // Handle timeout errors\n if (error.code === 'ETIMEDOUT') {\n throw new IOEventsApiError(\n 'Request timeout: Adobe I/O Events API did not respond in time',\n IoEventsGlobals.STATUS_CODES.TIMEOUT,\n 'TIMEOUT_ERROR'\n );\n }\n\n // Handle JSON parsing errors\n if (error.message?.includes('JSON')) {\n throw new IOEventsApiError(\n 'Invalid response format from Adobe I/O Events API',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'PARSE_ERROR'\n );\n }\n\n // Handle validation errors (from provider ID or response validation)\n if (\n error.message?.includes('Provider ID is required') ||\n error.message?.includes('Invalid response format')\n ) {\n throw new IOEventsApiError(\n error.message,\n IoEventsGlobals.STATUS_CODES.BAD_REQUEST,\n 'VALIDATION_ERROR'\n );\n }\n\n // Generic error fallback\n throw new IOEventsApiError(\n `Unexpected error: ${error.message || 'Unknown error occurred'}`,\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'UNKNOWN_ERROR'\n );\n }\n\n /**\n * Extract status code from error response\n */\n private extractStatusCode(error: any): number {\n return (\n error.response?.status || error.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR\n );\n }\n\n /**\n * Extracts the status code from RestClient error message\n *\n * @param errorMessage - Error message like \"HTTP error! status: 404\"\n * @returns The HTTP status code\n */\n private extractStatusCodeFromMessage(errorMessage: string): number {\n const match = errorMessage.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Get specific error message based on HTTP status code\n */\n private getErrorMessageForStatus(status: number): string {\n switch (status) {\n case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:\n return 'Unauthorized: Invalid or expired access token';\n case IoEventsGlobals.STATUS_CODES.FORBIDDEN:\n return 'Forbidden: Insufficient permissions to access this provider';\n case IoEventsGlobals.STATUS_CODES.NOT_FOUND:\n return 'Provider ID does not exist';\n case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:\n return 'Internal server error occurred while fetching provider';\n default:\n return `HTTP ${status}: Provider request failed`;\n }\n }\n}\n\nexport default Get;\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\nimport { Provider } from '../types';\nimport { ProviderInputModel } from './types';\n\n/**\n * Create provider for Adobe I/O Events\n *\n * This class handles the creation of new event providers for a specific organization,\n * project, and workspace. It supports both single-instance and multi-instance providers.\n */\nclass Create {\n private readonly endpoint: string = IoEventsGlobals.BASE_URL;\n private readonly restClient: RestClient;\n\n /**\n * Constructor for Create provider service\n *\n * @param clientId - Client ID from Adobe Developer Console (x-api-key header)\n * @param consumerId - Project Organization ID from Adobe Developer Console\n * @param projectId - Project ID from Adobe Developer Console\n * @param workspaceId - Workspace ID from Adobe Developer Console\n * @param accessToken - IMS token for authentication (Bearer token)\n */\n constructor(\n private readonly clientId: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new Error('clientId is required and cannot be empty');\n }\n if (!consumerId?.trim()) {\n throw new Error('consumerId is required and cannot be empty');\n }\n if (!projectId?.trim()) {\n throw new Error('projectId is required and cannot be empty');\n }\n if (!workspaceId?.trim()) {\n throw new Error('workspaceId is required and cannot be empty');\n }\n if (!accessToken?.trim()) {\n throw new Error('accessToken is required and cannot be empty');\n }\n\n this.restClient = new RestClient();\n }\n\n /**\n * Execute the create provider API call\n *\n * @param providerData - Provider input data\n * @returns Promise<Provider> - The created provider\n * @throws IOEventsApiError - When API call fails with specific error details\n */\n async execute(providerData: ProviderInputModel): Promise<Provider> {\n try {\n // Validate required parameters\n if (!providerData) {\n throw new Error('providerData is required');\n }\n if (!providerData.label?.trim()) {\n throw new Error('label is required in providerData');\n }\n\n // Build the API URL\n const url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/providers`;\n\n // Prepare headers as required by the API\n const headers = {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n Accept: 'application/hal+json',\n 'Content-Type': 'application/json',\n };\n\n // Make the POST request\n const response: Provider = await this.restClient.post(url, headers, providerData);\n\n // Validate response format\n if (response === null || response === undefined) {\n throw new Error('Invalid response format: Expected provider object');\n }\n\n if (typeof response !== 'object') {\n throw new Error('Invalid response format: Expected provider object');\n }\n\n // Validate required provider fields\n if (!response.id) {\n throw new Error('Invalid response format: Missing provider id');\n }\n\n return response;\n } catch (error: any) {\n // Handle different types of errors\n this.handleError(error);\n }\n }\n\n /**\n * Handle and transform errors from the API call\n * @private\n * @param error - The caught error\n * @throws IOEventsApiError - Transformed error with proper details\n */\n private handleError(error: any): never {\n // Check if it's an HTTP error from RestClient (e.g., \"HTTP error! status: 404\")\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n // Check if error has response body with error details\n if (error.response?.body) {\n const errorBody = error.response.body;\n const statusCode =\n error.response.statusCode || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n const message =\n errorBody.message || errorBody.error || this.getErrorMessageForStatus(statusCode);\n\n // Handle conflict error with special header\n if (\n statusCode === IoEventsGlobals.STATUS_CODES.CONFLICT &&\n error.response.headers?.[IoEventsGlobals.HEADERS.CONFLICTING_ID]\n ) {\n const conflictingId = error.response.headers[IoEventsGlobals.HEADERS.CONFLICTING_ID];\n throw new IOEventsApiError(\n `Provider already exists with conflicting ID: ${conflictingId}`,\n statusCode,\n 'CONFLICT_ERROR',\n `Conflicting provider ID: ${conflictingId}`\n );\n }\n\n throw new IOEventsApiError(message, statusCode, errorBody.error_code, errorBody.details);\n }\n\n // Handle network errors\n if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {\n throw new IOEventsApiError(\n 'Network error: Unable to connect to Adobe I/O Events API',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'NETWORK_ERROR'\n );\n }\n\n // Handle timeout errors\n if (error.code === 'ETIMEDOUT') {\n throw new IOEventsApiError(\n 'Request timeout: Adobe I/O Events API did not respond in time',\n IoEventsGlobals.STATUS_CODES.TIMEOUT,\n 'TIMEOUT_ERROR'\n );\n }\n\n // Handle JSON parsing errors\n if (error.message?.includes('JSON')) {\n throw new IOEventsApiError(\n 'Invalid response format from Adobe I/O Events API',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'PARSE_ERROR'\n );\n }\n\n // Handle validation errors\n if (\n error.message?.includes('is required') ||\n error.message?.includes('Invalid response format')\n ) {\n throw new IOEventsApiError(\n error.message,\n IoEventsGlobals.STATUS_CODES.BAD_REQUEST,\n 'VALIDATION_ERROR'\n );\n }\n\n // Generic error fallback\n throw new IOEventsApiError(\n `Failed to create provider: ${error.message || 'Unknown error occurred'}`,\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'UNKNOWN_ERROR'\n );\n }\n\n /**\n * Extracts the status code from RestClient error message\n *\n * @param errorMessage - Error message like \"HTTP error! status: 404\"\n * @returns The HTTP status code\n */\n private extractStatusCodeFromMessage(errorMessage: string): number {\n const match = errorMessage.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Get specific error message based on HTTP status code\n */\n private getErrorMessageForStatus(status: number): string {\n switch (status) {\n case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:\n return 'Unauthorized: Invalid or expired access token';\n case IoEventsGlobals.STATUS_CODES.FORBIDDEN:\n return 'Forbidden: Insufficient permissions or invalid scopes, or attempt to create non multi-instance provider';\n case IoEventsGlobals.STATUS_CODES.NOT_FOUND:\n return 'Provider metadata provided in the input model does not exist';\n case IoEventsGlobals.STATUS_CODES.CONFLICT:\n return 'The event provider already exists';\n case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:\n return 'Internal server error occurred while creating provider';\n default:\n return `HTTP ${status}: Provider creation failed`;\n }\n }\n}\n\nexport default Create;\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\n\n/**\n * Delete Provider Service\n *\n * Handles deletion of event providers in Adobe I/O Events.\n * Implements the DELETE /events/{consumerOrgId}/{projectId}/{workspaceId}/providers/{providerId} endpoint.\n */\nexport default class Delete {\n private readonly endpoint = IoEventsGlobals.BASE_URL;\n private readonly restClient: RestClient;\n\n /**\n * Creates an instance of Delete service\n *\n * @param clientId - Client ID from Adobe Developer Console\n * @param consumerId - Project Organization ID\n * @param projectId - Project ID from Adobe Developer Console\n * @param workspaceId - Workspace ID from Adobe Developer Console\n * @param accessToken - IMS token for authentication\n */\n constructor(\n private readonly clientId: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new Error('clientId is required and cannot be empty');\n }\n if (!consumerId?.trim()) {\n throw new Error('consumerId is required and cannot be empty');\n }\n if (!projectId?.trim()) {\n throw new Error('projectId is required and cannot be empty');\n }\n if (!workspaceId?.trim()) {\n throw new Error('workspaceId is required and cannot be empty');\n }\n if (!accessToken?.trim()) {\n throw new Error('accessToken is required and cannot be empty');\n }\n\n this.restClient = new RestClient();\n }\n\n /**\n * Delete a provider by ID\n *\n * @param providerId - The ID of the provider to delete\n * @returns Promise<void> - Resolves when provider is successfully deleted\n * @throws IOEventsApiError - When the API request fails\n */\n async execute(providerId: string): Promise<void> {\n try {\n // Validate required parameters\n if (!providerId?.trim()) {\n throw new Error('providerId is required and cannot be empty');\n }\n\n // Build the API URL\n const url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/providers/${providerId}`;\n\n // Prepare headers\n const headers = {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n Accept: 'application/hal+json',\n 'Content-Type': 'application/json',\n };\n\n // Make the DELETE request\n await this.restClient.delete(url, headers);\n\n // DELETE requests with 204 response don't return content\n // Success is indicated by no exception being thrown\n } catch (error: any) {\n // Handle different types of errors\n this.handleError(error);\n }\n }\n\n /**\n * Handle and transform errors from the API call\n * @private\n * @param error - The caught error\n * @throws IOEventsApiError - Transformed error with proper details\n */\n private handleError(error: any): never {\n // Check if it's an HTTP error from RestClient (e.g., \"HTTP error! status: 404\")\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n // Handle HTTP errors from RestClient\n if (error.response) {\n const status = this.extractStatusCode(error);\n const errorMessage = this.getErrorMessageForStatus(status);\n throw new IOEventsApiError(errorMessage, status, 'API_ERROR');\n }\n\n // Handle network errors\n if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {\n throw new IOEventsApiError(\n 'Network error: Unable to connect to Adobe I/O Events API',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'NETWORK_ERROR'\n );\n }\n\n // Handle timeout errors\n if (error.code === 'ETIMEDOUT' || error.message?.includes('timeout')) {\n throw new IOEventsApiError(\n 'Request timeout: Adobe I/O Events API did not respond in time',\n IoEventsGlobals.STATUS_CODES.TIMEOUT,\n 'TIMEOUT_ERROR'\n );\n }\n\n // Handle JSON parsing errors\n if (error.message?.includes('JSON')) {\n throw new IOEventsApiError(\n 'Invalid response format from Adobe I/O Events API',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'PARSE_ERROR'\n );\n }\n\n // Handle validation errors (from provider ID validation)\n if (error.message?.includes('required') || error.message?.includes('empty')) {\n throw new IOEventsApiError(\n `Validation error: ${error.message}`,\n IoEventsGlobals.STATUS_CODES.BAD_REQUEST,\n 'VALIDATION_ERROR'\n );\n }\n\n // Handle generic errors\n if (error instanceof Error) {\n throw new IOEventsApiError(\n `Failed to delete provider: ${error.message}`,\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'UNKNOWN_ERROR'\n );\n }\n\n // Handle unknown error types\n throw new IOEventsApiError(\n 'Unexpected error: Unknown error occurred',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'UNKNOWN_ERROR'\n );\n }\n\n /**\n * Extract status code from error response\n */\n private extractStatusCode(error: any): number {\n return (\n error.response?.status || error.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR\n );\n }\n\n /**\n * Extracts the status code from RestClient error message\n *\n * @param errorMessage - Error message like \"HTTP error! status: 404\"\n * @returns The HTTP status code\n */\n private extractStatusCodeFromMessage(errorMessage: string): number {\n const match = errorMessage.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Get appropriate error message for HTTP status code\n */\n private getErrorMessageForStatus(status: number): string {\n switch (status) {\n case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:\n return 'Unauthorized: Invalid or expired access token';\n case IoEventsGlobals.STATUS_CODES.FORBIDDEN:\n return 'Forbidden: Insufficient permissions to delete provider';\n case IoEventsGlobals.STATUS_CODES.NOT_FOUND:\n return 'Provider not found: The specified provider ID does not exist';\n case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:\n return 'Internal server error occurred while deleting provider';\n default:\n return `HTTP ${status}: Provider deletion failed`;\n }\n }\n}\n","/**\n * <license header>\n */\n\nimport List from './list';\nimport Get from './get';\nimport Create from './create';\nimport Delete from './delete';\nimport { IOEventsApiError } from '../types';\nimport { EventMetadata } from './types';\nimport { EventMetadataInputModel } from './create/types';\n\n/**\n * Main class for managing event metadata operations\n *\n * Provides methods to interact with Adobe I/O Events API for event metadata management.\n * Supports listing, getting, creating, and deleting event metadata for providers.\n */\nclass EventMetadataManager {\n private readonly listService: List;\n private readonly getService: Get;\n private readonly createService: Create;\n private readonly deleteService: Delete;\n\n /**\n * Creates an instance of EventMetadataManager\n *\n * @param clientId - Adobe I/O Client ID for API authentication\n * @param consumerId - Consumer organization ID\n * @param projectId - Project ID within the consumer organization\n * @param workspaceId - Workspace ID within the project\n * @param accessToken - Access token for API authentication\n */\n constructor(\n private readonly clientId: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly accessToken: string\n ) {\n this.listService = new List(clientId, consumerId, projectId, workspaceId, accessToken);\n this.getService = new Get(clientId, consumerId, projectId, workspaceId, accessToken);\n this.createService = new Create(clientId, consumerId, projectId, workspaceId, accessToken);\n this.deleteService = new Delete(clientId, consumerId, projectId, workspaceId, accessToken);\n }\n\n /**\n * Lists all event metadata for a provider\n *\n * @param providerId - The ID of the provider to fetch event metadata for\n * @returns Promise<EventMetadata[]> - Array of event metadata\n * @throws IOEventsApiError - When the API request fails\n *\n * @example\n * // List all event metadata for a provider\n * const allMetadata = await eventMetadata.list('provider-123');\n */\n async list(providerId: string): Promise<EventMetadata[]> {\n try {\n return await this.listService.execute(providerId);\n } catch (error) {\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n throw new IOEventsApiError(\n `Unexpected error in event metadata list: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 500,\n 'UNEXPECTED_ERROR'\n );\n }\n }\n\n /**\n * Gets specific event metadata by provider ID and event code\n *\n * @param providerId - The ID of the provider\n * @param eventCode - The event code to get metadata for\n * @returns Promise<EventMetadata> - The event metadata\n * @throws IOEventsApiError - When the API request fails\n *\n * @example\n * // Get specific event metadata by event code\n * const specificMetadata = await eventMetadata.get('provider-123', 'user.created');\n */\n async get(providerId: string, eventCode: string): Promise<EventMetadata> {\n try {\n return await this.getService.execute(providerId, eventCode);\n } catch (error) {\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n throw new IOEventsApiError(\n `Unexpected error in event metadata get: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 500,\n 'UNEXPECTED_ERROR'\n );\n }\n }\n\n /**\n * Creates new event metadata for a provider\n *\n * @param providerId - The ID of the provider to create event metadata for\n * @param eventMetadataData - The event metadata input data\n * @returns Promise<EventMetadata> - The created event metadata\n * @throws IOEventsApiError - When the API request fails\n *\n * @example\n * // Create new event metadata\n * const newMetadata = await eventMetadata.create('provider-123', {\n * event_code: 'com.example.user.created',\n * label: 'User Created',\n * description: 'Triggered when a new user is created',\n * sample_event_template: { name: 'John Doe', email: 'john@example.com' } // JSON object\n * });\n */\n async create(\n providerId: string,\n eventMetadataData: EventMetadataInputModel\n ): Promise<EventMetadata> {\n try {\n return await this.createService.execute(providerId, eventMetadataData);\n } catch (error) {\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n throw new IOEventsApiError(\n `Unexpected error in event metadata create: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 500,\n 'UNEXPECTED_ERROR'\n );\n }\n }\n\n /**\n * Deletes event metadata for a provider\n *\n * @param providerId - The ID of the provider to delete event metadata for\n * @param eventCode - Optional event code to delete specific event metadata. If not provided, deletes all event metadata for the provider\n * @returns Promise<void> - No content returned on successful deletion\n * @throws IOEventsApiError - When the API request fails\n *\n * @example\n * // Delete all event metadata for a provider\n * await eventMetadata.delete('provider-123');\n *\n * @example\n * // Delete specific event metadata by event code\n * await eventMetadata.delete('provider-123', 'com.example.user.created');\n */\n async delete(providerId: string, eventCode?: string): Promise<void> {\n try {\n return await this.deleteService.execute(providerId, eventCode);\n } catch (error) {\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n throw new IOEventsApiError(\n `Unexpected error in event metadata delete: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 500,\n 'UNEXPECTED_ERROR'\n );\n }\n }\n}\n\nexport default EventMetadataManager;\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\nimport { EventMetadata } from '../types';\nimport { EventMetadataListResponse } from './types';\n\n/**\n * Service class for listing all event metadata for a provider\n *\n * Handles: GET /events/providers/{providerId}/eventmetadata\n */\nexport default class List {\n private readonly restClient: RestClient;\n\n /**\n * Creates an instance of List service\n *\n * @param clientId - The Adobe I/O client ID (API key)\n * @param consumerId - The consumer organization ID\n * @param projectId - The project ID\n * @param workspaceId - The workspace ID\n * @param accessToken - The access token for authentication\n */\n constructor(\n private readonly clientId: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new Error('clientId is required and cannot be empty');\n }\n if (!consumerId?.trim()) {\n throw new Error('consumerId is required and cannot be empty');\n }\n if (!projectId?.trim()) {\n throw new Error('projectId is required and cannot be empty');\n }\n if (!workspaceId?.trim()) {\n throw new Error('workspaceId is required and cannot be empty');\n }\n if (!accessToken?.trim()) {\n throw new Error('accessToken is required and cannot be empty');\n }\n\n this.restClient = new RestClient();\n }\n\n /**\n * Retrieves all event metadata for a provider with automatic pagination\n *\n * This method automatically follows pagination links to fetch all event metadata\n * across multiple pages, returning a complete array of all event metadata.\n *\n * @param providerId - The ID of the provider to fetch event metadata for\n * @returns Promise<EventMetadata[]> - Array of all event metadata across all pages\n * @throws IOEventsApiError - When the API request fails\n */\n async execute(providerId: string): Promise<EventMetadata[]> {\n if (!providerId?.trim()) {\n throw new IOEventsApiError(\n 'providerId is required and cannot be empty',\n 400,\n 'VALIDATION_ERROR'\n );\n }\n\n try {\n const url = `${IoEventsGlobals.BASE_URL}/events/providers/${providerId}/eventmetadata`;\n return await this.fetchAllPages(url);\n } catch (error: any) {\n this.handleError(error);\n }\n }\n\n /**\n * Recursively fetches all pages of event metadata using pagination links\n *\n * @param url - The URL to fetch (either initial URL or next page URL)\n * @param accumulatedResults - Array to accumulate results across pages\n * @returns Promise<EventMetadata[]> - Complete array of all event metadata\n * @private\n */\n private async fetchAllPages(\n url: string,\n accumulatedResults: EventMetadata[] = []\n ): Promise<EventMetadata[]> {\n const response = await this.restClient.get(url, {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n Accept: 'application/hal+json',\n });\n\n // Validate response format\n if (response === null || response === undefined) {\n throw new IOEventsApiError(\n 'Invalid response format: Expected object',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'PARSE_ERROR'\n );\n }\n\n if (typeof response !== 'object') {\n throw new IOEventsApiError(\n 'Invalid response format: Expected object',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'PARSE_ERROR'\n );\n }\n\n const data = response as EventMetadataListResponse;\n\n // Validate _embedded structure\n if (!data._embedded || !Array.isArray(data._embedded.eventmetadata)) {\n throw new IOEventsApiError(\n 'Invalid response format: Expected eventmetadata array',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'PARSE_ERROR'\n );\n }\n\n const currentPageResults = data._embedded.eventmetadata;\n\n // Accumulate results from current page\n const allResults = [...accumulatedResults, ...currentPageResults];\n\n // Check if there's a next page\n const nextPageUrl = data._links?.next?.href;\n\n if (nextPageUrl) {\n // Recursively fetch the next page\n return await this.fetchAllPages(nextPageUrl, allResults);\n }\n\n // No more pages, return all accumulated results\n return allResults;\n }\n\n /**\n * Handles errors from the API request\n *\n * @param error - The error object from the API request\n * @throws IOEventsApiError - Always throws with appropriate error details\n */\n private handleError(error: any): never {\n // Check if it's an HTTP error from RestClient (e.g., \"HTTP error! status: 404\")\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n // Check if it's a structured API error response\n if (error.response) {\n const statusCode = this.extractStatusCode(error);\n const errorMessage =\n error.response.body?.message || this.getErrorMessageForStatus(statusCode);\n\n throw new IOEventsApiError(\n errorMessage,\n statusCode,\n error.response.body,\n error.response.headers\n );\n }\n\n // Handle other types of errors (network, timeout, parsing, etc.)\n let errorMessage: string;\n let statusCode: number;\n\n if (error instanceof Error) {\n if (error.message.includes('timeout') || error.message.includes('ETIMEDOUT')) {\n errorMessage = 'Request timeout while listing event metadata';\n statusCode = IoEventsGlobals.STATUS_CODES.REQUEST_TIMEOUT;\n } else if (error.message.includes('JSON') || error.message.includes('parse')) {\n errorMessage = 'Invalid response format from Adobe I/O Events API';\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n throw new IOEventsApiError(errorMessage, statusCode, 'PARSE_ERROR');\n } else {\n errorMessage = `Network error: ${error.message}`;\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n } else {\n errorMessage = `API Error: HTTP ${IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR}`;\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n /**\n * Extracts the status code from the error response\n *\n * @param error - The error object\n * @returns The HTTP status code\n */\n private extractStatusCode(error: any): number {\n return error.response?.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Extracts the status code from RestClient error message\n *\n * @param errorMessage - Error message like \"HTTP error! status: 404\"\n * @returns The HTTP status code\n */\n private extractStatusCodeFromMessage(errorMessage: string): number {\n const match = errorMessage.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Gets a human-readable error message for a given HTTP status code\n *\n * @param statusCode - The HTTP status code\n * @returns A descriptive error message\n */\n private getErrorMessageForStatus(statusCode: number): string {\n switch (statusCode) {\n case IoEventsGlobals.STATUS_CODES.BAD_REQUEST:\n return 'Invalid request parameters for listing event metadata';\n case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:\n return 'Authentication failed. Please check your access token';\n case IoEventsGlobals.STATUS_CODES.FORBIDDEN:\n return 'Access forbidden. You do not have permission to access event metadata';\n case IoEventsGlobals.STATUS_CODES.NOT_FOUND:\n return 'Provider not found or no event metadata available';\n case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:\n return 'Internal server error occurred while listing event metadata';\n default:\n return `Unexpected error occurred: HTTP ${statusCode}`;\n }\n }\n}\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\nimport { EventMetadata } from '../types';\n\n/**\n * Service class for getting specific event metadata by provider ID and event code\n */\nexport default class Get {\n private readonly restClient: RestClient;\n\n /**\n * Creates an instance of Get service\n *\n * @param clientId - The Adobe I/O client ID (API key)\n * @param consumerId - The consumer organization ID\n * @param projectId - The project ID\n * @param workspaceId - The workspace ID\n * @param accessToken - The access token for authentication\n */\n constructor(\n private readonly clientId: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new Error('clientId is required and cannot be empty');\n }\n if (!consumerId?.trim()) {\n throw new Error('consumerId is required and cannot be empty');\n }\n if (!projectId?.trim()) {\n throw new Error('projectId is required and cannot be empty');\n }\n if (!workspaceId?.trim()) {\n throw new Error('workspaceId is required and cannot be empty');\n }\n if (!accessToken?.trim()) {\n throw new Error('accessToken is required and cannot be empty');\n }\n\n this.restClient = new RestClient();\n }\n\n /**\n * Retrieves specific event metadata by provider ID and event code\n *\n * @param providerId - The ID of the provider\n * @param eventCode - The event code to get metadata for\n * @returns Promise<EventMetadata> - The event metadata\n * @throws IOEventsApiError - When the API request fails\n */\n async execute(providerId: string, eventCode: string): Promise<EventMetadata> {\n if (!providerId?.trim()) {\n throw new IOEventsApiError(\n 'providerId is required and cannot be empty',\n 400,\n 'VALIDATION_ERROR'\n );\n }\n if (!eventCode?.trim()) {\n throw new IOEventsApiError(\n 'eventCode is required and cannot be empty',\n 400,\n 'VALIDATION_ERROR'\n );\n }\n\n try {\n const url = `${IoEventsGlobals.BASE_URL}/events/providers/${providerId}/eventmetadata/${encodeURIComponent(eventCode)}`;\n\n const response = await this.restClient.get(url, {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n Accept: 'application/hal+json',\n });\n\n // Validate response format\n if (response === null || response === undefined) {\n throw new IOEventsApiError(\n 'Invalid response format: Expected object',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'PARSE_ERROR'\n );\n }\n\n if (typeof response !== 'object') {\n throw new IOEventsApiError(\n 'Invalid response format: Expected object',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'PARSE_ERROR'\n );\n }\n\n return response as EventMetadata;\n } catch (error: any) {\n this.handleError(error);\n }\n }\n\n /**\n * Handles errors from the API request\n *\n * @param error - The error object from the API request\n * @throws IOEventsApiError - Always throws with appropriate error details\n */\n private handleError(error: any): never {\n // Check if it's an HTTP error from RestClient (e.g., \"HTTP error! status: 404\")\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n // Check if it's a structured API error response\n if (error.response) {\n const statusCode = this.extractStatusCode(error);\n const errorMessage =\n error.response.body?.message || this.getErrorMessageForStatus(statusCode);\n\n throw new IOEventsApiError(\n errorMessage,\n statusCode,\n error.response.body?.error_code,\n error.response.body?.details\n );\n }\n\n // Handle other types of errors (network, timeout, parsing, etc.)\n let errorMessage: string;\n let statusCode: number;\n\n if (error instanceof Error) {\n if (error.message.includes('timeout') || error.message.includes('ETIMEDOUT')) {\n errorMessage = 'Request timeout while getting event metadata';\n statusCode = IoEventsGlobals.STATUS_CODES.REQUEST_TIMEOUT;\n } else if (error.message.includes('JSON') || error.message.includes('parse')) {\n errorMessage = 'Invalid response format from Adobe I/O Events API';\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n throw new IOEventsApiError(errorMessage, statusCode, 'PARSE_ERROR');\n } else {\n errorMessage = `Network error: ${error.message}`;\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n } else {\n errorMessage = `API Error: HTTP ${IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR}`;\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n /**\n * Extracts the status code from the error response\n *\n * @param error - The error object\n * @returns The HTTP status code\n */\n private extractStatusCode(error: any): number {\n return error.response?.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Extracts the status code from RestClient error message\n *\n * @param errorMessage - Error message like \"HTTP error! status: 404\"\n * @returns The HTTP status code\n */\n private extractStatusCodeFromMessage(errorMessage: string): number {\n const match = errorMessage.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Gets a human-readable error message for a given HTTP status code\n *\n * @param statusCode - The HTTP status code\n * @returns A descriptive error message\n */\n private getErrorMessageForStatus(statusCode: number): string {\n switch (statusCode) {\n case IoEventsGlobals.STATUS_CODES.BAD_REQUEST:\n return 'Invalid request parameters for getting event metadata';\n case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:\n return 'Authentication failed. Please check your access token';\n case IoEventsGlobals.STATUS_CODES.FORBIDDEN:\n return 'Access forbidden. You do not have permission to access this event metadata';\n case IoEventsGlobals.STATUS_CODES.NOT_FOUND:\n return 'Event metadata not found for the specified provider and event code';\n case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:\n return 'Internal server error occurred while getting event metadata';\n default:\n return `Unexpected error occurred: HTTP ${statusCode}`;\n }\n }\n}\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\nimport { EventMetadata } from '../types';\nimport { EventMetadataInputModel } from './types';\n\n/**\n * Create event metadata for Adobe I/O Events\n *\n * This class handles the creation of event metadata for a specific provider.\n * It validates the input data and makes the appropriate API call to create\n * the event metadata in Adobe I/O Events.\n */\nclass Create {\n private readonly endpoint: string = IoEventsGlobals.BASE_URL;\n private readonly restClient: RestClient;\n\n /**\n * Constructor for Create event metadata service\n *\n * @param clientId - Client ID from Adobe Developer Console (x-api-key header)\n * @param consumerId - Project Organization ID from Adobe Developer Console\n * @param projectId - Project ID from Adobe Developer Console\n * @param workspaceId - Workspace ID from Adobe Developer Console\n * @param accessToken - IMS token for authentication (Bearer token)\n */\n constructor(\n private readonly clientId: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new Error('clientId is required and cannot be empty');\n }\n if (!consumerId?.trim()) {\n throw new Error('consumerId is required and cannot be empty');\n }\n if (!projectId?.trim()) {\n throw new Error('projectId is required and cannot be empty');\n }\n if (!workspaceId?.trim()) {\n throw new Error('workspaceId is required and cannot be empty');\n }\n if (!accessToken?.trim()) {\n throw new Error('accessToken is required and cannot be empty');\n }\n\n this.restClient = new RestClient();\n }\n\n /**\n * Execute the create event metadata API call\n *\n * @param providerId - The ID of the provider to create event metadata for\n * @param eventMetadataData - The event metadata input model\n * @returns Promise<EventMetadata> - The created event metadata\n * @throws IOEventsApiError - When API call fails with specific error details\n */\n async execute(\n providerId: string,\n eventMetadataData: EventMetadataInputModel\n ): Promise<EventMetadata> {\n try {\n // Validate required parameters\n if (!providerId?.trim()) {\n throw new IOEventsApiError(\n 'providerId is required and cannot be empty',\n 400,\n 'VALIDATION_ERROR'\n );\n }\n\n if (!eventMetadataData) {\n throw new IOEventsApiError('eventMetadataData is required', 400, 'VALIDATION_ERROR');\n }\n\n // Validate required fields in eventMetadataData\n this.validateEventMetadataInput(eventMetadataData);\n\n // Convert the input data for API submission\n const apiPayload = this.convertToApiPayload(eventMetadataData);\n\n // Build the API URL\n const url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/providers/${providerId}/eventmetadata`;\n\n // Prepare headers as required by the API\n const headers = {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n Accept: 'application/hal+json',\n 'Content-Type': 'application/json',\n };\n\n // Make the POST request\n const response: EventMetadata = await this.restClient.post(url, headers, apiPayload);\n\n // Validate response format\n if (response === null || response === undefined) {\n throw new IOEventsApiError(\n 'Invalid response format: Expected object',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR\n );\n }\n\n if (typeof response !== 'object') {\n throw new IOEventsApiError(\n 'Invalid response format: Expected object',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR\n );\n }\n\n return response;\n } catch (error: any) {\n // Handle different types of errors\n this.handleError(error);\n }\n }\n\n /**\n * Validates the event metadata input data\n *\n * @param eventMetadataData - The event metadata input to validate\n * @throws Error - When validation fails\n * @private\n */\n private validateEventMetadataInput(eventMetadataData: EventMetadataInputModel): void {\n const { description, label, event_code, sample_event_template } = eventMetadataData;\n\n // Validate required fields\n if (!description?.trim()) {\n throw new IOEventsApiError(\n 'description is required and cannot be empty',\n 400,\n 'VALIDATION_ERROR'\n );\n }\n\n if (!label?.trim()) {\n throw new IOEventsApiError('label is required and cannot be empty', 400, 'VALIDATION_ERROR');\n }\n\n if (!event_code?.trim()) {\n throw new IOEventsApiError(\n 'event_code is required and cannot be empty',\n 400,\n 'VALIDATION_ERROR'\n );\n }\n\n // Validate field lengths\n if (description.length > 255) {\n throw new Error('description cannot exceed 255 characters');\n }\n\n if (label.length > 255) {\n throw new Error('label cannot exceed 255 characters');\n }\n\n if (event_code.length > 255) {\n throw new Error('event_code cannot exceed 255 characters');\n }\n\n // Validate patterns (basic validation - API will do full validation)\n const descriptionPattern = /^[\\w\\s\\-_.(),:''`?#!]+$/;\n if (!descriptionPattern.test(description)) {\n throw new Error('description contains invalid characters');\n }\n\n const labelPattern = /^[\\w\\s\\-_.(),:''`?#!]+$/;\n if (!labelPattern.test(label)) {\n throw new Error('label contains invalid characters');\n }\n\n const eventCodePattern = /^[\\w\\-_.]+$/;\n if (!eventCodePattern.test(event_code)) {\n throw new Error('event_code contains invalid characters');\n }\n\n // Validate sample_event_template if provided\n if (sample_event_template !== undefined) {\n if (typeof sample_event_template !== 'object' || sample_event_template === null) {\n throw new Error('sample_event_template must be a valid JSON object');\n }\n\n try {\n // Check if the JSON string representation would exceed the base64 limit\n // Base64 encoding increases size by ~33%, so we check the JSON string length\n const jsonString = JSON.stringify(sample_event_template);\n const base64Length = Buffer.from(jsonString).toString('base64').length;\n\n if (base64Length > 87382) {\n throw new Error('sample_event_template JSON object is too large when base64 encoded');\n }\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes('sample_event_template JSON object is too large')\n ) {\n throw error; // Re-throw our validation error\n }\n throw new Error('sample_event_template must be a valid JSON object');\n }\n }\n }\n\n /**\n * Converts the input data to the format expected by the API\n *\n * @param eventMetadataData - The event metadata input data\n * @returns The converted payload for the API\n * @private\n */\n private convertToApiPayload(eventMetadataData: EventMetadataInputModel): any {\n const { sample_event_template, ...rest } = eventMetadataData;\n\n const payload: any = { ...rest };\n\n // Convert sample_event_template from JSON object to base64 string if provided\n if (sample_event_template !== undefined) {\n payload.sample_event_template = Buffer.from(JSON.stringify(sample_event_template)).toString(\n 'base64'\n );\n }\n\n return payload;\n }\n\n /**\n * Handles errors from the API request\n *\n * @param error - The error object from the API request\n * @throws IOEventsApiError - Always throws with appropriate error details\n * @private\n */\n private handleError(error: any): never {\n // If it's already an IOEventsApiError, re-throw it\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n\n // Check if it's an HTTP error from RestClient (e.g., \"HTTP error! status: 404\")\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n // Check if it's a structured API error response\n if (error.response) {\n const statusCode = this.extractStatusCode(error);\n const errorMessage =\n error.response.body?.message || this.getErrorMessageForStatus(statusCode);\n\n throw new IOEventsApiError(\n errorMessage,\n statusCode,\n error.response.body?.error_code,\n error.response.body?.details\n );\n }\n\n // Handle other types of errors (network, timeout, parsing, etc.)\n let errorMessage: string;\n let statusCode: number;\n\n if (error instanceof Error) {\n if (error.message.includes('timeout') || error.message.includes('ETIMEDOUT')) {\n errorMessage = 'Request timeout while creating event metadata';\n statusCode = IoEventsGlobals.STATUS_CODES.REQUEST_TIMEOUT;\n } else if (\n error.message.includes('is required') ||\n error.message.includes('cannot be empty') ||\n error.message.includes('cannot exceed') ||\n error.message.includes('contains invalid characters') ||\n error.message.includes('must be a valid') ||\n error.message.includes('too large when base64 encoded')\n ) {\n // Validation errors should be thrown as-is with 400 status\n throw new IOEventsApiError(\n error.message,\n IoEventsGlobals.STATUS_CODES.BAD_REQUEST,\n 'VALIDATION_ERROR'\n );\n } else if (error.message.includes('JSON') || error.message.includes('parse')) {\n errorMessage = 'Invalid response format from Adobe I/O Events API';\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n } else {\n errorMessage = `Network error: ${error.message}`;\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n } else {\n errorMessage = `API Error: HTTP ${IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR}`;\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n /**\n * Extracts the status code from the error response\n *\n * @param error - The error object\n * @returns The HTTP status code\n * @private\n */\n private extractStatusCode(error: any): number {\n return error.response?.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Extracts the status code from RestClient error message\n *\n * @param errorMessage - Error message like \"HTTP error! status: 404\"\n * @returns The HTTP status code\n * @private\n */\n private extractStatusCodeFromMessage(errorMessage: string): number {\n const match = errorMessage.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Gets a human-readable error message based on HTTP status code\n *\n * @param statusCode - HTTP status code\n * @returns string - User-friendly error message\n * @private\n */\n private getErrorMessageForStatus(statusCode: number): string {\n switch (statusCode) {\n case IoEventsGlobals.STATUS_CODES.BAD_REQUEST:\n return 'Invalid request parameters for creating event metadata';\n case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:\n return 'Authentication failed. Please check your access token';\n case IoEventsGlobals.STATUS_CODES.FORBIDDEN:\n return 'Access forbidden. You do not have permission to create event metadata';\n case IoEventsGlobals.STATUS_CODES.NOT_FOUND:\n return 'Provider not found. The specified provider ID does not exist';\n case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:\n return 'Internal server error occurred while creating event metadata';\n default:\n return `Unexpected error occurred: HTTP ${statusCode}`;\n }\n }\n}\n\nexport default Create;\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\n\n/**\n * Delete all event metadata for a provider in Adobe I/O Events\n *\n * This class handles the deletion of all event metadata associated with a specific provider.\n * The operation returns 204 No Content on successful deletion.\n */\nclass Delete {\n private readonly endpoint: string = IoEventsGlobals.BASE_URL;\n private readonly restClient: RestClient;\n\n /**\n * Constructor for Delete event metadata service\n *\n * @param clientId - Client ID from Adobe Developer Console (x-api-key header)\n * @param consumerId - Project Organization ID from Adobe Developer Console\n * @param projectId - Project ID from Adobe Developer Console\n * @param workspaceId - Workspace ID from Adobe Developer Console\n * @param accessToken - IMS token for authentication (Bearer token)\n */\n constructor(\n private readonly clientId: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new Error('clientId is required and cannot be empty');\n }\n if (!consumerId?.trim()) {\n throw new Error('consumerId is required and cannot be empty');\n }\n if (!projectId?.trim()) {\n throw new Error('projectId is required and cannot be empty');\n }\n if (!workspaceId?.trim()) {\n throw new Error('workspaceId is required and cannot be empty');\n }\n if (!accessToken?.trim()) {\n throw new Error('accessToken is required and cannot be empty');\n }\n\n this.restClient = new RestClient();\n }\n\n /**\n * Execute the delete event metadata API call\n *\n * @param providerId - The ID of the provider to delete event metadata for\n * @param eventCode - Optional event code to delete specific event metadata. If not provided, deletes all event metadata for the provider\n * @returns Promise<void> - No content returned on successful deletion (204)\n * @throws IOEventsApiError - When API call fails with specific error details\n */\n async execute(providerId: string, eventCode?: string): Promise<void> {\n try {\n // Validate required parameters\n if (!providerId?.trim()) {\n throw new IOEventsApiError(\n 'providerId is required and cannot be empty',\n 400,\n 'VALIDATION_ERROR'\n );\n }\n\n // Validate eventCode if provided\n if (eventCode !== undefined && !eventCode?.trim()) {\n throw new IOEventsApiError(\n 'eventCode cannot be empty when provided',\n 400,\n 'VALIDATION_ERROR'\n );\n }\n\n // Build the API URL - append eventCode if provided for specific deletion\n let url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/providers/${providerId}/eventmetadata`;\n if (eventCode?.trim()) {\n url += `/${encodeURIComponent(eventCode.trim())}`;\n }\n\n // Prepare headers as required by the API\n const headers = {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n Accept: 'application/hal+json',\n };\n\n // Make the DELETE request - RestClient should handle 204 No Content properly\n await this.restClient.delete(url, headers);\n\n // No return value for 204 No Content\n } catch (error: any) {\n // Handle different types of errors\n this.handleError(error);\n }\n }\n\n /**\n * Handles errors from the API request\n *\n * @param error - The error object from the API request\n * @throws IOEventsApiError - Always throws with appropriate error details\n * @private\n */\n private handleError(error: any): never {\n // If it's already an IOEventsApiError, re-throw it\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n\n // Check if it's an HTTP error from RestClient (e.g., \"HTTP error! status: 404\")\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n // Check if it's a structured API error response\n if (error.response) {\n const statusCode = this.extractStatusCode(error);\n const errorMessage =\n error.response.body?.message || this.getErrorMessageForStatus(statusCode);\n\n throw new IOEventsApiError(\n errorMessage,\n statusCode,\n error.response.body?.error_code,\n error.response.body?.details\n );\n }\n\n // Handle other types of errors (network, timeout, parsing, etc.)\n let errorMessage: string;\n let statusCode: number;\n\n if (error instanceof Error) {\n if (error.message.includes('timeout') || error.message.includes('ETIMEDOUT')) {\n errorMessage = 'Request timeout while deleting event metadata';\n statusCode = IoEventsGlobals.STATUS_CODES.REQUEST_TIMEOUT;\n } else if (\n error.message.includes('is required') ||\n error.message.includes('cannot be empty')\n ) {\n // Validation errors should be thrown as-is with 400 status\n throw new IOEventsApiError(\n error.message,\n IoEventsGlobals.STATUS_CODES.BAD_REQUEST,\n 'VALIDATION_ERROR'\n );\n } else if (error.message.includes('JSON') || error.message.includes('parse')) {\n errorMessage = 'Invalid response format from Adobe I/O Events API';\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n } else {\n errorMessage = `Network error: ${error.message}`;\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n } else {\n errorMessage = `API Error: HTTP ${IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR}`;\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n /**\n * Extracts the status code from the error response\n *\n * @param error - The error object\n * @returns The HTTP status code\n * @private\n */\n private extractStatusCode(error: any): number {\n return error.response?.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Extracts the status code from RestClient error message\n *\n * @param errorMessage - Error message like \"HTTP error! status: 404\"\n * @returns The HTTP status code\n * @private\n */\n private extractStatusCodeFromMessage(errorMessage: string): number {\n const match = errorMessage.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Gets a human-readable error message based on HTTP status code\n *\n * @param statusCode - HTTP status code\n * @returns string - User-friendly error message\n * @private\n */\n private getErrorMessageForStatus(statusCode: number): string {\n switch (statusCode) {\n case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:\n return 'Authentication failed. Please check your access token';\n case IoEventsGlobals.STATUS_CODES.FORBIDDEN:\n return 'Access forbidden. You do not have permission to delete event metadata';\n case IoEventsGlobals.STATUS_CODES.NOT_FOUND:\n return 'Provider or event metadata not found. The specified provider ID or event code does not exist';\n case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:\n return 'Internal server error occurred while deleting event metadata';\n default:\n return `Unexpected error occurred: HTTP ${statusCode}`;\n }\n }\n}\n\nexport default Delete;\n","/**\n * <license header>\n */\n\nimport Create from './create';\nimport Delete from './delete';\nimport Get from './get';\nimport List from './list';\nimport type { Registration } from './types';\nimport type { RegistrationCreateModel } from './create/types';\nimport type { ListRegistrationQueryParams } from './list/types';\n\n/**\n * Manager class for registration operations\n */\nexport class RegistrationManager {\n private createService: Create;\n private deleteService: Delete;\n private getService: Get;\n private listService: List;\n\n /**\n * Initialize the RegistrationManager\n */\n constructor(\n clientId: string,\n consumerId: string,\n projectId: string,\n workspaceId: string,\n accessToken: string\n ) {\n this.createService = new Create(clientId, consumerId, projectId, workspaceId, accessToken);\n this.deleteService = new Delete(clientId, consumerId, projectId, workspaceId, accessToken);\n this.getService = new Get(clientId, consumerId, projectId, workspaceId, accessToken);\n this.listService = new List(clientId, consumerId, projectId, workspaceId, accessToken);\n }\n\n /**\n * Create a new registration\n *\n * @param registrationData - The registration data to create\n * @returns Promise<Registration> - The created registration\n *\n * @example\n * ```typescript\n * const registration = await registrationManager.create({\n * client_id: 'your-client-id',\n * name: 'My Registration',\n * description: 'Registration for user events',\n * webhook_url: 'https://example.com/webhook',\n * events_of_interest: [\n * {\n * provider_id: 'provider-123',\n * event_code: 'com.example.user.created'\n * }\n * ],\n * delivery_type: 'webhook',\n * enabled: true\n * });\n * console.log(registration.registration_id);\n * ```\n */\n async create(registrationData: RegistrationCreateModel): Promise<Registration> {\n return await this.createService.execute(registrationData);\n }\n\n /**\n * Delete a registration by ID\n *\n * @param registrationId - The registration ID to delete\n * @returns Promise<void> - Resolves when deletion is successful\n *\n * @example\n * ```typescript\n * await registrationManager.delete('your-registration-id');\n * console.log('Registration deleted successfully');\n * ```\n */\n async delete(registrationId: string): Promise<void> {\n return await this.deleteService.execute(registrationId);\n }\n\n /**\n * Get a registration by ID\n *\n * @param registrationId - The registration ID to retrieve\n * @returns Promise<Registration> - The registration data\n *\n * @example\n * ```typescript\n * const registration = await registrationManager.get('your-registration-id');\n * console.log(registration.name);\n * ```\n */\n async get(registrationId: string): Promise<Registration> {\n return await this.getService.execute(registrationId);\n }\n\n /**\n * List all registrations with automatic pagination\n *\n * @param queryParams - Optional query parameters for filtering\n * @returns Promise<Registration[]> - Array of all registrations across all pages\n *\n * @example\n * ```typescript\n * // List all registrations\n * const registrations = await registrationManager.list();\n *\n * // List with query parameters\n * const filteredRegistrations = await registrationManager.list({\n * enabled: true\n * });\n * ```\n */\n async list(queryParams?: ListRegistrationQueryParams): Promise<Registration[]> {\n return await this.listService.execute(queryParams);\n }\n}\n\nexport default RegistrationManager;\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\nimport type { Registration } from '../types';\nimport type { RegistrationCreateModel } from './types';\n\n/**\n * Service for creating registrations\n */\nexport class Create {\n private restClient: RestClient;\n private endpoint: string;\n private clientId: string;\n private consumerId: string;\n private projectId: string;\n private workspaceId: string;\n private accessToken: string;\n\n /**\n * Initialize the Create service\n */\n constructor(\n clientId: string,\n consumerId: string,\n projectId: string,\n workspaceId: string,\n accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new IOEventsApiError('clientId is required and cannot be empty', 400);\n }\n if (!consumerId?.trim()) {\n throw new IOEventsApiError('consumerId is required and cannot be empty', 400);\n }\n if (!projectId?.trim()) {\n throw new IOEventsApiError('projectId is required and cannot be empty', 400);\n }\n if (!workspaceId?.trim()) {\n throw new IOEventsApiError('workspaceId is required and cannot be empty', 400);\n }\n if (!accessToken?.trim()) {\n throw new IOEventsApiError('accessToken is required and cannot be empty', 400);\n }\n\n this.restClient = new RestClient();\n this.endpoint = IoEventsGlobals.BASE_URL;\n this.clientId = clientId;\n this.consumerId = consumerId;\n this.projectId = projectId;\n this.workspaceId = workspaceId;\n this.accessToken = accessToken;\n }\n\n /**\n * Create a new registration\n *\n * @param registrationData - The registration data to create\n * @returns Promise<Registration> - The created registration\n * @throws IOEventsApiError - When the API call fails\n *\n * @example\n * ```typescript\n * const registration = await registrationManager.create({\n * client_id: 'your-client-id',\n * name: 'My Registration',\n * description: 'Registration for user events',\n * webhook_url: 'https://example.com/webhook',\n * events_of_interest: [\n * {\n * provider_id: 'provider-123',\n * event_code: 'com.example.user.created'\n * }\n * ],\n * delivery_type: 'webhook',\n * enabled: true\n * });\n * console.log(registration.registration_id);\n * ```\n */\n async execute(registrationData: RegistrationCreateModel): Promise<Registration> {\n try {\n this.validateRegistrationInput(registrationData);\n\n const url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/registrations`;\n\n const response = await this.restClient.post(\n url,\n {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n 'Content-Type': 'application/json',\n Accept: 'application/hal+json',\n },\n registrationData\n );\n\n return response as Registration;\n } catch (error) {\n this.handleError(error);\n }\n }\n\n /**\n * Validates the registration input data\n */\n private validateRegistrationInput(registrationData: RegistrationCreateModel): void {\n if (!registrationData) {\n throw new IOEventsApiError('Registration data is required', 400);\n }\n\n if (!registrationData.client_id?.trim()) {\n throw new IOEventsApiError('Client ID is required', 400);\n }\n\n if (registrationData.client_id.length < 3 || registrationData.client_id.length > 255) {\n throw new IOEventsApiError('Client ID must be between 3 and 255 characters', 400);\n }\n\n if (!registrationData.name?.trim()) {\n throw new IOEventsApiError('Registration name is required', 400);\n }\n\n if (registrationData.name.length < 3 || registrationData.name.length > 255) {\n throw new IOEventsApiError('Registration name must be between 3 and 255 characters', 400);\n }\n\n if (registrationData.description && registrationData.description.length > 5000) {\n throw new IOEventsApiError('Description must not exceed 5000 characters', 400);\n }\n\n if (registrationData.webhook_url && registrationData.webhook_url.length > 4000) {\n throw new IOEventsApiError('Webhook URL must not exceed 4000 characters', 400);\n }\n\n if (\n !registrationData.events_of_interest ||\n !Array.isArray(registrationData.events_of_interest)\n ) {\n throw new IOEventsApiError('Events of interest is required and must be an array', 400);\n }\n\n if (registrationData.events_of_interest.length === 0) {\n throw new IOEventsApiError('At least one event of interest is required', 400);\n }\n\n // Validate each event of interest\n registrationData.events_of_interest.forEach((event, index) => {\n if (!event.provider_id?.trim()) {\n throw new IOEventsApiError(`Provider ID is required for event at index ${index}`, 400);\n }\n if (!event.event_code?.trim()) {\n throw new IOEventsApiError(`Event code is required for event at index ${index}`, 400);\n }\n });\n\n if (!registrationData.delivery_type?.trim()) {\n throw new IOEventsApiError('Delivery type is required', 400);\n }\n\n const validDeliveryTypes = ['webhook', 'webhook_batch', 'journal', 'aws_eventbridge'];\n if (!validDeliveryTypes.includes(registrationData.delivery_type)) {\n throw new IOEventsApiError(\n `Delivery type must be one of: ${validDeliveryTypes.join(', ')}`,\n 400\n );\n }\n\n if (registrationData.runtime_action && registrationData.runtime_action.length > 255) {\n throw new IOEventsApiError('Runtime action must not exceed 255 characters', 400);\n }\n }\n\n /**\n * Handles errors from the API call\n */\n private handleError(error: any): never {\n // Re-throw validation errors as-is\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n if (error.response?.status) {\n const statusCode = error.response.status;\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n if (error.status) {\n const statusCode = error.status;\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n throw new IOEventsApiError('Network error occurred', 500);\n }\n\n /**\n * Extracts status code from HTTP error message\n */\n private extractStatusCodeFromMessage(message: string): number {\n const match = message.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : 500;\n }\n\n /**\n * Gets appropriate error message for HTTP status code\n */\n private getErrorMessageForStatus(statusCode: number): string {\n switch (statusCode) {\n case 400:\n return 'Bad request: Invalid registration data provided';\n case 401:\n return 'Unauthorized: Invalid or missing authentication';\n case 403:\n return 'Forbidden: Insufficient permissions';\n case 409:\n return 'Conflict: Registration with this name already exists';\n case 422:\n return 'Unprocessable entity: Invalid registration data';\n case 500:\n return 'Internal server error';\n default:\n return `API error: HTTP ${statusCode}`;\n }\n }\n}\n\nexport default Create;\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\n\n/**\n * Service for deleting registrations\n */\nexport class Delete {\n private restClient: RestClient;\n private endpoint: string;\n private clientId: string;\n private consumerId: string;\n private projectId: string;\n private workspaceId: string;\n private accessToken: string;\n\n /**\n * Initialize the Delete service\n */\n constructor(\n clientId: string,\n consumerId: string,\n projectId: string,\n workspaceId: string,\n accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new IOEventsApiError('clientId is required and cannot be empty', 400);\n }\n if (!consumerId?.trim()) {\n throw new IOEventsApiError('consumerId is required and cannot be empty', 400);\n }\n if (!projectId?.trim()) {\n throw new IOEventsApiError('projectId is required and cannot be empty', 400);\n }\n if (!workspaceId?.trim()) {\n throw new IOEventsApiError('workspaceId is required and cannot be empty', 400);\n }\n if (!accessToken?.trim()) {\n throw new IOEventsApiError('accessToken is required and cannot be empty', 400);\n }\n\n this.restClient = new RestClient();\n this.endpoint = IoEventsGlobals.BASE_URL;\n this.clientId = clientId;\n this.consumerId = consumerId;\n this.projectId = projectId;\n this.workspaceId = workspaceId;\n this.accessToken = accessToken;\n }\n\n /**\n * Delete a registration by ID\n *\n * @param registrationId - The registration ID to delete\n * @returns Promise<void> - Resolves when deletion is successful\n * @throws IOEventsApiError - When the API call fails\n *\n * @example\n * ```typescript\n * await registrationManager.delete('your-registration-id');\n * console.log('Registration deleted successfully');\n * ```\n */\n async execute(registrationId: string): Promise<void> {\n try {\n this.validateInputs(registrationId);\n\n const url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/registrations/${registrationId}`;\n\n await this.restClient.delete(url, {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n Accept: 'text/plain',\n });\n\n // Delete operation returns 204 No Content on success\n } catch (error) {\n this.handleError(error);\n }\n }\n\n /**\n * Validates the input parameters\n */\n private validateInputs(registrationId: string): void {\n if (!registrationId?.trim()) {\n throw new IOEventsApiError('Registration ID is required', 400);\n }\n }\n\n /**\n * Handles errors from the API call\n */\n private handleError(error: any): never {\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n if (error.response?.status) {\n const statusCode = error.response.status;\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n if (error.status) {\n const statusCode = error.status;\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n throw new IOEventsApiError('Network error occurred', 500);\n }\n\n /**\n * Extracts status code from HTTP error message\n */\n private extractStatusCodeFromMessage(message: string): number {\n const match = message.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : 500;\n }\n\n /**\n * Gets appropriate error message for HTTP status code\n */\n private getErrorMessageForStatus(statusCode: number): string {\n switch (statusCode) {\n case 400:\n return 'Bad request: Invalid registration ID provided';\n case 401:\n return 'Unauthorized: Invalid or missing authentication';\n case 403:\n return 'Forbidden: Insufficient permissions';\n case 404:\n return 'Registration not found';\n case 500:\n return 'Internal server error';\n default:\n return `API error: HTTP ${statusCode}`;\n }\n }\n}\n\nexport default Delete;\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\nimport type { Registration } from '../types';\n\n/**\n * Service for getting a specific registration by ID\n */\nexport class Get {\n private restClient: RestClient;\n private endpoint: string;\n private clientId: string;\n private consumerId: string;\n private projectId: string;\n private workspaceId: string;\n private accessToken: string;\n\n /**\n * Initialize the Get service\n */\n constructor(\n clientId: string,\n consumerId: string,\n projectId: string,\n workspaceId: string,\n accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new IOEventsApiError('clientId is required and cannot be empty', 400);\n }\n if (!consumerId?.trim()) {\n throw new IOEventsApiError('consumerId is required and cannot be empty', 400);\n }\n if (!projectId?.trim()) {\n throw new IOEventsApiError('projectId is required and cannot be empty', 400);\n }\n if (!workspaceId?.trim()) {\n throw new IOEventsApiError('workspaceId is required and cannot be empty', 400);\n }\n if (!accessToken?.trim()) {\n throw new IOEventsApiError('accessToken is required and cannot be empty', 400);\n }\n\n this.restClient = new RestClient();\n this.endpoint = IoEventsGlobals.BASE_URL;\n this.clientId = clientId;\n this.consumerId = consumerId;\n this.projectId = projectId;\n this.workspaceId = workspaceId;\n this.accessToken = accessToken;\n }\n\n /**\n * Get a registration by ID\n *\n * @param registrationId - The registration ID to retrieve\n * @returns Promise<Registration> - The registration data\n * @throws IOEventsApiError - When the API call fails\n *\n * @example\n * ```typescript\n * const registration = await registrationManager.get('your-registration-id');\n * console.log(registration.name);\n * ```\n */\n async execute(registrationId: string): Promise<Registration> {\n try {\n this.validateInputs(registrationId);\n\n const url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/registrations/${registrationId}`;\n\n const response = await this.restClient.get(url, {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n Accept: 'application/hal+json',\n });\n\n return response as Registration;\n } catch (error) {\n this.handleError(error);\n }\n }\n\n /**\n * Validates the input parameters\n */\n private validateInputs(registrationId: string): void {\n if (!registrationId?.trim()) {\n throw new IOEventsApiError('Registration ID is required', 400);\n }\n }\n\n /**\n * Handles errors from the API call\n */\n private handleError(error: any): never {\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n if (error.response?.status) {\n const statusCode = error.response.status;\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n if (error.status) {\n const statusCode = error.status;\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n throw new IOEventsApiError('Network error occurred', 500);\n }\n\n /**\n * Extracts status code from HTTP error message\n */\n private extractStatusCodeFromMessage(message: string): number {\n const match = message.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : 500;\n }\n\n /**\n * Gets appropriate error message for HTTP status code\n */\n private getErrorMessageForStatus(statusCode: number): string {\n switch (statusCode) {\n case 400:\n return 'Bad request: Invalid parameters provided';\n case 401:\n return 'Unauthorized: Invalid or missing authentication';\n case 403:\n return 'Forbidden: Insufficient permissions';\n case 404:\n return 'Registration not found';\n case 500:\n return 'Internal server error';\n default:\n return `API error: HTTP ${statusCode}`;\n }\n }\n}\n\nexport default Get;\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\nimport type { Registration } from '../types';\nimport type { RegistrationListResponse, ListRegistrationQueryParams } from './types';\n\n/**\n * Service for listing registrations with automatic pagination\n */\nexport class List {\n private restClient: RestClient;\n private endpoint: string;\n private clientId: string;\n private consumerId: string;\n private projectId: string;\n private workspaceId: string;\n private accessToken: string;\n\n /**\n * Initialize the List service\n */\n constructor(\n clientId: string,\n consumerId: string,\n projectId: string,\n workspaceId: string,\n accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new IOEventsApiError('clientId is required and cannot be empty', 400);\n }\n if (!consumerId?.trim()) {\n throw new IOEventsApiError('consumerId is required and cannot be empty', 400);\n }\n if (!projectId?.trim()) {\n throw new IOEventsApiError('projectId is required and cannot be empty', 400);\n }\n if (!workspaceId?.trim()) {\n throw new IOEventsApiError('workspaceId is required and cannot be empty', 400);\n }\n if (!accessToken?.trim()) {\n throw new IOEventsApiError('accessToken is required and cannot be empty', 400);\n }\n\n this.restClient = new RestClient();\n this.endpoint = IoEventsGlobals.BASE_URL;\n this.clientId = clientId;\n this.consumerId = consumerId;\n this.projectId = projectId;\n this.workspaceId = workspaceId;\n this.accessToken = accessToken;\n }\n\n /**\n * Execute registration list with automatic pagination\n */\n async execute(queryParams?: ListRegistrationQueryParams): Promise<Registration[]> {\n try {\n this.validateInputs();\n\n let url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/registrations`;\n\n // Add query parameters if provided\n if (queryParams && Object.keys(queryParams).length > 0) {\n const searchParams = new URLSearchParams();\n Object.entries(queryParams).forEach(([key, value]) => {\n if (value !== undefined && value !== null) {\n searchParams.append(key, String(value));\n }\n });\n if (searchParams.toString()) {\n url += `?${searchParams.toString()}`;\n }\n }\n\n return await this.fetchAllPages(url);\n } catch (error: any) {\n this.handleError(error);\n }\n }\n\n /**\n * Fetch all pages recursively\n */\n private async fetchAllPages(\n url: string,\n accumulatedResults: Registration[] = []\n ): Promise<Registration[]> {\n const headers = {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n 'Content-Type': 'application/json',\n };\n\n const data = (await this.restClient.get(url, headers)) as RegistrationListResponse;\n\n // Extract registrations from current page\n const currentPageRegistrations = data._embedded?.registrations || [];\n const allResults = [...accumulatedResults, ...currentPageRegistrations];\n\n // Check if there's a next page\n const nextPageUrl = data._links?.next?.href;\n if (nextPageUrl) {\n // Recursively fetch the next page\n return await this.fetchAllPages(nextPageUrl, allResults);\n }\n\n return allResults;\n }\n\n /**\n * Validate required inputs\n */\n private validateInputs(): void {\n if (!this.consumerId?.trim()) {\n throw new IOEventsApiError(\n 'Consumer ID is required',\n IoEventsGlobals.STATUS_CODES.BAD_REQUEST\n );\n }\n if (!this.projectId?.trim()) {\n throw new IOEventsApiError(\n 'Project ID is required',\n IoEventsGlobals.STATUS_CODES.BAD_REQUEST\n );\n }\n if (!this.workspaceId?.trim()) {\n throw new IOEventsApiError(\n 'Workspace ID is required',\n IoEventsGlobals.STATUS_CODES.BAD_REQUEST\n );\n }\n if (!this.accessToken?.trim()) {\n throw new IOEventsApiError(\n 'Access token is required',\n IoEventsGlobals.STATUS_CODES.BAD_REQUEST\n );\n }\n }\n\n /**\n * Handle and categorize errors\n */\n private handleError(error: any): never {\n // Handle RestClient HTTP errors (e.g., \"HTTP error! status: 404\")\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n // Handle structured API error responses\n if (error.response) {\n const statusCode =\n error.response.status || error.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n // Handle other errors\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n\n // Default error handling\n throw new IOEventsApiError(\n error.message || 'An unexpected error occurred while listing registrations',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR\n );\n }\n\n /**\n * Extract status code from error message\n */\n private extractStatusCodeFromMessage(errorMessage: string): number {\n const match = errorMessage.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Get appropriate error message for status code\n */\n private getErrorMessageForStatus(statusCode: number): string {\n switch (statusCode) {\n case IoEventsGlobals.STATUS_CODES.BAD_REQUEST:\n return 'Bad request. Please check your input parameters';\n case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:\n return 'Unauthorized. Please check your access token';\n case IoEventsGlobals.STATUS_CODES.FORBIDDEN:\n return 'Forbidden. You do not have permission to access registrations';\n case IoEventsGlobals.STATUS_CODES.NOT_FOUND:\n return 'Registrations not found. The specified workspace may not exist or have no registrations';\n case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:\n return 'Internal server error. Please try again later';\n default:\n return `API request failed with status ${statusCode}`;\n }\n }\n}\n\nexport default List;\n","/**\n * <license header>\n */\n\nimport type { Logger } from '@adobe/aio-sdk';\nimport { EventMetadataManager, type EventMetadata } from '../../../io-events';\nimport type { ParsedEvent, CreateEventResult, CreateProviderResult } from '../types';\n\n/**\n * Utility class for creating event metadata in Adobe Commerce onboarding integrations\n *\n * @example\n * const logger = Core.Logger('my-create-events', { level: 'debug' });\n * const createEvents = new CreateEvents(\n * 'your-consumer-id',\n * 'your-project-id',\n * 'your-workspace-id',\n * 'your-client-id',\n * 'your-access-token',\n * logger\n * );\n *\n * // Process events for creation\n * await createEvents.process(events, providerResults);\n */\nclass CreateEvents {\n private readonly logger: Logger;\n private eventMetadataManager: EventMetadataManager | null = null;\n\n /**\n * Creates a new CreateEvents instance\n *\n * @param consumerId - Adobe I/O consumer ID\n * @param projectId - Adobe I/O project ID\n * @param workspaceId - Adobe I/O workspace ID\n * @param clientId - Adobe I/O client ID\n * @param accessToken - Adobe I/O access token\n * @param logger - Logger instance for consistent logging\n */\n constructor(\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly clientId: string,\n private readonly accessToken: string,\n logger: Logger\n ) {\n // Validate configuration\n const config = {\n consumerId: this.consumerId,\n projectId: this.projectId,\n workspaceId: this.workspaceId,\n clientId: this.clientId,\n accessToken: this.accessToken,\n };\n const required = ['consumerId', 'projectId', 'workspaceId', 'clientId', 'accessToken'];\n const missing = required.filter(\n key => !config[key as keyof typeof config] || config[key as keyof typeof config].trim() === ''\n );\n\n if (missing.length > 0) {\n throw new Error(`Missing required configuration: ${missing.join(', ')}`);\n }\n\n if (!logger) {\n throw new Error('Logger is required');\n }\n\n // Use the provided logger\n this.logger = logger;\n\n this.logger.debug(`[INIT] CreateEvents initialized with valid configuration`);\n }\n\n /**\n * Gets the EventMetadataManager instance (lazy initialization)\n * @private\n * @returns EventMetadataManager instance\n */\n private getEventMetadataManager(): EventMetadataManager {\n if (!this.eventMetadataManager) {\n this.eventMetadataManager = new EventMetadataManager(\n this.clientId,\n this.consumerId,\n this.projectId,\n this.workspaceId,\n this.accessToken\n );\n }\n return this.eventMetadataManager;\n }\n\n /**\n * Creates event metadata for a specific provider\n * @private\n * @param providerId - Provider ID to create event for\n * @param event - Parsed event data\n * @param existingEvents - Array of existing event metadata\n * @returns Promise<CreateEventResult> - Event creation result\n */\n private async createEvent(\n providerId: string,\n event: ParsedEvent,\n existingEvents: EventMetadata[]\n ): Promise<CreateEventResult> {\n try {\n const eventCode = event.eventCode;\n this.logger.debug(`[INFO] Processing event: ${eventCode}`);\n\n // Check if event metadata already exists\n const existingEvent = existingEvents.find(metadata => metadata.event_code === eventCode);\n\n if (existingEvent) {\n this.logger.debug(\n `[INFO] Event code '${eventCode}' already exists for provider ${providerId}`\n );\n this.logger.debug(`[SKIP] Event metadata already exists for: ${eventCode} - skipping`);\n return {\n created: false,\n skipped: true,\n event: {\n id: existingEvent.id,\n eventCode: eventCode,\n ...(existingEvent.label && { label: existingEvent.label }),\n ...(existingEvent.description && { description: existingEvent.description }),\n ...(existingEvent.sample_event_template && {\n sampleEventTemplate: existingEvent.sample_event_template,\n }),\n },\n raw: existingEvent,\n };\n }\n\n this.logger.debug(`[CREATE] Creating event metadata: ${eventCode}`);\n\n // Build the payload for EventMetadataInputModel\n const metadataPayload = {\n event_code: eventCode,\n label: eventCode,\n description: eventCode,\n ...(event.sampleEventTemplate ? { sample_event_template: event.sampleEventTemplate } : {}),\n };\n\n const eventMetadata = this.getEventMetadataManager();\n const result = await eventMetadata.create(providerId, metadataPayload);\n\n if (result) {\n const eventId = result.id || result.event_code || eventCode;\n this.logger.debug(`[SUCCESS] Event metadata created successfully: ${eventCode}`);\n\n return {\n created: true,\n skipped: false,\n event: {\n id: eventId,\n eventCode: eventCode,\n label: metadataPayload.label,\n description: metadataPayload.description,\n ...(metadataPayload.sample_event_template && {\n sampleEventTemplate: metadataPayload.sample_event_template,\n }),\n },\n raw: result,\n };\n } else {\n throw new Error('Event metadata creation returned no result');\n }\n } catch (error) {\n const eventCode = event.eventCode;\n this.logger.error(\n `[ERROR] Error creating event metadata for ${eventCode}: ${(error as Error).message}`\n );\n return {\n created: false,\n skipped: false,\n event: {\n eventCode: eventCode,\n },\n error: (error as Error).message,\n };\n }\n }\n\n /**\n * Fetches existing event metadata for a provider to avoid duplicates\n * @private\n * @param providerId - Provider ID to fetch metadata for\n * @returns Promise<EventMetadata[]> - List of existing event metadata\n */\n private async fetchMetadata(providerId: string): Promise<EventMetadata[]> {\n try {\n this.logger.debug(`[INFO] Fetching existing event metadata for provider: ${providerId}`);\n\n const eventMetadata = this.getEventMetadataManager();\n const existingList = await eventMetadata.list(providerId);\n\n this.logger.debug(`[INFO] Found ${existingList.length} existing event metadata entries`);\n return existingList;\n } catch (error) {\n this.logger.error(\n `[ERROR] Error fetching existing metadata for provider ${providerId}: ${(error as Error).message}`\n );\n return [];\n }\n }\n\n /**\n * Processes events for creation based on parsed events and provider results\n *\n * @param events - Array of parsed events from InputParser\n * @param providerResults - Array of provider creation results\n * @param projectName - Name of the project for enhanced labeling\n * @returns Promise resolving to event creation results\n */\n async process(\n events: ParsedEvent[],\n providerResults: CreateProviderResult[],\n projectName: string = 'Unknown Project'\n ): Promise<CreateEventResult[]> {\n this.logger.debug(`[CREATE] Creating events for project: ${projectName}`);\n this.logger.debug(\n `[INFO] Processing ${events.length} event(s) across ${providerResults.length} provider(s)...`\n );\n\n if (!events || events.length === 0) {\n this.logger.debug('[INFO] No events to process.');\n return [];\n }\n\n if (!providerResults || providerResults.length === 0) {\n this.logger.debug('[INFO] No provider results to process.');\n return [];\n }\n\n try {\n const results: CreateEventResult[] = [];\n\n for (const providerResult of providerResults) {\n const providerId = providerResult.provider.id;\n if (!providerId) {\n this.logger.debug(\n `[WARN] Skipping provider without ID: ${providerResult.provider.originalLabel}`\n );\n continue;\n }\n\n this.logger.debug(\n `[INFO] Processing events for provider: ${providerResult.provider.originalLabel}`\n );\n\n // Fetch existing metadata for this provider\n const existingEvents = await this.fetchMetadata(providerId);\n\n // Find events that belong to this provider\n const providerEvents = events.filter(\n event => event.providerKey === providerResult.provider.key\n );\n\n if (providerEvents.length === 0) {\n this.logger.debug(\n `[INFO] No events found for provider: ${providerResult.provider.originalLabel}`\n );\n continue;\n }\n\n this.logger.debug(`[INFO] Found ${providerEvents.length} event(s) for this provider`);\n\n // Process each event for this provider\n for (const event of providerEvents) {\n const eventResult = await this.createEvent(providerId, event, existingEvents);\n eventResult.provider = providerResult.provider;\n results.push(eventResult);\n }\n }\n\n return results;\n } catch (error) {\n this.logger.error(`[ERROR] Event metadata creation failed: ${(error as Error).message}`);\n throw error;\n }\n }\n}\n\nexport default CreateEvents;\n","/**\n * <license header>\n */\n\nimport type { Logger } from '@adobe/aio-sdk';\nimport { RegistrationManager } from '../../../io-events/registration';\nimport type { Registration } from '../../../io-events/registration/types';\nimport type { RegistrationCreateModel } from '../../../io-events/registration/create/types';\nimport type {\n ParsedRegistration,\n ParsedEvent,\n CreateRegistrationResult,\n CreateProviderResult,\n} from '../types';\n\n/**\n * Utility class for creating registrations in Adobe Commerce onboarding integrations\n *\n * @example\n * const logger = Core.Logger('my-create-registrations', { level: 'debug' });\n * const createRegistrations = new CreateRegistrations(\n * 'your-consumer-id',\n * 'your-project-id',\n * 'your-workspace-id',\n * 'your-client-id',\n * 'your-access-token',\n * logger\n * );\n *\n * // Process registrations for creation\n * await createRegistrations.process(registrations, providerResults);\n */\nclass CreateRegistrations {\n private readonly logger: Logger;\n private registrationManager?: RegistrationManager;\n\n /**\n * Creates a new CreateRegistrations instance\n *\n * @param consumerId - Adobe I/O consumer ID\n * @param projectId - Adobe I/O project ID\n * @param workspaceId - Adobe I/O workspace ID\n * @param clientId - Adobe I/O client ID\n * @param accessToken - Adobe I/O access token\n * @param logger - Logger instance for consistent logging\n */\n constructor(\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly clientId: string,\n private readonly accessToken: string,\n logger: Logger\n ) {\n // Validate configuration\n const config = {\n consumerId: this.consumerId,\n projectId: this.projectId,\n workspaceId: this.workspaceId,\n clientId: this.clientId,\n accessToken: this.accessToken,\n };\n\n const required = ['consumerId', 'projectId', 'workspaceId', 'clientId', 'accessToken'];\n const missing = required.filter(\n key => !config[key as keyof typeof config] || config[key as keyof typeof config].trim() === ''\n );\n\n if (missing.length > 0) {\n throw new Error(`Missing required configuration: ${missing.join(', ')}`);\n }\n\n if (!logger) {\n throw new Error('Logger is required');\n }\n\n this.logger = logger;\n this.logger.debug(`[INIT] CreateRegistrations initialized with valid configuration`);\n }\n\n /**\n * Process multiple registrations for creation\n *\n * @param registrations - Array of parsed registrations to process\n * @param events - Array of parsed events for registration creation\n * @param providerResults - Array of provider results to link registrations to\n * @param projectName - Optional project name for logging\n * @returns Promise resolving to array of registration creation results\n */\n async process(\n registrations: ParsedRegistration[],\n events: ParsedEvent[],\n providerResults: CreateProviderResult[],\n projectName: string = 'Unknown Project'\n ): Promise<CreateRegistrationResult[]> {\n this.logger.debug(`[INFO] Creating registrations for project: ${projectName}`);\n this.logger.debug(\n `[PROCESSING] Processing ${registrations.length} registration(s) with ${events.length} event(s) across ${providerResults.length} provider(s)...`\n );\n\n if (!registrations || registrations.length === 0) {\n this.logger.debug('[SKIP] No registrations to process.');\n return [];\n }\n\n if (!events || events.length === 0) {\n this.logger.debug('[SKIP] No events to process.');\n return [];\n }\n\n if (!providerResults || providerResults.length === 0) {\n this.logger.debug('[SKIP] No provider results to process.');\n return [];\n }\n\n try {\n // Fetch existing registrations first\n const existingRegistrations = await this.fetchRegistrations();\n\n const results: CreateRegistrationResult[] = [];\n\n for (const registration of registrations) {\n this.logger.debug(`[PROCESSING] Processing registration: ${registration.label}`);\n\n // Find events that belong to this registration\n const registrationEvents = events.filter(\n event => event.registrationKey === registration.key\n );\n\n if (registrationEvents.length === 0) {\n this.logger.debug(`[SKIP] No events found for registration: ${registration.label}`);\n continue;\n }\n\n this.logger.debug(\n `[INFO] Found ${registrationEvents.length} event(s) for this registration`\n );\n\n // Group events by provider to create separate registrations per provider\n const eventsByProvider = this.groupEventsByProvider(registrationEvents);\n\n for (const [providerKey, providerEvents] of Object.entries(eventsByProvider)) {\n const provider = providerResults.find(p => p.provider.key === providerKey);\n\n if (!provider || !provider.provider.id) {\n this.logger.debug(`[SKIP] Provider not found or missing ID for: ${providerKey}`);\n continue;\n }\n\n const result = await this.createRegistration(\n registration,\n providerEvents,\n provider,\n existingRegistrations\n );\n results.push(result);\n }\n }\n\n return results;\n } catch (error) {\n this.logger.error(`[ERROR] Registration creation failed: ${(error as Error).message}`);\n throw error;\n }\n }\n\n /**\n * Lazy initialization of RegistrationManager\n * @private\n * @returns RegistrationManager instance\n */\n private getRegistrationManager(): RegistrationManager {\n if (!this.registrationManager) {\n this.registrationManager = new RegistrationManager(\n this.clientId,\n this.consumerId,\n this.projectId,\n this.workspaceId,\n this.accessToken\n );\n }\n return this.registrationManager;\n }\n\n /**\n * Fetches existing registrations to avoid duplicates\n * @returns {Promise<Map>} Map of existing registrations by name\n */\n async fetchRegistrations(): Promise<Map<string, Registration>> {\n this.logger.debug('[INFO] Fetching existing registrations...');\n\n try {\n const registrationSDK = this.getRegistrationManager();\n const registrationList = await registrationSDK.list();\n\n const existingRegistrations = new Map<string, Registration>();\n registrationList.forEach(registration => {\n existingRegistrations.set(registration.name, registration);\n });\n\n this.logger.debug(`[INFO] Found ${existingRegistrations.size} existing registrations`);\n return existingRegistrations;\n } catch (error) {\n this.logger.error(\n `[ERROR] Failed to fetch existing registrations: ${(error as Error).message}`\n );\n throw error;\n }\n }\n\n /**\n * Groups events by their provider key\n * @private\n * @param events - Events to group\n * @returns Events grouped by provider key\n */\n private groupEventsByProvider(events: ParsedEvent[]): Record<string, ParsedEvent[]> {\n const grouped: Record<string, ParsedEvent[]> = {};\n\n events.forEach(event => {\n if (!grouped[event.providerKey]) {\n grouped[event.providerKey] = [];\n }\n grouped[event.providerKey]!.push(event);\n });\n\n return grouped;\n }\n\n /**\n * Builds registration input object for Adobe I/O API\n * @private\n * @param registration - Registration entity\n * @param events - Events for this registration\n * @param provider - Provider result\n * @param registrationName - Enhanced registration name\n * @param firstEvent - First event for common properties\n * @returns Registration input for API\n */\n private preparePayload(\n registration: ParsedRegistration,\n events: ParsedEvent[],\n provider: CreateProviderResult,\n registrationName: string,\n firstEvent: ParsedEvent\n ): RegistrationCreateModel {\n // Build events of interest array\n const eventsOfInterest = events.map(event => ({\n provider_id: provider.provider.id || '',\n event_code: event.eventCode,\n }));\n\n const input: RegistrationCreateModel = {\n client_id: this.clientId,\n name: registrationName,\n description: registration.description || registrationName,\n delivery_type:\n (firstEvent.deliveryType as 'webhook' | 'webhook_batch' | 'journal' | 'aws_eventbridge') ||\n 'webhook',\n events_of_interest: eventsOfInterest,\n ...(firstEvent.runtimeAction && { runtime_action: firstEvent.runtimeAction }),\n };\n\n return input;\n }\n\n /**\n * Creates a single registration for a provider and its events\n * @private\n * @param registrationData - Registration entity\n * @param events - Events for this registration\n * @param provider - Provider result\n * @param existingRegistrations - Map of existing registrations\n * @returns Registration creation result\n */\n private async createRegistration(\n registrationData: ParsedRegistration,\n events: ParsedEvent[],\n provider: CreateProviderResult,\n existingRegistrations: Map<string, Registration>\n ): Promise<CreateRegistrationResult> {\n // Use the first event to get common properties (runtimeAction, deliveryType)\n const firstEvent = events[0];\n if (!firstEvent) {\n throw new Error('No events provided for registration creation');\n }\n\n const registrationName = registrationData.label;\n\n this.logger.debug(\n `[PROCESSING] Processing registration: ${registrationData.label} for provider: ${provider.provider.originalLabel}`\n );\n this.logger.debug(`[INFO] Registration name: ${registrationName}`);\n\n // Check if registration already exists\n const existingRegistration = existingRegistrations.get(registrationName);\n\n if (existingRegistration) {\n this.logger.debug('[SKIP] Registration already exists - skipping creation');\n this.logger.debug(`[INFO] Existing ID: ${existingRegistration.id}`);\n\n return {\n created: false,\n skipped: true,\n registration: {\n id: existingRegistration.id,\n key: registrationData.key,\n label: registrationData.label,\n originalLabel: registrationData.label,\n name: registrationName,\n description: registrationData.description,\n },\n reason: 'Already exists',\n raw: existingRegistration,\n };\n }\n\n // Create new registration\n this.logger.debug('[CREATE] Creating new registration...');\n\n try {\n const registrationInput = this.preparePayload(\n registrationData,\n events,\n provider,\n registrationName,\n firstEvent\n );\n\n this.logger.debug(`[INFO] Creating registration: ${registrationName}`);\n\n const registrationSDK = this.getRegistrationManager();\n const createdRegistration = await registrationSDK.create(registrationInput);\n\n this.logger.debug('[SUCCESS] Registration created successfully!');\n this.logger.debug(`[INFO] New ID: ${createdRegistration.id}`);\n this.logger.debug(`[INFO] Registration ID: ${createdRegistration.registration_id}`);\n\n const result = {\n created: true,\n skipped: false,\n registration: {\n id: createdRegistration.id,\n key: registrationData.key,\n label: registrationData.label,\n originalLabel: registrationData.label,\n name: createdRegistration.name,\n description: registrationData.description,\n },\n provider: provider.provider,\n raw: createdRegistration,\n };\n\n return result;\n } catch (error) {\n this.logger.error(\n `[ERROR] Failed to create registration \"${registrationName}\": ${(error as Error).message}`\n );\n\n return {\n created: false,\n skipped: false,\n error: (error as Error).message,\n registration: {\n key: registrationData.key,\n label: registrationData.label,\n originalLabel: registrationData.label,\n name: registrationName,\n description: registrationData.description,\n },\n provider: provider.provider,\n };\n }\n }\n}\n\nexport default CreateRegistrations;\n","/**\n * <license header>\n */\n\nimport type {\n OnboardEventsInput,\n OnboardProvider,\n OnboardRegistration,\n OnboardEvent,\n ParsedEntities,\n ParsedProvider,\n ParsedRegistration,\n ParsedEvent,\n} from '../types';\n\n/**\n * InputParser - Parses and extracts entities from OnboardEventsInput data\n */\nclass InputParser {\n private entities: ParsedEntities = {\n providers: [],\n registrations: [],\n events: [],\n };\n\n constructor(input: OnboardEventsInput) {\n for (const provider of input.providers) {\n // Add provider\n this.entities.providers.push(this.createProviderEntity(provider));\n\n // Add registrations and events\n for (const registration of provider.registrations) {\n this.entities.registrations.push(this.createRegistrationEntity(registration, provider.key));\n\n for (const event of registration.events) {\n this.entities.events.push(this.createEventEntity(event, registration.key, provider.key));\n }\n }\n }\n }\n\n /**\n * Create provider entity structure\n */\n private createProviderEntity(provider: OnboardProvider): ParsedProvider {\n return {\n key: provider.key,\n label: provider.label,\n description: provider.description,\n docsUrl: provider.docsUrl,\n };\n }\n\n /**\n * Create registration entity structure\n */\n private createRegistrationEntity(\n registration: OnboardRegistration,\n providerKey: string\n ): ParsedRegistration {\n return {\n key: registration.key,\n label: registration.label,\n description: registration.description,\n providerKey: providerKey,\n };\n }\n\n /**\n * Create event entity structure\n */\n private createEventEntity(\n event: OnboardEvent,\n registrationKey: string,\n providerKey: string\n ): ParsedEvent {\n return {\n eventCode: event.eventCode,\n runtimeAction: event.runtimeAction,\n deliveryType: event.deliveryType,\n sampleEventTemplate: event.sampleEventTemplate,\n registrationKey: registrationKey,\n providerKey: providerKey,\n };\n }\n\n getEntities(): ParsedEntities {\n return this.entities;\n }\n}\n\nexport default InputParser;\n","/**\n * Copyright © Adobe, Inc. All rights reserved.\n */\n\nimport { Core, State } from '@adobe/aio-sdk';\nimport crypto from 'crypto';\n\nimport { InfiniteLoopData } from './types';\n\n/**\n * Utility class for detecting and preventing infinite loops in event processing\n */\nclass InfiniteLoopBreaker {\n /** The algorithm used to generate the fingerprint */\n private static readonly FINGERPRINT_ALGORITHM = 'sha256';\n\n /** The encoding used to generate the fingerprint */\n private static readonly FINGERPRINT_ENCODING = 'hex';\n\n /** The default time to live for the fingerprint in the lib state */\n private static readonly DEFAULT_INFINITE_LOOP_BREAKER_TTL = 60; // seconds\n\n /**\n * This function checks if there is a potential infinite loop\n *\n * @param state - The state object\n * @param infiniteLoopData - The event data containing the key and fingerprint functions, event types, and event name\n * @returns Returns true if the event is a potential infinite loop\n */\n static async isInfiniteLoop({\n keyFn,\n fingerprintFn,\n eventTypes,\n event,\n }: InfiniteLoopData): Promise<boolean> {\n const logLevel = process.env.LOG_LEVEL || 'info';\n const logger = Core.Logger('infiniteLoopBreaker', { level: logLevel });\n\n logger.debug(`Checking for potential infinite loop for event: ${event}`);\n\n if (!eventTypes.includes(event)) {\n logger.debug(`Event type ${event} is not in the infinite loop event types list`);\n return false;\n }\n\n const key = typeof keyFn === 'function' ? keyFn() : keyFn;\n const data = typeof fingerprintFn === 'function' ? fingerprintFn() : fingerprintFn;\n\n // Create a state instance\n const state = await State.init();\n const persistedFingerPrint = await state.get(key);\n if (!persistedFingerPrint) {\n logger.debug(`No persisted fingerprint found for key ${key}`);\n return false;\n }\n\n logger.debug(\n `Persisted fingerprint found for key ${key}: ${persistedFingerPrint.value}, ` +\n `Generated fingerprint: ${InfiniteLoopBreaker.fingerPrint(data)}`\n );\n\n return (\n persistedFingerPrint && persistedFingerPrint.value === InfiniteLoopBreaker.fingerPrint(data)\n );\n }\n\n /**\n * This function stores the fingerprint in the state\n *\n * @param keyFn - Function to generate the key for the fingerprint\n * @param fingerprintFn - Function to generate the fingerprint\n * @param ttl - The time to live for the fingerprint in the lib state\n */\n static async storeFingerPrint(\n keyFn: string | (() => string),\n fingerprintFn: any | (() => any),\n ttl?: number\n ): Promise<void> {\n const key = typeof keyFn === 'function' ? keyFn() : keyFn;\n const data = typeof fingerprintFn === 'function' ? fingerprintFn() : fingerprintFn;\n\n // Create a state instance\n const state = await State.init();\n\n await state.put(key, InfiniteLoopBreaker.fingerPrint(data), {\n ttl: ttl !== undefined ? ttl : InfiniteLoopBreaker.DEFAULT_INFINITE_LOOP_BREAKER_TTL,\n });\n }\n\n /**\n * This function generates a function to generate fingerprint for the data to be used in infinite loop detection based on params.\n *\n * @param obj - Data received from the event\n * @returns The function that generates the fingerprint\n */\n static fnFingerprint(obj: any): () => any {\n return () => {\n return obj;\n };\n }\n\n /**\n * This function generates a function to create a key for the infinite loop detection based on params.\n *\n * @param key - Data received from the event\n * @returns The function that generates the key\n */\n static fnInfiniteLoopKey(key: any): () => any {\n return () => {\n return key;\n };\n }\n\n /**\n * This function generates a fingerprint for the data\n *\n * @param data - The data to generate the fingerprint\n * @returns The fingerprint\n */\n private static fingerPrint(data: any): string {\n const hash = crypto.createHash(InfiniteLoopBreaker.FINGERPRINT_ALGORITHM);\n hash.update(JSON.stringify(data));\n return hash.digest(InfiniteLoopBreaker.FINGERPRINT_ENCODING);\n }\n}\n\nexport default InfiniteLoopBreaker;\n","/**\n * Adobe Commerce I/O Events Configuration Component\n *\n * <license header>\n */\n\nimport AdobeCommerceClient from '../../commerce/adobe-commerce-client';\nimport CustomLogger from '../../framework/custom-logger';\nimport type { Provider } from '../../io-events/provider/types';\nimport type { WorkspaceConfig, CommerceEventConfig } from './types';\nimport ConfigureProvider from './configure-provider';\nimport {\n EventService,\n EventSubscriptionService,\n type EventSubscription,\n} from '@adobe-commerce/aio-services-kit';\n\n/**\n * OnboardCommerce for Adobe Commerce I/O Events Configuration\n *\n * This class provides functionality to automate the configuration of Adobe Commerce\n * I/O Events via REST endpoint, simplifying the onboarding process for Commerce instances.\n *\n * @example\n * ```typescript\n * const adobeCommerceClient = new AdobeCommerceClient(...);\n * const onboardCommerce = new OnboardCommerce(\n * adobeCommerceClient,\n * 'merchant-id-123',\n * 'environment-id-456',\n * logger\n * );\n * ```\n */\nclass OnboardCommerce {\n /** Adobe Commerce client instance */\n private readonly adobeCommerceClient: AdobeCommerceClient;\n\n /** Merchant ID for Adobe Commerce */\n private readonly merchantId: string;\n\n /** Environment ID for Adobe Commerce */\n private readonly environmentId: string;\n\n /** CustomLogger instance for logging operations */\n private readonly customLogger: CustomLogger;\n\n /** ConfigureProvider instance for provider configuration */\n private readonly configureProvider: ConfigureProvider;\n\n /** EventSubscriptionService instance for managing event subscriptions */\n private readonly eventSubscriptionService: EventSubscriptionService;\n\n /** EventService instance for managing events */\n private readonly eventService: EventService;\n\n /** Flag to indicate if the Commerce instance is PaaS (defaults to false) */\n private readonly isPaaS: boolean;\n\n /**\n * Constructor for OnboardCommerce\n *\n * @param adobeCommerceClient - Adobe Commerce client instance\n * @param merchantId - Merchant ID for Adobe Commerce\n * @param environmentId - Environment ID for Adobe Commerce\n * @param logger - Optional logger instance for logging operations\n * @param isPaaS - Flag to indicate if the Commerce instance is PaaS (defaults to false)\n * @throws {Error} When required parameters are missing or invalid\n * @example\n * ```typescript\n * const adobeCommerceClient = new AdobeCommerceClient(...);\n * const onboardCommerce = new OnboardCommerce(\n * adobeCommerceClient,\n * 'merchant-id-123',\n * 'environment-id-456',\n * logger\n * );\n * ```\n */\n constructor(\n adobeCommerceClient: AdobeCommerceClient,\n merchantId: string,\n environmentId: string,\n logger: any = null,\n isPaaS: boolean = false\n ) {\n // Validate required parameters\n if (!adobeCommerceClient) {\n throw new Error('Adobe Commerce client is required');\n }\n if (!merchantId || typeof merchantId !== 'string') {\n throw new Error('Valid merchant ID is required');\n }\n if (!environmentId || typeof environmentId !== 'string') {\n throw new Error('Valid environment ID is required');\n }\n\n this.adobeCommerceClient = adobeCommerceClient;\n this.merchantId = merchantId;\n this.environmentId = environmentId;\n this.isPaaS = isPaaS;\n this.customLogger = new CustomLogger(logger);\n this.configureProvider = new ConfigureProvider(\n adobeCommerceClient,\n merchantId,\n environmentId,\n logger\n );\n this.eventSubscriptionService = new EventSubscriptionService(adobeCommerceClient);\n this.eventService = new EventService(adobeCommerceClient);\n }\n\n /**\n * Process Adobe Commerce I/O Events Configuration\n *\n * This method automates the configuration of Adobe Commerce I/O Events by setting up\n * the provider, workspace, and commerce-specific event configurations.\n *\n * @param provider - Provider configuration for Adobe I/O Events\n * @param workspaceConfig - Workspace configuration settings\n * @param commerceEventsConfig - Array of commerce event configurations (optional, defaults to empty array)\n * @returns A promise that resolves with the configuration result\n * @throws {Error} If configuration fails\n * @example\n * ```typescript\n * const result = await onboardCommerce.process(\n * providerConfig,\n * workspaceConfig,\n * commerceEventsConfig\n * );\n * ```\n */\n async process(\n provider: Provider,\n workspaceConfig: WorkspaceConfig,\n commerceEventsConfig: CommerceEventConfig[] = []\n ): Promise<any> {\n this.customLogger.info(\n `[START] Configuring Adobe Commerce I/O Events\\n` +\n ` Provider: ${provider.label} (${provider.id})\\n` +\n ` Workspace: ${workspaceConfig.project.name}\\n` +\n ` Events to process: ${commerceEventsConfig.length}`\n );\n\n try {\n // Configure the provider using the ConfigureProvider component\n const providerResult = await this.configureProvider.execute(provider, workspaceConfig);\n\n if (!providerResult.success) {\n return providerResult;\n }\n\n // Process commerce events configuration if provided\n if (commerceEventsConfig && commerceEventsConfig.length > 0) {\n // Get current event subscriptions to check what's already configured\n this.customLogger.debug('[FETCH] Fetching current event subscriptions...');\n const eventSubscriptionsResult = await this.eventSubscriptionService.list();\n\n let existingSubscriptions: any[] = [];\n if (!eventSubscriptionsResult.success) {\n this.customLogger.error(\n `[ERROR] Failed to fetch event subscriptions: ${eventSubscriptionsResult.error}`\n );\n } else {\n existingSubscriptions = Array.isArray(eventSubscriptionsResult.data)\n ? eventSubscriptionsResult.data\n : [];\n this.customLogger.debug(\n `[FETCH] Retrieved ${existingSubscriptions.length} existing event subscription(s)`\n );\n }\n\n // Get supported events to validate commerce events configuration\n // Skip this step for PaaS instances as they don't require supported events validation\n let supportedEvents: any[] = [];\n if (!this.isPaaS) {\n this.customLogger.debug('[FETCH] Fetching supported events list...');\n const supportedEventsResult = await this.eventService.supportedList();\n\n if (!supportedEventsResult.success) {\n this.customLogger.error(\n `[ERROR] Failed to fetch supported events: ${supportedEventsResult.error}`\n );\n } else {\n supportedEvents = Array.isArray(supportedEventsResult.data)\n ? supportedEventsResult.data\n : [];\n this.customLogger.debug(\n `[FETCH] Retrieved ${supportedEvents.length} supported event(s)`\n );\n }\n } else {\n this.customLogger.debug('[SKIP] Skipping supported events validation for PaaS instance');\n }\n\n // Filter events based on existing subscriptions and supported events\n const { alreadySubscribed, needsSubscription, unsupported } =\n this.filterEventsBySubscriptionStatus(\n commerceEventsConfig,\n existingSubscriptions,\n provider.id,\n supportedEvents\n );\n\n const result = {\n successfulSubscriptions: [] as string[],\n failedSubscriptions: [] as string[],\n alreadySubscribed: alreadySubscribed.map(event => event.event.name),\n unsupported: unsupported.map(event => event.event?.name || 'Unknown'),\n skipped: alreadySubscribed.length + unsupported.length,\n };\n\n // Process events that need subscription\n for (const commerceEvent of needsSubscription) {\n try {\n // Prepare the event payload with proper transformations\n const preparedEvent = this.prepareEventPayload(commerceEvent, provider.id);\n\n this.customLogger.debug(`[DEBUG] Subscribing to event: ${commerceEvent.event.name}`);\n\n // Create the event subscription\n const eventSubscribeResult = await this.eventSubscriptionService.create(\n preparedEvent.event as EventSubscription\n );\n\n if (!eventSubscribeResult.success) {\n result.failedSubscriptions.push(commerceEvent.event.name);\n this.customLogger.error(\n `[ERROR] Failed to subscribe to event: ${commerceEvent.event.name} - ${eventSubscribeResult.error}`\n );\n continue;\n }\n\n this.customLogger.info(`[CREATE] Successfully subscribed: ${commerceEvent.event.name}`);\n result.successfulSubscriptions.push(commerceEvent.event.name);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n result.failedSubscriptions.push(commerceEvent.event?.name || 'Unknown');\n this.customLogger.error(\n `[ERROR] Error processing event subscription for ${commerceEvent.event?.name || 'Unknown'}: ${errorMessage}`\n );\n }\n }\n\n // Log summary of event subscriptions\n this.logEventSubscriptionSummary(result, provider.label);\n\n // Log important post-subscription steps for PaaS instances\n if (this.isPaaS) {\n this.customLogger.info('[IMPORTANT] ⚠️ Post-Subscription Steps for PaaS:');\n this.customLogger.info(\n '[IMPORTANT] 1. Run: bin/magento events:generate:module to generate module after successful event subscription'\n );\n this.customLogger.info(\n '[IMPORTANT] 2. Run: bin/magento setup:upgrade && bin/magento setup:di:compile && bin/magento cache:flush to install the generated module'\n );\n }\n }\n\n return {\n success: true,\n message: 'Configuration completed successfully',\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n this.customLogger.error(`[ERROR] Configuration failed: ${errorMessage}`);\n throw new Error(`Failed to configure Adobe Commerce I/O Events: ${errorMessage}`);\n }\n }\n\n /**\n * Filters commerce events configuration based on existing subscriptions and supported events\n *\n * @param commerceEventsConfig - Array of commerce event configurations\n * @param existingSubscriptions - Array of existing event subscriptions\n * @param providerId - Provider ID to match against\n * @param supportedEvents - Array of supported events from Adobe Commerce\n * @returns Object containing alreadySubscribed, needsSubscription, and unsupported arrays\n * @private\n */\n private filterEventsBySubscriptionStatus(\n commerceEventsConfig: CommerceEventConfig[],\n existingSubscriptions: any[],\n providerId: string,\n supportedEvents: any[] = []\n ): {\n alreadySubscribed: CommerceEventConfig[];\n needsSubscription: CommerceEventConfig[];\n unsupported: CommerceEventConfig[];\n } {\n const alreadySubscribed: CommerceEventConfig[] = [];\n const needsSubscription: CommerceEventConfig[] = [];\n const unsupported: CommerceEventConfig[] = [];\n\n // Create a set of supported event names for faster lookup\n const supportedEventNames = new Set(supportedEvents.map(event => event.name));\n\n commerceEventsConfig.forEach(commerceEvent => {\n const eventName = commerceEvent.event?.name;\n\n if (!eventName) {\n this.customLogger.error(\n 'Commerce event configuration missing event name, skipping:',\n commerceEvent\n );\n return;\n }\n\n // First check if the event is supported by Adobe Commerce\n if (supportedEvents.length > 0 && !supportedEventNames.has(eventName)) {\n unsupported.push(commerceEvent);\n return;\n }\n\n // Check if this event is already subscribed for this provider\n const isAlreadySubscribed = existingSubscriptions.some(\n subscription => subscription.name === eventName && subscription.provider_id === providerId\n );\n\n if (isAlreadySubscribed) {\n alreadySubscribed.push(commerceEvent);\n } else {\n needsSubscription.push(commerceEvent);\n }\n });\n\n return {\n alreadySubscribed,\n needsSubscription,\n unsupported,\n };\n }\n\n /**\n * Prepares event payload by transforming event names and adding provider information\n *\n * For PaaS instances, the parent field is omitted to support native events (observer.*, plugin.*)\n * which would be rejected by Adobe Commerce as invalid aliases if parent is set to the same name.\n * For non-PaaS instances, the parent field is set to the event name as usual.\n *\n * @param eventSpec - Event specification object containing event details\n * @param providerId - Provider ID to assign to the event\n * @returns Modified event specification with updated event properties\n * @private\n */\n private prepareEventPayload(eventSpec: CommerceEventConfig, providerId: string): any {\n // Input validation\n if (!eventSpec || !eventSpec.event) {\n throw new Error('Invalid event specification: event object is required');\n }\n\n if (!eventSpec.event.name) {\n throw new Error('Invalid event specification: event name is required');\n }\n\n if (!providerId || typeof providerId !== 'string') {\n throw new Error('Valid provider ID is required');\n }\n\n // Create a deep copy to avoid modifying the original object\n const modifiedEventSpec = JSON.parse(JSON.stringify(eventSpec));\n const eventName = modifiedEventSpec.event.name;\n\n // For PaaS instances, don't set parent field to support native events\n // For non-PaaS instances, set parent as usual\n if (!this.isPaaS) {\n modifiedEventSpec.event.parent = eventName;\n }\n // Note: For PaaS instances, we intentionally omit the parent field\n\n modifiedEventSpec.event.provider_id = providerId;\n modifiedEventSpec.event.destination = 'default';\n modifiedEventSpec.event.provider_id = providerId;\n modifiedEventSpec.event.priority = true;\n modifiedEventSpec.event.hipaa_audit_required = false;\n\n // Ensure rules array exists (required by Adobe Commerce API)\n if (!modifiedEventSpec.event.rules) {\n modifiedEventSpec.event.rules = [];\n }\n\n return modifiedEventSpec;\n }\n\n /**\n * Logs a comprehensive summary of event subscription results\n *\n * @param result - Event subscription processing results\n * @param providerLabel - Provider label for display\n * @private\n */\n private logEventSubscriptionSummary(\n result: {\n successfulSubscriptions: string[];\n failedSubscriptions: string[];\n alreadySubscribed: string[];\n unsupported: string[];\n skipped: number;\n },\n providerLabel: string\n ): void {\n // Log individual events with prefixes during processing\n if (result.alreadySubscribed.length > 0) {\n result.alreadySubscribed.forEach(eventName => {\n this.customLogger.info(`[SKIP] Already subscribed: ${eventName}`);\n });\n }\n\n if (result.unsupported.length > 0) {\n result.unsupported.forEach(eventName => {\n this.customLogger.error(`[ERROR] Unsupported event: ${eventName}`);\n });\n }\n\n // Summary section (no prefix)\n this.customLogger.info('');\n this.customLogger.info('='.repeat(60));\n this.customLogger.info(`📊 COMMERCE EVENTS CONFIGURATION SUMMARY - ${providerLabel}`);\n this.customLogger.info('='.repeat(60));\n this.customLogger.info('');\n\n // Overall summary\n const totalProcessed =\n result.successfulSubscriptions.length +\n result.failedSubscriptions.length +\n result.alreadySubscribed.length +\n result.unsupported.length;\n this.customLogger.info(\n `📈 OVERALL: ${totalProcessed} processed | ${result.successfulSubscriptions.length} created | ${result.alreadySubscribed.length} existing | ${result.unsupported.length} unsupported | ${result.failedSubscriptions.length} failed`\n );\n this.customLogger.info('');\n\n // Successful subscriptions\n if (result.successfulSubscriptions.length > 0) {\n this.customLogger.info(\n `✅ SUCCESSFUL SUBSCRIPTIONS (${result.successfulSubscriptions.length}):`\n );\n result.successfulSubscriptions.forEach(eventName => {\n this.customLogger.info(` ✓ ${eventName}`);\n });\n this.customLogger.info('');\n }\n\n // Already subscribed\n if (result.alreadySubscribed.length > 0) {\n this.customLogger.info(`ℹ️ ALREADY SUBSCRIBED (${result.alreadySubscribed.length}):`);\n result.alreadySubscribed.forEach(eventName => {\n this.customLogger.info(` → ${eventName}`);\n });\n this.customLogger.info('');\n }\n\n // Unsupported events\n if (result.unsupported.length > 0) {\n this.customLogger.info(`⚠️ UNSUPPORTED EVENTS (${result.unsupported.length}):`);\n result.unsupported.forEach(eventName => {\n this.customLogger.info(` ⚠ ${eventName}`);\n });\n this.customLogger.info('');\n }\n\n // Failed subscriptions\n if (result.failedSubscriptions.length > 0) {\n this.customLogger.info(`❌ FAILED SUBSCRIPTIONS (${result.failedSubscriptions.length}):`);\n result.failedSubscriptions.forEach(eventName => {\n this.customLogger.info(` ✗ ${eventName}`);\n });\n this.customLogger.info('');\n }\n\n this.customLogger.info('='.repeat(60));\n }\n}\n\nexport default OnboardCommerce;\n","/**\n * ConfigureProvider for Adobe I/O Events Provider Configuration\n *\n * <license header>\n */\n\nimport {\n EventConfigurationService,\n EventProviderService,\n type EventProvider,\n} from '@adobe-commerce/aio-services-kit';\nimport AdobeCommerceClient from '../../../commerce/adobe-commerce-client';\nimport CustomLogger from '../../../framework/custom-logger';\nimport type { Provider } from '../../../io-events/provider/types';\nimport type { WorkspaceConfig } from '../types';\nimport type { ConfigureProviderResult } from './types';\n\n/**\n * ConfigureProvider for Adobe I/O Events Provider Setup\n *\n * This class handles the configuration and setup of Adobe I/O Events providers\n * for Adobe Commerce integration.\n *\n * @example\n * ```typescript\n * const configureProvider = new ConfigureProvider(\n * adobeCommerceClient,\n * 'merchant-id-123',\n * 'environment-id-456',\n * logger\n * );\n * const result = await configureProvider.execute(provider, workspaceConfig);\n * ```\n */\nclass ConfigureProvider {\n /** Adobe Commerce client instance */\n private readonly adobeCommerceClient: AdobeCommerceClient;\n\n /** Merchant ID for Adobe Commerce */\n private readonly merchantId: string;\n\n /** Environment ID for Adobe Commerce */\n private readonly environmentId: string;\n\n /** CustomLogger instance for logging operations */\n private readonly customLogger: CustomLogger;\n\n /** EventProviderService instance for provider operations */\n private readonly eventProviderService: EventProviderService;\n\n /** EventConfigurationService instance for configuration operations */\n private readonly eventConfigurationService: EventConfigurationService;\n\n /**\n * Constructor for ConfigureProvider\n *\n * @param adobeCommerceClient - Adobe Commerce client instance\n * @param merchantId - Merchant ID for Adobe Commerce\n * @param environmentId - Environment ID for Adobe Commerce\n * @param logger - Optional logger instance for logging operations\n * @throws {Error} When required parameters are missing or invalid\n * @example\n * ```typescript\n * const configureProvider = new ConfigureProvider(\n * adobeCommerceClient,\n * 'merchant-id-123',\n * 'environment-id-456',\n * logger\n * );\n * ```\n */\n constructor(\n adobeCommerceClient: AdobeCommerceClient,\n merchantId: string,\n environmentId: string,\n logger: any = null\n ) {\n // Validate required parameters\n if (!adobeCommerceClient) {\n throw new Error('Adobe Commerce client is required');\n }\n if (!merchantId || typeof merchantId !== 'string') {\n throw new Error('Valid merchant ID is required');\n }\n if (!environmentId || typeof environmentId !== 'string') {\n throw new Error('Valid environment ID is required');\n }\n\n this.adobeCommerceClient = adobeCommerceClient;\n this.merchantId = merchantId;\n this.environmentId = environmentId;\n this.customLogger = new CustomLogger(logger);\n this.eventProviderService = new EventProviderService(this.adobeCommerceClient);\n this.eventConfigurationService = new EventConfigurationService(this.adobeCommerceClient);\n }\n\n /**\n * Execute provider configuration\n *\n * This method handles the provider configuration process for Adobe I/O Events.\n *\n * @param provider - Provider configuration for Adobe I/O Events\n * @param workspaceConfig - Workspace configuration settings\n * @returns A promise that resolves with the configuration result\n * @throws {Error} If provider configuration fails\n * @example\n * ```typescript\n * const result = await configureProvider.execute(provider, workspaceConfig);\n * if (result.success) {\n * console.log('Provider configured successfully');\n * }\n * ```\n */\n async execute(\n provider: Provider,\n workspaceConfig: WorkspaceConfig\n ): Promise<ConfigureProviderResult> {\n this.customLogger.debug('[DEBUG] Starting provider configuration');\n\n try {\n // Validate input parameters\n this.validateConfigureParams(provider, workspaceConfig);\n\n // Get current event providers\n this.customLogger.debug('[FETCH] Fetching current event providers');\n const eventProviderResult = await this.eventProviderService.list();\n\n if (!eventProviderResult.success) {\n const errorMsg = `Failed to fetch event providers: ${eventProviderResult.error}`;\n this.customLogger.error(`[ERROR] ${errorMsg}`);\n return {\n success: false,\n error: errorMsg,\n details: eventProviderResult,\n };\n }\n\n // Check if default workspace is empty and update if needed\n const workspaceUpdateResult = await this.updateWorkspaceIfEmpty(\n eventProviderResult.data,\n workspaceConfig\n );\n if (!workspaceUpdateResult.success) {\n return workspaceUpdateResult;\n }\n\n // Check if the provider is already added\n const providerList = Array.isArray(eventProviderResult.data) ? eventProviderResult.data : [];\n const existingProvider = providerList.find(\n (existingProvider: any) => existingProvider.provider_id === provider.id\n );\n\n if (existingProvider) {\n this.customLogger.info(`[SKIP] Provider ${provider.id} is already configured`);\n return {\n success: true,\n provider: existingProvider,\n };\n } else {\n this.customLogger.debug(\n `[DEBUG] Provider ${provider.id} is not yet configured - creating new provider...`\n );\n\n const createResult = await this.createNewProvider(provider, workspaceConfig);\n if (!createResult.success) {\n return createResult;\n }\n\n this.customLogger.info(`[CREATE] Event provider ${provider.id} created successfully`);\n return {\n success: true,\n provider: createResult.provider!,\n };\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n this.customLogger.error(`[ERROR] Provider configuration failed: ${errorMessage}`);\n\n return {\n success: false,\n error: errorMessage,\n };\n }\n }\n\n /**\n * Creates a new event provider\n *\n * @param provider - Provider configuration object\n * @param workspaceConfig - Workspace configuration object\n * @returns Creation result with success status and provider data\n * @private\n */\n private async createNewProvider(\n provider: Provider,\n workspaceConfig: WorkspaceConfig\n ): Promise<ConfigureProviderResult> {\n const providerData = {\n provider_id: provider.id,\n instance_id: provider.instance_id!, // Already validated in validateConfigureParams\n label: provider.label,\n description: provider.description,\n workspace_configuration: JSON.stringify(workspaceConfig),\n };\n\n this.customLogger.debug(`[DEBUG] Creating event provider: ${provider.label} (${provider.id})`);\n\n const createResult = await this.eventProviderService.create(providerData);\n\n if (!createResult.success) {\n const errorMsg = `Failed to create event provider: ${createResult.error}`;\n this.customLogger.error(`[ERROR] ${errorMsg}`);\n return {\n success: false,\n error: errorMsg,\n details: createResult,\n };\n }\n\n return {\n success: true,\n provider: createResult.data as EventProvider,\n };\n }\n\n /**\n * Updates workspace configuration if the default workspace is empty\n *\n * @param existingProviders - Array of existing providers\n * @param workspaceConfig - Workspace configuration object\n * @returns Update result with success status\n * @private\n */\n private async updateWorkspaceIfEmpty(\n existingProviders: any,\n workspaceConfig: WorkspaceConfig\n ): Promise<ConfigureProviderResult> {\n const providerArray = Array.isArray(existingProviders) ? existingProviders : [];\n const isDefaultWorkspaceEmpty =\n providerArray.length === 0 ||\n providerArray.every(\n (item: any) => !item.workspace_configuration || item.workspace_configuration === ''\n );\n\n if (isDefaultWorkspaceEmpty) {\n this.customLogger.debug('[DEBUG] Default workspace is empty, updating configuration...');\n\n const updateConfigPayload = {\n enabled: true,\n merchant_id: this.merchantId,\n environment_id: this.environmentId,\n workspace_configuration: JSON.stringify(workspaceConfig),\n };\n\n this.customLogger.debug(\n `[DEBUG] Updating workspace configuration for merchant: ${this.merchantId}`\n );\n\n const updateResult = await this.eventConfigurationService.update(updateConfigPayload);\n\n if (!updateResult.success) {\n const errorMsg = `Failed to update configuration: ${updateResult.error}`;\n this.customLogger.error(`[ERROR] ${errorMsg}`);\n return {\n success: false,\n error: errorMsg,\n details: updateResult,\n };\n }\n\n this.customLogger.info('[UPDATE] Configuration updated successfully');\n }\n\n return { success: true };\n }\n\n /**\n * Validate input parameters for configure method\n *\n * @param provider - Provider configuration for Adobe I/O Events\n * @param workspaceConfig - Workspace configuration settings\n * @throws {Error} If validation fails\n * @private\n */\n private validateConfigureParams(provider: Provider, workspaceConfig: WorkspaceConfig): void {\n if (!provider || typeof provider !== 'object') {\n throw new Error('Provider configuration object is required');\n }\n\n const requiredProviderFields: (keyof Provider)[] = [\n 'id',\n 'instance_id',\n 'label',\n 'description',\n ];\n for (const field of requiredProviderFields) {\n if (!provider[field] || typeof provider[field] !== 'string') {\n throw new Error(`Provider ${field} is required and must be a string`);\n }\n }\n\n if (!workspaceConfig || typeof workspaceConfig !== 'object') {\n throw new Error('Workspace configuration object is required');\n }\n\n this.customLogger.debug(`[DEBUG] Validated provider: ${provider.label} (${provider.id})`);\n }\n}\n\nexport default ConfigureProvider;\n","/**\n * <license header>\n */\n\n/**\n * Commerce utilities for Adobe Commerce AIO Toolkit\n */\n\n// Export Adobe Auth utility\nexport { default as AdobeAuth } from './adobe-auth';\n\n// Export Adobe Commerce Client utility\nexport { default as AdobeCommerceClient } from './adobe-commerce-client';\n\n// Export Adobe Commerce Client connection implementations\nexport { default as BasicAuthConnection } from './adobe-commerce-client/basic-auth-connection';\nexport { default as Oauth1aConnection } from './adobe-commerce-client/oauth1a-connection';\nexport { default as ImsConnection } from './adobe-commerce-client/ims-connection';\nexport { default as GenerateBasicAuthToken } from './adobe-commerce-client/basic-auth-connection/generate-basic-auth-token';\n\n// Export Shipping Carrier\nexport { default as ShippingCarrier } from './shipping-carrier';\nexport { default as ShippingCarrierMethod } from './shipping-carrier/method';\nexport { default as ShippingCarrierResponse } from './shipping-carrier/response';\n\n// Export Adobe Auth types\nexport type { AdobeIMSConfig } from './adobe-auth/types';\n\n// Export Adobe Commerce Client types\nexport type { Connection, ExtendedRequestError } from './adobe-commerce-client/types';\n\n// Export Basic Auth Token types\nexport type { TokenResult } from './adobe-commerce-client/basic-auth-connection/generate-basic-auth-token/types';\n\n// Export Shipping Carrier types\nexport type { ShippingCarrierData } from './shipping-carrier/types';\nexport type {\n ShippingCarrierMethodData,\n ShippingCarrierMethodAdditionalData,\n} from './shipping-carrier/method/types';\n","/**\n * <license header>\n */\n\nimport got, { Got } from 'got';\n\nimport CustomLogger from '../../framework/custom-logger';\nimport { HttpStatus } from '../../framework/runtime-action/types';\nimport { Connection, ExtendedRequestError, HttpsOptions } from './types';\n\nclass AdobeCommerceClient {\n private baseUrl: string;\n private connection: Connection;\n private logger: any;\n private httpsOptions: HttpsOptions | undefined;\n\n /**\n * @param baseUrl\n * @param connection\n * @param logger\n * @param httpsOptions\n */\n constructor(\n baseUrl: string,\n connection: Connection,\n logger: any = null,\n httpsOptions?: HttpsOptions\n ) {\n if (!baseUrl) {\n throw new Error('Commerce URL must be provided');\n }\n this.baseUrl = baseUrl;\n this.connection = connection;\n this.httpsOptions = httpsOptions;\n\n // Use `CustomLogger` to wrap the logger\n this.logger = new CustomLogger(logger);\n }\n\n /**\n * @param endpoint\n * @param headers\n */\n async get(endpoint: string, headers: Record<string, string> = {}): Promise<any> {\n return await this.apiCall(endpoint, 'GET', headers);\n }\n\n /**\n * @param endpoint\n * @param headers\n * @param payload\n */\n async post(\n endpoint: string,\n headers: Record<string, string> = {},\n payload: any = null\n ): Promise<any> {\n return await this.apiCall(endpoint, 'POST', headers, payload);\n }\n\n /**\n * @param endpoint\n * @param headers\n * @param payload\n */\n async put(\n endpoint: string,\n headers: Record<string, string> = {},\n payload: any = null\n ): Promise<any> {\n return await this.apiCall(endpoint, 'PUT', headers, payload);\n }\n\n /**\n * @param endpoint\n * @param headers\n */\n async delete(endpoint: string, headers: Record<string, string> = {}): Promise<any> {\n return await this.apiCall(endpoint, 'DELETE', headers);\n }\n\n /**\n * @param endpoint\n * @param method\n * @param headers\n * @param payload\n * @private\n */\n private async apiCall(\n endpoint: string,\n method: string,\n headers: Record<string, string>,\n payload: any = null\n ): Promise<any> {\n const commerceGot = await this.getHttpClient();\n\n commerceGot.extend({\n headers: headers,\n });\n\n const wrapper = async (callable: () => Promise<any>): Promise<any> => {\n try {\n const message = await callable();\n return { success: true, message };\n } catch (e: any) {\n if (e.code === 'ERR_GOT_REQUEST_ERROR') {\n this.logger.error('Error while calling Commerce API', e);\n return {\n success: false,\n statusCode: HttpStatus.INTERNAL_ERROR,\n message: `Unexpected error, check logs. Original error \"${e.message}\"`,\n };\n }\n return {\n success: false,\n statusCode: e.response?.statusCode || HttpStatus.INTERNAL_ERROR,\n message: e.message,\n body: (e as ExtendedRequestError).responseBody,\n };\n }\n };\n\n let options: any = {\n method: method,\n };\n\n if (payload !== null) {\n options = {\n ...options,\n json: payload,\n };\n }\n\n return await wrapper(() => commerceGot(endpoint, options).json());\n }\n\n /**\n * @private\n */\n private async getHttpClient(): Promise<Got> {\n const commerceGot = got.extend({\n http2: true,\n responseType: 'json',\n prefixUrl: this.baseUrl,\n headers: {\n 'Content-Type': 'application/json',\n },\n ...(this.httpsOptions && { https: this.httpsOptions }),\n hooks: {\n beforeRequest: [\n (options): void => this.logger.debug(`Request [${options.method}] ${options.url}`),\n ],\n beforeRetry: [\n (options, error, retryCount): void =>\n this.logger.debug(\n `Retrying request [${options.method}] ${options.url} - count: ${retryCount} - error: ${error?.code} - ${error?.message}`\n ),\n ],\n beforeError: [\n (error: ExtendedRequestError): ExtendedRequestError => {\n const { response } = error;\n if (response?.body) {\n error.responseBody = response.body;\n }\n return error;\n },\n ],\n afterResponse: [\n (response): any => {\n this.logger.debug(\n `Response [${response.request.options.method}] ${response.request.options.url} - ${response.statusCode} ${response.statusMessage}`\n );\n return response;\n },\n ],\n },\n });\n\n return await this.connection.extend(commerceGot);\n }\n}\n\nexport default AdobeCommerceClient;\n","/**\n * <license header>\n */\n\nimport CustomLogger from '../../../framework/custom-logger';\nimport GenerateBasicAuthToken from './generate-basic-auth-token';\nimport { Connection } from '../types';\n\nclass BasicAuthConnection implements Connection {\n private baseUrl: string;\n private username: string;\n private password: string;\n private logger: any;\n\n /**\n * @param baseUrl\n * @param username\n * @param password\n * @param logger\n */\n constructor(baseUrl: string, username: string, password: string, logger: any = null) {\n this.baseUrl = baseUrl;\n this.username = username;\n this.password = password;\n\n // Use `CustomLogger` to wrap the logger\n this.logger = new CustomLogger(logger);\n }\n\n /**\n * @param commerceGot\n */\n async extend(commerceGot: any): Promise<any> {\n this.logger.debug('Using Commerce client with integration options');\n\n const generateToken = new GenerateBasicAuthToken(\n this.baseUrl,\n this.username,\n this.password,\n this.logger.getLogger()\n );\n const token = await generateToken.execute();\n\n return commerceGot.extend({\n headers: {\n Authorization: `Bearer ${token}`,\n },\n });\n }\n}\n\nexport default BasicAuthConnection;\n","/**\n * <license header>\n */\n\nimport { State } from '@adobe/aio-sdk';\n\nimport CustomLogger from '../../../../framework/custom-logger';\nimport RestClient from '../../../../integration/rest-client';\nimport { TokenResult } from './types';\n\nclass GenerateBasicAuthToken {\n private baseUrl: string;\n private username: string;\n private password: string;\n private key: string;\n private logger: any;\n private state: any;\n\n /**\n * @param baseUrl\n * @param username\n * @param password\n * @param logger\n */\n constructor(baseUrl: string, username: string, password: string, logger: any = null) {\n this.baseUrl = baseUrl;\n this.username = username;\n this.password = password;\n this.key = 'adobe_commerce_basic_auth_token';\n\n // Use `CustomLogger` to wrap the logger\n this.logger = new CustomLogger(logger);\n }\n\n /**\n * @return string | null\n */\n async execute(): Promise<string | null> {\n const currentValue = await this.getValue();\n if (currentValue !== null) {\n return currentValue;\n }\n\n let result: TokenResult = {\n token: null,\n expire_in: 3600,\n };\n\n const response = await this.getCommerceToken();\n if (response !== null) {\n result = response;\n }\n\n this.logger.debug(`Token: ${JSON.stringify(result)}`);\n\n if (result.token !== null) {\n await this.setValue(result);\n }\n\n return result.token;\n }\n\n /**\n * @return TokenResult | null\n */\n async getCommerceToken(): Promise<TokenResult | null> {\n const endpoint = this.createTokenEndpoint();\n\n this.logger.debug(`Endpoint: ${endpoint}`);\n\n try {\n const restClient = new RestClient();\n const response = await restClient.post(\n endpoint,\n {\n 'Content-Type': 'application/json',\n },\n {\n username: this.username,\n password: this.password,\n }\n );\n\n this.logger.debug(`Raw response type: ${typeof response}`);\n this.logger.debug(`Raw response: ${JSON.stringify(response)}`);\n\n if (response !== null && response !== undefined) {\n // Adobe Commerce returns the token as a JSON string (e.g., \"abc123\")\n // If it's already a string, use it directly\n // If it's an object with token property, extract it\n let tokenValue: string;\n\n if (typeof response === 'string') {\n tokenValue = response;\n } else if (typeof response === 'object' && response.token) {\n tokenValue = response.token;\n } else {\n // Try to convert to string as a fallback\n try {\n tokenValue = response.toString();\n this.logger.debug(`Converted response to string: ${tokenValue?.substring(0, 10)}...`);\n } catch {\n this.logger.error(`Unexpected response format: ${JSON.stringify(response)}`);\n return null;\n }\n }\n\n this.logger.debug(`Extracted token: ${tokenValue?.substring(0, 10)}...`);\n\n return {\n token: tokenValue,\n expire_in: 3600, // Adobe Commerce tokens typically expire in 1 hour\n };\n }\n\n this.logger.error('Received null or undefined response from Commerce API');\n return null;\n } catch (error: any) {\n this.logger.error(`Failed to get Commerce token: ${error.message}`);\n this.logger.debug(`Full error: ${JSON.stringify(error)}`);\n return null;\n }\n }\n\n /**\n * Create the Adobe Commerce integration admin token endpoint.\n * Handles cases where baseUrl may or may not already include /rest.\n * @return string\n */\n createTokenEndpoint(): string {\n // Normalize base URL (remove trailing slash if present)\n const normalizedBaseUrl = this.baseUrl.replace(/\\/+$/, '');\n\n // Check if baseUrl already ends with /rest\n if (normalizedBaseUrl.endsWith('/rest')) {\n // Base URL already includes /rest, so append V1/integration/admin/token\n return `${normalizedBaseUrl}/V1/integration/admin/token`;\n } else {\n // Base URL doesn't include /rest, so append the full path\n return `${normalizedBaseUrl}/rest/V1/integration/admin/token`;\n }\n }\n\n /**\n * @param endpoint\n * @return string\n */\n createEndpoint(endpoint: string): string {\n // Normalize base URL (remove trailing slash if present)\n const normalizedBaseUrl = this.baseUrl.replace(/\\/+$/, '');\n // Ensure endpoint starts with /\n const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;\n return `${normalizedBaseUrl}${normalizedEndpoint}`;\n }\n\n /**\n * @param result\n * @return boolean\n */\n async setValue(result: TokenResult): Promise<boolean> {\n try {\n const state = await this.getState();\n if (state === null) {\n // State API not available, skip caching\n return true; // Return true since token generation succeeded\n }\n\n await state.put(this.key, result.token, { ttl: result.expire_in });\n return true;\n } catch (error) {\n this.logger.debug('Failed to cache token, continuing without caching');\n return true; // Return true since token generation succeeded\n }\n }\n\n /**\n * @return string | null\n */\n async getValue(): Promise<string | null> {\n try {\n const state = await this.getState();\n if (state === null) {\n // State API not available, skip caching\n return null;\n }\n\n const value = await state.get(this.key);\n if (value !== undefined) {\n return value.value;\n }\n } catch (error) {\n this.logger.debug('State API not available, skipping cache lookup');\n }\n\n return null;\n }\n\n /**\n * @return any\n */\n async getState(): Promise<any> {\n if (this.state === undefined) {\n try {\n this.state = await State.init();\n } catch (error) {\n this.logger.debug('State API initialization failed, running without caching');\n this.state = null;\n }\n }\n return this.state;\n }\n}\n\nexport default GenerateBasicAuthToken;\n","/**\n * <license header>\n */\n\nimport Oauth1a from 'oauth-1.0a';\nimport * as crypto from 'crypto';\nimport { Got } from 'got';\n\nimport CustomLogger from '../../../framework/custom-logger';\nimport { Connection } from '../types';\n\nclass Oauth1aConnection implements Connection {\n private consumerKey: string;\n private consumerSecret: string;\n private accessToken: string;\n private accessTokenSecret: string;\n private logger: any;\n\n /**\n * @param consumerKey\n * @param consumerSecret\n * @param accessToken\n * @param accessTokenSecret\n * @param logger\n */\n constructor(\n consumerKey: string,\n consumerSecret: string,\n accessToken: string,\n accessTokenSecret: string,\n logger: any = null\n ) {\n this.consumerKey = consumerKey;\n this.consumerSecret = consumerSecret;\n this.accessToken = accessToken;\n this.accessTokenSecret = accessTokenSecret;\n\n // Use `CustomLogger` to wrap the logger\n this.logger = new CustomLogger(logger);\n }\n\n /**\n * @param commerceGot\n */\n async extend(commerceGot: Got): Promise<Got> {\n this.logger.debug('Using Commerce client with integration options');\n\n const headers = this.headersProvider();\n\n return commerceGot.extend({\n handlers: [\n (options: any, next: any): Promise<any> => {\n options.headers = {\n ...options.headers,\n ...headers(options.url.toString(), options.method),\n };\n return next(options);\n },\n ],\n });\n }\n\n /**\n * return () => { }\n */\n headersProvider(): (url: string, method: string) => any {\n const oauth = new Oauth1a({\n consumer: {\n key: this.consumerKey,\n secret: this.consumerSecret,\n },\n signature_method: 'HMAC-SHA256',\n hash_function: (baseString: string, key: string): string =>\n crypto.createHmac('sha256', key).update(baseString).digest('base64'),\n });\n\n const oauthToken = {\n key: this.accessToken,\n secret: this.accessTokenSecret,\n };\n\n return (url: string, method: string): any =>\n oauth.toHeader(oauth.authorize({ url, method }, oauthToken));\n }\n}\n\nexport default Oauth1aConnection;\n","/**\n * <license header>\n */\n\nimport { Connection } from '../types';\nimport CustomLogger from '../../../framework/custom-logger';\n\n/**\n * ImsConnection for Adobe Commerce Client with IMS authentication\n *\n * This class provides IMS (Identity Management System) authentication for Adobe Commerce API requests\n * by accepting a pre-generated bearer token.\n *\n * **Token Management Best Practice:**\n * Generate tokens using `AdobeAuth.getToken()` and implement caching at the application level\n * (Redis, Memcached, in-memory, etc.) to avoid unnecessary token generation calls.\n *\n * @example\n * ```typescript\n * import { ImsConnection, AdobeCommerceClient } from '@adobe-commerce/aio-toolkit';\n * import AdobeAuth from '@adobe-commerce/aio-toolkit/commerce/adobe-auth';\n * import BearerToken from '@adobe-commerce/aio-toolkit/integration/bearer-token';\n *\n * // Check your application cache first\n * let token = await yourAppCache.get('commerce_ims_token');\n *\n * if (!token || !BearerToken.info(token).isValid) {\n * // Generate new token using AdobeAuth\n * token = await AdobeAuth.getToken(\n * 'client-id',\n * 'client-secret',\n * 'technical-account-id',\n * 'technical-account-email',\n * 'ims-org-id@AdobeOrg',\n * ['AdobeID', 'openid', 'adobeio_api']\n * );\n *\n * // Store in your application cache with appropriate TTL\n * const tokenInfo = BearerToken.info(token);\n * if (tokenInfo.isValid && tokenInfo.timeUntilExpiry) {\n * const ttl = Math.floor(tokenInfo.timeUntilExpiry / 1000) - 600;\n * await yourAppCache.set('commerce_ims_token', token, ttl);\n * }\n * }\n *\n * // Create connection with token\n * const connection = new ImsConnection(token, logger);\n *\n * // Create Commerce client\n * const client = new AdobeCommerceClient('https://your-store.com', connection);\n *\n * // Make API calls\n * const products = await client.get('V1/products');\n * ```\n */\nclass ImsConnection implements Connection {\n /** Bearer token for IMS authentication */\n private readonly imsToken: string;\n\n /** CustomLogger instance for logging operations */\n private readonly customLogger: CustomLogger;\n\n /**\n * Creates an instance of ImsConnection\n *\n * @param imsToken - Bearer token string for IMS authentication (generate using AdobeAuth)\n * @param logger - Optional logger instance for logging operations\n * @example\n * ```typescript\n * const token = await AdobeAuth.getToken(...);\n * const connection = new ImsConnection(token, logger);\n * ```\n */\n constructor(imsToken: string, logger: any = null) {\n this.imsToken = imsToken;\n this.customLogger = new CustomLogger(logger);\n }\n\n /**\n * Extends the Commerce Got client with IMS authentication headers\n *\n * @param commerceGot - The Got instance to extend with authentication\n * @returns Promise<any> - Extended Got instance with authentication headers\n * @throws {Error} If token is invalid or empty\n */\n async extend(commerceGot: any): Promise<any> {\n this.customLogger.info('Using Commerce client with IMS authentication');\n\n if (!this.imsToken || this.imsToken.trim() === '') {\n throw new Error('Failed to generate or retrieve IMS token');\n }\n\n this.customLogger.info(\n `IMS token being extended to header: ${this.imsToken.substring(0, 10)}...`\n );\n\n return commerceGot.extend({\n headers: {\n Authorization: `Bearer ${this.imsToken}`,\n },\n });\n }\n}\n\nexport default ImsConnection;\n","/**\n * <license header>\n */\n\nimport { ShippingCarrierMethodData } from './method/types';\nimport { ShippingCarrierData } from './types';\nimport ShippingCarrierMethod from './method';\n\n/**\n * Builder class for constructing shipping carriers with methods and metadata\n */\nclass ShippingCarrier {\n private carrierData: Partial<ShippingCarrierData>;\n private addedMethods: ShippingCarrierMethodData[] = [];\n private removedMethods: string[] = [];\n\n constructor(code: string, callback?: (builder: ShippingCarrier) => void) {\n this.validateCarrierCode(code);\n\n this.carrierData = {\n code,\n active: true,\n tracking_available: true,\n shipping_labels_available: true,\n };\n this.addedMethods = [];\n this.removedMethods = [];\n\n if (callback) {\n callback(this);\n }\n }\n\n /**\n * Validates that the carrier code contains only alphanumeric characters and underscores\n *\n * @param code - Carrier code to validate\n * @throws Error if code is invalid\n */\n private validateCarrierCode(code: string): void {\n if (!code || code.trim() === '') {\n throw new Error('Carrier code cannot be empty');\n }\n\n const validPattern = /^[a-zA-Z0-9_]+$/;\n if (!validPattern.test(code)) {\n throw new Error('Carrier code must contain only alphanumeric characters and underscores');\n }\n }\n\n /**\n * Validates that the method code contains only alphanumeric characters and underscores\n *\n * @param method - Method code to validate\n * @throws Error if method code is invalid\n */\n private validateMethodCode(method: string): void {\n if (!method || method.trim() === '') {\n throw new Error('Method code cannot be empty');\n }\n\n const validPattern = /^[a-zA-Z0-9_]+$/;\n if (!validPattern.test(method)) {\n throw new Error('Method code must contain only alphanumeric characters and underscores');\n }\n }\n\n /**\n * Sets the title for the shipping carrier\n *\n * @param title - Display title for the carrier\n * @returns The builder instance for method chaining\n *\n * @example\n * ```typescript\n * carrier.setTitle('FedEx Express');\n * ```\n */\n setTitle(title: string): this {\n this.carrierData.title = title;\n return this;\n }\n\n /**\n * Sets the stores for the shipping carrier\n *\n * @param stores - Array of store codes\n * @returns The builder instance for method chaining\n *\n * @example\n * ```typescript\n * carrier.setStores(['default', 'store1', 'store2']);\n * ```\n */\n setStores(stores: string[]): this {\n this.carrierData.stores = stores;\n return this;\n }\n\n /**\n * Sets the countries for the shipping carrier\n *\n * @param countries - Array of country codes\n * @returns The builder instance for method chaining\n *\n * @example\n * ```typescript\n * carrier.setCountries(['US', 'CA', 'MX']);\n * ```\n */\n setCountries(countries: string[]): this {\n this.carrierData.countries = countries;\n return this;\n }\n\n /**\n * Sets the sort order for the shipping carrier\n *\n * @param sortOrder - Sort order number\n * @returns The builder instance for method chaining\n *\n * @example\n * ```typescript\n * carrier.setSortOrder(10);\n * ```\n */\n setSortOrder(sortOrder: number): this {\n this.carrierData.sort_order = sortOrder;\n return this;\n }\n\n /**\n * Sets the active status for the shipping carrier\n *\n * @param active - Active status\n * @returns The builder instance for method chaining\n *\n * @example\n * ```typescript\n * carrier.setActive(true);\n * carrier.setActive(false);\n * ```\n */\n setActive(active: boolean): this {\n this.carrierData.active = active;\n return this;\n }\n\n /**\n * Sets the tracking availability for the shipping carrier\n *\n * @param trackingAvailable - Tracking availability status\n * @returns The builder instance for method chaining\n *\n * @example\n * ```typescript\n * carrier.setTrackingAvailable(true);\n * carrier.setTrackingAvailable(false);\n * ```\n */\n setTrackingAvailable(trackingAvailable: boolean): this {\n this.carrierData.tracking_available = trackingAvailable;\n return this;\n }\n\n /**\n * Sets the shipping labels availability for the shipping carrier\n *\n * @param shippingLabelsAvailable - Shipping labels availability status\n * @returns The builder instance for method chaining\n *\n * @example\n * ```typescript\n * carrier.setShippingLabelsAvailable(true);\n * carrier.setShippingLabelsAvailable(false);\n * ```\n */\n setShippingLabelsAvailable(shippingLabelsAvailable: boolean): this {\n this.carrierData.shipping_labels_available = shippingLabelsAvailable;\n return this;\n }\n\n /**\n * Sets the carrier data from a ShippingCarrierData object\n * Note: The code property cannot be changed once set in the constructor\n *\n * @param carrierData - Carrier data object\n * @returns The builder instance for method chaining\n *\n * @example\n * ```typescript\n * carrier.setData({\n * code: 'fedex',\n * title: 'FedEx Express',\n * stores: ['default'],\n * countries: ['US', 'CA'],\n * sort_order: 10,\n * active: true,\n * tracking_available: true,\n * shipping_labels_available: true\n * });\n * ```\n */\n setData(carrierData: ShippingCarrierData): this {\n // Preserve the original code - it cannot be changed\n const originalCode = this.carrierData.code as string;\n\n // Validate if a code is provided in the input data (even if empty string)\n if (carrierData.code !== undefined) {\n this.validateCarrierCode(carrierData.code);\n }\n\n // Copy all data but restore the original code\n this.carrierData = { ...carrierData, code: originalCode };\n return this;\n }\n\n /**\n * Adds a shipping method to the carrier using a callback pattern\n *\n * @param method - Unique method for the shipping rate\n * @param callback - Optional callback function to configure the method\n * @returns The builder instance for method chaining\n *\n * @example\n * ```typescript\n * builder.addMethod('standard', (method) => {\n * method.setMethodTitle('Standard Shipping')\n * .setPrice(9.99)\n * .setCost(5.00)\n * .addAdditionalData('delivery_time', '3-5 business days');\n * });\n * ```\n */\n addMethod(method: string, callback?: (builder: ShippingCarrierMethod) => void): this {\n this.validateMethodCode(method);\n\n const methodBuilder = new ShippingCarrierMethod(this.carrierData.code as string, method);\n\n if (callback) {\n callback(methodBuilder);\n }\n\n this.addedMethods.push(methodBuilder.getData());\n return this;\n }\n\n /**\n * Removes a shipping method from the carrier\n *\n * @param method - Method code to remove\n * @returns The builder instance for method chaining\n *\n * @example\n * ```typescript\n * builder.removeMethod('express');\n * ```\n */\n removeMethod(method: string): this {\n this.validateMethodCode(method);\n this.removedMethods.push(method);\n return this;\n }\n\n /**\n * Gets and returns the shipping carrier data as a JSON object\n *\n * @returns The shipping carrier data\n *\n * @example\n * ```typescript\n * const carrierData = carrier.getData();\n * // Returns:\n * // {\n * // code: 'DPS',\n * // title: 'Demo Postal Service',\n * // stores: ['default'],\n * // countries: ['US', 'CA'],\n * // sort_order: 10,\n * // active: true,\n * // tracking_available: true,\n * // shipping_labels_available: true\n * // }\n * ```\n */\n getData(): ShippingCarrierData {\n return this.carrierData as ShippingCarrierData;\n }\n\n /**\n * Gets the list of methods that have been added to the carrier\n *\n * @returns Array of added shipping carrier methods\n *\n * @example\n * ```typescript\n * const addedMethods = carrier.getAddedMethods();\n * // Returns: [{ carrier_code: 'fedex', method: 'standard', ... }, ...]\n * ```\n */\n getAddedMethods(): ShippingCarrierMethodData[] {\n return this.addedMethods;\n }\n\n /**\n * Gets the list of method codes that have been marked for removal\n *\n * @returns Array of method codes to be removed\n *\n * @example\n * ```typescript\n * const removedMethods = carrier.getRemovedMethods();\n * // Returns: ['overnight', 'express']\n * ```\n */\n getRemovedMethods(): string[] {\n return this.removedMethods;\n }\n}\n\nexport default ShippingCarrier;\n","/**\n * <license header>\n */\n\nimport { ShippingCarrierMethodData, ShippingCarrierMethodAdditionalData } from './types';\n\n/**\n * Builder class for constructing a shipping carrier method\n */\nclass ShippingCarrierMethod {\n private methodData: Partial<ShippingCarrierMethodData>;\n\n constructor(carrierCode: string, method: string) {\n this.methodData = { carrier_code: carrierCode, method, additional_data: [] };\n }\n\n /**\n * Sets the display name for the shipping method\n *\n * @param methodTitle - Display name for the shipping method\n * @returns The rate builder instance for method chaining\n */\n setMethodTitle(methodTitle: string): this {\n this.methodData.method_title = methodTitle;\n return this;\n }\n\n /**\n * Sets the price charged to the customer\n *\n * @param price - Price charged to the customer\n * @returns The rate builder instance for method chaining\n */\n setPrice(price: number): this {\n this.methodData.price = price;\n return this;\n }\n\n /**\n * Sets the cost to the merchant\n *\n * @param cost - Cost to the merchant\n * @returns The rate builder instance for method chaining\n */\n setCost(cost: number): this {\n this.methodData.cost = cost;\n return this;\n }\n\n /**\n * Adds additional data to the shipping method\n *\n * @param key - Key for the additional data\n * @param value - Value for the additional data\n * @returns The rate builder instance for method chaining\n *\n * @example\n * ```typescript\n * rate.addAdditionalData('delivery_time', '3-5 business days')\n * .addAdditionalData('tracking_available', true);\n * ```\n */\n addAdditionalData(key: string, value: any): this {\n const additionalDataItem: ShippingCarrierMethodAdditionalData = { key, value };\n this.methodData.additional_data?.push(additionalDataItem);\n return this;\n }\n\n /**\n * Gets and returns the shipping carrier method data\n *\n * @returns The shipping carrier method data\n */\n getData(): ShippingCarrierMethodData {\n return this.methodData as ShippingCarrierMethodData;\n }\n}\n\nexport default ShippingCarrierMethod;\n","/**\n * <license header>\n */\n\nimport ShippingCarrier from '..';\nimport WebhookActionResponse from '../../../framework/webhook-action/response';\nimport { WebhookActionResponseType } from '../../../framework/webhook-action/response/types';\n\n/**\n * Response generator for shipping carriers\n */\nclass ShippingCarrierResponse {\n private carrier: ShippingCarrier;\n\n constructor(carrier: ShippingCarrier) {\n this.carrier = carrier;\n }\n\n /**\n * Generates and returns an array of WebhookActionResponse operations\n *\n * @returns Array of WebhookActionResponse operations\n *\n * @example\n * ```typescript\n * const carrier = new ShippingCarrier('fedex');\n * const response = new ShippingCarrierResponse(carrier);\n * const operations = response.generate();\n * ```\n */\n generate(): WebhookActionResponseType[] {\n const operations: WebhookActionResponseType[] = [];\n\n // Get added methods from carrier\n const addedMethods = this.carrier['addedMethods'];\n for (const method of addedMethods) {\n operations.push(WebhookActionResponse.add('result', method));\n }\n\n // Get removed methods from carrier\n const removedMethods = this.carrier['removedMethods'];\n for (const method of removedMethods) {\n operations.push(WebhookActionResponse.add('result', { method: method, remove: true }));\n }\n\n return operations;\n }\n}\n\nexport default ShippingCarrierResponse;\n","/**\n * <license header>\n */\n\nexport { AdminUiSdk } from './admin-ui-sdk';\nexport type { MenuItem, Page, AdminUiSdkRegistration } from './admin-ui-sdk/types';\n","/**\n * <license header>\n */\n\nimport { MenuItem, AdminUiSdkRegistration } from './types';\n\n/**\n * AdminUiSdk class for managing Admin UI extensions\n * Provides methods to create menu items, sections, and pages for Adobe Commerce Admin UI extensions\n */\nexport class AdminUiSdk {\n private extensionId: string;\n private menuItems: MenuItem[] = [];\n private pageTitle?: string;\n\n /**\n * Creates a new AdminUiSdk instance\n * @param extensionId - Unique identifier for the extension\n * @throws {Error} If extensionId is empty or invalid\n */\n constructor(extensionId: string) {\n if (!extensionId?.trim()) {\n throw new Error('Extension ID is required and cannot be empty');\n }\n\n const trimmedId = extensionId.trim();\n if (!this.isValidExtensionId(trimmedId)) {\n throw new Error(\n 'Extension ID must be alphanumeric with underscores only (no spaces, hyphens, or special characters)'\n );\n }\n\n this.extensionId = trimmedId;\n }\n\n /**\n * Validates that an extension ID contains only alphanumeric characters and underscores\n * @param id - The extension ID to validate\n * @returns true if valid, false otherwise\n */\n private isValidExtensionId(id: string): boolean {\n return /^[a-zA-Z0-9_]+$/.test(id);\n }\n\n /**\n * Validates that a menu ID is valid (can contain :: separator for namespacing)\n * @param id - The menu ID to validate\n * @returns true if valid, false otherwise\n */\n private isValidMenuId(id: string): boolean {\n return /^[a-zA-Z0-9_:]+$/.test(id);\n }\n\n /**\n * Adds a menu item to the extension\n * @param id - Full identifier for the menu item (e.g., 'extensionId::menuItem')\n * @param title - Display title for the menu item\n * @param sortOrder - Sort order for menu positioning\n * @param parent - Parent menu identifier (optional, full ID like 'extensionId::parent')\n * @throws {Error} If parameters are invalid or ID already exists\n */\n addMenuItem(id: string, title: string, sortOrder: number, parent?: string): void {\n // Validation\n if (!id?.trim()) {\n throw new Error('Menu item ID is required and cannot be empty');\n }\n if (!this.isValidMenuId(id.trim())) {\n throw new Error(\n 'Menu item ID must be alphanumeric with underscores and colons only (no spaces, hyphens, or other special characters)'\n );\n }\n if (!title?.trim()) {\n throw new Error('Menu item title is required and cannot be empty');\n }\n if (parent !== undefined && !parent?.trim()) {\n throw new Error('Menu item parent cannot be empty if provided');\n }\n if (parent !== undefined && !this.isValidMenuId(parent.trim())) {\n throw new Error(\n 'Menu item parent must be alphanumeric with underscores and colons only (no spaces, hyphens, or other special characters)'\n );\n }\n if (typeof sortOrder !== 'number' || sortOrder < 0) {\n throw new Error('Menu item sortOrder must be a non-negative number');\n }\n\n const trimmedId = id.trim();\n\n // Check for duplicate IDs\n if (this.menuItems.some(item => item.id === trimmedId)) {\n throw new Error(`Menu item with ID '${trimmedId}' already exists`);\n }\n\n // Build menu item object - only include parent if provided\n const menuItem: MenuItem = {\n id: trimmedId,\n title: title.trim(),\n sortOrder,\n };\n\n if (parent?.trim()) {\n menuItem.parent = parent.trim();\n }\n\n // Add sanitized menu item\n this.menuItems.push(menuItem);\n }\n\n /**\n * Adds a menu section to the extension\n * @param id - Full identifier for the menu section (e.g., 'extensionId::section')\n * @param title - Display title for the menu section\n * @param sortOrder - Sort order for section positioning\n * @param parent - Parent menu identifier (optional, full ID like 'Magento_Backend::system')\n * @throws {Error} If parameters are invalid or ID already exists\n */\n addMenuSection(id: string, title: string, sortOrder: number, parent?: string): void {\n // Validation\n if (!id?.trim()) {\n throw new Error('Menu section ID is required and cannot be empty');\n }\n if (!this.isValidMenuId(id.trim())) {\n throw new Error(\n 'Menu section ID must be alphanumeric with underscores and colons only (no spaces, hyphens, or other special characters)'\n );\n }\n if (!title?.trim()) {\n throw new Error('Menu section title is required and cannot be empty');\n }\n if (parent !== undefined && !parent?.trim()) {\n throw new Error('Menu section parent cannot be empty if provided');\n }\n if (parent !== undefined && !this.isValidMenuId(parent.trim())) {\n throw new Error(\n 'Menu section parent must be alphanumeric with underscores and colons only (no spaces, hyphens, or other special characters)'\n );\n }\n if (typeof sortOrder !== 'number' || sortOrder < 0) {\n throw new Error('Menu section sortOrder must be a non-negative number');\n }\n\n const trimmedId = id.trim();\n\n // Check for duplicate IDs\n if (this.menuItems.some(item => item.id === trimmedId)) {\n throw new Error(`Menu item with ID '${trimmedId}' already exists`);\n }\n\n // Build menu section object - only include parent if provided\n const menuSection: MenuItem = {\n id: trimmedId,\n title: title.trim(),\n sortOrder,\n isSection: true,\n };\n\n if (parent?.trim()) {\n menuSection.parent = parent.trim();\n }\n\n // Add sanitized menu section\n this.menuItems.push(menuSection);\n }\n\n /**\n * Sets the page title for the extension\n * @param title - The page title\n * @throws {Error} If title is empty or invalid\n */\n addPage(title: string): void {\n if (!title?.trim()) {\n throw new Error('Page title is required and cannot be empty');\n }\n this.pageTitle = title.trim();\n }\n\n /**\n * Gets the complete registration object for the extension\n * @returns The registration object with optional menu items and page configuration\n */\n getRegistration(): AdminUiSdkRegistration {\n const registration: any = {};\n\n // Only include menuItems if there are any\n if (this.menuItems.length > 0) {\n registration.menuItems = [...this.menuItems]; // Return copy to prevent mutation\n }\n\n // Only include page if title is set\n if (this.pageTitle) {\n registration.page = {\n title: this.pageTitle,\n };\n }\n\n return {\n registration,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAF9B;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAyBa;AAzBb;AAAA;AAAA;AAAA;AAyBO,IAAM,uBAAN,MAAM,6BAA4B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAM7C,YAAY,SAAiB;AAC3B,cAAM,OAAO;AACb,aAAK,OAAO;AAGZ,YAAI,MAAM,mBAAmB;AAC3B,gBAAM,kBAAkB,MAAM,oBAAmB;AAAA,QACnD;AAAA,MACF;AAAA,IACF;AAf+C;AAAxC,IAAM,sBAAN;AAAA;AAAA;;;ACzBP,IAyBa;AAzBb;AAAA;AAAA;AAAA;AAIA;AAqBO,IAAM,8BAAN,MAAM,4BAA6D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAuBjE,aAAa,QAA0C;AAC5D,eAAO,OAAO,qBAAqB,QAAQ,OAAO,wBAAwB;AAAA,MAC5E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAgCO,sBAAsB,QAAuC;AAClE,YACE,OAAO,2BAA2B,UAClC,OAAO,2BAA2B,QAClC,OAAO,2BAA2B,IAClC;AACA,gBAAM,IAAI,oBAAoB,oCAAoC;AAAA,QACpE;AAEA,YACE,OAAO,0BAA0B,U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,mBAAa,OAAO;AAAA,QAClB,OAAO,KAAK;AAAA,MACd;AAAA,IACF;AAEA,WAAO;AAAA,MACL;AAAA,IACF;AAAA,EACF;AACF;AA7LwB;AAAjB,IAAM,aAAN;","names":["HttpStatus","HttpMethod","NewRelicTelemetry","errorMessage","context","WebhookActionOperation","path","response_default","SignatureVerification","response_default","Core","_List","statusCode","errorMessage","List","_Get","statusCode","errorMessage","Get","_Create","statusCode","errorMessage","Create","create_default","_Delete","statusCode","errorMessage","Delete","List","Get","create_default","_Create","Create","create_default","_Delete","Delete","delete_default","_Get","Get","get_default","_List","List","list_default","create_default","delete_default","get_default","list_default","Core","Core","State","crypto","Core","State","crypto","existingProvider","State","State","crypto","response_default"]}
1
+ {"version":3,"sources":["../node_modules/@opentelemetry/api/src/platform/node/globalThis.ts","../node_modules/@opentelemetry/api/src/platform/node/index.ts","../node_modules/@opentelemetry/api/src/platform/index.ts","../node_modules/@opentelemetry/api/src/version.ts","../node_modules/@opentelemetry/api/src/internal/semver.ts","../node_modules/@opentelemetry/api/src/internal/global-utils.ts","../node_modules/@opentelemetry/api/src/diag/ComponentLogger.ts","../node_modules/@opentelemetry/api/src/diag/types.ts","../node_modules/@opentelemetry/api/src/diag/internal/logLevelLogger.ts","../node_modules/@opentelemetry/api/src/api/diag.ts","../node_modules/@opentelemetry/api/src/diag-api.ts","../node_modules/@opentelemetry/api/src/index.ts","../src/framework/runtime-action/types.ts","../src/framework/runtime-action/response/index.ts","../src/framework/runtime-action/validator/index.ts","../src/framework/telemetry/index.ts","../src/framework/telemetry/new-relic/index.ts","../src/framework/telemetry/helpers/input-error/index.ts","../src/framework/telemetry/new-relic/validator/index.ts","../src/framework/telemetry/helpers/resource-factory/index.ts","../node_modules/@opentelemetry/resources/src/ResourceImpl.ts","../node_modules/@opentelemetry/resources/src/utils.ts","../src/framework/telemetry/helpers/success-checker/index.ts","../src/framework/telemetry/helpers/json-message-processor/index.ts","../src/framework/runtime-action/index.ts","../src/framework/runtime-action/parameters/index.ts","../src/framework/event-consumer-action/index.ts","../src/framework/graphql-action/index.ts","../src/framework/openwhisk/index.ts","../src/framework/openwhisk-action/index.ts","../src/framework/repository/file-repository/index.ts","../src/framework/publish-event/index.ts","../src/framework/custom-logger/index.ts","../src/framework/webhook-action/response/types.ts","../src/framework/webhook-action/response/index.ts","../src/framework/webhook-action/types.ts","../src/framework/webhook-action/index.ts","../src/framework/ims-token/index.ts","../src/commerce/adobe-auth/index.ts","../src/integration/bearer-token/index.ts","../src/integration/rest-client/index.ts","../src/framework/runtime-api-gateway-service/index.ts","../src/integration/onboard-events/index.ts","../src/io-events/types.ts","../src/io-events/provider/list/index.ts","../src/io-events/provider/get/index.ts","../src/io-events/provider/create/index.ts","../src/io-events/provider/delete/index.ts","../src/io-events/provider/index.ts","../src/io-events/event-metadata/list/index.ts","../src/io-events/event-metadata/get/index.ts","../src/io-events/event-metadata/create/index.ts","../src/io-events/event-metadata/delete/index.ts","../src/io-events/event-metadata/index.ts","../src/io-events/registration/create/index.ts","../src/io-events/registration/delete/index.ts","../src/io-events/registration/get/index.ts","../src/io-events/registration/list/index.ts","../src/io-events/registration/index.ts","../src/integration/onboard-events/create-providers/index.ts","../src/integration/onboard-events/create-events/index.ts","../src/integration/onboard-events/create-registrations/index.ts","../src/integration/onboard-events/input-parser/index.ts","../src/integration/infinite-loop-breaker/index.ts","../src/integration/onboard-commerce/configure-provider/index.ts","../src/integration/onboard-commerce/index.ts","../src/commerce/adobe-commerce-client/index.ts","../src/commerce/adobe-commerce-client/basic-auth-connection/generate-basic-auth-token/index.ts","../src/commerce/adobe-commerce-client/basic-auth-connection/index.ts","../src/commerce/adobe-commerce-client/oauth1a-connection/index.ts","../src/commerce/adobe-commerce-client/ims-connection/index.ts","../src/commerce/shipping-carrier/method/index.ts","../src/commerce/shipping-carrier/index.ts","../src/commerce/shipping-carrier/response/index.ts","../src/experience/admin-ui-sdk/index.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './globalThis';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './node';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.9.0';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { VERSION } from '../version';\n\nconst re = /^(\\d+)\\.(\\d+)\\.(\\d+)(-(.+))?$/;\n\n/**\n * Create a function to test an API version to see if it is compatible with the provided ownVersion.\n *\n * The returned function has the following semantics:\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param ownVersion version which should be checked against\n */\nexport function _makeCompatibilityCheck(\n ownVersion: string\n): (globalVersion: string) => boolean {\n const acceptedVersions = new Set<string>([ownVersion]);\n const rejectedVersions = new Set<string>();\n\n const myVersionMatch = ownVersion.match(re);\n if (!myVersionMatch) {\n // we cannot guarantee compatibility so we always return noop\n return () => false;\n }\n\n const ownVersionParsed = {\n major: +myVersionMatch[1],\n minor: +myVersionMatch[2],\n patch: +myVersionMatch[3],\n prerelease: myVersionMatch[4],\n };\n\n // if ownVersion has a prerelease tag, versions must match exactly\n if (ownVersionParsed.prerelease != null) {\n return function isExactmatch(globalVersion: string): boolean {\n return globalVersion === ownVersion;\n };\n }\n\n function _reject(v: string) {\n rejectedVersions.add(v);\n return false;\n }\n\n function _accept(v: string) {\n acceptedVersions.add(v);\n return true;\n }\n\n return function isCompatible(globalVersion: string): boolean {\n if (acceptedVersions.has(globalVersion)) {\n return true;\n }\n\n if (rejectedVersions.has(globalVersion)) {\n return false;\n }\n\n const globalVersionMatch = globalVersion.match(re);\n if (!globalVersionMatch) {\n // cannot parse other version\n // we cannot guarantee compatibility so we always noop\n return _reject(globalVersion);\n }\n\n const globalVersionParsed = {\n major: +globalVersionMatch[1],\n minor: +globalVersionMatch[2],\n patch: +globalVersionMatch[3],\n prerelease: globalVersionMatch[4],\n };\n\n // if globalVersion has a prerelease tag, versions must match exactly\n if (globalVersionParsed.prerelease != null) {\n return _reject(globalVersion);\n }\n\n // major versions must match\n if (ownVersionParsed.major !== globalVersionParsed.major) {\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.major === 0) {\n if (\n ownVersionParsed.minor === globalVersionParsed.minor &&\n ownVersionParsed.patch <= globalVersionParsed.patch\n ) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.minor <= globalVersionParsed.minor) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n };\n}\n\n/**\n * Test an API version to see if it is compatible with this API.\n *\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param version version of the API requesting an instance of the global API\n */\nexport const isCompatible = _makeCompatibilityCheck(VERSION);\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MeterProvider } from '../metrics/MeterProvider';\nimport { ContextManager } from '../context/types';\nimport { DiagLogger } from '../diag/types';\nimport { _globalThis } from '../platform';\nimport { TextMapPropagator } from '../propagation/TextMapPropagator';\nimport type { TracerProvider } from '../trace/tracer_provider';\nimport { VERSION } from '../version';\nimport { isCompatible } from './semver';\n\nconst major = VERSION.split('.')[0];\nconst GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(\n `opentelemetry.js.api.${major}`\n);\n\nconst _global = _globalThis as OTelGlobal;\n\nexport function registerGlobal<Type extends keyof OTelGlobalAPI>(\n type: Type,\n instance: OTelGlobalAPI[Type],\n diag: DiagLogger,\n allowOverride = false\n): boolean {\n const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = _global[\n GLOBAL_OPENTELEMETRY_API_KEY\n ] ?? {\n version: VERSION,\n });\n\n if (!allowOverride && api[type]) {\n // already registered an API of this type\n const err = new Error(\n `@opentelemetry/api: Attempted duplicate registration of API: ${type}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n if (api.version !== VERSION) {\n // All registered APIs must be of the same version exactly\n const err = new Error(\n `@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n api[type] = instance;\n diag.debug(\n `@opentelemetry/api: Registered a global for ${type} v${VERSION}.`\n );\n\n return true;\n}\n\nexport function getGlobal<Type extends keyof OTelGlobalAPI>(\n type: Type\n): OTelGlobalAPI[Type] | undefined {\n const globalVersion = _global[GLOBAL_OPENTELEMETRY_API_KEY]?.version;\n if (!globalVersion || !isCompatible(globalVersion)) {\n return;\n }\n return _global[GLOBAL_OPENTELEMETRY_API_KEY]?.[type];\n}\n\nexport function unregisterGlobal(type: keyof OTelGlobalAPI, diag: DiagLogger) {\n diag.debug(\n `@opentelemetry/api: Unregistering a global for ${type} v${VERSION}.`\n );\n const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];\n\n if (api) {\n delete api[type];\n }\n}\n\ntype OTelGlobal = {\n [GLOBAL_OPENTELEMETRY_API_KEY]?: OTelGlobalAPI;\n};\n\ntype OTelGlobalAPI = {\n version: string;\n\n diag?: DiagLogger;\n trace?: TracerProvider;\n context?: ContextManager;\n metrics?: MeterProvider;\n propagation?: TextMapPropagator;\n};\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobal } from '../internal/global-utils';\nimport { ComponentLoggerOptions, DiagLogger, DiagLogFunction } from './types';\n\n/**\n * Component Logger which is meant to be used as part of any component which\n * will add automatically additional namespace in front of the log message.\n * It will then forward all message to global diag logger\n * @example\n * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });\n * cLogger.debug('test');\n * // @opentelemetry/instrumentation-http test\n */\nexport class DiagComponentLogger implements DiagLogger {\n private _namespace: string;\n\n constructor(props: ComponentLoggerOptions) {\n this._namespace = props.namespace || 'DiagComponentLogger';\n }\n\n public debug(...args: any[]): void {\n return logProxy('debug', this._namespace, args);\n }\n\n public error(...args: any[]): void {\n return logProxy('error', this._namespace, args);\n }\n\n public info(...args: any[]): void {\n return logProxy('info', this._namespace, args);\n }\n\n public warn(...args: any[]): void {\n return logProxy('warn', this._namespace, args);\n }\n\n public verbose(...args: any[]): void {\n return logProxy('verbose', this._namespace, args);\n }\n}\n\nfunction logProxy(\n funcName: keyof DiagLogger,\n namespace: string,\n args: any\n): void {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) {\n return;\n }\n\n args.unshift(namespace);\n return logger[funcName](...(args as Parameters<DiagLogFunction>));\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type DiagLogFunction = (message: string, ...args: unknown[]) => void;\n\n/**\n * Defines an internal diagnostic logger interface which is used to log internal diagnostic\n * messages, you can set the default diagnostic logger via the {@link DiagAPI} setLogger function.\n * API provided implementations include :-\n * - a No-Op {@link createNoopDiagLogger}\n * - a {@link DiagLogLevel} filtering wrapper {@link createLogLevelDiagLogger}\n * - a general Console {@link DiagConsoleLogger} version.\n */\nexport interface DiagLogger {\n /** Log an error scenario that was not expected and caused the requested operation to fail. */\n error: DiagLogFunction;\n\n /**\n * Log a warning scenario to inform the developer of an issues that should be investigated.\n * The requested operation may or may not have succeeded or completed.\n */\n warn: DiagLogFunction;\n\n /**\n * Log a general informational message, this should not affect functionality.\n * This is also the default logging level so this should NOT be used for logging\n * debugging level information.\n */\n info: DiagLogFunction;\n\n /**\n * Log a general debug message that can be useful for identifying a failure.\n * Information logged at this level may include diagnostic details that would\n * help identify a failure scenario.\n * For example: Logging the order of execution of async operations.\n */\n debug: DiagLogFunction;\n\n /**\n * Log a detailed (verbose) trace level logging that can be used to identify failures\n * where debug level logging would be insufficient, this level of tracing can include\n * input and output parameters and as such may include PII information passing through\n * the API. As such it is recommended that this level of tracing should not be enabled\n * in a production environment.\n */\n verbose: DiagLogFunction;\n}\n\n/**\n * Defines the available internal logging levels for the diagnostic logger, the numeric values\n * of the levels are defined to match the original values from the initial LogLevel to avoid\n * compatibility/migration issues for any implementation that assume the numeric ordering.\n */\nexport enum DiagLogLevel {\n /** Diagnostic Logging level setting to disable all logging (except and forced logs) */\n NONE = 0,\n\n /** Identifies an error scenario */\n ERROR = 30,\n\n /** Identifies a warning scenario */\n WARN = 50,\n\n /** General informational log message */\n INFO = 60,\n\n /** General debug log message */\n DEBUG = 70,\n\n /**\n * Detailed trace level logging should only be used for development, should only be set\n * in a development environment.\n */\n VERBOSE = 80,\n\n /** Used to set the logging level to include all logging */\n ALL = 9999,\n}\n\n/**\n * Defines options for ComponentLogger\n */\nexport interface ComponentLoggerOptions {\n namespace: string;\n}\n\nexport interface DiagLoggerOptions {\n /**\n * The {@link DiagLogLevel} used to filter logs sent to the logger.\n *\n * @defaultValue DiagLogLevel.INFO\n */\n logLevel?: DiagLogLevel;\n\n /**\n * Setting this value to `true` will suppress the warning message normally emitted when registering a logger when another logger is already registered.\n */\n suppressOverrideMessage?: boolean;\n}\n\nexport interface DiagLoggerApi {\n /**\n * Set the global DiagLogger and DiagLogLevel.\n * If a global diag logger is already set, this will override it.\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param options - A {@link DiagLoggerOptions} object. If not provided, default values will be set.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, options?: DiagLoggerOptions): boolean;\n\n /**\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param logLevel - The {@link DiagLogLevel} used to filter logs sent to the logger. If not provided it will default to {@link DiagLogLevel.INFO}.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, logLevel?: DiagLogLevel): boolean;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogFunction, DiagLogger, DiagLogLevel } from '../types';\n\nexport function createLogLevelDiagLogger(\n maxLevel: DiagLogLevel,\n logger: DiagLogger\n): DiagLogger {\n if (maxLevel < DiagLogLevel.NONE) {\n maxLevel = DiagLogLevel.NONE;\n } else if (maxLevel > DiagLogLevel.ALL) {\n maxLevel = DiagLogLevel.ALL;\n }\n\n // In case the logger is null or undefined\n logger = logger || {};\n\n function _filterFunc(\n funcName: keyof DiagLogger,\n theLevel: DiagLogLevel\n ): DiagLogFunction {\n const theFunc = logger[funcName];\n\n if (typeof theFunc === 'function' && maxLevel >= theLevel) {\n return theFunc.bind(logger);\n }\n return function () {};\n }\n\n return {\n error: _filterFunc('error', DiagLogLevel.ERROR),\n warn: _filterFunc('warn', DiagLogLevel.WARN),\n info: _filterFunc('info', DiagLogLevel.INFO),\n debug: _filterFunc('debug', DiagLogLevel.DEBUG),\n verbose: _filterFunc('verbose', DiagLogLevel.VERBOSE),\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagComponentLogger } from '../diag/ComponentLogger';\nimport { createLogLevelDiagLogger } from '../diag/internal/logLevelLogger';\nimport {\n ComponentLoggerOptions,\n DiagLogFunction,\n DiagLogger,\n DiagLoggerApi,\n DiagLogLevel,\n} from '../diag/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\n\nconst API_NAME = 'diag';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry internal\n * diagnostic API\n */\nexport class DiagAPI implements DiagLogger, DiagLoggerApi {\n private static _instance?: DiagAPI;\n\n /** Get the singleton instance of the DiagAPI API */\n public static instance(): DiagAPI {\n if (!this._instance) {\n this._instance = new DiagAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Private internal constructor\n * @private\n */\n private constructor() {\n function _logProxy(funcName: keyof DiagLogger): DiagLogFunction {\n return function (...args) {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) return;\n return logger[funcName](...args);\n };\n }\n\n // Using self local variable for minification purposes as 'this' cannot be minified\n const self = this;\n\n // DiagAPI specific functions\n\n const setLogger: DiagLoggerApi['setLogger'] = (\n logger,\n optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }\n ) => {\n if (logger === self) {\n // There isn't much we can do here.\n // Logging to the console might break the user application.\n // Try to log to self. If a logger was previously registered it will receive the log.\n const err = new Error(\n 'Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'\n );\n self.error(err.stack ?? err.message);\n return false;\n }\n\n if (typeof optionsOrLogLevel === 'number') {\n optionsOrLogLevel = {\n logLevel: optionsOrLogLevel,\n };\n }\n\n const oldLogger = getGlobal('diag');\n const newLogger = createLogLevelDiagLogger(\n optionsOrLogLevel.logLevel ?? DiagLogLevel.INFO,\n logger\n );\n // There already is an logger registered. We'll let it know before overwriting it.\n if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {\n const stack = new Error().stack ?? '<failed to generate stacktrace>';\n oldLogger.warn(`Current logger will be overwritten from ${stack}`);\n newLogger.warn(\n `Current logger will overwrite one already registered from ${stack}`\n );\n }\n\n return registerGlobal('diag', newLogger, self, true);\n };\n\n self.setLogger = setLogger;\n\n self.disable = () => {\n unregisterGlobal(API_NAME, self);\n };\n\n self.createComponentLogger = (options: ComponentLoggerOptions) => {\n return new DiagComponentLogger(options);\n };\n\n self.verbose = _logProxy('verbose');\n self.debug = _logProxy('debug');\n self.info = _logProxy('info');\n self.warn = _logProxy('warn');\n self.error = _logProxy('error');\n }\n\n public setLogger!: DiagLoggerApi['setLogger'];\n /**\n *\n */\n public createComponentLogger!: (\n options: ComponentLoggerOptions\n ) => DiagLogger;\n\n // DiagLogger implementation\n public verbose!: DiagLogFunction;\n public debug!: DiagLogFunction;\n public info!: DiagLogFunction;\n public warn!: DiagLogFunction;\n public error!: DiagLogFunction;\n\n /**\n * Unregister the global logger and return to Noop\n */\n public disable!: () => void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { DiagAPI } from './api/diag';\n/**\n * Entrypoint for Diag API.\n * Defines Diagnostic handler used for internal diagnostic logging operations.\n * The default provides a Noop DiagLogger implementation which may be changed via the\n * diag.setLogger(logger: DiagLogger) function.\n */\nexport const diag = DiagAPI.instance();\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { BaggageEntry, BaggageEntryMetadata, Baggage } from './baggage/types';\nexport { baggageEntryMetadataFromString } from './baggage/utils';\nexport { Exception } from './common/Exception';\nexport { HrTime, TimeInput } from './common/Time';\nexport { Attributes, AttributeValue } from './common/Attributes';\n\n// Context APIs\nexport { createContextKey, ROOT_CONTEXT } from './context/context';\nexport { Context, ContextManager } from './context/types';\nexport type { ContextAPI } from './api/context';\n\n// Diag APIs\nexport { DiagConsoleLogger } from './diag/consoleLogger';\nexport {\n DiagLogFunction,\n DiagLogger,\n DiagLogLevel,\n ComponentLoggerOptions,\n DiagLoggerOptions,\n} from './diag/types';\nexport type { DiagAPI } from './api/diag';\n\n// Metrics APIs\nexport { createNoopMeter } from './metrics/NoopMeter';\nexport { MeterOptions, Meter } from './metrics/Meter';\nexport { MeterProvider } from './metrics/MeterProvider';\nexport {\n ValueType,\n Counter,\n Gauge,\n Histogram,\n MetricOptions,\n Observable,\n ObservableCounter,\n ObservableGauge,\n ObservableUpDownCounter,\n UpDownCounter,\n BatchObservableCallback,\n MetricAdvice,\n MetricAttributes,\n MetricAttributeValue,\n ObservableCallback,\n} from './metrics/Metric';\nexport {\n BatchObservableResult,\n ObservableResult,\n} from './metrics/ObservableResult';\nexport type { MetricsAPI } from './api/metrics';\n\n// Propagation APIs\nexport {\n TextMapPropagator,\n TextMapSetter,\n TextMapGetter,\n defaultTextMapGetter,\n defaultTextMapSetter,\n} from './propagation/TextMapPropagator';\nexport type { PropagationAPI } from './api/propagation';\n\n// Trace APIs\nexport { SpanAttributes, SpanAttributeValue } from './trace/attributes';\nexport { Link } from './trace/link';\nexport { ProxyTracer, TracerDelegator } from './trace/ProxyTracer';\nexport { ProxyTracerProvider } from './trace/ProxyTracerProvider';\nexport { Sampler } from './trace/Sampler';\nexport { SamplingDecision, SamplingResult } from './trace/SamplingResult';\nexport { SpanContext } from './trace/span_context';\nexport { SpanKind } from './trace/span_kind';\nexport { Span } from './trace/span';\nexport { SpanOptions } from './trace/SpanOptions';\nexport { SpanStatus, SpanStatusCode } from './trace/status';\nexport { TraceFlags } from './trace/trace_flags';\nexport { TraceState } from './trace/trace_state';\nexport { createTraceState } from './trace/internal/utils';\nexport { TracerProvider } from './trace/tracer_provider';\nexport { Tracer } from './trace/tracer';\nexport { TracerOptions } from './trace/tracer_options';\nexport {\n isSpanContextValid,\n isValidTraceId,\n isValidSpanId,\n} from './trace/spancontext-utils';\nexport {\n INVALID_SPANID,\n INVALID_TRACEID,\n INVALID_SPAN_CONTEXT,\n} from './trace/invalid-span-constants';\nexport type { TraceAPI } from './api/trace';\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { context } from './context-api';\nimport { diag } from './diag-api';\nimport { metrics } from './metrics-api';\nimport { propagation } from './propagation-api';\nimport { trace } from './trace-api';\n\n// Named export.\nexport { context, diag, metrics, propagation, trace };\n// Default export.\nexport default {\n context,\n diag,\n metrics,\n propagation,\n trace,\n};\n","/**\n * <license header>\n */\n\nexport enum HttpStatus {\n OK = 200,\n BAD_REQUEST = 400,\n UNAUTHORIZED = 401,\n NOT_FOUND = 404,\n METHOD_NOT_ALLOWED = 405,\n INTERNAL_ERROR = 500,\n}\n\nexport enum HttpMethod {\n GET = 'GET',\n POST = 'POST',\n PUT = 'PUT',\n DELETE = 'DELETE',\n PATCH = 'PATCH',\n HEAD = 'HEAD',\n OPTIONS = 'OPTIONS',\n}\n","/**\n * <license header>\n */\n\nimport { HttpStatus } from '../types';\nimport { SuccessResponse, ErrorResponse } from './types';\n\nclass RuntimeActionResponse {\n /**\n * Returns a success response object, this method should be called on the handlers actions\n *\n * @param response a descriptive message of the result\n * e.g. 'missing xyz parameter'\n * @param headers optional headers to include in the response\n * @returns the response object, ready to be returned from the action main's function.\n */\n static success(\n response: object | string,\n headers: { [key: string]: string } = {}\n ): SuccessResponse {\n return {\n statusCode: HttpStatus.OK,\n body: response,\n headers: headers,\n };\n }\n\n /**\n * Returns an error response object, this method should be called on the handlers actions\n *\n * @param statusCode the status code.\n * e.g. 400\n * @param error a descriptive message of the result\n * e.g. 'missing xyz parameter'\n * @returns the response object, ready to be returned from the action main's function.\n */\n static error(statusCode: HttpStatus, error: string): ErrorResponse {\n return {\n error: {\n statusCode,\n body: {\n error: error,\n },\n },\n };\n }\n}\n\nexport default RuntimeActionResponse;\n","/**\n * <license header>\n */\n\nclass Validator {\n /**\n * Returns the list of missing keys given an object and its required keys.\n * A parameter is missing if its value is undefined or ''.\n * A value of 0 or null is not considered as missing.\n *\n * @param obj object to check.\n * @param required list of required keys.\n * Each element can be multi-level deep using a '.' separator e.g. 'myRequiredObj.myRequiredKey'\n *\n * @returns array\n * @private\n */\n static getMissingKeys(obj: { [key: string]: any }, required: string[]): string[] {\n return required.filter(r => {\n const splits = r.split('.');\n const last = splits[splits.length - 1];\n const traverse = splits.slice(0, -1).reduce((tObj, split) => tObj[split] || {}, obj);\n return last && (traverse[last] === undefined || traverse[last] === ''); // missing default params are empty string\n });\n }\n\n /**\n * Returns the list of missing keys given an object and its required keys.\n * A parameter is missing if its value is undefined or ''.\n * A value of 0 or null is not considered as missing.\n *\n * @param params action input parameters.\n * @param requiredHeaders list of required input headers.\n * @param requiredParams list of required input parameters.\n * Each element can be multi-level deep using a '.' separator e.g. 'myRequiredObj.myRequiredKey'.\n *\n * @returns string|null if the return value is not null, then it holds an error message describing the missing inputs.\n *\n */\n static checkMissingRequestInputs(\n params: { [key: string]: any },\n requiredParams: string[] = [],\n requiredHeaders: string[] = []\n ): string | null {\n let errorMessage: string | null = null;\n\n // input headers are always lowercase\n requiredHeaders = requiredHeaders.map(h => h.toLowerCase());\n // normalize header keys to lowercase for case-insensitive comparison\n const normalizedHeaders = Object.keys(params.__ow_headers || {}).reduce(\n (acc, key) => {\n acc[key.toLowerCase()] = params.__ow_headers?.[key];\n return acc;\n },\n {} as { [key: string]: any }\n );\n // check for missing headers\n const missingHeaders = Validator.getMissingKeys(normalizedHeaders, requiredHeaders);\n if (missingHeaders.length > 0) {\n errorMessage = `missing header(s) '${missingHeaders.join(', ')}'`;\n }\n\n // check for missing parameters\n const missingParams = Validator.getMissingKeys(params, requiredParams);\n if (missingParams.length > 0) {\n if (errorMessage) {\n errorMessage += ' and ';\n } else {\n errorMessage = '';\n }\n errorMessage += `missing parameter(s) '${missingParams.join(', ')}'`;\n }\n\n return errorMessage;\n }\n}\n\nexport default Validator;\n","/**\n * <license header>\n */\n\nimport { Core } from '@adobe/aio-sdk';\nimport { getLogger, type EntrypointInstrumentationConfig } from '@adobe/aio-lib-telemetry';\n\nimport NewRelicTelemetry from './new-relic';\nimport RuntimeActionResponse from '../runtime-action/response';\nimport { HttpStatus } from '../runtime-action/types';\n\nclass Telemetry {\n /**\n * Create a logger with standard configuration and automatic metadata injection.\n *\n * This method creates a structured logger and wraps it to automatically add\n * contextual metadata to all log calls:\n * - `x-adobe-commerce-request-id`: Extracted from `__ow_headers` (when present)\n * - `action.type`: Extracted from `params.action_type` (when present)\n *\n * If ENABLE_TELEMETRY is true, uses OpenTelemetry logger; otherwise uses Core.Logger.\n * The environment from params.ENVIRONMENT is set at the resource level and will\n * automatically appear in all logs sent to New Relic if ENABLE_TELEMETRY is true.\n *\n * @param name - Logger name (typically action name)\n * @param params - Runtime parameters containing LOG_LEVEL, optional ENABLE_TELEMETRY, ENVIRONMENT, action_type, and __ow_headers\n * @returns Configured logger instance with automatic metadata injection\n *\n * @example Basic string message\n * ```typescript\n * const logger = Telemetry.createLogger(\"my-action\", params);\n * logger.info(\"Processing started\");\n * // Logs: \"Processing started\"\n * ```\n *\n * @example JSON object message with automatic metadata\n * ```typescript\n * const logger = Telemetry.createLogger(\"my-action\", {\n * ...params,\n * action_type: \"webhook\",\n * __ow_headers: { 'x-adobe-commerce-request-id': 'req-123' }\n * });\n * logger.info({\n * message: \"User action completed\",\n * user_id: \"123\"\n * });\n * // In New Relic: {\n * // message: \"User action completed\",\n * // user_id: \"123\",\n * // \"x-adobe-commerce-request-id\": \"req-123\",\n * // \"action.type\": \"webhook\",\n * // environment: \"development\",\n * // ...\n * // }\n * ```\n */\n public static createLogger(name: string, params: Record<string, unknown>): any {\n // Create base logger with or without telemetry\n const baseLogger = !params.ENABLE_TELEMETRY\n ? Core.Logger(name, {\n level: (params.LOG_LEVEL as string) || 'info',\n })\n : getLogger(name, {\n level: (params.LOG_LEVEL as string) || 'info',\n });\n\n // Build metadata object with available context\n const metadata: Record<string, string> = {};\n\n // Extract request ID from headers\n const headers = params.__ow_headers as Record<string, unknown> | undefined;\n const requestId = headers?.['x-adobe-commerce-request-id'];\n if (requestId && requestId !== '') {\n metadata['x-adobe-commerce-request-id'] = requestId as string;\n }\n\n // Extract action type from params\n const actionType = params.action_type;\n if (actionType && actionType !== '') {\n metadata['action.type'] = actionType as string;\n }\n\n // If no metadata to add, return the base logger as-is\n if (Object.keys(metadata).length === 0) {\n return baseLogger;\n }\n\n // Create a wrapper that merges metadata into all log calls\n const wrapper = {\n debug: (message: any): void => {\n if (typeof message === 'object' && message !== null) {\n baseLogger.debug({ ...metadata, ...message });\n } else {\n baseLogger.debug(message);\n }\n },\n info: (message: any): void => {\n if (typeof message === 'object' && message !== null) {\n baseLogger.info({ ...metadata, ...message });\n } else {\n baseLogger.info(message);\n }\n },\n warn: (message: any): void => {\n if (typeof message === 'object' && message !== null) {\n baseLogger.warn({ ...metadata, ...message });\n } else {\n baseLogger.warn(message);\n }\n },\n error: (message: any): void => {\n if (typeof message === 'object' && message !== null) {\n baseLogger.error({ ...metadata, ...message });\n } else {\n baseLogger.error(message);\n }\n },\n };\n\n // Return a logger that includes the wrapper methods plus any other baseLogger methods\n return {\n ...baseLogger,\n ...wrapper,\n };\n }\n\n /**\n * Extract structured error information for logging\n *\n * Converts Error objects into a structured format suitable for logging\n * and telemetry systems like New Relic.\n *\n * @param error - Error object or unknown error value\n * @returns Structured error object with name, message, and stack trace\n *\n * @example\n * ```typescript\n * try {\n * // some operation\n * } catch (error) {\n * logger.error(\"Operation failed\", Telemetry.formatError(error));\n * }\n * ```\n */\n public static formatError(error: unknown): Record<string, unknown> {\n if (error instanceof Error) {\n return {\n error_name: error.name,\n error_message: error.message,\n error_stack: error.stack,\n };\n }\n return { error: String(error) };\n }\n\n /**\n * Initialize telemetry for a runtime action with provider fallback chain\n *\n * Attempts to initialize telemetry providers in the following order:\n * 1. New Relic (if NEW_RELIC_TELEMETRY=true)\n * 2. Grafana (if GRAFANA_TELEMETRY=true) - Future support\n * 3. Original action (no telemetry)\n *\n * Telemetry initialization is deferred to runtime when params are available.\n * This allows proper configuration detection and graceful fallback to the\n * next provider in the chain.\n *\n * **IMPORTANT**: If a provider is explicitly enabled (e.g., NEW_RELIC_TELEMETRY=true)\n * but has invalid configuration (missing API key, service name), a 500 error response\n * is returned to alert you of the misconfiguration. This prevents silently running\n * without telemetry when you expect it to be working.\n *\n * Environment Configuration:\n * Pass params.ENVIRONMENT to set the environment field in all logs.\n * This can be set via environment variables in your action configuration.\n *\n * @param action - The runtime action function to instrument\n * @returns The instrumented action ready for export\n *\n * @example Single provider (New Relic) - Valid configuration\n * ```typescript\n * // Environment:\n * // ENABLE_TELEMETRY=true\n * // NEW_RELIC_TELEMETRY=true\n * // NEW_RELIC_SERVICE_NAME=my-service\n * // NEW_RELIC_LICENSE_KEY=xxxxx\n *\n * export const main = Telemetry.initialize(myAction);\n * // ✅ Uses New Relic telemetry\n * ```\n *\n * @example New Relic enabled but misconfigured - Returns error response\n * ```typescript\n * // Environment:\n * // ENABLE_TELEMETRY=true\n * // NEW_RELIC_TELEMETRY=true\n * // NEW_RELIC_SERVICE_NAME=my-service\n * // Missing NEW_RELIC_LICENSE_KEY!\n *\n * export const main = Telemetry.initialize(myAction);\n * // ❌ Returns { error: { statusCode: 500, body: { error: \"Telemetry configuration error: NEW_RELIC_LICENSE_KEY is required\" } } }\n * // This is intentional - you want to know your telemetry config is broken!\n * ```\n *\n * @example Multi-provider fallback\n * ```typescript\n * // Environment:\n * // ENABLE_TELEMETRY=true\n * // NEW_RELIC_TELEMETRY=false // Skip New Relic\n * // GRAFANA_TELEMETRY=true // Use Grafana instead\n *\n * export const main = Telemetry.initialize(myAction);\n * // ✅ Skips New Relic, tries Grafana (when implemented)\n * ```\n *\n * @example No telemetry\n * ```typescript\n * // Environment:\n * // ENABLE_TELEMETRY=false (or not set)\n *\n * export const main = Telemetry.initialize(myAction);\n * // ✅ Returns original action without instrumentation\n * ```\n */\n public static initialize(\n action: (params: Record<string, unknown>) => any\n ): (params: Record<string, unknown>) => any {\n // Return a wrapper that initializes telemetry at runtime with actual params\n return async (params: Record<string, unknown>) => {\n // Try New Relic telemetry first if configured\n const newRelicTelemetry = new NewRelicTelemetry();\n if (newRelicTelemetry.canInitialize(params)) {\n try {\n // New Relic is explicitly enabled, try to initialize it\n const instrumentedAction = newRelicTelemetry.initialize(action);\n return await instrumentedAction(params);\n } catch (error) {\n // Configuration error: New Relic is enabled but misconfigured\n // Return a proper error response instead of crashing\n const errorMessage =\n error instanceof Error ? error.message : 'Telemetry initialization failed';\n return RuntimeActionResponse.error(\n HttpStatus.INTERNAL_ERROR,\n `Telemetry configuration error: ${errorMessage}`\n );\n }\n }\n\n // TODO: Try Grafana telemetry if configured\n // const grafanaTelemetry = new GrafanaTelemetry();\n // if (grafanaTelemetry.canInitialize(params)) {\n // try {\n // const instrumentedAction = grafanaTelemetry.initialize(action);\n // return await instrumentedAction(params);\n // } catch (error) {\n // const errorMessage = error instanceof Error ? error.message : 'Telemetry initialization failed';\n // return RuntimeActionResponse.error(\n // HttpStatus.INTERNAL_ERROR,\n // `Telemetry configuration error: ${errorMessage}`\n // );\n // }\n // }\n\n // No telemetry configured, run original action without instrumentation\n return action(params);\n };\n }\n}\n\nexport default Telemetry;\n\nexport type { BaseTelemetry } from './types';\nexport type { EntrypointInstrumentationConfig };\n","/**\n * <license header>\n */\n\nimport type { BaseTelemetry } from '../types';\nimport {\n defineTelemetryConfig,\n EntrypointInstrumentationConfig,\n getPresetInstrumentations,\n instrumentEntrypoint,\n} from '@adobe/aio-lib-telemetry';\nimport { NewRelicTelemetryValidator } from './validator';\nimport { ResourceFactory } from '../helpers/resource-factory';\nimport { SuccessChecker } from '../helpers/success-checker';\nimport {\n OTLPLogExporterProto,\n OTLPMetricExporterProto,\n OTLPTraceExporterProto,\n PeriodicExportingMetricReader,\n SimpleLogRecordProcessor,\n // @ts-expect-error - Type definitions may not match runtime implementation\n} from '@adobe/aio-lib-telemetry/otel';\nimport { JsonMessageProcessor } from '../helpers/json-message-processor';\n\n/**\n * New Relic telemetry implementation for Adobe I/O Runtime actions\n *\n * Provides OpenTelemetry instrumentation configured specifically for New Relic.\n * Handles configuration of OTLP exporters for traces, metrics, and logs,\n * and wraps runtime actions with telemetry instrumentation.\n *\n * Features:\n * - Automatic trace collection for action executions\n * - Metric export via OTLP protocol\n * - Structured log forwarding with JSON attribute extraction\n * - Custom resource attributes (environment, service name)\n * - Action success/failure detection\n *\n * Required Environment Variables:\n * - ENABLE_TELEMETRY: Set to true to enable telemetry\n * - NEW_RELIC_TELEMETRY: Must be set to true to enable New Relic specific telemetry\n * - NEW_RELIC_SERVICE_NAME: Name of your service/action\n * - NEW_RELIC_LICENSE_KEY: Your New Relic license key\n * - NEW_RELIC_URL (optional): Custom New Relic OTLP endpoint (defaults to https://otlp.nr-data.net)\n * - ENVIRONMENT (optional): Environment name (dev, stage, prod) for filtering\n *\n * @implements {BaseTelemetry}\n *\n * @example Basic usage\n * ```typescript\n * import { Telemetry } from '@adobe-commerce/aio-toolkit';\n *\n * async function myAction(params) {\n * const logger = Telemetry.createLogger(\"my-action\", params);\n * logger.info(\"Action started\");\n *\n * return { statusCode: 200, body: { message: \"Success\" } };\n * }\n *\n * // Wrap action with telemetry\n * export const main = Telemetry.initialize(myAction);\n * ```\n *\n * @example Environment configuration\n * ```typescript\n * // In your .env or action configuration:\n * // ENABLE_TELEMETRY=true\n * // NEW_RELIC_TELEMETRY=true\n * // NEW_RELIC_SERVICE_NAME=my-commerce-action\n * // NEW_RELIC_LICENSE_KEY=your-license-key\n * // ENVIRONMENT=production\n *\n * // All telemetry will be tagged with environment=\"production\"\n * ```\n *\n * @example Multi-provider fallback (New Relic → Grafana → None)\n * ```typescript\n * // If NEW_RELIC_TELEMETRY is not true, the system will try\n * // the next telemetry provider (e.g., Grafana) automatically\n * // ENABLE_TELEMETRY=true\n * // GRAFANA_TELEMETRY=true // Falls back to Grafana if New Relic not configured\n * ```\n */\nclass NewRelicTelemetry implements BaseTelemetry {\n /**\n * Validator for New Relic telemetry configuration\n *\n * @private\n * @type {NewRelicTelemetryValidator}\n * @readonly\n * @memberof NewRelicTelemetry\n * @description Validator for New Relic telemetry configuration\n * @example\n * ```typescript\n * const validator = new NewRelicTelemetryValidator();\n * if (validator.isConfigured(params)) {\n * validator.validateConfiguration(params);\n * }\n * ```\n */\n private readonly validator: NewRelicTelemetryValidator;\n\n /**\n * Success checker for action execution results\n *\n * @private\n * @type {SuccessChecker}\n * @readonly\n * @memberof NewRelicTelemetry\n * @description Utility to determine if an action execution was successful\n */\n private readonly successChecker: SuccessChecker;\n\n /**\n * Resource factory for creating OpenTelemetry resources\n *\n * @private\n * @type {ResourceFactory}\n * @readonly\n * @memberof NewRelicTelemetry\n * @description Factory for creating resources with custom attributes\n */\n private readonly resourceFactory: ResourceFactory;\n\n /**\n * Constructor for New Relic telemetry\n *\n * @description Constructor for New Relic telemetry\n * @example\n * ```typescript\n * const telemetry = new NewRelicTelemetry();\n * ```\n */\n constructor() {\n this.validator = new NewRelicTelemetryValidator();\n this.successChecker = new SuccessChecker();\n this.resourceFactory = new ResourceFactory();\n }\n\n /**\n * Checks if New Relic telemetry can be initialized\n *\n * Determines if New Relic telemetry is properly configured without actually\n * attempting initialization. Useful for provider chain fallback logic.\n *\n * @param params - Runtime parameters to check\n * @returns true if New Relic is configured and can be initialized\n *\n * @example\n * ```typescript\n * const telemetry = new NewRelicTelemetry();\n * if (telemetry.canInitialize(params)) {\n * // New Relic is configured, use it\n * } else {\n * // Try next provider\n * }\n * ```\n */\n public canInitialize(params: Record<string, unknown>): boolean {\n return this.validator.isConfigured(params);\n }\n /**\n * Get the OpenTelemetry instrumentation configuration for New Relic\n *\n * Builds and returns the complete instrumentation configuration including:\n * - Service name and preset instrumentations\n * - Custom resource attributes (environment)\n * - OTLP exporters for traces, metrics, and logs\n * - Success/failure detection for actions\n *\n * This method is called internally by `instrumentEntrypoint` to configure\n * telemetry before wrapping the action.\n *\n * @returns Complete entrypoint instrumentation configuration\n * @throws {TelemetryInputError} If required parameters are missing (service name, license key)\n *\n * @example\n * ```typescript\n * const telemetry = new NewRelicTelemetry();\n * const config = telemetry.getConfig();\n * // Returns configuration with exporters, instrumentations, and resource attributes\n * ```\n */\n public getConfig(): EntrypointInstrumentationConfig {\n return {\n ...defineTelemetryConfig((params: Record<string, unknown>) => {\n // Check if New Relic telemetry is configured\n if (!this.validator.isConfigured(params)) {\n throw new Error('New Relic telemetry is not configured');\n }\n\n // Validate required parameters\n this.validator.validateConfiguration(params);\n\n const serviceName = params.NEW_RELIC_SERVICE_NAME as string;\n\n return {\n sdkConfig: {\n serviceName: serviceName,\n instrumentations: getPresetInstrumentations('simple'),\n resource: this.resourceFactory.createWithEnvironment(params),\n ...this.getExportersConfig(params),\n },\n };\n }),\n isSuccessful: this.successChecker.execute.bind(this.successChecker),\n };\n }\n\n /**\n * Configure New Relic exporters for traces, metrics, and logs\n *\n * Creates OTLP exporters for all three signal types (traces, metrics, logs)\n * and configures them to send data to New Relic. Log processors are wrapped\n * with JsonMessageProcessor for better attribute extraction.\n *\n * @param params - Runtime parameters containing NEW_RELIC_LICENSE_KEY and optional NEW_RELIC_URL\n * @returns Configuration object with traceExporter, metricReaders, and logRecordProcessors\n * @private\n */\n private getExportersConfig(params: Record<string, unknown>): {\n traceExporter: any;\n metricReaders: any[];\n logRecordProcessors: JsonMessageProcessor[];\n } {\n const licenseKey = params.NEW_RELIC_LICENSE_KEY as string;\n const newRelicUrl = (params.NEW_RELIC_URL as string) || 'https://otlp.nr-data.net';\n\n /**\n * Factory function to create OTLP exporter configuration\n * @param endpoint - New Relic endpoint path (e.g., \"v1/logs\", \"v1/traces\")\n */\n const makeExporterConfig = (\n endpoint: string\n ): { url: string; headers: { 'api-key': string } } => {\n return {\n url: `${newRelicUrl}/${endpoint}`,\n headers: {\n 'api-key': licenseKey,\n },\n };\n };\n\n return {\n traceExporter: new OTLPTraceExporterProto(makeExporterConfig('v1/traces')),\n metricReaders: [\n new PeriodicExportingMetricReader({\n exporter: new OTLPMetricExporterProto(makeExporterConfig('v1/metrics')),\n }),\n ],\n logRecordProcessors: [\n new JsonMessageProcessor(\n new SimpleLogRecordProcessor(new OTLPLogExporterProto(makeExporterConfig('v1/logs')))\n ),\n ],\n };\n }\n\n /**\n * Initialize telemetry instrumentation for a runtime action\n *\n * Wraps the provided action with OpenTelemetry instrumentation using\n * New Relic as the backend. The instrumented action will automatically:\n * - Create spans for the action execution\n * - Export metrics during runtime\n * - Forward logs to New Relic\n * - Track success/failure status\n *\n * This method delegates to `instrumentEntrypoint` from `@adobe/aio-lib-telemetry`,\n * passing the action and New Relic specific configuration.\n *\n * @param action - The runtime action function to instrument\n * @returns The instrumented action function with telemetry enabled\n * @throws {TelemetryInputError} If required configuration is missing\n *\n * @example\n * ```typescript\n * async function myAction(params: Record<string, unknown>) {\n * const logger = Telemetry.createLogger(\"my-action\", params);\n * logger.info(\"Processing request\");\n *\n * return { statusCode: 200, body: { success: true } };\n * }\n *\n * const telemetry = new NewRelicTelemetry();\n * const instrumentedAction = telemetry.initialize(myAction);\n *\n * // instrumentedAction now sends traces, metrics, and logs to New Relic\n * export const main = instrumentedAction;\n * ```\n */\n public initialize(\n action: (params: Record<string, unknown>) => any\n ): (params: Record<string, unknown>) => any {\n return instrumentEntrypoint(action, this.getConfig());\n }\n}\n\nexport default NewRelicTelemetry;\n","/*\n * <license header>\n */\n\n/**\n * Error thrown when input validation fails\n *\n * This error indicates that provided input does not meet validation requirements.\n * Common scenarios include:\n * - Missing required parameters\n * - Invalid parameter format\n * - Parameter value out of acceptable range\n * - Type mismatch\n *\n * @example\n * ```typescript\n * if (!params.SERVICE_NAME) {\n * throw new TelemetryInputError('SERVICE_NAME is required');\n * }\n *\n * if (typeof params.PORT !== 'number') {\n * throw new TelemetryInputError('PORT must be a number');\n * }\n * ```\n */\nexport class TelemetryInputError extends Error {\n /**\n * Creates a new TelemetryInputError\n *\n * @param message - Descriptive error message explaining the validation failure\n */\n constructor(message: string) {\n super(message);\n this.name = 'TelemetryInputError';\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, TelemetryInputError);\n }\n }\n}\n","/*\n * <license header>\n */\n\nimport { TelemetryInputError } from '../../helpers/input-error';\nimport type { BaseTelemetryValidator } from '../../types';\n\n/**\n * Validator for New Relic telemetry configuration\n *\n * Implements BaseTelemetryValidator interface to provide validation\n * for New Relic telemetry provider. Supports multi-provider telemetry\n * architecture by separating configuration detection from validation.\n *\n * @example\n * ```typescript\n * const validator = new NewRelicTelemetryValidator();\n * if (validator.isConfigured(params)) {\n * validator.validateConfiguration(params);\n * // Proceed with New Relic initialization\n * } else {\n * // Try next telemetry provider (e.g., Grafana)\n * }\n * ```\n */\nexport class NewRelicTelemetryValidator implements BaseTelemetryValidator {\n /**\n * Checks if New Relic telemetry is configured\n *\n * Returns true if:\n * - ENABLE_TELEMETRY is explicitly set to true\n * - NEW_RELIC_TELEMETRY is explicitly set to true\n *\n * This method does NOT validate the completeness of configuration,\n * it only checks if the provider is enabled.\n *\n * @param params - Runtime parameters to check\n * @returns true if New Relic telemetry is enabled, false otherwise\n *\n * @example\n * ```typescript\n * const validator = new NewRelicTelemetryValidator();\n * const params = { ENABLE_TELEMETRY: true, NEW_RELIC_TELEMETRY: true };\n * if (validator.isConfigured(params)) {\n * // New Relic is enabled, proceed with initialization\n * }\n * ```\n */\n public isConfigured(params: Record<string, unknown>): boolean {\n return params.ENABLE_TELEMETRY === true && params.NEW_RELIC_TELEMETRY === true;\n }\n\n /**\n * Validates New Relic specific parameters\n *\n * IMPORTANT: Only call this method after checking isConfigured() returns true.\n * This method assumes New Relic telemetry is enabled and validates that\n * all required parameters are present.\n *\n * Required parameters when New Relic is enabled:\n * - NEW_RELIC_SERVICE_NAME must be provided\n * - NEW_RELIC_LICENSE_KEY must be provided\n *\n * @param params - Runtime parameters to validate\n * @throws {TelemetryInputError} If NEW_RELIC_SERVICE_NAME is missing\n * @throws {TelemetryInputError} If NEW_RELIC_LICENSE_KEY is missing\n *\n * @example\n * ```typescript\n * const validator = new NewRelicTelemetryValidator();\n * const params = {\n * ENABLE_TELEMETRY: true,\n * NEW_RELIC_TELEMETRY: true,\n * NEW_RELIC_SERVICE_NAME: \"my-service\",\n * NEW_RELIC_LICENSE_KEY: \"license-key\"\n * };\n *\n * if (validator.isConfigured(params)) {\n * validator.validateConfiguration(params); // Validates required fields\n * }\n * ```\n */\n public validateConfiguration(params: Record<string, unknown>): void {\n if (\n params.NEW_RELIC_SERVICE_NAME === undefined ||\n params.NEW_RELIC_SERVICE_NAME === null ||\n params.NEW_RELIC_SERVICE_NAME === ''\n ) {\n throw new TelemetryInputError('NEW_RELIC_SERVICE_NAME is required');\n }\n\n if (\n params.NEW_RELIC_LICENSE_KEY === undefined ||\n params.NEW_RELIC_LICENSE_KEY === null ||\n params.NEW_RELIC_LICENSE_KEY === ''\n ) {\n throw new TelemetryInputError('NEW_RELIC_LICENSE_KEY is required');\n }\n }\n}\n","/*\n * <license header>\n */\n\nimport { getAioRuntimeResource } from '@adobe/aio-lib-telemetry';\nimport { Resource, resourceFromAttributes } from '@opentelemetry/resources';\n\n/**\n * Factory for creating OpenTelemetry resources with custom attributes\n *\n * Resources represent the entity producing telemetry data. This factory\n * creates resources based on Adobe I/O Runtime environment and enriches\n * them with custom attributes like environment name and request ID.\n *\n * Resources are attached to all telemetry signals (logs, traces, metrics)\n * and appear as filterable attributes in observability platforms.\n *\n * @example\n * ```typescript\n * const factory = new ResourceFactory();\n * const params = {\n * ENVIRONMENT: \"production\"\n * };\n * const resource = factory.createWithEnvironment(params);\n *\n * // This resource will include:\n * // - All Adobe I/O Runtime attributes (service.name, etc.)\n * // - environment: \"production\"\n * ```\n */\nexport class ResourceFactory {\n /**\n * Creates a resource with custom environment attributes\n *\n * Starts with the base Adobe I/O Runtime resource and optionally\n * merges environment attributes. These attributes are useful for\n * filtering and correlating telemetry data by deployment environment.\n *\n * Note: Request-specific data (like request IDs) should NOT be added to\n * Resources as they are created once and reused across all requests.\n * Use log attributes or span attributes for request-specific data.\n *\n * @param params - Runtime parameters containing optional ENVIRONMENT\n * @param params.ENVIRONMENT - Environment name (e.g., \"dev\", \"stage\", \"prod\")\n * @returns OpenTelemetry Resource with custom attributes if provided\n *\n * @example Without custom attributes\n * ```typescript\n * const factory = new ResourceFactory();\n * const resource = factory.createWithEnvironment({});\n * // Returns base Adobe I/O Runtime resource\n * ```\n *\n * @example With environment\n * ```typescript\n * const factory = new ResourceFactory();\n * const params = { ENVIRONMENT: \"production\" };\n * const resource = factory.createWithEnvironment(params);\n * // Returns resource with environment=\"production\" attribute\n * ```\n */\n public createWithEnvironment(params: Record<string, unknown>): Resource {\n const baseResource = getAioRuntimeResource();\n\n // Collect custom attributes\n const customAttributes: Record<string, unknown> = {};\n\n // Extract environment if provided\n if (params.ENVIRONMENT) {\n customAttributes.environment = params.ENVIRONMENT as string;\n }\n\n // If no custom attributes, return base resource as-is\n if (Object.keys(customAttributes).length === 0) {\n return baseResource;\n }\n\n // Create a new Resource with custom attributes and merge it\n const customResource = resourceFromAttributes(\n customAttributes as Record<string, string | number | boolean>\n );\n\n return baseResource.merge(customResource);\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Attributes, AttributeValue, diag } from '@opentelemetry/api';\nimport { SDK_INFO } from '@opentelemetry/core';\nimport {\n ATTR_SERVICE_NAME,\n ATTR_TELEMETRY_SDK_LANGUAGE,\n ATTR_TELEMETRY_SDK_NAME,\n ATTR_TELEMETRY_SDK_VERSION,\n} from '@opentelemetry/semantic-conventions';\nimport { Resource } from './Resource';\nimport { defaultServiceName } from './platform';\nimport {\n DetectedResource,\n DetectedResourceAttributes,\n MaybePromise,\n RawResourceAttribute,\n ResourceOptions,\n} from './types';\nimport { isPromiseLike } from './utils';\n\nclass ResourceImpl implements Resource {\n private _rawAttributes: RawResourceAttribute[];\n private _asyncAttributesPending = false;\n private _schemaUrl?: string;\n\n private _memoizedAttributes?: Attributes;\n\n static FromAttributeList(\n attributes: [string, MaybePromise<AttributeValue | undefined>][],\n options?: ResourceOptions\n ): Resource {\n const res = new ResourceImpl({}, options);\n res._rawAttributes = guardedRawAttributes(attributes);\n res._asyncAttributesPending =\n attributes.filter(([_, val]) => isPromiseLike(val)).length > 0;\n return res;\n }\n\n constructor(\n /**\n * A dictionary of attributes with string keys and values that provide\n * information about the entity as numbers, strings or booleans\n * TODO: Consider to add check/validation on attributes.\n */\n resource: DetectedResource,\n options?: ResourceOptions\n ) {\n const attributes = resource.attributes ?? {};\n this._rawAttributes = Object.entries(attributes).map(([k, v]) => {\n if (isPromiseLike(v)) {\n // side-effect\n this._asyncAttributesPending = true;\n }\n\n return [k, v];\n });\n\n this._rawAttributes = guardedRawAttributes(this._rawAttributes);\n this._schemaUrl = validateSchemaUrl(options?.schemaUrl);\n }\n\n public get asyncAttributesPending(): boolean {\n return this._asyncAttributesPending;\n }\n\n public async waitForAsyncAttributes(): Promise<void> {\n if (!this.asyncAttributesPending) {\n return;\n }\n\n for (let i = 0; i < this._rawAttributes.length; i++) {\n const [k, v] = this._rawAttributes[i];\n this._rawAttributes[i] = [k, isPromiseLike(v) ? await v : v];\n }\n\n this._asyncAttributesPending = false;\n }\n\n public get attributes(): Attributes {\n if (this.asyncAttributesPending) {\n diag.error(\n 'Accessing resource attributes before async attributes settled'\n );\n }\n\n if (this._memoizedAttributes) {\n return this._memoizedAttributes;\n }\n\n const attrs: Attributes = {};\n for (const [k, v] of this._rawAttributes) {\n if (isPromiseLike(v)) {\n diag.debug(`Unsettled resource attribute ${k} skipped`);\n continue;\n }\n if (v != null) {\n attrs[k] ??= v;\n }\n }\n\n // only memoize output if all attributes are settled\n if (!this._asyncAttributesPending) {\n this._memoizedAttributes = attrs;\n }\n\n return attrs;\n }\n\n public getRawAttributes(): RawResourceAttribute[] {\n return this._rawAttributes;\n }\n\n public get schemaUrl(): string | undefined {\n return this._schemaUrl;\n }\n\n public merge(resource: Resource | null): Resource {\n if (resource == null) return this;\n\n // Order is important\n // Spec states incoming attributes override existing attributes\n const mergedSchemaUrl = mergeSchemaUrl(this, resource);\n const mergedOptions: ResourceOptions | undefined = mergedSchemaUrl\n ? { schemaUrl: mergedSchemaUrl }\n : undefined;\n\n return ResourceImpl.FromAttributeList(\n [...resource.getRawAttributes(), ...this.getRawAttributes()],\n mergedOptions\n );\n }\n}\n\nexport function resourceFromAttributes(\n attributes: DetectedResourceAttributes,\n options?: ResourceOptions\n): Resource {\n return ResourceImpl.FromAttributeList(Object.entries(attributes), options);\n}\n\nexport function resourceFromDetectedResource(\n detectedResource: DetectedResource,\n options?: ResourceOptions\n): Resource {\n return new ResourceImpl(detectedResource, options);\n}\n\nexport function emptyResource(): Resource {\n return resourceFromAttributes({});\n}\n\nexport function defaultResource(): Resource {\n return resourceFromAttributes({\n [ATTR_SERVICE_NAME]: defaultServiceName(),\n [ATTR_TELEMETRY_SDK_LANGUAGE]: SDK_INFO[ATTR_TELEMETRY_SDK_LANGUAGE],\n [ATTR_TELEMETRY_SDK_NAME]: SDK_INFO[ATTR_TELEMETRY_SDK_NAME],\n [ATTR_TELEMETRY_SDK_VERSION]: SDK_INFO[ATTR_TELEMETRY_SDK_VERSION],\n });\n}\n\nfunction guardedRawAttributes(\n attributes: RawResourceAttribute[]\n): RawResourceAttribute[] {\n return attributes.map(([k, v]) => {\n if (isPromiseLike(v)) {\n return [\n k,\n v.catch(err => {\n diag.debug(\n 'promise rejection for resource attribute: %s - %s',\n k,\n err\n );\n return undefined;\n }),\n ];\n }\n return [k, v];\n });\n}\n\nfunction validateSchemaUrl(schemaUrl?: string): string | undefined {\n if (typeof schemaUrl === 'string' || schemaUrl === undefined) {\n return schemaUrl;\n }\n\n diag.warn(\n 'Schema URL must be string or undefined, got %s. Schema URL will be ignored.',\n schemaUrl\n );\n\n return undefined;\n}\n\nfunction mergeSchemaUrl(\n old: Resource,\n updating: Resource | null\n): string | undefined {\n const oldSchemaUrl = old?.schemaUrl;\n const updatingSchemaUrl = updating?.schemaUrl;\n\n const isOldEmpty = oldSchemaUrl === undefined || oldSchemaUrl === '';\n const isUpdatingEmpty =\n updatingSchemaUrl === undefined || updatingSchemaUrl === '';\n\n if (isOldEmpty) {\n return updatingSchemaUrl;\n }\n\n if (isUpdatingEmpty) {\n return oldSchemaUrl;\n }\n\n if (oldSchemaUrl === updatingSchemaUrl) {\n return oldSchemaUrl;\n }\n\n diag.warn(\n 'Schema URL merge conflict: old resource has \"%s\", updating resource has \"%s\". Resulting resource will have undefined Schema URL.',\n oldSchemaUrl,\n updatingSchemaUrl\n );\n\n return undefined;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const isPromiseLike = <R>(val: unknown): val is PromiseLike<R> => {\n return (\n val !== null &&\n typeof val === 'object' &&\n typeof (val as Partial<PromiseLike<R>>).then === 'function'\n );\n};\n\nexport function identity<T>(_: T): T {\n return _;\n}\n","/*\n * <license header>\n */\n\nimport type { ActionResult } from './types';\n\n/**\n * Utility class to determine if an action execution was successful\n *\n * This class provides methods to validate action execution results\n * based on HTTP status codes and response body content.\n *\n * @example\n * ```typescript\n * const checker = new SuccessChecker();\n * const result = await executeAction(params);\n * if (checker.execute(result)) {\n * console.log('Action executed successfully');\n * } else {\n * console.error('Action execution failed');\n * }\n * ```\n */\nexport class SuccessChecker {\n /**\n * Determines if an action execution was successful\n *\n * Success criteria:\n * - Response has statusCode 200\n * - Body does not contain an exception operation\n *\n * @param result - The action execution result\n * @returns true if successful, false otherwise\n *\n * @example Success case\n * ```typescript\n * const checker = new SuccessChecker();\n * const result = { statusCode: 200, body: { data: 'success' } };\n * checker.execute(result); // true\n * ```\n *\n * @example Failure case - wrong status code\n * ```typescript\n * const checker = new SuccessChecker();\n * const result = { statusCode: 500, body: { error: 'Internal error' } };\n * checker.execute(result); // false\n * ```\n *\n * @example Failure case - exception in body\n * ```typescript\n * const checker = new SuccessChecker();\n * const result = { statusCode: 200, body: { op: 'exception', message: 'Error' } };\n * checker.execute(result); // false\n * ```\n */\n public execute(result: unknown): boolean {\n if (!result || typeof result !== 'object') {\n return false;\n }\n\n const actionResult = result as ActionResult;\n\n if (actionResult.statusCode !== 200) {\n return false;\n }\n\n // Check if body contains an error operation\n if (actionResult.body && typeof actionResult.body === 'object') {\n return actionResult.body.op !== 'exception';\n }\n\n return true;\n }\n}\n","/*\n * <license header>\n */\n\nimport type { LogRecordProcessor } from '@opentelemetry/sdk-logs';\n// @ts-expect-error - Type definitions may not match runtime implementation\nimport type { SdkLogRecord } from '@adobe/aio-lib-telemetry/otel';\n\n/**\n * Custom log record processor that parses JSON messages and merges\n * them into log attributes for better querying in observability platforms\n *\n * This processor implements the decorator pattern, wrapping another processor\n * and enhancing log records before passing them through. It intelligently\n * parses structured log messages (JSON, Winston format) and extracts their\n * properties as individual log attributes.\n *\n * Features:\n * - Extracts log level from severity (debug, info, warn, error, etc.)\n * - Parses JSON strings in log messages\n * - Handles Winston's JavaScript object notation (util.inspect format)\n * - Flattens nested objects into dot-notation keys for searchability\n * - Graceful error handling (silent failures, no partial extraction)\n * - Preserves message body while extracting attributes\n *\n * Parsing Strategy:\n * 1. Try standard JSON.parse() for proper JSON format\n * 2. Convert JavaScript object notation to JSON and parse\n * 3. If both fail, leave message unchanged (prevents data loss)\n *\n * @implements {LogRecordProcessor}\n *\n * @example Basic Usage\n * ```typescript\n * const baseProcessor = new SimpleLogRecordProcessor(\n * new OTLPLogExporterProto(config)\n * );\n * const processor = new JsonMessageProcessor(baseProcessor);\n *\n * // Use in telemetry configuration\n * const config = {\n * logRecordProcessors: [processor]\n * };\n * ```\n *\n * @example Log Transformation - Simple Object\n * ```typescript\n * // Input log:\n * logger.info({ message: \"User login\", userId: \"123\", success: true });\n *\n * // Processed output in New Relic:\n * // level: \"info\" (extracted from severity)\n * // message: \"User login\"\n * // userId: \"123\"\n * // success: true\n * // (all as separate, queryable attributes)\n * ```\n *\n * @example Log Transformation - Nested Objects (Flattened)\n * ```typescript\n * // Input log:\n * logger.debug({\n * message: \"ACTION_HEADERS\",\n * headers: {\n * accept: \"star/star\",\n * encoding: \"gzip\",\n * authorization: \"Bearer token\"\n * }\n * });\n *\n * // Processed output in New Relic (flattened with dot-notation):\n * // level: \"debug\"\n * // message: \"ACTION_HEADERS\"\n * // headers.accept: \"star/star\"\n * // headers.encoding: \"gzip\"\n * // headers.authorization: \"Bearer token\"\n * // (nested objects are flattened for better searchability)\n * ```\n */\nexport class JsonMessageProcessor implements LogRecordProcessor {\n /**\n * The wrapped log processor that receives the enhanced log records\n * @private\n */\n private readonly wrappedProcessor: LogRecordProcessor;\n\n /**\n * Creates a new JsonMessageProcessor\n *\n * @param wrappedProcessor - The log processor to wrap and enhance\n *\n * @example\n * ```typescript\n * const exporter = new OTLPLogExporterProto({\n * url: \"https://otlp.nr-data.net/v1/logs\",\n * headers: { \"api-key\": licenseKey }\n * });\n * const baseProcessor = new SimpleLogRecordProcessor(exporter);\n * const processor = new JsonMessageProcessor(baseProcessor);\n * ```\n */\n constructor(wrappedProcessor: LogRecordProcessor) {\n this.wrappedProcessor = wrappedProcessor;\n }\n\n /**\n * Parse JavaScript object notation and convert to proper object\n *\n * Handles Winston's util.inspect format which produces JavaScript\n * object literals instead of JSON strings.\n *\n * Examples:\n * - { key: 'value' } → {\"key\":\"value\"}\n * - { 'accept-encoding': 'gzip' } → {\"accept-encoding\":\"gzip\"}\n *\n * @param str - JavaScript object notation string\n * @returns Parsed object\n * @throws Error if parsing fails\n * @private\n */\n private parseJavaScriptObjectNotation(str: string): any {\n // Use Function constructor to safely evaluate JavaScript object literals\n // This is safer than eval() because we control the execution context\n // and it properly handles complex values with special characters\n //\n // The Function constructor can parse:\n // - { key: 'value' }\n // - { 'accept-encoding': 'gzip, deflate' }\n // - { authorization: 'Bearer eyJ...' }\n // - Nested objects and arrays\n //\n // Wrap in parentheses to ensure it's treated as an expression\n const func = new Function('return (' + str + ')');\n return func();\n }\n\n /**\n * Flatten nested objects into dot-notation keys\n *\n * Converts nested structures like:\n * { headers: { accept: '*' } }\n *\n * Into flat structure:\n * { 'headers.accept': '*' }\n *\n * This makes all attributes searchable in observability platforms.\n *\n * @param obj - Object to flatten\n * @param prefix - Current key prefix (used in recursion)\n * @returns Flattened object with dot-notation keys\n * @private\n */\n private flattenObject(obj: any, prefix: string = ''): Record<string, any> {\n const flattened: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value === null || value === undefined) {\n flattened[newKey] = value;\n } else if (Array.isArray(value)) {\n // Stringify arrays as they can't be flattened meaningfully\n flattened[newKey] = JSON.stringify(value);\n } else if (typeof value === 'object') {\n // Check if object is empty\n if (Object.keys(value).length === 0) {\n // Skip empty objects - they don't add any value as attributes\n continue;\n }\n // Recursively flatten nested objects\n const nested = this.flattenObject(value, newKey);\n Object.assign(flattened, nested);\n } else {\n // Primitive values (string, number, boolean)\n flattened[newKey] = value;\n }\n }\n\n return flattened;\n }\n\n /**\n * Processes a log record by parsing JSON messages and extracting attributes\n *\n * This method intercepts log records, attempts to parse structured data\n * from the message body, and merges extracted properties as attributes.\n * Additionally, it extracts the log level from the severity information\n * and adds it as a 'level' attribute for easier querying.\n *\n * The enhanced log record is then passed to the wrapped processor.\n *\n * @param logRecord - The log record to process\n *\n * @remarks\n * Processing steps:\n * 1. Extract log level from severityText or severityNumber\n * 2. Add 'level' attribute (debug, info, warn, error, etc.)\n * 3. Parse JSON bodies that start with '{'\n * 4. Extract properties as individual attributes\n * 5. Preserve 'message' field as primary log body\n *\n * Error handling:\n * - Silently handles parsing errors to avoid breaking the logging pipeline\n * - Failed parsing results in unmodified log record\n */\n onEmit(logRecord: SdkLogRecord): void {\n try {\n // Add log level as an attribute\n if (logRecord.severityText) {\n logRecord.setAttribute('level', logRecord.severityText.toLowerCase());\n } else if (logRecord.severityNumber !== undefined) {\n // Map severity number to level name if severityText is not available\n const levelName = this.mapSeverityNumberToLevel(logRecord.severityNumber);\n if (levelName) {\n logRecord.setAttribute('level', levelName);\n }\n }\n\n const body = logRecord.body;\n\n // Check if body is a string that might contain structured data\n if (typeof body === 'string' && body.trim().startsWith('{')) {\n let parsed: any = null;\n\n // Strategy 1: Try standard JSON.parse() for proper JSON\n try {\n parsed = JSON.parse(body);\n } catch {\n // Strategy 2: Convert JavaScript object notation to valid JSON\n // Winston's util.inspect produces: { key: 'value' } instead of {\"key\":\"value\"}\n try {\n parsed = this.parseJavaScriptObjectNotation(body);\n } catch {\n // If both parsing strategies fail, leave body as-is\n // This prevents partial/incorrect data extraction\n }\n }\n\n // If we successfully parsed the message, extract its properties\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n // Extract message field first (will be used as body)\n const messageValue = parsed.message;\n\n // Remove message from parsed object to avoid duplication\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { message, ...attributesObj } = parsed;\n\n // Flatten nested objects into dot-notation keys\n const flattenedAttributes = this.flattenObject(attributesObj);\n\n // Set flattened attributes on the log record\n Object.entries(flattenedAttributes).forEach(([key, value]) => {\n if (value !== undefined && value !== null) {\n logRecord.setAttribute(key, value as any);\n }\n });\n\n // If there's a 'message' field in the parsed object, use it as the body\n if (messageValue) {\n logRecord.body = messageValue;\n }\n }\n }\n } catch {\n // If any error occurs during processing, silently continue\n // to avoid breaking the logging pipeline\n }\n\n // Pass the modified log record to the wrapped processor\n this.wrappedProcessor.onEmit(logRecord);\n }\n\n /**\n * Maps OpenTelemetry severity number to log level name\n *\n * OpenTelemetry defines severity numbers from 1-24:\n * - 1-4: TRACE\n * - 5-8: DEBUG\n * - 9-12: INFO\n * - 13-16: WARN\n * - 17-20: ERROR\n * - 21-24: FATAL\n *\n * @param severityNumber - OpenTelemetry severity number\n * @returns Log level name (trace, debug, info, warn, error, fatal) or null\n * @private\n */\n private mapSeverityNumberToLevel(severityNumber: number): string | null {\n if (severityNumber >= 1 && severityNumber <= 4) return 'trace';\n if (severityNumber >= 5 && severityNumber <= 8) return 'debug';\n if (severityNumber >= 9 && severityNumber <= 12) return 'info';\n if (severityNumber >= 13 && severityNumber <= 16) return 'warn';\n if (severityNumber >= 17 && severityNumber <= 20) return 'error';\n if (severityNumber >= 21 && severityNumber <= 24) return 'fatal';\n return null;\n }\n\n /**\n * Forces the processor to flush any pending log records\n *\n * Delegates to the wrapped processor's forceFlush method.\n * Useful for ensuring logs are sent before application shutdown.\n *\n * @returns Promise that resolves when flush is complete\n *\n * @example\n * ```typescript\n * await processor.forceFlush();\n * console.log(\"All logs have been sent\");\n * ```\n */\n async forceFlush(): Promise<void> {\n return this.wrappedProcessor.forceFlush();\n }\n\n /**\n * Shuts down the processor and releases resources\n *\n * Delegates to the wrapped processor's shutdown method.\n * Should be called when the application is terminating.\n *\n * @returns Promise that resolves when shutdown is complete\n *\n * @example\n * ```typescript\n * await processor.shutdown();\n * console.log(\"Processor has been shut down\");\n * ```\n */\n async shutdown(): Promise<void> {\n return this.wrappedProcessor.shutdown();\n }\n}\n","/**\n * <license header>\n */\n\nimport RuntimeActionResponse from './response';\nimport Validator from './validator';\n\nimport { HttpStatus, HttpMethod } from './types';\nimport { RuntimeActionResponseType } from './response/types';\nimport Telemetry from '../telemetry';\n\n/**\n * RuntimeAction provides a standardized wrapper for Adobe I/O Runtime actions\n *\n * This class wraps user-defined actions with common runtime functionality including:\n * - Structured logging with telemetry integration\n * - Request validation (parameters, headers, HTTP methods)\n * - Error handling with appropriate HTTP status codes\n * - OpenTelemetry instrumentation for observability\n *\n * @example Basic Usage\n * ```typescript\n * const handler = RuntimeAction.execute(\n * 'myAction',\n * [HttpMethod.GET, HttpMethod.POST],\n * ['userId'],\n * ['authorization'],\n * async (params, { logger, headers }) => {\n * logger.info('Processing request');\n * return { statusCode: 200, body: { success: true } };\n * }\n * );\n *\n * export const main = handler;\n * ```\n */\nclass RuntimeAction {\n /**\n * Private static property to store the action type for logging\n * Can be set using setActionType() before calling execute()\n */\n private static actionType: string = 'runtime-action';\n\n /**\n * Sets the action type for the next action execution\n * This is used for logging to identify different action types\n * (runtime-action, webhook-action, event-consumer-action, etc.)\n *\n * @param type - The action type identifier\n */\n public static setActionType(type: string): void {\n RuntimeAction.actionType = type;\n }\n\n /**\n * Gets the current action type\n * @returns The current action type identifier\n */\n public static getActionType(): string {\n return RuntimeAction.actionType;\n }\n\n /**\n * Creates a runtime action handler with validation, logging, and telemetry\n *\n * Wraps a user-defined action function with standardized runtime functionality:\n * 1. Creates a structured logger with telemetry integration\n * 2. Logs action start, headers, and body at debug level\n * 3. Validates required parameters, headers, and HTTP methods\n * 4. Executes the user action with logger and headers context\n * 5. Logs the result and handles errors with appropriate status codes\n * 6. Integrates with OpenTelemetry for distributed tracing\n *\n * @param name - Action name used for logging and telemetry spans (default: 'main')\n * @param httpMethods - Allowed HTTP methods (GET, POST, etc.). Empty array allows all methods\n * @param requiredParams - Required parameter names in the request body\n * @param requiredHeaders - Required header names (case-insensitive)\n * @param action - User-defined action function that receives:\n * - params: All request parameters including __ow_* runtime parameters\n * - ctx: Context object with logger and headers\n * @returns Wrapped action function ready to be exported as Adobe I/O Runtime entrypoint\n *\n * @example With All Options\n * ```typescript\n * const handler = RuntimeAction.execute(\n * 'processOrder',\n * [HttpMethod.POST],\n * ['orderId', 'customerId'],\n * ['authorization', 'x-api-key'],\n * async (params, { logger, headers }) => {\n * const { orderId, customerId } = params;\n * logger.info({ message: 'Processing order', orderId, customerId });\n *\n * // Your business logic here\n * const result = await processOrderLogic(orderId, customerId);\n *\n * return {\n * statusCode: 200,\n * body: { orderId, status: 'processed', result }\n * };\n * }\n * );\n * ```\n *\n * @example Minimal Configuration\n * ```typescript\n * const handler = RuntimeAction.execute('simpleAction', [], [], [], async (params, { logger }) => {\n * logger.info('Simple action executed');\n * return { statusCode: 200, body: { message: 'Success' } };\n * });\n * ```\n */\n static execute(\n name: string = 'main',\n httpMethods: HttpMethod[] = [],\n requiredParams: string[] = [],\n requiredHeaders: string[] = [],\n action: (\n params: { [key: string]: any },\n ctx: { logger: any; headers: { [key: string]: any } }\n ) => Promise<RuntimeActionResponseType> = async (\n _params\n ): Promise<RuntimeActionResponseType> => {\n return { statusCode: HttpStatus.OK, body: {} };\n }\n ): (params: { [key: string]: any }) => Promise<RuntimeActionResponseType> {\n /**\n * Internal wrapped action that executes with full runtime support\n * This function is instrumented with telemetry and returned to the caller\n *\n * The logger automatically includes x-adobe-commerce-request-id (if present)\n * in all log messages through Winston's child logger mechanism.\n */\n const runtimeAction = async (params: {\n [key: string]: any;\n }): Promise<RuntimeActionResponseType> => {\n if (!params.action_type) {\n params.action_type = RuntimeAction.getActionType();\n }\n // Step 1: Create a structured logger with telemetry integration and request ID metadata\n // This ensures x-adobe-commerce-request-id is automatically added to ALL logs\n const logger = Telemetry.createLogger(name, params);\n\n try {\n // Step 2: Log action start with structured data for observability\n // (x-adobe-commerce-request-id is automatically added by the logger if present)\n logger.debug({\n message: `${name}-started`,\n action_name: name,\n });\n\n // Step 3: Log incoming headers for debugging and audit trails\n // These are flattened by JsonMessageProcessor for searchability\n logger.debug({\n message: `${name}-headers`,\n headers: params.__ow_headers || {},\n });\n\n // Step 4: Log request body for debugging\n logger.debug({\n message: `${name}-body`,\n body: params.__ow_body || {},\n });\n\n // Step 5: Validate request (params, headers, HTTP method)\n // Returns error response immediately if validation fails\n const validationError = RuntimeAction.validateRequest(\n params,\n requiredParams,\n requiredHeaders,\n httpMethods,\n logger,\n name\n );\n if (validationError) {\n return validationError;\n }\n\n // Step 6: Execute user's action with logger and headers context\n const result = await action(params, { logger: logger, headers: params.__ow_headers || {} });\n\n // Step 7: Log the result for observability\n logger.debug({\n message: `${name}-completed`,\n result: result,\n });\n\n return result;\n } catch (error) {\n // Step 8: Handle unexpected errors\n // Log the error for debugging and return 500 response\n if (error instanceof Error) {\n logger.error({\n message: `${name}-failed`,\n error: error.message,\n stack: error.stack,\n });\n } else {\n logger.error({\n message: `${name}-failed`,\n error: error,\n });\n }\n return RuntimeActionResponse.error(HttpStatus.INTERNAL_ERROR, 'server error');\n }\n };\n\n // Step 9: Initialize telemetry instrumentation (traces, metrics, logs)\n // This wraps the action with OpenTelemetry if configured\n return Telemetry.initialize(runtimeAction);\n }\n\n /**\n * Validates incoming request against required parameters, headers, and HTTP methods\n *\n * This private method performs comprehensive request validation:\n * 1. Checks for missing required parameters in the request body\n * 2. Checks for missing required headers (case-insensitive)\n * 3. Validates the HTTP method against allowed methods list\n *\n * @param params - Request parameters including __ow_* runtime parameters\n * @param requiredParams - List of required parameter names to validate\n * @param requiredHeaders - List of required header names to validate (case-insensitive)\n * @param httpMethods - Allowed HTTP methods. Empty array skips HTTP method validation\n * @param logger - Logger instance for error logging (child logger with request ID if present)\n * @param name - Action name for logging\n * @returns RuntimeActionResponseType with error details if validation fails, null if valid\n *\n * @private\n *\n * @example Validation Error Response\n * ```typescript\n * // Missing parameter returns:\n * {\n * statusCode: 400,\n * body: { error: 'Missing required parameter: userId' }\n * }\n *\n * // Invalid HTTP method returns:\n * {\n * statusCode: 405,\n * body: { error: 'Invalid HTTP method: DELETE. Allowed methods are: GET, POST' }\n * }\n * ```\n */\n private static validateRequest(\n params: { [key: string]: any },\n requiredParams: string[],\n requiredHeaders: string[],\n httpMethods: HttpMethod[],\n logger: any,\n name: string\n ): RuntimeActionResponseType | null {\n // check for missing request input parameters and headers\n const errorMessage =\n Validator.checkMissingRequestInputs(params, requiredParams, requiredHeaders) ?? '';\n if (errorMessage) {\n logger.error({\n message: `${name}-validation-failed`,\n error: errorMessage,\n });\n // return and log client errors\n return RuntimeActionResponse.error(HttpStatus.BAD_REQUEST, errorMessage);\n }\n\n // validate HTTP method\n const requestMethod = params.__ow_method?.toUpperCase();\n if (httpMethods.length > 0 && !httpMethods.includes(requestMethod)) {\n const errorMessage = `Invalid HTTP method: ${params.__ow_method}. Allowed methods are: ${httpMethods.join(', ')}`;\n logger.error({\n message: `${name}-validation-failed`,\n error: errorMessage,\n });\n return RuntimeActionResponse.error(HttpStatus.METHOD_NOT_ALLOWED, errorMessage);\n }\n\n return null;\n }\n}\n\nexport default RuntimeAction;\n","/**\n * <license header>\n */\n\nclass Parameters {\n /**\n * Returns a log-ready string of the action input parameters.\n * The `Authorization` header content will be replaced by '<hidden>'.\n *\n * @param params action input parameters.\n *\n * @returns string\n */\n static stringify(params: { [key: string]: any }): string {\n // hide authorization token without overriding params\n let headers = params.__ow_headers || {};\n if (headers.authorization) {\n headers = { ...headers, authorization: '<hidden>' };\n }\n return JSON.stringify({ ...params, __ow_headers: headers });\n }\n}\n\nexport default Parameters;\n","/**\n * Adobe App Builder Event Consumer Action handler\n *\n * <license header>\n */\n\nimport RuntimeActionResponse from '../runtime-action/response';\nimport Validator from '../runtime-action/validator';\nimport Telemetry from '../telemetry';\n\nimport { HttpStatus } from '../runtime-action/types';\nimport { RuntimeActionResponseType } from '../runtime-action/response/types';\n\n/**\n * EventConsumerAction provides a standardized wrapper for Adobe I/O Runtime event consumer actions\n *\n * This class handles:\n * - Structured logging with automatic request ID correlation (x-adobe-commerce-request-id)\n * - Request validation (parameters and headers)\n * - OpenTelemetry instrumentation for traces, metrics, and logs\n * - Consistent error handling and response formatting\n *\n * @example Basic event consumer action\n * ```typescript\n * const handler = EventConsumerAction.execute(\n * 'order-processor',\n * ['orderId'],\n * ['x-signature'],\n * async (params, { logger }) => {\n * logger.info({ message: 'Processing order', orderId: params.orderId });\n * return { statusCode: 200, body: { success: true } };\n * }\n * );\n * ```\n */\nclass EventConsumerAction {\n /**\n * Creates an event consumer action handler with telemetry integration\n *\n * This method wraps a user-defined action with:\n * - Structured logging (all logs automatically include x-adobe-commerce-request-id if present)\n * - Request validation for required parameters and headers\n * - OpenTelemetry instrumentation\n * - Standardized error handling\n *\n * @param name - Action name for logging and observability\n * @param requiredParams - List of required parameter names to validate\n * @param requiredHeaders - List of required header names to validate (case-insensitive)\n * @param action - User's event consumer function that receives params and context\n * @returns Wrapped action handler ready for OpenWhisk runtime\n *\n * @example\n * ```typescript\n * const handler = EventConsumerAction.execute(\n * 'webhook-processor',\n * ['eventType', 'eventData'],\n * ['x-webhook-signature'],\n * async (params, { logger, headers }) => {\n * logger.info({\n * message: 'Processing webhook',\n * eventType: params.eventType\n * });\n * // Process event...\n * return { statusCode: 200, body: { processed: true } };\n * }\n * );\n * ```\n */\n static execute(\n name: string = 'main',\n requiredParams: string[] = [],\n requiredHeaders: string[] = [],\n action: (\n params: { [key: string]: any },\n ctx: { logger: any; headers: { [key: string]: any } }\n ) => Promise<RuntimeActionResponseType> = async (\n _params\n ): Promise<RuntimeActionResponseType> => {\n return { statusCode: HttpStatus.OK, body: {} };\n }\n ): (params: { [key: string]: any }) => Promise<RuntimeActionResponseType> {\n const eventConsumerAction = async (params: {\n [key: string]: any;\n }): Promise<RuntimeActionResponseType> => {\n params.action_type = 'event-consumer-action';\n // Step 1: Create a structured logger with telemetry integration and request ID metadata\n // This ensures x-adobe-commerce-request-id is automatically added to ALL logs\n const logger = Telemetry.createLogger(name, params);\n\n try {\n // Step 2: Log action start with structured data for observability\n // (x-adobe-commerce-request-id is automatically added by the logger if present)\n logger.debug({\n message: `${name}-started`,\n action_name: name,\n });\n\n // Step 3: Log incoming headers for debugging and audit trails\n // These are flattened by JsonMessageProcessor for searchability\n logger.debug({\n message: `${name}-headers`,\n headers: params.__ow_headers || {},\n });\n\n // Step 4: Log request body/parameters for debugging\n logger.debug({\n message: `${name}-parameters`,\n parameters: params,\n });\n\n // Step 5: Validate request (params and headers)\n // Returns error response immediately if validation fails\n const errorMessage =\n Validator.checkMissingRequestInputs(params, requiredParams, requiredHeaders) || '';\n if (errorMessage) {\n logger.error({\n message: `${name}-validation-failed`,\n error: errorMessage,\n });\n return RuntimeActionResponse.error(HttpStatus.BAD_REQUEST, errorMessage);\n }\n\n // Step 6: Execute user's event consumer action with logger and headers context\n const result = await action(params, { logger: logger, headers: params.__ow_headers || {} });\n\n // Step 7: Log the result for observability\n logger.debug({\n message: `${name}-completed`,\n result: result,\n });\n\n return result;\n } catch (error) {\n // Step 8: Handle unexpected errors\n // Log the error for debugging and return 500 response\n if (error instanceof Error) {\n logger.error({\n error: error.message,\n stack: error.stack,\n });\n } else {\n logger.error({ error });\n }\n return RuntimeActionResponse.error(HttpStatus.INTERNAL_ERROR, 'server error');\n }\n };\n\n // Step 9: Initialize telemetry instrumentation (traces, metrics, logs)\n // This wraps the action with OpenTelemetry if configured\n return Telemetry.initialize(eventConsumerAction);\n }\n}\n\nexport default EventConsumerAction;\n","/**\n * Adobe App Builder GraphQL framework utilities\n *\n * <license header>\n */\n\nimport { graphql, buildSchema, parse, validate } from 'graphql';\n\nimport RuntimeAction from '../runtime-action';\nimport RuntimeActionResponse from '../runtime-action/response';\n\nimport { HttpMethod, HttpStatus } from '../runtime-action/types';\nimport { RuntimeActionResponseType } from '../runtime-action/response/types';\n\nclass GraphQlAction {\n static execute(\n schema: string = `\n type Query {\n hello: String\n }\n `,\n resolvers: (ctx: {\n logger: any;\n headers: { [key: string]: any };\n params: { [key: string]: any };\n }) => Promise<any> = async (_params): Promise<any> => {\n return {\n hello: (): string => 'Hello World!',\n };\n },\n name: string = 'main',\n disableIntrospection: boolean = false\n ): (params: { [key: string]: any }) => Promise<RuntimeActionResponseType> {\n return RuntimeAction.execute(\n `graphql-${name}`,\n [HttpMethod.GET, HttpMethod.POST],\n ['query'],\n [],\n async (params, ctx) => {\n let graphqlSchema;\n try {\n graphqlSchema = buildSchema(schema);\n } catch (error) {\n return RuntimeActionResponse.error(HttpStatus.BAD_REQUEST, (error as Error).message);\n }\n const graphqlResolvers = await resolvers({\n ...ctx,\n ...{\n params,\n },\n });\n\n const context = {};\n const query = params.query;\n\n let parsedQuery;\n try {\n parsedQuery = parse(query);\n } catch (error) {\n return RuntimeActionResponse.error(HttpStatus.BAD_REQUEST, (error as Error).message);\n }\n\n const validationErrors = validate(graphqlSchema, parsedQuery);\n if (validationErrors.length) {\n return RuntimeActionResponse.error(\n HttpStatus.BAD_REQUEST,\n validationErrors.map(err => err.message).join(', ')\n );\n }\n\n if (disableIntrospection) {\n // Check for introspection queries\n const isIntrospectionQuery = parsedQuery.definitions.some((definition: any) =>\n definition.selectionSet.selections.some((selection: any) =>\n selection.name.value.startsWith('__')\n )\n );\n if (isIntrospectionQuery) {\n // return and log client errors\n return RuntimeActionResponse.error(\n HttpStatus.BAD_REQUEST,\n 'Introspection is disabled for security reasons.'\n );\n }\n }\n\n const variables =\n typeof params.variables === 'string' ? JSON.parse(params.variables) : params.variables;\n\n return RuntimeActionResponse.success(\n await graphql({\n schema: graphqlSchema,\n source: query,\n rootValue: graphqlResolvers,\n contextValue: context,\n variableValues: variables,\n operationName: params.operationName,\n })\n );\n }\n );\n }\n}\n\nexport default GraphQlAction;\n","/**\n * Adobe App Builder OpenWhisk client wrapper\n *\n * <license header>\n */\n\nimport openwhisk, { Activation, Dict } from 'openwhisk';\n\nclass Openwhisk {\n /**\n * @var openwhisk\n */\n openwhiskClient: ReturnType<typeof openwhisk>;\n\n /**\n * @param host\n * @param apiKey\n */\n constructor(host: string, apiKey: string) {\n this.openwhiskClient = openwhisk({ apihost: host, api_key: apiKey });\n }\n\n /**\n * @param action\n * @param params\n * @returns {Promise<Activation<Dict>>}\n */\n async execute(action: string, params: Dict): Promise<Activation<Dict>> {\n return await this.openwhiskClient.actions.invoke({\n name: action,\n blocking: true,\n params: params,\n });\n }\n}\n\nexport default Openwhisk;\n","/**\n * Adobe App Builder OpenWhisk Action handler\n *\n * <license header>\n */\n// OpenWhisk action handler - no direct client dependency needed\n\nimport RuntimeActionResponse from '../runtime-action/response';\n\nimport { HttpStatus } from '../runtime-action/types';\nimport { RuntimeActionResponseType } from '../runtime-action/response/types';\nimport Telemetry from '../telemetry';\n\n/**\n * OpenwhiskAction provides a standardized wrapper for Adobe I/O Runtime OpenWhisk-based webhook actions\n *\n * This class wraps user-defined webhook actions with common runtime functionality including:\n * - Structured logging with telemetry integration\n * - Error handling with appropriate HTTP status codes\n * - OpenTelemetry instrumentation for observability\n * - Automatic request ID tracking from headers\n *\n * @example Basic Usage\n * ```typescript\n * const handler = OpenwhiskAction.execute(\n * 'webhookHandler',\n * async (params, { logger, headers }) => {\n * logger.info({ message: 'Processing webhook', data: params });\n * return { statusCode: 200, body: { success: true } };\n * }\n * );\n *\n * export const main = handler;\n * ```\n */\nclass OpenwhiskAction {\n /**\n * Creates an OpenWhisk webhook action handler with logging and telemetry\n *\n * Wraps a user-defined action function with standardized runtime functionality:\n * 1. Creates a structured logger with telemetry integration\n * 2. Logs action start with structured data\n * 3. Logs request parameters at debug level\n * 4. Executes the user action with logger and headers context\n * 5. Logs the result and handles errors with appropriate status codes\n * 6. Integrates with OpenTelemetry for distributed tracing\n *\n * The logger automatically includes x-adobe-commerce-request-id and action.type\n * (if present) in all log messages.\n *\n * @param name - Action name used for logging and telemetry spans (default: 'main')\n * @param action - User-defined action function that receives:\n * - params: All request parameters including __ow_* runtime parameters\n * - ctx: Context object with logger and headers\n * @returns Wrapped action function ready to be exported as Adobe I/O Runtime entrypoint\n *\n * @example Complete Example\n * ```typescript\n * const handler = OpenwhiskAction.execute(\n * 'processWebhook',\n * async (params, { logger, headers }) => {\n * logger.info({ message: 'Webhook received', event: params.event });\n *\n * // Your webhook processing logic here\n * const result = await processWebhookData(params);\n *\n * return {\n * statusCode: 200,\n * body: { status: 'processed', result }\n * };\n * }\n * );\n * ```\n */\n static execute(\n name: string = 'main',\n action: (\n params: { [key: string]: any },\n ctx: { logger: any; headers: { [key: string]: any } }\n ) => Promise<RuntimeActionResponseType> = async (\n _params\n ): Promise<RuntimeActionResponseType> => {\n return { statusCode: HttpStatus.OK, body: {} };\n }\n ): (params: { [key: string]: any }) => Promise<RuntimeActionResponseType> {\n /**\n * Internal wrapped action that executes with full runtime support\n * This function is instrumented with telemetry and returned to the caller\n */\n const openwhiskAction = async (params: {\n [key: string]: any;\n }): Promise<RuntimeActionResponseType> => {\n // Always set action type to 'openwhisk-action'\n params.action_type = 'openwhisk-action';\n\n // Step 1: Create a structured logger with telemetry integration\n // This ensures x-adobe-commerce-request-id and action.type are automatically added to ALL logs\n const logger = Telemetry.createLogger(name, params);\n\n try {\n // Step 2: Log action start with structured data\n logger.debug({\n message: `${name}-started`,\n action_name: name,\n });\n\n // Step 3: Log parameters at debug level for troubleshooting\n logger.debug({\n message: `${name}-params`,\n params: params,\n });\n\n // Step 4: Execute user's action with logger and headers context\n const result = await action(params, { logger: logger, headers: params.__ow_headers || {} });\n\n // Step 5: Log the result for observability\n logger.debug({\n message: `${name}-completed`,\n result: result,\n });\n\n return result;\n } catch (error) {\n // Step 6: Handle unexpected errors\n // Log the error for debugging and return 500 response\n if (error instanceof Error) {\n logger.error({\n message: `${name}-failed`,\n error: error.message,\n stack: error.stack,\n });\n } else {\n logger.error({\n message: `${name}-failed`,\n error: error,\n });\n }\n return RuntimeActionResponse.error(HttpStatus.INTERNAL_ERROR, 'server error');\n }\n };\n\n // Step 7: Initialize telemetry instrumentation (traces, metrics, logs)\n // This wraps the action with OpenTelemetry if configured\n return Telemetry.initialize(openwhiskAction);\n }\n}\n\nexport default OpenwhiskAction;\n","/**\n * Copyright © Adobe, Inc. All rights reserved.\n */\n\nimport { Files } from '@adobe/aio-sdk';\nimport { FileRecord, FileMetadata } from './types';\n\n/**\n * FileRepository class for managing file-based storage operations\n * Provides CRUD operations for JSON files in a specified directory\n */\nclass FileRepository {\n private readonly filepath: string;\n private files: any = null;\n\n /**\n * Creates a new FileRepository instance\n * @param filepath - The base directory path for file operations\n */\n constructor(filepath: string) {\n this.filepath = filepath;\n }\n\n /**\n * Lists all files in the repository directory\n * @returns Promise<FileRecord[]> Array of file records\n */\n async list(): Promise<FileRecord[]> {\n const filesLib = await this.getFiles();\n const results: FileRecord[] = [];\n\n const existingFiles = (await this.metadata()) as FileMetadata[];\n if (existingFiles.length) {\n for (const file of existingFiles) {\n const buffer = await filesLib.read(`${file.name}`);\n const data = JSON.parse(buffer.toString());\n\n // Add file system timestamps\n results.push({\n ...data,\n createdAt: file.creationTime.toISOString(),\n updatedAt: file.lastModified.toISOString(),\n });\n }\n }\n\n return results;\n }\n\n /**\n * Lists file metadata without reading file contents\n * Provides a lightweight alternative to list() for performance-critical operations\n * @param id - Optional ID of a specific file to get metadata for\n * @returns Promise<FileMetadata | FileMetadata[]> Single file metadata if id provided, array of all files otherwise\n */\n async metadata(id?: string): Promise<FileMetadata | FileMetadata[]> {\n const filesLib = await this.getFiles();\n\n if (id) {\n const filepath = `${this.filepath}/${id}.json`;\n return await filesLib.getProperties(filepath);\n }\n\n return await filesLib.list(`${this.filepath}/`);\n }\n\n /**\n * Loads a specific file by ID\n * @param id - The ID of the file to load\n * @returns Promise<FileRecord> The loaded file record or empty object if not found\n */\n async load(id: string = ''): Promise<FileRecord> {\n const filepath = `${this.filepath}/${id}.json`;\n const filesLib = await this.getFiles();\n\n const existingFile = await filesLib.list(filepath);\n if (existingFile.length) {\n const buffer = await filesLib.read(filepath);\n const data = JSON.parse(buffer.toString());\n\n // Get file system properties to add timestamps\n const fileProps = await filesLib.getProperties(filepath);\n\n return {\n ...data,\n createdAt: fileProps.creationTime.toISOString(),\n updatedAt: fileProps.lastModified.toISOString(),\n };\n }\n\n return {} as FileRecord;\n }\n\n /**\n * Saves a file record to the repository\n * @param payload - The data to save\n * @param id - Optional ID for the file (sanitized to alphanumeric + underscore, takes precedence over payload.id)\n * @param overwrite - Optional flag to control file write behavior:\n * - true: Replace file entirely with payload (no merge)\n * - false (default): Merge payload with existing file content\n * @returns Promise<string | null> The filename on success, null on failure\n */\n async save(\n payload: Partial<FileRecord> = {},\n id?: string | null,\n overwrite: boolean = false\n ): Promise<string | null> {\n try {\n const filesLib = await this.getFiles();\n\n // ID parameter takes precedence, then payload.id, then timestamp\n let fileId: string;\n if (id) {\n fileId = this.sanitizeFileId(id);\n } else if ('id' in payload && payload.id !== undefined) {\n fileId = String(payload.id);\n } else {\n fileId = String(new Date().getTime());\n }\n\n const filepath = `${this.filepath}/${fileId}.json`;\n\n const existingFile = await filesLib.list(filepath);\n if (existingFile.length) {\n if (overwrite) {\n // Overwrite mode: Replace entirely with payload (no merge)\n console.log(`Overwriting existing file: ${filepath}`);\n payload = {\n id: fileId,\n ...payload,\n };\n } else {\n // Default mode: Merge with existing content\n const buffer = await filesLib.read(filepath);\n const existingData = JSON.parse(buffer.toString());\n\n payload = { ...existingData, ...payload };\n }\n // Note: No delete needed - write() will overwrite the file content\n // while preserving the file system's createdAt timestamp\n } else {\n payload = {\n id: fileId,\n ...payload,\n };\n }\n\n // Remove createdAt and updatedAt from payload before saving\n // (these will be added from file system properties when loading)\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { createdAt, updatedAt, ...payloadWithoutTimestamps } = payload as FileRecord;\n\n // Write the file\n await filesLib.write(filepath, JSON.stringify(payloadWithoutTimestamps));\n\n return fileId;\n } catch (error) {\n console.error('Error saving file:', error);\n return null;\n }\n }\n\n /**\n * Deletes files by their IDs\n * @param ids - Array of file IDs to delete\n * @returns Promise<FileRecord[]> Updated list of remaining files\n */\n async delete(ids: string[] = []): Promise<FileRecord[]> {\n const filesLib = await this.getFiles();\n\n for (const id of ids) {\n await filesLib.delete(`${this.filepath}/${id}.json`);\n }\n\n return await this.list();\n }\n\n /**\n * Sanitizes the file ID to contain only alphanumeric characters and underscores\n * @param id - The ID to sanitize\n * @returns Sanitized ID with invalid characters replaced by underscores\n */\n private sanitizeFileId(id: string): string {\n if (!id || typeof id !== 'string') {\n return String(new Date().getTime());\n }\n\n // Replace any non-alphanumeric characters (except underscore) with underscore\n const sanitized = id.replace(/[^a-zA-Z0-9_]/g, '_');\n\n // If the sanitized ID is empty or only underscores, use timestamp\n if (!sanitized || /^_+$/.test(sanitized)) {\n return String(new Date().getTime());\n }\n\n return sanitized;\n }\n\n /**\n * Initializes and returns the Files library instance\n * @returns Promise<any> Initialized Files library instance\n */\n private async getFiles(): Promise<any> {\n if (!this.files) {\n this.files = await Files.init();\n }\n return this.files;\n }\n}\n\nexport default FileRepository;\n","/**\n * <license header>\n */\n\nimport { Events } from '@adobe/aio-sdk';\nimport { CloudEvent } from 'cloudevents';\nimport { v4 as uuidv4 } from 'uuid';\nimport CustomLogger from '../custom-logger';\nimport type { PublishEventResult } from './types';\n\n/**\n * PublishEvent component for Adobe I/O Event Publishing\n *\n * This component encapsulates the logic for publishing CloudEvents using Adobe I/O Events SDK.\n * It constructs CloudEvents with the provided payload and publishes them to the specified provider.\n *\n * @example\n * ```typescript\n * const publishEvent = new PublishEvent(\n * 'your-ims-org-id@AdobeOrg',\n * 'your-api-key',\n * 'your-access-token'\n * );\n *\n * // Publish an event\n * const result = await publishEvent.execute('provider-id', {\n * type: 'commerce.order.created',\n * data: {\n * orderId: 'ORD-123456',\n * customerId: 'CUST-789',\n * amount: 199.99\n * }\n * });\n * ```\n */\nclass PublishEvent {\n private readonly imsOrgId: string;\n private readonly apiKey: string;\n private readonly accessToken: string;\n private readonly customLogger: CustomLogger;\n\n /**\n * Creates a new PublishEvent instance\n *\n * @param imsOrgId - Adobe IMS Organization ID\n * @param apiKey - Adobe API Key (Client ID)\n * @param accessToken - Adobe Access Token\n * @param logger - Optional logger instance\n */\n constructor(imsOrgId: string, apiKey: string, accessToken: string, logger: any = null) {\n // Validate required parameters\n if (!imsOrgId?.trim()) {\n throw new Error('imsOrgId is required and cannot be empty');\n }\n if (!apiKey?.trim()) {\n throw new Error('apiKey is required and cannot be empty');\n }\n if (!accessToken?.trim()) {\n throw new Error('accessToken is required and cannot be empty');\n }\n\n this.imsOrgId = imsOrgId;\n this.apiKey = apiKey;\n this.accessToken = accessToken;\n this.customLogger = new CustomLogger(logger);\n\n this.customLogger.debug('PublishEvent initialized with valid configuration');\n }\n\n /**\n * Publishes a CloudEvent to Adobe I/O Events\n *\n * @param providerId - The Adobe I/O Events provider ID\n * @param eventCode - The event type identifier (e.g., 'commerce.order.created')\n * @param payload - The event payload data\n * @param subject - Optional subject for the event\n * @returns Promise<PublishEventResult> - The publish result\n *\n * @throws Error when providerId or eventCode is invalid or publishing fails\n */\n async execute(\n providerId: string,\n eventCode: string,\n payload: any,\n subject?: string\n ): Promise<PublishEventResult> {\n try {\n // Validate inputs\n if (!providerId?.trim()) {\n throw new Error('providerId is required and cannot be empty');\n }\n\n if (!eventCode?.trim()) {\n throw new Error('eventCode is required and cannot be empty');\n }\n\n if (payload === null || payload === undefined) {\n throw new Error('payload is required');\n }\n\n this.customLogger.info(`Publishing event to provider: ${providerId}`);\n\n // Generate unique event ID\n const eventId = uuidv4();\n\n // Construct CloudEvent using the cloudevents library\n const cloudEvent = new CloudEvent({\n id: eventId,\n source: `urn:uuid:${providerId}`,\n datacontenttype: 'application/json',\n type: eventCode,\n data: payload,\n ...(subject && { subject }),\n });\n\n this.customLogger.debug(`Constructed CloudEvent with ID: ${eventId}`);\n\n // Initialize Adobe I/O Events client\n const eventsClient = await Events.init(this.imsOrgId, this.apiKey, this.accessToken);\n\n this.customLogger.debug('Adobe I/O Events client initialized successfully');\n\n // Publish the event\n await eventsClient.publishEvent(cloudEvent);\n\n const publishedAt = new Date().toISOString();\n\n this.customLogger.info(`Event published successfully with ID: ${eventId}`);\n\n return {\n eventId,\n status: 'published',\n publishedAt,\n };\n } catch (error: any) {\n this.customLogger.error(`Failed to publish event: ${error.message}`);\n\n // Return error result instead of throwing\n return {\n eventId: uuidv4(), // Generate ID for tracking even failed events\n status: 'failed',\n publishedAt: new Date().toISOString(),\n error: error.message,\n };\n }\n }\n}\n\nexport default PublishEvent;\n","/**\n * <license header>\n */\n\n/**\n * Custom logger class that provides null-safe logging methods\n * This class is private to the package and should not be exported publicly\n */\nclass CustomLogger {\n private logger: any;\n\n /**\n * @param logger - External logger instance (can be null)\n */\n constructor(logger: any = null) {\n this.logger = logger;\n }\n\n /**\n * Log debug message if logger is available\n * @param message - Debug message to log\n * @param args - Additional arguments to pass to logger\n */\n debug(message: string, ...args: any[]): void {\n if (this.logger && typeof this.logger.debug === 'function') {\n this.logger.debug(message, ...args);\n }\n }\n\n /**\n * Log info message if logger is available\n * @param message - Info message to log\n * @param args - Additional arguments to pass to logger\n */\n info(message: string, ...args: any[]): void {\n if (this.logger && typeof this.logger.info === 'function') {\n this.logger.info(message, ...args);\n }\n }\n\n /**\n * Log error message if logger is available\n * @param message - Error message to log\n * @param args - Additional arguments to pass to logger\n */\n error(message: string, ...args: any[]): void {\n if (this.logger && typeof this.logger.error === 'function') {\n this.logger.error(message, ...args);\n }\n }\n\n /**\n * Get the underlying logger instance\n * @returns the logger instance or null\n */\n getLogger(): any {\n return this.logger;\n }\n}\n\nexport default CustomLogger;\n","/**\n * <license header>\n */\n\n/**\n * Webhook operation types for Adobe Commerce webhooks.\n *\n * These operations define the different types of responses that can be returned\n * from a webhook handler to modify the behavior or data in Adobe Commerce.\n *\n * @see https://developer.adobe.com/commerce/extensibility/webhooks/\n */\nexport enum WebhookActionOperation {\n /** Indicates successful webhook processing with no modifications */\n SUCCESS = 'success',\n /** Indicates an exception or error occurred during webhook processing */\n EXCEPTION = 'exception',\n /** Adds a new field or value to the webhook payload */\n ADD = 'add',\n /** Replaces an existing field or value in the webhook payload */\n REPLACE = 'replace',\n /** Removes a field from the webhook payload */\n REMOVE = 'remove',\n}\n\n/**\n * Response indicating successful webhook processing.\n *\n * Use this response when the webhook has been processed successfully\n * and no modifications to the payload are needed.\n *\n * @example\n * ```typescript\n * const response: WebhookActionSuccessResponse = {\n * op: WebhookActionOperation.SUCCESS\n * };\n * ```\n */\nexport interface WebhookActionSuccessResponse {\n /** Operation type */\n op: typeof WebhookActionOperation.SUCCESS;\n}\n\n/**\n * Response indicating an exception or error during webhook processing.\n *\n * Use this response to notify Adobe Commerce that an error occurred\n * during webhook processing. Optionally include the exception class\n * and error message for debugging purposes.\n *\n * @example\n * ```typescript\n * const response: WebhookActionExceptionResponse = {\n * op: WebhookActionOperation.EXCEPTION,\n * class: 'ProductNotFoundException',\n * message: 'Product with SKU ABC123 not found'\n * };\n * ```\n */\nexport interface WebhookActionExceptionResponse {\n /** Operation type */\n op: typeof WebhookActionOperation.EXCEPTION;\n /** Optional exception class name for categorization */\n class?: string;\n /** Optional error message describing what went wrong */\n message?: string;\n}\n\n/**\n * Response for adding a new field or value to the webhook payload.\n *\n * Use this response to inject new data into the webhook payload that will\n * be processed by Adobe Commerce. The path specifies where to add the data,\n * and value contains the data to add.\n *\n * @example\n * ```typescript\n * const response: WebhookActionAddResponse = {\n * op: WebhookActionOperation.ADD,\n * path: 'order.items',\n * value: { sku: 'PRODUCT-123', quantity: 2, price: 49.99 },\n * instance: 'order-12345'\n * };\n * ```\n */\nexport interface WebhookActionAddResponse {\n /** Operation type */\n op: typeof WebhookActionOperation.ADD;\n /** Dot-notation path where the value should be added (e.g., 'order.items', 'customer.addresses') */\n path: string;\n /** The value to add at the specified path */\n value: any;\n /** Optional instance identifier for tracking or reference */\n instance?: string;\n}\n\n/**\n * Response for replacing an existing field or value in the webhook payload.\n *\n * Use this response to modify existing data in the webhook payload.\n * The path specifies which field to replace, and value contains the new data.\n *\n * @example\n * ```typescript\n * const response: WebhookActionReplaceResponse = {\n * op: WebhookActionOperation.REPLACE,\n * path: 'product.price',\n * value: 29.99,\n * instance: 'product-456'\n * };\n * ```\n */\nexport interface WebhookActionReplaceResponse {\n /** Operation type */\n op: typeof WebhookActionOperation.REPLACE;\n /** Dot-notation path to the field that should be replaced (e.g., 'product.price', 'order.status') */\n path: string;\n /** The new value to replace the existing value */\n value: any;\n /** Optional instance identifier for tracking or reference */\n instance?: string;\n}\n\n/**\n * Response for removing a field from the webhook payload.\n *\n * Use this response to remove data from the webhook payload before\n * it's processed by Adobe Commerce.\n *\n * @example\n * ```typescript\n * const response: WebhookActionRemoveResponse = {\n * op: WebhookActionOperation.REMOVE,\n * path: 'customer.addresses.0'\n * };\n * ```\n */\nexport interface WebhookActionRemoveResponse {\n /** Operation type */\n op: typeof WebhookActionOperation.REMOVE;\n /** Dot-notation path to the field that should be removed (e.g., 'items.0', 'customer.email') */\n path: string;\n}\n\n/**\n * Union type representing all possible webhook action response types.\n *\n * This type can be used when you need to handle multiple response types\n * or want to ensure type safety across different webhook operations.\n *\n * @example\n * ```typescript\n * function handleResponse(response: WebhookActionResponseType) {\n * switch (response.op) {\n * case WebhookActionOperation.SUCCESS:\n * // Handle success\n * break;\n * case WebhookActionOperation.EXCEPTION:\n * // Handle exception\n * break;\n * // ... handle other operations\n * }\n * }\n * ```\n */\nexport type WebhookActionResponseType =\n | WebhookActionSuccessResponse\n | WebhookActionExceptionResponse\n | WebhookActionAddResponse\n | WebhookActionReplaceResponse\n | WebhookActionRemoveResponse;\n","/**\n * <license header>\n */\n\nimport {\n WebhookActionOperation,\n WebhookActionSuccessResponse,\n WebhookActionExceptionResponse,\n WebhookActionAddResponse,\n WebhookActionReplaceResponse,\n WebhookActionRemoveResponse,\n} from './types';\n\n/**\n * WebhookActionResponse - Factory class for creating Adobe Commerce webhook responses\n *\n * This class provides static methods to create properly formatted responses for\n * Adobe Commerce webhooks. These responses can be used to signal success, report\n * exceptions, or modify webhook payloads by adding, replacing, or removing data.\n *\n * All methods return strongly-typed response objects that conform to Adobe Commerce's\n * webhook response specification.\n *\n * @example\n * ```typescript\n * // Return a success response\n * return WebhookActionResponse.success();\n *\n * // Report an exception\n * return WebhookActionResponse.exception('ValidationException', 'Invalid product data');\n *\n * // Add new data to the payload\n * return WebhookActionResponse.add('order.metadata', { processed: true });\n *\n * // Modify existing data\n * return WebhookActionResponse.replace('product.price', 29.99);\n *\n * // Remove data from the payload\n * return WebhookActionResponse.remove('customer.internal_notes');\n * ```\n *\n * @see https://developer.adobe.com/commerce/extensibility/webhooks/\n */\nclass WebhookActionResponse {\n /**\n * Creates a success response indicating the webhook was processed successfully.\n *\n * Use this method when the webhook has been processed without errors and\n * no modifications to the payload are needed.\n *\n * @returns A success response object\n *\n * @example\n * ```typescript\n * const handler = WebhookAction.execute('process-order', [], [], async (params) => {\n * // Process the order...\n * await processOrder(params.order);\n *\n * // Return success\n * return {\n * statusCode: 200,\n * body: WebhookActionResponse.success()\n * };\n * });\n * ```\n */\n static success(): WebhookActionSuccessResponse {\n return {\n op: WebhookActionOperation.SUCCESS,\n };\n }\n\n /**\n * Creates an exception response to report an error during webhook processing.\n *\n * Use this method to notify Adobe Commerce that an error occurred while\n * processing the webhook. This helps with debugging and error tracking.\n *\n * @param message - Optional error message describing what went wrong\n * @param exceptionClass - Optional exception class name for categorization (e.g., 'Magento\\\\Framework\\\\Exception\\\\LocalizedException')\n * @returns An exception response object\n *\n * @example\n * ```typescript\n * const handler = WebhookAction.execute('validate-product', [], [], async (params) => {\n * const product = await findProduct(params.sku);\n *\n * if (!product) {\n * return {\n * statusCode: 404,\n * body: WebhookActionResponse.exception(\n * `Product with SKU ${params.sku} not found`,\n * 'Magento\\\\Framework\\\\Exception\\\\NoSuchEntityException'\n * )\n * };\n * }\n *\n * return { statusCode: 200, body: WebhookActionResponse.success() };\n * });\n * ```\n */\n static exception(message?: string, exceptionClass?: string): WebhookActionExceptionResponse {\n const response: WebhookActionExceptionResponse = {\n op: WebhookActionOperation.EXCEPTION,\n };\n\n if (message !== undefined) {\n response.message = message;\n }\n if (exceptionClass !== undefined) {\n response.class = exceptionClass;\n }\n\n return response;\n }\n\n /**\n * Creates a response to add new data to the webhook payload.\n *\n * Use this method to inject additional data into the webhook payload that\n * will be processed by Adobe Commerce. The data is added at the specified\n * path using dot notation.\n *\n * @param path - Dot-notation path where the value should be added (e.g., 'order.items', 'customer.addresses')\n * @param value - The value to add at the specified path\n * @param instance - Optional instance identifier for tracking or reference purposes\n * @returns An add response object\n *\n * @example\n * ```typescript\n * const handler = WebhookAction.execute('enrich-order', [], [], async (params) => {\n * // Add loyalty points to the order\n * return {\n * statusCode: 200,\n * body: WebhookActionResponse.add(\n * 'order.loyalty',\n * { points: 150, tier: 'gold' },\n * params.order.id\n * )\n * };\n * });\n * ```\n */\n static add(path: string, value: any, instance?: string): WebhookActionAddResponse {\n const response: WebhookActionAddResponse = {\n op: WebhookActionOperation.ADD,\n path: path,\n value: value,\n };\n\n if (instance !== undefined) {\n response.instance = instance;\n }\n\n return response;\n }\n\n /**\n * Creates a response to replace existing data in the webhook payload.\n *\n * Use this method to modify existing fields in the webhook payload.\n * The existing value at the specified path will be replaced with the new value.\n *\n * @param path - Dot-notation path to the field that should be replaced (e.g., 'product.price', 'order.status')\n * @param value - The new value to replace the existing value\n * @param instance - Optional instance identifier for tracking or reference purposes\n * @returns A replace response object\n *\n * @example\n * ```typescript\n * const handler = WebhookAction.execute('adjust-price', [], [], async (params) => {\n * // Apply dynamic pricing\n * const newPrice = await calculateDiscountedPrice(params.product.price);\n *\n * return {\n * statusCode: 200,\n * body: WebhookActionResponse.replace(\n * 'product.price',\n * newPrice,\n * params.product.id\n * )\n * };\n * });\n * ```\n */\n static replace(path: string, value: any, instance?: string): WebhookActionReplaceResponse {\n const response: WebhookActionReplaceResponse = {\n op: WebhookActionOperation.REPLACE,\n path: path,\n value: value,\n };\n\n if (instance !== undefined) {\n response.instance = instance;\n }\n\n return response;\n }\n\n /**\n * Creates a response to remove data from the webhook payload.\n *\n * Use this method to remove fields from the webhook payload before it's\n * processed by Adobe Commerce. This is useful for filtering sensitive data\n * or removing unnecessary information.\n *\n * @param path - Dot-notation path to the field that should be removed (e.g., 'items.0', 'customer.internal_notes')\n * @returns A remove response object\n *\n * @example\n * ```typescript\n * const handler = WebhookAction.execute('sanitize-customer', [], [], async (params) => {\n * // Remove internal notes before processing\n * return {\n * statusCode: 200,\n * body: WebhookActionResponse.remove('customer.internal_notes')\n * };\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Remove an item from an array\n * return {\n * statusCode: 200,\n * body: WebhookActionResponse.remove('order.items.2')\n * };\n * ```\n */\n static remove(path: string): WebhookActionRemoveResponse {\n return {\n op: WebhookActionOperation.REMOVE,\n path: path,\n };\n }\n}\n\nexport default WebhookActionResponse;\n","/**\n * <license header>\n */\n\n/**\n * Signature verification options for webhook requests\n */\nexport enum SignatureVerification {\n /** Signature verification is enabled */\n ENABLED = 'enabled',\n /** Signature verification is disabled */\n DISABLED = 'disabled',\n}\n","/**\n * <license header>\n */\n\nimport RuntimeAction from '../runtime-action';\nimport RuntimeActionResponse from '../runtime-action/response';\nimport WebhookActionResponse from './response';\nimport { HttpMethod } from '../runtime-action/types';\nimport { RuntimeActionResponseType } from '../runtime-action/response/types';\nimport { WebhookActionResponseType } from './response/types';\nimport { SignatureVerification } from './types';\nimport crypto from 'crypto';\nimport Validator from '../runtime-action/validator';\n\n/**\n * WebhookAction - Wrapper for RuntimeAction with webhook-specific functionality.\n *\n * Handles Adobe Commerce webhook requests with automatic signature verification,\n * parameter validation, and response formatting.\n */\nclass WebhookAction {\n /**\n * Execute a webhook action with validation and response handling.\n *\n * @param name - Name of the webhook action\n * @param requiredParams - Required parameters in the webhook payload\n * @param requiredHeaders - Required headers (e.g., signature headers)\n * @param signatureVerification - Enable/disable signature verification\n * @param action - Webhook action function returning WebhookActionResponse\n * @returns Function that handles the webhook HTTP request\n */\n static execute(\n name: string = 'webhook',\n requiredParams: string[] = [],\n requiredHeaders: string[] = [],\n signatureVerification: SignatureVerification = SignatureVerification.DISABLED,\n action: (\n params: { [key: string]: any },\n ctx: { logger: any; headers: { [key: string]: any } }\n ) => Promise<\n WebhookActionResponseType | WebhookActionResponseType[]\n > = async (): Promise<WebhookActionResponseType> => WebhookActionResponse.success()\n ): (params: { [key: string]: any }) => Promise<RuntimeActionResponseType> {\n // Webhooks typically use POST method\n const httpMethods: HttpMethod[] = [HttpMethod.POST];\n\n // Verify webhook signature using a public key and SHA256.\n const verifySignature = async (params: { [key: string]: any }): Promise<string | null> => {\n const signature = params.__ow_headers['x-adobe-commerce-webhook-signature'] || '';\n if (!signature) {\n return 'Header `x-adobe-commerce-webhook-signature` not found. Make sure Webhooks signature is enabled in the Commerce instance.';\n }\n\n const body = params.__ow_body;\n if (!body) {\n return 'Request body not found. Make sure the action is configured with `raw-http: true`.';\n }\n\n let publicKey = params.PUBLIC_KEY;\n if (!publicKey && params.PUBLIC_KEY_BASE64) {\n publicKey = atob(params.PUBLIC_KEY_BASE64);\n }\n\n if (!publicKey) {\n return 'Public key not found. Make sure the action is configured with the input `PUBLIC_KEY` or `PUBLIC_KEY_BASE64` and it is defined in .env file.';\n }\n\n try {\n const verifier = crypto.createVerify('SHA256');\n verifier.update(body);\n const isSignatureValid = verifier.verify(publicKey, signature, 'base64');\n\n if (!isSignatureValid) {\n return 'The signature is invalid.';\n }\n } catch (error) {\n return 'The signature is invalid.';\n }\n return null;\n };\n\n // Create a callback that wraps the webhook action response\n const callback = async (\n params: { [key: string]: any },\n ctx: { logger: any; headers: { [key: string]: any } }\n ): Promise<RuntimeActionResponseType> => {\n const { logger } = ctx;\n\n if (signatureVerification === SignatureVerification.ENABLED) {\n const verificationErrorMessage = await verifySignature(params);\n if (verificationErrorMessage) {\n logger.error({\n message: `${name}-signature-verification-failed`,\n error: verificationErrorMessage,\n });\n const verificationErrorResponse =\n WebhookActionResponse.exception(verificationErrorMessage);\n return RuntimeActionResponse.success(JSON.stringify(verificationErrorResponse));\n }\n\n params = {\n ...params,\n ...JSON.parse(atob(params.__ow_body)),\n };\n }\n\n // check for missing request input parameters and headers\n const errorMessage =\n Validator.checkMissingRequestInputs(params, requiredParams, requiredHeaders) ?? '';\n if (errorMessage) {\n logger.error({\n message: `${name}-validation-failed`,\n error: errorMessage,\n });\n const errorMessageResponse = WebhookActionResponse.exception(errorMessage);\n return RuntimeActionResponse.success(JSON.stringify(errorMessageResponse));\n }\n\n // Execute the webhook action\n const response = await action(params, ctx);\n\n // Wrap the webhook response in a successful HTTP response\n return RuntimeActionResponse.success(JSON.stringify(response));\n };\n\n // Delegate to RuntimeAction with webhook-specific defaults\n // Set action type to 'webhook-action' for proper logging identification\n RuntimeAction.setActionType('webhook-action');\n return RuntimeAction.execute(name, httpMethods, [], [], callback);\n }\n}\n\nexport default WebhookAction;\n","/**\n * <license header>\n */\n\nimport { State } from '@adobe/aio-sdk';\n\nimport AdobeAuth from '../../commerce/adobe-auth';\nimport BearerToken from '../../integration/bearer-token';\nimport CustomLogger from '../custom-logger';\nimport { ImsTokenResult } from './types';\n\n/**\n * ImsToken for Adobe IMS Token Management\n *\n * @deprecated This class is deprecated due to issues with the built-in caching mechanism.\n *\n * **Deprecation Reasons:**\n * - The internal caching mechanism relies on Adobe I/O Runtime State API which has reliability issues\n * - Token caching should be managed at the application level for better control and flexibility\n * - The State API may not be available in all runtime environments\n * - TTL buffer calculations (10-minute buffer) are opinionated and may not suit all use cases\n *\n * **Migration Path:**\n * Use `AdobeAuth` class directly and implement caching in your application:\n *\n * @example\n * ```typescript\n * // OLD (Deprecated) - ImsToken with built-in caching\n * const imsToken = new ImsToken(\n * 'client-id',\n * 'client-secret',\n * 'tech-account-id',\n * 'tech@example.com',\n * 'org-id',\n * ['openid', 'AdobeID']\n * );\n * const token = await imsToken.execute();\n *\n * // NEW (Recommended) - AdobeAuth with application-level caching\n * import AdobeAuth from '../../commerce/adobe-auth';\n * import BearerToken from '../../integration/bearer-token';\n *\n * // Check your application cache first\n * let token = await yourAppCache.get('ims_token');\n *\n * if (!token || !BearerToken.info(token).isValid) {\n * // Generate new token using AdobeAuth\n * token = await AdobeAuth.getToken(\n * 'client-id',\n * 'client-secret',\n * 'tech-account-id',\n * 'tech@example.com',\n * 'org-id',\n * ['openid', 'AdobeID'],\n * 'your-context' // optional\n * );\n *\n * // Store in your application cache with appropriate TTL\n * const tokenInfo = BearerToken.info(token);\n * if (tokenInfo.isValid && tokenInfo.timeUntilExpiry) {\n * const ttl = Math.floor(tokenInfo.timeUntilExpiry / 1000) - 600; // 10-min buffer\n * await yourAppCache.set('ims_token', token, ttl);\n * }\n * }\n *\n * // Use the token\n * console.log('Token:', token);\n * ```\n *\n * **Benefits of Using AdobeAuth Directly:**\n * - Full control over caching strategy (Redis, Memcached, in-memory, etc.)\n * - Better error handling and retry logic\n * - Easier to test and mock\n * - No dependency on Adobe I/O Runtime State API\n * - More flexible TTL management based on your application needs\n *\n * This class handles Adobe IMS (Identity Management System) token operations\n * for authenticating API requests to Adobe services.\n */\nclass ImsToken {\n /** OAuth client ID for Adobe IMS authentication */\n private readonly clientId: string;\n\n /** OAuth client secret for Adobe IMS authentication */\n private readonly clientSecret: string;\n\n /** Technical account ID for service-to-service authentication */\n private readonly technicalAccountId: string;\n\n /** Technical account email for service-to-service authentication */\n private readonly technicalAccountEmail: string;\n\n /** IMS organization ID */\n private readonly imsOrgId: string;\n\n /** Array of scopes required for the token */\n private readonly scopes: Array<string>;\n\n /** Custom logger instance for logging operations */\n private readonly customLogger: CustomLogger;\n\n /** State property for managing token state */\n private state: any | undefined = undefined;\n\n /** Optional token context for additional authentication parameters */\n private readonly tokenContext: string;\n\n /** Key for storing token in state (State API only available in Adobe I/O Runtime) */\n private readonly key: string;\n\n /**\n * Creates an instance of ImsToken\n *\n * @deprecated Use `AdobeAuth.getToken()` directly and implement caching in your application.\n * See class documentation for migration examples.\n *\n * @param clientId - OAuth client ID for Adobe IMS authentication\n * @param clientSecret - OAuth client secret for Adobe IMS authentication\n * @param technicalAccountId - Technical account ID for service-to-service authentication\n * @param technicalAccountEmail - Technical account email for service-to-service authentication\n * @param imsOrgId - IMS organization ID\n * @param scopes - Array of scopes required for the token\n * @param logger - Optional logger instance for logging operations\n * @param cacheKey - Optional custom cache key for token storage (defaults to 'runtime_api_gateway_token')\n * @param tokenContext - Optional token context for authentication (defaults to 'runtime-api-gateway-context')\n */\n constructor(\n clientId: string,\n clientSecret: string,\n technicalAccountId: string,\n technicalAccountEmail: string,\n imsOrgId: string,\n scopes: Array<string>,\n logger: any = null,\n cacheKey?: string,\n tokenContext?: string\n ) {\n this.clientId = clientId;\n this.clientSecret = clientSecret;\n this.technicalAccountId = technicalAccountId;\n this.technicalAccountEmail = technicalAccountEmail;\n this.imsOrgId = imsOrgId;\n this.scopes = scopes;\n this.customLogger = new CustomLogger(logger);\n this.key = cacheKey || 'ims_token';\n this.tokenContext = tokenContext || 'ims-context';\n }\n\n /**\n * Executes IMS token generation or retrieves a cached token\n *\n * @deprecated Use `AdobeAuth.getToken()` directly and implement caching in your application.\n * The built-in caching mechanism has reliability issues with the State API.\n * See class documentation for migration examples.\n *\n * This method first checks for a cached token. If a valid cached token exists,\n * it returns that. Otherwise, it generates a new token, caches it, and returns it.\n *\n * @returns A promise that resolves to the IMS token string or null if generation fails\n * @example\n * ```typescript\n * const token = await imsToken.execute();\n * if (token) {\n * console.log('Token obtained:', token);\n * }\n * ```\n */\n async execute(): Promise<string | null> {\n try {\n this.customLogger.info('Starting IMS token generation/retrieval process');\n\n const currentValue = await this.getValue();\n if (currentValue !== null) {\n this.customLogger.info('Found cached IMS token, returning cached value');\n return currentValue;\n }\n\n this.customLogger.info('No cached token found, generating new IMS token');\n\n let result: ImsTokenResult = {\n token: null,\n expire_in: 86399, // Default fallback, will be overridden by actual token expiry\n };\n\n const response = await this.getImsToken();\n if (response !== null) {\n result = response;\n }\n\n if (result.token !== null) {\n this.customLogger.info(`Generated new IMS token, caching for ${result.expire_in} seconds`);\n await this.setValue(result);\n }\n\n return result.token;\n } catch (error: any) {\n this.customLogger.error(`Failed to execute IMS token generation: ${error.message}`);\n return null;\n }\n }\n\n /**\n * Generates a new IMS token from Adobe IMS service\n *\n * @returns A promise that resolves to ImsTokenResult or null if generation fails\n * @private\n */\n async getImsToken(): Promise<ImsTokenResult | null> {\n try {\n this.customLogger.debug(`Calling AdobeAuth.getToken with context: ${this.tokenContext}`);\n\n const token = await AdobeAuth.getToken(\n this.clientId,\n this.clientSecret,\n this.technicalAccountId,\n this.technicalAccountEmail,\n this.imsOrgId,\n this.scopes,\n this.tokenContext\n );\n\n if (token !== null && token !== undefined) {\n this.customLogger.debug('Received token from AdobeAuth, parsing with BearerToken.info');\n\n // Use BearerToken.info to extract actual expiration from JWT token\n const tokenInfo = BearerToken.info(token);\n\n if (!tokenInfo.isValid) {\n this.customLogger.error('Received invalid or expired token from IMS');\n return null;\n }\n\n // Calculate expire_in from timeUntilExpiry (convert milliseconds to seconds)\n const expireInSeconds = tokenInfo.timeUntilExpiry\n ? Math.floor(tokenInfo.timeUntilExpiry / 1000)\n : 86399; // Fallback to 24 hours if unable to determine\n\n this.customLogger.debug(`Token expires in ${expireInSeconds} seconds`);\n\n return {\n token: token,\n expire_in: expireInSeconds,\n };\n }\n\n this.customLogger.error('Received null or undefined token from IMS');\n return null;\n } catch (error: any) {\n this.customLogger.error(`Failed to get IMS token: ${error.message}`);\n return null;\n }\n }\n\n /**\n * Caches the IMS token in the state store with TTL\n *\n * @deprecated This method has issues with State API reliability. Use application-level caching instead.\n *\n * **Known Issues:**\n * - State API may not be available in all runtime environments\n * - Hard-coded 10-minute buffer may not suit all use cases\n * - Minimum 60-minute TTL is opinionated and inflexible\n * - No retry mechanism for State API failures\n *\n * @param result - The token result containing the token and expiration time\n * @returns A promise that resolves to true if caching succeeded, false otherwise\n * @private\n */\n async setValue(result: ImsTokenResult): Promise<boolean> {\n try {\n const state = await this.getState();\n if (state === null) {\n this.customLogger.info('State API not available, skipping token caching');\n // State API not available, skip caching\n return true; // Return true since token generation succeeded\n }\n\n // Apply 10-minute buffer (600 seconds) to prevent token expiry during usage\n const ttlWithBuffer = Math.max(result.expire_in - 600, 3600); // Minimum 60 minutes TTL\n\n this.customLogger.debug(\n `Caching IMS token with TTL: ${ttlWithBuffer} seconds (original: ${result.expire_in})`\n );\n\n await state.put(this.key, result.token, { ttl: ttlWithBuffer });\n return true;\n } catch (error: any) {\n this.customLogger.error(`Failed to cache IMS token: ${error.message}`);\n return true; // Return true since token generation succeeded\n }\n }\n\n /**\n * Retrieves a cached IMS token from the state store\n *\n * @deprecated This method has issues with State API reliability. Use application-level caching instead.\n *\n * **Known Issues:**\n * - State API may not be available in all runtime environments\n * - No validation of cached token expiry\n * - Silent failures may return null without proper error context\n *\n * @returns A promise that resolves to the cached token string or null if not found\n * @private\n */\n async getValue(): Promise<string | null> {\n try {\n this.customLogger.debug('Checking for cached IMS token');\n\n const state = await this.getState();\n if (state === null) {\n this.customLogger.debug('State API not available, cannot retrieve cached token');\n // State API not available, skip caching\n return null;\n }\n\n const value = await state.get(this.key);\n if (value !== undefined && value.value) {\n this.customLogger.debug('Found cached IMS token');\n return value.value;\n }\n\n this.customLogger.debug('No cached IMS token found');\n } catch (error: any) {\n this.customLogger.error(`Failed to retrieve cached IMS token: ${error.message}`);\n }\n\n return null;\n }\n\n /**\n * Initializes and returns the state store instance\n *\n * @deprecated This method relies on State API which has reliability issues.\n * Use application-level caching instead.\n *\n * **Known Issues:**\n * - State API initialization may fail silently\n * - Not available outside Adobe I/O Runtime environments\n * - Caches the state instance which may become stale\n *\n * @returns A promise that resolves to the state instance or null if initialization fails\n * @private\n */\n async getState(): Promise<any> {\n if (this.state === undefined) {\n try {\n this.customLogger.debug('Initializing State API for token caching');\n this.state = await State.init();\n } catch (error: any) {\n this.customLogger.error(`Failed to initialize State API: ${error.message}`);\n this.state = null;\n }\n }\n return this.state;\n }\n}\n\nexport default ImsToken;\n","/**\n * <license header>\n */\n\nimport { context, getToken } from '@adobe/aio-lib-ims';\nimport { AdobeIMSConfig } from './types';\n\n/**\n * Class providing authentication functionality for Adobe IMS (Identity Management System)\n */\nclass AdobeAuth {\n /**\n * Retrieves an authentication token from Adobe IMS\n *\n * @param clientId - The client ID for the Adobe IMS integration\n * @param clientSecret - The client secret for the Adobe IMS integration\n * @param technicalAccountId - The technical account ID for the Adobe IMS integration\n * @param technicalAccountEmail - The technical account email for the Adobe IMS integration\n * @param imsOrgId - The IMS organization ID\n * @param scopes - Array of permission scopes to request for the token\n * @param currentContext - The context name for storing the configuration (defaults to 'onboarding-config')\n * @returns Promise<string> - A promise that resolves to the authentication token\n *\n * @example\n * const token = await AdobeAuth.getToken(\n * 'your-client-id',\n * 'your-client-secret',\n * 'your-technical-account-id',\n * 'your-technical-account-email',\n * 'your-ims-org-id',\n * ['AdobeID', 'openid', 'adobeio_api']\n * );\n */\n static async getToken(\n clientId: string,\n clientSecret: string,\n technicalAccountId: string,\n technicalAccountEmail: string,\n imsOrgId: string,\n scopes: string[],\n currentContext: string = 'onboarding-config'\n ): Promise<string> {\n const config: AdobeIMSConfig = {\n client_id: clientId,\n client_secrets: [clientSecret],\n technical_account_id: technicalAccountId,\n technical_account_email: technicalAccountEmail,\n ims_org_id: imsOrgId,\n scopes: scopes,\n };\n\n await context.setCurrent(currentContext);\n await context.set(currentContext, config);\n\n return await getToken();\n }\n}\n\nexport default AdobeAuth;\n","/**\n * <license header>\n */\n\nimport type { BearerTokenInfo } from './types';\n\n/**\n * Utility class for extracting and handling Bearer tokens from HTTP request headers.\n * Supports both standard HTTP headers and OpenWhisk action parameter formats for maximum portability.\n */\nclass BearerToken {\n /**\n * Extracts the Bearer token from HTTP request headers and returns detailed token information.\n * Supports both standard HTTP headers and OpenWhisk action parameter formats.\n *\n * @param headersOrParams - Either a standard headers object or OpenWhisk action parameters\n * @returns Detailed token information object\n *\n * @example\n * // Standard HTTP headers approach\n * const headers = {\n * authorization: 'Bearer abc123token'\n * };\n * const tokenInfo = BearerToken.extract(headers);\n *\n * @example\n * // OpenWhisk action parameters (backward compatibility)\n * const params = {\n * __ow_headers: {\n * authorization: 'Bearer abc123token'\n * }\n * };\n * const tokenInfo = BearerToken.extract(params);\n *\n * @example\n * // Both return the same result:\n * // {\n * // token: 'abc123token',\n * // tokenLength: 11,\n * // isValid: true,\n * // expiry: '2024-01-01T12:00:00.000Z',\n * // timeUntilExpiry: 3600000\n * // }\n */\n static extract(headersOrParams: { [key: string]: any }): BearerTokenInfo {\n let token: string | null = null;\n\n // Try standard headers approach first (more portable)\n if (headersOrParams.authorization?.startsWith('Bearer ')) {\n token = headersOrParams.authorization.substring('Bearer '.length);\n }\n // Fall back to OpenWhisk format for backward compatibility\n else if (headersOrParams.__ow_headers?.authorization?.startsWith('Bearer ')) {\n token = headersOrParams.__ow_headers.authorization.substring('Bearer '.length);\n }\n\n return BearerToken.info(token);\n }\n\n /**\n * Analyzes a Bearer token and returns detailed information including validity and expiry.\n * Supports both JWT tokens (with automatic expiry detection) and plain tokens (24h default expiry).\n *\n * @param token - The Bearer token string (or null). Can be JWT or plain token.\n * @returns Detailed token information object\n *\n * @example\n * // Plain token (gets 24h default expiry)\n * const plainTokenInfo = BearerToken.info('abc123token');\n * // returns: {\n * // token: 'abc123token',\n * // tokenLength: 11,\n * // isValid: true,\n * // expiry: '2024-01-02T12:00:00.000Z', // 24h from now\n * // timeUntilExpiry: 86400000 // milliseconds until expiry\n * // }\n *\n * @example\n * // JWT token (automatic expiry detection from 'exp' or 'expires_in' claims)\n * const jwtToken = 'eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MDQ0Njc2MDB9.signature';\n * const jwtTokenInfo = BearerToken.info(jwtToken);\n * // returns: {\n * // token: 'eyJhbGciOiJIUzI1NiJ9...',\n * // tokenLength: 45,\n * // isValid: true, // false if expired\n * // expiry: '2024-01-05T12:00:00.000Z', // from JWT exp claim\n * // timeUntilExpiry: 172800000 // actual time until expiry\n * // }\n *\n * @example\n * // Null or invalid token\n * const nullTokenInfo = BearerToken.info(null);\n * // returns: {\n * // token: null,\n * // tokenLength: 0,\n * // isValid: false,\n * // expiry: null,\n * // timeUntilExpiry: null\n * // }\n */\n static info(token: string | null): BearerTokenInfo {\n const tokenExpiry = BearerToken._calculateExpiry(token);\n\n return {\n token: token,\n tokenLength: token ? token.length : 0,\n isValid: BearerToken._isTokenValid(token, tokenExpiry),\n expiry: tokenExpiry ? tokenExpiry.toISOString() : null,\n timeUntilExpiry: tokenExpiry ? Math.max(0, tokenExpiry.getTime() - Date.now()) : null,\n };\n }\n\n /**\n * Checks if the given token is valid and not expired\n * @private\n * @param token - The bearer token string\n * @param tokenExpiry - The token expiry date\n * @returns {boolean} True if token is valid\n */\n private static _isTokenValid(token: string | null, tokenExpiry: Date | null): boolean {\n if (!token) {\n return false;\n }\n\n if (tokenExpiry && Date.now() >= tokenExpiry.getTime()) {\n console.log('⏰ Token has expired');\n return false;\n }\n\n return true;\n }\n\n /**\n * Calculates token expiry from JWT token or uses default for non-JWT tokens\n * @private\n * @param token - The token string (JWT or plain token)\n * @returns Date object representing token expiry\n */\n private static _calculateExpiry(token: string | null): Date | null {\n // Handle empty tokens\n if (!token) {\n return null;\n }\n\n try {\n // Try to parse as JWT token\n const parts = token.split('.');\n if (parts.length === 3) {\n const payload = JSON.parse(Buffer.from(parts[1] || '', 'base64').toString());\n\n if (payload.expires_in) {\n // expires_in is in milliseconds\n return new Date(Date.now() + parseInt(payload.expires_in));\n }\n\n if (payload.exp) {\n // exp is Unix timestamp in seconds\n return new Date(payload.exp * 1000);\n }\n }\n\n // For non-JWT tokens or JWT tokens without expiry, default to 24 hours\n return new Date(Date.now() + 24 * 60 * 60 * 1000);\n } catch (error) {\n console.warn('[WARN] Could not parse token expiry, using default 24h');\n return new Date(Date.now() + 24 * 60 * 60 * 1000);\n }\n }\n}\n\nexport default BearerToken;\nexport type { BearerTokenInfo } from './types';\n","/**\n * <license header>\n */\n\nimport fetch, { RequestInit, Response } from 'node-fetch';\nimport { Headers } from './types';\n\nclass RestClient {\n /**\n * A completely raw method to make HTTP requests\n *\n * @param endpoint\n * @param method\n * @param headers\n * @param payload\n * @returns {Promise<Response>}\n */\n async makeRequest(\n endpoint: string,\n method: string = 'GET',\n headers: Headers = {},\n payload: any = null\n ): Promise<Response> {\n let options: RequestInit = {\n method: method,\n headers: headers,\n };\n\n if (payload !== null) {\n let body: any;\n let contentType: string | undefined;\n\n // Handle different payload types\n if (payload instanceof URLSearchParams) {\n // Form-encoded data\n body = payload.toString();\n contentType = headers['Content-Type'] || 'application/x-www-form-urlencoded';\n } else if (typeof FormData !== 'undefined' && payload instanceof FormData) {\n // Multipart form data - let browser set Content-Type with boundary\n body = payload;\n contentType = headers['Content-Type']; // Don't set default, browser handles this\n } else if (typeof payload === 'string') {\n // String payloads (text, XML, etc.)\n body = payload;\n contentType = headers['Content-Type'] || 'text/plain';\n } else if (\n payload instanceof Buffer ||\n payload instanceof ArrayBuffer ||\n (typeof Uint8Array !== 'undefined' && payload instanceof Uint8Array)\n ) {\n // Binary data\n body = payload;\n contentType = headers['Content-Type'] || 'application/octet-stream';\n } else {\n // Regular objects/primitives as JSON\n body = JSON.stringify(payload);\n contentType = headers['Content-Type'] || 'application/json';\n }\n\n // Build options with appropriate headers\n const requestHeaders = { ...headers };\n if (contentType) {\n requestHeaders['Content-Type'] = contentType;\n }\n\n options = {\n ...options,\n body,\n headers: requestHeaders,\n };\n }\n\n return await fetch(endpoint, options);\n }\n\n /**\n * A method to parse HTTP response\n *\n * @param response\n * @returns {Promise<any>}\n */\n async parseResponse(response: Response): Promise<any> {\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n // Handle responses with no content (like 204 No Content)\n if (response.status === 204 || response.headers?.get('content-length') === '0') {\n return null;\n }\n\n // Try JSON first (for both real responses and mocked responses)\n if (typeof response.json === 'function') {\n const contentType = response.headers?.get('content-type');\n // If no content-type header (mocked response) or JSON content-type, parse as JSON\n if (\n !contentType ||\n contentType.includes('application/json') ||\n contentType.includes('application/hal+json')\n ) {\n return await response.json();\n }\n }\n\n // For non-JSON responses, return text\n if (typeof response.text === 'function') {\n const text = await response.text();\n return text;\n }\n\n // Fallback for responses without text/json methods\n return null;\n }\n\n /**\n * A generic method to make GET rest call\n *\n * @param endpoint\n * @param headers\n * @param parsed\n * @returns {Promise<Response | any>}\n */\n async get(\n endpoint: string,\n headers: Headers = {},\n parsed: boolean = true\n ): Promise<Response | any> {\n const response = await this.makeRequest(endpoint, 'GET', headers);\n return parsed ? await this.parseResponse(response) : response;\n }\n\n /**\n * A generic method to make POST rest call\n *\n * @param endpoint\n * @param headers\n * @param payload\n * @param parsed\n * @returns {Promise<Response | any>}\n */\n async post(\n endpoint: string,\n headers: Headers = {},\n payload: any = null,\n parsed: boolean = true\n ): Promise<Response | any> {\n const response = await this.makeRequest(endpoint, 'POST', headers, payload);\n return parsed ? await this.parseResponse(response) : response;\n }\n\n /**\n * A generic method to make PUT rest call\n *\n * @param endpoint\n * @param headers\n * @param payload\n * @param parsed\n * @returns {Promise<Response | any>}\n */\n async put(\n endpoint: string,\n headers: Headers = {},\n payload: any = null,\n parsed: boolean = true\n ): Promise<Response | any> {\n const response = await this.makeRequest(endpoint, 'PUT', headers, payload);\n return parsed ? await this.parseResponse(response) : response;\n }\n\n /**\n * A generic method to make DELETE rest call\n *\n * @param endpoint\n * @param headers\n * @param parsed\n * @returns {Promise<Response | any>}\n */\n async delete(\n endpoint: string,\n headers: Headers = {},\n parsed: boolean = true\n ): Promise<Response | any> {\n const response = await this.makeRequest(endpoint, 'DELETE', headers);\n return parsed ? await this.parseResponse(response) : response;\n }\n\n /**\n * A generic method to make rest call\n *\n * @param endpoint\n * @param method\n * @param headers\n * @param payload\n * @returns {Promise<any>}\n * @deprecated Use makeRequest() and parseResponse() methods instead\n */\n async apiCall(\n endpoint: string,\n method: string = 'POST',\n headers: Headers = {},\n payload: any = null\n ): Promise<any> {\n let options: RequestInit = {\n method: method,\n headers: headers,\n };\n\n if (payload !== null) {\n options = {\n ...options,\n body: JSON.stringify(payload),\n headers: {\n ...headers,\n 'Content-Type': 'application/json',\n },\n };\n }\n\n const response: Response = await fetch(endpoint, options);\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n // Handle responses with no content (like 204 No Content)\n if (response.status === 204 || response.headers?.get('content-length') === '0') {\n return null;\n }\n\n // Try JSON first (for both real responses and mocked responses)\n if (typeof response.json === 'function') {\n const contentType = response.headers?.get('content-type');\n // If no content-type header (mocked response) or JSON content-type, parse as JSON\n if (\n !contentType ||\n contentType.includes('application/json') ||\n contentType.includes('application/hal+json')\n ) {\n return await response.json();\n }\n }\n\n // For non-JSON responses, return text\n if (typeof response.text === 'function') {\n const text = await response.text();\n return text;\n }\n\n // Fallback for responses without text/json methods\n return null;\n }\n}\n\nexport default RestClient;\n","/**\n * <license header>\n */\n\nimport RestClient from '../../integration/rest-client';\nimport CustomLogger from '../custom-logger';\n\n/**\n * RuntimeApiGatewayService for Adobe Runtime API Gateway\n *\n * This service provides a flexible way to interact with Adobe I/O Runtime API Gateway\n * endpoints with authentication and authorization support.\n *\n * Key Features:\n * - Built-in authentication headers\n * - Centralized error handling\n * - Support for common HTTP methods (GET, POST, PUT, DELETE)\n *\n * @example\n * ```typescript\n * const service = new RuntimeApiGatewayService(\n * 'test-namespace',\n * 'org-id@AdobeOrg',\n * 'bearer-token-string',\n * logger\n * );\n *\n * // GET request\n * const data = await service.get('v1/my-endpoint', { 'Custom-Header': 'value' });\n * ```\n */\nexport class RuntimeApiGatewayService {\n /** Base URL for the Adobe I/O Runtime APIs */\n private static readonly BASE_URL = 'https://adobeioruntime.net/apis';\n\n /** The namespace identifier for the Adobe I/O Runtime actions */\n private readonly namespace: string;\n\n /** IMS organization ID */\n private readonly imsOrgId: string;\n\n /** Bearer token for authentication */\n private readonly imsToken: string;\n\n /** RestClient instance for making HTTP requests */\n private readonly restClient: RestClient;\n\n /** CustomLogger instance for logging */\n private readonly customLogger: CustomLogger;\n\n /**\n * Creates an instance of RuntimeApiGatewayService\n *\n * @param namespace - The Adobe I/O Runtime namespace identifier\n * @param imsOrgId - IMS organization ID\n * @param imsToken - Bearer token string for authentication\n * @param logger - Optional logger instance for logging operations\n * @example\n * ```typescript\n * const service = new RuntimeApiGatewayService(\n * 'test-namespace',\n * 'org-id@AdobeOrg',\n * 'bearer-token-string',\n * logger\n * );\n * ```\n */\n constructor(namespace: string, imsOrgId: string, imsToken: string, logger: any = null) {\n this.namespace = namespace;\n this.imsOrgId = imsOrgId;\n this.imsToken = imsToken;\n this.restClient = new RestClient();\n this.customLogger = new CustomLogger(logger);\n }\n\n /**\n * Builds the complete API endpoint URL\n *\n * @param endpoint - API endpoint path (e.g., 'v1/my-endpoint')\n * @returns The fully constructed endpoint URL\n * @private\n */\n private buildEndpoint(endpoint: string): string {\n return `${RuntimeApiGatewayService.BASE_URL}/${this.namespace}/${endpoint}`;\n }\n\n /**\n * Gets the authenticated headers for API requests\n *\n * @returns Headers object including authentication\n * @private\n */\n private getAuthenticatedHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.imsToken}`,\n 'x-gw-ims-org-id': this.imsOrgId,\n };\n }\n\n /**\n * Performs a GET request to the Runtime API Gateway\n *\n * @param endpoint - API endpoint path (e.g., 'v1/my-endpoint')\n * @param additionalHeaders - Optional additional headers to include in the request\n * @returns A promise that resolves with the API response data\n * @throws {Error} If the API request fails\n * @example\n * ```typescript\n * const service = new RuntimeApiGatewayService(...);\n * const data = await service.get('v1/my-endpoint');\n *\n * // With additional headers\n * const data = await service.get('v1/my-endpoint', { 'Custom-Header': 'value' });\n * ```\n */\n async get(endpoint: string, additionalHeaders: Record<string, string> = {}): Promise<any> {\n try {\n const url = this.buildEndpoint(endpoint);\n this.customLogger.info(`Performing GET request to: ${url}`);\n const headers = { ...this.getAuthenticatedHeaders(), ...additionalHeaders };\n this.customLogger.debug(`GET headers: ${JSON.stringify(headers)}`);\n\n const response = await this.restClient.get(url, headers, false);\n this.customLogger.debug(`GET response: ${JSON.stringify(response)}`);\n this.customLogger.info('GET request completed successfully');\n return response;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n this.customLogger.error(`GET request failed: ${errorMessage}`);\n throw new Error(`Runtime API gateway GET request failed: ${errorMessage}`);\n }\n }\n\n /**\n * Performs a POST request to the Runtime API Gateway\n *\n * @param endpoint - API endpoint path (e.g., 'v1/my-endpoint')\n * @param payload - The data to send in the request body\n * @param additionalHeaders - Optional additional headers to include in the request\n * @returns A promise that resolves with the API response data\n * @throws {Error} If the API request fails\n * @example\n * ```typescript\n * const service = new RuntimeApiGatewayService(...);\n * const result = await service.post('v1/my-endpoint', { key: 'value' });\n *\n * // With additional headers\n * const result = await service.post('v1/my-endpoint', { key: 'value' }, { 'Custom-Header': 'value' });\n * ```\n */\n async post(\n endpoint: string,\n payload: any,\n additionalHeaders: Record<string, string> = {}\n ): Promise<any> {\n try {\n const url = this.buildEndpoint(endpoint);\n this.customLogger.info(`Performing POST request to: ${url}`);\n this.customLogger.debug(`POST payload: ${JSON.stringify(payload)}`);\n const headers = { ...this.getAuthenticatedHeaders(), ...additionalHeaders };\n this.customLogger.debug(`POST headers: ${JSON.stringify(headers)}`);\n\n const response = await this.restClient.post(url, headers, payload, false);\n this.customLogger.debug(`POST response: ${JSON.stringify(response)}`);\n this.customLogger.info('POST request completed successfully');\n return response;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n this.customLogger.error(`POST request failed: ${errorMessage}`);\n throw new Error(`Runtime API gateway POST request failed: ${errorMessage}`);\n }\n }\n\n /**\n * Performs a PUT request to the Runtime API Gateway\n *\n * @param endpoint - API endpoint path (e.g., 'v1/my-endpoint')\n * @param payload - The data to send in the request body\n * @param additionalHeaders - Optional additional headers to include in the request\n * @returns A promise that resolves with the API response data\n * @throws {Error} If the API request fails\n * @example\n * ```typescript\n * const service = new RuntimeApiGatewayService(...);\n * const updated = await service.put('v1/my-endpoint', { id: 1, name: 'updated' });\n *\n * // With additional headers\n * const updated = await service.put('v1/my-endpoint', { id: 1 }, { 'Custom-Header': 'value' });\n * ```\n */\n async put(\n endpoint: string,\n payload: any,\n additionalHeaders: Record<string, string> = {}\n ): Promise<any> {\n try {\n const url = this.buildEndpoint(endpoint);\n this.customLogger.info(`Performing PUT request to: ${url}`);\n this.customLogger.debug(`PUT payload: ${JSON.stringify(payload)}`);\n const headers = { ...this.getAuthenticatedHeaders(), ...additionalHeaders };\n this.customLogger.debug(`PUT headers: ${JSON.stringify(headers)}`);\n\n const response = await this.restClient.put(url, headers, payload, false);\n this.customLogger.debug(`PUT response: ${JSON.stringify(response)}`);\n this.customLogger.info('PUT request completed successfully');\n return response;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n this.customLogger.error(`PUT request failed: ${errorMessage}`);\n throw new Error(`Runtime API gateway PUT request failed: ${errorMessage}`);\n }\n }\n\n /**\n * Performs a DELETE request to the Runtime API Gateway\n *\n * @param endpoint - API endpoint path (e.g., 'v1/my-endpoint')\n * @param additionalHeaders - Optional additional headers to include in the request\n * @returns A promise that resolves with the API response data\n * @throws {Error} If the API request fails\n * @example\n * ```typescript\n * const service = new RuntimeApiGatewayService(...);\n * const deleted = await service.delete('v1/my-endpoint');\n *\n * // With additional headers\n * const deleted = await service.delete('v1/my-endpoint', { 'Custom-Header': 'value' });\n * ```\n */\n async delete(endpoint: string, additionalHeaders: Record<string, string> = {}): Promise<any> {\n try {\n const url = this.buildEndpoint(endpoint);\n this.customLogger.info(`Performing DELETE request to: ${url}`);\n const headers = { ...this.getAuthenticatedHeaders(), ...additionalHeaders };\n this.customLogger.debug(`DELETE headers: ${JSON.stringify(headers)}`);\n\n const response = await this.restClient.delete(url, headers, false);\n this.customLogger.debug(`DELETE response: ${JSON.stringify(response)}`);\n this.customLogger.info('DELETE request completed successfully');\n return response;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n this.customLogger.error(`DELETE request failed: ${errorMessage}`);\n throw new Error(`Runtime API gateway DELETE request failed: ${errorMessage}`);\n }\n }\n}\n","/**\n * <license header>\n */\n\nimport { Core, Logger } from '@adobe/aio-sdk';\nimport type { OnboardEventsInput, OnboardEventsResponse, OnboardEventsSummary } from './types';\nimport CreateProviders from './create-providers';\nimport CreateEvents from './create-events';\nimport CreateRegistrations from './create-registrations';\nimport InputParser from './input-parser';\n\n/**\n * Utility class for handling onboarding events in Adobe Commerce integrations\n *\n * @example\n * const onboardEvents = new OnboardEvents(\n * 'My Adobe Commerce Project',\n * 'your-consumer-id',\n * 'your-project-id',\n * 'your-workspace-id',\n * 'your-api-key',\n * 'your-access-token'\n * );\n *\n * // Get the configured logger for consistent logging\n * const logger = onboardEvents.getLogger();\n * logger.info('Custom logging with the same configuration');\n *\n * // Process onboard events input\n * await onboardEvents.process({ providers });\n */\nclass OnboardEvents {\n private readonly logger: Logger;\n private readonly createProviders: CreateProviders;\n private readonly createEvents: CreateEvents;\n private readonly createRegistrations: CreateRegistrations;\n\n /**\n * Creates a new OnboardEvents instance\n *\n * @param projectName - Name of the Adobe Commerce project\n * @param consumerId - Adobe I/O consumer ID\n * @param projectId - Adobe I/O project ID\n * @param workspaceId - Adobe I/O workspace ID\n * @param apiKey - API key for authentication\n * @param accessToken - Access token for API calls\n */\n constructor(\n private readonly projectName: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly apiKey: string,\n private readonly accessToken: string\n ) {\n if (!projectName) {\n throw new Error('Project name is required');\n }\n\n if (!consumerId) {\n throw new Error('Consumer ID is required');\n }\n\n if (!projectId) {\n throw new Error('Project ID is required');\n }\n\n if (!workspaceId) {\n throw new Error('Workspace ID is required');\n }\n\n if (!apiKey) {\n throw new Error('API key is required');\n }\n\n if (!accessToken) {\n throw new Error('Access token is required');\n }\n\n // create a Logger using project name\n const loggerName = projectName\n .toLowerCase()\n .replace(/[^a-z0-9\\s-_]/g, '') // Remove special characters except spaces, hyphens, underscores\n .replace(/\\s+/g, '-') // Replace spaces with hyphens\n .replace(/_{2,}/g, '_') // Replace multiple underscores with single\n .replace(/-{2,}/g, '-') // Replace multiple hyphens with single\n .trim()\n .concat('-onboard-events'); // Add suffix to identify as onboard events logger\n this.logger = Core.Logger(loggerName, { level: 'debug' });\n\n // Initialize CreateProviders instance\n this.createProviders = new CreateProviders(\n consumerId,\n projectId,\n workspaceId,\n apiKey,\n accessToken,\n this.logger\n );\n\n // Initialize CreateEvents instance\n this.createEvents = new CreateEvents(\n consumerId,\n projectId,\n workspaceId,\n apiKey, // Using apiKey as clientId\n accessToken,\n this.logger\n );\n\n // Initialize CreateRegistrations instance\n this.createRegistrations = new CreateRegistrations(\n consumerId,\n projectId,\n workspaceId,\n apiKey, // Using apiKey as clientId\n accessToken,\n this.logger\n );\n }\n\n /**\n * Gets the configured logger instance for consistent logging\n *\n * @returns The configured logger instance\n */\n getLogger(): Logger {\n return this.logger;\n }\n\n /**\n * Processes the onboarding events\n *\n * @param input - Onboard events input configuration containing providers, registrations, and events\n * @returns Promise resolving to processing result with created providers\n */\n async process(input: OnboardEventsInput): Promise<OnboardEventsResponse> {\n this.logger.debug(\n `[START] Processing onboard events for project: ${this.projectName} (${this.projectId}) with ${input.providers.length} providers`\n );\n\n const inputParser = new InputParser(input);\n const entities = inputParser.getEntities();\n\n // Use CreateProviders to create the providers\n const providerResults = await this.createProviders.process(\n entities.providers,\n this.projectName\n );\n\n // Use CreateEvents to create the events\n const eventResults = await this.createEvents.process(\n entities.events,\n providerResults,\n this.projectName\n );\n\n // Use CreateRegistrations to create the registrations\n const registrationResults = await this.createRegistrations.process(\n entities.registrations,\n entities.events,\n providerResults,\n this.projectName\n );\n\n const response = {\n createdProviders: providerResults,\n createdEvents: eventResults,\n createdRegistrations: registrationResults,\n };\n\n // Generate and log comprehensive summary\n const summary = this.generateSummary(response);\n this.logSummary(summary);\n\n return response;\n }\n\n /**\n * Generates a concise summary of onboard events processing results\n * @private\n * @param response - The response from the onboard events processing\n * @returns A concise summary with IDs and status information\n */\n private generateSummary(response: OnboardEventsResponse): OnboardEventsSummary {\n // Process providers\n const providerItems = response.createdProviders.map(result => ({\n id: result.provider.id,\n key: result.provider.key,\n label: result.provider.label,\n status: result.created\n ? ('created' as const)\n : result.skipped\n ? ('existing' as const)\n : ('failed' as const),\n error: result.error,\n }));\n\n const providerCounts = {\n created: response.createdProviders.filter(r => r.created).length,\n existing: response.createdProviders.filter(r => r.skipped).length,\n failed: response.createdProviders.filter(r => !r.created && !r.skipped).length,\n total: response.createdProviders.length,\n };\n\n // Process events\n const eventItems = response.createdEvents.map(result => ({\n id: result.event.id,\n eventCode: result.event.eventCode,\n label: result.event.eventCode,\n status: result.created\n ? ('created' as const)\n : result.skipped\n ? ('existing' as const)\n : ('failed' as const),\n provider: result.provider?.key,\n error: result.error,\n }));\n\n const eventCounts = {\n created: response.createdEvents.filter(r => r.created).length,\n existing: response.createdEvents.filter(r => r.skipped).length,\n failed: response.createdEvents.filter(r => !r.created && !r.skipped).length,\n total: response.createdEvents.length,\n };\n\n // Process registrations\n const registrationItems = response.createdRegistrations.map(result => ({\n id: result.registration.id,\n key: result.registration.key,\n label: result.registration.label,\n status: result.created\n ? ('created' as const)\n : result.skipped\n ? ('existing' as const)\n : ('failed' as const),\n provider: result.provider?.key,\n error: result.error,\n }));\n\n const registrationCounts = {\n created: response.createdRegistrations.filter(r => r.created).length,\n existing: response.createdRegistrations.filter(r => r.skipped).length,\n failed: response.createdRegistrations.filter(r => !r.created && !r.skipped).length,\n total: response.createdRegistrations.length,\n };\n\n // Calculate overall totals\n const overall = {\n totalProcessed: providerCounts.total + eventCounts.total + registrationCounts.total,\n totalCreated: providerCounts.created + eventCounts.created + registrationCounts.created,\n totalExisting: providerCounts.existing + eventCounts.existing + registrationCounts.existing,\n totalFailed: providerCounts.failed + eventCounts.failed + registrationCounts.failed,\n };\n\n return {\n providers: {\n items: providerItems,\n counts: providerCounts,\n },\n events: {\n items: eventItems,\n counts: eventCounts,\n },\n registrations: {\n items: registrationItems,\n counts: registrationCounts,\n },\n overall,\n };\n }\n\n /**\n * Logs a formatted summary of onboard events processing results\n * @private\n * @param summary - The summary to log\n */\n private logSummary(summary: OnboardEventsSummary): void {\n this.logger.info('='.repeat(60));\n this.logger.info(`📊 ONBOARD EVENTS SUMMARY - ${this.projectName}`);\n this.logger.info('='.repeat(60));\n\n this.logger.info('');\n // Overall summary\n this.logger.info(\n `📈 OVERALL: ${summary.overall.totalProcessed} processed | ${summary.overall.totalCreated} created | ${summary.overall.totalExisting} existing | ${summary.overall.totalFailed} failed`\n );\n this.logger.info('');\n\n // Providers summary\n if (summary.providers.counts.total > 0) {\n this.logger.info(`🏭 PROVIDERS (${summary.providers.counts.total}):`);\n summary.providers.items.forEach(item => {\n const status = item.status === 'created' ? '✅' : item.status === 'existing' ? '⏭️' : '❌';\n const id = item.id ? ` [ID: ${item.id}]` : '';\n const error = item.error ? ` - Error: ${item.error}` : '';\n this.logger.info(` ${status} ${item.key} - ${item.label}${id}${error}`);\n });\n this.logger.info('');\n }\n\n // Events summary\n if (summary.events.counts.total > 0) {\n this.logger.info(`📅 EVENTS (${summary.events.counts.total}):`);\n summary.events.items.forEach(item => {\n const status = item.status === 'created' ? '✅' : item.status === 'existing' ? '⏭️' : '❌';\n const id = item.id ? ` [ID: ${item.id}]` : '';\n const provider = item.provider ? ` (Provider: ${item.provider})` : '';\n const error = item.error ? ` - Error: ${item.error}` : '';\n this.logger.info(` ${status} ${item.eventCode}${provider}${id}${error}`);\n });\n this.logger.info('');\n }\n\n // Registrations summary\n if (summary.registrations.counts.total > 0) {\n this.logger.info(`📋 REGISTRATIONS (${summary.registrations.counts.total}):`);\n summary.registrations.items.forEach(item => {\n const status = item.status === 'created' ? '✅' : item.status === 'existing' ? '⏭️' : '❌';\n const id = item.id ? ` [ID: ${item.id}]` : '';\n const provider = item.provider ? ` (Provider: ${item.provider})` : '';\n const error = item.error ? ` - Error: ${item.error}` : '';\n this.logger.info(` ${status} ${item.key} - ${item.label}${provider}${id}${error}`);\n });\n this.logger.info('');\n }\n\n this.logger.info('='.repeat(60));\n }\n}\n\nexport default OnboardEvents;\n","/**\n * <license header>\n */\n\n/**\n * Adobe I/O Events global constants\n */\nexport const IoEventsGlobals = {\n BASE_URL: 'https://api.adobe.io',\n STATUS_CODES: {\n OK: 200,\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n REQUEST_TIMEOUT: 408,\n TIMEOUT: 408,\n CONFLICT: 409,\n INTERNAL_SERVER_ERROR: 500,\n },\n HEADERS: {\n CONFLICTING_ID: 'x-conflicting-id',\n },\n} as const;\n\n/**\n * HAL (Hypertext Application Language) link structure\n */\nexport interface HALLink {\n href: string;\n templated?: boolean;\n type?: string;\n title?: string;\n}\n\n/**\n * Error response from Adobe I/O Events API\n */\nexport interface IOEventsError {\n error?: string;\n message?: string;\n error_code?: string;\n details?: string;\n}\n\n/**\n * Custom error class for Adobe I/O Events API errors\n */\nexport class IOEventsApiError extends Error {\n public readonly statusCode: number;\n public readonly errorCode: string | undefined;\n public readonly details: string | undefined;\n\n constructor(message: string, statusCode: number, errorCode?: string, details?: string) {\n super(message);\n this.name = 'IOEventsApiError';\n this.statusCode = statusCode;\n this.errorCode = errorCode;\n this.details = details;\n }\n}\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IOEventsError, IoEventsGlobals } from '../../types';\nimport { Provider } from '../types';\nimport { ListProvidersQueryParams, ProvidersListResponse } from './types';\n\n/**\n * List providers for Adobe I/O Events\n *\n * This class handles the retrieval of event providers entitled to a specific organization ID.\n * It supports filtering by provider metadata ID, instance ID, and can optionally include\n * event metadata in the response.\n */\nclass List {\n private readonly endpoint: string = IoEventsGlobals.BASE_URL;\n private readonly restClient: RestClient;\n\n /**\n * Constructor for List providers service\n *\n * @param clientId - Client ID from Adobe Developer Console (x-api-key header)\n * @param consumerId - Project Organization ID from Adobe Developer Console\n * @param projectId - Project ID from Adobe Developer Console\n * @param workspaceId - Workspace ID from Adobe Developer Console\n * @param accessToken - IMS token for authentication (Bearer token)\n */\n constructor(\n private readonly clientId: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new Error('clientId is required and cannot be empty');\n }\n if (!consumerId?.trim()) {\n throw new Error('consumerId is required and cannot be empty');\n }\n if (!projectId?.trim()) {\n throw new Error('projectId is required and cannot be empty');\n }\n if (!workspaceId?.trim()) {\n throw new Error('workspaceId is required and cannot be empty');\n }\n if (!accessToken?.trim()) {\n throw new Error('accessToken is required and cannot be empty');\n }\n\n this.restClient = new RestClient();\n }\n\n /**\n * Execute the list providers API call with automatic pagination\n *\n * This method automatically handles pagination by following the `_links.next.href` from the HAL+JSON response.\n * It makes recursive API calls to fetch all pages and returns a complete array containing all providers\n * across all pages.\n *\n * @param queryParams - Optional query parameters for filtering providers\n * @param queryParams.providerMetadataId - Filter by provider metadata id\n * @param queryParams.instanceId - Filter by instance id\n * @param queryParams.providerMetadataIds - List of provider metadata ids to filter (mutually exclusive with providerMetadataId)\n * @param queryParams.eventmetadata - Boolean to fetch provider's event metadata (default: false)\n * @returns Promise<Provider[]> - Complete array of all providers across all pages\n * @throws IOEventsApiError - When API call fails with specific error details\n */\n async execute(queryParams: ListProvidersQueryParams = {}): Promise<Provider[]> {\n try {\n // Validate query parameters\n if (queryParams.providerMetadataId && queryParams.providerMetadataIds) {\n throw new Error('Cannot specify both providerMetadataId and providerMetadataIds');\n }\n\n // Build the API URL\n const url = `${this.endpoint}/events/${this.consumerId}/providers`;\n\n // Build query string if parameters are provided\n const queryString = this.buildQueryString(queryParams);\n const fullUrl = queryString ? `${url}?${queryString}` : url;\n\n // Prepare headers as required by the API\n const headers = {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n Accept: 'application/hal+json',\n };\n\n return await this.fetchAllPages(fullUrl, headers);\n } catch (error: any) {\n // Handle different types of errors\n this.handleError(error);\n }\n }\n\n /**\n * Recursively fetches all pages of providers using pagination links\n *\n * @param url - The URL to fetch (either initial URL or next page URL)\n * @param headers - Headers for the API request\n * @param accumulatedResults - Array to accumulate results across pages\n * @returns Promise<Provider[]> - Complete array of all providers\n * @private\n */\n private async fetchAllPages(\n url: string,\n headers: Record<string, string>,\n accumulatedResults: Provider[] = []\n ): Promise<Provider[]> {\n // Make the GET request\n const response: ProvidersListResponse = await this.restClient.get(url, headers);\n\n // Validate response format\n if (response === null || response === undefined) {\n throw new Error('Invalid response format: Expected object');\n }\n\n if (typeof response !== 'object') {\n throw new Error('Invalid response format: Expected object');\n }\n\n // Extract providers array\n const providers = response._embedded?.providers;\n\n if (providers !== undefined && !Array.isArray(providers)) {\n throw new Error('Invalid response format: providers should be an array');\n }\n\n // Get current page results\n const currentPageResults = providers || [];\n\n // Accumulate results from current page\n const allResults = [...accumulatedResults, ...currentPageResults];\n\n // Check if there's a next page\n const nextPageUrl = response._links?.next?.href;\n\n if (nextPageUrl) {\n // Recursively fetch the next page\n return await this.fetchAllPages(nextPageUrl, headers, allResults);\n }\n\n // No more pages, return all accumulated results\n return allResults;\n }\n\n /**\n * Handle and transform errors from the API call\n * @private\n * @param error - The caught error\n * @throws IOEventsApiError - Transformed error with proper details\n */\n private handleError(error: any): never {\n // Check if it's an HTTP error from RestClient (e.g., \"HTTP error! status: 404\")\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n // Check if error has response body with error details\n if (error.response?.body) {\n const errorBody: IOEventsError = error.response.body;\n const statusCode =\n error.response.statusCode || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n const message =\n errorBody.message || errorBody.error || this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(message, statusCode, errorBody.error_code, errorBody.details);\n }\n\n // Handle network errors\n if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {\n throw new IOEventsApiError(\n 'Network error: Unable to connect to Adobe I/O Events API. Please check your internet connection.',\n 0,\n 'NETWORK_ERROR'\n );\n }\n\n // Handle timeout errors\n if (error.code === 'ETIMEDOUT') {\n throw new IOEventsApiError(\n 'Request timeout: Adobe I/O Events API did not respond in time.',\n 0,\n 'TIMEOUT_ERROR'\n );\n }\n\n // Handle JSON parsing errors\n if (error.message?.includes('JSON') || error.name === 'SyntaxError') {\n throw new IOEventsApiError(\n 'Invalid response format: Unable to parse API response.',\n 0,\n 'PARSE_ERROR'\n );\n }\n\n // Handle validation errors\n if (\n error.message?.includes('Cannot specify both') ||\n error.message?.includes('Invalid response format')\n ) {\n throw new IOEventsApiError(\n error.message,\n IoEventsGlobals.STATUS_CODES.BAD_REQUEST,\n 'VALIDATION_ERROR'\n );\n }\n\n // Generic error fallback\n throw new IOEventsApiError(\n `Failed to list providers: ${error.message || 'Unknown error occurred'}`,\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'UNKNOWN_ERROR'\n );\n }\n\n /**\n * Extracts the status code from RestClient error message\n *\n * @param errorMessage - Error message like \"HTTP error! status: 404\"\n * @returns The HTTP status code\n */\n private extractStatusCodeFromMessage(errorMessage: string): number {\n const match = errorMessage.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Get user-friendly error message based on HTTP status code\n * @private\n * @param statusCode - HTTP status code\n * @returns string - User-friendly error message\n */\n private getErrorMessageForStatus(statusCode: number): string {\n switch (statusCode) {\n case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:\n return 'Unauthorized: Invalid or expired access token';\n case IoEventsGlobals.STATUS_CODES.FORBIDDEN:\n return 'Forbidden: Insufficient permissions or invalid API key';\n case IoEventsGlobals.STATUS_CODES.NOT_FOUND:\n return 'Not Found: Provider associated with the consumerOrgId, providerMetadataId or instanceID does not exist';\n case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:\n return 'Internal Server Error: Adobe I/O Events service is temporarily unavailable';\n default:\n return `API Error: HTTP ${statusCode}`;\n }\n }\n\n /**\n * Build query string from parameters\n * @private\n */\n private buildQueryString(params: ListProvidersQueryParams): string {\n const queryParts: string[] = [];\n\n // Add providerMetadataId if provided\n if (params.providerMetadataId) {\n queryParts.push(`providerMetadataId=${encodeURIComponent(params.providerMetadataId)}`);\n }\n\n // Add instanceId if provided\n if (params.instanceId) {\n queryParts.push(`instanceId=${encodeURIComponent(params.instanceId)}`);\n }\n\n // Add providerMetadataIds array if provided\n if (params.providerMetadataIds && Array.isArray(params.providerMetadataIds)) {\n params.providerMetadataIds.forEach((id: string) => {\n queryParts.push(`providerMetadataIds=${encodeURIComponent(id)}`);\n });\n }\n\n // Add eventmetadata boolean if provided\n if (typeof params.eventmetadata === 'boolean') {\n queryParts.push(`eventmetadata=${params.eventmetadata}`);\n }\n\n return queryParts.join('&');\n }\n}\n\nexport default List;\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\nimport { Provider } from '../types';\nimport { GetProviderQueryParams } from './types';\n\n/**\n * Get provider by ID for Adobe I/O Events\n *\n * This class handles the retrieval of a specific event provider by its ID.\n * It supports including event metadata in the response.\n */\nclass Get {\n private readonly endpoint: string = IoEventsGlobals.BASE_URL;\n private readonly restClient: RestClient;\n\n /**\n * Constructor for Get provider service\n *\n * @param clientId - Client ID from Adobe Developer Console (x-api-key header)\n * @param consumerId - Project Organization ID from Adobe Developer Console\n * @param projectId - Project ID from Adobe Developer Console\n * @param workspaceId - Workspace ID from Adobe Developer Console\n * @param accessToken - IMS token for authentication (Bearer token)\n */\n constructor(\n private readonly clientId: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new Error('clientId is required and cannot be empty');\n }\n if (!consumerId?.trim()) {\n throw new Error('consumerId is required and cannot be empty');\n }\n if (!projectId?.trim()) {\n throw new Error('projectId is required and cannot be empty');\n }\n if (!workspaceId?.trim()) {\n throw new Error('workspaceId is required and cannot be empty');\n }\n if (!accessToken?.trim()) {\n throw new Error('accessToken is required and cannot be empty');\n }\n\n this.restClient = new RestClient();\n }\n\n /**\n * Execute the get provider by ID API call\n *\n * @param providerId - The ID of the provider to retrieve\n * @param queryParams - Optional query parameters\n * @param queryParams.eventmetadata - Boolean to fetch provider's event metadata (default: false)\n * @returns Promise<Provider> - The provider details\n * @throws IOEventsApiError - When API call fails with specific error details\n *\n * @example\n * ```typescript\n * // Get basic provider details\n * const provider = await getService.execute('provider-123');\n *\n * // Get provider details with event metadata\n * const providerWithMetadata = await getService.execute('provider-123', {\n * eventmetadata: true\n * });\n * ```\n */\n async execute(providerId: string, queryParams: GetProviderQueryParams = {}): Promise<Provider> {\n try {\n // Validate provider ID\n if (!providerId?.trim()) {\n throw new Error('Provider ID is required and cannot be empty');\n }\n\n // Build the API URL\n const url = `${this.endpoint}/events/providers/${encodeURIComponent(providerId)}`;\n\n // Build query string if parameters are provided\n const queryString = this.buildQueryString(queryParams);\n const fullUrl = queryString ? `${url}?${queryString}` : url;\n\n // Prepare headers as required by the API\n const headers = {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n Accept: 'application/hal+json',\n };\n\n // Make the GET request\n const response: Provider = await this.restClient.get(fullUrl, headers);\n\n // Validate response format\n if (response === null || response === undefined) {\n throw new Error('Invalid response format: Expected provider object');\n }\n if (typeof response !== 'object') {\n throw new Error('Invalid response format: Expected provider object');\n }\n\n return response;\n } catch (error: any) {\n this.handleError(error);\n }\n }\n\n /**\n * Build query string from parameters\n */\n private buildQueryString(queryParams: GetProviderQueryParams): string {\n const params = new URLSearchParams();\n\n // Handle eventmetadata parameter\n if (queryParams.eventmetadata !== undefined) {\n params.append('eventmetadata', String(queryParams.eventmetadata));\n }\n\n return params.toString();\n }\n\n /**\n * Handle and transform errors into IOEventsApiError\n */\n private handleError(error: any): never {\n // Check if it's an HTTP error from RestClient (e.g., \"HTTP error! status: 404\")\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n // Handle HTTP errors from RestClient\n if (error.response) {\n const status = this.extractStatusCode(error);\n const errorMessage = this.getErrorMessageForStatus(status);\n throw new IOEventsApiError(errorMessage, status, 'API_ERROR');\n }\n\n // Handle network errors\n if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {\n throw new IOEventsApiError(\n 'Network error: Unable to connect to Adobe I/O Events API',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'NETWORK_ERROR'\n );\n }\n\n // Handle timeout errors\n if (error.code === 'ETIMEDOUT') {\n throw new IOEventsApiError(\n 'Request timeout: Adobe I/O Events API did not respond in time',\n IoEventsGlobals.STATUS_CODES.TIMEOUT,\n 'TIMEOUT_ERROR'\n );\n }\n\n // Handle JSON parsing errors\n if (error.message?.includes('JSON')) {\n throw new IOEventsApiError(\n 'Invalid response format from Adobe I/O Events API',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'PARSE_ERROR'\n );\n }\n\n // Handle validation errors (from provider ID or response validation)\n if (\n error.message?.includes('Provider ID is required') ||\n error.message?.includes('Invalid response format')\n ) {\n throw new IOEventsApiError(\n error.message,\n IoEventsGlobals.STATUS_CODES.BAD_REQUEST,\n 'VALIDATION_ERROR'\n );\n }\n\n // Generic error fallback\n throw new IOEventsApiError(\n `Unexpected error: ${error.message || 'Unknown error occurred'}`,\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'UNKNOWN_ERROR'\n );\n }\n\n /**\n * Extract status code from error response\n */\n private extractStatusCode(error: any): number {\n return (\n error.response?.status || error.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR\n );\n }\n\n /**\n * Extracts the status code from RestClient error message\n *\n * @param errorMessage - Error message like \"HTTP error! status: 404\"\n * @returns The HTTP status code\n */\n private extractStatusCodeFromMessage(errorMessage: string): number {\n const match = errorMessage.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Get specific error message based on HTTP status code\n */\n private getErrorMessageForStatus(status: number): string {\n switch (status) {\n case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:\n return 'Unauthorized: Invalid or expired access token';\n case IoEventsGlobals.STATUS_CODES.FORBIDDEN:\n return 'Forbidden: Insufficient permissions to access this provider';\n case IoEventsGlobals.STATUS_CODES.NOT_FOUND:\n return 'Provider ID does not exist';\n case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:\n return 'Internal server error occurred while fetching provider';\n default:\n return `HTTP ${status}: Provider request failed`;\n }\n }\n}\n\nexport default Get;\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\nimport { Provider } from '../types';\nimport { ProviderInputModel } from './types';\n\n/**\n * Create provider for Adobe I/O Events\n *\n * This class handles the creation of new event providers for a specific organization,\n * project, and workspace. It supports both single-instance and multi-instance providers.\n */\nclass Create {\n private readonly endpoint: string = IoEventsGlobals.BASE_URL;\n private readonly restClient: RestClient;\n\n /**\n * Constructor for Create provider service\n *\n * @param clientId - Client ID from Adobe Developer Console (x-api-key header)\n * @param consumerId - Project Organization ID from Adobe Developer Console\n * @param projectId - Project ID from Adobe Developer Console\n * @param workspaceId - Workspace ID from Adobe Developer Console\n * @param accessToken - IMS token for authentication (Bearer token)\n */\n constructor(\n private readonly clientId: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new Error('clientId is required and cannot be empty');\n }\n if (!consumerId?.trim()) {\n throw new Error('consumerId is required and cannot be empty');\n }\n if (!projectId?.trim()) {\n throw new Error('projectId is required and cannot be empty');\n }\n if (!workspaceId?.trim()) {\n throw new Error('workspaceId is required and cannot be empty');\n }\n if (!accessToken?.trim()) {\n throw new Error('accessToken is required and cannot be empty');\n }\n\n this.restClient = new RestClient();\n }\n\n /**\n * Execute the create provider API call\n *\n * @param providerData - Provider input data\n * @returns Promise<Provider> - The created provider\n * @throws IOEventsApiError - When API call fails with specific error details\n */\n async execute(providerData: ProviderInputModel): Promise<Provider> {\n try {\n // Validate required parameters\n if (!providerData) {\n throw new Error('providerData is required');\n }\n if (!providerData.label?.trim()) {\n throw new Error('label is required in providerData');\n }\n\n // Build the API URL\n const url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/providers`;\n\n // Prepare headers as required by the API\n const headers = {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n Accept: 'application/hal+json',\n 'Content-Type': 'application/json',\n };\n\n // Make the POST request\n const response: Provider = await this.restClient.post(url, headers, providerData);\n\n // Validate response format\n if (response === null || response === undefined) {\n throw new Error('Invalid response format: Expected provider object');\n }\n\n if (typeof response !== 'object') {\n throw new Error('Invalid response format: Expected provider object');\n }\n\n // Validate required provider fields\n if (!response.id) {\n throw new Error('Invalid response format: Missing provider id');\n }\n\n return response;\n } catch (error: any) {\n // Handle different types of errors\n this.handleError(error);\n }\n }\n\n /**\n * Handle and transform errors from the API call\n * @private\n * @param error - The caught error\n * @throws IOEventsApiError - Transformed error with proper details\n */\n private handleError(error: any): never {\n // Check if it's an HTTP error from RestClient (e.g., \"HTTP error! status: 404\")\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n // Check if error has response body with error details\n if (error.response?.body) {\n const errorBody = error.response.body;\n const statusCode =\n error.response.statusCode || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n const message =\n errorBody.message || errorBody.error || this.getErrorMessageForStatus(statusCode);\n\n // Handle conflict error with special header\n if (\n statusCode === IoEventsGlobals.STATUS_CODES.CONFLICT &&\n error.response.headers?.[IoEventsGlobals.HEADERS.CONFLICTING_ID]\n ) {\n const conflictingId = error.response.headers[IoEventsGlobals.HEADERS.CONFLICTING_ID];\n throw new IOEventsApiError(\n `Provider already exists with conflicting ID: ${conflictingId}`,\n statusCode,\n 'CONFLICT_ERROR',\n `Conflicting provider ID: ${conflictingId}`\n );\n }\n\n throw new IOEventsApiError(message, statusCode, errorBody.error_code, errorBody.details);\n }\n\n // Handle network errors\n if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {\n throw new IOEventsApiError(\n 'Network error: Unable to connect to Adobe I/O Events API',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'NETWORK_ERROR'\n );\n }\n\n // Handle timeout errors\n if (error.code === 'ETIMEDOUT') {\n throw new IOEventsApiError(\n 'Request timeout: Adobe I/O Events API did not respond in time',\n IoEventsGlobals.STATUS_CODES.TIMEOUT,\n 'TIMEOUT_ERROR'\n );\n }\n\n // Handle JSON parsing errors\n if (error.message?.includes('JSON')) {\n throw new IOEventsApiError(\n 'Invalid response format from Adobe I/O Events API',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'PARSE_ERROR'\n );\n }\n\n // Handle validation errors\n if (\n error.message?.includes('is required') ||\n error.message?.includes('Invalid response format')\n ) {\n throw new IOEventsApiError(\n error.message,\n IoEventsGlobals.STATUS_CODES.BAD_REQUEST,\n 'VALIDATION_ERROR'\n );\n }\n\n // Generic error fallback\n throw new IOEventsApiError(\n `Failed to create provider: ${error.message || 'Unknown error occurred'}`,\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'UNKNOWN_ERROR'\n );\n }\n\n /**\n * Extracts the status code from RestClient error message\n *\n * @param errorMessage - Error message like \"HTTP error! status: 404\"\n * @returns The HTTP status code\n */\n private extractStatusCodeFromMessage(errorMessage: string): number {\n const match = errorMessage.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Get specific error message based on HTTP status code\n */\n private getErrorMessageForStatus(status: number): string {\n switch (status) {\n case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:\n return 'Unauthorized: Invalid or expired access token';\n case IoEventsGlobals.STATUS_CODES.FORBIDDEN:\n return 'Forbidden: Insufficient permissions or invalid scopes, or attempt to create non multi-instance provider';\n case IoEventsGlobals.STATUS_CODES.NOT_FOUND:\n return 'Provider metadata provided in the input model does not exist';\n case IoEventsGlobals.STATUS_CODES.CONFLICT:\n return 'The event provider already exists';\n case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:\n return 'Internal server error occurred while creating provider';\n default:\n return `HTTP ${status}: Provider creation failed`;\n }\n }\n}\n\nexport default Create;\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\n\n/**\n * Delete Provider Service\n *\n * Handles deletion of event providers in Adobe I/O Events.\n * Implements the DELETE /events/{consumerOrgId}/{projectId}/{workspaceId}/providers/{providerId} endpoint.\n */\nexport default class Delete {\n private readonly endpoint = IoEventsGlobals.BASE_URL;\n private readonly restClient: RestClient;\n\n /**\n * Creates an instance of Delete service\n *\n * @param clientId - Client ID from Adobe Developer Console\n * @param consumerId - Project Organization ID\n * @param projectId - Project ID from Adobe Developer Console\n * @param workspaceId - Workspace ID from Adobe Developer Console\n * @param accessToken - IMS token for authentication\n */\n constructor(\n private readonly clientId: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new Error('clientId is required and cannot be empty');\n }\n if (!consumerId?.trim()) {\n throw new Error('consumerId is required and cannot be empty');\n }\n if (!projectId?.trim()) {\n throw new Error('projectId is required and cannot be empty');\n }\n if (!workspaceId?.trim()) {\n throw new Error('workspaceId is required and cannot be empty');\n }\n if (!accessToken?.trim()) {\n throw new Error('accessToken is required and cannot be empty');\n }\n\n this.restClient = new RestClient();\n }\n\n /**\n * Delete a provider by ID\n *\n * @param providerId - The ID of the provider to delete\n * @returns Promise<void> - Resolves when provider is successfully deleted\n * @throws IOEventsApiError - When the API request fails\n */\n async execute(providerId: string): Promise<void> {\n try {\n // Validate required parameters\n if (!providerId?.trim()) {\n throw new Error('providerId is required and cannot be empty');\n }\n\n // Build the API URL\n const url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/providers/${providerId}`;\n\n // Prepare headers\n const headers = {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n Accept: 'application/hal+json',\n 'Content-Type': 'application/json',\n };\n\n // Make the DELETE request\n await this.restClient.delete(url, headers);\n\n // DELETE requests with 204 response don't return content\n // Success is indicated by no exception being thrown\n } catch (error: any) {\n // Handle different types of errors\n this.handleError(error);\n }\n }\n\n /**\n * Handle and transform errors from the API call\n * @private\n * @param error - The caught error\n * @throws IOEventsApiError - Transformed error with proper details\n */\n private handleError(error: any): never {\n // Check if it's an HTTP error from RestClient (e.g., \"HTTP error! status: 404\")\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n // Handle HTTP errors from RestClient\n if (error.response) {\n const status = this.extractStatusCode(error);\n const errorMessage = this.getErrorMessageForStatus(status);\n throw new IOEventsApiError(errorMessage, status, 'API_ERROR');\n }\n\n // Handle network errors\n if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {\n throw new IOEventsApiError(\n 'Network error: Unable to connect to Adobe I/O Events API',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'NETWORK_ERROR'\n );\n }\n\n // Handle timeout errors\n if (error.code === 'ETIMEDOUT' || error.message?.includes('timeout')) {\n throw new IOEventsApiError(\n 'Request timeout: Adobe I/O Events API did not respond in time',\n IoEventsGlobals.STATUS_CODES.TIMEOUT,\n 'TIMEOUT_ERROR'\n );\n }\n\n // Handle JSON parsing errors\n if (error.message?.includes('JSON')) {\n throw new IOEventsApiError(\n 'Invalid response format from Adobe I/O Events API',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'PARSE_ERROR'\n );\n }\n\n // Handle validation errors (from provider ID validation)\n if (error.message?.includes('required') || error.message?.includes('empty')) {\n throw new IOEventsApiError(\n `Validation error: ${error.message}`,\n IoEventsGlobals.STATUS_CODES.BAD_REQUEST,\n 'VALIDATION_ERROR'\n );\n }\n\n // Handle generic errors\n if (error instanceof Error) {\n throw new IOEventsApiError(\n `Failed to delete provider: ${error.message}`,\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'UNKNOWN_ERROR'\n );\n }\n\n // Handle unknown error types\n throw new IOEventsApiError(\n 'Unexpected error: Unknown error occurred',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'UNKNOWN_ERROR'\n );\n }\n\n /**\n * Extract status code from error response\n */\n private extractStatusCode(error: any): number {\n return (\n error.response?.status || error.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR\n );\n }\n\n /**\n * Extracts the status code from RestClient error message\n *\n * @param errorMessage - Error message like \"HTTP error! status: 404\"\n * @returns The HTTP status code\n */\n private extractStatusCodeFromMessage(errorMessage: string): number {\n const match = errorMessage.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Get appropriate error message for HTTP status code\n */\n private getErrorMessageForStatus(status: number): string {\n switch (status) {\n case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:\n return 'Unauthorized: Invalid or expired access token';\n case IoEventsGlobals.STATUS_CODES.FORBIDDEN:\n return 'Forbidden: Insufficient permissions to delete provider';\n case IoEventsGlobals.STATUS_CODES.NOT_FOUND:\n return 'Provider not found: The specified provider ID does not exist';\n case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:\n return 'Internal server error occurred while deleting provider';\n default:\n return `HTTP ${status}: Provider deletion failed`;\n }\n }\n}\n","/**\n * <license header>\n */\n\nimport List from './list';\nimport Get from './get';\nimport Create from './create';\nimport Delete from './delete';\nimport { IOEventsApiError } from '../types';\nimport { Provider } from './types';\nimport { GetProviderQueryParams } from './get/types';\nimport { ListProvidersQueryParams } from './list/types';\nimport { ProviderInputModel } from './create/types';\n\n/**\n * Providers service for Adobe I/O Events\n *\n * This class provides methods to interact with event providers in Adobe I/O Events.\n * It handles authentication and provides a clean interface for provider operations.\n */\nclass ProviderManager {\n private readonly listService: List;\n private readonly getService: Get;\n private readonly createService: Create;\n private readonly deleteService: Delete;\n\n /**\n * Constructor for Providers service\n *\n * @param clientId - Client ID from Adobe Developer Console (x-api-key header)\n * @param consumerId - Project Organization ID from Adobe Developer Console\n * @param projectId - Project ID from Adobe Developer Console\n * @param workspaceId - Workspace ID from Adobe Developer Console\n * @param accessToken - IMS token for authentication (Bearer token)\n */\n constructor(\n private readonly clientId: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly accessToken: string\n ) {\n this.listService = new List(clientId, consumerId, projectId, workspaceId, accessToken);\n this.getService = new Get(clientId, consumerId, projectId, workspaceId, accessToken);\n this.createService = new Create(clientId, consumerId, projectId, workspaceId, accessToken);\n this.deleteService = new Delete(clientId, consumerId, projectId, workspaceId, accessToken);\n }\n\n /**\n * List all event providers entitled to the provided organization ID\n *\n * @param queryParams - Optional query parameters for filtering providers\n * @param queryParams.providerMetadataId - Filter by provider metadata id\n * @param queryParams.instanceId - Filter by instance id\n * @param queryParams.providerMetadataIds - List of provider metadata ids to filter (mutually exclusive with providerMetadataId)\n * @param queryParams.eventmetadata - Boolean to fetch provider's event metadata (default: false)\n * @returns Promise<Provider[]> - Array of providers\n * @throws IOEventsApiError - When API call fails with specific error details\n *\n * @example\n * ```typescript\n * // List all providers\n * const providers = await providersService.list();\n *\n * // Filter by provider metadata ID\n * const customProviders = await providersService.list({\n * providerMetadataId: '3rd_party_custom_events'\n * });\n *\n * // Include event metadata in response\n * const providersWithMetadata = await providersService.list({\n * eventmetadata: true\n * });\n * ```\n */\n async list(queryParams: ListProvidersQueryParams = {}): Promise<Provider[]> {\n try {\n return await this.listService.execute(queryParams);\n } catch (error) {\n // Re-throw IOEventsApiError as-is, or wrap other errors\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n throw new IOEventsApiError(\n `Unexpected error in providers list: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 500,\n 'UNEXPECTED_ERROR'\n );\n }\n }\n\n /**\n * Get a specific event provider by its ID\n *\n * @param providerId - The ID of the provider to retrieve\n * @param queryParams - Optional query parameters\n * @param queryParams.eventmetadata - Boolean to fetch provider's event metadata (default: false)\n * @returns Promise<Provider> - The provider details\n * @throws IOEventsApiError - When API call fails with specific error details\n *\n * @example\n * ```typescript\n * // Get basic provider details\n * const provider = await providersService.get('provider-123');\n *\n * // Get provider details with event metadata\n * const providerWithMetadata = await providersService.get('provider-123', {\n * eventmetadata: true\n * });\n * ```\n */\n async get(providerId: string, queryParams: GetProviderQueryParams = {}): Promise<Provider> {\n try {\n return await this.getService.execute(providerId, queryParams);\n } catch (error) {\n // Re-throw IOEventsApiError as-is, or wrap other errors\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n throw new IOEventsApiError(\n `Unexpected error in providers get: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 500,\n 'UNEXPECTED_ERROR'\n );\n }\n }\n\n /**\n * Create a new event provider\n *\n * @param providerData - Provider input data\n * @param providerData.label - The label of this event provider (required)\n * @param providerData.description - Optional description for the provider\n * @param providerData.docs_url - Optional documentation URL for the provider\n * @param providerData.provider_metadata - Optional provider metadata ID (defaults to '3rd_party_custom_events')\n * @param providerData.instance_id - Optional technical instance ID\n * @param providerData.data_residency_region - Optional data residency region (defaults to 'va6')\n * @returns Promise<Provider> - The created provider\n * @throws IOEventsApiError - When API call fails with specific error details\n *\n * @example\n * ```typescript\n * // Create a basic provider\n * const provider = await providersService.create({\n * label: 'My Event Provider'\n * });\n *\n * // Create a provider with custom details\n * const customProvider = await providersService.create({\n * label: 'My Custom Provider',\n * description: 'Provider for custom business events',\n * provider_metadata: '3rd_party_custom_events',\n * instance_id: 'production-instance'\n * });\n * ```\n */\n async create(providerData: ProviderInputModel): Promise<Provider> {\n try {\n return await this.createService.execute(providerData);\n } catch (error) {\n // Re-throw IOEventsApiError as-is, or wrap other errors\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n throw new IOEventsApiError(\n `Unexpected error in providers create: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 500,\n 'UNEXPECTED_ERROR'\n );\n }\n }\n\n /**\n * Delete an event provider by ID\n *\n * @param providerId - The ID of the provider to delete\n * @returns Promise<void> - Resolves when provider is successfully deleted\n * @throws IOEventsApiError - When API call fails with specific error details\n *\n * @example\n * ```typescript\n * // Delete a provider by ID\n * await providersService.delete('provider-123');\n * console.log('Provider deleted successfully');\n * ```\n */\n async delete(providerId: string): Promise<void> {\n try {\n return await this.deleteService.execute(providerId);\n } catch (error) {\n // Re-throw IOEventsApiError as-is, or wrap other errors\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n throw new IOEventsApiError(\n `Unexpected error in providers delete: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 500,\n 'UNEXPECTED_ERROR'\n );\n }\n }\n}\n\nexport default ProviderManager;\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\nimport { EventMetadata } from '../types';\nimport { EventMetadataListResponse } from './types';\n\n/**\n * Service class for listing all event metadata for a provider\n *\n * Handles: GET /events/providers/{providerId}/eventmetadata\n */\nexport default class List {\n private readonly restClient: RestClient;\n\n /**\n * Creates an instance of List service\n *\n * @param clientId - The Adobe I/O client ID (API key)\n * @param consumerId - The consumer organization ID\n * @param projectId - The project ID\n * @param workspaceId - The workspace ID\n * @param accessToken - The access token for authentication\n */\n constructor(\n private readonly clientId: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new Error('clientId is required and cannot be empty');\n }\n if (!consumerId?.trim()) {\n throw new Error('consumerId is required and cannot be empty');\n }\n if (!projectId?.trim()) {\n throw new Error('projectId is required and cannot be empty');\n }\n if (!workspaceId?.trim()) {\n throw new Error('workspaceId is required and cannot be empty');\n }\n if (!accessToken?.trim()) {\n throw new Error('accessToken is required and cannot be empty');\n }\n\n this.restClient = new RestClient();\n }\n\n /**\n * Retrieves all event metadata for a provider with automatic pagination\n *\n * This method automatically follows pagination links to fetch all event metadata\n * across multiple pages, returning a complete array of all event metadata.\n *\n * @param providerId - The ID of the provider to fetch event metadata for\n * @returns Promise<EventMetadata[]> - Array of all event metadata across all pages\n * @throws IOEventsApiError - When the API request fails\n */\n async execute(providerId: string): Promise<EventMetadata[]> {\n if (!providerId?.trim()) {\n throw new IOEventsApiError(\n 'providerId is required and cannot be empty',\n 400,\n 'VALIDATION_ERROR'\n );\n }\n\n try {\n const url = `${IoEventsGlobals.BASE_URL}/events/providers/${providerId}/eventmetadata`;\n return await this.fetchAllPages(url);\n } catch (error: any) {\n this.handleError(error);\n }\n }\n\n /**\n * Recursively fetches all pages of event metadata using pagination links\n *\n * @param url - The URL to fetch (either initial URL or next page URL)\n * @param accumulatedResults - Array to accumulate results across pages\n * @returns Promise<EventMetadata[]> - Complete array of all event metadata\n * @private\n */\n private async fetchAllPages(\n url: string,\n accumulatedResults: EventMetadata[] = []\n ): Promise<EventMetadata[]> {\n const response = await this.restClient.get(url, {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n Accept: 'application/hal+json',\n });\n\n // Validate response format\n if (response === null || response === undefined) {\n throw new IOEventsApiError(\n 'Invalid response format: Expected object',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'PARSE_ERROR'\n );\n }\n\n if (typeof response !== 'object') {\n throw new IOEventsApiError(\n 'Invalid response format: Expected object',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'PARSE_ERROR'\n );\n }\n\n const data = response as EventMetadataListResponse;\n\n // Validate _embedded structure\n if (!data._embedded || !Array.isArray(data._embedded.eventmetadata)) {\n throw new IOEventsApiError(\n 'Invalid response format: Expected eventmetadata array',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'PARSE_ERROR'\n );\n }\n\n const currentPageResults = data._embedded.eventmetadata;\n\n // Accumulate results from current page\n const allResults = [...accumulatedResults, ...currentPageResults];\n\n // Check if there's a next page\n const nextPageUrl = data._links?.next?.href;\n\n if (nextPageUrl) {\n // Recursively fetch the next page\n return await this.fetchAllPages(nextPageUrl, allResults);\n }\n\n // No more pages, return all accumulated results\n return allResults;\n }\n\n /**\n * Handles errors from the API request\n *\n * @param error - The error object from the API request\n * @throws IOEventsApiError - Always throws with appropriate error details\n */\n private handleError(error: any): never {\n // Check if it's an HTTP error from RestClient (e.g., \"HTTP error! status: 404\")\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n // Check if it's a structured API error response\n if (error.response) {\n const statusCode = this.extractStatusCode(error);\n const errorMessage =\n error.response.body?.message || this.getErrorMessageForStatus(statusCode);\n\n throw new IOEventsApiError(\n errorMessage,\n statusCode,\n error.response.body,\n error.response.headers\n );\n }\n\n // Handle other types of errors (network, timeout, parsing, etc.)\n let errorMessage: string;\n let statusCode: number;\n\n if (error instanceof Error) {\n if (error.message.includes('timeout') || error.message.includes('ETIMEDOUT')) {\n errorMessage = 'Request timeout while listing event metadata';\n statusCode = IoEventsGlobals.STATUS_CODES.REQUEST_TIMEOUT;\n } else if (error.message.includes('JSON') || error.message.includes('parse')) {\n errorMessage = 'Invalid response format from Adobe I/O Events API';\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n throw new IOEventsApiError(errorMessage, statusCode, 'PARSE_ERROR');\n } else {\n errorMessage = `Network error: ${error.message}`;\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n } else {\n errorMessage = `API Error: HTTP ${IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR}`;\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n /**\n * Extracts the status code from the error response\n *\n * @param error - The error object\n * @returns The HTTP status code\n */\n private extractStatusCode(error: any): number {\n return error.response?.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Extracts the status code from RestClient error message\n *\n * @param errorMessage - Error message like \"HTTP error! status: 404\"\n * @returns The HTTP status code\n */\n private extractStatusCodeFromMessage(errorMessage: string): number {\n const match = errorMessage.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Gets a human-readable error message for a given HTTP status code\n *\n * @param statusCode - The HTTP status code\n * @returns A descriptive error message\n */\n private getErrorMessageForStatus(statusCode: number): string {\n switch (statusCode) {\n case IoEventsGlobals.STATUS_CODES.BAD_REQUEST:\n return 'Invalid request parameters for listing event metadata';\n case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:\n return 'Authentication failed. Please check your access token';\n case IoEventsGlobals.STATUS_CODES.FORBIDDEN:\n return 'Access forbidden. You do not have permission to access event metadata';\n case IoEventsGlobals.STATUS_CODES.NOT_FOUND:\n return 'Provider not found or no event metadata available';\n case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:\n return 'Internal server error occurred while listing event metadata';\n default:\n return `Unexpected error occurred: HTTP ${statusCode}`;\n }\n }\n}\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\nimport { EventMetadata } from '../types';\n\n/**\n * Service class for getting specific event metadata by provider ID and event code\n */\nexport default class Get {\n private readonly restClient: RestClient;\n\n /**\n * Creates an instance of Get service\n *\n * @param clientId - The Adobe I/O client ID (API key)\n * @param consumerId - The consumer organization ID\n * @param projectId - The project ID\n * @param workspaceId - The workspace ID\n * @param accessToken - The access token for authentication\n */\n constructor(\n private readonly clientId: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new Error('clientId is required and cannot be empty');\n }\n if (!consumerId?.trim()) {\n throw new Error('consumerId is required and cannot be empty');\n }\n if (!projectId?.trim()) {\n throw new Error('projectId is required and cannot be empty');\n }\n if (!workspaceId?.trim()) {\n throw new Error('workspaceId is required and cannot be empty');\n }\n if (!accessToken?.trim()) {\n throw new Error('accessToken is required and cannot be empty');\n }\n\n this.restClient = new RestClient();\n }\n\n /**\n * Retrieves specific event metadata by provider ID and event code\n *\n * @param providerId - The ID of the provider\n * @param eventCode - The event code to get metadata for\n * @returns Promise<EventMetadata> - The event metadata\n * @throws IOEventsApiError - When the API request fails\n */\n async execute(providerId: string, eventCode: string): Promise<EventMetadata> {\n if (!providerId?.trim()) {\n throw new IOEventsApiError(\n 'providerId is required and cannot be empty',\n 400,\n 'VALIDATION_ERROR'\n );\n }\n if (!eventCode?.trim()) {\n throw new IOEventsApiError(\n 'eventCode is required and cannot be empty',\n 400,\n 'VALIDATION_ERROR'\n );\n }\n\n try {\n const url = `${IoEventsGlobals.BASE_URL}/events/providers/${providerId}/eventmetadata/${encodeURIComponent(eventCode)}`;\n\n const response = await this.restClient.get(url, {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n Accept: 'application/hal+json',\n });\n\n // Validate response format\n if (response === null || response === undefined) {\n throw new IOEventsApiError(\n 'Invalid response format: Expected object',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'PARSE_ERROR'\n );\n }\n\n if (typeof response !== 'object') {\n throw new IOEventsApiError(\n 'Invalid response format: Expected object',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,\n 'PARSE_ERROR'\n );\n }\n\n return response as EventMetadata;\n } catch (error: any) {\n this.handleError(error);\n }\n }\n\n /**\n * Handles errors from the API request\n *\n * @param error - The error object from the API request\n * @throws IOEventsApiError - Always throws with appropriate error details\n */\n private handleError(error: any): never {\n // Check if it's an HTTP error from RestClient (e.g., \"HTTP error! status: 404\")\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n // Check if it's a structured API error response\n if (error.response) {\n const statusCode = this.extractStatusCode(error);\n const errorMessage =\n error.response.body?.message || this.getErrorMessageForStatus(statusCode);\n\n throw new IOEventsApiError(\n errorMessage,\n statusCode,\n error.response.body?.error_code,\n error.response.body?.details\n );\n }\n\n // Handle other types of errors (network, timeout, parsing, etc.)\n let errorMessage: string;\n let statusCode: number;\n\n if (error instanceof Error) {\n if (error.message.includes('timeout') || error.message.includes('ETIMEDOUT')) {\n errorMessage = 'Request timeout while getting event metadata';\n statusCode = IoEventsGlobals.STATUS_CODES.REQUEST_TIMEOUT;\n } else if (error.message.includes('JSON') || error.message.includes('parse')) {\n errorMessage = 'Invalid response format from Adobe I/O Events API';\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n throw new IOEventsApiError(errorMessage, statusCode, 'PARSE_ERROR');\n } else {\n errorMessage = `Network error: ${error.message}`;\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n } else {\n errorMessage = `API Error: HTTP ${IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR}`;\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n /**\n * Extracts the status code from the error response\n *\n * @param error - The error object\n * @returns The HTTP status code\n */\n private extractStatusCode(error: any): number {\n return error.response?.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Extracts the status code from RestClient error message\n *\n * @param errorMessage - Error message like \"HTTP error! status: 404\"\n * @returns The HTTP status code\n */\n private extractStatusCodeFromMessage(errorMessage: string): number {\n const match = errorMessage.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Gets a human-readable error message for a given HTTP status code\n *\n * @param statusCode - The HTTP status code\n * @returns A descriptive error message\n */\n private getErrorMessageForStatus(statusCode: number): string {\n switch (statusCode) {\n case IoEventsGlobals.STATUS_CODES.BAD_REQUEST:\n return 'Invalid request parameters for getting event metadata';\n case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:\n return 'Authentication failed. Please check your access token';\n case IoEventsGlobals.STATUS_CODES.FORBIDDEN:\n return 'Access forbidden. You do not have permission to access this event metadata';\n case IoEventsGlobals.STATUS_CODES.NOT_FOUND:\n return 'Event metadata not found for the specified provider and event code';\n case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:\n return 'Internal server error occurred while getting event metadata';\n default:\n return `Unexpected error occurred: HTTP ${statusCode}`;\n }\n }\n}\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\nimport { EventMetadata } from '../types';\nimport { EventMetadataInputModel } from './types';\n\n/**\n * Create event metadata for Adobe I/O Events\n *\n * This class handles the creation of event metadata for a specific provider.\n * It validates the input data and makes the appropriate API call to create\n * the event metadata in Adobe I/O Events.\n */\nclass Create {\n private readonly endpoint: string = IoEventsGlobals.BASE_URL;\n private readonly restClient: RestClient;\n\n /**\n * Constructor for Create event metadata service\n *\n * @param clientId - Client ID from Adobe Developer Console (x-api-key header)\n * @param consumerId - Project Organization ID from Adobe Developer Console\n * @param projectId - Project ID from Adobe Developer Console\n * @param workspaceId - Workspace ID from Adobe Developer Console\n * @param accessToken - IMS token for authentication (Bearer token)\n */\n constructor(\n private readonly clientId: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new Error('clientId is required and cannot be empty');\n }\n if (!consumerId?.trim()) {\n throw new Error('consumerId is required and cannot be empty');\n }\n if (!projectId?.trim()) {\n throw new Error('projectId is required and cannot be empty');\n }\n if (!workspaceId?.trim()) {\n throw new Error('workspaceId is required and cannot be empty');\n }\n if (!accessToken?.trim()) {\n throw new Error('accessToken is required and cannot be empty');\n }\n\n this.restClient = new RestClient();\n }\n\n /**\n * Execute the create event metadata API call\n *\n * @param providerId - The ID of the provider to create event metadata for\n * @param eventMetadataData - The event metadata input model\n * @returns Promise<EventMetadata> - The created event metadata\n * @throws IOEventsApiError - When API call fails with specific error details\n */\n async execute(\n providerId: string,\n eventMetadataData: EventMetadataInputModel\n ): Promise<EventMetadata> {\n try {\n // Validate required parameters\n if (!providerId?.trim()) {\n throw new IOEventsApiError(\n 'providerId is required and cannot be empty',\n 400,\n 'VALIDATION_ERROR'\n );\n }\n\n if (!eventMetadataData) {\n throw new IOEventsApiError('eventMetadataData is required', 400, 'VALIDATION_ERROR');\n }\n\n // Validate required fields in eventMetadataData\n this.validateEventMetadataInput(eventMetadataData);\n\n // Convert the input data for API submission\n const apiPayload = this.convertToApiPayload(eventMetadataData);\n\n // Build the API URL\n const url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/providers/${providerId}/eventmetadata`;\n\n // Prepare headers as required by the API\n const headers = {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n Accept: 'application/hal+json',\n 'Content-Type': 'application/json',\n };\n\n // Make the POST request\n const response: EventMetadata = await this.restClient.post(url, headers, apiPayload);\n\n // Validate response format\n if (response === null || response === undefined) {\n throw new IOEventsApiError(\n 'Invalid response format: Expected object',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR\n );\n }\n\n if (typeof response !== 'object') {\n throw new IOEventsApiError(\n 'Invalid response format: Expected object',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR\n );\n }\n\n return response;\n } catch (error: any) {\n // Handle different types of errors\n this.handleError(error);\n }\n }\n\n /**\n * Validates the event metadata input data\n *\n * @param eventMetadataData - The event metadata input to validate\n * @throws Error - When validation fails\n * @private\n */\n private validateEventMetadataInput(eventMetadataData: EventMetadataInputModel): void {\n const { description, label, event_code, sample_event_template } = eventMetadataData;\n\n // Validate required fields\n if (!description?.trim()) {\n throw new IOEventsApiError(\n 'description is required and cannot be empty',\n 400,\n 'VALIDATION_ERROR'\n );\n }\n\n if (!label?.trim()) {\n throw new IOEventsApiError('label is required and cannot be empty', 400, 'VALIDATION_ERROR');\n }\n\n if (!event_code?.trim()) {\n throw new IOEventsApiError(\n 'event_code is required and cannot be empty',\n 400,\n 'VALIDATION_ERROR'\n );\n }\n\n // Validate field lengths\n if (description.length > 255) {\n throw new Error('description cannot exceed 255 characters');\n }\n\n if (label.length > 255) {\n throw new Error('label cannot exceed 255 characters');\n }\n\n if (event_code.length > 255) {\n throw new Error('event_code cannot exceed 255 characters');\n }\n\n // Validate patterns (basic validation - API will do full validation)\n const descriptionPattern = /^[\\w\\s\\-_.(),:''`?#!]+$/;\n if (!descriptionPattern.test(description)) {\n throw new Error('description contains invalid characters');\n }\n\n const labelPattern = /^[\\w\\s\\-_.(),:''`?#!]+$/;\n if (!labelPattern.test(label)) {\n throw new Error('label contains invalid characters');\n }\n\n const eventCodePattern = /^[\\w\\-_.]+$/;\n if (!eventCodePattern.test(event_code)) {\n throw new Error('event_code contains invalid characters');\n }\n\n // Validate sample_event_template if provided\n if (sample_event_template !== undefined) {\n if (typeof sample_event_template !== 'object' || sample_event_template === null) {\n throw new Error('sample_event_template must be a valid JSON object');\n }\n\n try {\n // Check if the JSON string representation would exceed the base64 limit\n // Base64 encoding increases size by ~33%, so we check the JSON string length\n const jsonString = JSON.stringify(sample_event_template);\n const base64Length = Buffer.from(jsonString).toString('base64').length;\n\n if (base64Length > 87382) {\n throw new Error('sample_event_template JSON object is too large when base64 encoded');\n }\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes('sample_event_template JSON object is too large')\n ) {\n throw error; // Re-throw our validation error\n }\n throw new Error('sample_event_template must be a valid JSON object');\n }\n }\n }\n\n /**\n * Converts the input data to the format expected by the API\n *\n * @param eventMetadataData - The event metadata input data\n * @returns The converted payload for the API\n * @private\n */\n private convertToApiPayload(eventMetadataData: EventMetadataInputModel): any {\n const { sample_event_template, ...rest } = eventMetadataData;\n\n const payload: any = { ...rest };\n\n // Convert sample_event_template from JSON object to base64 string if provided\n if (sample_event_template !== undefined) {\n payload.sample_event_template = Buffer.from(JSON.stringify(sample_event_template)).toString(\n 'base64'\n );\n }\n\n return payload;\n }\n\n /**\n * Handles errors from the API request\n *\n * @param error - The error object from the API request\n * @throws IOEventsApiError - Always throws with appropriate error details\n * @private\n */\n private handleError(error: any): never {\n // If it's already an IOEventsApiError, re-throw it\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n\n // Check if it's an HTTP error from RestClient (e.g., \"HTTP error! status: 404\")\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n // Check if it's a structured API error response\n if (error.response) {\n const statusCode = this.extractStatusCode(error);\n const errorMessage =\n error.response.body?.message || this.getErrorMessageForStatus(statusCode);\n\n throw new IOEventsApiError(\n errorMessage,\n statusCode,\n error.response.body?.error_code,\n error.response.body?.details\n );\n }\n\n // Handle other types of errors (network, timeout, parsing, etc.)\n let errorMessage: string;\n let statusCode: number;\n\n if (error instanceof Error) {\n if (error.message.includes('timeout') || error.message.includes('ETIMEDOUT')) {\n errorMessage = 'Request timeout while creating event metadata';\n statusCode = IoEventsGlobals.STATUS_CODES.REQUEST_TIMEOUT;\n } else if (\n error.message.includes('is required') ||\n error.message.includes('cannot be empty') ||\n error.message.includes('cannot exceed') ||\n error.message.includes('contains invalid characters') ||\n error.message.includes('must be a valid') ||\n error.message.includes('too large when base64 encoded')\n ) {\n // Validation errors should be thrown as-is with 400 status\n throw new IOEventsApiError(\n error.message,\n IoEventsGlobals.STATUS_CODES.BAD_REQUEST,\n 'VALIDATION_ERROR'\n );\n } else if (error.message.includes('JSON') || error.message.includes('parse')) {\n errorMessage = 'Invalid response format from Adobe I/O Events API';\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n } else {\n errorMessage = `Network error: ${error.message}`;\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n } else {\n errorMessage = `API Error: HTTP ${IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR}`;\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n /**\n * Extracts the status code from the error response\n *\n * @param error - The error object\n * @returns The HTTP status code\n * @private\n */\n private extractStatusCode(error: any): number {\n return error.response?.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Extracts the status code from RestClient error message\n *\n * @param errorMessage - Error message like \"HTTP error! status: 404\"\n * @returns The HTTP status code\n * @private\n */\n private extractStatusCodeFromMessage(errorMessage: string): number {\n const match = errorMessage.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Gets a human-readable error message based on HTTP status code\n *\n * @param statusCode - HTTP status code\n * @returns string - User-friendly error message\n * @private\n */\n private getErrorMessageForStatus(statusCode: number): string {\n switch (statusCode) {\n case IoEventsGlobals.STATUS_CODES.BAD_REQUEST:\n return 'Invalid request parameters for creating event metadata';\n case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:\n return 'Authentication failed. Please check your access token';\n case IoEventsGlobals.STATUS_CODES.FORBIDDEN:\n return 'Access forbidden. You do not have permission to create event metadata';\n case IoEventsGlobals.STATUS_CODES.NOT_FOUND:\n return 'Provider not found. The specified provider ID does not exist';\n case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:\n return 'Internal server error occurred while creating event metadata';\n default:\n return `Unexpected error occurred: HTTP ${statusCode}`;\n }\n }\n}\n\nexport default Create;\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\n\n/**\n * Delete all event metadata for a provider in Adobe I/O Events\n *\n * This class handles the deletion of all event metadata associated with a specific provider.\n * The operation returns 204 No Content on successful deletion.\n */\nclass Delete {\n private readonly endpoint: string = IoEventsGlobals.BASE_URL;\n private readonly restClient: RestClient;\n\n /**\n * Constructor for Delete event metadata service\n *\n * @param clientId - Client ID from Adobe Developer Console (x-api-key header)\n * @param consumerId - Project Organization ID from Adobe Developer Console\n * @param projectId - Project ID from Adobe Developer Console\n * @param workspaceId - Workspace ID from Adobe Developer Console\n * @param accessToken - IMS token for authentication (Bearer token)\n */\n constructor(\n private readonly clientId: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new Error('clientId is required and cannot be empty');\n }\n if (!consumerId?.trim()) {\n throw new Error('consumerId is required and cannot be empty');\n }\n if (!projectId?.trim()) {\n throw new Error('projectId is required and cannot be empty');\n }\n if (!workspaceId?.trim()) {\n throw new Error('workspaceId is required and cannot be empty');\n }\n if (!accessToken?.trim()) {\n throw new Error('accessToken is required and cannot be empty');\n }\n\n this.restClient = new RestClient();\n }\n\n /**\n * Execute the delete event metadata API call\n *\n * @param providerId - The ID of the provider to delete event metadata for\n * @param eventCode - Optional event code to delete specific event metadata. If not provided, deletes all event metadata for the provider\n * @returns Promise<void> - No content returned on successful deletion (204)\n * @throws IOEventsApiError - When API call fails with specific error details\n */\n async execute(providerId: string, eventCode?: string): Promise<void> {\n try {\n // Validate required parameters\n if (!providerId?.trim()) {\n throw new IOEventsApiError(\n 'providerId is required and cannot be empty',\n 400,\n 'VALIDATION_ERROR'\n );\n }\n\n // Validate eventCode if provided\n if (eventCode !== undefined && !eventCode?.trim()) {\n throw new IOEventsApiError(\n 'eventCode cannot be empty when provided',\n 400,\n 'VALIDATION_ERROR'\n );\n }\n\n // Build the API URL - append eventCode if provided for specific deletion\n let url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/providers/${providerId}/eventmetadata`;\n if (eventCode?.trim()) {\n url += `/${encodeURIComponent(eventCode.trim())}`;\n }\n\n // Prepare headers as required by the API\n const headers = {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n Accept: 'application/hal+json',\n };\n\n // Make the DELETE request - RestClient should handle 204 No Content properly\n await this.restClient.delete(url, headers);\n\n // No return value for 204 No Content\n } catch (error: any) {\n // Handle different types of errors\n this.handleError(error);\n }\n }\n\n /**\n * Handles errors from the API request\n *\n * @param error - The error object from the API request\n * @throws IOEventsApiError - Always throws with appropriate error details\n * @private\n */\n private handleError(error: any): never {\n // If it's already an IOEventsApiError, re-throw it\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n\n // Check if it's an HTTP error from RestClient (e.g., \"HTTP error! status: 404\")\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n // Check if it's a structured API error response\n if (error.response) {\n const statusCode = this.extractStatusCode(error);\n const errorMessage =\n error.response.body?.message || this.getErrorMessageForStatus(statusCode);\n\n throw new IOEventsApiError(\n errorMessage,\n statusCode,\n error.response.body?.error_code,\n error.response.body?.details\n );\n }\n\n // Handle other types of errors (network, timeout, parsing, etc.)\n let errorMessage: string;\n let statusCode: number;\n\n if (error instanceof Error) {\n if (error.message.includes('timeout') || error.message.includes('ETIMEDOUT')) {\n errorMessage = 'Request timeout while deleting event metadata';\n statusCode = IoEventsGlobals.STATUS_CODES.REQUEST_TIMEOUT;\n } else if (\n error.message.includes('is required') ||\n error.message.includes('cannot be empty')\n ) {\n // Validation errors should be thrown as-is with 400 status\n throw new IOEventsApiError(\n error.message,\n IoEventsGlobals.STATUS_CODES.BAD_REQUEST,\n 'VALIDATION_ERROR'\n );\n } else if (error.message.includes('JSON') || error.message.includes('parse')) {\n errorMessage = 'Invalid response format from Adobe I/O Events API';\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n } else {\n errorMessage = `Network error: ${error.message}`;\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n } else {\n errorMessage = `API Error: HTTP ${IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR}`;\n statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n /**\n * Extracts the status code from the error response\n *\n * @param error - The error object\n * @returns The HTTP status code\n * @private\n */\n private extractStatusCode(error: any): number {\n return error.response?.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Extracts the status code from RestClient error message\n *\n * @param errorMessage - Error message like \"HTTP error! status: 404\"\n * @returns The HTTP status code\n * @private\n */\n private extractStatusCodeFromMessage(errorMessage: string): number {\n const match = errorMessage.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Gets a human-readable error message based on HTTP status code\n *\n * @param statusCode - HTTP status code\n * @returns string - User-friendly error message\n * @private\n */\n private getErrorMessageForStatus(statusCode: number): string {\n switch (statusCode) {\n case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:\n return 'Authentication failed. Please check your access token';\n case IoEventsGlobals.STATUS_CODES.FORBIDDEN:\n return 'Access forbidden. You do not have permission to delete event metadata';\n case IoEventsGlobals.STATUS_CODES.NOT_FOUND:\n return 'Provider or event metadata not found. The specified provider ID or event code does not exist';\n case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:\n return 'Internal server error occurred while deleting event metadata';\n default:\n return `Unexpected error occurred: HTTP ${statusCode}`;\n }\n }\n}\n\nexport default Delete;\n","/**\n * <license header>\n */\n\nimport List from './list';\nimport Get from './get';\nimport Create from './create';\nimport Delete from './delete';\nimport { IOEventsApiError } from '../types';\nimport { EventMetadata } from './types';\nimport { EventMetadataInputModel } from './create/types';\n\n/**\n * Main class for managing event metadata operations\n *\n * Provides methods to interact with Adobe I/O Events API for event metadata management.\n * Supports listing, getting, creating, and deleting event metadata for providers.\n */\nclass EventMetadataManager {\n private readonly listService: List;\n private readonly getService: Get;\n private readonly createService: Create;\n private readonly deleteService: Delete;\n\n /**\n * Creates an instance of EventMetadataManager\n *\n * @param clientId - Adobe I/O Client ID for API authentication\n * @param consumerId - Consumer organization ID\n * @param projectId - Project ID within the consumer organization\n * @param workspaceId - Workspace ID within the project\n * @param accessToken - Access token for API authentication\n */\n constructor(\n private readonly clientId: string,\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly accessToken: string\n ) {\n this.listService = new List(clientId, consumerId, projectId, workspaceId, accessToken);\n this.getService = new Get(clientId, consumerId, projectId, workspaceId, accessToken);\n this.createService = new Create(clientId, consumerId, projectId, workspaceId, accessToken);\n this.deleteService = new Delete(clientId, consumerId, projectId, workspaceId, accessToken);\n }\n\n /**\n * Lists all event metadata for a provider\n *\n * @param providerId - The ID of the provider to fetch event metadata for\n * @returns Promise<EventMetadata[]> - Array of event metadata\n * @throws IOEventsApiError - When the API request fails\n *\n * @example\n * // List all event metadata for a provider\n * const allMetadata = await eventMetadata.list('provider-123');\n */\n async list(providerId: string): Promise<EventMetadata[]> {\n try {\n return await this.listService.execute(providerId);\n } catch (error) {\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n throw new IOEventsApiError(\n `Unexpected error in event metadata list: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 500,\n 'UNEXPECTED_ERROR'\n );\n }\n }\n\n /**\n * Gets specific event metadata by provider ID and event code\n *\n * @param providerId - The ID of the provider\n * @param eventCode - The event code to get metadata for\n * @returns Promise<EventMetadata> - The event metadata\n * @throws IOEventsApiError - When the API request fails\n *\n * @example\n * // Get specific event metadata by event code\n * const specificMetadata = await eventMetadata.get('provider-123', 'user.created');\n */\n async get(providerId: string, eventCode: string): Promise<EventMetadata> {\n try {\n return await this.getService.execute(providerId, eventCode);\n } catch (error) {\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n throw new IOEventsApiError(\n `Unexpected error in event metadata get: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 500,\n 'UNEXPECTED_ERROR'\n );\n }\n }\n\n /**\n * Creates new event metadata for a provider\n *\n * @param providerId - The ID of the provider to create event metadata for\n * @param eventMetadataData - The event metadata input data\n * @returns Promise<EventMetadata> - The created event metadata\n * @throws IOEventsApiError - When the API request fails\n *\n * @example\n * // Create new event metadata\n * const newMetadata = await eventMetadata.create('provider-123', {\n * event_code: 'com.example.user.created',\n * label: 'User Created',\n * description: 'Triggered when a new user is created',\n * sample_event_template: { name: 'John Doe', email: 'john@example.com' } // JSON object\n * });\n */\n async create(\n providerId: string,\n eventMetadataData: EventMetadataInputModel\n ): Promise<EventMetadata> {\n try {\n return await this.createService.execute(providerId, eventMetadataData);\n } catch (error) {\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n throw new IOEventsApiError(\n `Unexpected error in event metadata create: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 500,\n 'UNEXPECTED_ERROR'\n );\n }\n }\n\n /**\n * Deletes event metadata for a provider\n *\n * @param providerId - The ID of the provider to delete event metadata for\n * @param eventCode - Optional event code to delete specific event metadata. If not provided, deletes all event metadata for the provider\n * @returns Promise<void> - No content returned on successful deletion\n * @throws IOEventsApiError - When the API request fails\n *\n * @example\n * // Delete all event metadata for a provider\n * await eventMetadata.delete('provider-123');\n *\n * @example\n * // Delete specific event metadata by event code\n * await eventMetadata.delete('provider-123', 'com.example.user.created');\n */\n async delete(providerId: string, eventCode?: string): Promise<void> {\n try {\n return await this.deleteService.execute(providerId, eventCode);\n } catch (error) {\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n throw new IOEventsApiError(\n `Unexpected error in event metadata delete: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 500,\n 'UNEXPECTED_ERROR'\n );\n }\n }\n}\n\nexport default EventMetadataManager;\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\nimport type { Registration } from '../types';\nimport type { RegistrationCreateModel } from './types';\n\n/**\n * Service for creating registrations\n */\nexport class Create {\n private restClient: RestClient;\n private endpoint: string;\n private clientId: string;\n private consumerId: string;\n private projectId: string;\n private workspaceId: string;\n private accessToken: string;\n\n /**\n * Initialize the Create service\n */\n constructor(\n clientId: string,\n consumerId: string,\n projectId: string,\n workspaceId: string,\n accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new IOEventsApiError('clientId is required and cannot be empty', 400);\n }\n if (!consumerId?.trim()) {\n throw new IOEventsApiError('consumerId is required and cannot be empty', 400);\n }\n if (!projectId?.trim()) {\n throw new IOEventsApiError('projectId is required and cannot be empty', 400);\n }\n if (!workspaceId?.trim()) {\n throw new IOEventsApiError('workspaceId is required and cannot be empty', 400);\n }\n if (!accessToken?.trim()) {\n throw new IOEventsApiError('accessToken is required and cannot be empty', 400);\n }\n\n this.restClient = new RestClient();\n this.endpoint = IoEventsGlobals.BASE_URL;\n this.clientId = clientId;\n this.consumerId = consumerId;\n this.projectId = projectId;\n this.workspaceId = workspaceId;\n this.accessToken = accessToken;\n }\n\n /**\n * Create a new registration\n *\n * @param registrationData - The registration data to create\n * @returns Promise<Registration> - The created registration\n * @throws IOEventsApiError - When the API call fails\n *\n * @example\n * ```typescript\n * const registration = await registrationManager.create({\n * client_id: 'your-client-id',\n * name: 'My Registration',\n * description: 'Registration for user events',\n * webhook_url: 'https://example.com/webhook',\n * events_of_interest: [\n * {\n * provider_id: 'provider-123',\n * event_code: 'com.example.user.created'\n * }\n * ],\n * delivery_type: 'webhook',\n * enabled: true\n * });\n * console.log(registration.registration_id);\n * ```\n */\n async execute(registrationData: RegistrationCreateModel): Promise<Registration> {\n try {\n this.validateRegistrationInput(registrationData);\n\n const url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/registrations`;\n\n const response = await this.restClient.post(\n url,\n {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n 'Content-Type': 'application/json',\n Accept: 'application/hal+json',\n },\n registrationData\n );\n\n return response as Registration;\n } catch (error) {\n this.handleError(error);\n }\n }\n\n /**\n * Validates the registration input data\n */\n private validateRegistrationInput(registrationData: RegistrationCreateModel): void {\n if (!registrationData) {\n throw new IOEventsApiError('Registration data is required', 400);\n }\n\n if (!registrationData.client_id?.trim()) {\n throw new IOEventsApiError('Client ID is required', 400);\n }\n\n if (registrationData.client_id.length < 3 || registrationData.client_id.length > 255) {\n throw new IOEventsApiError('Client ID must be between 3 and 255 characters', 400);\n }\n\n if (!registrationData.name?.trim()) {\n throw new IOEventsApiError('Registration name is required', 400);\n }\n\n if (registrationData.name.length < 3 || registrationData.name.length > 255) {\n throw new IOEventsApiError('Registration name must be between 3 and 255 characters', 400);\n }\n\n if (registrationData.description && registrationData.description.length > 5000) {\n throw new IOEventsApiError('Description must not exceed 5000 characters', 400);\n }\n\n if (registrationData.webhook_url && registrationData.webhook_url.length > 4000) {\n throw new IOEventsApiError('Webhook URL must not exceed 4000 characters', 400);\n }\n\n if (\n !registrationData.events_of_interest ||\n !Array.isArray(registrationData.events_of_interest)\n ) {\n throw new IOEventsApiError('Events of interest is required and must be an array', 400);\n }\n\n if (registrationData.events_of_interest.length === 0) {\n throw new IOEventsApiError('At least one event of interest is required', 400);\n }\n\n // Validate each event of interest\n registrationData.events_of_interest.forEach((event, index) => {\n if (!event.provider_id?.trim()) {\n throw new IOEventsApiError(`Provider ID is required for event at index ${index}`, 400);\n }\n if (!event.event_code?.trim()) {\n throw new IOEventsApiError(`Event code is required for event at index ${index}`, 400);\n }\n });\n\n if (!registrationData.delivery_type?.trim()) {\n throw new IOEventsApiError('Delivery type is required', 400);\n }\n\n const validDeliveryTypes = ['webhook', 'webhook_batch', 'journal', 'aws_eventbridge'];\n if (!validDeliveryTypes.includes(registrationData.delivery_type)) {\n throw new IOEventsApiError(\n `Delivery type must be one of: ${validDeliveryTypes.join(', ')}`,\n 400\n );\n }\n\n if (registrationData.runtime_action && registrationData.runtime_action.length > 255) {\n throw new IOEventsApiError('Runtime action must not exceed 255 characters', 400);\n }\n }\n\n /**\n * Handles errors from the API call\n */\n private handleError(error: any): never {\n // Re-throw validation errors as-is\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n if (error.response?.status) {\n const statusCode = error.response.status;\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n if (error.status) {\n const statusCode = error.status;\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n throw new IOEventsApiError('Network error occurred', 500);\n }\n\n /**\n * Extracts status code from HTTP error message\n */\n private extractStatusCodeFromMessage(message: string): number {\n const match = message.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : 500;\n }\n\n /**\n * Gets appropriate error message for HTTP status code\n */\n private getErrorMessageForStatus(statusCode: number): string {\n switch (statusCode) {\n case 400:\n return 'Bad request: Invalid registration data provided';\n case 401:\n return 'Unauthorized: Invalid or missing authentication';\n case 403:\n return 'Forbidden: Insufficient permissions';\n case 409:\n return 'Conflict: Registration with this name already exists';\n case 422:\n return 'Unprocessable entity: Invalid registration data';\n case 500:\n return 'Internal server error';\n default:\n return `API error: HTTP ${statusCode}`;\n }\n }\n}\n\nexport default Create;\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\n\n/**\n * Service for deleting registrations\n */\nexport class Delete {\n private restClient: RestClient;\n private endpoint: string;\n private clientId: string;\n private consumerId: string;\n private projectId: string;\n private workspaceId: string;\n private accessToken: string;\n\n /**\n * Initialize the Delete service\n */\n constructor(\n clientId: string,\n consumerId: string,\n projectId: string,\n workspaceId: string,\n accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new IOEventsApiError('clientId is required and cannot be empty', 400);\n }\n if (!consumerId?.trim()) {\n throw new IOEventsApiError('consumerId is required and cannot be empty', 400);\n }\n if (!projectId?.trim()) {\n throw new IOEventsApiError('projectId is required and cannot be empty', 400);\n }\n if (!workspaceId?.trim()) {\n throw new IOEventsApiError('workspaceId is required and cannot be empty', 400);\n }\n if (!accessToken?.trim()) {\n throw new IOEventsApiError('accessToken is required and cannot be empty', 400);\n }\n\n this.restClient = new RestClient();\n this.endpoint = IoEventsGlobals.BASE_URL;\n this.clientId = clientId;\n this.consumerId = consumerId;\n this.projectId = projectId;\n this.workspaceId = workspaceId;\n this.accessToken = accessToken;\n }\n\n /**\n * Delete a registration by ID\n *\n * @param registrationId - The registration ID to delete\n * @returns Promise<void> - Resolves when deletion is successful\n * @throws IOEventsApiError - When the API call fails\n *\n * @example\n * ```typescript\n * await registrationManager.delete('your-registration-id');\n * console.log('Registration deleted successfully');\n * ```\n */\n async execute(registrationId: string): Promise<void> {\n try {\n this.validateInputs(registrationId);\n\n const url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/registrations/${registrationId}`;\n\n await this.restClient.delete(url, {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n Accept: 'text/plain',\n });\n\n // Delete operation returns 204 No Content on success\n } catch (error) {\n this.handleError(error);\n }\n }\n\n /**\n * Validates the input parameters\n */\n private validateInputs(registrationId: string): void {\n if (!registrationId?.trim()) {\n throw new IOEventsApiError('Registration ID is required', 400);\n }\n }\n\n /**\n * Handles errors from the API call\n */\n private handleError(error: any): never {\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n if (error.response?.status) {\n const statusCode = error.response.status;\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n if (error.status) {\n const statusCode = error.status;\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n throw new IOEventsApiError('Network error occurred', 500);\n }\n\n /**\n * Extracts status code from HTTP error message\n */\n private extractStatusCodeFromMessage(message: string): number {\n const match = message.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : 500;\n }\n\n /**\n * Gets appropriate error message for HTTP status code\n */\n private getErrorMessageForStatus(statusCode: number): string {\n switch (statusCode) {\n case 400:\n return 'Bad request: Invalid registration ID provided';\n case 401:\n return 'Unauthorized: Invalid or missing authentication';\n case 403:\n return 'Forbidden: Insufficient permissions';\n case 404:\n return 'Registration not found';\n case 500:\n return 'Internal server error';\n default:\n return `API error: HTTP ${statusCode}`;\n }\n }\n}\n\nexport default Delete;\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\nimport type { Registration } from '../types';\n\n/**\n * Service for getting a specific registration by ID\n */\nexport class Get {\n private restClient: RestClient;\n private endpoint: string;\n private clientId: string;\n private consumerId: string;\n private projectId: string;\n private workspaceId: string;\n private accessToken: string;\n\n /**\n * Initialize the Get service\n */\n constructor(\n clientId: string,\n consumerId: string,\n projectId: string,\n workspaceId: string,\n accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new IOEventsApiError('clientId is required and cannot be empty', 400);\n }\n if (!consumerId?.trim()) {\n throw new IOEventsApiError('consumerId is required and cannot be empty', 400);\n }\n if (!projectId?.trim()) {\n throw new IOEventsApiError('projectId is required and cannot be empty', 400);\n }\n if (!workspaceId?.trim()) {\n throw new IOEventsApiError('workspaceId is required and cannot be empty', 400);\n }\n if (!accessToken?.trim()) {\n throw new IOEventsApiError('accessToken is required and cannot be empty', 400);\n }\n\n this.restClient = new RestClient();\n this.endpoint = IoEventsGlobals.BASE_URL;\n this.clientId = clientId;\n this.consumerId = consumerId;\n this.projectId = projectId;\n this.workspaceId = workspaceId;\n this.accessToken = accessToken;\n }\n\n /**\n * Get a registration by ID\n *\n * @param registrationId - The registration ID to retrieve\n * @returns Promise<Registration> - The registration data\n * @throws IOEventsApiError - When the API call fails\n *\n * @example\n * ```typescript\n * const registration = await registrationManager.get('your-registration-id');\n * console.log(registration.name);\n * ```\n */\n async execute(registrationId: string): Promise<Registration> {\n try {\n this.validateInputs(registrationId);\n\n const url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/registrations/${registrationId}`;\n\n const response = await this.restClient.get(url, {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n Accept: 'application/hal+json',\n });\n\n return response as Registration;\n } catch (error) {\n this.handleError(error);\n }\n }\n\n /**\n * Validates the input parameters\n */\n private validateInputs(registrationId: string): void {\n if (!registrationId?.trim()) {\n throw new IOEventsApiError('Registration ID is required', 400);\n }\n }\n\n /**\n * Handles errors from the API call\n */\n private handleError(error: any): never {\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n if (error.response?.status) {\n const statusCode = error.response.status;\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n if (error.status) {\n const statusCode = error.status;\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n throw new IOEventsApiError('Network error occurred', 500);\n }\n\n /**\n * Extracts status code from HTTP error message\n */\n private extractStatusCodeFromMessage(message: string): number {\n const match = message.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : 500;\n }\n\n /**\n * Gets appropriate error message for HTTP status code\n */\n private getErrorMessageForStatus(statusCode: number): string {\n switch (statusCode) {\n case 400:\n return 'Bad request: Invalid parameters provided';\n case 401:\n return 'Unauthorized: Invalid or missing authentication';\n case 403:\n return 'Forbidden: Insufficient permissions';\n case 404:\n return 'Registration not found';\n case 500:\n return 'Internal server error';\n default:\n return `API error: HTTP ${statusCode}`;\n }\n }\n}\n\nexport default Get;\n","/**\n * <license header>\n */\n\nimport RestClient from '../../../integration/rest-client';\nimport { IOEventsApiError, IoEventsGlobals } from '../../types';\nimport type { Registration } from '../types';\nimport type { RegistrationListResponse, ListRegistrationQueryParams } from './types';\n\n/**\n * Service for listing registrations with automatic pagination\n */\nexport class List {\n private restClient: RestClient;\n private endpoint: string;\n private clientId: string;\n private consumerId: string;\n private projectId: string;\n private workspaceId: string;\n private accessToken: string;\n\n /**\n * Initialize the List service\n */\n constructor(\n clientId: string,\n consumerId: string,\n projectId: string,\n workspaceId: string,\n accessToken: string\n ) {\n if (!clientId?.trim()) {\n throw new IOEventsApiError('clientId is required and cannot be empty', 400);\n }\n if (!consumerId?.trim()) {\n throw new IOEventsApiError('consumerId is required and cannot be empty', 400);\n }\n if (!projectId?.trim()) {\n throw new IOEventsApiError('projectId is required and cannot be empty', 400);\n }\n if (!workspaceId?.trim()) {\n throw new IOEventsApiError('workspaceId is required and cannot be empty', 400);\n }\n if (!accessToken?.trim()) {\n throw new IOEventsApiError('accessToken is required and cannot be empty', 400);\n }\n\n this.restClient = new RestClient();\n this.endpoint = IoEventsGlobals.BASE_URL;\n this.clientId = clientId;\n this.consumerId = consumerId;\n this.projectId = projectId;\n this.workspaceId = workspaceId;\n this.accessToken = accessToken;\n }\n\n /**\n * Execute registration list with automatic pagination\n */\n async execute(queryParams?: ListRegistrationQueryParams): Promise<Registration[]> {\n try {\n this.validateInputs();\n\n let url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/registrations`;\n\n // Add query parameters if provided\n if (queryParams && Object.keys(queryParams).length > 0) {\n const searchParams = new URLSearchParams();\n Object.entries(queryParams).forEach(([key, value]) => {\n if (value !== undefined && value !== null) {\n searchParams.append(key, String(value));\n }\n });\n if (searchParams.toString()) {\n url += `?${searchParams.toString()}`;\n }\n }\n\n return await this.fetchAllPages(url);\n } catch (error: any) {\n this.handleError(error);\n }\n }\n\n /**\n * Fetch all pages recursively\n */\n private async fetchAllPages(\n url: string,\n accumulatedResults: Registration[] = []\n ): Promise<Registration[]> {\n const headers = {\n Authorization: `Bearer ${this.accessToken}`,\n 'x-api-key': this.clientId,\n 'Content-Type': 'application/json',\n };\n\n const data = (await this.restClient.get(url, headers)) as RegistrationListResponse;\n\n // Extract registrations from current page\n const currentPageRegistrations = data._embedded?.registrations || [];\n const allResults = [...accumulatedResults, ...currentPageRegistrations];\n\n // Check if there's a next page\n const nextPageUrl = data._links?.next?.href;\n if (nextPageUrl) {\n // Recursively fetch the next page\n return await this.fetchAllPages(nextPageUrl, allResults);\n }\n\n return allResults;\n }\n\n /**\n * Validate required inputs\n */\n private validateInputs(): void {\n if (!this.consumerId?.trim()) {\n throw new IOEventsApiError(\n 'Consumer ID is required',\n IoEventsGlobals.STATUS_CODES.BAD_REQUEST\n );\n }\n if (!this.projectId?.trim()) {\n throw new IOEventsApiError(\n 'Project ID is required',\n IoEventsGlobals.STATUS_CODES.BAD_REQUEST\n );\n }\n if (!this.workspaceId?.trim()) {\n throw new IOEventsApiError(\n 'Workspace ID is required',\n IoEventsGlobals.STATUS_CODES.BAD_REQUEST\n );\n }\n if (!this.accessToken?.trim()) {\n throw new IOEventsApiError(\n 'Access token is required',\n IoEventsGlobals.STATUS_CODES.BAD_REQUEST\n );\n }\n }\n\n /**\n * Handle and categorize errors\n */\n private handleError(error: any): never {\n // Handle RestClient HTTP errors (e.g., \"HTTP error! status: 404\")\n if (error instanceof Error && error.message.includes('HTTP error! status:')) {\n const statusCode = this.extractStatusCodeFromMessage(error.message);\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n // Handle structured API error responses\n if (error.response) {\n const statusCode =\n error.response.status || error.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n const errorMessage = this.getErrorMessageForStatus(statusCode);\n throw new IOEventsApiError(errorMessage, statusCode);\n }\n\n // Handle other errors\n if (error instanceof IOEventsApiError) {\n throw error;\n }\n\n // Default error handling\n throw new IOEventsApiError(\n error.message || 'An unexpected error occurred while listing registrations',\n IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR\n );\n }\n\n /**\n * Extract status code from error message\n */\n private extractStatusCodeFromMessage(errorMessage: string): number {\n const match = errorMessage.match(/HTTP error! status:\\s*(\\d+)/);\n return match ? parseInt(match[1]!, 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;\n }\n\n /**\n * Get appropriate error message for status code\n */\n private getErrorMessageForStatus(statusCode: number): string {\n switch (statusCode) {\n case IoEventsGlobals.STATUS_CODES.BAD_REQUEST:\n return 'Bad request. Please check your input parameters';\n case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:\n return 'Unauthorized. Please check your access token';\n case IoEventsGlobals.STATUS_CODES.FORBIDDEN:\n return 'Forbidden. You do not have permission to access registrations';\n case IoEventsGlobals.STATUS_CODES.NOT_FOUND:\n return 'Registrations not found. The specified workspace may not exist or have no registrations';\n case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:\n return 'Internal server error. Please try again later';\n default:\n return `API request failed with status ${statusCode}`;\n }\n }\n}\n\nexport default List;\n","/**\n * <license header>\n */\n\nimport Create from './create';\nimport Delete from './delete';\nimport Get from './get';\nimport List from './list';\nimport type { Registration } from './types';\nimport type { RegistrationCreateModel } from './create/types';\nimport type { ListRegistrationQueryParams } from './list/types';\n\n/**\n * Manager class for registration operations\n */\nexport class RegistrationManager {\n private createService: Create;\n private deleteService: Delete;\n private getService: Get;\n private listService: List;\n\n /**\n * Initialize the RegistrationManager\n */\n constructor(\n clientId: string,\n consumerId: string,\n projectId: string,\n workspaceId: string,\n accessToken: string\n ) {\n this.createService = new Create(clientId, consumerId, projectId, workspaceId, accessToken);\n this.deleteService = new Delete(clientId, consumerId, projectId, workspaceId, accessToken);\n this.getService = new Get(clientId, consumerId, projectId, workspaceId, accessToken);\n this.listService = new List(clientId, consumerId, projectId, workspaceId, accessToken);\n }\n\n /**\n * Create a new registration\n *\n * @param registrationData - The registration data to create\n * @returns Promise<Registration> - The created registration\n *\n * @example\n * ```typescript\n * const registration = await registrationManager.create({\n * client_id: 'your-client-id',\n * name: 'My Registration',\n * description: 'Registration for user events',\n * webhook_url: 'https://example.com/webhook',\n * events_of_interest: [\n * {\n * provider_id: 'provider-123',\n * event_code: 'com.example.user.created'\n * }\n * ],\n * delivery_type: 'webhook',\n * enabled: true\n * });\n * console.log(registration.registration_id);\n * ```\n */\n async create(registrationData: RegistrationCreateModel): Promise<Registration> {\n return await this.createService.execute(registrationData);\n }\n\n /**\n * Delete a registration by ID\n *\n * @param registrationId - The registration ID to delete\n * @returns Promise<void> - Resolves when deletion is successful\n *\n * @example\n * ```typescript\n * await registrationManager.delete('your-registration-id');\n * console.log('Registration deleted successfully');\n * ```\n */\n async delete(registrationId: string): Promise<void> {\n return await this.deleteService.execute(registrationId);\n }\n\n /**\n * Get a registration by ID\n *\n * @param registrationId - The registration ID to retrieve\n * @returns Promise<Registration> - The registration data\n *\n * @example\n * ```typescript\n * const registration = await registrationManager.get('your-registration-id');\n * console.log(registration.name);\n * ```\n */\n async get(registrationId: string): Promise<Registration> {\n return await this.getService.execute(registrationId);\n }\n\n /**\n * List all registrations with automatic pagination\n *\n * @param queryParams - Optional query parameters for filtering\n * @returns Promise<Registration[]> - Array of all registrations across all pages\n *\n * @example\n * ```typescript\n * // List all registrations\n * const registrations = await registrationManager.list();\n *\n * // List with query parameters\n * const filteredRegistrations = await registrationManager.list({\n * enabled: true\n * });\n * ```\n */\n async list(queryParams?: ListRegistrationQueryParams): Promise<Registration[]> {\n return await this.listService.execute(queryParams);\n }\n}\n\nexport default RegistrationManager;\n","/**\n * <license header>\n */\n\nimport type { Logger } from '@adobe/aio-sdk';\nimport type { ParsedProvider, CreateProviderResult } from '../types';\nimport { ProviderManager } from '../../../io-events';\nimport { randomUUID } from 'crypto';\n\n/**\n * Utility class for creating providers in Adobe Commerce onboarding integrations\n *\n * @example\n * const logger = Core.Logger('my-create-providers', { level: 'debug' });\n * const createProviders = new CreateProviders(\n * 'your-consumer-id',\n * 'your-project-id',\n * 'your-workspace-id',\n * 'your-api-key',\n * 'your-access-token',\n * logger\n * );\n *\n * // Process providers for creation\n * await createProviders.process(providers);\n */\nclass CreateProviders {\n private readonly logger: Logger;\n private providerManager: ProviderManager | null = null;\n\n /**\n * Creates a new CreateProviders instance\n *\n * @param consumerId - Adobe I/O consumer ID\n * @param projectId - Adobe I/O project ID\n * @param workspaceId - Adobe I/O workspace ID\n * @param apiKey - API key for authentication\n * @param accessToken - Access token for API calls\n * @param logger - Logger instance for consistent logging\n */\n constructor(\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly apiKey: string,\n private readonly accessToken: string,\n logger: Logger\n ) {\n // Validate configuration\n const config = {\n consumerId: this.consumerId,\n projectId: this.projectId,\n workspaceId: this.workspaceId,\n apiKey: this.apiKey,\n accessToken: this.accessToken,\n };\n const required = ['consumerId', 'projectId', 'workspaceId', 'apiKey', 'accessToken'];\n const missing = required.filter(\n key => !config[key as keyof typeof config] || config[key as keyof typeof config].trim() === ''\n );\n\n if (missing.length > 0) {\n throw new Error(`Missing required configuration: ${missing.join(', ')}`);\n }\n\n if (!logger) {\n throw new Error('Logger is required');\n }\n\n // Use the provided logger\n this.logger = logger;\n\n this.logger.debug(`[INIT] CreateProviders initialized with valid configuration`);\n }\n\n /**\n * Processes providers for creation in the Adobe Commerce integration\n *\n * @param providers - Array of parsed provider configurations to create\n * @param projectName - Name of the project for enhanced labeling\n * @returns Promise resolving to processing result\n */\n async process(\n providers: ParsedProvider[],\n projectName: string = 'Unknown Project'\n ): Promise<CreateProviderResult[]> {\n this.logger.debug(`[CREATE] Creating providers for project: ${projectName}`);\n this.logger.debug(`[INFO] Processing ${providers.length} provider(s)...`);\n\n try {\n // Fetch existing providers first\n const existingProviders = await this.getProviders();\n\n const results: CreateProviderResult[] = [];\n\n for (const provider of providers) {\n const result = await this.createProvider(provider, projectName, existingProviders);\n results.push(result);\n }\n\n this.logger.debug('[DONE] Provider creation completed');\n\n // Show provider IDs in results\n results.forEach(result => {\n if (result.provider.id) {\n this.logger.debug(\n `[ID] Provider ID: ${result.provider.id} (${result.provider.originalLabel})`\n );\n }\n });\n\n return results;\n } catch (error: any) {\n this.logger.error(`[ERROR] Provider creation failed: ${error.message}`);\n throw error;\n }\n }\n\n /**\n * Gets the Provider SDK instance from the framework\n * @private\n */\n private getProviderManager(): ProviderManager {\n if (!this.providerManager) {\n this.providerManager = new ProviderManager(\n this.apiKey,\n this.consumerId,\n this.projectId,\n this.workspaceId,\n this.accessToken\n );\n }\n\n return this.providerManager;\n }\n\n /**\n * Gets existing providers from Adobe I/O\n * @returns Promise<Map> Map of existing providers by label\n */\n private async getProviders(): Promise<Map<string, any>> {\n this.logger.debug('[FETCH] Fetching existing providers...');\n\n try {\n const providerManager = this.getProviderManager();\n const providerList = await providerManager.list();\n\n const existingProviders = new Map<string, any>();\n providerList.forEach((provider: any) => {\n existingProviders.set(provider.label, provider);\n });\n\n this.logger.debug(`[INFO] Found ${existingProviders.size} existing providers`);\n return existingProviders;\n } catch (error: any) {\n this.logger.error(`[ERROR] Failed to fetch existing providers: ${error.message}`);\n throw error;\n }\n }\n\n /**\n * Creates a single provider\n * @param providerData - Provider configuration data\n * @param projectName - Project name for enhanced labeling\n * @param existingProviders - Map of existing providers by label\n * @private\n */\n private async createProvider(\n providerData: ParsedProvider,\n projectName: string,\n existingProviders: Map<string, any>\n ): Promise<CreateProviderResult> {\n const enhancedLabel = `${projectName} - ${providerData.label}`;\n this.logger.debug(\n `[PROCESS] Processing provider: ${providerData.label} with enhanced label: ${enhancedLabel}`\n );\n\n // Check if provider already exists\n const existingProvider = existingProviders.get(enhancedLabel);\n\n if (existingProvider) {\n this.logger.debug(`[SKIP] Provider already exists - skipping creation`);\n this.logger.debug(`[ID] Existing ID: ${existingProvider.id}`);\n\n return {\n created: false,\n skipped: true,\n provider: {\n id: existingProvider.id,\n ...(existingProvider.instance_id && { instanceId: existingProvider.instance_id }),\n key: providerData.key,\n label: enhancedLabel,\n originalLabel: providerData.label,\n description: providerData.description,\n docsUrl: providerData.docsUrl,\n },\n reason: 'Already exists',\n raw: existingProvider,\n };\n }\n\n try {\n const providerInput = this.preparePayload(providerData, enhancedLabel);\n\n this.logger.debug(`[NEW] Creating new provider: ${enhancedLabel}`);\n\n const createdProvider = await this.getProviderManager().create(providerInput);\n\n this.logger.debug(\n `[INFO] Provider created successfully! ID: ${createdProvider.id}, Instance ID: ${createdProvider.instance_id}`\n );\n\n const result: CreateProviderResult = {\n created: true,\n skipped: false,\n provider: {\n id: createdProvider.id,\n ...(createdProvider.instance_id && { instanceId: createdProvider.instance_id }),\n key: providerData.key,\n label: createdProvider.label,\n originalLabel: providerData.label,\n description: providerData.description,\n docsUrl: providerData.docsUrl,\n },\n raw: createdProvider,\n };\n\n return result;\n } catch (error: any) {\n this.logger.error(`[ERROR] Failed to create provider \"${enhancedLabel}\": ${error.message}`);\n\n return {\n created: false,\n skipped: false,\n error: error.message,\n provider: {\n key: providerData.key,\n label: enhancedLabel,\n originalLabel: providerData.label,\n description: providerData.description,\n docsUrl: providerData.docsUrl,\n },\n };\n }\n }\n\n /**\n * Prepares payload object for Adobe I/O API\n * @param providerData - Provider configuration data\n * @param enhancedLabel - Enhanced provider label\n * @private\n */\n private preparePayload(providerData: ParsedProvider, enhancedLabel: string): any {\n const input: any = {\n label: enhancedLabel,\n };\n\n // Add description if provided\n if (providerData.description) {\n input.description = providerData.description;\n }\n\n // Add docs URL if provided\n if (providerData.docsUrl) {\n input.docs_url = providerData.docsUrl;\n }\n\n // Add special commerce provider metadata if needed\n if (this.isCommerceProvider(providerData)) {\n input.provider_metadata = 'dx_commerce_events';\n input.instance_id = randomUUID();\n }\n\n return input;\n }\n\n /**\n * Determines if provider is a commerce provider\n * @private\n */\n private isCommerceProvider(providerData: ParsedProvider): boolean {\n const commerceIndicators = ['commerce', 'magento', 'adobe commerce'];\n const key = providerData.key.toLowerCase();\n const label = providerData.label.toLowerCase();\n const description = (providerData.description || '').toLowerCase();\n\n return commerceIndicators.some(\n indicator =>\n key.includes(indicator) || label.includes(indicator) || description.includes(indicator)\n );\n }\n}\n\nexport default CreateProviders;\n","/**\n * <license header>\n */\n\nimport type { Logger } from '@adobe/aio-sdk';\nimport { EventMetadataManager, type EventMetadata } from '../../../io-events';\nimport type { ParsedEvent, CreateEventResult, CreateProviderResult } from '../types';\n\n/**\n * Utility class for creating event metadata in Adobe Commerce onboarding integrations\n *\n * @example\n * const logger = Core.Logger('my-create-events', { level: 'debug' });\n * const createEvents = new CreateEvents(\n * 'your-consumer-id',\n * 'your-project-id',\n * 'your-workspace-id',\n * 'your-client-id',\n * 'your-access-token',\n * logger\n * );\n *\n * // Process events for creation\n * await createEvents.process(events, providerResults);\n */\nclass CreateEvents {\n private readonly logger: Logger;\n private eventMetadataManager: EventMetadataManager | null = null;\n\n /**\n * Creates a new CreateEvents instance\n *\n * @param consumerId - Adobe I/O consumer ID\n * @param projectId - Adobe I/O project ID\n * @param workspaceId - Adobe I/O workspace ID\n * @param clientId - Adobe I/O client ID\n * @param accessToken - Adobe I/O access token\n * @param logger - Logger instance for consistent logging\n */\n constructor(\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly clientId: string,\n private readonly accessToken: string,\n logger: Logger\n ) {\n // Validate configuration\n const config = {\n consumerId: this.consumerId,\n projectId: this.projectId,\n workspaceId: this.workspaceId,\n clientId: this.clientId,\n accessToken: this.accessToken,\n };\n const required = ['consumerId', 'projectId', 'workspaceId', 'clientId', 'accessToken'];\n const missing = required.filter(\n key => !config[key as keyof typeof config] || config[key as keyof typeof config].trim() === ''\n );\n\n if (missing.length > 0) {\n throw new Error(`Missing required configuration: ${missing.join(', ')}`);\n }\n\n if (!logger) {\n throw new Error('Logger is required');\n }\n\n // Use the provided logger\n this.logger = logger;\n\n this.logger.debug(`[INIT] CreateEvents initialized with valid configuration`);\n }\n\n /**\n * Gets the EventMetadataManager instance (lazy initialization)\n * @private\n * @returns EventMetadataManager instance\n */\n private getEventMetadataManager(): EventMetadataManager {\n if (!this.eventMetadataManager) {\n this.eventMetadataManager = new EventMetadataManager(\n this.clientId,\n this.consumerId,\n this.projectId,\n this.workspaceId,\n this.accessToken\n );\n }\n return this.eventMetadataManager;\n }\n\n /**\n * Creates event metadata for a specific provider\n * @private\n * @param providerId - Provider ID to create event for\n * @param event - Parsed event data\n * @param existingEvents - Array of existing event metadata\n * @returns Promise<CreateEventResult> - Event creation result\n */\n private async createEvent(\n providerId: string,\n event: ParsedEvent,\n existingEvents: EventMetadata[]\n ): Promise<CreateEventResult> {\n try {\n const eventCode = event.eventCode;\n this.logger.debug(`[INFO] Processing event: ${eventCode}`);\n\n // Check if event metadata already exists\n const existingEvent = existingEvents.find(metadata => metadata.event_code === eventCode);\n\n if (existingEvent) {\n this.logger.debug(\n `[INFO] Event code '${eventCode}' already exists for provider ${providerId}`\n );\n this.logger.debug(`[SKIP] Event metadata already exists for: ${eventCode} - skipping`);\n return {\n created: false,\n skipped: true,\n event: {\n id: existingEvent.id,\n eventCode: eventCode,\n ...(existingEvent.label && { label: existingEvent.label }),\n ...(existingEvent.description && { description: existingEvent.description }),\n ...(existingEvent.sample_event_template && {\n sampleEventTemplate: existingEvent.sample_event_template,\n }),\n },\n raw: existingEvent,\n };\n }\n\n this.logger.debug(`[CREATE] Creating event metadata: ${eventCode}`);\n\n // Build the payload for EventMetadataInputModel\n const metadataPayload = {\n event_code: eventCode,\n label: eventCode,\n description: eventCode,\n ...(event.sampleEventTemplate ? { sample_event_template: event.sampleEventTemplate } : {}),\n };\n\n const eventMetadata = this.getEventMetadataManager();\n const result = await eventMetadata.create(providerId, metadataPayload);\n\n if (result) {\n const eventId = result.id || result.event_code || eventCode;\n this.logger.debug(`[SUCCESS] Event metadata created successfully: ${eventCode}`);\n\n return {\n created: true,\n skipped: false,\n event: {\n id: eventId,\n eventCode: eventCode,\n label: metadataPayload.label,\n description: metadataPayload.description,\n ...(metadataPayload.sample_event_template && {\n sampleEventTemplate: metadataPayload.sample_event_template,\n }),\n },\n raw: result,\n };\n } else {\n throw new Error('Event metadata creation returned no result');\n }\n } catch (error) {\n const eventCode = event.eventCode;\n this.logger.error(\n `[ERROR] Error creating event metadata for ${eventCode}: ${(error as Error).message}`\n );\n return {\n created: false,\n skipped: false,\n event: {\n eventCode: eventCode,\n },\n error: (error as Error).message,\n };\n }\n }\n\n /**\n * Fetches existing event metadata for a provider to avoid duplicates\n * @private\n * @param providerId - Provider ID to fetch metadata for\n * @returns Promise<EventMetadata[]> - List of existing event metadata\n */\n private async fetchMetadata(providerId: string): Promise<EventMetadata[]> {\n try {\n this.logger.debug(`[INFO] Fetching existing event metadata for provider: ${providerId}`);\n\n const eventMetadata = this.getEventMetadataManager();\n const existingList = await eventMetadata.list(providerId);\n\n this.logger.debug(`[INFO] Found ${existingList.length} existing event metadata entries`);\n return existingList;\n } catch (error) {\n this.logger.error(\n `[ERROR] Error fetching existing metadata for provider ${providerId}: ${(error as Error).message}`\n );\n return [];\n }\n }\n\n /**\n * Processes events for creation based on parsed events and provider results\n *\n * @param events - Array of parsed events from InputParser\n * @param providerResults - Array of provider creation results\n * @param projectName - Name of the project for enhanced labeling\n * @returns Promise resolving to event creation results\n */\n async process(\n events: ParsedEvent[],\n providerResults: CreateProviderResult[],\n projectName: string = 'Unknown Project'\n ): Promise<CreateEventResult[]> {\n this.logger.debug(`[CREATE] Creating events for project: ${projectName}`);\n this.logger.debug(\n `[INFO] Processing ${events.length} event(s) across ${providerResults.length} provider(s)...`\n );\n\n if (!events || events.length === 0) {\n this.logger.debug('[INFO] No events to process.');\n return [];\n }\n\n if (!providerResults || providerResults.length === 0) {\n this.logger.debug('[INFO] No provider results to process.');\n return [];\n }\n\n try {\n const results: CreateEventResult[] = [];\n\n for (const providerResult of providerResults) {\n const providerId = providerResult.provider.id;\n if (!providerId) {\n this.logger.debug(\n `[WARN] Skipping provider without ID: ${providerResult.provider.originalLabel}`\n );\n continue;\n }\n\n this.logger.debug(\n `[INFO] Processing events for provider: ${providerResult.provider.originalLabel}`\n );\n\n // Fetch existing metadata for this provider\n const existingEvents = await this.fetchMetadata(providerId);\n\n // Find events that belong to this provider\n const providerEvents = events.filter(\n event => event.providerKey === providerResult.provider.key\n );\n\n if (providerEvents.length === 0) {\n this.logger.debug(\n `[INFO] No events found for provider: ${providerResult.provider.originalLabel}`\n );\n continue;\n }\n\n this.logger.debug(`[INFO] Found ${providerEvents.length} event(s) for this provider`);\n\n // Process each event for this provider\n for (const event of providerEvents) {\n const eventResult = await this.createEvent(providerId, event, existingEvents);\n eventResult.provider = providerResult.provider;\n results.push(eventResult);\n }\n }\n\n return results;\n } catch (error) {\n this.logger.error(`[ERROR] Event metadata creation failed: ${(error as Error).message}`);\n throw error;\n }\n }\n}\n\nexport default CreateEvents;\n","/**\n * <license header>\n */\n\nimport type { Logger } from '@adobe/aio-sdk';\nimport { RegistrationManager } from '../../../io-events/registration';\nimport type { Registration } from '../../../io-events/registration/types';\nimport type { RegistrationCreateModel } from '../../../io-events/registration/create/types';\nimport type {\n ParsedRegistration,\n ParsedEvent,\n CreateRegistrationResult,\n CreateProviderResult,\n} from '../types';\n\n/**\n * Utility class for creating registrations in Adobe Commerce onboarding integrations\n *\n * @example\n * const logger = Core.Logger('my-create-registrations', { level: 'debug' });\n * const createRegistrations = new CreateRegistrations(\n * 'your-consumer-id',\n * 'your-project-id',\n * 'your-workspace-id',\n * 'your-client-id',\n * 'your-access-token',\n * logger\n * );\n *\n * // Process registrations for creation\n * await createRegistrations.process(registrations, providerResults);\n */\nclass CreateRegistrations {\n private readonly logger: Logger;\n private registrationManager?: RegistrationManager;\n\n /**\n * Creates a new CreateRegistrations instance\n *\n * @param consumerId - Adobe I/O consumer ID\n * @param projectId - Adobe I/O project ID\n * @param workspaceId - Adobe I/O workspace ID\n * @param clientId - Adobe I/O client ID\n * @param accessToken - Adobe I/O access token\n * @param logger - Logger instance for consistent logging\n */\n constructor(\n private readonly consumerId: string,\n private readonly projectId: string,\n private readonly workspaceId: string,\n private readonly clientId: string,\n private readonly accessToken: string,\n logger: Logger\n ) {\n // Validate configuration\n const config = {\n consumerId: this.consumerId,\n projectId: this.projectId,\n workspaceId: this.workspaceId,\n clientId: this.clientId,\n accessToken: this.accessToken,\n };\n\n const required = ['consumerId', 'projectId', 'workspaceId', 'clientId', 'accessToken'];\n const missing = required.filter(\n key => !config[key as keyof typeof config] || config[key as keyof typeof config].trim() === ''\n );\n\n if (missing.length > 0) {\n throw new Error(`Missing required configuration: ${missing.join(', ')}`);\n }\n\n if (!logger) {\n throw new Error('Logger is required');\n }\n\n this.logger = logger;\n this.logger.debug(`[INIT] CreateRegistrations initialized with valid configuration`);\n }\n\n /**\n * Process multiple registrations for creation\n *\n * @param registrations - Array of parsed registrations to process\n * @param events - Array of parsed events for registration creation\n * @param providerResults - Array of provider results to link registrations to\n * @param projectName - Optional project name for logging\n * @returns Promise resolving to array of registration creation results\n */\n async process(\n registrations: ParsedRegistration[],\n events: ParsedEvent[],\n providerResults: CreateProviderResult[],\n projectName: string = 'Unknown Project'\n ): Promise<CreateRegistrationResult[]> {\n this.logger.debug(`[INFO] Creating registrations for project: ${projectName}`);\n this.logger.debug(\n `[PROCESSING] Processing ${registrations.length} registration(s) with ${events.length} event(s) across ${providerResults.length} provider(s)...`\n );\n\n if (!registrations || registrations.length === 0) {\n this.logger.debug('[SKIP] No registrations to process.');\n return [];\n }\n\n if (!events || events.length === 0) {\n this.logger.debug('[SKIP] No events to process.');\n return [];\n }\n\n if (!providerResults || providerResults.length === 0) {\n this.logger.debug('[SKIP] No provider results to process.');\n return [];\n }\n\n try {\n // Fetch existing registrations first\n const existingRegistrations = await this.fetchRegistrations();\n\n const results: CreateRegistrationResult[] = [];\n\n for (const registration of registrations) {\n this.logger.debug(`[PROCESSING] Processing registration: ${registration.label}`);\n\n // Find events that belong to this registration\n const registrationEvents = events.filter(\n event => event.registrationKey === registration.key\n );\n\n if (registrationEvents.length === 0) {\n this.logger.debug(`[SKIP] No events found for registration: ${registration.label}`);\n continue;\n }\n\n this.logger.debug(\n `[INFO] Found ${registrationEvents.length} event(s) for this registration`\n );\n\n // Group events by provider to create separate registrations per provider\n const eventsByProvider = this.groupEventsByProvider(registrationEvents);\n\n for (const [providerKey, providerEvents] of Object.entries(eventsByProvider)) {\n const provider = providerResults.find(p => p.provider.key === providerKey);\n\n if (!provider || !provider.provider.id) {\n this.logger.debug(`[SKIP] Provider not found or missing ID for: ${providerKey}`);\n continue;\n }\n\n const result = await this.createRegistration(\n registration,\n providerEvents,\n provider,\n existingRegistrations\n );\n results.push(result);\n }\n }\n\n return results;\n } catch (error) {\n this.logger.error(`[ERROR] Registration creation failed: ${(error as Error).message}`);\n throw error;\n }\n }\n\n /**\n * Lazy initialization of RegistrationManager\n * @private\n * @returns RegistrationManager instance\n */\n private getRegistrationManager(): RegistrationManager {\n if (!this.registrationManager) {\n this.registrationManager = new RegistrationManager(\n this.clientId,\n this.consumerId,\n this.projectId,\n this.workspaceId,\n this.accessToken\n );\n }\n return this.registrationManager;\n }\n\n /**\n * Fetches existing registrations to avoid duplicates\n * @returns {Promise<Map>} Map of existing registrations by name\n */\n async fetchRegistrations(): Promise<Map<string, Registration>> {\n this.logger.debug('[INFO] Fetching existing registrations...');\n\n try {\n const registrationSDK = this.getRegistrationManager();\n const registrationList = await registrationSDK.list();\n\n const existingRegistrations = new Map<string, Registration>();\n registrationList.forEach(registration => {\n existingRegistrations.set(registration.name, registration);\n });\n\n this.logger.debug(`[INFO] Found ${existingRegistrations.size} existing registrations`);\n return existingRegistrations;\n } catch (error) {\n this.logger.error(\n `[ERROR] Failed to fetch existing registrations: ${(error as Error).message}`\n );\n throw error;\n }\n }\n\n /**\n * Groups events by their provider key\n * @private\n * @param events - Events to group\n * @returns Events grouped by provider key\n */\n private groupEventsByProvider(events: ParsedEvent[]): Record<string, ParsedEvent[]> {\n const grouped: Record<string, ParsedEvent[]> = {};\n\n events.forEach(event => {\n if (!grouped[event.providerKey]) {\n grouped[event.providerKey] = [];\n }\n grouped[event.providerKey]!.push(event);\n });\n\n return grouped;\n }\n\n /**\n * Builds registration input object for Adobe I/O API\n * @private\n * @param registration - Registration entity\n * @param events - Events for this registration\n * @param provider - Provider result\n * @param registrationName - Enhanced registration name\n * @param firstEvent - First event for common properties\n * @returns Registration input for API\n */\n private preparePayload(\n registration: ParsedRegistration,\n events: ParsedEvent[],\n provider: CreateProviderResult,\n registrationName: string,\n firstEvent: ParsedEvent\n ): RegistrationCreateModel {\n // Build events of interest array\n const eventsOfInterest = events.map(event => ({\n provider_id: provider.provider.id || '',\n event_code: event.eventCode,\n }));\n\n const input: RegistrationCreateModel = {\n client_id: this.clientId,\n name: registrationName,\n description: registration.description || registrationName,\n delivery_type:\n (firstEvent.deliveryType as 'webhook' | 'webhook_batch' | 'journal' | 'aws_eventbridge') ||\n 'webhook',\n events_of_interest: eventsOfInterest,\n ...(firstEvent.runtimeAction && { runtime_action: firstEvent.runtimeAction }),\n };\n\n return input;\n }\n\n /**\n * Creates a single registration for a provider and its events\n * @private\n * @param registrationData - Registration entity\n * @param events - Events for this registration\n * @param provider - Provider result\n * @param existingRegistrations - Map of existing registrations\n * @returns Registration creation result\n */\n private async createRegistration(\n registrationData: ParsedRegistration,\n events: ParsedEvent[],\n provider: CreateProviderResult,\n existingRegistrations: Map<string, Registration>\n ): Promise<CreateRegistrationResult> {\n // Use the first event to get common properties (runtimeAction, deliveryType)\n const firstEvent = events[0];\n if (!firstEvent) {\n throw new Error('No events provided for registration creation');\n }\n\n const registrationName = registrationData.label;\n\n this.logger.debug(\n `[PROCESSING] Processing registration: ${registrationData.label} for provider: ${provider.provider.originalLabel}`\n );\n this.logger.debug(`[INFO] Registration name: ${registrationName}`);\n\n // Check if registration already exists\n const existingRegistration = existingRegistrations.get(registrationName);\n\n if (existingRegistration) {\n this.logger.debug('[SKIP] Registration already exists - skipping creation');\n this.logger.debug(`[INFO] Existing ID: ${existingRegistration.id}`);\n\n return {\n created: false,\n skipped: true,\n registration: {\n id: existingRegistration.id,\n key: registrationData.key,\n label: registrationData.label,\n originalLabel: registrationData.label,\n name: registrationName,\n description: registrationData.description,\n },\n reason: 'Already exists',\n raw: existingRegistration,\n };\n }\n\n // Create new registration\n this.logger.debug('[CREATE] Creating new registration...');\n\n try {\n const registrationInput = this.preparePayload(\n registrationData,\n events,\n provider,\n registrationName,\n firstEvent\n );\n\n this.logger.debug(`[INFO] Creating registration: ${registrationName}`);\n\n const registrationSDK = this.getRegistrationManager();\n const createdRegistration = await registrationSDK.create(registrationInput);\n\n this.logger.debug('[SUCCESS] Registration created successfully!');\n this.logger.debug(`[INFO] New ID: ${createdRegistration.id}`);\n this.logger.debug(`[INFO] Registration ID: ${createdRegistration.registration_id}`);\n\n const result = {\n created: true,\n skipped: false,\n registration: {\n id: createdRegistration.id,\n key: registrationData.key,\n label: registrationData.label,\n originalLabel: registrationData.label,\n name: createdRegistration.name,\n description: registrationData.description,\n },\n provider: provider.provider,\n raw: createdRegistration,\n };\n\n return result;\n } catch (error) {\n this.logger.error(\n `[ERROR] Failed to create registration \"${registrationName}\": ${(error as Error).message}`\n );\n\n return {\n created: false,\n skipped: false,\n error: (error as Error).message,\n registration: {\n key: registrationData.key,\n label: registrationData.label,\n originalLabel: registrationData.label,\n name: registrationName,\n description: registrationData.description,\n },\n provider: provider.provider,\n };\n }\n }\n}\n\nexport default CreateRegistrations;\n","/**\n * <license header>\n */\n\nimport type {\n OnboardEventsInput,\n OnboardProvider,\n OnboardRegistration,\n OnboardEvent,\n ParsedEntities,\n ParsedProvider,\n ParsedRegistration,\n ParsedEvent,\n} from '../types';\n\n/**\n * InputParser - Parses and extracts entities from OnboardEventsInput data\n */\nclass InputParser {\n private entities: ParsedEntities = {\n providers: [],\n registrations: [],\n events: [],\n };\n\n constructor(input: OnboardEventsInput) {\n for (const provider of input.providers) {\n // Add provider\n this.entities.providers.push(this.createProviderEntity(provider));\n\n // Add registrations and events\n for (const registration of provider.registrations) {\n this.entities.registrations.push(this.createRegistrationEntity(registration, provider.key));\n\n for (const event of registration.events) {\n this.entities.events.push(this.createEventEntity(event, registration.key, provider.key));\n }\n }\n }\n }\n\n /**\n * Create provider entity structure\n */\n private createProviderEntity(provider: OnboardProvider): ParsedProvider {\n return {\n key: provider.key,\n label: provider.label,\n description: provider.description,\n docsUrl: provider.docsUrl,\n };\n }\n\n /**\n * Create registration entity structure\n */\n private createRegistrationEntity(\n registration: OnboardRegistration,\n providerKey: string\n ): ParsedRegistration {\n return {\n key: registration.key,\n label: registration.label,\n description: registration.description,\n providerKey: providerKey,\n };\n }\n\n /**\n * Create event entity structure\n */\n private createEventEntity(\n event: OnboardEvent,\n registrationKey: string,\n providerKey: string\n ): ParsedEvent {\n return {\n eventCode: event.eventCode,\n runtimeAction: event.runtimeAction,\n deliveryType: event.deliveryType,\n sampleEventTemplate: event.sampleEventTemplate,\n registrationKey: registrationKey,\n providerKey: providerKey,\n };\n }\n\n getEntities(): ParsedEntities {\n return this.entities;\n }\n}\n\nexport default InputParser;\n","/**\n * Copyright © Adobe, Inc. All rights reserved.\n */\n\nimport { Core, State } from '@adobe/aio-sdk';\nimport crypto from 'crypto';\n\nimport { InfiniteLoopData } from './types';\n\n/**\n * Utility class for detecting and preventing infinite loops in event processing\n */\nclass InfiniteLoopBreaker {\n /** The algorithm used to generate the fingerprint */\n private static readonly FINGERPRINT_ALGORITHM = 'sha256';\n\n /** The encoding used to generate the fingerprint */\n private static readonly FINGERPRINT_ENCODING = 'hex';\n\n /** The default time to live for the fingerprint in the lib state */\n private static readonly DEFAULT_INFINITE_LOOP_BREAKER_TTL = 60; // seconds\n\n /**\n * This function checks if there is a potential infinite loop\n *\n * @param state - The state object\n * @param infiniteLoopData - The event data containing the key and fingerprint functions, event types, and event name\n * @returns Returns true if the event is a potential infinite loop\n */\n static async isInfiniteLoop({\n keyFn,\n fingerprintFn,\n eventTypes,\n event,\n }: InfiniteLoopData): Promise<boolean> {\n const logLevel = process.env.LOG_LEVEL || 'info';\n const logger = Core.Logger('infiniteLoopBreaker', { level: logLevel });\n\n logger.debug(`Checking for potential infinite loop for event: ${event}`);\n\n if (!eventTypes.includes(event)) {\n logger.debug(`Event type ${event} is not in the infinite loop event types list`);\n return false;\n }\n\n const key = typeof keyFn === 'function' ? keyFn() : keyFn;\n const data = typeof fingerprintFn === 'function' ? fingerprintFn() : fingerprintFn;\n\n // Create a state instance\n const state = await State.init();\n const persistedFingerPrint = await state.get(key);\n if (!persistedFingerPrint) {\n logger.debug(`No persisted fingerprint found for key ${key}`);\n return false;\n }\n\n logger.debug(\n `Persisted fingerprint found for key ${key}: ${persistedFingerPrint.value}, ` +\n `Generated fingerprint: ${InfiniteLoopBreaker.fingerPrint(data)}`\n );\n\n return (\n persistedFingerPrint && persistedFingerPrint.value === InfiniteLoopBreaker.fingerPrint(data)\n );\n }\n\n /**\n * This function stores the fingerprint in the state\n *\n * @param keyFn - Function to generate the key for the fingerprint\n * @param fingerprintFn - Function to generate the fingerprint\n * @param ttl - The time to live for the fingerprint in the lib state\n */\n static async storeFingerPrint(\n keyFn: string | (() => string),\n fingerprintFn: any | (() => any),\n ttl?: number\n ): Promise<void> {\n const key = typeof keyFn === 'function' ? keyFn() : keyFn;\n const data = typeof fingerprintFn === 'function' ? fingerprintFn() : fingerprintFn;\n\n // Create a state instance\n const state = await State.init();\n\n await state.put(key, InfiniteLoopBreaker.fingerPrint(data), {\n ttl: ttl !== undefined ? ttl : InfiniteLoopBreaker.DEFAULT_INFINITE_LOOP_BREAKER_TTL,\n });\n }\n\n /**\n * This function generates a function to generate fingerprint for the data to be used in infinite loop detection based on params.\n *\n * @param obj - Data received from the event\n * @returns The function that generates the fingerprint\n */\n static fnFingerprint(obj: any): () => any {\n return () => {\n return obj;\n };\n }\n\n /**\n * This function generates a function to create a key for the infinite loop detection based on params.\n *\n * @param key - Data received from the event\n * @returns The function that generates the key\n */\n static fnInfiniteLoopKey(key: any): () => any {\n return () => {\n return key;\n };\n }\n\n /**\n * This function generates a fingerprint for the data\n *\n * @param data - The data to generate the fingerprint\n * @returns The fingerprint\n */\n private static fingerPrint(data: any): string {\n const hash = crypto.createHash(InfiniteLoopBreaker.FINGERPRINT_ALGORITHM);\n hash.update(JSON.stringify(data));\n return hash.digest(InfiniteLoopBreaker.FINGERPRINT_ENCODING);\n }\n}\n\nexport default InfiniteLoopBreaker;\n","/**\n * ConfigureProvider for Adobe I/O Events Provider Configuration\n *\n * <license header>\n */\n\nimport {\n EventConfigurationService,\n EventProviderService,\n type EventProvider,\n} from '@adobe-commerce/aio-services-kit';\nimport AdobeCommerceClient from '../../../commerce/adobe-commerce-client';\nimport CustomLogger from '../../../framework/custom-logger';\nimport type { Provider } from '../../../io-events/provider/types';\nimport type { WorkspaceConfig } from '../types';\nimport type { ConfigureProviderResult } from './types';\n\n/**\n * ConfigureProvider for Adobe I/O Events Provider Setup\n *\n * This class handles the configuration and setup of Adobe I/O Events providers\n * for Adobe Commerce integration.\n *\n * @example\n * ```typescript\n * const configureProvider = new ConfigureProvider(\n * adobeCommerceClient,\n * 'merchant-id-123',\n * 'environment-id-456',\n * logger\n * );\n * const result = await configureProvider.execute(provider, workspaceConfig);\n * ```\n */\nclass ConfigureProvider {\n /** Adobe Commerce client instance */\n private readonly adobeCommerceClient: AdobeCommerceClient;\n\n /** Merchant ID for Adobe Commerce */\n private readonly merchantId: string;\n\n /** Environment ID for Adobe Commerce */\n private readonly environmentId: string;\n\n /** CustomLogger instance for logging operations */\n private readonly customLogger: CustomLogger;\n\n /** EventProviderService instance for provider operations */\n private readonly eventProviderService: EventProviderService;\n\n /** EventConfigurationService instance for configuration operations */\n private readonly eventConfigurationService: EventConfigurationService;\n\n /**\n * Constructor for ConfigureProvider\n *\n * @param adobeCommerceClient - Adobe Commerce client instance\n * @param merchantId - Merchant ID for Adobe Commerce\n * @param environmentId - Environment ID for Adobe Commerce\n * @param logger - Optional logger instance for logging operations\n * @throws {Error} When required parameters are missing or invalid\n * @example\n * ```typescript\n * const configureProvider = new ConfigureProvider(\n * adobeCommerceClient,\n * 'merchant-id-123',\n * 'environment-id-456',\n * logger\n * );\n * ```\n */\n constructor(\n adobeCommerceClient: AdobeCommerceClient,\n merchantId: string,\n environmentId: string,\n logger: any = null\n ) {\n // Validate required parameters\n if (!adobeCommerceClient) {\n throw new Error('Adobe Commerce client is required');\n }\n if (!merchantId || typeof merchantId !== 'string') {\n throw new Error('Valid merchant ID is required');\n }\n if (!environmentId || typeof environmentId !== 'string') {\n throw new Error('Valid environment ID is required');\n }\n\n this.adobeCommerceClient = adobeCommerceClient;\n this.merchantId = merchantId;\n this.environmentId = environmentId;\n this.customLogger = new CustomLogger(logger);\n this.eventProviderService = new EventProviderService(this.adobeCommerceClient);\n this.eventConfigurationService = new EventConfigurationService(this.adobeCommerceClient);\n }\n\n /**\n * Execute provider configuration\n *\n * This method handles the provider configuration process for Adobe I/O Events.\n *\n * @param provider - Provider configuration for Adobe I/O Events\n * @param workspaceConfig - Workspace configuration settings\n * @returns A promise that resolves with the configuration result\n * @throws {Error} If provider configuration fails\n * @example\n * ```typescript\n * const result = await configureProvider.execute(provider, workspaceConfig);\n * if (result.success) {\n * console.log('Provider configured successfully');\n * }\n * ```\n */\n async execute(\n provider: Provider,\n workspaceConfig: WorkspaceConfig\n ): Promise<ConfigureProviderResult> {\n this.customLogger.debug('[DEBUG] Starting provider configuration');\n\n try {\n // Validate input parameters\n this.validateConfigureParams(provider, workspaceConfig);\n\n // Get current event providers\n this.customLogger.debug('[FETCH] Fetching current event providers');\n const eventProviderResult = await this.eventProviderService.list();\n\n if (!eventProviderResult.success) {\n const errorMsg = `Failed to fetch event providers: ${eventProviderResult.error}`;\n this.customLogger.error(`[ERROR] ${errorMsg}`);\n return {\n success: false,\n error: errorMsg,\n details: eventProviderResult,\n };\n }\n\n // Check if default workspace is empty and update if needed\n const workspaceUpdateResult = await this.updateWorkspaceIfEmpty(\n eventProviderResult.data,\n workspaceConfig\n );\n if (!workspaceUpdateResult.success) {\n return workspaceUpdateResult;\n }\n\n // Check if the provider is already added\n const providerList = Array.isArray(eventProviderResult.data) ? eventProviderResult.data : [];\n const existingProvider = providerList.find(\n (existingProvider: any) => existingProvider.provider_id === provider.id\n );\n\n if (existingProvider) {\n this.customLogger.info(`[SKIP] Provider ${provider.id} is already configured`);\n return {\n success: true,\n provider: existingProvider,\n };\n } else {\n this.customLogger.debug(\n `[DEBUG] Provider ${provider.id} is not yet configured - creating new provider...`\n );\n\n const createResult = await this.createNewProvider(provider, workspaceConfig);\n if (!createResult.success) {\n return createResult;\n }\n\n this.customLogger.info(`[CREATE] Event provider ${provider.id} created successfully`);\n return {\n success: true,\n provider: createResult.provider!,\n };\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n this.customLogger.error(`[ERROR] Provider configuration failed: ${errorMessage}`);\n\n return {\n success: false,\n error: errorMessage,\n };\n }\n }\n\n /**\n * Creates a new event provider\n *\n * @param provider - Provider configuration object\n * @param workspaceConfig - Workspace configuration object\n * @returns Creation result with success status and provider data\n * @private\n */\n private async createNewProvider(\n provider: Provider,\n workspaceConfig: WorkspaceConfig\n ): Promise<ConfigureProviderResult> {\n const providerData = {\n provider_id: provider.id,\n instance_id: provider.instance_id!, // Already validated in validateConfigureParams\n label: provider.label,\n description: provider.description,\n workspace_configuration: JSON.stringify(workspaceConfig),\n };\n\n this.customLogger.debug(`[DEBUG] Creating event provider: ${provider.label} (${provider.id})`);\n\n const createResult = await this.eventProviderService.create(providerData);\n\n if (!createResult.success) {\n const errorMsg = `Failed to create event provider: ${createResult.error}`;\n this.customLogger.error(`[ERROR] ${errorMsg}`);\n return {\n success: false,\n error: errorMsg,\n details: createResult,\n };\n }\n\n return {\n success: true,\n provider: createResult.data as EventProvider,\n };\n }\n\n /**\n * Updates workspace configuration if the default workspace is empty\n *\n * @param existingProviders - Array of existing providers\n * @param workspaceConfig - Workspace configuration object\n * @returns Update result with success status\n * @private\n */\n private async updateWorkspaceIfEmpty(\n existingProviders: any,\n workspaceConfig: WorkspaceConfig\n ): Promise<ConfigureProviderResult> {\n const providerArray = Array.isArray(existingProviders) ? existingProviders : [];\n const isDefaultWorkspaceEmpty =\n providerArray.length === 0 ||\n providerArray.every(\n (item: any) => !item.workspace_configuration || item.workspace_configuration === ''\n );\n\n if (isDefaultWorkspaceEmpty) {\n this.customLogger.debug('[DEBUG] Default workspace is empty, updating configuration...');\n\n const updateConfigPayload = {\n enabled: true,\n merchant_id: this.merchantId,\n environment_id: this.environmentId,\n workspace_configuration: JSON.stringify(workspaceConfig),\n };\n\n this.customLogger.debug(\n `[DEBUG] Updating workspace configuration for merchant: ${this.merchantId}`\n );\n\n const updateResult = await this.eventConfigurationService.update(updateConfigPayload);\n\n if (!updateResult.success) {\n const errorMsg = `Failed to update configuration: ${updateResult.error}`;\n this.customLogger.error(`[ERROR] ${errorMsg}`);\n return {\n success: false,\n error: errorMsg,\n details: updateResult,\n };\n }\n\n this.customLogger.info('[UPDATE] Configuration updated successfully');\n }\n\n return { success: true };\n }\n\n /**\n * Validate input parameters for configure method\n *\n * @param provider - Provider configuration for Adobe I/O Events\n * @param workspaceConfig - Workspace configuration settings\n * @throws {Error} If validation fails\n * @private\n */\n private validateConfigureParams(provider: Provider, workspaceConfig: WorkspaceConfig): void {\n if (!provider || typeof provider !== 'object') {\n throw new Error('Provider configuration object is required');\n }\n\n const requiredProviderFields: (keyof Provider)[] = [\n 'id',\n 'instance_id',\n 'label',\n 'description',\n ];\n for (const field of requiredProviderFields) {\n if (!provider[field] || typeof provider[field] !== 'string') {\n throw new Error(`Provider ${field} is required and must be a string`);\n }\n }\n\n if (!workspaceConfig || typeof workspaceConfig !== 'object') {\n throw new Error('Workspace configuration object is required');\n }\n\n this.customLogger.debug(`[DEBUG] Validated provider: ${provider.label} (${provider.id})`);\n }\n}\n\nexport default ConfigureProvider;\n","/**\n * Adobe Commerce I/O Events Configuration Component\n *\n * <license header>\n */\n\nimport AdobeCommerceClient from '../../commerce/adobe-commerce-client';\nimport CustomLogger from '../../framework/custom-logger';\nimport type { Provider } from '../../io-events/provider/types';\nimport type { WorkspaceConfig, CommerceEventConfig } from './types';\nimport ConfigureProvider from './configure-provider';\nimport {\n EventService,\n EventSubscriptionService,\n type EventSubscription,\n} from '@adobe-commerce/aio-services-kit';\n\n/**\n * OnboardCommerce for Adobe Commerce I/O Events Configuration\n *\n * This class provides functionality to automate the configuration of Adobe Commerce\n * I/O Events via REST endpoint, simplifying the onboarding process for Commerce instances.\n *\n * @example\n * ```typescript\n * const adobeCommerceClient = new AdobeCommerceClient(...);\n * const onboardCommerce = new OnboardCommerce(\n * adobeCommerceClient,\n * 'merchant-id-123',\n * 'environment-id-456',\n * logger\n * );\n * ```\n */\nclass OnboardCommerce {\n /** Adobe Commerce client instance */\n private readonly adobeCommerceClient: AdobeCommerceClient;\n\n /** Merchant ID for Adobe Commerce */\n private readonly merchantId: string;\n\n /** Environment ID for Adobe Commerce */\n private readonly environmentId: string;\n\n /** CustomLogger instance for logging operations */\n private readonly customLogger: CustomLogger;\n\n /** ConfigureProvider instance for provider configuration */\n private readonly configureProvider: ConfigureProvider;\n\n /** EventSubscriptionService instance for managing event subscriptions */\n private readonly eventSubscriptionService: EventSubscriptionService;\n\n /** EventService instance for managing events */\n private readonly eventService: EventService;\n\n /** Flag to indicate if the Commerce instance is PaaS (defaults to false) */\n private readonly isPaaS: boolean;\n\n /**\n * Constructor for OnboardCommerce\n *\n * @param adobeCommerceClient - Adobe Commerce client instance\n * @param merchantId - Merchant ID for Adobe Commerce\n * @param environmentId - Environment ID for Adobe Commerce\n * @param logger - Optional logger instance for logging operations\n * @param isPaaS - Flag to indicate if the Commerce instance is PaaS (defaults to false)\n * @throws {Error} When required parameters are missing or invalid\n * @example\n * ```typescript\n * const adobeCommerceClient = new AdobeCommerceClient(...);\n * const onboardCommerce = new OnboardCommerce(\n * adobeCommerceClient,\n * 'merchant-id-123',\n * 'environment-id-456',\n * logger\n * );\n * ```\n */\n constructor(\n adobeCommerceClient: AdobeCommerceClient,\n merchantId: string,\n environmentId: string,\n logger: any = null,\n isPaaS: boolean = false\n ) {\n // Validate required parameters\n if (!adobeCommerceClient) {\n throw new Error('Adobe Commerce client is required');\n }\n if (!merchantId || typeof merchantId !== 'string') {\n throw new Error('Valid merchant ID is required');\n }\n if (!environmentId || typeof environmentId !== 'string') {\n throw new Error('Valid environment ID is required');\n }\n\n this.adobeCommerceClient = adobeCommerceClient;\n this.merchantId = merchantId;\n this.environmentId = environmentId;\n this.isPaaS = isPaaS;\n this.customLogger = new CustomLogger(logger);\n this.configureProvider = new ConfigureProvider(\n adobeCommerceClient,\n merchantId,\n environmentId,\n logger\n );\n this.eventSubscriptionService = new EventSubscriptionService(adobeCommerceClient);\n this.eventService = new EventService(adobeCommerceClient);\n }\n\n /**\n * Process Adobe Commerce I/O Events Configuration\n *\n * This method automates the configuration of Adobe Commerce I/O Events by setting up\n * the provider, workspace, and commerce-specific event configurations.\n *\n * @param provider - Provider configuration for Adobe I/O Events\n * @param workspaceConfig - Workspace configuration settings\n * @param commerceEventsConfig - Array of commerce event configurations (optional, defaults to empty array)\n * @returns A promise that resolves with the configuration result\n * @throws {Error} If configuration fails\n * @example\n * ```typescript\n * const result = await onboardCommerce.process(\n * providerConfig,\n * workspaceConfig,\n * commerceEventsConfig\n * );\n * ```\n */\n async process(\n provider: Provider,\n workspaceConfig: WorkspaceConfig,\n commerceEventsConfig: CommerceEventConfig[] = []\n ): Promise<any> {\n this.customLogger.info(\n `[START] Configuring Adobe Commerce I/O Events\\n` +\n ` Provider: ${provider.label} (${provider.id})\\n` +\n ` Workspace: ${workspaceConfig.project.name}\\n` +\n ` Events to process: ${commerceEventsConfig.length}`\n );\n\n try {\n // Configure the provider using the ConfigureProvider component\n const providerResult = await this.configureProvider.execute(provider, workspaceConfig);\n\n if (!providerResult.success) {\n return providerResult;\n }\n\n // Process commerce events configuration if provided\n if (commerceEventsConfig && commerceEventsConfig.length > 0) {\n // Get current event subscriptions to check what's already configured\n this.customLogger.debug('[FETCH] Fetching current event subscriptions...');\n const eventSubscriptionsResult = await this.eventSubscriptionService.list();\n\n let existingSubscriptions: any[] = [];\n if (!eventSubscriptionsResult.success) {\n this.customLogger.error(\n `[ERROR] Failed to fetch event subscriptions: ${eventSubscriptionsResult.error}`\n );\n } else {\n existingSubscriptions = Array.isArray(eventSubscriptionsResult.data)\n ? eventSubscriptionsResult.data\n : [];\n this.customLogger.debug(\n `[FETCH] Retrieved ${existingSubscriptions.length} existing event subscription(s)`\n );\n }\n\n // Get supported events to validate commerce events configuration\n // Skip this step for PaaS instances as they don't require supported events validation\n let supportedEvents: any[] = [];\n if (!this.isPaaS) {\n this.customLogger.debug('[FETCH] Fetching supported events list...');\n const supportedEventsResult = await this.eventService.supportedList();\n\n if (!supportedEventsResult.success) {\n this.customLogger.error(\n `[ERROR] Failed to fetch supported events: ${supportedEventsResult.error}`\n );\n } else {\n supportedEvents = Array.isArray(supportedEventsResult.data)\n ? supportedEventsResult.data\n : [];\n this.customLogger.debug(\n `[FETCH] Retrieved ${supportedEvents.length} supported event(s)`\n );\n }\n } else {\n this.customLogger.debug('[SKIP] Skipping supported events validation for PaaS instance');\n }\n\n // Filter events based on existing subscriptions and supported events\n const { alreadySubscribed, needsSubscription, unsupported } =\n this.filterEventsBySubscriptionStatus(\n commerceEventsConfig,\n existingSubscriptions,\n provider.id,\n supportedEvents\n );\n\n const result = {\n successfulSubscriptions: [] as string[],\n failedSubscriptions: [] as string[],\n alreadySubscribed: alreadySubscribed.map(event => event.event.name),\n unsupported: unsupported.map(event => event.event?.name || 'Unknown'),\n skipped: alreadySubscribed.length + unsupported.length,\n };\n\n // Process events that need subscription\n for (const commerceEvent of needsSubscription) {\n try {\n // Prepare the event payload with proper transformations\n const preparedEvent = this.prepareEventPayload(commerceEvent, provider.id);\n\n this.customLogger.debug(`[DEBUG] Subscribing to event: ${commerceEvent.event.name}`);\n\n // Create the event subscription\n const eventSubscribeResult = await this.eventSubscriptionService.create(\n preparedEvent.event as EventSubscription\n );\n\n if (!eventSubscribeResult.success) {\n result.failedSubscriptions.push(commerceEvent.event.name);\n this.customLogger.error(\n `[ERROR] Failed to subscribe to event: ${commerceEvent.event.name} - ${eventSubscribeResult.error}`\n );\n continue;\n }\n\n this.customLogger.info(`[CREATE] Successfully subscribed: ${commerceEvent.event.name}`);\n result.successfulSubscriptions.push(commerceEvent.event.name);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n result.failedSubscriptions.push(commerceEvent.event?.name || 'Unknown');\n this.customLogger.error(\n `[ERROR] Error processing event subscription for ${commerceEvent.event?.name || 'Unknown'}: ${errorMessage}`\n );\n }\n }\n\n // Log summary of event subscriptions\n this.logEventSubscriptionSummary(result, provider.label);\n\n // Log important post-subscription steps for PaaS instances\n if (this.isPaaS) {\n this.customLogger.info('[IMPORTANT] ⚠️ Post-Subscription Steps for PaaS:');\n this.customLogger.info(\n '[IMPORTANT] 1. Run: bin/magento events:generate:module to generate module after successful event subscription'\n );\n this.customLogger.info(\n '[IMPORTANT] 2. Run: bin/magento setup:upgrade && bin/magento setup:di:compile && bin/magento cache:flush to install the generated module'\n );\n }\n }\n\n return {\n success: true,\n message: 'Configuration completed successfully',\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n this.customLogger.error(`[ERROR] Configuration failed: ${errorMessage}`);\n throw new Error(`Failed to configure Adobe Commerce I/O Events: ${errorMessage}`);\n }\n }\n\n /**\n * Filters commerce events configuration based on existing subscriptions and supported events\n *\n * @param commerceEventsConfig - Array of commerce event configurations\n * @param existingSubscriptions - Array of existing event subscriptions\n * @param providerId - Provider ID to match against\n * @param supportedEvents - Array of supported events from Adobe Commerce\n * @returns Object containing alreadySubscribed, needsSubscription, and unsupported arrays\n * @private\n */\n private filterEventsBySubscriptionStatus(\n commerceEventsConfig: CommerceEventConfig[],\n existingSubscriptions: any[],\n providerId: string,\n supportedEvents: any[] = []\n ): {\n alreadySubscribed: CommerceEventConfig[];\n needsSubscription: CommerceEventConfig[];\n unsupported: CommerceEventConfig[];\n } {\n const alreadySubscribed: CommerceEventConfig[] = [];\n const needsSubscription: CommerceEventConfig[] = [];\n const unsupported: CommerceEventConfig[] = [];\n\n // Create a set of supported event names for faster lookup\n const supportedEventNames = new Set(supportedEvents.map(event => event.name));\n\n commerceEventsConfig.forEach(commerceEvent => {\n const eventName = commerceEvent.event?.name;\n\n if (!eventName) {\n this.customLogger.error(\n 'Commerce event configuration missing event name, skipping:',\n commerceEvent\n );\n return;\n }\n\n // First check if the event is supported by Adobe Commerce\n if (supportedEvents.length > 0 && !supportedEventNames.has(eventName)) {\n unsupported.push(commerceEvent);\n return;\n }\n\n // Check if this event is already subscribed for this provider\n const isAlreadySubscribed = existingSubscriptions.some(\n subscription => subscription.name === eventName && subscription.provider_id === providerId\n );\n\n if (isAlreadySubscribed) {\n alreadySubscribed.push(commerceEvent);\n } else {\n needsSubscription.push(commerceEvent);\n }\n });\n\n return {\n alreadySubscribed,\n needsSubscription,\n unsupported,\n };\n }\n\n /**\n * Prepares event payload by transforming event names and adding provider information\n *\n * For PaaS instances, the parent field is omitted to support native events (observer.*, plugin.*)\n * which would be rejected by Adobe Commerce as invalid aliases if parent is set to the same name.\n * For non-PaaS instances, the parent field is set to the event name as usual.\n *\n * @param eventSpec - Event specification object containing event details\n * @param providerId - Provider ID to assign to the event\n * @returns Modified event specification with updated event properties\n * @private\n */\n private prepareEventPayload(eventSpec: CommerceEventConfig, providerId: string): any {\n // Input validation\n if (!eventSpec || !eventSpec.event) {\n throw new Error('Invalid event specification: event object is required');\n }\n\n if (!eventSpec.event.name) {\n throw new Error('Invalid event specification: event name is required');\n }\n\n if (!providerId || typeof providerId !== 'string') {\n throw new Error('Valid provider ID is required');\n }\n\n // Create a deep copy to avoid modifying the original object\n const modifiedEventSpec = JSON.parse(JSON.stringify(eventSpec));\n const eventName = modifiedEventSpec.event.name;\n\n // For PaaS instances, don't set parent field to support native events\n // For non-PaaS instances, set parent as usual\n if (!this.isPaaS) {\n modifiedEventSpec.event.parent = eventName;\n }\n // Note: For PaaS instances, we intentionally omit the parent field\n\n modifiedEventSpec.event.provider_id = providerId;\n modifiedEventSpec.event.destination = 'default';\n modifiedEventSpec.event.provider_id = providerId;\n modifiedEventSpec.event.priority = true;\n modifiedEventSpec.event.hipaa_audit_required = false;\n\n // Ensure rules array exists (required by Adobe Commerce API)\n if (!modifiedEventSpec.event.rules) {\n modifiedEventSpec.event.rules = [];\n }\n\n return modifiedEventSpec;\n }\n\n /**\n * Logs a comprehensive summary of event subscription results\n *\n * @param result - Event subscription processing results\n * @param providerLabel - Provider label for display\n * @private\n */\n private logEventSubscriptionSummary(\n result: {\n successfulSubscriptions: string[];\n failedSubscriptions: string[];\n alreadySubscribed: string[];\n unsupported: string[];\n skipped: number;\n },\n providerLabel: string\n ): void {\n // Log individual events with prefixes during processing\n if (result.alreadySubscribed.length > 0) {\n result.alreadySubscribed.forEach(eventName => {\n this.customLogger.info(`[SKIP] Already subscribed: ${eventName}`);\n });\n }\n\n if (result.unsupported.length > 0) {\n result.unsupported.forEach(eventName => {\n this.customLogger.error(`[ERROR] Unsupported event: ${eventName}`);\n });\n }\n\n // Summary section (no prefix)\n this.customLogger.info('');\n this.customLogger.info('='.repeat(60));\n this.customLogger.info(`📊 COMMERCE EVENTS CONFIGURATION SUMMARY - ${providerLabel}`);\n this.customLogger.info('='.repeat(60));\n this.customLogger.info('');\n\n // Overall summary\n const totalProcessed =\n result.successfulSubscriptions.length +\n result.failedSubscriptions.length +\n result.alreadySubscribed.length +\n result.unsupported.length;\n this.customLogger.info(\n `📈 OVERALL: ${totalProcessed} processed | ${result.successfulSubscriptions.length} created | ${result.alreadySubscribed.length} existing | ${result.unsupported.length} unsupported | ${result.failedSubscriptions.length} failed`\n );\n this.customLogger.info('');\n\n // Successful subscriptions\n if (result.successfulSubscriptions.length > 0) {\n this.customLogger.info(\n `✅ SUCCESSFUL SUBSCRIPTIONS (${result.successfulSubscriptions.length}):`\n );\n result.successfulSubscriptions.forEach(eventName => {\n this.customLogger.info(` ✓ ${eventName}`);\n });\n this.customLogger.info('');\n }\n\n // Already subscribed\n if (result.alreadySubscribed.length > 0) {\n this.customLogger.info(`ℹ️ ALREADY SUBSCRIBED (${result.alreadySubscribed.length}):`);\n result.alreadySubscribed.forEach(eventName => {\n this.customLogger.info(` → ${eventName}`);\n });\n this.customLogger.info('');\n }\n\n // Unsupported events\n if (result.unsupported.length > 0) {\n this.customLogger.info(`⚠️ UNSUPPORTED EVENTS (${result.unsupported.length}):`);\n result.unsupported.forEach(eventName => {\n this.customLogger.info(` ⚠ ${eventName}`);\n });\n this.customLogger.info('');\n }\n\n // Failed subscriptions\n if (result.failedSubscriptions.length > 0) {\n this.customLogger.info(`❌ FAILED SUBSCRIPTIONS (${result.failedSubscriptions.length}):`);\n result.failedSubscriptions.forEach(eventName => {\n this.customLogger.info(` ✗ ${eventName}`);\n });\n this.customLogger.info('');\n }\n\n this.customLogger.info('='.repeat(60));\n }\n}\n\nexport default OnboardCommerce;\n","/**\n * <license header>\n */\n\nimport got, { Got } from 'got';\n\nimport CustomLogger from '../../framework/custom-logger';\nimport { HttpStatus } from '../../framework/runtime-action/types';\nimport { Connection, ExtendedRequestError, HttpsOptions } from './types';\n\nclass AdobeCommerceClient {\n private baseUrl: string;\n private connection: Connection;\n private logger: any;\n private httpsOptions: HttpsOptions | undefined;\n\n /**\n * @param baseUrl\n * @param connection\n * @param logger\n * @param httpsOptions\n */\n constructor(\n baseUrl: string,\n connection: Connection,\n logger: any = null,\n httpsOptions?: HttpsOptions\n ) {\n if (!baseUrl) {\n throw new Error('Commerce URL must be provided');\n }\n this.baseUrl = baseUrl;\n this.connection = connection;\n this.httpsOptions = httpsOptions;\n\n // Use `CustomLogger` to wrap the logger\n this.logger = new CustomLogger(logger);\n }\n\n /**\n * @param endpoint\n * @param headers\n */\n async get(endpoint: string, headers: Record<string, string> = {}): Promise<any> {\n return await this.apiCall(endpoint, 'GET', headers);\n }\n\n /**\n * @param endpoint\n * @param headers\n * @param payload\n */\n async post(\n endpoint: string,\n headers: Record<string, string> = {},\n payload: any = null\n ): Promise<any> {\n return await this.apiCall(endpoint, 'POST', headers, payload);\n }\n\n /**\n * @param endpoint\n * @param headers\n * @param payload\n */\n async put(\n endpoint: string,\n headers: Record<string, string> = {},\n payload: any = null\n ): Promise<any> {\n return await this.apiCall(endpoint, 'PUT', headers, payload);\n }\n\n /**\n * @param endpoint\n * @param headers\n */\n async delete(endpoint: string, headers: Record<string, string> = {}): Promise<any> {\n return await this.apiCall(endpoint, 'DELETE', headers);\n }\n\n /**\n * @param endpoint\n * @param method\n * @param headers\n * @param payload\n * @private\n */\n private async apiCall(\n endpoint: string,\n method: string,\n headers: Record<string, string>,\n payload: any = null\n ): Promise<any> {\n const commerceGot = await this.getHttpClient();\n\n commerceGot.extend({\n headers: headers,\n });\n\n const wrapper = async (callable: () => Promise<any>): Promise<any> => {\n try {\n const message = await callable();\n return { success: true, message };\n } catch (e: any) {\n if (e.code === 'ERR_GOT_REQUEST_ERROR') {\n this.logger.error('Error while calling Commerce API', e);\n return {\n success: false,\n statusCode: HttpStatus.INTERNAL_ERROR,\n message: `Unexpected error, check logs. Original error \"${e.message}\"`,\n };\n }\n return {\n success: false,\n statusCode: e.response?.statusCode || HttpStatus.INTERNAL_ERROR,\n message: e.message,\n body: (e as ExtendedRequestError).responseBody,\n };\n }\n };\n\n let options: any = {\n method: method,\n };\n\n if (payload !== null) {\n options = {\n ...options,\n json: payload,\n };\n }\n\n return await wrapper(() => commerceGot(endpoint, options).json());\n }\n\n /**\n * @private\n */\n private async getHttpClient(): Promise<Got> {\n const commerceGot = got.extend({\n http2: true,\n responseType: 'json',\n prefixUrl: this.baseUrl,\n headers: {\n 'Content-Type': 'application/json',\n },\n ...(this.httpsOptions && { https: this.httpsOptions }),\n hooks: {\n beforeRequest: [\n (options): void => this.logger.debug(`Request [${options.method}] ${options.url}`),\n ],\n beforeRetry: [\n (options, error, retryCount): void =>\n this.logger.debug(\n `Retrying request [${options.method}] ${options.url} - count: ${retryCount} - error: ${error?.code} - ${error?.message}`\n ),\n ],\n beforeError: [\n (error: ExtendedRequestError): ExtendedRequestError => {\n const { response } = error;\n if (response?.body) {\n error.responseBody = response.body;\n }\n return error;\n },\n ],\n afterResponse: [\n (response): any => {\n this.logger.debug(\n `Response [${response.request.options.method}] ${response.request.options.url} - ${response.statusCode} ${response.statusMessage}`\n );\n return response;\n },\n ],\n },\n });\n\n return await this.connection.extend(commerceGot);\n }\n}\n\nexport default AdobeCommerceClient;\n","/**\n * <license header>\n */\n\nimport { State } from '@adobe/aio-sdk';\n\nimport CustomLogger from '../../../../framework/custom-logger';\nimport RestClient from '../../../../integration/rest-client';\nimport { TokenResult } from './types';\n\nclass GenerateBasicAuthToken {\n private baseUrl: string;\n private username: string;\n private password: string;\n private key: string;\n private logger: any;\n private state: any;\n\n /**\n * @param baseUrl\n * @param username\n * @param password\n * @param logger\n */\n constructor(baseUrl: string, username: string, password: string, logger: any = null) {\n this.baseUrl = baseUrl;\n this.username = username;\n this.password = password;\n this.key = 'adobe_commerce_basic_auth_token';\n\n // Use `CustomLogger` to wrap the logger\n this.logger = new CustomLogger(logger);\n }\n\n /**\n * @return string | null\n */\n async execute(): Promise<string | null> {\n const currentValue = await this.getValue();\n if (currentValue !== null) {\n return currentValue;\n }\n\n let result: TokenResult = {\n token: null,\n expire_in: 3600,\n };\n\n const response = await this.getCommerceToken();\n if (response !== null) {\n result = response;\n }\n\n this.logger.debug(`Token: ${JSON.stringify(result)}`);\n\n if (result.token !== null) {\n await this.setValue(result);\n }\n\n return result.token;\n }\n\n /**\n * @return TokenResult | null\n */\n async getCommerceToken(): Promise<TokenResult | null> {\n const endpoint = this.createTokenEndpoint();\n\n this.logger.debug(`Endpoint: ${endpoint}`);\n\n try {\n const restClient = new RestClient();\n const response = await restClient.post(\n endpoint,\n {\n 'Content-Type': 'application/json',\n },\n {\n username: this.username,\n password: this.password,\n }\n );\n\n this.logger.debug(`Raw response type: ${typeof response}`);\n this.logger.debug(`Raw response: ${JSON.stringify(response)}`);\n\n if (response !== null && response !== undefined) {\n // Adobe Commerce returns the token as a JSON string (e.g., \"abc123\")\n // If it's already a string, use it directly\n // If it's an object with token property, extract it\n let tokenValue: string;\n\n if (typeof response === 'string') {\n tokenValue = response;\n } else if (typeof response === 'object' && response.token) {\n tokenValue = response.token;\n } else {\n // Try to convert to string as a fallback\n try {\n tokenValue = response.toString();\n this.logger.debug(`Converted response to string: ${tokenValue?.substring(0, 10)}...`);\n } catch {\n this.logger.error(`Unexpected response format: ${JSON.stringify(response)}`);\n return null;\n }\n }\n\n this.logger.debug(`Extracted token: ${tokenValue?.substring(0, 10)}...`);\n\n return {\n token: tokenValue,\n expire_in: 3600, // Adobe Commerce tokens typically expire in 1 hour\n };\n }\n\n this.logger.error('Received null or undefined response from Commerce API');\n return null;\n } catch (error: any) {\n this.logger.error(`Failed to get Commerce token: ${error.message}`);\n this.logger.debug(`Full error: ${JSON.stringify(error)}`);\n return null;\n }\n }\n\n /**\n * Create the Adobe Commerce integration admin token endpoint.\n * Handles cases where baseUrl may or may not already include /rest.\n * @return string\n */\n createTokenEndpoint(): string {\n // Normalize base URL (remove trailing slash if present)\n const normalizedBaseUrl = this.baseUrl.replace(/\\/+$/, '');\n\n // Check if baseUrl already ends with /rest\n if (normalizedBaseUrl.endsWith('/rest')) {\n // Base URL already includes /rest, so append V1/integration/admin/token\n return `${normalizedBaseUrl}/V1/integration/admin/token`;\n } else {\n // Base URL doesn't include /rest, so append the full path\n return `${normalizedBaseUrl}/rest/V1/integration/admin/token`;\n }\n }\n\n /**\n * @param endpoint\n * @return string\n */\n createEndpoint(endpoint: string): string {\n // Normalize base URL (remove trailing slash if present)\n const normalizedBaseUrl = this.baseUrl.replace(/\\/+$/, '');\n // Ensure endpoint starts with /\n const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;\n return `${normalizedBaseUrl}${normalizedEndpoint}`;\n }\n\n /**\n * @param result\n * @return boolean\n */\n async setValue(result: TokenResult): Promise<boolean> {\n try {\n const state = await this.getState();\n if (state === null) {\n // State API not available, skip caching\n return true; // Return true since token generation succeeded\n }\n\n await state.put(this.key, result.token, { ttl: result.expire_in });\n return true;\n } catch (error) {\n this.logger.debug('Failed to cache token, continuing without caching');\n return true; // Return true since token generation succeeded\n }\n }\n\n /**\n * @return string | null\n */\n async getValue(): Promise<string | null> {\n try {\n const state = await this.getState();\n if (state === null) {\n // State API not available, skip caching\n return null;\n }\n\n const value = await state.get(this.key);\n if (value !== undefined) {\n return value.value;\n }\n } catch (error) {\n this.logger.debug('State API not available, skipping cache lookup');\n }\n\n return null;\n }\n\n /**\n * @return any\n */\n async getState(): Promise<any> {\n if (this.state === undefined) {\n try {\n this.state = await State.init();\n } catch (error) {\n this.logger.debug('State API initialization failed, running without caching');\n this.state = null;\n }\n }\n return this.state;\n }\n}\n\nexport default GenerateBasicAuthToken;\n","/**\n * <license header>\n */\n\nimport CustomLogger from '../../../framework/custom-logger';\nimport GenerateBasicAuthToken from './generate-basic-auth-token';\nimport { Connection } from '../types';\n\nclass BasicAuthConnection implements Connection {\n private baseUrl: string;\n private username: string;\n private password: string;\n private logger: any;\n\n /**\n * @param baseUrl\n * @param username\n * @param password\n * @param logger\n */\n constructor(baseUrl: string, username: string, password: string, logger: any = null) {\n this.baseUrl = baseUrl;\n this.username = username;\n this.password = password;\n\n // Use `CustomLogger` to wrap the logger\n this.logger = new CustomLogger(logger);\n }\n\n /**\n * @param commerceGot\n */\n async extend(commerceGot: any): Promise<any> {\n this.logger.debug('Using Commerce client with integration options');\n\n const generateToken = new GenerateBasicAuthToken(\n this.baseUrl,\n this.username,\n this.password,\n this.logger.getLogger()\n );\n const token = await generateToken.execute();\n\n return commerceGot.extend({\n headers: {\n Authorization: `Bearer ${token}`,\n },\n });\n }\n}\n\nexport default BasicAuthConnection;\n","/**\n * <license header>\n */\n\nimport Oauth1a from 'oauth-1.0a';\nimport * as crypto from 'crypto';\nimport { Got } from 'got';\n\nimport CustomLogger from '../../../framework/custom-logger';\nimport { Connection } from '../types';\n\nclass Oauth1aConnection implements Connection {\n private consumerKey: string;\n private consumerSecret: string;\n private accessToken: string;\n private accessTokenSecret: string;\n private logger: any;\n\n /**\n * @param consumerKey\n * @param consumerSecret\n * @param accessToken\n * @param accessTokenSecret\n * @param logger\n */\n constructor(\n consumerKey: string,\n consumerSecret: string,\n accessToken: string,\n accessTokenSecret: string,\n logger: any = null\n ) {\n this.consumerKey = consumerKey;\n this.consumerSecret = consumerSecret;\n this.accessToken = accessToken;\n this.accessTokenSecret = accessTokenSecret;\n\n // Use `CustomLogger` to wrap the logger\n this.logger = new CustomLogger(logger);\n }\n\n /**\n * @param commerceGot\n */\n async extend(commerceGot: Got): Promise<Got> {\n this.logger.debug('Using Commerce client with integration options');\n\n const headers = this.headersProvider();\n\n return commerceGot.extend({\n handlers: [\n (options: any, next: any): Promise<any> => {\n options.headers = {\n ...options.headers,\n ...headers(options.url.toString(), options.method),\n };\n return next(options);\n },\n ],\n });\n }\n\n /**\n * return () => { }\n */\n headersProvider(): (url: string, method: string) => any {\n const oauth = new Oauth1a({\n consumer: {\n key: this.consumerKey,\n secret: this.consumerSecret,\n },\n signature_method: 'HMAC-SHA256',\n hash_function: (baseString: string, key: string): string =>\n crypto.createHmac('sha256', key).update(baseString).digest('base64'),\n });\n\n const oauthToken = {\n key: this.accessToken,\n secret: this.accessTokenSecret,\n };\n\n return (url: string, method: string): any =>\n oauth.toHeader(oauth.authorize({ url, method }, oauthToken));\n }\n}\n\nexport default Oauth1aConnection;\n","/**\n * <license header>\n */\n\nimport { Connection } from '../types';\nimport CustomLogger from '../../../framework/custom-logger';\n\n/**\n * ImsConnection for Adobe Commerce Client with IMS authentication\n *\n * This class provides IMS (Identity Management System) authentication for Adobe Commerce API requests\n * by accepting a pre-generated bearer token.\n *\n * **Token Management Best Practice:**\n * Generate tokens using `AdobeAuth.getToken()` and implement caching at the application level\n * (Redis, Memcached, in-memory, etc.) to avoid unnecessary token generation calls.\n *\n * @example\n * ```typescript\n * import { ImsConnection, AdobeCommerceClient } from '@adobe-commerce/aio-toolkit';\n * import AdobeAuth from '@adobe-commerce/aio-toolkit/commerce/adobe-auth';\n * import BearerToken from '@adobe-commerce/aio-toolkit/integration/bearer-token';\n *\n * // Check your application cache first\n * let token = await yourAppCache.get('commerce_ims_token');\n *\n * if (!token || !BearerToken.info(token).isValid) {\n * // Generate new token using AdobeAuth\n * token = await AdobeAuth.getToken(\n * 'client-id',\n * 'client-secret',\n * 'technical-account-id',\n * 'technical-account-email',\n * 'ims-org-id@AdobeOrg',\n * ['AdobeID', 'openid', 'adobeio_api']\n * );\n *\n * // Store in your application cache with appropriate TTL\n * const tokenInfo = BearerToken.info(token);\n * if (tokenInfo.isValid && tokenInfo.timeUntilExpiry) {\n * const ttl = Math.floor(tokenInfo.timeUntilExpiry / 1000) - 600;\n * await yourAppCache.set('commerce_ims_token', token, ttl);\n * }\n * }\n *\n * // Create connection with token\n * const connection = new ImsConnection(token, logger);\n *\n * // Create Commerce client\n * const client = new AdobeCommerceClient('https://your-store.com', connection);\n *\n * // Make API calls\n * const products = await client.get('V1/products');\n * ```\n */\nclass ImsConnection implements Connection {\n /** Bearer token for IMS authentication */\n private readonly imsToken: string;\n\n /** CustomLogger instance for logging operations */\n private readonly customLogger: CustomLogger;\n\n /**\n * Creates an instance of ImsConnection\n *\n * @param imsToken - Bearer token string for IMS authentication (generate using AdobeAuth)\n * @param logger - Optional logger instance for logging operations\n * @example\n * ```typescript\n * const token = await AdobeAuth.getToken(...);\n * const connection = new ImsConnection(token, logger);\n * ```\n */\n constructor(imsToken: string, logger: any = null) {\n this.imsToken = imsToken;\n this.customLogger = new CustomLogger(logger);\n }\n\n /**\n * Extends the Commerce Got client with IMS authentication headers\n *\n * @param commerceGot - The Got instance to extend with authentication\n * @returns Promise<any> - Extended Got instance with authentication headers\n * @throws {Error} If token is invalid or empty\n */\n async extend(commerceGot: any): Promise<any> {\n this.customLogger.info('Using Commerce client with IMS authentication');\n\n if (!this.imsToken || this.imsToken.trim() === '') {\n throw new Error('Failed to generate or retrieve IMS token');\n }\n\n this.customLogger.info(\n `IMS token being extended to header: ${this.imsToken.substring(0, 10)}...`\n );\n\n return commerceGot.extend({\n headers: {\n Authorization: `Bearer ${this.imsToken}`,\n },\n });\n }\n}\n\nexport default ImsConnection;\n","/**\n * <license header>\n */\n\nimport { ShippingCarrierMethodData, ShippingCarrierMethodAdditionalData } from './types';\n\n/**\n * Builder class for constructing a shipping carrier method\n */\nclass ShippingCarrierMethod {\n private methodData: Partial<ShippingCarrierMethodData>;\n\n constructor(carrierCode: string, method: string) {\n this.methodData = { carrier_code: carrierCode, method, additional_data: [] };\n }\n\n /**\n * Sets the display name for the shipping method\n *\n * @param methodTitle - Display name for the shipping method\n * @returns The rate builder instance for method chaining\n */\n setMethodTitle(methodTitle: string): this {\n this.methodData.method_title = methodTitle;\n return this;\n }\n\n /**\n * Sets the price charged to the customer\n *\n * @param price - Price charged to the customer\n * @returns The rate builder instance for method chaining\n */\n setPrice(price: number): this {\n this.methodData.price = price;\n return this;\n }\n\n /**\n * Sets the cost to the merchant\n *\n * @param cost - Cost to the merchant\n * @returns The rate builder instance for method chaining\n */\n setCost(cost: number): this {\n this.methodData.cost = cost;\n return this;\n }\n\n /**\n * Adds additional data to the shipping method\n *\n * @param key - Key for the additional data\n * @param value - Value for the additional data\n * @returns The rate builder instance for method chaining\n *\n * @example\n * ```typescript\n * rate.addAdditionalData('delivery_time', '3-5 business days')\n * .addAdditionalData('tracking_available', true);\n * ```\n */\n addAdditionalData(key: string, value: any): this {\n const additionalDataItem: ShippingCarrierMethodAdditionalData = { key, value };\n this.methodData.additional_data?.push(additionalDataItem);\n return this;\n }\n\n /**\n * Gets and returns the shipping carrier method data\n *\n * @returns The shipping carrier method data\n */\n getData(): ShippingCarrierMethodData {\n return this.methodData as ShippingCarrierMethodData;\n }\n}\n\nexport default ShippingCarrierMethod;\n","/**\n * <license header>\n */\n\nimport { ShippingCarrierMethodData } from './method/types';\nimport { ShippingCarrierData } from './types';\nimport ShippingCarrierMethod from './method';\n\n/**\n * Builder class for constructing shipping carriers with methods and metadata\n */\nclass ShippingCarrier {\n private carrierData: Partial<ShippingCarrierData>;\n private addedMethods: ShippingCarrierMethodData[] = [];\n private removedMethods: string[] = [];\n\n constructor(code: string, callback?: (builder: ShippingCarrier) => void) {\n this.validateCarrierCode(code);\n\n this.carrierData = {\n code,\n active: true,\n tracking_available: true,\n shipping_labels_available: true,\n };\n this.addedMethods = [];\n this.removedMethods = [];\n\n if (callback) {\n callback(this);\n }\n }\n\n /**\n * Validates that the carrier code contains only alphanumeric characters and underscores\n *\n * @param code - Carrier code to validate\n * @throws Error if code is invalid\n */\n private validateCarrierCode(code: string): void {\n if (!code || code.trim() === '') {\n throw new Error('Carrier code cannot be empty');\n }\n\n const validPattern = /^[a-zA-Z0-9_]+$/;\n if (!validPattern.test(code)) {\n throw new Error('Carrier code must contain only alphanumeric characters and underscores');\n }\n }\n\n /**\n * Validates that the method code contains only alphanumeric characters and underscores\n *\n * @param method - Method code to validate\n * @throws Error if method code is invalid\n */\n private validateMethodCode(method: string): void {\n if (!method || method.trim() === '') {\n throw new Error('Method code cannot be empty');\n }\n\n const validPattern = /^[a-zA-Z0-9_]+$/;\n if (!validPattern.test(method)) {\n throw new Error('Method code must contain only alphanumeric characters and underscores');\n }\n }\n\n /**\n * Sets the title for the shipping carrier\n *\n * @param title - Display title for the carrier\n * @returns The builder instance for method chaining\n *\n * @example\n * ```typescript\n * carrier.setTitle('FedEx Express');\n * ```\n */\n setTitle(title: string): this {\n this.carrierData.title = title;\n return this;\n }\n\n /**\n * Sets the stores for the shipping carrier\n *\n * @param stores - Array of store codes\n * @returns The builder instance for method chaining\n *\n * @example\n * ```typescript\n * carrier.setStores(['default', 'store1', 'store2']);\n * ```\n */\n setStores(stores: string[]): this {\n this.carrierData.stores = stores;\n return this;\n }\n\n /**\n * Sets the countries for the shipping carrier\n *\n * @param countries - Array of country codes\n * @returns The builder instance for method chaining\n *\n * @example\n * ```typescript\n * carrier.setCountries(['US', 'CA', 'MX']);\n * ```\n */\n setCountries(countries: string[]): this {\n this.carrierData.countries = countries;\n return this;\n }\n\n /**\n * Sets the sort order for the shipping carrier\n *\n * @param sortOrder - Sort order number\n * @returns The builder instance for method chaining\n *\n * @example\n * ```typescript\n * carrier.setSortOrder(10);\n * ```\n */\n setSortOrder(sortOrder: number): this {\n this.carrierData.sort_order = sortOrder;\n return this;\n }\n\n /**\n * Sets the active status for the shipping carrier\n *\n * @param active - Active status\n * @returns The builder instance for method chaining\n *\n * @example\n * ```typescript\n * carrier.setActive(true);\n * carrier.setActive(false);\n * ```\n */\n setActive(active: boolean): this {\n this.carrierData.active = active;\n return this;\n }\n\n /**\n * Sets the tracking availability for the shipping carrier\n *\n * @param trackingAvailable - Tracking availability status\n * @returns The builder instance for method chaining\n *\n * @example\n * ```typescript\n * carrier.setTrackingAvailable(true);\n * carrier.setTrackingAvailable(false);\n * ```\n */\n setTrackingAvailable(trackingAvailable: boolean): this {\n this.carrierData.tracking_available = trackingAvailable;\n return this;\n }\n\n /**\n * Sets the shipping labels availability for the shipping carrier\n *\n * @param shippingLabelsAvailable - Shipping labels availability status\n * @returns The builder instance for method chaining\n *\n * @example\n * ```typescript\n * carrier.setShippingLabelsAvailable(true);\n * carrier.setShippingLabelsAvailable(false);\n * ```\n */\n setShippingLabelsAvailable(shippingLabelsAvailable: boolean): this {\n this.carrierData.shipping_labels_available = shippingLabelsAvailable;\n return this;\n }\n\n /**\n * Sets the carrier data from a ShippingCarrierData object\n * Note: The code property cannot be changed once set in the constructor\n *\n * @param carrierData - Carrier data object\n * @returns The builder instance for method chaining\n *\n * @example\n * ```typescript\n * carrier.setData({\n * code: 'fedex',\n * title: 'FedEx Express',\n * stores: ['default'],\n * countries: ['US', 'CA'],\n * sort_order: 10,\n * active: true,\n * tracking_available: true,\n * shipping_labels_available: true\n * });\n * ```\n */\n setData(carrierData: ShippingCarrierData): this {\n // Preserve the original code - it cannot be changed\n const originalCode = this.carrierData.code as string;\n\n // Validate if a code is provided in the input data (even if empty string)\n if (carrierData.code !== undefined) {\n this.validateCarrierCode(carrierData.code);\n }\n\n // Copy all data but restore the original code\n this.carrierData = { ...carrierData, code: originalCode };\n return this;\n }\n\n /**\n * Adds a shipping method to the carrier using a callback pattern\n *\n * @param method - Unique method for the shipping rate\n * @param callback - Optional callback function to configure the method\n * @returns The builder instance for method chaining\n *\n * @example\n * ```typescript\n * builder.addMethod('standard', (method) => {\n * method.setMethodTitle('Standard Shipping')\n * .setPrice(9.99)\n * .setCost(5.00)\n * .addAdditionalData('delivery_time', '3-5 business days');\n * });\n * ```\n */\n addMethod(method: string, callback?: (builder: ShippingCarrierMethod) => void): this {\n this.validateMethodCode(method);\n\n const methodBuilder = new ShippingCarrierMethod(this.carrierData.code as string, method);\n\n if (callback) {\n callback(methodBuilder);\n }\n\n this.addedMethods.push(methodBuilder.getData());\n return this;\n }\n\n /**\n * Removes a shipping method from the carrier\n *\n * @param method - Method code to remove\n * @returns The builder instance for method chaining\n *\n * @example\n * ```typescript\n * builder.removeMethod('express');\n * ```\n */\n removeMethod(method: string): this {\n this.validateMethodCode(method);\n this.removedMethods.push(method);\n return this;\n }\n\n /**\n * Gets and returns the shipping carrier data as a JSON object\n *\n * @returns The shipping carrier data\n *\n * @example\n * ```typescript\n * const carrierData = carrier.getData();\n * // Returns:\n * // {\n * // code: 'DPS',\n * // title: 'Demo Postal Service',\n * // stores: ['default'],\n * // countries: ['US', 'CA'],\n * // sort_order: 10,\n * // active: true,\n * // tracking_available: true,\n * // shipping_labels_available: true\n * // }\n * ```\n */\n getData(): ShippingCarrierData {\n return this.carrierData as ShippingCarrierData;\n }\n\n /**\n * Gets the list of methods that have been added to the carrier\n *\n * @returns Array of added shipping carrier methods\n *\n * @example\n * ```typescript\n * const addedMethods = carrier.getAddedMethods();\n * // Returns: [{ carrier_code: 'fedex', method: 'standard', ... }, ...]\n * ```\n */\n getAddedMethods(): ShippingCarrierMethodData[] {\n return this.addedMethods;\n }\n\n /**\n * Gets the list of method codes that have been marked for removal\n *\n * @returns Array of method codes to be removed\n *\n * @example\n * ```typescript\n * const removedMethods = carrier.getRemovedMethods();\n * // Returns: ['overnight', 'express']\n * ```\n */\n getRemovedMethods(): string[] {\n return this.removedMethods;\n }\n}\n\nexport default ShippingCarrier;\n","/**\n * <license header>\n */\n\nimport ShippingCarrier from '..';\nimport WebhookActionResponse from '../../../framework/webhook-action/response';\nimport { WebhookActionResponseType } from '../../../framework/webhook-action/response/types';\n\n/**\n * Response generator for shipping carriers\n */\nclass ShippingCarrierResponse {\n private carrier: ShippingCarrier;\n\n constructor(carrier: ShippingCarrier) {\n this.carrier = carrier;\n }\n\n /**\n * Generates and returns an array of WebhookActionResponse operations\n *\n * @returns Array of WebhookActionResponse operations\n *\n * @example\n * ```typescript\n * const carrier = new ShippingCarrier('fedex');\n * const response = new ShippingCarrierResponse(carrier);\n * const operations = response.generate();\n * ```\n */\n generate(): WebhookActionResponseType[] {\n const operations: WebhookActionResponseType[] = [];\n\n // Get added methods from carrier\n const addedMethods = this.carrier['addedMethods'];\n for (const method of addedMethods) {\n operations.push(WebhookActionResponse.add('result', method));\n }\n\n // Get removed methods from carrier\n const removedMethods = this.carrier['removedMethods'];\n for (const method of removedMethods) {\n operations.push(WebhookActionResponse.add('result', { method: method, remove: true }));\n }\n\n return operations;\n }\n}\n\nexport default ShippingCarrierResponse;\n","/**\n * <license header>\n */\n\nimport { MenuItem, AdminUiSdkRegistration } from './types';\n\n/**\n * AdminUiSdk class for managing Admin UI extensions\n * Provides methods to create menu items, sections, and pages for Adobe Commerce Admin UI extensions\n */\nexport class AdminUiSdk {\n private extensionId: string;\n private menuItems: MenuItem[] = [];\n private pageTitle?: string;\n\n /**\n * Creates a new AdminUiSdk instance\n * @param extensionId - Unique identifier for the extension\n * @throws {Error} If extensionId is empty or invalid\n */\n constructor(extensionId: string) {\n if (!extensionId?.trim()) {\n throw new Error('Extension ID is required and cannot be empty');\n }\n\n const trimmedId = extensionId.trim();\n if (!this.isValidExtensionId(trimmedId)) {\n throw new Error(\n 'Extension ID must be alphanumeric with underscores only (no spaces, hyphens, or special characters)'\n );\n }\n\n this.extensionId = trimmedId;\n }\n\n /**\n * Validates that an extension ID contains only alphanumeric characters and underscores\n * @param id - The extension ID to validate\n * @returns true if valid, false otherwise\n */\n private isValidExtensionId(id: string): boolean {\n return /^[a-zA-Z0-9_]+$/.test(id);\n }\n\n /**\n * Validates that a menu ID is valid (can contain :: separator for namespacing)\n * @param id - The menu ID to validate\n * @returns true if valid, false otherwise\n */\n private isValidMenuId(id: string): boolean {\n return /^[a-zA-Z0-9_:]+$/.test(id);\n }\n\n /**\n * Adds a menu item to the extension\n * @param id - Full identifier for the menu item (e.g., 'extensionId::menuItem')\n * @param title - Display title for the menu item\n * @param sortOrder - Sort order for menu positioning\n * @param parent - Parent menu identifier (optional, full ID like 'extensionId::parent')\n * @throws {Error} If parameters are invalid or ID already exists\n */\n addMenuItem(id: string, title: string, sortOrder: number, parent?: string): void {\n // Validation\n if (!id?.trim()) {\n throw new Error('Menu item ID is required and cannot be empty');\n }\n if (!this.isValidMenuId(id.trim())) {\n throw new Error(\n 'Menu item ID must be alphanumeric with underscores and colons only (no spaces, hyphens, or other special characters)'\n );\n }\n if (!title?.trim()) {\n throw new Error('Menu item title is required and cannot be empty');\n }\n if (parent !== undefined && !parent?.trim()) {\n throw new Error('Menu item parent cannot be empty if provided');\n }\n if (parent !== undefined && !this.isValidMenuId(parent.trim())) {\n throw new Error(\n 'Menu item parent must be alphanumeric with underscores and colons only (no spaces, hyphens, or other special characters)'\n );\n }\n if (typeof sortOrder !== 'number' || sortOrder < 0) {\n throw new Error('Menu item sortOrder must be a non-negative number');\n }\n\n const trimmedId = id.trim();\n\n // Check for duplicate IDs\n if (this.menuItems.some(item => item.id === trimmedId)) {\n throw new Error(`Menu item with ID '${trimmedId}' already exists`);\n }\n\n // Build menu item object - only include parent if provided\n const menuItem: MenuItem = {\n id: trimmedId,\n title: title.trim(),\n sortOrder,\n };\n\n if (parent?.trim()) {\n menuItem.parent = parent.trim();\n }\n\n // Add sanitized menu item\n this.menuItems.push(menuItem);\n }\n\n /**\n * Adds a menu section to the extension\n * @param id - Full identifier for the menu section (e.g., 'extensionId::section')\n * @param title - Display title for the menu section\n * @param sortOrder - Sort order for section positioning\n * @param parent - Parent menu identifier (optional, full ID like 'Magento_Backend::system')\n * @throws {Error} If parameters are invalid or ID already exists\n */\n addMenuSection(id: string, title: string, sortOrder: number, parent?: string): void {\n // Validation\n if (!id?.trim()) {\n throw new Error('Menu section ID is required and cannot be empty');\n }\n if (!this.isValidMenuId(id.trim())) {\n throw new Error(\n 'Menu section ID must be alphanumeric with underscores and colons only (no spaces, hyphens, or other special characters)'\n );\n }\n if (!title?.trim()) {\n throw new Error('Menu section title is required and cannot be empty');\n }\n if (parent !== undefined && !parent?.trim()) {\n throw new Error('Menu section parent cannot be empty if provided');\n }\n if (parent !== undefined && !this.isValidMenuId(parent.trim())) {\n throw new Error(\n 'Menu section parent must be alphanumeric with underscores and colons only (no spaces, hyphens, or other special characters)'\n );\n }\n if (typeof sortOrder !== 'number' || sortOrder < 0) {\n throw new Error('Menu section sortOrder must be a non-negative number');\n }\n\n const trimmedId = id.trim();\n\n // Check for duplicate IDs\n if (this.menuItems.some(item => item.id === trimmedId)) {\n throw new Error(`Menu item with ID '${trimmedId}' already exists`);\n }\n\n // Build menu section object - only include parent if provided\n const menuSection: MenuItem = {\n id: trimmedId,\n title: title.trim(),\n sortOrder,\n isSection: true,\n };\n\n if (parent?.trim()) {\n menuSection.parent = parent.trim();\n }\n\n // Add sanitized menu section\n this.menuItems.push(menuSection);\n }\n\n /**\n * Sets the page title for the extension\n * @param title - The page title\n * @throws {Error} If title is empty or invalid\n */\n addPage(title: string): void {\n if (!title?.trim()) {\n throw new Error('Page title is required and cannot be empty');\n }\n this.pageTitle = title.trim();\n }\n\n /**\n * Gets the complete registration object for the extension\n * @returns The registration object with optional menu items and page configuration\n */\n getRegistration(): AdminUiSdkRegistration {\n const registration: any = {};\n\n // Only include menuItems if there are any\n if (this.menuItems.length > 0) {\n registration.menuItems = [...this.menuItems]; // Return copy to prevent mutation\n }\n\n // Only include page if title is set\n if (this.pageTitle) {\n registration.page = {\n title: this.pageTitle,\n };\n }\n\n return {\n registration,\n };\n }\n}\n"],"mappings":";;;;;;;;;;AAAA,IAkBa;AAlBb;;;AAkBO,IAAM,cAAc,OAAO,eAAe,WAAW,aAAa;;;;;AClBzE;;;AAgBA;;;;;AChBA;;;AAgBA;;;;;AChBA,IAiBa;AAjBb;;;AAiBO,IAAM,UAAU;;;;;ACmBjB,SAAU,wBACd,YAAkB;AAElB,MAAM,mBAAmB,oBAAI,IAAY,CAAC,UAAU,CAAC;AACrD,MAAM,mBAAmB,oBAAI,IAAG;AAEhC,MAAM,iBAAiB,WAAW,MAAM,EAAE;AAC1C,MAAI,CAAC,gBAAgB;AAEnB,WAAO,WAAA;AAAM,aAAA;IAAA;;AAGf,MAAM,mBAAmB;IACvB,OAAO,CAAC,eAAe,CAAC;IACxB,OAAO,CAAC,eAAe,CAAC;IACxB,OAAO,CAAC,eAAe,CAAC;IACxB,YAAY,eAAe,CAAC;;AAI9B,MAAI,iBAAiB,cAAc,MAAM;AACvC,WAAO,gCAAS,aAAa,eAAqB;AAChD,aAAO,kBAAkB;IAC3B,GAFO;;AAKT,WAAS,QAAQ,GAAS;AACxB,qBAAiB,IAAI,CAAC;AACtB,WAAO;EACT;AAHS;AAKT,WAAS,QAAQ,GAAS;AACxB,qBAAiB,IAAI,CAAC;AACtB,WAAO;EACT;AAHS;AAKT,SAAO,gCAASA,cAAa,eAAqB;AAChD,QAAI,iBAAiB,IAAI,aAAa,GAAG;AACvC,aAAO;;AAGT,QAAI,iBAAiB,IAAI,aAAa,GAAG;AACvC,aAAO;;AAGT,QAAM,qBAAqB,cAAc,MAAM,EAAE;AACj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SAAS;AAAA,IAC7C;AAGA,QAAI,KAAK,WAAW;AAClB,mBAAa,OAAO;AAAA,QAClB,OAAO,KAAK;AAAA,MACd;AAAA,IACF;AAEA,WAAO;AAAA,MACL;AAAA,IACF;AAAA,EACF;AACF;AA7LwB;AAAjB,IAAM,aAAN;","names":["isCompatible","diag","DiagComponentLogger","DiagLogLevel","DiagAPI","__spreadArray","__read","HttpStatus","HttpMethod","errorMessage","context","WebhookActionOperation","response_default","SignatureVerification","response_default","Core","_List","statusCode","errorMessage","List","_Get","statusCode","errorMessage","Get","_Create","statusCode","errorMessage","Create","create_default","_Delete","statusCode","errorMessage","Delete","List","Get","create_default","_Create","Create","create_default","_Delete","Delete","delete_default","_Get","Get","get_default","_List","List","list_default","create_default","delete_default","get_default","list_default","Core","Core","State","crypto","Core","State","crypto","existingProvider","State","State","crypto","response_default"]}