@adobe-commerce/aio-toolkit 1.0.5 → 1.0.7

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,97 +5268,594 @@ 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
  });
4833
5275
  }
4834
5276
  /**
4835
- * This function generates a function to generate fingerprint for the data to be used in infinite loop detection based on params.
5277
+ * This function generates a function to generate fingerprint for the data to be used in infinite loop detection based on params.
5278
+ *
5279
+ * @param obj - Data received from the event
5280
+ * @returns The function that generates the fingerprint
5281
+ */
5282
+ static fnFingerprint(obj) {
5283
+ return () => {
5284
+ return obj;
5285
+ };
5286
+ }
5287
+ /**
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
+ * @param isPaaS - Flag to indicate if the Commerce instance is PaaS (defaults to false)
5555
+ * @throws {Error} When required parameters are missing or invalid
5556
+ * @example
5557
+ * ```typescript
5558
+ * const adobeCommerceClient = new AdobeCommerceClient(...);
5559
+ * const onboardCommerce = new OnboardCommerce(
5560
+ * adobeCommerceClient,
5561
+ * 'merchant-id-123',
5562
+ * 'environment-id-456',
5563
+ * logger
5564
+ * );
5565
+ * ```
5566
+ */
5567
+ constructor(adobeCommerceClient, merchantId, environmentId, logger = null, isPaaS = false) {
5568
+ if (!adobeCommerceClient) {
5569
+ throw new Error("Adobe Commerce client is required");
5570
+ }
5571
+ if (!merchantId || typeof merchantId !== "string") {
5572
+ throw new Error("Valid merchant ID is required");
5573
+ }
5574
+ if (!environmentId || typeof environmentId !== "string") {
5575
+ throw new Error("Valid environment ID is required");
5576
+ }
5577
+ this.adobeCommerceClient = adobeCommerceClient;
5578
+ this.merchantId = merchantId;
5579
+ this.environmentId = environmentId;
5580
+ this.isPaaS = isPaaS;
5581
+ this.customLogger = new custom_logger_default(logger);
5582
+ this.configureProvider = new configure_provider_default(
5583
+ adobeCommerceClient,
5584
+ merchantId,
5585
+ environmentId,
5586
+ logger
5587
+ );
5588
+ this.eventSubscriptionService = new EventSubscriptionService(adobeCommerceClient);
5589
+ this.eventService = new EventService(adobeCommerceClient);
5590
+ }
5591
+ /**
5592
+ * Process Adobe Commerce I/O Events Configuration
5593
+ *
5594
+ * This method automates the configuration of Adobe Commerce I/O Events by setting up
5595
+ * the provider, workspace, and commerce-specific event configurations.
5596
+ *
5597
+ * @param provider - Provider configuration for Adobe I/O Events
5598
+ * @param workspaceConfig - Workspace configuration settings
5599
+ * @param commerceEventsConfig - Array of commerce event configurations (optional, defaults to empty array)
5600
+ * @returns A promise that resolves with the configuration result
5601
+ * @throws {Error} If configuration fails
5602
+ * @example
5603
+ * ```typescript
5604
+ * const result = await onboardCommerce.process(
5605
+ * providerConfig,
5606
+ * workspaceConfig,
5607
+ * commerceEventsConfig
5608
+ * );
5609
+ * ```
5610
+ */
5611
+ async process(provider, workspaceConfig, commerceEventsConfig = []) {
5612
+ this.customLogger.info(
5613
+ `[START] Configuring Adobe Commerce I/O Events
5614
+ Provider: ${provider.label} (${provider.id})
5615
+ Workspace: ${workspaceConfig.project.name}
5616
+ Events to process: ${commerceEventsConfig.length}`
5617
+ );
5618
+ try {
5619
+ const providerResult = await this.configureProvider.execute(provider, workspaceConfig);
5620
+ if (!providerResult.success) {
5621
+ return providerResult;
5622
+ }
5623
+ if (commerceEventsConfig && commerceEventsConfig.length > 0) {
5624
+ this.customLogger.debug("[FETCH] Fetching current event subscriptions...");
5625
+ const eventSubscriptionsResult = await this.eventSubscriptionService.list();
5626
+ let existingSubscriptions = [];
5627
+ if (!eventSubscriptionsResult.success) {
5628
+ this.customLogger.error(
5629
+ `[ERROR] Failed to fetch event subscriptions: ${eventSubscriptionsResult.error}`
5630
+ );
5631
+ } else {
5632
+ existingSubscriptions = Array.isArray(eventSubscriptionsResult.data) ? eventSubscriptionsResult.data : [];
5633
+ this.customLogger.debug(
5634
+ `[FETCH] Retrieved ${existingSubscriptions.length} existing event subscription(s)`
5635
+ );
5636
+ }
5637
+ let supportedEvents = [];
5638
+ if (!this.isPaaS) {
5639
+ this.customLogger.debug("[FETCH] Fetching supported events list...");
5640
+ const supportedEventsResult = await this.eventService.supportedList();
5641
+ if (!supportedEventsResult.success) {
5642
+ this.customLogger.error(
5643
+ `[ERROR] Failed to fetch supported events: ${supportedEventsResult.error}`
5644
+ );
5645
+ } else {
5646
+ supportedEvents = Array.isArray(supportedEventsResult.data) ? supportedEventsResult.data : [];
5647
+ this.customLogger.debug(
5648
+ `[FETCH] Retrieved ${supportedEvents.length} supported event(s)`
5649
+ );
5650
+ }
5651
+ } else {
5652
+ this.customLogger.debug("[SKIP] Skipping supported events validation for PaaS instance");
5653
+ }
5654
+ const { alreadySubscribed, needsSubscription, unsupported } = this.filterEventsBySubscriptionStatus(
5655
+ commerceEventsConfig,
5656
+ existingSubscriptions,
5657
+ provider.id,
5658
+ supportedEvents
5659
+ );
5660
+ const result = {
5661
+ successfulSubscriptions: [],
5662
+ failedSubscriptions: [],
5663
+ alreadySubscribed: alreadySubscribed.map((event) => event.event.name),
5664
+ unsupported: unsupported.map((event) => event.event?.name || "Unknown"),
5665
+ skipped: alreadySubscribed.length + unsupported.length
5666
+ };
5667
+ for (const commerceEvent of needsSubscription) {
5668
+ try {
5669
+ const preparedEvent = this.prepareEventPayload(commerceEvent, provider.id);
5670
+ this.customLogger.debug(
5671
+ `[DEBUG] Subscribing to event with payload:
5672
+ ${JSON.stringify(preparedEvent.event, null, 2)}`
5673
+ );
5674
+ const eventSubscribeResult = await this.eventSubscriptionService.create(
5675
+ preparedEvent.event
5676
+ );
5677
+ if (!eventSubscribeResult.success) {
5678
+ result.failedSubscriptions.push(commerceEvent.event.name);
5679
+ this.customLogger.error(
5680
+ `[ERROR] Failed to subscribe to event: ${commerceEvent.event.name} - ${eventSubscribeResult.error}`
5681
+ );
5682
+ continue;
5683
+ }
5684
+ this.customLogger.info(`[CREATE] Successfully subscribed: ${commerceEvent.event.name}`);
5685
+ result.successfulSubscriptions.push(commerceEvent.event.name);
5686
+ } catch (error) {
5687
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
5688
+ result.failedSubscriptions.push(commerceEvent.event?.name || "Unknown");
5689
+ this.customLogger.error(
5690
+ `[ERROR] Error processing event subscription for ${commerceEvent.event?.name || "Unknown"}: ${errorMessage}`
5691
+ );
5692
+ }
5693
+ }
5694
+ this.logEventSubscriptionSummary(result, provider.label);
5695
+ if (this.isPaaS) {
5696
+ this.customLogger.info("[IMPORTANT] \u26A0\uFE0F Post-Subscription Steps for PaaS:");
5697
+ this.customLogger.info(
5698
+ "[IMPORTANT] 1. Run: bin/magento events:generate:module to generate module after successful event subscription"
5699
+ );
5700
+ this.customLogger.info(
5701
+ "[IMPORTANT] 2. Run: bin/magento setup:upgrade && bin/magento setup:di:compile && bin/magento cache:flush to install the generated module"
5702
+ );
5703
+ }
5704
+ }
5705
+ return {
5706
+ success: true,
5707
+ message: "Configuration completed successfully"
5708
+ };
5709
+ } catch (error) {
5710
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
5711
+ this.customLogger.error(`[ERROR] Configuration failed: ${errorMessage}`);
5712
+ throw new Error(`Failed to configure Adobe Commerce I/O Events: ${errorMessage}`);
5713
+ }
5714
+ }
5715
+ /**
5716
+ * Filters commerce events configuration based on existing subscriptions and supported events
4836
5717
  *
4837
- * @param obj - Data received from the event
4838
- * @returns The function that generates the fingerprint
5718
+ * @param commerceEventsConfig - Array of commerce event configurations
5719
+ * @param existingSubscriptions - Array of existing event subscriptions
5720
+ * @param providerId - Provider ID to match against
5721
+ * @param supportedEvents - Array of supported events from Adobe Commerce
5722
+ * @returns Object containing alreadySubscribed, needsSubscription, and unsupported arrays
5723
+ * @private
4839
5724
  */
4840
- static fnFingerprint(obj) {
4841
- return () => {
4842
- return obj;
5725
+ filterEventsBySubscriptionStatus(commerceEventsConfig, existingSubscriptions, providerId, supportedEvents = []) {
5726
+ const alreadySubscribed = [];
5727
+ const needsSubscription = [];
5728
+ const unsupported = [];
5729
+ const supportedEventNames = new Set(supportedEvents.map((event) => event.name));
5730
+ commerceEventsConfig.forEach((commerceEvent) => {
5731
+ const eventName = commerceEvent.event?.name;
5732
+ if (!eventName) {
5733
+ this.customLogger.error(
5734
+ "Commerce event configuration missing event name, skipping:",
5735
+ commerceEvent
5736
+ );
5737
+ return;
5738
+ }
5739
+ if (supportedEvents.length > 0 && !supportedEventNames.has(eventName)) {
5740
+ unsupported.push(commerceEvent);
5741
+ return;
5742
+ }
5743
+ const isAlreadySubscribed = existingSubscriptions.some(
5744
+ (subscription) => subscription.name === eventName && subscription.provider_id === providerId
5745
+ );
5746
+ if (isAlreadySubscribed) {
5747
+ alreadySubscribed.push(commerceEvent);
5748
+ } else {
5749
+ needsSubscription.push(commerceEvent);
5750
+ }
5751
+ });
5752
+ return {
5753
+ alreadySubscribed,
5754
+ needsSubscription,
5755
+ unsupported
4843
5756
  };
4844
5757
  }
4845
5758
  /**
4846
- * This function generates a function to create a key for the infinite loop detection based on params.
5759
+ * Prepares event payload by transforming event names and adding provider information
4847
5760
  *
4848
- * @param key - Data received from the event
4849
- * @returns The function that generates the key
4850
- */
4851
- static fnInfiniteLoopKey(key) {
4852
- return () => {
4853
- return key;
4854
- };
4855
- }
4856
- /**
4857
- * This function generates a fingerprint for the data
5761
+ * For PaaS instances, the parent field is omitted to support native events (observer.*, plugin.*)
5762
+ * which would be rejected by Adobe Commerce as invalid aliases if parent is set to the same name.
5763
+ * For non-PaaS instances, the parent field is set to the event name as usual.
4858
5764
  *
4859
- * @param data - The data to generate the fingerprint
4860
- * @returns The fingerprint
5765
+ * @param eventSpec - Event specification object containing event details
5766
+ * @param providerId - Provider ID to assign to the event
5767
+ * @returns Modified event specification with updated event properties
5768
+ * @private
4861
5769
  */
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);
5770
+ prepareEventPayload(eventSpec, providerId) {
5771
+ if (!eventSpec || !eventSpec.event) {
5772
+ throw new Error("Invalid event specification: event object is required");
5773
+ }
5774
+ if (!eventSpec.event.name) {
5775
+ throw new Error("Invalid event specification: event name is required");
5776
+ }
5777
+ if (!providerId || typeof providerId !== "string") {
5778
+ throw new Error("Valid provider ID is required");
5779
+ }
5780
+ const modifiedEventSpec = JSON.parse(JSON.stringify(eventSpec));
5781
+ const eventName = modifiedEventSpec.event.name;
5782
+ if (!this.isPaaS) {
5783
+ modifiedEventSpec.event.parent = eventName;
5784
+ }
5785
+ modifiedEventSpec.event.provider_id = providerId;
5786
+ modifiedEventSpec.event.destination = "default";
5787
+ modifiedEventSpec.event.provider_id = providerId;
5788
+ modifiedEventSpec.event.priority = true;
5789
+ modifiedEventSpec.event.hipaa_audit_required = false;
5790
+ if (!modifiedEventSpec.event.rules) {
5791
+ modifiedEventSpec.event.rules = [];
5792
+ }
5793
+ return modifiedEventSpec;
4866
5794
  }
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
5795
  /**
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
5796
+ * Logs a comprehensive summary of event subscription results
4892
5797
  *
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
- * );
5798
+ * @param result - Event subscription processing results
5799
+ * @param providerLabel - Provider label for display
5800
+ * @private
4902
5801
  */
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();
5802
+ logEventSubscriptionSummary(result, providerLabel) {
5803
+ if (result.alreadySubscribed.length > 0) {
5804
+ result.alreadySubscribed.forEach((eventName) => {
5805
+ this.customLogger.info(`[SKIP] Already subscribed: ${eventName}`);
5806
+ });
5807
+ }
5808
+ if (result.unsupported.length > 0) {
5809
+ result.unsupported.forEach((eventName) => {
5810
+ this.customLogger.error(`[ERROR] Unsupported event: ${eventName}`);
5811
+ });
5812
+ }
5813
+ this.customLogger.info("");
5814
+ this.customLogger.info("=".repeat(60));
5815
+ this.customLogger.info(`\u{1F4CA} COMMERCE EVENTS CONFIGURATION SUMMARY - ${providerLabel}`);
5816
+ this.customLogger.info("=".repeat(60));
5817
+ this.customLogger.info("");
5818
+ const totalProcessed = result.successfulSubscriptions.length + result.failedSubscriptions.length + result.alreadySubscribed.length + result.unsupported.length;
5819
+ this.customLogger.info(
5820
+ `\u{1F4C8} OVERALL: ${totalProcessed} processed | ${result.successfulSubscriptions.length} created | ${result.alreadySubscribed.length} existing | ${result.unsupported.length} unsupported | ${result.failedSubscriptions.length} failed`
5821
+ );
5822
+ this.customLogger.info("");
5823
+ if (result.successfulSubscriptions.length > 0) {
5824
+ this.customLogger.info(
5825
+ `\u2705 SUCCESSFUL SUBSCRIPTIONS (${result.successfulSubscriptions.length}):`
5826
+ );
5827
+ result.successfulSubscriptions.forEach((eventName) => {
5828
+ this.customLogger.info(` \u2713 ${eventName}`);
5829
+ });
5830
+ this.customLogger.info("");
5831
+ }
5832
+ if (result.alreadySubscribed.length > 0) {
5833
+ this.customLogger.info(`\u2139\uFE0F ALREADY SUBSCRIBED (${result.alreadySubscribed.length}):`);
5834
+ result.alreadySubscribed.forEach((eventName) => {
5835
+ this.customLogger.info(` \u2192 ${eventName}`);
5836
+ });
5837
+ this.customLogger.info("");
5838
+ }
5839
+ if (result.unsupported.length > 0) {
5840
+ this.customLogger.info(`\u26A0\uFE0F UNSUPPORTED EVENTS (${result.unsupported.length}):`);
5841
+ result.unsupported.forEach((eventName) => {
5842
+ this.customLogger.info(` \u26A0 ${eventName}`);
5843
+ });
5844
+ this.customLogger.info("");
5845
+ }
5846
+ if (result.failedSubscriptions.length > 0) {
5847
+ this.customLogger.info(`\u274C FAILED SUBSCRIPTIONS (${result.failedSubscriptions.length}):`);
5848
+ result.failedSubscriptions.forEach((eventName) => {
5849
+ this.customLogger.info(` \u2717 ${eventName}`);
5850
+ });
5851
+ this.customLogger.info("");
5852
+ }
5853
+ this.customLogger.info("=".repeat(60));
4915
5854
  }
4916
5855
  };
4917
- __name(_AdobeAuth, "AdobeAuth");
4918
- var AdobeAuth = _AdobeAuth;
4919
- var adobe_auth_default = AdobeAuth;
5856
+ __name(_OnboardCommerce, "OnboardCommerce");
5857
+ var OnboardCommerce = _OnboardCommerce;
5858
+ var onboard_commerce_default = OnboardCommerce;
4920
5859
 
4921
5860
  // src/commerce/adobe-commerce-client/index.ts
4922
5861
  import got from "got";
@@ -5058,7 +5997,7 @@ var AdobeCommerceClient = _AdobeCommerceClient;
5058
5997
  var adobe_commerce_client_default = AdobeCommerceClient;
5059
5998
 
5060
5999
  // src/commerce/adobe-commerce-client/basic-auth-connection/generate-basic-auth-token/index.ts
5061
- import { State as State2 } from "@adobe/aio-sdk";
6000
+ import { State as State3 } from "@adobe/aio-sdk";
5062
6001
  var _GenerateBasicAuthToken = class _GenerateBasicAuthToken {
5063
6002
  /**
5064
6003
  * @param baseUrl
@@ -5208,7 +6147,7 @@ var _GenerateBasicAuthToken = class _GenerateBasicAuthToken {
5208
6147
  async getState() {
5209
6148
  if (this.state === void 0) {
5210
6149
  try {
5211
- this.state = await State2.init();
6150
+ this.state = await State3.init();
5212
6151
  } catch (error) {
5213
6152
  this.logger.debug("State API initialization failed, running without caching");
5214
6153
  this.state = null;
@@ -5317,160 +6256,6 @@ __name(_Oauth1aConnection, "Oauth1aConnection");
5317
6256
  var Oauth1aConnection = _Oauth1aConnection;
5318
6257
  var oauth1a_connection_default = Oauth1aConnection;
5319
6258
 
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
6259
  // src/commerce/adobe-commerce-client/ims-connection/index.ts
5475
6260
  var _ImsConnection = class _ImsConnection {
5476
6261
  /**
@@ -5496,14 +6281,18 @@ var _ImsConnection = class _ImsConnection {
5496
6281
  */
5497
6282
  async extend(commerceGot) {
5498
6283
  this.customLogger.info("Using Commerce client with IMS authentication");
5499
- const tokenGenerator = new generate_ims_token_default(
6284
+ const tokenGenerator = new ims_token_default(
5500
6285
  this.clientId,
5501
6286
  this.clientSecret,
5502
6287
  this.technicalAccountId,
5503
6288
  this.technicalAccountEmail,
5504
6289
  this.imsOrgId,
5505
6290
  this.scopes,
5506
- this.customLogger.getLogger()
6291
+ this.customLogger.getLogger(),
6292
+ "adobe_commerce_ims_token",
6293
+ // Use specific cache key for commerce client
6294
+ "adobe-commerce-client"
6295
+ // Use adobe-commerce-client context for backward compatibility
5507
6296
  );
5508
6297
  const token = await tokenGenerator.execute();
5509
6298
  if (token === null) {
@@ -6081,10 +6870,13 @@ export {
6081
6870
  HttpStatus,
6082
6871
  IOEventsApiError,
6083
6872
  ims_connection_default as ImsConnection,
6873
+ ims_token_default as ImsToken,
6084
6874
  infinite_loop_breaker_default as InfiniteLoopBreaker,
6085
6875
  IoEventsGlobals,
6086
6876
  oauth1a_connection_default as Oauth1aConnection,
6877
+ onboard_commerce_default as OnboardCommerce,
6087
6878
  onboard_events_default as OnboardEvents,
6879
+ onboard_events_default as OnboardIOEvents,
6088
6880
  openwhisk_default as Openwhisk,
6089
6881
  openwhisk_action_default as OpenwhiskAction,
6090
6882
  parameters_default as Parameters,
@@ -6094,6 +6886,7 @@ export {
6094
6886
  rest_client_default as RestClient,
6095
6887
  runtime_action_default as RuntimeAction,
6096
6888
  response_default as RuntimeActionResponse,
6889
+ RuntimeApiGatewayService,
6097
6890
  shipping_carrier_default as ShippingCarrier,
6098
6891
  method_default as ShippingCarrierMethod,
6099
6892
  response_default3 as ShippingCarrierResponse,