@adobe-commerce/aio-toolkit 1.0.5 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -951,6 +951,52 @@ __name(_WebhookAction, "WebhookAction");
951
951
  var WebhookAction = _WebhookAction;
952
952
  var webhook_action_default = WebhookAction;
953
953
 
954
+ // src/framework/ims-token/index.ts
955
+ import { State } from "@adobe/aio-sdk";
956
+
957
+ // src/commerce/adobe-auth/index.ts
958
+ import { context, getToken } from "@adobe/aio-lib-ims";
959
+ var _AdobeAuth = class _AdobeAuth {
960
+ /**
961
+ * Retrieves an authentication token from Adobe IMS
962
+ *
963
+ * @param clientId - The client ID for the Adobe IMS integration
964
+ * @param clientSecret - The client secret for the Adobe IMS integration
965
+ * @param technicalAccountId - The technical account ID for the Adobe IMS integration
966
+ * @param technicalAccountEmail - The technical account email for the Adobe IMS integration
967
+ * @param imsOrgId - The IMS organization ID
968
+ * @param scopes - Array of permission scopes to request for the token
969
+ * @param currentContext - The context name for storing the configuration (defaults to 'onboarding-config')
970
+ * @returns Promise<string> - A promise that resolves to the authentication token
971
+ *
972
+ * @example
973
+ * const token = await AdobeAuth.getToken(
974
+ * 'your-client-id',
975
+ * 'your-client-secret',
976
+ * 'your-technical-account-id',
977
+ * 'your-technical-account-email',
978
+ * 'your-ims-org-id',
979
+ * ['AdobeID', 'openid', 'adobeio_api']
980
+ * );
981
+ */
982
+ static async getToken(clientId, clientSecret, technicalAccountId, technicalAccountEmail, imsOrgId, scopes, currentContext = "onboarding-config") {
983
+ const config = {
984
+ client_id: clientId,
985
+ client_secrets: [clientSecret],
986
+ technical_account_id: technicalAccountId,
987
+ technical_account_email: technicalAccountEmail,
988
+ ims_org_id: imsOrgId,
989
+ scopes
990
+ };
991
+ await context.setCurrent(currentContext);
992
+ await context.set(currentContext, config);
993
+ return await getToken();
994
+ }
995
+ };
996
+ __name(_AdobeAuth, "AdobeAuth");
997
+ var AdobeAuth = _AdobeAuth;
998
+ var adobe_auth_default = AdobeAuth;
999
+
954
1000
  // src/integration/bearer-token/index.ts
955
1001
  var _BearerToken = class _BearerToken {
956
1002
  /**
@@ -1095,6 +1141,189 @@ __name(_BearerToken, "BearerToken");
1095
1141
  var BearerToken = _BearerToken;
1096
1142
  var bearer_token_default = BearerToken;
1097
1143
 
1144
+ // src/framework/ims-token/index.ts
1145
+ var _ImsToken = class _ImsToken {
1146
+ /**
1147
+ * Creates an instance of ImsToken
1148
+ *
1149
+ * @param clientId - OAuth client ID for Adobe IMS authentication
1150
+ * @param clientSecret - OAuth client secret for Adobe IMS authentication
1151
+ * @param technicalAccountId - Technical account ID for service-to-service authentication
1152
+ * @param technicalAccountEmail - Technical account email for service-to-service authentication
1153
+ * @param imsOrgId - IMS organization ID
1154
+ * @param scopes - Array of scopes required for the token
1155
+ * @param logger - Optional logger instance for logging operations
1156
+ * @param cacheKey - Optional custom cache key for token storage (defaults to 'runtime_api_gateway_token')
1157
+ * @param tokenContext - Optional token context for authentication (defaults to 'runtime-api-gateway-context')
1158
+ */
1159
+ constructor(clientId, clientSecret, technicalAccountId, technicalAccountEmail, imsOrgId, scopes, logger = null, cacheKey, tokenContext) {
1160
+ /** State property for managing token state */
1161
+ this.state = void 0;
1162
+ this.clientId = clientId;
1163
+ this.clientSecret = clientSecret;
1164
+ this.technicalAccountId = technicalAccountId;
1165
+ this.technicalAccountEmail = technicalAccountEmail;
1166
+ this.imsOrgId = imsOrgId;
1167
+ this.scopes = scopes;
1168
+ this.customLogger = new custom_logger_default(logger);
1169
+ this.key = cacheKey || "ims_token";
1170
+ this.tokenContext = tokenContext || "ims-context";
1171
+ }
1172
+ /**
1173
+ * Executes IMS token generation or retrieves a cached token
1174
+ *
1175
+ * This method first checks for a cached token. If a valid cached token exists,
1176
+ * it returns that. Otherwise, it generates a new token, caches it, and returns it.
1177
+ *
1178
+ * @returns A promise that resolves to the IMS token string or null if generation fails
1179
+ * @example
1180
+ * ```typescript
1181
+ * const token = await imsToken.execute();
1182
+ * if (token) {
1183
+ * console.log('Token obtained:', token);
1184
+ * }
1185
+ * ```
1186
+ */
1187
+ async execute() {
1188
+ try {
1189
+ this.customLogger.info("Starting IMS token generation/retrieval process");
1190
+ const currentValue = await this.getValue();
1191
+ if (currentValue !== null) {
1192
+ this.customLogger.info("Found cached IMS token, returning cached value");
1193
+ return currentValue;
1194
+ }
1195
+ this.customLogger.info("No cached token found, generating new IMS token");
1196
+ let result = {
1197
+ token: null,
1198
+ expire_in: 86399
1199
+ // Default fallback, will be overridden by actual token expiry
1200
+ };
1201
+ const response = await this.getImsToken();
1202
+ if (response !== null) {
1203
+ result = response;
1204
+ }
1205
+ if (result.token !== null) {
1206
+ this.customLogger.info(`Generated new IMS token, caching for ${result.expire_in} seconds`);
1207
+ await this.setValue(result);
1208
+ }
1209
+ return result.token;
1210
+ } catch (error) {
1211
+ this.customLogger.error(`Failed to execute IMS token generation: ${error.message}`);
1212
+ return null;
1213
+ }
1214
+ }
1215
+ /**
1216
+ * Generates a new IMS token from Adobe IMS service
1217
+ *
1218
+ * @returns A promise that resolves to ImsTokenResult or null if generation fails
1219
+ * @private
1220
+ */
1221
+ async getImsToken() {
1222
+ try {
1223
+ this.customLogger.debug(`Calling AdobeAuth.getToken with context: ${this.tokenContext}`);
1224
+ const token = await adobe_auth_default.getToken(
1225
+ this.clientId,
1226
+ this.clientSecret,
1227
+ this.technicalAccountId,
1228
+ this.technicalAccountEmail,
1229
+ this.imsOrgId,
1230
+ this.scopes,
1231
+ this.tokenContext
1232
+ );
1233
+ if (token !== null && token !== void 0) {
1234
+ this.customLogger.debug("Received token from AdobeAuth, parsing with BearerToken.info");
1235
+ const tokenInfo = bearer_token_default.info(token);
1236
+ if (!tokenInfo.isValid) {
1237
+ this.customLogger.error("Received invalid or expired token from IMS");
1238
+ return null;
1239
+ }
1240
+ const expireInSeconds = tokenInfo.timeUntilExpiry ? Math.floor(tokenInfo.timeUntilExpiry / 1e3) : 86399;
1241
+ this.customLogger.debug(`Token expires in ${expireInSeconds} seconds`);
1242
+ return {
1243
+ token,
1244
+ expire_in: expireInSeconds
1245
+ };
1246
+ }
1247
+ this.customLogger.error("Received null or undefined token from IMS");
1248
+ return null;
1249
+ } catch (error) {
1250
+ this.customLogger.error(`Failed to get IMS token: ${error.message}`);
1251
+ return null;
1252
+ }
1253
+ }
1254
+ /**
1255
+ * Caches the IMS token in the state store with TTL
1256
+ *
1257
+ * @param result - The token result containing the token and expiration time
1258
+ * @returns A promise that resolves to true if caching succeeded, false otherwise
1259
+ * @private
1260
+ */
1261
+ async setValue(result) {
1262
+ try {
1263
+ const state = await this.getState();
1264
+ if (state === null) {
1265
+ this.customLogger.info("State API not available, skipping token caching");
1266
+ return true;
1267
+ }
1268
+ const ttlWithBuffer = Math.max(result.expire_in - 600, 3600);
1269
+ this.customLogger.debug(
1270
+ `Caching IMS token with TTL: ${ttlWithBuffer} seconds (original: ${result.expire_in})`
1271
+ );
1272
+ await state.put(this.key, result.token, { ttl: ttlWithBuffer });
1273
+ return true;
1274
+ } catch (error) {
1275
+ this.customLogger.error(`Failed to cache IMS token: ${error.message}`);
1276
+ return true;
1277
+ }
1278
+ }
1279
+ /**
1280
+ * Retrieves a cached IMS token from the state store
1281
+ *
1282
+ * @returns A promise that resolves to the cached token string or null if not found
1283
+ * @private
1284
+ */
1285
+ async getValue() {
1286
+ try {
1287
+ this.customLogger.debug("Checking for cached IMS token");
1288
+ const state = await this.getState();
1289
+ if (state === null) {
1290
+ this.customLogger.debug("State API not available, cannot retrieve cached token");
1291
+ return null;
1292
+ }
1293
+ const value = await state.get(this.key);
1294
+ if (value !== void 0 && value.value) {
1295
+ this.customLogger.debug("Found cached IMS token");
1296
+ return value.value;
1297
+ }
1298
+ this.customLogger.debug("No cached IMS token found");
1299
+ } catch (error) {
1300
+ this.customLogger.error(`Failed to retrieve cached IMS token: ${error.message}`);
1301
+ }
1302
+ return null;
1303
+ }
1304
+ /**
1305
+ * Initializes and returns the state store instance
1306
+ *
1307
+ * @returns A promise that resolves to the state instance or null if initialization fails
1308
+ * @private
1309
+ */
1310
+ async getState() {
1311
+ if (this.state === void 0) {
1312
+ try {
1313
+ this.customLogger.debug("Initializing State API for token caching");
1314
+ this.state = await State.init();
1315
+ } catch (error) {
1316
+ this.customLogger.error(`Failed to initialize State API: ${error.message}`);
1317
+ this.state = null;
1318
+ }
1319
+ }
1320
+ return this.state;
1321
+ }
1322
+ };
1323
+ __name(_ImsToken, "ImsToken");
1324
+ var ImsToken = _ImsToken;
1325
+ var ims_token_default = ImsToken;
1326
+
1098
1327
  // src/integration/rest-client/index.ts
1099
1328
  import fetch from "node-fetch";
1100
1329
  var _RestClient = class _RestClient {
@@ -1267,6 +1496,219 @@ __name(_RestClient, "RestClient");
1267
1496
  var RestClient = _RestClient;
1268
1497
  var rest_client_default = RestClient;
1269
1498
 
1499
+ // src/framework/runtime-api-gateway-service/index.ts
1500
+ var _RuntimeApiGatewayService = class _RuntimeApiGatewayService {
1501
+ /**
1502
+ * Creates an instance of RuntimeApiGatewayService
1503
+ *
1504
+ * @param clientId - OAuth client ID for Adobe IMS authentication
1505
+ * @param clientSecret - OAuth client secret for Adobe IMS authentication
1506
+ * @param technicalAccountId - Technical account ID for service-to-service authentication
1507
+ * @param technicalAccountEmail - Technical account email for service-to-service authentication
1508
+ * @param imsOrgId - IMS organization ID
1509
+ * @param scopes - Array of scopes required for the token
1510
+ * @param namespace - The Adobe I/O Runtime namespace identifier
1511
+ * @param logger - Optional logger instance for logging operations
1512
+ * @example
1513
+ * ```typescript
1514
+ * const service = new RuntimeApiGatewayService(
1515
+ * 'client-id',
1516
+ * 'client-secret',
1517
+ * 'tech-account-id',
1518
+ * 'tech@example.com',
1519
+ * 'org-id',
1520
+ * ['openid', 'AdobeID'],
1521
+ * 'my-namespace-12345',
1522
+ * logger // optional
1523
+ * );
1524
+ * ```
1525
+ */
1526
+ constructor(clientId, clientSecret, technicalAccountId, technicalAccountEmail, imsOrgId, scopes, namespace, logger = null) {
1527
+ this.namespace = namespace;
1528
+ this.imsOrgId = imsOrgId;
1529
+ this.customLogger = new custom_logger_default(logger);
1530
+ this.imsToken = new ims_token_default(
1531
+ clientId,
1532
+ clientSecret,
1533
+ technicalAccountId,
1534
+ technicalAccountEmail,
1535
+ imsOrgId,
1536
+ scopes,
1537
+ logger,
1538
+ "runtime_api_gateway_token",
1539
+ "runtime-api-gateway-context"
1540
+ );
1541
+ this.restClient = new rest_client_default();
1542
+ }
1543
+ /**
1544
+ * Builds the complete API endpoint URL
1545
+ *
1546
+ * @param endpoint - API endpoint path (e.g., 'v1/my-endpoint')
1547
+ * @returns The fully constructed endpoint URL
1548
+ * @private
1549
+ */
1550
+ buildEndpoint(endpoint) {
1551
+ return `${_RuntimeApiGatewayService.BASE_URL}/${this.namespace}/${endpoint}`;
1552
+ }
1553
+ /**
1554
+ * Gets the authenticated headers for API requests
1555
+ *
1556
+ * @returns A promise that resolves with the headers object including authentication
1557
+ * @throws {Error} If token generation fails
1558
+ * @private
1559
+ */
1560
+ async getAuthenticatedHeaders() {
1561
+ this.customLogger.debug("Generating authenticated headers for API request");
1562
+ const token = await this.imsToken.execute();
1563
+ if (!token) {
1564
+ this.customLogger.error("Failed to generate IMS token for authenticated headers");
1565
+ throw new Error("Failed to generate IMS token");
1566
+ }
1567
+ this.customLogger.debug("Successfully generated authenticated headers");
1568
+ return {
1569
+ "Content-Type": "application/json",
1570
+ Authorization: `Bearer ${token}`,
1571
+ "x-gw-ims-org-id": this.imsOrgId
1572
+ };
1573
+ }
1574
+ /**
1575
+ * Performs a GET request to the Runtime API Gateway
1576
+ *
1577
+ * @param endpoint - API endpoint path (e.g., 'v1/my-endpoint')
1578
+ * @param additionalHeaders - Optional additional headers to include in the request
1579
+ * @returns A promise that resolves with the API response data
1580
+ * @throws {Error} If the API request fails
1581
+ * @example
1582
+ * ```typescript
1583
+ * const service = new RuntimeApiGatewayService(...);
1584
+ * const data = await service.get('v1/my-endpoint');
1585
+ *
1586
+ * // With additional headers
1587
+ * const data = await service.get('v1/my-endpoint', { 'Custom-Header': 'value' });
1588
+ * ```
1589
+ */
1590
+ async get(endpoint, additionalHeaders = {}) {
1591
+ try {
1592
+ const url = this.buildEndpoint(endpoint);
1593
+ this.customLogger.info(`Performing GET request to: ${url}`);
1594
+ const headers = { ...await this.getAuthenticatedHeaders(), ...additionalHeaders };
1595
+ this.customLogger.debug(`GET headers: ${JSON.stringify(headers)}`);
1596
+ const response = await this.restClient.get(url, headers, false);
1597
+ this.customLogger.debug(`GET response: ${JSON.stringify(response)}`);
1598
+ this.customLogger.info("GET request completed successfully");
1599
+ return response;
1600
+ } catch (error) {
1601
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
1602
+ this.customLogger.error(`GET request failed: ${errorMessage}`);
1603
+ throw new Error(`Runtime API gateway GET request failed: ${errorMessage}`);
1604
+ }
1605
+ }
1606
+ /**
1607
+ * Performs a POST request to the Runtime API Gateway
1608
+ *
1609
+ * @param endpoint - API endpoint path (e.g., 'v1/my-endpoint')
1610
+ * @param payload - The data to send in the request body
1611
+ * @param additionalHeaders - Optional additional headers to include in the request
1612
+ * @returns A promise that resolves with the API response data
1613
+ * @throws {Error} If the API request fails
1614
+ * @example
1615
+ * ```typescript
1616
+ * const service = new RuntimeApiGatewayService(...);
1617
+ * const result = await service.post('v1/my-endpoint', { key: 'value' });
1618
+ *
1619
+ * // With additional headers
1620
+ * const result = await service.post('v1/my-endpoint', { key: 'value' }, { 'Custom-Header': 'value' });
1621
+ * ```
1622
+ */
1623
+ async post(endpoint, payload, additionalHeaders = {}) {
1624
+ try {
1625
+ const url = this.buildEndpoint(endpoint);
1626
+ this.customLogger.info(`Performing POST request to: ${url}`);
1627
+ this.customLogger.debug(`POST payload: ${JSON.stringify(payload)}`);
1628
+ const headers = { ...await this.getAuthenticatedHeaders(), ...additionalHeaders };
1629
+ this.customLogger.debug(`POST headers: ${JSON.stringify(headers)}`);
1630
+ const response = await this.restClient.post(url, headers, payload, false);
1631
+ this.customLogger.debug(`POST response: ${JSON.stringify(response)}`);
1632
+ this.customLogger.info("POST request completed successfully");
1633
+ return response;
1634
+ } catch (error) {
1635
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
1636
+ this.customLogger.error(`POST request failed: ${errorMessage}`);
1637
+ throw new Error(`Runtime API gateway POST request failed: ${errorMessage}`);
1638
+ }
1639
+ }
1640
+ /**
1641
+ * Performs a PUT request to the Runtime API Gateway
1642
+ *
1643
+ * @param endpoint - API endpoint path (e.g., 'v1/my-endpoint')
1644
+ * @param payload - The data to send in the request body
1645
+ * @param additionalHeaders - Optional additional headers to include in the request
1646
+ * @returns A promise that resolves with the API response data
1647
+ * @throws {Error} If the API request fails
1648
+ * @example
1649
+ * ```typescript
1650
+ * const service = new RuntimeApiGatewayService(...);
1651
+ * const updated = await service.put('v1/my-endpoint', { id: 1, name: 'updated' });
1652
+ *
1653
+ * // With additional headers
1654
+ * const updated = await service.put('v1/my-endpoint', { id: 1 }, { 'Custom-Header': 'value' });
1655
+ * ```
1656
+ */
1657
+ async put(endpoint, payload, additionalHeaders = {}) {
1658
+ try {
1659
+ const url = this.buildEndpoint(endpoint);
1660
+ this.customLogger.info(`Performing PUT request to: ${url}`);
1661
+ this.customLogger.debug(`PUT payload: ${JSON.stringify(payload)}`);
1662
+ const headers = { ...await this.getAuthenticatedHeaders(), ...additionalHeaders };
1663
+ this.customLogger.debug(`PUT headers: ${JSON.stringify(headers)}`);
1664
+ const response = await this.restClient.put(url, headers, payload, false);
1665
+ this.customLogger.debug(`PUT response: ${JSON.stringify(response)}`);
1666
+ this.customLogger.info("PUT request completed successfully");
1667
+ return response;
1668
+ } catch (error) {
1669
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
1670
+ this.customLogger.error(`PUT request failed: ${errorMessage}`);
1671
+ throw new Error(`Runtime API gateway PUT request failed: ${errorMessage}`);
1672
+ }
1673
+ }
1674
+ /**
1675
+ * Performs a DELETE request to the Runtime API Gateway
1676
+ *
1677
+ * @param endpoint - API endpoint path (e.g., 'v1/my-endpoint')
1678
+ * @param additionalHeaders - Optional additional headers to include in the request
1679
+ * @returns A promise that resolves with the API response data
1680
+ * @throws {Error} If the API request fails
1681
+ * @example
1682
+ * ```typescript
1683
+ * const service = new RuntimeApiGatewayService(...);
1684
+ * const deleted = await service.delete('v1/my-endpoint');
1685
+ *
1686
+ * // With additional headers
1687
+ * const deleted = await service.delete('v1/my-endpoint', { 'Custom-Header': 'value' });
1688
+ * ```
1689
+ */
1690
+ async delete(endpoint, additionalHeaders = {}) {
1691
+ try {
1692
+ const url = this.buildEndpoint(endpoint);
1693
+ this.customLogger.info(`Performing DELETE request to: ${url}`);
1694
+ const headers = { ...await this.getAuthenticatedHeaders(), ...additionalHeaders };
1695
+ this.customLogger.debug(`DELETE headers: ${JSON.stringify(headers)}`);
1696
+ const response = await this.restClient.delete(url, headers, false);
1697
+ this.customLogger.debug(`DELETE response: ${JSON.stringify(response)}`);
1698
+ this.customLogger.info("DELETE request completed successfully");
1699
+ return response;
1700
+ } catch (error) {
1701
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
1702
+ this.customLogger.error(`DELETE request failed: ${errorMessage}`);
1703
+ throw new Error(`Runtime API gateway DELETE request failed: ${errorMessage}`);
1704
+ }
1705
+ }
1706
+ };
1707
+ __name(_RuntimeApiGatewayService, "RuntimeApiGatewayService");
1708
+ /** Base URL for the Adobe I/O Runtime APIs */
1709
+ _RuntimeApiGatewayService.BASE_URL = "https://adobeioruntime.net/apis";
1710
+ var RuntimeApiGatewayService = _RuntimeApiGatewayService;
1711
+
1270
1712
  // src/integration/onboard-events/index.ts
1271
1713
  import { Core as Core4 } from "@adobe/aio-sdk";
1272
1714
 
@@ -4779,7 +5221,7 @@ var OnboardEvents = _OnboardEvents;
4779
5221
  var onboard_events_default = OnboardEvents;
4780
5222
 
4781
5223
  // src/integration/infinite-loop-breaker/index.ts
4782
- import { Core as Core5, State } from "@adobe/aio-sdk";
5224
+ import { Core as Core5, State as State2 } from "@adobe/aio-sdk";
4783
5225
  import crypto2 from "crypto";
4784
5226
  var _InfiniteLoopBreaker = class _InfiniteLoopBreaker {
4785
5227
  // seconds
@@ -4805,7 +5247,7 @@ var _InfiniteLoopBreaker = class _InfiniteLoopBreaker {
4805
5247
  }
4806
5248
  const key = typeof keyFn === "function" ? keyFn() : keyFn;
4807
5249
  const data = typeof fingerprintFn === "function" ? fingerprintFn() : fingerprintFn;
4808
- const state = await State.init();
5250
+ const state = await State2.init();
4809
5251
  const persistedFingerPrint = await state.get(key);
4810
5252
  if (!persistedFingerPrint) {
4811
5253
  logger.debug(`No persisted fingerprint found for key ${key}`);
@@ -4826,7 +5268,7 @@ var _InfiniteLoopBreaker = class _InfiniteLoopBreaker {
4826
5268
  static async storeFingerPrint(keyFn, fingerprintFn, ttl) {
4827
5269
  const key = typeof keyFn === "function" ? keyFn() : keyFn;
4828
5270
  const data = typeof fingerprintFn === "function" ? fingerprintFn() : fingerprintFn;
4829
- const state = await State.init();
5271
+ const state = await State2.init();
4830
5272
  await state.put(key, _InfiniteLoopBreaker.fingerPrint(data), {
4831
5273
  ttl: ttl !== void 0 ? ttl : _InfiniteLoopBreaker.DEFAULT_INFINITE_LOOP_BREAKER_TTL
4832
5274
  });
@@ -4843,80 +5285,550 @@ var _InfiniteLoopBreaker = class _InfiniteLoopBreaker {
4843
5285
  };
4844
5286
  }
4845
5287
  /**
4846
- * This function generates a function to create a key for the infinite loop detection based on params.
5288
+ * This function generates a function to create a key for the infinite loop detection based on params.
5289
+ *
5290
+ * @param key - Data received from the event
5291
+ * @returns The function that generates the key
5292
+ */
5293
+ static fnInfiniteLoopKey(key) {
5294
+ return () => {
5295
+ return key;
5296
+ };
5297
+ }
5298
+ /**
5299
+ * This function generates a fingerprint for the data
5300
+ *
5301
+ * @param data - The data to generate the fingerprint
5302
+ * @returns The fingerprint
5303
+ */
5304
+ static fingerPrint(data) {
5305
+ const hash = crypto2.createHash(_InfiniteLoopBreaker.FINGERPRINT_ALGORITHM);
5306
+ hash.update(JSON.stringify(data));
5307
+ return hash.digest(_InfiniteLoopBreaker.FINGERPRINT_ENCODING);
5308
+ }
5309
+ };
5310
+ __name(_InfiniteLoopBreaker, "InfiniteLoopBreaker");
5311
+ /** The algorithm used to generate the fingerprint */
5312
+ _InfiniteLoopBreaker.FINGERPRINT_ALGORITHM = "sha256";
5313
+ /** The encoding used to generate the fingerprint */
5314
+ _InfiniteLoopBreaker.FINGERPRINT_ENCODING = "hex";
5315
+ /** The default time to live for the fingerprint in the lib state */
5316
+ _InfiniteLoopBreaker.DEFAULT_INFINITE_LOOP_BREAKER_TTL = 60;
5317
+ var InfiniteLoopBreaker = _InfiniteLoopBreaker;
5318
+ var infinite_loop_breaker_default = InfiniteLoopBreaker;
5319
+
5320
+ // src/integration/onboard-commerce/configure-provider/index.ts
5321
+ import {
5322
+ EventConfigurationService,
5323
+ EventProviderService
5324
+ } from "@adobe-commerce/aio-services-kit";
5325
+ var _ConfigureProvider = class _ConfigureProvider {
5326
+ /**
5327
+ * Constructor for ConfigureProvider
5328
+ *
5329
+ * @param adobeCommerceClient - Adobe Commerce client instance
5330
+ * @param merchantId - Merchant ID for Adobe Commerce
5331
+ * @param environmentId - Environment ID for Adobe Commerce
5332
+ * @param logger - Optional logger instance for logging operations
5333
+ * @throws {Error} When required parameters are missing or invalid
5334
+ * @example
5335
+ * ```typescript
5336
+ * const configureProvider = new ConfigureProvider(
5337
+ * adobeCommerceClient,
5338
+ * 'merchant-id-123',
5339
+ * 'environment-id-456',
5340
+ * logger
5341
+ * );
5342
+ * ```
5343
+ */
5344
+ constructor(adobeCommerceClient, merchantId, environmentId, logger = null) {
5345
+ if (!adobeCommerceClient) {
5346
+ throw new Error("Adobe Commerce client is required");
5347
+ }
5348
+ if (!merchantId || typeof merchantId !== "string") {
5349
+ throw new Error("Valid merchant ID is required");
5350
+ }
5351
+ if (!environmentId || typeof environmentId !== "string") {
5352
+ throw new Error("Valid environment ID is required");
5353
+ }
5354
+ this.adobeCommerceClient = adobeCommerceClient;
5355
+ this.merchantId = merchantId;
5356
+ this.environmentId = environmentId;
5357
+ this.customLogger = new custom_logger_default(logger);
5358
+ this.eventProviderService = new EventProviderService(this.adobeCommerceClient);
5359
+ this.eventConfigurationService = new EventConfigurationService(this.adobeCommerceClient);
5360
+ }
5361
+ /**
5362
+ * Execute provider configuration
5363
+ *
5364
+ * This method handles the provider configuration process for Adobe I/O Events.
5365
+ *
5366
+ * @param provider - Provider configuration for Adobe I/O Events
5367
+ * @param workspaceConfig - Workspace configuration settings
5368
+ * @returns A promise that resolves with the configuration result
5369
+ * @throws {Error} If provider configuration fails
5370
+ * @example
5371
+ * ```typescript
5372
+ * const result = await configureProvider.execute(provider, workspaceConfig);
5373
+ * if (result.success) {
5374
+ * console.log('Provider configured successfully');
5375
+ * }
5376
+ * ```
5377
+ */
5378
+ async execute(provider, workspaceConfig) {
5379
+ this.customLogger.debug("[DEBUG] Starting provider configuration");
5380
+ try {
5381
+ this.validateConfigureParams(provider, workspaceConfig);
5382
+ this.customLogger.debug("[FETCH] Fetching current event providers");
5383
+ const eventProviderResult = await this.eventProviderService.list();
5384
+ if (!eventProviderResult.success) {
5385
+ const errorMsg = `Failed to fetch event providers: ${eventProviderResult.error}`;
5386
+ this.customLogger.error(`[ERROR] ${errorMsg}`);
5387
+ return {
5388
+ success: false,
5389
+ error: errorMsg,
5390
+ details: eventProviderResult
5391
+ };
5392
+ }
5393
+ const workspaceUpdateResult = await this.updateWorkspaceIfEmpty(
5394
+ eventProviderResult.data,
5395
+ workspaceConfig
5396
+ );
5397
+ if (!workspaceUpdateResult.success) {
5398
+ return workspaceUpdateResult;
5399
+ }
5400
+ const providerList = Array.isArray(eventProviderResult.data) ? eventProviderResult.data : [];
5401
+ const existingProvider = providerList.find(
5402
+ (existingProvider2) => existingProvider2.provider_id === provider.id
5403
+ );
5404
+ if (existingProvider) {
5405
+ this.customLogger.info(`[SKIP] Provider ${provider.id} is already configured`);
5406
+ return {
5407
+ success: true,
5408
+ provider: existingProvider
5409
+ };
5410
+ } else {
5411
+ this.customLogger.debug(
5412
+ `[DEBUG] Provider ${provider.id} is not yet configured - creating new provider...`
5413
+ );
5414
+ const createResult = await this.createNewProvider(provider, workspaceConfig);
5415
+ if (!createResult.success) {
5416
+ return createResult;
5417
+ }
5418
+ this.customLogger.info(`[CREATE] Event provider ${provider.id} created successfully`);
5419
+ return {
5420
+ success: true,
5421
+ provider: createResult.provider
5422
+ };
5423
+ }
5424
+ } catch (error) {
5425
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
5426
+ this.customLogger.error(`[ERROR] Provider configuration failed: ${errorMessage}`);
5427
+ return {
5428
+ success: false,
5429
+ error: errorMessage
5430
+ };
5431
+ }
5432
+ }
5433
+ /**
5434
+ * Creates a new event provider
5435
+ *
5436
+ * @param provider - Provider configuration object
5437
+ * @param workspaceConfig - Workspace configuration object
5438
+ * @returns Creation result with success status and provider data
5439
+ * @private
5440
+ */
5441
+ async createNewProvider(provider, workspaceConfig) {
5442
+ const providerData = {
5443
+ provider_id: provider.id,
5444
+ instance_id: provider.instance_id,
5445
+ // Already validated in validateConfigureParams
5446
+ label: provider.label,
5447
+ description: provider.description,
5448
+ workspace_configuration: JSON.stringify(workspaceConfig)
5449
+ };
5450
+ this.customLogger.debug(
5451
+ `[DEBUG] Creating event provider:
5452
+ ${JSON.stringify(providerData, null, 2)}`
5453
+ );
5454
+ const createResult = await this.eventProviderService.create(providerData);
5455
+ if (!createResult.success) {
5456
+ const errorMsg = `Failed to create event provider: ${createResult.error}`;
5457
+ this.customLogger.error(`[ERROR] ${errorMsg}`);
5458
+ return {
5459
+ success: false,
5460
+ error: errorMsg,
5461
+ details: createResult
5462
+ };
5463
+ }
5464
+ return {
5465
+ success: true,
5466
+ provider: createResult.data
5467
+ };
5468
+ }
5469
+ /**
5470
+ * Updates workspace configuration if the default workspace is empty
5471
+ *
5472
+ * @param existingProviders - Array of existing providers
5473
+ * @param workspaceConfig - Workspace configuration object
5474
+ * @returns Update result with success status
5475
+ * @private
5476
+ */
5477
+ async updateWorkspaceIfEmpty(existingProviders, workspaceConfig) {
5478
+ const providerArray = Array.isArray(existingProviders) ? existingProviders : [];
5479
+ const isDefaultWorkspaceEmpty = providerArray.length === 0 || providerArray.every(
5480
+ (item) => !item.workspace_configuration || item.workspace_configuration === ""
5481
+ );
5482
+ if (isDefaultWorkspaceEmpty) {
5483
+ this.customLogger.debug("[DEBUG] Default workspace is empty, updating configuration...");
5484
+ const updateConfigPayload = {
5485
+ enabled: true,
5486
+ merchant_id: this.merchantId,
5487
+ environment_id: this.environmentId,
5488
+ workspace_configuration: JSON.stringify(workspaceConfig)
5489
+ };
5490
+ this.customLogger.debug(
5491
+ `[DEBUG] Updating configuration with payload:
5492
+ ${JSON.stringify(updateConfigPayload, null, 2)}`
5493
+ );
5494
+ const updateResult = await this.eventConfigurationService.update(updateConfigPayload);
5495
+ if (!updateResult.success) {
5496
+ const errorMsg = `Failed to update configuration: ${updateResult.error}`;
5497
+ this.customLogger.error(`[ERROR] ${errorMsg}`);
5498
+ return {
5499
+ success: false,
5500
+ error: errorMsg,
5501
+ details: updateResult
5502
+ };
5503
+ }
5504
+ this.customLogger.info("[UPDATE] Configuration updated successfully");
5505
+ }
5506
+ return { success: true };
5507
+ }
5508
+ /**
5509
+ * Validate input parameters for configure method
5510
+ *
5511
+ * @param provider - Provider configuration for Adobe I/O Events
5512
+ * @param workspaceConfig - Workspace configuration settings
5513
+ * @throws {Error} If validation fails
5514
+ * @private
5515
+ */
5516
+ validateConfigureParams(provider, workspaceConfig) {
5517
+ if (!provider || typeof provider !== "object") {
5518
+ throw new Error("Provider configuration object is required");
5519
+ }
5520
+ const requiredProviderFields = [
5521
+ "id",
5522
+ "instance_id",
5523
+ "label",
5524
+ "description"
5525
+ ];
5526
+ for (const field of requiredProviderFields) {
5527
+ if (!provider[field] || typeof provider[field] !== "string") {
5528
+ throw new Error(`Provider ${field} is required and must be a string`);
5529
+ }
5530
+ }
5531
+ if (!workspaceConfig || typeof workspaceConfig !== "object") {
5532
+ throw new Error("Workspace configuration object is required");
5533
+ }
5534
+ this.customLogger.debug(`[DEBUG] Validated provider: ${provider.label} (${provider.id})`);
5535
+ }
5536
+ };
5537
+ __name(_ConfigureProvider, "ConfigureProvider");
5538
+ var ConfigureProvider = _ConfigureProvider;
5539
+ var configure_provider_default = ConfigureProvider;
5540
+
5541
+ // src/integration/onboard-commerce/index.ts
5542
+ import {
5543
+ EventService,
5544
+ EventSubscriptionService
5545
+ } from "@adobe-commerce/aio-services-kit";
5546
+ var _OnboardCommerce = class _OnboardCommerce {
5547
+ /**
5548
+ * Constructor for OnboardCommerce
5549
+ *
5550
+ * @param adobeCommerceClient - Adobe Commerce client instance
5551
+ * @param merchantId - Merchant ID for Adobe Commerce
5552
+ * @param environmentId - Environment ID for Adobe Commerce
5553
+ * @param logger - Optional logger instance for logging operations
5554
+ * @throws {Error} When required parameters are missing or invalid
5555
+ * @example
5556
+ * ```typescript
5557
+ * const adobeCommerceClient = new AdobeCommerceClient(...);
5558
+ * const onboardCommerce = new OnboardCommerce(
5559
+ * adobeCommerceClient,
5560
+ * 'merchant-id-123',
5561
+ * 'environment-id-456',
5562
+ * logger
5563
+ * );
5564
+ * ```
5565
+ */
5566
+ constructor(adobeCommerceClient, merchantId, environmentId, logger = null) {
5567
+ if (!adobeCommerceClient) {
5568
+ throw new Error("Adobe Commerce client is required");
5569
+ }
5570
+ if (!merchantId || typeof merchantId !== "string") {
5571
+ throw new Error("Valid merchant ID is required");
5572
+ }
5573
+ if (!environmentId || typeof environmentId !== "string") {
5574
+ throw new Error("Valid environment ID is required");
5575
+ }
5576
+ this.adobeCommerceClient = adobeCommerceClient;
5577
+ this.merchantId = merchantId;
5578
+ this.environmentId = environmentId;
5579
+ this.customLogger = new custom_logger_default(logger);
5580
+ this.configureProvider = new configure_provider_default(
5581
+ adobeCommerceClient,
5582
+ merchantId,
5583
+ environmentId,
5584
+ logger
5585
+ );
5586
+ this.eventSubscriptionService = new EventSubscriptionService(adobeCommerceClient);
5587
+ this.eventService = new EventService(adobeCommerceClient);
5588
+ }
5589
+ /**
5590
+ * Process Adobe Commerce I/O Events Configuration
5591
+ *
5592
+ * This method automates the configuration of Adobe Commerce I/O Events by setting up
5593
+ * the provider, workspace, and commerce-specific event configurations.
5594
+ *
5595
+ * @param provider - Provider configuration for Adobe I/O Events
5596
+ * @param workspaceConfig - Workspace configuration settings
5597
+ * @param commerceEventsConfig - Array of commerce event configurations (optional, defaults to empty array)
5598
+ * @returns A promise that resolves with the configuration result
5599
+ * @throws {Error} If configuration fails
5600
+ * @example
5601
+ * ```typescript
5602
+ * const result = await onboardCommerce.process(
5603
+ * providerConfig,
5604
+ * workspaceConfig,
5605
+ * commerceEventsConfig
5606
+ * );
5607
+ * ```
5608
+ */
5609
+ async process(provider, workspaceConfig, commerceEventsConfig = []) {
5610
+ this.customLogger.info(
5611
+ `[START] Configuring Adobe Commerce I/O Events
5612
+ Provider: ${provider.label} (${provider.id})
5613
+ Workspace: ${workspaceConfig.project.name}
5614
+ Events to process: ${commerceEventsConfig.length}`
5615
+ );
5616
+ try {
5617
+ const providerResult = await this.configureProvider.execute(provider, workspaceConfig);
5618
+ if (!providerResult.success) {
5619
+ return providerResult;
5620
+ }
5621
+ if (commerceEventsConfig && commerceEventsConfig.length > 0) {
5622
+ this.customLogger.debug("[FETCH] Fetching current event subscriptions...");
5623
+ const eventSubscriptionsResult = await this.eventSubscriptionService.list();
5624
+ let existingSubscriptions = [];
5625
+ if (!eventSubscriptionsResult.success) {
5626
+ this.customLogger.error(
5627
+ `[ERROR] Failed to fetch event subscriptions: ${eventSubscriptionsResult.error}`
5628
+ );
5629
+ } else {
5630
+ existingSubscriptions = Array.isArray(eventSubscriptionsResult.data) ? eventSubscriptionsResult.data : [];
5631
+ this.customLogger.debug(
5632
+ `[FETCH] Retrieved ${existingSubscriptions.length} existing event subscription(s)`
5633
+ );
5634
+ }
5635
+ this.customLogger.debug("[FETCH] Fetching supported events list...");
5636
+ const supportedEventsResult = await this.eventService.supportedList();
5637
+ let supportedEvents = [];
5638
+ if (!supportedEventsResult.success) {
5639
+ this.customLogger.error(
5640
+ `[ERROR] Failed to fetch supported events: ${supportedEventsResult.error}`
5641
+ );
5642
+ } else {
5643
+ supportedEvents = Array.isArray(supportedEventsResult.data) ? supportedEventsResult.data : [];
5644
+ this.customLogger.debug(`[FETCH] Retrieved ${supportedEvents.length} supported event(s)`);
5645
+ }
5646
+ const { alreadySubscribed, needsSubscription, unsupported } = this.filterEventsBySubscriptionStatus(
5647
+ commerceEventsConfig,
5648
+ existingSubscriptions,
5649
+ provider.id,
5650
+ supportedEvents
5651
+ );
5652
+ const result = {
5653
+ successfulSubscriptions: [],
5654
+ failedSubscriptions: [],
5655
+ alreadySubscribed: alreadySubscribed.map((event) => event.event.name),
5656
+ unsupported: unsupported.map((event) => event.event?.name || "Unknown"),
5657
+ skipped: alreadySubscribed.length + unsupported.length
5658
+ };
5659
+ for (const commerceEvent of needsSubscription) {
5660
+ try {
5661
+ const preparedEvent = this.prepareEventPayload(commerceEvent, provider.id);
5662
+ this.customLogger.debug(
5663
+ `[DEBUG] Subscribing to event with payload:
5664
+ ${JSON.stringify(preparedEvent.event, null, 2)}`
5665
+ );
5666
+ const eventSubscribeResult = await this.eventSubscriptionService.create(
5667
+ preparedEvent.event
5668
+ );
5669
+ if (!eventSubscribeResult.success) {
5670
+ result.failedSubscriptions.push(commerceEvent.event.name);
5671
+ this.customLogger.error(
5672
+ `[ERROR] Failed to subscribe to event: ${commerceEvent.event.name} - ${eventSubscribeResult.error}`
5673
+ );
5674
+ continue;
5675
+ }
5676
+ this.customLogger.info(`[CREATE] Successfully subscribed: ${commerceEvent.event.name}`);
5677
+ result.successfulSubscriptions.push(commerceEvent.event.name);
5678
+ } catch (error) {
5679
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
5680
+ result.failedSubscriptions.push(commerceEvent.event?.name || "Unknown");
5681
+ this.customLogger.error(
5682
+ `[ERROR] Error processing event subscription for ${commerceEvent.event?.name || "Unknown"}: ${errorMessage}`
5683
+ );
5684
+ }
5685
+ }
5686
+ this.logEventSubscriptionSummary(result, provider.label);
5687
+ }
5688
+ return {
5689
+ success: true,
5690
+ message: "Configuration completed successfully"
5691
+ };
5692
+ } catch (error) {
5693
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
5694
+ this.customLogger.error(`[ERROR] Configuration failed: ${errorMessage}`);
5695
+ throw new Error(`Failed to configure Adobe Commerce I/O Events: ${errorMessage}`);
5696
+ }
5697
+ }
5698
+ /**
5699
+ * Filters commerce events configuration based on existing subscriptions and supported events
4847
5700
  *
4848
- * @param key - Data received from the event
4849
- * @returns The function that generates the key
5701
+ * @param commerceEventsConfig - Array of commerce event configurations
5702
+ * @param existingSubscriptions - Array of existing event subscriptions
5703
+ * @param providerId - Provider ID to match against
5704
+ * @param supportedEvents - Array of supported events from Adobe Commerce
5705
+ * @returns Object containing alreadySubscribed, needsSubscription, and unsupported arrays
5706
+ * @private
4850
5707
  */
4851
- static fnInfiniteLoopKey(key) {
4852
- return () => {
4853
- return key;
5708
+ filterEventsBySubscriptionStatus(commerceEventsConfig, existingSubscriptions, providerId, supportedEvents = []) {
5709
+ const alreadySubscribed = [];
5710
+ const needsSubscription = [];
5711
+ const unsupported = [];
5712
+ const supportedEventNames = new Set(supportedEvents.map((event) => event.name));
5713
+ commerceEventsConfig.forEach((commerceEvent) => {
5714
+ const eventName = commerceEvent.event?.name;
5715
+ if (!eventName) {
5716
+ this.customLogger.error(
5717
+ "Commerce event configuration missing event name, skipping:",
5718
+ commerceEvent
5719
+ );
5720
+ return;
5721
+ }
5722
+ if (supportedEvents.length > 0 && !supportedEventNames.has(eventName)) {
5723
+ unsupported.push(commerceEvent);
5724
+ return;
5725
+ }
5726
+ const isAlreadySubscribed = existingSubscriptions.some(
5727
+ (subscription) => subscription.name === eventName && subscription.provider_id === providerId
5728
+ );
5729
+ if (isAlreadySubscribed) {
5730
+ alreadySubscribed.push(commerceEvent);
5731
+ } else {
5732
+ needsSubscription.push(commerceEvent);
5733
+ }
5734
+ });
5735
+ return {
5736
+ alreadySubscribed,
5737
+ needsSubscription,
5738
+ unsupported
4854
5739
  };
4855
5740
  }
4856
5741
  /**
4857
- * This function generates a fingerprint for the data
5742
+ * Prepares event payload by transforming event names and adding provider information
4858
5743
  *
4859
- * @param data - The data to generate the fingerprint
4860
- * @returns The fingerprint
5744
+ * @param eventSpec - Event specification object containing event details
5745
+ * @param providerId - Provider ID to assign to the event
5746
+ * @returns Modified event specification with updated event properties
5747
+ * @private
4861
5748
  */
4862
- static fingerPrint(data) {
4863
- const hash = crypto2.createHash(_InfiniteLoopBreaker.FINGERPRINT_ALGORITHM);
4864
- hash.update(JSON.stringify(data));
4865
- return hash.digest(_InfiniteLoopBreaker.FINGERPRINT_ENCODING);
5749
+ prepareEventPayload(eventSpec, providerId) {
5750
+ if (!eventSpec || !eventSpec.event) {
5751
+ throw new Error("Invalid event specification: event object is required");
5752
+ }
5753
+ if (!eventSpec.event.name) {
5754
+ throw new Error("Invalid event specification: event name is required");
5755
+ }
5756
+ if (!providerId || typeof providerId !== "string") {
5757
+ throw new Error("Valid provider ID is required");
5758
+ }
5759
+ const modifiedEventSpec = JSON.parse(JSON.stringify(eventSpec));
5760
+ modifiedEventSpec.event.parent = modifiedEventSpec.event.name;
5761
+ modifiedEventSpec.event.provider_id = providerId;
5762
+ modifiedEventSpec.event.destination = "default";
5763
+ modifiedEventSpec.event.provider_id = providerId;
5764
+ modifiedEventSpec.event.priority = true;
5765
+ modifiedEventSpec.event.hipaa_audit_required = false;
5766
+ return modifiedEventSpec;
4866
5767
  }
4867
- };
4868
- __name(_InfiniteLoopBreaker, "InfiniteLoopBreaker");
4869
- /** The algorithm used to generate the fingerprint */
4870
- _InfiniteLoopBreaker.FINGERPRINT_ALGORITHM = "sha256";
4871
- /** The encoding used to generate the fingerprint */
4872
- _InfiniteLoopBreaker.FINGERPRINT_ENCODING = "hex";
4873
- /** The default time to live for the fingerprint in the lib state */
4874
- _InfiniteLoopBreaker.DEFAULT_INFINITE_LOOP_BREAKER_TTL = 60;
4875
- var InfiniteLoopBreaker = _InfiniteLoopBreaker;
4876
- var infinite_loop_breaker_default = InfiniteLoopBreaker;
4877
-
4878
- // src/commerce/adobe-auth/index.ts
4879
- import { context, getToken } from "@adobe/aio-lib-ims";
4880
- var _AdobeAuth = class _AdobeAuth {
4881
5768
  /**
4882
- * Retrieves an authentication token from Adobe IMS
4883
- *
4884
- * @param clientId - The client ID for the Adobe IMS integration
4885
- * @param clientSecret - The client secret for the Adobe IMS integration
4886
- * @param technicalAccountId - The technical account ID for the Adobe IMS integration
4887
- * @param technicalAccountEmail - The technical account email for the Adobe IMS integration
4888
- * @param imsOrgId - The IMS organization ID
4889
- * @param scopes - Array of permission scopes to request for the token
4890
- * @param currentContext - The context name for storing the configuration (defaults to 'onboarding-config')
4891
- * @returns Promise<string> - A promise that resolves to the authentication token
5769
+ * Logs a comprehensive summary of event subscription results
4892
5770
  *
4893
- * @example
4894
- * const token = await AdobeAuth.getToken(
4895
- * 'your-client-id',
4896
- * 'your-client-secret',
4897
- * 'your-technical-account-id',
4898
- * 'your-technical-account-email',
4899
- * 'your-ims-org-id',
4900
- * ['AdobeID', 'openid', 'adobeio_api']
4901
- * );
5771
+ * @param result - Event subscription processing results
5772
+ * @param providerLabel - Provider label for display
5773
+ * @private
4902
5774
  */
4903
- static async getToken(clientId, clientSecret, technicalAccountId, technicalAccountEmail, imsOrgId, scopes, currentContext = "onboarding-config") {
4904
- const config = {
4905
- client_id: clientId,
4906
- client_secrets: [clientSecret],
4907
- technical_account_id: technicalAccountId,
4908
- technical_account_email: technicalAccountEmail,
4909
- ims_org_id: imsOrgId,
4910
- scopes
4911
- };
4912
- await context.setCurrent(currentContext);
4913
- await context.set(currentContext, config);
4914
- return await getToken();
5775
+ logEventSubscriptionSummary(result, providerLabel) {
5776
+ if (result.alreadySubscribed.length > 0) {
5777
+ result.alreadySubscribed.forEach((eventName) => {
5778
+ this.customLogger.info(`[SKIP] Already subscribed: ${eventName}`);
5779
+ });
5780
+ }
5781
+ if (result.unsupported.length > 0) {
5782
+ result.unsupported.forEach((eventName) => {
5783
+ this.customLogger.error(`[ERROR] Unsupported event: ${eventName}`);
5784
+ });
5785
+ }
5786
+ this.customLogger.info("");
5787
+ this.customLogger.info("=".repeat(60));
5788
+ this.customLogger.info(`\u{1F4CA} COMMERCE EVENTS CONFIGURATION SUMMARY - ${providerLabel}`);
5789
+ this.customLogger.info("=".repeat(60));
5790
+ this.customLogger.info("");
5791
+ const totalProcessed = result.successfulSubscriptions.length + result.failedSubscriptions.length + result.alreadySubscribed.length + result.unsupported.length;
5792
+ this.customLogger.info(
5793
+ `\u{1F4C8} OVERALL: ${totalProcessed} processed | ${result.successfulSubscriptions.length} created | ${result.alreadySubscribed.length} existing | ${result.unsupported.length} unsupported | ${result.failedSubscriptions.length} failed`
5794
+ );
5795
+ this.customLogger.info("");
5796
+ if (result.successfulSubscriptions.length > 0) {
5797
+ this.customLogger.info(
5798
+ `\u2705 SUCCESSFUL SUBSCRIPTIONS (${result.successfulSubscriptions.length}):`
5799
+ );
5800
+ result.successfulSubscriptions.forEach((eventName) => {
5801
+ this.customLogger.info(` \u2713 ${eventName}`);
5802
+ });
5803
+ this.customLogger.info("");
5804
+ }
5805
+ if (result.alreadySubscribed.length > 0) {
5806
+ this.customLogger.info(`\u2139\uFE0F ALREADY SUBSCRIBED (${result.alreadySubscribed.length}):`);
5807
+ result.alreadySubscribed.forEach((eventName) => {
5808
+ this.customLogger.info(` \u2192 ${eventName}`);
5809
+ });
5810
+ this.customLogger.info("");
5811
+ }
5812
+ if (result.unsupported.length > 0) {
5813
+ this.customLogger.info(`\u26A0\uFE0F UNSUPPORTED EVENTS (${result.unsupported.length}):`);
5814
+ result.unsupported.forEach((eventName) => {
5815
+ this.customLogger.info(` \u26A0 ${eventName}`);
5816
+ });
5817
+ this.customLogger.info("");
5818
+ }
5819
+ if (result.failedSubscriptions.length > 0) {
5820
+ this.customLogger.info(`\u274C FAILED SUBSCRIPTIONS (${result.failedSubscriptions.length}):`);
5821
+ result.failedSubscriptions.forEach((eventName) => {
5822
+ this.customLogger.info(` \u2717 ${eventName}`);
5823
+ });
5824
+ this.customLogger.info("");
5825
+ }
5826
+ this.customLogger.info("=".repeat(60));
4915
5827
  }
4916
5828
  };
4917
- __name(_AdobeAuth, "AdobeAuth");
4918
- var AdobeAuth = _AdobeAuth;
4919
- var adobe_auth_default = AdobeAuth;
5829
+ __name(_OnboardCommerce, "OnboardCommerce");
5830
+ var OnboardCommerce = _OnboardCommerce;
5831
+ var onboard_commerce_default = OnboardCommerce;
4920
5832
 
4921
5833
  // src/commerce/adobe-commerce-client/index.ts
4922
5834
  import got from "got";
@@ -5058,7 +5970,7 @@ var AdobeCommerceClient = _AdobeCommerceClient;
5058
5970
  var adobe_commerce_client_default = AdobeCommerceClient;
5059
5971
 
5060
5972
  // src/commerce/adobe-commerce-client/basic-auth-connection/generate-basic-auth-token/index.ts
5061
- import { State as State2 } from "@adobe/aio-sdk";
5973
+ import { State as State3 } from "@adobe/aio-sdk";
5062
5974
  var _GenerateBasicAuthToken = class _GenerateBasicAuthToken {
5063
5975
  /**
5064
5976
  * @param baseUrl
@@ -5208,7 +6120,7 @@ var _GenerateBasicAuthToken = class _GenerateBasicAuthToken {
5208
6120
  async getState() {
5209
6121
  if (this.state === void 0) {
5210
6122
  try {
5211
- this.state = await State2.init();
6123
+ this.state = await State3.init();
5212
6124
  } catch (error) {
5213
6125
  this.logger.debug("State API initialization failed, running without caching");
5214
6126
  this.state = null;
@@ -5317,160 +6229,6 @@ __name(_Oauth1aConnection, "Oauth1aConnection");
5317
6229
  var Oauth1aConnection = _Oauth1aConnection;
5318
6230
  var oauth1a_connection_default = Oauth1aConnection;
5319
6231
 
5320
- // src/commerce/adobe-commerce-client/ims-connection/generate-ims-token/index.ts
5321
- import { State as State3 } from "@adobe/aio-sdk";
5322
- var _GenerateImsToken = class _GenerateImsToken {
5323
- /**
5324
- * @param clientId
5325
- * @param clientSecret
5326
- * @param technicalAccountId
5327
- * @param technicalAccountEmail
5328
- * @param imsOrgId
5329
- * @param scopes
5330
- * @param logger
5331
- */
5332
- constructor(clientId, clientSecret, technicalAccountId, technicalAccountEmail, imsOrgId, scopes, logger = null) {
5333
- this.key = "adobe_ims_auth_token";
5334
- this.tokenContext = "adobe-commerce-client";
5335
- this.clientId = clientId;
5336
- this.clientSecret = clientSecret;
5337
- this.technicalAccountId = technicalAccountId;
5338
- this.technicalAccountEmail = technicalAccountEmail;
5339
- this.imsOrgId = imsOrgId;
5340
- this.scopes = scopes;
5341
- this.customLogger = new custom_logger_default(logger);
5342
- }
5343
- /**
5344
- * @return string | null
5345
- */
5346
- async execute() {
5347
- try {
5348
- this.customLogger.info("Starting IMS token generation/retrieval process");
5349
- const currentValue = await this.getValue();
5350
- if (currentValue !== null) {
5351
- this.customLogger.info("Found cached IMS token, returning cached value");
5352
- return currentValue;
5353
- }
5354
- this.customLogger.info("No cached token found, generating new IMS token");
5355
- let result = {
5356
- token: null,
5357
- expire_in: 86399
5358
- // Default fallback, will be overridden by actual token expiry
5359
- };
5360
- const response = await this.getImsToken();
5361
- if (response !== null) {
5362
- result = response;
5363
- }
5364
- if (result.token !== null) {
5365
- this.customLogger.info(`Generated new IMS token, caching for ${result.expire_in} seconds`);
5366
- await this.setValue(result);
5367
- }
5368
- return result.token;
5369
- } catch (error) {
5370
- this.customLogger.error(`Failed to execute IMS token generation: ${error.message}`);
5371
- return null;
5372
- }
5373
- }
5374
- /**
5375
- * @return ImsTokenResult | null
5376
- */
5377
- async getImsToken() {
5378
- try {
5379
- this.customLogger.debug(`Calling AdobeAuth.getToken with context: ${this.tokenContext}`);
5380
- const token = await adobe_auth_default.getToken(
5381
- this.clientId,
5382
- this.clientSecret,
5383
- this.technicalAccountId,
5384
- this.technicalAccountEmail,
5385
- this.imsOrgId,
5386
- this.scopes,
5387
- this.tokenContext
5388
- );
5389
- if (token !== null && token !== void 0) {
5390
- this.customLogger.debug("Received token from AdobeAuth, parsing with BearerToken.info");
5391
- const tokenInfo = bearer_token_default.info(token);
5392
- if (!tokenInfo.isValid) {
5393
- this.customLogger.error("Received invalid or expired token from IMS");
5394
- return null;
5395
- }
5396
- const expireInSeconds = tokenInfo.timeUntilExpiry ? Math.floor(tokenInfo.timeUntilExpiry / 1e3) : 86399;
5397
- this.customLogger.debug(`Token expires in ${expireInSeconds} seconds`);
5398
- return {
5399
- token,
5400
- expire_in: expireInSeconds
5401
- };
5402
- }
5403
- this.customLogger.error("Received null or undefined token from IMS");
5404
- return null;
5405
- } catch (error) {
5406
- this.customLogger.error(`Failed to get IMS token: ${error.message}`);
5407
- return null;
5408
- }
5409
- }
5410
- /**
5411
- * @param result
5412
- * @return boolean
5413
- */
5414
- async setValue(result) {
5415
- try {
5416
- const state = await this.getState();
5417
- if (state === null) {
5418
- this.customLogger.info("State API not available, skipping token caching");
5419
- return true;
5420
- }
5421
- const ttlWithBuffer = Math.max(result.expire_in - 300, 60);
5422
- this.customLogger.debug(
5423
- `Caching IMS token with TTL: ${ttlWithBuffer} seconds (original: ${result.expire_in})`
5424
- );
5425
- await state.put(this.key, result.token, { ttl: ttlWithBuffer });
5426
- return true;
5427
- } catch (error) {
5428
- this.customLogger.error(`Failed to cache IMS token: ${error.message}`);
5429
- return true;
5430
- }
5431
- }
5432
- /**
5433
- * @return string | null
5434
- */
5435
- async getValue() {
5436
- try {
5437
- this.customLogger.debug("Checking for cached IMS token");
5438
- const state = await this.getState();
5439
- if (state === null) {
5440
- this.customLogger.debug("State API not available, cannot retrieve cached token");
5441
- return null;
5442
- }
5443
- const value = await state.get(this.key);
5444
- if (value !== void 0 && value.value) {
5445
- this.customLogger.debug("Found cached IMS token");
5446
- return value.value;
5447
- }
5448
- this.customLogger.debug("No cached IMS token found");
5449
- } catch (error) {
5450
- this.customLogger.error(`Failed to retrieve cached IMS token: ${error.message}`);
5451
- }
5452
- return null;
5453
- }
5454
- /**
5455
- * @return any
5456
- */
5457
- async getState() {
5458
- if (this.state === void 0) {
5459
- try {
5460
- this.customLogger.debug("Initializing State API for token caching");
5461
- this.state = await State3.init();
5462
- } catch (error) {
5463
- this.customLogger.error(`Failed to initialize State API: ${error.message}`);
5464
- this.state = null;
5465
- }
5466
- }
5467
- return this.state;
5468
- }
5469
- };
5470
- __name(_GenerateImsToken, "GenerateImsToken");
5471
- var GenerateImsToken = _GenerateImsToken;
5472
- var generate_ims_token_default = GenerateImsToken;
5473
-
5474
6232
  // src/commerce/adobe-commerce-client/ims-connection/index.ts
5475
6233
  var _ImsConnection = class _ImsConnection {
5476
6234
  /**
@@ -5496,14 +6254,18 @@ var _ImsConnection = class _ImsConnection {
5496
6254
  */
5497
6255
  async extend(commerceGot) {
5498
6256
  this.customLogger.info("Using Commerce client with IMS authentication");
5499
- const tokenGenerator = new generate_ims_token_default(
6257
+ const tokenGenerator = new ims_token_default(
5500
6258
  this.clientId,
5501
6259
  this.clientSecret,
5502
6260
  this.technicalAccountId,
5503
6261
  this.technicalAccountEmail,
5504
6262
  this.imsOrgId,
5505
6263
  this.scopes,
5506
- this.customLogger.getLogger()
6264
+ this.customLogger.getLogger(),
6265
+ "adobe_commerce_ims_token",
6266
+ // Use specific cache key for commerce client
6267
+ "adobe-commerce-client"
6268
+ // Use adobe-commerce-client context for backward compatibility
5507
6269
  );
5508
6270
  const token = await tokenGenerator.execute();
5509
6271
  if (token === null) {
@@ -6081,10 +6843,13 @@ export {
6081
6843
  HttpStatus,
6082
6844
  IOEventsApiError,
6083
6845
  ims_connection_default as ImsConnection,
6846
+ ims_token_default as ImsToken,
6084
6847
  infinite_loop_breaker_default as InfiniteLoopBreaker,
6085
6848
  IoEventsGlobals,
6086
6849
  oauth1a_connection_default as Oauth1aConnection,
6850
+ onboard_commerce_default as OnboardCommerce,
6087
6851
  onboard_events_default as OnboardEvents,
6852
+ onboard_events_default as OnboardIOEvents,
6088
6853
  openwhisk_default as Openwhisk,
6089
6854
  openwhisk_action_default as OpenwhiskAction,
6090
6855
  parameters_default as Parameters,
@@ -6094,6 +6859,7 @@ export {
6094
6859
  rest_client_default as RestClient,
6095
6860
  runtime_action_default as RuntimeAction,
6096
6861
  response_default as RuntimeActionResponse,
6862
+ RuntimeApiGatewayService,
6097
6863
  shipping_carrier_default as ShippingCarrier,
6098
6864
  method_default as ShippingCarrierMethod,
6099
6865
  response_default3 as ShippingCarrierResponse,