@plyaz/api 1.2.2 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/dist/api/client/clientEventManager.d.ts +8 -2
  2. package/dist/api/client/clientEventManager.d.ts.map +1 -1
  3. package/dist/api/client/createApiClient.d.ts.map +1 -1
  4. package/dist/api/client/helpers/interceptors.d.ts +2 -2
  5. package/dist/api/client/helpers/interceptors.d.ts.map +1 -1
  6. package/dist/api/config/global.d.ts.map +1 -1
  7. package/dist/api/debugger/DebugReport.d.ts.map +1 -1
  8. package/dist/api/debugger/UnifiedDebugger.d.ts.map +1 -1
  9. package/dist/api/debugger/queue/DebuggerQueueManager.d.ts.map +1 -1
  10. package/dist/api/debugger/queue/OperationTracker.d.ts.map +1 -1
  11. package/dist/api/endpoints/campaigns.d.ts.map +1 -1
  12. package/dist/api/endpoints/cdn.d.ts +122 -0
  13. package/dist/api/endpoints/cdn.d.ts.map +1 -0
  14. package/dist/api/endpoints/index.d.ts +89 -4
  15. package/dist/api/endpoints/index.d.ts.map +1 -1
  16. package/dist/api/endpoints/infobip.d.ts +209 -0
  17. package/dist/api/endpoints/infobip.d.ts.map +1 -0
  18. package/dist/api/endpoints/virustotal.d.ts +91 -0
  19. package/dist/api/endpoints/virustotal.d.ts.map +1 -0
  20. package/dist/api/errors/adapter.d.ts +71 -0
  21. package/dist/api/errors/adapter.d.ts.map +1 -0
  22. package/dist/api/errors/index.d.ts +3 -15
  23. package/dist/api/errors/index.d.ts.map +1 -1
  24. package/dist/api/events/EventManager.d.ts.map +1 -1
  25. package/dist/api/events/factories/base.d.ts +11 -3
  26. package/dist/api/events/factories/base.d.ts.map +1 -1
  27. package/dist/api/events/factories/errors.d.ts +10 -10
  28. package/dist/api/events/factories/errors.d.ts.map +1 -1
  29. package/dist/api/events/queue/ConfigUpdateQueueManager.d.ts.map +1 -1
  30. package/dist/api/events/queue/EventQueueManager.d.ts.map +1 -1
  31. package/dist/api/headers/headerBuilder.d.ts.map +1 -1
  32. package/dist/api/hooks/factories/createApiMutation.d.ts +3 -3
  33. package/dist/api/hooks/factories/createApiMutation.d.ts.map +1 -1
  34. package/dist/api/hooks/factories/createApiQuery.d.ts +3 -3
  35. package/dist/api/hooks/factories/createApiQuery.d.ts.map +1 -1
  36. package/dist/api/hooks/index.d.ts +0 -1
  37. package/dist/api/hooks/index.d.ts.map +1 -1
  38. package/dist/api/index.d.ts +1 -1
  39. package/dist/api/index.d.ts.map +1 -1
  40. package/dist/api/network/frameworks/express.d.ts.map +1 -1
  41. package/dist/api/network/frameworks/nestjs/decorators.d.ts +9 -1
  42. package/dist/api/network/frameworks/nestjs/decorators.d.ts.map +1 -1
  43. package/dist/api/network/frameworks/nestjs/enrichedHeadersGuard.d.ts.map +1 -1
  44. package/dist/api/network/frameworks/nestjs/enrichedHeadersInterceptor.d.ts.map +1 -1
  45. package/dist/api/network/networkConfigurationManager.d.ts.map +1 -1
  46. package/dist/api/network/status.d.ts +1 -4
  47. package/dist/api/network/status.d.ts.map +1 -1
  48. package/dist/api/performance/performanceMonitor.d.ts.map +1 -1
  49. package/dist/api/polling/index.d.ts +1 -1
  50. package/dist/api/polling/index.d.ts.map +1 -1
  51. package/dist/api/polling/strategies.d.ts +1 -5
  52. package/dist/api/polling/strategies.d.ts.map +1 -1
  53. package/dist/api/polling/utils.d.ts.map +1 -1
  54. package/dist/api/pubsub/index.d.ts.map +1 -1
  55. package/dist/api/pubsub/react.d.ts +6 -10
  56. package/dist/api/pubsub/react.d.ts.map +1 -1
  57. package/dist/api/queue/BaseOperationTracker.d.ts.map +1 -1
  58. package/dist/api/queue/EventQueueManager.d.ts.map +1 -1
  59. package/dist/api/queue/QueueOrchestrator.d.ts.map +1 -1
  60. package/dist/api/services/campaigns/GET/useCampaign.d.ts +1 -1
  61. package/dist/api/services/campaigns/GET/useCampaign.d.ts.map +1 -1
  62. package/dist/api/services/campaigns/GET/useCampaignParticipants.d.ts +1 -11
  63. package/dist/api/services/campaigns/GET/useCampaignParticipants.d.ts.map +1 -1
  64. package/dist/api/services/campaigns/GET/useCampaignStats.d.ts +1 -1
  65. package/dist/api/services/campaigns/GET/useCampaignStats.d.ts.map +1 -1
  66. package/dist/api/services/campaigns/GET/useCampaigns.d.ts +1 -1
  67. package/dist/api/services/campaigns/GET/useCampaigns.d.ts.map +1 -1
  68. package/dist/api/services/campaigns/PUT/useUpdateCampaign.d.ts +1 -9
  69. package/dist/api/services/campaigns/PUT/useUpdateCampaign.d.ts.map +1 -1
  70. package/dist/api/services/cdn/cloudflare/POST/cloudflarePurgeCache.d.ts +35 -0
  71. package/dist/api/services/cdn/cloudflare/POST/cloudflarePurgeCache.d.ts.map +1 -0
  72. package/dist/api/services/cdn/cloudflare/POST/index.d.ts +5 -0
  73. package/dist/api/services/cdn/cloudflare/POST/index.d.ts.map +1 -0
  74. package/dist/api/services/cdn/cloudflare/index.d.ts +5 -0
  75. package/dist/api/services/cdn/cloudflare/index.d.ts.map +1 -0
  76. package/dist/api/services/cdn/cloudfront/POST/cloudFrontCreateInvalidation.d.ts +38 -0
  77. package/dist/api/services/cdn/cloudfront/POST/cloudFrontCreateInvalidation.d.ts.map +1 -0
  78. package/dist/api/services/cdn/cloudfront/POST/index.d.ts +5 -0
  79. package/dist/api/services/cdn/cloudfront/POST/index.d.ts.map +1 -0
  80. package/dist/api/services/cdn/cloudfront/index.d.ts +5 -0
  81. package/dist/api/services/cdn/cloudfront/index.d.ts.map +1 -0
  82. package/dist/api/services/cdn/fastly/POST/fastlyPurgeUrl.d.ts +35 -0
  83. package/dist/api/services/cdn/fastly/POST/fastlyPurgeUrl.d.ts.map +1 -0
  84. package/dist/api/services/cdn/fastly/POST/index.d.ts +5 -0
  85. package/dist/api/services/cdn/fastly/POST/index.d.ts.map +1 -0
  86. package/dist/api/services/cdn/fastly/index.d.ts +5 -0
  87. package/dist/api/services/cdn/fastly/index.d.ts.map +1 -0
  88. package/dist/api/services/cdn/index.d.ts +8 -0
  89. package/dist/api/services/cdn/index.d.ts.map +1 -0
  90. package/dist/api/services/index.d.ts +3 -0
  91. package/dist/api/services/index.d.ts.map +1 -1
  92. package/dist/api/services/infobip/email/GET/fetchEmailLogs.d.ts +50 -0
  93. package/dist/api/services/infobip/email/GET/fetchEmailLogs.d.ts.map +1 -0
  94. package/dist/api/services/infobip/email/GET/fetchEmailReports.d.ts +44 -0
  95. package/dist/api/services/infobip/email/GET/fetchEmailReports.d.ts.map +1 -0
  96. package/dist/api/services/infobip/email/GET/fetchScheduledEmailStatuses.d.ts +28 -0
  97. package/dist/api/services/infobip/email/GET/fetchScheduledEmailStatuses.d.ts.map +1 -0
  98. package/dist/api/services/infobip/email/GET/fetchScheduledEmails.d.ts +27 -0
  99. package/dist/api/services/infobip/email/GET/fetchScheduledEmails.d.ts.map +1 -0
  100. package/dist/api/services/infobip/email/GET/fetchValidations.d.ts +60 -0
  101. package/dist/api/services/infobip/email/GET/fetchValidations.d.ts.map +1 -0
  102. package/dist/api/services/infobip/email/GET/index.d.ts +10 -0
  103. package/dist/api/services/infobip/email/GET/index.d.ts.map +1 -0
  104. package/dist/api/services/infobip/email/POST/bulkValidateEmails.d.ts +50 -0
  105. package/dist/api/services/infobip/email/POST/bulkValidateEmails.d.ts.map +1 -0
  106. package/dist/api/services/infobip/email/POST/index.d.ts +9 -0
  107. package/dist/api/services/infobip/email/POST/index.d.ts.map +1 -0
  108. package/dist/api/services/infobip/email/POST/sendAdvancedEmail.d.ts +67 -0
  109. package/dist/api/services/infobip/email/POST/sendAdvancedEmail.d.ts.map +1 -0
  110. package/dist/api/services/infobip/email/POST/sendEmail.d.ts +60 -0
  111. package/dist/api/services/infobip/email/POST/sendEmail.d.ts.map +1 -0
  112. package/dist/api/services/infobip/email/POST/validateEmail.d.ts +40 -0
  113. package/dist/api/services/infobip/email/POST/validateEmail.d.ts.map +1 -0
  114. package/dist/api/services/infobip/email/PUT/index.d.ts +7 -0
  115. package/dist/api/services/infobip/email/PUT/index.d.ts.map +1 -0
  116. package/dist/api/services/infobip/email/PUT/rescheduleEmails.d.ts +29 -0
  117. package/dist/api/services/infobip/email/PUT/rescheduleEmails.d.ts.map +1 -0
  118. package/dist/api/services/infobip/email/PUT/updateScheduledEmailStatuses.d.ts +36 -0
  119. package/dist/api/services/infobip/email/PUT/updateScheduledEmailStatuses.d.ts.map +1 -0
  120. package/dist/api/services/infobip/email/index.d.ts +8 -0
  121. package/dist/api/services/infobip/email/index.d.ts.map +1 -0
  122. package/dist/api/services/infobip/index.d.ts +6 -0
  123. package/dist/api/services/infobip/index.d.ts.map +1 -0
  124. package/dist/api/services/virustotal/analyses/GET/getAnalysisResult.d.ts +35 -0
  125. package/dist/api/services/virustotal/analyses/GET/getAnalysisResult.d.ts.map +1 -0
  126. package/dist/api/services/virustotal/analyses/GET/index.d.ts +6 -0
  127. package/dist/api/services/virustotal/analyses/GET/index.d.ts.map +1 -0
  128. package/dist/api/services/virustotal/analyses/index.d.ts +6 -0
  129. package/dist/api/services/virustotal/analyses/index.d.ts.map +1 -0
  130. package/dist/api/services/virustotal/files/POST/index.d.ts +6 -0
  131. package/dist/api/services/virustotal/files/POST/index.d.ts.map +1 -0
  132. package/dist/api/services/virustotal/files/POST/uploadFileForScanning.d.ts +36 -0
  133. package/dist/api/services/virustotal/files/POST/uploadFileForScanning.d.ts.map +1 -0
  134. package/dist/api/services/virustotal/files/index.d.ts +6 -0
  135. package/dist/api/services/virustotal/files/index.d.ts.map +1 -0
  136. package/dist/api/services/virustotal/index.d.ts +8 -0
  137. package/dist/api/services/virustotal/index.d.ts.map +1 -0
  138. package/dist/api/utils/aws/index.d.ts +7 -0
  139. package/dist/api/utils/aws/index.d.ts.map +1 -0
  140. package/dist/api/utils/aws/signature-v4.d.ts +41 -0
  141. package/dist/api/utils/aws/signature-v4.d.ts.map +1 -0
  142. package/dist/api/utils/aws/xml/cloudfront.d.ts +37 -0
  143. package/dist/api/utils/aws/xml/cloudfront.d.ts.map +1 -0
  144. package/dist/api/utils/aws/xml/index.d.ts +6 -0
  145. package/dist/api/utils/aws/xml/index.d.ts.map +1 -0
  146. package/dist/api/utils/index.d.ts +0 -3
  147. package/dist/api/utils/index.d.ts.map +1 -1
  148. package/dist/index.cjs +1586 -1384
  149. package/dist/index.cjs.map +1 -1
  150. package/dist/index.mjs +1522 -1354
  151. package/dist/index.mjs.map +1 -1
  152. package/package.json +7 -5
  153. package/dist/api/errors/ApiPackageError.d.ts +0 -101
  154. package/dist/api/errors/ApiPackageError.d.ts.map +0 -1
  155. package/dist/api/errors/definitions.d.ts +0 -24
  156. package/dist/api/errors/definitions.d.ts.map +0 -1
  157. package/dist/api/errors/error-codes.d.ts +0 -116
  158. package/dist/api/errors/error-codes.d.ts.map +0 -1
  159. package/dist/api/errors/error-events.d.ts +0 -63
  160. package/dist/api/errors/error-events.d.ts.map +0 -1
  161. package/dist/api/errors/types-constants.d.ts +0 -64
  162. package/dist/api/errors/types-constants.d.ts.map +0 -1
  163. package/dist/api/hooks/types.d.ts +0 -82
  164. package/dist/api/hooks/types.d.ts.map +0 -1
  165. package/dist/api/utils/generation/correlation-id.d.ts +0 -206
  166. package/dist/api/utils/generation/correlation-id.d.ts.map +0 -1
  167. package/dist/api/utils/generation/id-generator.d.ts +0 -133
  168. package/dist/api/utils/generation/id-generator.d.ts.map +0 -1
  169. package/dist/api/utils/generation/request-id.d.ts +0 -106
  170. package/dist/api/utils/generation/request-id.d.ts.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,14 +1,19 @@
1
- import { HTTP_STATUS, isDev, TIME_CONSTANTS, NUMERIC_CONSTANTS, MULTIPLIERS, NETWORK_SCORES, NETWORK_TIMEOUTS, RETRY_BACKOFF, RETRY_DELAYS, RETRY_ATTEMPTS, DEDUPE_TIME, CACHE_STALE, CACHE_TTL, BATCH_SIZES, PAGE_SIZES, TIMEZONE_REGIONS, LOCALE_REGIONS_DETAILED, COUNTRY_REGIONS_DETAILED, DEFAULT_API_CONFIG, DEFAULT_API_CLIENT_OPTIONS } from '@plyaz/config';
2
- import { ERROR_CATEGORY } from '@plyaz/types';
3
- export { ERROR_CATEGORY as ErrorCategory } from '@plyaz/types';
4
- import { API_ERROR_CODES, PRIORITY_LEVEL, EVENT_SCOPES, EVENT_NAMESPACES, HEADER_EVENTS, NETWORK_EVENTS, ERROR_EVENTS, DEBUG_EVENTS, CONFIG_EVENTS, PERFORMANCE_EVENTS, CACHE_EVENTS, CLIENT_EVENTS, NETWORK_QUALITY, EVENT_PRIORITY_MAP, PACKAGE_STATUS_CODES, OPERATIONS, HISTORY_TYPES, ERROR_DEFINITIONS as ERROR_DEFINITIONS$1, HANDLER_SCOPES as HANDLER_SCOPES$1, DEFAULT_THRESHOLDS, CORRELATION_TYPE, NETWORK_CONFIDENCE_LEVELS, ERROR_CATEGORY_TO_EMITTER_KEY, UPDATE_STRATEGIES, DEBUGGER_CONFIG_SOURCES, RTT_THRESHOLDS, SPEED_THRESHOLDS, REGIONAL_CONFIDENCE_LEVELS as REGIONAL_CONFIDENCE_LEVELS$1, COORDINATES, STORAGE_TYPES, ERROR_FIELDS, EVENT_OPERATIONS } from '@plyaz/types/api';
5
- export { API_ERROR_CODES, ERROR_DEFINITIONS, NETWORK_QUALITY, PUB_SUB_EVENT } from '@plyaz/types/api';
1
+ import { ApiPackageError as ApiPackageError$1, emitScopedErrorEvent, generateCorrelationId, generateRequestId, generateTraceCorrelationId, registerEventFactory, registerErrorHandler as registerErrorHandler$1, registerScopedHandlers, setErrorHandlers as setErrorHandlers$1, getErrorHandlers as getErrorHandlers$1, unregisterScopedHandlers, clearErrorHandlers as clearErrorHandlers$1, registerOnceErrorHandler, isErrorSystemInitialized, setErrorLocale, addMessageCatalog, initializeErrorSystem } from '@plyaz/errors';
2
+ export { getErrorCategory, getErrorCodeByStatus, getErrorDefinition } from '@plyaz/errors';
6
3
  import { abortRequest as abortRequest$1, isSlowConnection as isSlowConnection$1, deleteCache as deleteCache$1, getCache as getCache$1, mutate, setCache as setCache$1, subscribe as subscribe$1, revalidateAll as revalidateAll$1, revalidate, setDefaultConfig, createApiFetcher } from 'fetchff';
7
4
  export { removeRevalidators, revalidate, revalidateAll } from 'fetchff';
5
+ import { PRIORITY_LEVEL, EVENT_SCOPES_WITH_TEMPORARY, EVENT_NAMESPACES, HEADER_EVENTS, NETWORK_EVENTS, ERROR_EVENTS, DEBUG_EVENTS, CONFIG_EVENTS, PERFORMANCE_EVENTS, CACHE_EVENTS, CLIENT_EVENTS, NETWORK_QUALITY, EVENT_PRIORITY_MAP, PACKAGE_STATUS_CODES, API_ERROR_CODES, OPERATIONS, HISTORY_TYPES, EVENT_SCOPES as EVENT_SCOPES$1, HANDLER_SCOPES as HANDLER_SCOPES$1, DEFAULT_THRESHOLDS, NETWORK_CONFIDENCE_LEVELS, UPDATE_STRATEGIES, DEBUGGER_CONFIG_SOURCES, RTT_THRESHOLDS, SPEED_THRESHOLDS, REGIONAL_CONFIDENCE_LEVELS as REGIONAL_CONFIDENCE_LEVELS$1, COORDINATES, STORAGE_TYPES, ERROR_FIELDS, EVENT_OPERATIONS } from '@plyaz/types/api';
6
+ export { NETWORK_QUALITY, PUB_SUB_EVENT } from '@plyaz/types/api';
7
+ import { ApiLogger } from '@plyaz/logger';
8
+ import { LOGGER_SERVICES } from '@plyaz/types';
9
+ import { isDev, HTTP_STATUS, TIME_CONSTANTS, AWS_CLOUDFRONT_CONFIG, NUMERIC_CONSTANTS, MULTIPLIERS, NETWORK_SCORES, NETWORK_TIMEOUTS, RETRY_BACKOFF, RETRY_DELAYS, RETRY_ATTEMPTS, DEDUPE_TIME, CACHE_STALE, CACHE_TTL, BATCH_SIZES, PAGE_SIZES, TIMEZONE_REGIONS, LOCALE_REGIONS_DETAILED, COUNTRY_REGIONS_DETAILED, DEFAULT_API_CONFIG, DEFAULT_API_CLIENT_OPTIONS } from '@plyaz/config';
8
10
  import 'events';
11
+ import { INTERNAL_STATUS_CODES, API_ERROR_CODES as API_ERROR_CODES$1, COMMON_OPERATIONS } from '@plyaz/types/errors';
12
+ export { API_ERROR_CODES, ERROR_DEFINITIONS, COMMON_FIELDS as ERROR_FIELDS, COMMON_OPERATIONS as OPERATIONS, COMMON_STORAGE_TYPES as STORAGE_TYPES } from '@plyaz/types/errors';
9
13
  import { AsyncLocalStorage } from 'async_hooks';
10
14
  import { Injectable, createParamDecorator } from '@nestjs/common';
11
15
  import { Observable } from 'rxjs';
16
+ import * as crypto2 from 'crypto';
12
17
  import { createHash } from 'crypto';
13
18
  import { useQueryClient, useQuery, useMutation } from '@tanstack/react-query';
14
19
  import { useState, useRef, useCallback, useEffect } from 'react';
@@ -612,7 +617,7 @@ function getCrypto() {
612
617
  }
613
618
  __name(getCrypto, "getCrypto");
614
619
  function generateUUID() {
615
- const crypto2 = getCrypto();
620
+ const crypto3 = getCrypto();
616
621
  const UUID_CONSTANTS = {
617
622
  BYTES: 16,
618
623
  VERSION_POSITION: 6,
@@ -629,12 +634,12 @@ function generateUUID() {
629
634
  // eslint-disable-next-line no-magic-numbers
630
635
  POSITIONS: [8, 12, 16, 20, 32]
631
636
  };
632
- if (crypto2 && typeof crypto2.randomUUID === "function") {
633
- return crypto2.randomUUID();
637
+ if (crypto3 && typeof crypto3.randomUUID === "function") {
638
+ return crypto3.randomUUID();
634
639
  }
635
- if (crypto2?.getRandomValues) {
640
+ if (crypto3?.getRandomValues) {
636
641
  const bytes = new Uint8Array(UUID_CONSTANTS.BYTES);
637
- crypto2.getRandomValues(bytes);
642
+ crypto3.getRandomValues(bytes);
638
643
  bytes[UUID_CONSTANTS.VERSION_POSITION] = bytes[UUID_CONSTANTS.VERSION_POSITION] & UUID_CONSTANTS.VERSION_MASK | UUID_CONSTANTS.VERSION_VALUE;
639
644
  bytes[UUID_CONSTANTS.VARIANT_POSITION] = bytes[UUID_CONSTANTS.VARIANT_POSITION] & UUID_CONSTANTS.VARIANT_MASK | UUID_CONSTANTS.VARIANT_VALUE;
640
645
  const hex = Array.from(
@@ -1009,302 +1014,6 @@ function applyPollingStrategy(strategy) {
1009
1014
  return strategy;
1010
1015
  }
1011
1016
  __name(applyPollingStrategy, "applyPollingStrategy");
1012
- var ERROR_DEFINITIONS = {
1013
- // Authentication
1014
- [API_ERROR_CODES.AUTH_UNAUTHORIZED]: {
1015
- code: API_ERROR_CODES.AUTH_UNAUTHORIZED,
1016
- status: HTTP_STATUS.UNAUTHORIZED,
1017
- category: ERROR_CATEGORY.Authentication
1018
- },
1019
- [API_ERROR_CODES.AUTH_FORBIDDEN]: {
1020
- code: API_ERROR_CODES.AUTH_FORBIDDEN,
1021
- status: HTTP_STATUS.FORBIDDEN,
1022
- category: ERROR_CATEGORY.Authorization
1023
- },
1024
- [API_ERROR_CODES.AUTH_TOKEN_EXPIRED]: {
1025
- code: API_ERROR_CODES.AUTH_TOKEN_EXPIRED,
1026
- status: HTTP_STATUS.UNAUTHORIZED,
1027
- category: ERROR_CATEGORY.Authentication
1028
- },
1029
- [API_ERROR_CODES.AUTH_INVALID_CREDENTIALS]: {
1030
- code: API_ERROR_CODES.AUTH_INVALID_CREDENTIALS,
1031
- status: HTTP_STATUS.UNAUTHORIZED,
1032
- category: ERROR_CATEGORY.Authentication
1033
- },
1034
- // Rate Limiting
1035
- [API_ERROR_CODES.RATE_LIMIT_EXCEEDED]: {
1036
- code: API_ERROR_CODES.RATE_LIMIT_EXCEEDED,
1037
- status: HTTP_STATUS.TOO_MANY_REQUESTS,
1038
- category: ERROR_CATEGORY.RateLimit
1039
- },
1040
- // Resource Errors
1041
- [API_ERROR_CODES.RESOURCE_NOT_FOUND]: {
1042
- code: API_ERROR_CODES.RESOURCE_NOT_FOUND,
1043
- status: HTTP_STATUS.NOT_FOUND,
1044
- category: ERROR_CATEGORY.NotFound
1045
- },
1046
- // System Errors
1047
- [API_ERROR_CODES.INTERNAL_SERVER_ERROR]: {
1048
- code: API_ERROR_CODES.INTERNAL_SERVER_ERROR,
1049
- status: HTTP_STATUS.INTERNAL_SERVER_ERROR,
1050
- category: ERROR_CATEGORY.Server
1051
- },
1052
- [API_ERROR_CODES.SERVICE_UNAVAILABLE]: {
1053
- code: API_ERROR_CODES.SERVICE_UNAVAILABLE,
1054
- status: HTTP_STATUS.SERVICE_UNAVAILABLE,
1055
- category: ERROR_CATEGORY.Server
1056
- },
1057
- [API_ERROR_CODES.EXTERNAL_SERVICE_ERROR]: {
1058
- code: API_ERROR_CODES.EXTERNAL_SERVICE_ERROR,
1059
- status: HTTP_STATUS.BAD_GATEWAY,
1060
- category: ERROR_CATEGORY.ExternalService
1061
- },
1062
- // Validation
1063
- [API_ERROR_CODES.VALIDATION_ERROR]: {
1064
- code: API_ERROR_CODES.VALIDATION_ERROR,
1065
- status: HTTP_STATUS.BAD_REQUEST,
1066
- category: ERROR_CATEGORY.Validation
1067
- },
1068
- [API_ERROR_CODES.VALIDATION_FAILED]: {
1069
- code: API_ERROR_CODES.VALIDATION_FAILED,
1070
- status: HTTP_STATUS.BAD_REQUEST,
1071
- category: ERROR_CATEGORY.Validation
1072
- },
1073
- [API_ERROR_CODES.REQUIRED_FIELD_MISSING]: {
1074
- code: API_ERROR_CODES.REQUIRED_FIELD_MISSING,
1075
- status: HTTP_STATUS.BAD_REQUEST,
1076
- category: ERROR_CATEGORY.Validation,
1077
- fieldsLeft: ["field"]
1078
- },
1079
- [API_ERROR_CODES.INVALID_FORMAT]: {
1080
- code: API_ERROR_CODES.INVALID_FORMAT,
1081
- status: HTTP_STATUS.BAD_REQUEST,
1082
- category: ERROR_CATEGORY.Validation
1083
- },
1084
- [API_ERROR_CODES.STRING_TOO_SHORT]: {
1085
- code: API_ERROR_CODES.STRING_TOO_SHORT,
1086
- status: HTTP_STATUS.BAD_REQUEST,
1087
- category: ERROR_CATEGORY.Validation,
1088
- fieldsLeft: ["field", "minLength"]
1089
- },
1090
- [API_ERROR_CODES.STRING_TOO_LONG]: {
1091
- code: API_ERROR_CODES.STRING_TOO_LONG,
1092
- status: HTTP_STATUS.BAD_REQUEST,
1093
- category: ERROR_CATEGORY.Validation,
1094
- fieldsLeft: ["field", "maxLength"]
1095
- },
1096
- // Request Errors
1097
- [API_ERROR_CODES.REQUEST_TIMEOUT]: {
1098
- code: API_ERROR_CODES.REQUEST_TIMEOUT,
1099
- status: HTTP_STATUS.REQUEST_TIMEOUT,
1100
- category: ERROR_CATEGORY.Timeout
1101
- },
1102
- [API_ERROR_CODES.REQUEST_ABORTED]: {
1103
- code: API_ERROR_CODES.REQUEST_ABORTED,
1104
- status: 0,
1105
- // No HTTP status for aborted
1106
- category: ERROR_CATEGORY.Client
1107
- },
1108
- [API_ERROR_CODES.REQUEST_INVALID_PARAMS]: {
1109
- code: API_ERROR_CODES.REQUEST_INVALID_PARAMS,
1110
- status: HTTP_STATUS.BAD_REQUEST,
1111
- category: ERROR_CATEGORY.Client
1112
- },
1113
- [API_ERROR_CODES.REQUEST_PREPARATION_FAILED]: {
1114
- code: API_ERROR_CODES.REQUEST_PREPARATION_FAILED,
1115
- status: HTTP_STATUS.BAD_REQUEST,
1116
- category: ERROR_CATEGORY.Client
1117
- },
1118
- // Response Errors
1119
- [API_ERROR_CODES.RESPONSE_INVALID_FORMAT]: {
1120
- code: API_ERROR_CODES.RESPONSE_INVALID_FORMAT,
1121
- status: HTTP_STATUS.UNPROCESSABLE_ENTITY,
1122
- category: ERROR_CATEGORY.Client
1123
- },
1124
- [API_ERROR_CODES.RESPONSE_PARSING_FAILED]: {
1125
- code: API_ERROR_CODES.RESPONSE_PARSING_FAILED,
1126
- status: HTTP_STATUS.UNPROCESSABLE_ENTITY,
1127
- category: ERROR_CATEGORY.Client
1128
- },
1129
- // Network
1130
- [API_ERROR_CODES.NETWORK_ERROR]: {
1131
- code: API_ERROR_CODES.NETWORK_ERROR,
1132
- status: HTTP_STATUS.BAD_GATEWAY,
1133
- category: ERROR_CATEGORY.Network
1134
- },
1135
- [API_ERROR_CODES.NETWORK_TIMEOUT]: {
1136
- code: API_ERROR_CODES.NETWORK_TIMEOUT,
1137
- status: HTTP_STATUS.GATEWAY_TIMEOUT,
1138
- category: ERROR_CATEGORY.Timeout
1139
- },
1140
- [API_ERROR_CODES.NETWORK_CONNECTION_FAILED]: {
1141
- code: API_ERROR_CODES.NETWORK_CONNECTION_FAILED,
1142
- status: 0,
1143
- // No HTTP status for connection failure
1144
- category: ERROR_CATEGORY.Network
1145
- },
1146
- [API_ERROR_CODES.NETWORK_OFFLINE]: {
1147
- code: API_ERROR_CODES.NETWORK_OFFLINE,
1148
- status: 0,
1149
- // No HTTP status for offline
1150
- category: ERROR_CATEGORY.Network
1151
- },
1152
- [API_ERROR_CODES.NETWORK_DNS_FAILED]: {
1153
- code: API_ERROR_CODES.NETWORK_DNS_FAILED,
1154
- status: 0,
1155
- // No HTTP status for DNS failure
1156
- category: ERROR_CATEGORY.Network
1157
- },
1158
- // Server
1159
- [API_ERROR_CODES.SERVER_ERROR]: {
1160
- code: API_ERROR_CODES.SERVER_ERROR,
1161
- status: HTTP_STATUS.INTERNAL_SERVER_ERROR,
1162
- category: ERROR_CATEGORY.Server
1163
- },
1164
- // Client
1165
- [API_ERROR_CODES.CLIENT_ERROR]: {
1166
- code: API_ERROR_CODES.CLIENT_ERROR,
1167
- status: HTTP_STATUS.BAD_REQUEST,
1168
- category: ERROR_CATEGORY.Client
1169
- },
1170
- [API_ERROR_CODES.CLIENT_CANCELLED]: {
1171
- code: API_ERROR_CODES.CLIENT_CANCELLED,
1172
- status: 0,
1173
- // No HTTP status for cancelled
1174
- category: ERROR_CATEGORY.Client
1175
- },
1176
- [API_ERROR_CODES.CLIENT_INITIALIZATION_FAILED]: {
1177
- code: API_ERROR_CODES.CLIENT_INITIALIZATION_FAILED,
1178
- status: 0,
1179
- // No HTTP status for initialization failure
1180
- category: ERROR_CATEGORY.Client
1181
- },
1182
- [API_ERROR_CODES.CLIENT_INVALID_CONFIG]: {
1183
- code: API_ERROR_CODES.CLIENT_INVALID_CONFIG,
1184
- status: 0,
1185
- // No HTTP status for configuration errors
1186
- category: ERROR_CATEGORY.Client
1187
- },
1188
- [API_ERROR_CODES.CLIENT_MISSING_BASE_URL]: {
1189
- code: API_ERROR_CODES.CLIENT_MISSING_BASE_URL,
1190
- status: 0,
1191
- // No HTTP status for configuration errors
1192
- category: ERROR_CATEGORY.Client
1193
- },
1194
- [API_ERROR_CODES.CONFIG_VALIDATION_FAILED]: {
1195
- code: API_ERROR_CODES.CONFIG_VALIDATION_FAILED,
1196
- status: HTTP_STATUS.BAD_REQUEST,
1197
- category: ERROR_CATEGORY.Validation
1198
- },
1199
- [API_ERROR_CODES.HEADER_PROCESSING_FAILED]: {
1200
- code: API_ERROR_CODES.HEADER_PROCESSING_FAILED,
1201
- status: HTTP_STATUS.INTERNAL_SERVER_ERROR,
1202
- category: ERROR_CATEGORY.Headers
1203
- },
1204
- [API_ERROR_CODES.NETWORK_OVERRIDE_FAILED]: {
1205
- code: API_ERROR_CODES.NETWORK_OVERRIDE_FAILED,
1206
- status: HTTP_STATUS.INTERNAL_SERVER_ERROR,
1207
- category: ERROR_CATEGORY.Network
1208
- },
1209
- // Headers
1210
- [API_ERROR_CODES.HEADERS_ENRICHMENT_FAILED]: {
1211
- code: API_ERROR_CODES.HEADERS_ENRICHMENT_FAILED,
1212
- status: HTTP_STATUS.BAD_REQUEST,
1213
- category: ERROR_CATEGORY.Headers
1214
- },
1215
- [API_ERROR_CODES.HEADERS_VALIDATION_FAILED]: {
1216
- code: API_ERROR_CODES.HEADERS_VALIDATION_FAILED,
1217
- status: HTTP_STATUS.BAD_REQUEST,
1218
- category: ERROR_CATEGORY.Headers
1219
- },
1220
- [API_ERROR_CODES.HEADERS_MERGE_CONFLICT]: {
1221
- code: API_ERROR_CODES.HEADERS_MERGE_CONFLICT,
1222
- status: HTTP_STATUS.CONFLICT,
1223
- category: ERROR_CATEGORY.Headers
1224
- },
1225
- // Cache
1226
- [API_ERROR_CODES.CACHE_STORAGE_FAILED]: {
1227
- code: API_ERROR_CODES.CACHE_STORAGE_FAILED,
1228
- status: 0,
1229
- // No HTTP status for cache failures
1230
- category: ERROR_CATEGORY.Cache
1231
- },
1232
- [API_ERROR_CODES.CACHE_RETRIEVAL_FAILED]: {
1233
- code: API_ERROR_CODES.CACHE_RETRIEVAL_FAILED,
1234
- status: 0,
1235
- // No HTTP status for cache failures
1236
- category: ERROR_CATEGORY.Cache
1237
- },
1238
- [API_ERROR_CODES.CACHE_INVALIDATION_FAILED]: {
1239
- code: API_ERROR_CODES.CACHE_INVALIDATION_FAILED,
1240
- status: 0,
1241
- // No HTTP status for cache failures
1242
- category: ERROR_CATEGORY.Cache
1243
- },
1244
- // Retry
1245
- [API_ERROR_CODES.RETRY_EXHAUSTED]: {
1246
- code: API_ERROR_CODES.RETRY_EXHAUSTED,
1247
- status: HTTP_STATUS.SERVICE_UNAVAILABLE,
1248
- category: ERROR_CATEGORY.Retry
1249
- },
1250
- [API_ERROR_CODES.RETRY_STRATEGY_INVALID]: {
1251
- code: API_ERROR_CODES.RETRY_STRATEGY_INVALID,
1252
- status: 0,
1253
- // No HTTP status for strategy errors
1254
- category: ERROR_CATEGORY.Retry
1255
- },
1256
- // Strategy
1257
- [API_ERROR_CODES.STRATEGY_INVALID]: {
1258
- code: API_ERROR_CODES.STRATEGY_INVALID,
1259
- status: 0,
1260
- // No HTTP status for strategy errors
1261
- category: ERROR_CATEGORY.Strategy
1262
- },
1263
- [API_ERROR_CODES.STRATEGY_CONFLICT]: {
1264
- code: API_ERROR_CODES.STRATEGY_CONFLICT,
1265
- status: HTTP_STATUS.CONFLICT,
1266
- category: ERROR_CATEGORY.Strategy
1267
- },
1268
- // Regional
1269
- [API_ERROR_CODES.REGIONAL_PRESET_NOT_FOUND]: {
1270
- code: API_ERROR_CODES.REGIONAL_PRESET_NOT_FOUND,
1271
- status: 0,
1272
- // No HTTP status for regional preset errors
1273
- category: ERROR_CATEGORY.Regional
1274
- },
1275
- [API_ERROR_CODES.REGION_DETECTION_FAILED]: {
1276
- code: API_ERROR_CODES.REGION_DETECTION_FAILED,
1277
- status: HTTP_STATUS.INTERNAL_SERVER_ERROR,
1278
- category: ERROR_CATEGORY.Regional
1279
- },
1280
- // Timeout
1281
- [API_ERROR_CODES.TIMEOUT]: {
1282
- code: API_ERROR_CODES.TIMEOUT,
1283
- status: HTTP_STATUS.REQUEST_TIMEOUT,
1284
- category: ERROR_CATEGORY.Timeout
1285
- },
1286
- // Unknown
1287
- [API_ERROR_CODES.UNKNOWN_ERROR]: {
1288
- code: API_ERROR_CODES.UNKNOWN_ERROR,
1289
- status: HTTP_STATUS.INTERNAL_SERVER_ERROR,
1290
- category: ERROR_CATEGORY.Unknown
1291
- }
1292
- };
1293
- function getErrorDefinition(errorCode) {
1294
- return ERROR_DEFINITIONS[errorCode];
1295
- }
1296
- __name(getErrorDefinition, "getErrorDefinition");
1297
- function getErrorCodeByStatus(status) {
1298
- const entry = Object.entries(ERROR_DEFINITIONS).find(
1299
- ([, definition]) => definition.status === status
1300
- );
1301
- return entry?.[0];
1302
- }
1303
- __name(getErrorCodeByStatus, "getErrorCodeByStatus");
1304
- function getErrorCategory(errorCode) {
1305
- return ERROR_DEFINITIONS[errorCode]?.category ?? ERROR_CATEGORY.Unknown;
1306
- }
1307
- __name(getErrorCategory, "getErrorCategory");
1308
1017
  var BINARY_HEAP = {
1309
1018
  /** Number of children per node in binary heap */
1310
1019
  CHILDREN_PER_NODE: 2,
@@ -2031,8 +1740,6 @@ function removeCircularReferences(obj) {
2031
1740
  }
2032
1741
  }
2033
1742
  __name(removeCircularReferences, "removeCircularReferences");
2034
-
2035
- // src/api/utils/time.ts
2036
1743
  var MS_IN_SECOND = 1e3;
2037
1744
  var SECONDS_PER_MINUTE = 60;
2038
1745
  var MINUTES_PER_HOUR = 60;
@@ -2577,13 +2284,13 @@ var BaseEventFactory = class {
2577
2284
  constructor(namespace, emitter) {
2578
2285
  this.namespace = namespace;
2579
2286
  this.emitter = emitter;
2580
- EVENT_SCOPES.forEach((scope) => {
2287
+ EVENT_SCOPES_WITH_TEMPORARY.forEach((scope) => {
2581
2288
  this.scopedHandlers.set(scope, /* @__PURE__ */ new Map());
2582
2289
  this.originalHandlers.set(scope, /* @__PURE__ */ new Map());
2583
2290
  });
2584
2291
  this.trackFactoryOperation("factory_initialized", {
2585
2292
  namespace: this.namespace,
2586
- scopesInitialized: EVENT_SCOPES.length,
2293
+ scopesInitialized: EVENT_SCOPES_WITH_TEMPORARY.length,
2587
2294
  emitterType: "EventEmitter"
2588
2295
  });
2589
2296
  }
@@ -2735,16 +2442,14 @@ var BaseEventFactory = class {
2735
2442
  * - Non-scoped wildcards for backwards compatibility (e.g., headers:*)
2736
2443
  */
2737
2444
  emitAcrossScopes(eventType, eventName, data, scopes) {
2738
- const targetScopes = scopes ?? EVENT_SCOPES;
2739
- const normalizedScopes = targetScopes.map(
2740
- (s) => s === "temporary" ? "request" : s
2741
- );
2742
- const scopeOrder = [...EVENT_SCOPES];
2445
+ const targetScopes = scopes ?? EVENT_SCOPES_WITH_TEMPORARY;
2446
+ const scopeOrder = [...EVENT_SCOPES_WITH_TEMPORARY];
2743
2447
  for (const scope of scopeOrder) {
2744
- if (normalizedScopes.includes(scope)) {
2745
- const namespacedEvent = `${scope}:${eventType}:${eventName}`;
2448
+ if (targetScopes.includes(scope)) {
2449
+ const emitScope = scope === "temporary" ? "request" : scope;
2450
+ const namespacedEvent = `${emitScope}:${eventType}:${eventName}`;
2746
2451
  this.emitter.emit(namespacedEvent, data);
2747
- const wildcardEvent = `${scope}:${eventType}:*`;
2452
+ const wildcardEvent = `${emitScope}:${eventType}:*`;
2748
2453
  const wildcardData2 = typeof data === "object" && data !== null ? { ...data, originalEvent: eventName } : { data, originalEvent: eventName };
2749
2454
  this.emitter.emit(wildcardEvent, wildcardData2);
2750
2455
  }
@@ -2942,6 +2647,52 @@ var BaseEventFactory = class {
2942
2647
  });
2943
2648
  return this.createHandlerUnsubscribe(scope, eventName, handler, unsubscribes);
2944
2649
  }
2650
+ /**
2651
+ * Remove a specific handler from a scoped event
2652
+ *
2653
+ * @param scope - The scope to remove from ('global', 'config', 'client', 'request')
2654
+ * @param eventName - The event name (e.g., 'validation', 'network', '*')
2655
+ * @param handler - The specific handler to remove (should be the original handler, not wrapped)
2656
+ */
2657
+ removeScopedHandler(scope, eventName, handler) {
2658
+ const startTime = Date.now();
2659
+ const scopeMap = this.scopedHandlers.get(scope);
2660
+ const originalMap = this.originalHandlers.get(scope);
2661
+ if (!scopeMap || !originalMap) {
2662
+ return;
2663
+ }
2664
+ const handlers = scopeMap.get(eventName);
2665
+ const originals = originalMap.get(eventName);
2666
+ if (!handlers || !originals) {
2667
+ return;
2668
+ }
2669
+ const handlerAsUnknown = handler;
2670
+ const originalIndex = originals.indexOf(handlerAsUnknown);
2671
+ if (originalIndex === -1) {
2672
+ return;
2673
+ }
2674
+ const beforeCount = handlers.length;
2675
+ const wrappedHandler = handlers[originalIndex];
2676
+ handlers.splice(originalIndex, 1);
2677
+ originals.splice(originalIndex, 1);
2678
+ const scopedEventKey = `${scope}:${this.namespace}:${eventName}`;
2679
+ this.emitter.off(scopedEventKey, wrappedHandler);
2680
+ if (handlers.length === 0) {
2681
+ scopeMap.delete(eventName);
2682
+ originalMap.delete(eventName);
2683
+ } else {
2684
+ scopeMap.set(eventName, handlers);
2685
+ originalMap.set(eventName, originals);
2686
+ }
2687
+ this.trackFactoryOperation("specific_handler_removed", {
2688
+ scope,
2689
+ eventName,
2690
+ beforeHandlerCount: beforeCount,
2691
+ afterHandlerCount: handlers.length,
2692
+ eventDeleted: handlers.length === 0,
2693
+ removalTime: Date.now() - startTime
2694
+ });
2695
+ }
2945
2696
  /**
2946
2697
  * Remove all listeners for a scoped event
2947
2698
  *
@@ -4690,13 +4441,13 @@ var HANDLER_SCOPES = {
4690
4441
  REQUEST: "request"
4691
4442
  // Request-level handlers (highest priority, per-request)
4692
4443
  };
4693
- var EVENT_SCOPES2 = [
4444
+ var EVENT_SCOPES = [
4694
4445
  HANDLER_SCOPES.GLOBAL,
4695
4446
  HANDLER_SCOPES.CONFIG,
4696
4447
  HANDLER_SCOPES.CLIENT,
4697
4448
  HANDLER_SCOPES.REQUEST
4698
4449
  ];
4699
- var EVENT_SCOPES_WITH_TEMPORARY = [...EVENT_SCOPES2, "temporary"];
4450
+ var EVENT_SCOPES_WITH_TEMPORARY2 = [...EVENT_SCOPES, "temporary"];
4700
4451
  function createHandlerNamespace(eventType, scope) {
4701
4452
  return `${HANDLER_SCOPES[scope]}:${eventType}`;
4702
4453
  }
@@ -4888,6 +4639,7 @@ __name(getHandlerNamespaceForEvent, "getHandlerNamespaceForEvent");
4888
4639
 
4889
4640
  // src/api/events/EventManager.ts
4890
4641
  var SLOW_REQUEST_THRESHOLD_MS = 5e3;
4642
+ var logger = new ApiLogger({ service: LOGGER_SERVICES.EVENT_MANAGER, transport: "console" });
4891
4643
  var EventManager = class _EventManager extends BaseEventFactory {
4892
4644
  static {
4893
4645
  __name(this, "EventManager");
@@ -4905,7 +4657,7 @@ var EventManager = class _EventManager extends BaseEventFactory {
4905
4657
  // DEFAULT: ALL scopes are active ['global', 'config', 'client', 'request']
4906
4658
  // This means events are emitted to handlers at all scope levels by default
4907
4659
  // Can be restricted by calling setEventScopes() with specific scopes
4908
- eventScopes = [...EVENT_SCOPES2];
4660
+ eventScopes = [...EVENT_SCOPES];
4909
4661
  currentEventScopes = this.eventScopes;
4910
4662
  // Alias for compatibility
4911
4663
  constructor() {
@@ -5081,9 +4833,10 @@ var EventManager = class _EventManager extends BaseEventFactory {
5081
4833
  */
5082
4834
  setupDebugHandlers() {
5083
4835
  this.on(DEBUG_EVENTS2.CONFIG_CONFLICT, (event) => {
5084
- if (typeof console !== "undefined" && typeof console.debug === "function") {
5085
- console.debug("[EventManager] Config conflict detected:", event);
5086
- }
4836
+ logger.debug("Config conflict detected", {
4837
+ conflictType: event.type,
4838
+ source: event.source
4839
+ });
5087
4840
  });
5088
4841
  }
5089
4842
  /**
@@ -5377,6 +5130,7 @@ var eventManager = {
5377
5130
  getEventStats: /* @__PURE__ */ __name(() => getEventManager().getEventStats(), "getEventStats"),
5378
5131
  getActiveScopes: /* @__PURE__ */ __name(() => getEventManager().getActiveScopes(), "getActiveScopes")
5379
5132
  };
5133
+ var logger2 = new ApiLogger({ service: LOGGER_SERVICES.EVENT_QUEUE, transport: "console" });
5380
5134
  var EventQueueManager = class _EventQueueManager {
5381
5135
  static {
5382
5136
  __name(this, "EventQueueManager");
@@ -5478,7 +5232,11 @@ var EventQueueManager = class _EventQueueManager {
5478
5232
  }
5479
5233
  }
5480
5234
  if (isDev) {
5481
- console.warn("[EventQueue] Event processing failed:", error);
5235
+ logger2.warn("Event processing failed", {
5236
+ eventType: event.eventType,
5237
+ eventName: event.eventName,
5238
+ error: error instanceof Error ? error.message : String(error)
5239
+ });
5482
5240
  }
5483
5241
  }
5484
5242
  }
@@ -7517,6 +7275,7 @@ function colorProgressBar(value, max2, width = DEFAULT_PROGRESS_BAR_WIDTH) {
7517
7275
  return `[${bar}] ${percentText}`;
7518
7276
  }
7519
7277
  __name(colorProgressBar, "colorProgressBar");
7278
+ var logger3 = new ApiLogger({ service: LOGGER_SERVICES.DEBUG_REPORT, transport: "console" });
7520
7279
  var DEBUG_REPORT_CONSTANTS = {
7521
7280
  // Byte sizes
7522
7281
  BYTES_PER_KB: 1024,
@@ -9262,24 +9021,26 @@ function logNetworkOverride(params) {
9262
9021
  networkQuality,
9263
9022
  duration
9264
9023
  } = params;
9265
- console.group(`🔧 Network Config Override: ${property}`);
9266
- console.log(`Value: ${originalValue} → ${overrideValue}`);
9267
- console.log(`Source: ${source}`);
9268
- console.log(`Reason: ${reason}`);
9024
+ logger3.group(`🔧 Network Config Override: ${property}`);
9025
+ logger3.info("Value changed", {
9026
+ from: originalValue,
9027
+ to: overrideValue
9028
+ });
9029
+ logger3.info("Source", { source });
9030
+ logger3.info("Reason", { reason });
9269
9031
  if (networkQuality) {
9270
- console.log(`Network Quality: ${networkQuality.toLowerCase()}`);
9032
+ logger3.info("Network Quality", { quality: networkQuality.toLowerCase() });
9271
9033
  }
9272
9034
  if (networkInfo?.saveData) {
9273
- console.log("Save-Data: enabled");
9035
+ logger3.info("Save-Data enabled");
9274
9036
  }
9275
9037
  if (duration) {
9276
- console.log(`Duration: ${duration}ms`);
9038
+ logger3.info("Duration", { ms: duration });
9277
9039
  }
9278
- console.groupEnd();
9040
+ logger3.groupEnd();
9279
9041
  }
9280
9042
  __name(logNetworkOverride, "logNetworkOverride");
9281
-
9282
- // src/api/debugger/UnifiedDebugger.ts
9043
+ var logger4 = new ApiLogger({ service: LOGGER_SERVICES.UNIFIED_DEBUGGER, transport: "console" });
9283
9044
  var DEBUGGER_CONSTANTS = {
9284
9045
  // Array/Division constants
9285
9046
  HALF_DIVISOR: 2,
@@ -9465,7 +9226,10 @@ var UnifiedDebugger = class _UnifiedDebugger {
9465
9226
  }
9466
9227
  }
9467
9228
  );
9468
- console.warn("⚠️ Debugger tracking failed:", apiError.message, apiError.context);
9229
+ logger4.warn("⚠️ Debugger tracking failed", {
9230
+ error: apiError.message,
9231
+ context: apiError.context
9232
+ });
9469
9233
  }
9470
9234
  /**
9471
9235
  * Safe tracking helper that handles errors properly
@@ -9800,11 +9564,11 @@ var UnifiedDebugger = class _UnifiedDebugger {
9800
9564
  try {
9801
9565
  const presetReport = this.getPresetChangeReport();
9802
9566
  if (presetReport) {
9803
- console.log(presetReport);
9804
- console.log("");
9567
+ logger4.info(presetReport);
9568
+ logger4.info("");
9805
9569
  }
9806
9570
  const report = await generateComprehensiveReport();
9807
- console.log(formatReportForConsole(report));
9571
+ logger4.info(formatReportForConsole(report));
9808
9572
  } catch (err) {
9809
9573
  const error = new ApiPackageError(
9810
9574
  "Failed to generate debug report",
@@ -9812,7 +9576,9 @@ var UnifiedDebugger = class _UnifiedDebugger {
9812
9576
  API_ERROR_CODES.DEBUG_TRACKING_FAILED,
9813
9577
  { cause: err }
9814
9578
  );
9815
- console.error("⚠️ Failed to generate debug report:", error.message);
9579
+ logger4.error("⚠️ Failed to generate debug report", {
9580
+ error: error.message
9581
+ });
9816
9582
  throw error;
9817
9583
  }
9818
9584
  }
@@ -10129,11 +9895,11 @@ var UnifiedDebugger = class _UnifiedDebugger {
10129
9895
  trigger: options.trigger,
10130
9896
  timestamp
10131
9897
  };
10132
- if (this.enabled && typeof console !== "undefined") {
10133
- console.group(`📋 Network preset applied: ${options.preset}`);
10134
- console.log(`Quality: ${options.networkConditions.quality}`);
10135
- console.log(`Trigger: ${options.trigger}`);
10136
- console.groupEnd();
9898
+ if (this.enabled) {
9899
+ logger4.group(`📋 Network preset applied: ${options.preset}`);
9900
+ logger4.info(`Quality: ${options.networkConditions.quality}`);
9901
+ logger4.info(`Trigger: ${options.trigger}`);
9902
+ logger4.groupEnd();
10137
9903
  }
10138
9904
  }
10139
9905
  options.changes.forEach((change) => {
@@ -10195,8 +9961,8 @@ var UnifiedDebugger = class _UnifiedDebugger {
10195
9961
  source: "networkPreset",
10196
9962
  reason: options.trigger
10197
9963
  });
10198
- if (this.enabled && typeof console !== "undefined") {
10199
- console.log(`🔄 Network config restored: ${property}`);
9964
+ if (this.enabled) {
9965
+ logger4.info("🔄 Network config restored", { property });
10200
9966
  }
10201
9967
  this.addToHistory({
10202
9968
  type: "network",
@@ -10223,16 +9989,16 @@ var UnifiedDebugger = class _UnifiedDebugger {
10223
9989
  trigger: options.trigger,
10224
9990
  timestamp: Date.now()
10225
9991
  };
10226
- if (this.enabled && typeof console !== "undefined") {
10227
- console.group(`📋 Network preset applied: ${presetId}`);
10228
- console.log(`Quality: ${options.networkQuality}`);
10229
- console.log(`Trigger: ${options.trigger}`);
9992
+ if (this.enabled) {
9993
+ logger4.group(`📋 Network preset applied: ${presetId}`);
9994
+ logger4.info(`Quality: ${options.networkQuality}`);
9995
+ logger4.info(`Trigger: ${options.trigger}`);
10230
9996
  changes.forEach((change) => {
10231
9997
  const prev = typeof change.previousValue === "string" ? `"${change.previousValue}"` : String(change.previousValue);
10232
9998
  const next = typeof change.newValue === "string" ? `"${change.newValue}"` : String(change.newValue);
10233
- console.log(` ${change.property}: ${prev} → ${next}`);
9999
+ logger4.info(` ${change.property}: ${prev} → ${next}`);
10234
10000
  });
10235
- console.groupEnd();
10001
+ logger4.groupEnd();
10236
10002
  }
10237
10003
  const configChanges = changes.reduce(
10238
10004
  (acc, change) => {
@@ -10655,14 +10421,14 @@ var UnifiedDebugger = class _UnifiedDebugger {
10655
10421
  */
10656
10422
  enableNetworkDebug() {
10657
10423
  this.setEnabled(true);
10658
- console.log("🌐 Network configuration debugging enabled");
10424
+ logger4.info("🌐 Network configuration debugging enabled");
10659
10425
  }
10660
10426
  /**
10661
10427
  * Disable network config debugging
10662
10428
  */
10663
10429
  disableNetworkDebug() {
10664
10430
  this.setEnabled(false);
10665
- console.log("🌐 Network configuration debugging disabled");
10431
+ logger4.info("🌐 Network configuration debugging disabled");
10666
10432
  }
10667
10433
  /**
10668
10434
  * Clear network debug data
@@ -10671,8 +10437,8 @@ var UnifiedDebugger = class _UnifiedDebugger {
10671
10437
  this.networkOverrides.clear();
10672
10438
  this.history = [];
10673
10439
  this.lastPresetChange = void 0;
10674
- if (this.enabled && typeof console !== "undefined") {
10675
- console.log("🗑️ Network configuration debug data cleared");
10440
+ if (this.enabled) {
10441
+ logger4.info("🗑️ Network configuration debug data cleared");
10676
10442
  }
10677
10443
  this.getDebugFactory().emitNetworkDataCleared();
10678
10444
  eventManager.debug.emitNetworkDataCleared();
@@ -10693,7 +10459,7 @@ var UnifiedDebugger = class _UnifiedDebugger {
10693
10459
  duration: config.duration
10694
10460
  });
10695
10461
  if (this.enabled && config.trigger) {
10696
- console.log(`🌐 Network override triggered by ${config.trigger}:`, {
10462
+ logger4.info(`🌐 Network override triggered by ${config.trigger}`, {
10697
10463
  property: config.property,
10698
10464
  value: config.overrideValue,
10699
10465
  reason: config.reason
@@ -11074,6 +10840,9 @@ function validateConfigUpdate(updates, options) {
11074
10840
  };
11075
10841
  }
11076
10842
  __name(validateConfigUpdate, "validateConfigUpdate");
10843
+ new ApiLogger({ service: LOGGER_SERVICES.CONFIG_QUEUE, transport: "console" });
10844
+ new ApiLogger({ service: LOGGER_SERVICES.QUEUE_ORCHESTRATOR, transport: "console" });
10845
+ var logger7 = new ApiLogger({ service: LOGGER_SERVICES.OPERATION_TRACKER, transport: "console" });
11077
10846
  var BaseOperationTracker = class {
11078
10847
  constructor(queueName, priorityDetector, sourceDetector) {
11079
10848
  this.queueName = queueName;
@@ -11138,7 +10907,10 @@ var BaseOperationTracker = class {
11138
10907
  try {
11139
10908
  await this.processor(op.data);
11140
10909
  } catch (error) {
11141
- console.error(`[${this.queueName}] Failed to process operation:`, error);
10910
+ logger7.error("Failed to process operation", {
10911
+ queueName: this.queueName,
10912
+ error: error instanceof Error ? error.message : String(error)
10913
+ });
11142
10914
  this.handleProcessingError(error, op.data);
11143
10915
  }
11144
10916
  }
@@ -11147,8 +10919,9 @@ var BaseOperationTracker = class {
11147
10919
  */
11148
10920
  handleProcessingError(error, operation) {
11149
10921
  if (isDev) {
11150
- console.debug(`[${this.queueName}] Error processing operation:`, {
11151
- error,
10922
+ logger7.debug("Error processing operation", {
10923
+ queueName: this.queueName,
10924
+ error: error instanceof Error ? error.message : String(error),
11152
10925
  operation: operation.operation,
11153
10926
  event: operation.event
11154
10927
  });
@@ -11227,6 +11000,14 @@ function createDefaultSourceDetector() {
11227
11000
  };
11228
11001
  }
11229
11002
  __name(createDefaultSourceDetector, "createDefaultSourceDetector");
11003
+ new ApiLogger({
11004
+ service: LOGGER_SERVICES.EVENT_QUEUE_MANAGER,
11005
+ transport: "console"
11006
+ });
11007
+ var logger9 = new ApiLogger({
11008
+ service: LOGGER_SERVICES.DEBUGGER_QUEUE_MANAGER,
11009
+ transport: "console"
11010
+ });
11230
11011
  var DebuggerQueueManager = class _DebuggerQueueManager {
11231
11012
  static {
11232
11013
  __name(this, "DebuggerQueueManager");
@@ -11298,7 +11079,9 @@ var DebuggerQueueManager = class _DebuggerQueueManager {
11298
11079
  }
11299
11080
  } catch (error) {
11300
11081
  if (isDev) {
11301
- console.warn("[DebuggerQueue] Operation failed:", error);
11082
+ logger9.warn("Operation failed", {
11083
+ error: error instanceof Error ? error.message : String(error)
11084
+ });
11302
11085
  }
11303
11086
  }
11304
11087
  }
@@ -11391,6 +11174,7 @@ var DebuggerQueueManager = class _DebuggerQueueManager {
11391
11174
  }
11392
11175
  };
11393
11176
  var MAX_RETRY_ATTEMPTS = 3;
11177
+ var logger10 = new ApiLogger({ service: LOGGER_SERVICES.OPERATION_TRACKER, transport: "console" });
11394
11178
  var OperationTracker = class _OperationTracker extends BaseOperationTracker {
11395
11179
  static {
11396
11180
  __name(this, "OperationTracker");
@@ -11454,7 +11238,12 @@ var OperationTracker = class _OperationTracker extends BaseOperationTracker {
11454
11238
  handleProcessingError(error, operation) {
11455
11239
  const retryCount = operation.retryCount ?? 0;
11456
11240
  if (operation.category === "debugging" && retryCount < MAX_RETRY_ATTEMPTS) {
11457
- console.warn(`[OperationTracker] Retrying critical operation (attempt ${retryCount + 1})`);
11241
+ logger10.warn("Retrying critical operation", {
11242
+ attempt: retryCount + 1,
11243
+ maxAttempts: MAX_RETRY_ATTEMPTS,
11244
+ operation: operation.operation,
11245
+ category: operation.category
11246
+ });
11458
11247
  this.getQueue().add({
11459
11248
  data: {
11460
11249
  ...operation,
@@ -11463,7 +11252,12 @@ var OperationTracker = class _OperationTracker extends BaseOperationTracker {
11463
11252
  priority: PRIORITY_LEVEL.CRITICAL
11464
11253
  });
11465
11254
  } else {
11466
- console.error(`[OperationTracker] Failed to process operation after retries:`, error);
11255
+ logger10.error("Failed to process operation after retries", {
11256
+ operation: operation.operation,
11257
+ category: operation.category,
11258
+ retryCount,
11259
+ error: error instanceof Error ? error.message : String(error)
11260
+ });
11467
11261
  }
11468
11262
  }
11469
11263
  /**
@@ -11546,6 +11340,7 @@ var trackingQueue = {
11546
11340
  return [];
11547
11341
  }
11548
11342
  };
11343
+ var logger11 = new ApiLogger({ service: LOGGER_SERVICES.PUB_SUB, transport: "console" });
11549
11344
  var EVENT_CONSTANTS = {
11550
11345
  /** Minimum event segments for scoped events (namespace:scope:event) */
11551
11346
  MIN_SCOPED_SEGMENTS: 2,
@@ -11651,7 +11446,10 @@ function createEmitMethod(listeners, trackOperation) {
11651
11446
  try {
11652
11447
  callback(data);
11653
11448
  } catch (error) {
11654
- console.error(`Error in event listener for ${event}:`, error);
11449
+ logger11.error("Event listener failed", {
11450
+ event,
11451
+ error: error instanceof Error ? error.message : String(error)
11452
+ });
11655
11453
  }
11656
11454
  });
11657
11455
  listeners.forEach((callbacks, pattern) => {
@@ -11664,7 +11462,11 @@ function createEmitMethod(listeners, trackOperation) {
11664
11462
  const wildcardData = typeof data === "object" && data !== null ? { ...data, originalEvent: event.split(":").pop() } : { data, originalEvent: event.split(":").pop() };
11665
11463
  callback(wildcardData);
11666
11464
  } catch (error) {
11667
- console.error(`Error in wildcard listener for ${event}:`, error);
11465
+ logger11.error("Wildcard listener failed", {
11466
+ event,
11467
+ pattern: prefix,
11468
+ error: error instanceof Error ? error.message : String(error)
11469
+ });
11668
11470
  }
11669
11471
  });
11670
11472
  }
@@ -11676,7 +11478,10 @@ function createEmitMethod(listeners, trackOperation) {
11676
11478
  try {
11677
11479
  callback(data);
11678
11480
  } catch (error) {
11679
- console.error(`Error in global wildcard listener for ${event}:`, error);
11481
+ logger11.error("Global wildcard listener failed", {
11482
+ event,
11483
+ error: error instanceof Error ? error.message : String(error)
11484
+ });
11680
11485
  }
11681
11486
  });
11682
11487
  }
@@ -11841,7 +11646,9 @@ function createEventEmitter() {
11841
11646
  result = handlerResult;
11842
11647
  }
11843
11648
  } catch (error) {
11844
- console.warn("Handler in chain failed:", error);
11649
+ logger11.warn("Handler in chain failed", {
11650
+ error: error instanceof Error ? error.message : String(error)
11651
+ });
11845
11652
  }
11846
11653
  }
11847
11654
  return result;
@@ -11911,858 +11718,239 @@ var EventHelpers = {
11911
11718
  return namespace ? [`${namespace}:*`] : [];
11912
11719
  }, "getMatchingWildcards")
11913
11720
  };
11721
+ var API_ERROR_NAMESPACE = "api";
11722
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
11914
11723
  var DEFAULT_SERVER_ERROR_STATUS2 = 500;
11915
- var DEFAULT_CLIENT_ERROR_STATUS = 400;
11916
- function getErrorEventType(errorEvent) {
11917
- return errorEvent.replace(/^errors:/, "");
11918
- }
11919
- __name(getErrorEventType, "getErrorEventType");
11920
- var ANY_ERROR_HANDLER = "onAnyError";
11921
- function mapHandlerNameToEventName(handlerName) {
11922
- if (handlerName === ANY_ERROR_HANDLER) {
11923
- return "*";
11724
+ var SCOPE_MAP = {
11725
+ GLOBAL: "global",
11726
+ CONFIG: "config",
11727
+ CLIENT: "client",
11728
+ REQUEST: "request",
11729
+ TEMPORARY: "temporary"
11730
+ };
11731
+ function convertToApiEventScope(scope) {
11732
+ const mapped = SCOPE_MAP[scope];
11733
+ if (!mapped) {
11734
+ throw new Error(`Invalid EventScope: ${scope}`);
11924
11735
  }
11925
- return handlerName.replace(/^on/, "").replace(/Error$/, "").replace(/([A-Z])/g, "-$1").toLowerCase().replace(/^-/, "");
11926
- }
11927
- __name(mapHandlerNameToEventName, "mapHandlerNameToEventName");
11928
- function registerScopedHandlers(scope, handlers, options = {}) {
11929
- Object.entries(handlers).forEach(([handlerName, handler]) => {
11930
- if (handler) {
11931
- const eventName = mapHandlerNameToEventName(handlerName);
11932
- const wrappedHandler = /* @__PURE__ */ __name((event) => {
11933
- const error = event?.data?.error ?? event;
11934
- try {
11935
- handler(error);
11936
- } catch (err) {
11937
- console.error("Error in error handler:", err);
11938
- }
11939
- }, "wrappedHandler");
11940
- eventManager.errors.addScopedHandler(HANDLER_SCOPES$1[scope], eventName, wrappedHandler, {
11941
- ...options,
11942
- originalHandler: handler
11943
- });
11944
- }
11945
- });
11736
+ return mapped;
11946
11737
  }
11947
- __name(registerScopedHandlers, "registerScopedHandlers");
11948
- function retrieveScopedHandlers(scope) {
11949
- const scopeKey = HANDLER_SCOPES$1[scope];
11950
- const originalHandlersMap = eventManager.errors.getOriginalScopedHandlers(scopeKey);
11951
- const result = {};
11952
- originalHandlersMap.forEach((handlers, eventName) => {
11953
- let handlerName;
11954
- if (eventName === "*") {
11955
- handlerName = "onAnyError";
11738
+ __name(convertToApiEventScope, "convertToApiEventScope");
11739
+ var ApiPackageError = class extends ApiPackageError$1 {
11740
+ static {
11741
+ __name(this, "ApiPackageError");
11742
+ }
11743
+ };
11744
+ var apiErrorEventFactory = {
11745
+ addScopedHandler(scope, eventName, handler, options) {
11746
+ const eventScope = convertToApiEventScope(scope);
11747
+ eventManager.errors.addScopedHandler(eventScope, eventName, handler, options);
11748
+ },
11749
+ removeScopedHandler(scope, eventName, handler) {
11750
+ const apiScope = convertToApiEventScope(scope);
11751
+ if (!handler) {
11752
+ eventManager.errors.removeAllScopedListeners(apiScope, eventName);
11956
11753
  } else {
11957
- const camelCase = eventName.replace(/-(.)/g, (_, c) => c.toUpperCase());
11958
- handlerName = `on${camelCase.charAt(0).toUpperCase() + camelCase.slice(1)}Error`;
11754
+ eventManager.errors.removeScopedHandler(apiScope, eventName, handler);
11959
11755
  }
11960
- if (handlers.length > 0) {
11961
- const key = handlerName;
11962
- result[key] = handlers[0];
11756
+ },
11757
+ getOriginalScopedHandlers(scope) {
11758
+ const eventScope = convertToApiEventScope(scope);
11759
+ return eventManager.errors.getOriginalScopedHandlers(eventScope);
11760
+ },
11761
+ emit(eventName, data, options) {
11762
+ if (options?.scopes && options.scopes.length > 0) {
11763
+ options.scopes.forEach((scope) => {
11764
+ const apiScope = convertToApiEventScope(scope);
11765
+ const scopedEventKey = `${apiScope}:errors:${eventName}`;
11766
+ eventManager.errors.emit(scopedEventKey, data);
11767
+ });
11768
+ } else {
11769
+ eventManager.errors.emit(eventName, data);
11963
11770
  }
11771
+ }
11772
+ };
11773
+ var isApiNamespaceRegistered = false;
11774
+ function ensureApiNamespaceRegistered() {
11775
+ if (isApiNamespaceRegistered) {
11776
+ return;
11777
+ }
11778
+ registerEventFactory(API_ERROR_NAMESPACE, apiErrorEventFactory);
11779
+ ApiPackageError$1.configure({
11780
+ namespace: API_ERROR_NAMESPACE,
11781
+ eventFactory: apiErrorEventFactory
11964
11782
  });
11965
- return result;
11783
+ isApiNamespaceRegistered = true;
11966
11784
  }
11967
- __name(retrieveScopedHandlers, "retrieveScopedHandlers");
11785
+ __name(ensureApiNamespaceRegistered, "ensureApiNamespaceRegistered");
11786
+ ensureApiNamespaceRegistered();
11968
11787
  function registerErrorHandler(eventType, handler, options = {}) {
11969
- const { scope = "GLOBAL", strategy = "merge" } = options;
11970
- const type = typeof eventType === "string" && eventType.startsWith("errors:") ? getErrorEventType(eventType) : eventType;
11971
- const wrappedHandler = /* @__PURE__ */ __name((event) => {
11972
- const error = event?.data?.error ?? event;
11973
- try {
11974
- handler(error);
11975
- } catch (err) {
11976
- console.error("Error in error handler:", err);
11977
- }
11978
- }, "wrappedHandler");
11979
- return eventManager.errors.addScopedHandler(
11980
- HANDLER_SCOPES$1[scope],
11981
- type,
11982
- wrappedHandler,
11983
- { strategy, originalHandler: handler }
11984
- );
11788
+ return registerErrorHandler$1(API_ERROR_NAMESPACE, eventType, handler, {
11789
+ ...options,
11790
+ eventFactory: apiErrorEventFactory
11791
+ });
11985
11792
  }
11986
11793
  __name(registerErrorHandler, "registerErrorHandler");
11794
+ function registerErrorHandlers(handlers, options = {}) {
11795
+ const { scope = "GLOBAL", ...rest } = options;
11796
+ registerScopedHandlers(API_ERROR_NAMESPACE, scope, handlers, {
11797
+ ...rest,
11798
+ eventFactory: apiErrorEventFactory
11799
+ });
11800
+ }
11801
+ __name(registerErrorHandlers, "registerErrorHandlers");
11987
11802
  function setErrorHandlers(handlers, scope = "GLOBAL") {
11988
- registerScopedHandlers(scope, handlers);
11803
+ setErrorHandlers$1(API_ERROR_NAMESPACE, handlers, scope, apiErrorEventFactory);
11989
11804
  }
11990
11805
  __name(setErrorHandlers, "setErrorHandlers");
11991
11806
  function getErrorHandlers(scope = "GLOBAL") {
11992
- return retrieveScopedHandlers(scope);
11807
+ return getErrorHandlers$1(API_ERROR_NAMESPACE, scope, apiErrorEventFactory);
11993
11808
  }
11994
11809
  __name(getErrorHandlers, "getErrorHandlers");
11995
- function registerErrorHandlers(handlers, options = {}) {
11996
- const { scope = "GLOBAL", strategy = "merge" } = options;
11997
- registerScopedHandlers(scope, handlers, { strategy });
11998
- }
11999
- __name(registerErrorHandlers, "registerErrorHandlers");
12000
11810
  function unregisterErrorHandlers(eventTypes, options = {}) {
12001
11811
  const { scope = "GLOBAL" } = options;
12002
- const scopeKey = HANDLER_SCOPES$1[scope];
12003
- if (!eventTypes) {
12004
- eventManager.errors.clearScopedHandlers(scopeKey);
12005
- } else {
12006
- eventTypes.forEach((eventType) => {
12007
- const type = typeof eventType === "string" && eventType.startsWith("errors:") ? getErrorEventType(eventType) : eventType;
12008
- eventManager.errors.removeAllScopedListeners(scopeKey, type);
12009
- });
12010
- }
11812
+ unregisterScopedHandlers(API_ERROR_NAMESPACE, scope, eventTypes, apiErrorEventFactory);
12011
11813
  }
12012
11814
  __name(unregisterErrorHandlers, "unregisterErrorHandlers");
12013
11815
  function clearErrorHandlers(options = {}) {
12014
- const { scopes = ["GLOBAL"] } = options;
12015
- scopes.forEach((scope) => {
12016
- const scopeKey = HANDLER_SCOPES$1[scope];
12017
- eventManager.errors.clearScopedHandlers(scopeKey);
11816
+ clearErrorHandlers$1(API_ERROR_NAMESPACE, {
11817
+ ...options,
11818
+ eventFactory: apiErrorEventFactory
12018
11819
  });
12019
11820
  }
12020
11821
  __name(clearErrorHandlers, "clearErrorHandlers");
12021
11822
  function onceErrorHandler(eventType, handler, options = {}) {
12022
- const { scope = "GLOBAL" } = options;
12023
- const type = typeof eventType === "string" && eventType.startsWith("errors:") ? getErrorEventType(eventType) : eventType;
12024
- eventManager.errors.onceScoped(HANDLER_SCOPES$1[scope], type, (event) => {
12025
- const eventData = event;
12026
- const error = eventData?.data?.error ?? event;
12027
- handler(error);
11823
+ registerOnceErrorHandler(API_ERROR_NAMESPACE, eventType, handler, {
11824
+ ...options,
11825
+ eventFactory: apiErrorEventFactory
12028
11826
  });
12029
11827
  }
12030
11828
  __name(onceErrorHandler, "onceErrorHandler");
12031
- var ERROR_EMITTERS = {
12032
- network: /* @__PURE__ */ __name((error) => {
12033
- eventManager.errors.emitNetworkError({
12034
- error,
12035
- url: error.context?.url,
12036
- method: error.context?.method,
12037
- status: error.statusCode,
12038
- retryable: error.context?.retryable
12039
- });
12040
- }, "network"),
12041
- validation: /* @__PURE__ */ __name((error) => {
12042
- eventManager.errors.emitValidationError({
12043
- error,
12044
- field: error.context?.field,
12045
- value: error.context?.value,
12046
- constraints: error.context?.constraints
12047
- });
12048
- }, "validation"),
12049
- authentication: /* @__PURE__ */ __name((error) => {
12050
- eventManager.errors.emitAuthenticationError(
12051
- error,
12052
- error.context?.realm,
12053
- error.context?.scheme
12054
- );
12055
- }, "authentication"),
12056
- rateLimit: /* @__PURE__ */ __name((error) => {
12057
- eventManager.errors.emitRateLimitError({
12058
- error,
12059
- limit: error.context?.limit,
12060
- remaining: error.context?.remaining,
12061
- resetAt: error.context?.resetAt,
12062
- retryAfter: error.context?.retryAfter
12063
- });
12064
- }, "rateLimit"),
12065
- server: /* @__PURE__ */ __name((error) => {
12066
- eventManager.errors.emitServerError({
12067
- error,
12068
- statusCode: error.statusCode ?? DEFAULT_SERVER_ERROR_STATUS2,
12069
- serverMessage: error.context?.serverMessage,
12070
- traceId: error.context?.traceId
12071
- });
12072
- }, "server"),
12073
- timeout: /* @__PURE__ */ __name((error) => {
12074
- eventManager.errors.emitTimeoutError({
12075
- error,
12076
- timeout: error.context?.timeoutMs || error.context?.timeout || 0,
12077
- operation: error.context?.operation,
12078
- url: error.context?.url
12079
- });
12080
- }, "timeout"),
12081
- authorization: /* @__PURE__ */ __name((error) => {
12082
- eventManager.errors.emitAuthorizationError({
12083
- error,
12084
- url: error.context?.url,
12085
- method: error.context?.method,
12086
- resource: void 0,
12087
- permission: void 0
12088
- });
12089
- }, "authorization"),
12090
- notFound: /* @__PURE__ */ __name((error) => {
12091
- eventManager.errors.emitNotFoundError(error, error.context?.url, void 0);
12092
- }, "notFound"),
12093
- conflict: /* @__PURE__ */ __name((error) => {
12094
- eventManager.errors.emitConflictError({
12095
- error,
12096
- conflictingResource: void 0,
12097
- currentValue: void 0,
12098
- attemptedValue: void 0
12099
- });
12100
- }, "conflict"),
12101
- client: /* @__PURE__ */ __name((error) => {
12102
- eventManager.errors.emitClientError({
12103
- error,
12104
- status: error.statusCode ?? DEFAULT_CLIENT_ERROR_STATUS,
12105
- url: error.context?.url,
12106
- method: error.context?.method
12107
- });
12108
- }, "client"),
12109
- externalService: /* @__PURE__ */ __name((error) => {
12110
- eventManager.errors.emitExternalServiceError({
12111
- error,
12112
- service: void 0,
12113
- endpoint: error.context?.url,
12114
- timeout: error.context?.timeout
12115
- });
12116
- }, "externalService"),
12117
- cache: /* @__PURE__ */ __name((error) => {
12118
- eventManager.errors.emitCacheError(
12119
- error,
12120
- error.context?.operation,
12121
- error.context && "cacheKey" in error.context ? error.context.cacheKey : "unknown"
12122
- );
12123
- }, "cache"),
12124
- headers: /* @__PURE__ */ __name((error) => {
12125
- eventManager.errors.emitHeadersError(error, void 0, error.context?.operation);
12126
- }, "headers"),
12127
- retry: /* @__PURE__ */ __name((error) => {
12128
- eventManager.errors.emitRetryError({
12129
- error,
12130
- attempts: void 0,
12131
- maxAttempts: void 0,
12132
- lastError: error.context?.originalError
12133
- });
12134
- }, "retry")
12135
- };
12136
- function getCategoryKey(category) {
12137
- if (!category) {
12138
- return "unknown";
12139
- }
12140
- return ERROR_CATEGORY_TO_EMITTER_KEY[category] || category.toLowerCase();
12141
- }
12142
- __name(getCategoryKey, "getCategoryKey");
12143
- async function emitErrorEvent(error) {
12144
- const categoryKey = getCategoryKey(error.category);
12145
- const emitter = ERROR_EMITTERS[categoryKey];
12146
- if (emitter) {
12147
- emitter(error);
12148
- } else {
12149
- eventManager.errors.emitGenericError(error);
12150
- }
12151
- }
12152
- __name(emitErrorEvent, "emitErrorEvent");
12153
-
12154
- // src/api/utils/generation/id-generator.ts
12155
- var ID_CONSTANTS = {
12156
- RANDOM_START_INDEX: 2,
12157
- DEFAULT_RANDOM_LENGTH: 8,
12158
- MAX_PREFIX_LENGTH: 10,
12159
- DEFAULT_RADIX: 36,
12160
- TWO_PARTS: 2
12161
- };
12162
- var DEFAULT_OPTIONS = {
12163
- prefix: "",
12164
- suffix: "",
12165
- useTimestamp: false,
12166
- separator: "_",
12167
- includeRandom: true,
12168
- radix: ID_CONSTANTS.DEFAULT_RADIX,
12169
- randomLength: ID_CONSTANTS.DEFAULT_RANDOM_LENGTH
12170
- };
12171
- function generateBaseId(options = {}) {
12172
- const opts = { ...DEFAULT_OPTIONS, ...options };
12173
- const components = [];
12174
- if (opts.prefix) {
12175
- components.push(opts.prefix);
12176
- }
12177
- if (opts.useTimestamp) {
12178
- const timestamp = Date.now().toString(opts.radix);
12179
- components.push(timestamp);
12180
- if (opts.includeRandom) {
12181
- const random = Math.random().toString(opts.radix).slice(
12182
- ID_CONSTANTS.RANDOM_START_INDEX,
12183
- ID_CONSTANTS.RANDOM_START_INDEX + opts.randomLength
12184
- );
12185
- components.push(random);
12186
- }
12187
- } else {
12188
- components.push(generateUUID());
12189
- }
12190
- if (opts.suffix) {
12191
- components.push(opts.suffix);
12192
- }
12193
- return components.join(opts.separator);
12194
- }
12195
- __name(generateBaseId, "generateBaseId");
12196
- function generateContextualId(context, options = {}) {
12197
- const baseId = generateBaseId(options);
12198
- const contextParts = [];
12199
- for (const [, value] of Object.entries(context)) {
12200
- if (value !== void 0) {
12201
- contextParts.push(String(value));
12202
- }
12203
- }
12204
- if (contextParts.length > 0) {
12205
- return `${contextParts.join(":")}:${baseId}`;
12206
- }
12207
- return baseId;
12208
- }
12209
- __name(generateContextualId, "generateContextualId");
12210
- function extractFromLastSeparator(id, separator) {
12211
- const lastIndex = id.lastIndexOf(separator);
12212
- return lastIndex !== -1 ? id.substring(lastIndex + 1) : null;
12213
- }
12214
- __name(extractFromLastSeparator, "extractFromLastSeparator");
12215
- function extractFromFirstSeparator(id, separator) {
12216
- const firstIndex = id.indexOf(separator);
12217
- return firstIndex !== -1 ? id.substring(0, firstIndex) : null;
12218
- }
12219
- __name(extractFromFirstSeparator, "extractFromFirstSeparator");
12220
- function extractAfterPrefix(id, separator) {
12221
- const firstIndex = id.indexOf(separator);
12222
- if (firstIndex === -1 || separator !== "_") {
12223
- return null;
12224
- }
12225
- const prefix = id.substring(0, firstIndex);
12226
- const isShortAlphabeticPrefix = prefix.length <= ID_CONSTANTS.MAX_PREFIX_LENGTH && /^[a-z]+$/i.test(prefix);
12227
- return isShortAlphabeticPrefix ? id.substring(firstIndex + 1) : null;
12228
- }
12229
- __name(extractAfterPrefix, "extractAfterPrefix");
12230
- function extractWithUnderscoreSeparator(id, separator) {
12231
- const afterPrefix = extractAfterPrefix(id, separator);
12232
- if (afterPrefix) {
12233
- return afterPrefix;
12234
- }
12235
- return extractFromLastSeparator(id, separator);
11829
+ function emitNetworkErrorEvent(error, context) {
11830
+ eventManager.errors.emitNetworkError({
11831
+ error,
11832
+ url: context?.url,
11833
+ method: context?.method,
11834
+ status: error.statusCode,
11835
+ retryable: error.retryable
11836
+ });
12236
11837
  }
12237
- __name(extractWithUnderscoreSeparator, "extractWithUnderscoreSeparator");
12238
- function extractBySeparatorType(id, separator) {
12239
- if (separator === ":") {
12240
- return extractFromLastSeparator(id, separator);
12241
- }
12242
- return extractWithUnderscoreSeparator(id, separator);
11838
+ __name(emitNetworkErrorEvent, "emitNetworkErrorEvent");
11839
+ function emitTimeoutErrorEvent(error, context) {
11840
+ eventManager.errors.emitTimeoutError({
11841
+ error,
11842
+ timeout: context?.timeout ?? context?.timeoutMs ?? DEFAULT_TIMEOUT_MS2,
11843
+ url: context?.url,
11844
+ operation: context?.operation
11845
+ });
12243
11846
  }
12244
- __name(extractBySeparatorType, "extractBySeparatorType");
12245
- function extractBaseId(id, options = {}) {
12246
- const { separator = ":", extractLast = true } = options;
12247
- if (!extractLast) {
12248
- return extractFromFirstSeparator(id, separator) ?? id;
12249
- }
12250
- return extractBySeparatorType(id, separator) ?? id;
11847
+ __name(emitTimeoutErrorEvent, "emitTimeoutErrorEvent");
11848
+ function emitServerErrorEvent(error, context) {
11849
+ eventManager.errors.emitServerError({
11850
+ error,
11851
+ statusCode: error.statusCode ?? DEFAULT_SERVER_ERROR_STATUS2,
11852
+ serverMessage: context?.serverMessage,
11853
+ traceId: context?.traceId
11854
+ });
12251
11855
  }
12252
- __name(extractBaseId, "extractBaseId");
12253
- function isUuidPattern(id) {
12254
- const uuidRegex = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
12255
- return uuidRegex.test(id);
11856
+ __name(emitServerErrorEvent, "emitServerErrorEvent");
11857
+ function emitAuthorizationErrorEvent(error, context) {
11858
+ eventManager.errors.emitAuthorizationError({
11859
+ error,
11860
+ url: context?.url,
11861
+ method: context?.method,
11862
+ resource: context?.resource,
11863
+ permission: context?.permission
11864
+ });
12256
11865
  }
12257
- __name(isUuidPattern, "isUuidPattern");
12258
- function isTimestampPattern(id) {
12259
- const timestampRegex = /^[a-z]+_[0-9a-z]+_[0-9a-z]+$/i;
12260
- return timestampRegex.test(id);
11866
+ __name(emitAuthorizationErrorEvent, "emitAuthorizationErrorEvent");
11867
+ function emitRateLimitErrorEvent(error, context) {
11868
+ eventManager.errors.emitRateLimitError({
11869
+ error,
11870
+ limit: context?.limit,
11871
+ remaining: context?.remaining,
11872
+ resetAt: context?.resetAt,
11873
+ retryAfter: context?.retryAfter
11874
+ });
12261
11875
  }
12262
- __name(isTimestampPattern, "isTimestampPattern");
12263
- function isPrefixedPattern(id) {
12264
- const prefixedRegex = /^[a-z]+_[0-9a-z-]+$/i;
12265
- return prefixedRegex.test(id);
11876
+ __name(emitRateLimitErrorEvent, "emitRateLimitErrorEvent");
11877
+ function emitValidationErrorEvent(error) {
11878
+ eventManager.errors.emitValidationError({
11879
+ error,
11880
+ field: void 0,
11881
+ value: void 0,
11882
+ constraints: void 0
11883
+ });
12266
11884
  }
12267
- __name(isPrefixedPattern, "isPrefixedPattern");
12268
- function isValidFallbackPattern(id) {
12269
- const fallbackRegex = /^[0-9a-z][\w-]*$/i;
12270
- if (!fallbackRegex.test(id)) {
12271
- return false;
12272
- }
12273
- const rejectList = ["invalid", "invalid-uuid"];
12274
- return !rejectList.includes(id);
11885
+ __name(emitValidationErrorEvent, "emitValidationErrorEvent");
11886
+ function emitAuthenticationErrorEvent(error, context) {
11887
+ eventManager.errors.emitAuthenticationError(
11888
+ error,
11889
+ context?.realm,
11890
+ context?.scheme
11891
+ );
12275
11892
  }
12276
- __name(isValidFallbackPattern, "isValidFallbackPattern");
12277
- function checkPatterns(id, patterns) {
12278
- for (const { check, allowed } of patterns) {
12279
- if (check(id)) {
12280
- return allowed;
12281
- }
11893
+ __name(emitAuthenticationErrorEvent, "emitAuthenticationErrorEvent");
11894
+ function emitNotFoundErrorEvent(error, context) {
11895
+ eventManager.errors.emitNotFoundError(error, context?.url);
11896
+ }
11897
+ __name(emitNotFoundErrorEvent, "emitNotFoundErrorEvent");
11898
+ var ERROR_CATEGORY_HANDLERS = {
11899
+ network: emitNetworkErrorEvent,
11900
+ validation: emitValidationErrorEvent,
11901
+ authentication: emitAuthenticationErrorEvent,
11902
+ authorization: emitAuthorizationErrorEvent,
11903
+ "rate.limit": emitRateLimitErrorEvent,
11904
+ timeout: emitTimeoutErrorEvent,
11905
+ "not.found": emitNotFoundErrorEvent,
11906
+ server: emitServerErrorEvent
11907
+ };
11908
+ function emitErrorEvent(error) {
11909
+ const context = error.context;
11910
+ const category = error.category?.toLowerCase();
11911
+ const handler = category ? ERROR_CATEGORY_HANDLERS[category] : void 0;
11912
+ if (handler) {
11913
+ handler(error, context);
11914
+ } else {
11915
+ eventManager.errors.emitGenericError(error);
12282
11916
  }
12283
- return null;
12284
- }
12285
- __name(checkPatterns, "checkPatterns");
12286
- function isAnyPatternAllowed(options) {
12287
- return !!(options.allowUuid ?? options.allowTimestamp ?? options.allowPrefix);
12288
11917
  }
12289
- __name(isAnyPatternAllowed, "isAnyPatternAllowed");
12290
- function checkIdPatterns(id, options) {
12291
- const patterns = [
12292
- { check: isUuidPattern, allowed: options.allowUuid },
12293
- { check: isTimestampPattern, allowed: options.allowTimestamp },
12294
- { check: isPrefixedPattern, allowed: options.allowPrefix }
12295
- ];
12296
- return checkPatterns(id, patterns);
12297
- }
12298
- __name(checkIdPatterns, "checkIdPatterns");
12299
- function validateIdWithPatterns(id, options) {
12300
- const patternResult = checkIdPatterns(id, options);
12301
- if (patternResult !== null) {
12302
- return patternResult;
12303
- }
12304
- return isAnyPatternAllowed(options) && isValidFallbackPattern(id);
11918
+ __name(emitErrorEvent, "emitErrorEvent");
11919
+
11920
+ // src/api/polling/utils.ts
11921
+ function isPollingActive(config) {
11922
+ return (config.interval ?? 0) > 0;
12305
11923
  }
12306
- __name(validateIdWithPatterns, "validateIdWithPatterns");
12307
- function isValidId(id, options = {}) {
12308
- const { allowUuid = true, allowTimestamp = true, allowPrefix = true, minLength = 5 } = options;
12309
- if (id.length < minLength) {
12310
- return false;
11924
+ __name(isPollingActive, "isPollingActive");
11925
+ function calculatePollingDuration(config) {
11926
+ if (!config.interval || !config.maxAttempts || config.maxAttempts <= 0) {
11927
+ return null;
12311
11928
  }
12312
- return validateIdWithPatterns(id, { allowUuid, allowTimestamp, allowPrefix });
11929
+ const intervals = config.interval * config.maxAttempts;
11930
+ const delays = (config.delay ?? 0) * config.maxAttempts;
11931
+ return intervals + delays;
12313
11932
  }
12314
- __name(isValidId, "isValidId");
12315
- function parseId(id, options = {}) {
12316
- const { separator = "_" } = options;
12317
- if (id.includes(":")) {
12318
- const lastColonIndex = id.lastIndexOf(":");
11933
+ __name(calculatePollingDuration, "calculatePollingDuration");
11934
+ function getSSRSafePollingConfig(config) {
11935
+ if (!isBrowser()) {
12319
11936
  return {
12320
- context: id.substring(0, lastColonIndex),
12321
- core: id.substring(lastColonIndex + 1),
12322
- full: id
11937
+ ...config,
11938
+ interval: 0,
11939
+ maxAttempts: 1
12323
11940
  };
12324
11941
  }
12325
- const parts = id.split(separator);
12326
- if (parts.length === 1) {
12327
- return { core: id, full: id };
12328
- }
12329
- if (parts.length === ID_CONSTANTS.TWO_PARTS) {
12330
- if (parts[0].length <= ID_CONSTANTS.MAX_PREFIX_LENGTH && /^[a-z]+$/i.test(parts[0])) {
12331
- return { prefix: parts[0], core: parts[1], full: id };
12332
- }
12333
- return { core: parts[0], suffix: parts[1], full: id };
12334
- }
12335
- return {
12336
- prefix: parts[0],
12337
- core: parts.slice(1, -1).join(separator),
12338
- suffix: parts[parts.length - 1],
12339
- full: id
12340
- };
11942
+ return config;
12341
11943
  }
12342
- __name(parseId, "parseId");
12343
- function createIdGenerator(defaultOptions = {}) {
12344
- return (options) => {
12345
- return generateBaseId({ ...defaultOptions, ...options });
12346
- };
12347
- }
12348
- __name(createIdGenerator, "createIdGenerator");
12349
- var correlationGenerators = /* @__PURE__ */ new Map();
12350
- function getCorrelationGenerator(type) {
12351
- if (!correlationGenerators.has(type)) {
12352
- correlationGenerators.set(
12353
- type,
12354
- createIdGenerator({
12355
- prefix: type,
12356
- useTimestamp: true,
12357
- includeRandom: true,
12358
- radix: 36,
12359
- randomLength: 8
12360
- })
12361
- );
12362
- }
12363
- return correlationGenerators.get(type);
12364
- }
12365
- __name(getCorrelationGenerator, "getCorrelationGenerator");
12366
- function generateCorrelationId(type = CORRELATION_TYPE.GENERIC, options) {
12367
- const generator = getCorrelationGenerator(type);
12368
- return generator(options);
12369
- }
12370
- __name(generateCorrelationId, "generateCorrelationId");
12371
- function generateContextualCorrelationId(context, type = CORRELATION_TYPE.GENERIC, options) {
12372
- return generateContextualId(context, {
12373
- prefix: type,
12374
- useTimestamp: true,
12375
- includeRandom: true,
12376
- radix: 36,
12377
- randomLength: 8,
12378
- ...options
12379
- });
12380
- }
12381
- __name(generateContextualCorrelationId, "generateContextualCorrelationId");
12382
- function generateNetworkCorrelationId(options) {
12383
- return generateCorrelationId(CORRELATION_TYPE.NETWORK, options);
12384
- }
12385
- __name(generateNetworkCorrelationId, "generateNetworkCorrelationId");
12386
- function generateApiCorrelationId(options) {
12387
- return generateCorrelationId(CORRELATION_TYPE.API, options);
12388
- }
12389
- __name(generateApiCorrelationId, "generateApiCorrelationId");
12390
- function generateSessionCorrelationId(options) {
12391
- return generateCorrelationId(CORRELATION_TYPE.SESSION, options);
12392
- }
12393
- __name(generateSessionCorrelationId, "generateSessionCorrelationId");
12394
- function generateTraceCorrelationId(options) {
12395
- return generateCorrelationId(CORRELATION_TYPE.TRACE, options);
12396
- }
12397
- __name(generateTraceCorrelationId, "generateTraceCorrelationId");
12398
- function extractBaseCorrelationId(contextualId) {
12399
- let id = extractBaseId(contextualId, { separator: ":", extractLast: true });
12400
- const prefixes = Object.values(CORRELATION_TYPE);
12401
- for (const prefix of prefixes) {
12402
- if (id.startsWith(`${prefix}_`)) {
12403
- id = id.substring(prefix.length + 1);
12404
- break;
12405
- }
12406
- }
12407
- return id;
12408
- }
12409
- __name(extractBaseCorrelationId, "extractBaseCorrelationId");
12410
- function extractCorrelationType(id) {
12411
- let idToCheck = id;
12412
- if (id.includes(":")) {
12413
- const parts = id.split(":");
12414
- idToCheck = parts[parts.length - 1];
12415
- }
12416
- const parsed = parseId(idToCheck, { separator: "_" });
12417
- if (parsed.prefix) {
12418
- const types = Object.values(CORRELATION_TYPE);
12419
- if (types.includes(parsed.prefix)) {
12420
- return parsed.prefix;
12421
- }
12422
- }
12423
- return void 0;
12424
- }
12425
- __name(extractCorrelationType, "extractCorrelationType");
12426
- function isValidCorrelationId(id) {
12427
- let idToValidate = id;
12428
- if (id.includes(":")) {
12429
- const parts = id.split(":");
12430
- idToValidate = parts[parts.length - 1];
12431
- }
12432
- return isValidId(idToValidate, {
12433
- allowUuid: true,
12434
- allowTimestamp: true,
12435
- allowPrefix: true,
12436
- minLength: 5
12437
- });
12438
- }
12439
- __name(isValidCorrelationId, "isValidCorrelationId");
12440
- function createCorrelationIdGenerator(type = CORRELATION_TYPE.GENERIC, defaultOptions = {}) {
12441
- return createIdGenerator({
12442
- prefix: type,
12443
- useTimestamp: true,
12444
- includeRandom: true,
12445
- radix: 36,
12446
- randomLength: 8,
12447
- ...defaultOptions
12448
- });
12449
- }
12450
- __name(createCorrelationIdGenerator, "createCorrelationIdGenerator");
12451
- function linkCorrelationIds(...ids) {
12452
- return ids.join("->");
12453
- }
12454
- __name(linkCorrelationIds, "linkCorrelationIds");
12455
- function extractLinkedCorrelationIds(linkedId) {
12456
- return linkedId.split("->");
12457
- }
12458
- __name(extractLinkedCorrelationIds, "extractLinkedCorrelationIds");
12459
-
12460
- // src/api/errors/ApiPackageError.ts
12461
- var ApiPackageError = class _ApiPackageError extends Error {
12462
- static {
12463
- __name(this, "ApiPackageError");
12464
- }
12465
- statusCode;
12466
- errorCode;
12467
- message;
12468
- errors;
12469
- correlationId;
12470
- timestamp;
12471
- // Additional properties beyond ErrorResponse
12472
- responseError;
12473
- category;
12474
- cause;
12475
- context;
12476
- // Store the original request/response data from fetchff (not Web API types)
12477
- requestConfig;
12478
- responseData;
12479
- details;
12480
- originalError;
12481
- metadata;
12482
- /**
12483
- * Getter for code property (alias for errorCode)
12484
- * Provides compatibility with standard error patterns
12485
- */
12486
- get code() {
12487
- return this.errorCode;
12488
- }
12489
- constructor(message, statusCode, errorCode = API_ERROR_CODES.UNKNOWN_ERROR, options) {
12490
- super(message);
12491
- this.name = "ApiPackageError";
12492
- this.message = message;
12493
- this.errorCode = errorCode;
12494
- this.timestamp = (/* @__PURE__ */ new Date()).toISOString();
12495
- this.statusCode = this.resolveStatusCode(statusCode, errorCode);
12496
- if (options) {
12497
- this.errors = options.errors;
12498
- this.correlationId = options.correlationId ?? generateApiCorrelationId();
12499
- this.responseError = options.responseError;
12500
- this.cause = options.cause;
12501
- this.context = options.context;
12502
- this.details = options.errors;
12503
- this.originalError = options.cause;
12504
- if (options.responseError) {
12505
- this.requestConfig = options.responseError.request;
12506
- this.responseData = options.responseError.response;
12507
- }
12508
- } else {
12509
- this.correlationId = generateApiCorrelationId();
12510
- }
12511
- this.category = this.categorizeError();
12512
- Object.setPrototypeOf(this, _ApiPackageError.prototype);
12513
- this.emitEvent();
12514
- }
12515
- /**
12516
- * Resolves the status code from the provided value or error definitions
12517
- */
12518
- resolveStatusCode(statusCode, errorCode) {
12519
- if (statusCode !== void 0) {
12520
- return statusCode;
12521
- }
12522
- const definition = ERROR_DEFINITIONS$1[errorCode];
12523
- if (definition?.status !== void 0) {
12524
- return definition.status;
12525
- }
12526
- return HTTP_STATUS.INTERNAL_SERVER_ERROR;
12527
- }
12528
- /**
12529
- * Emit error event for this error
12530
- * Can be called with a specific client context or uses global handlers
12531
- */
12532
- emitEvent() {
12533
- void Promise.resolve().then(() => emitErrorEvent(this)).catch(() => {
12534
- });
12535
- }
12536
- /**
12537
- * Creates an ApiPackageError from a fetchff ResponseError
12538
- */
12539
- static fromResponseError(responseError, config, clientContext) {
12540
- const statusCode = responseError.status ?? HTTP_STATUS.INTERNAL_SERVER_ERROR;
12541
- const message = responseError.message ?? "An error occurred";
12542
- const code = this.determineErrorCode(responseError);
12543
- return new _ApiPackageError(message, statusCode, code, {
12544
- responseError,
12545
- cause: responseError,
12546
- clientContext,
12547
- context: {
12548
- url: config?.url ?? "",
12549
- method: config?.method ?? "GET"
12550
- }
12551
- });
12552
- }
12553
- /**
12554
- * Creates an ApiPackageError from a standard Error
12555
- */
12556
- static fromError(error, statusCode, errorCode = API_ERROR_CODES.UNKNOWN_ERROR, context) {
12557
- if (error instanceof _ApiPackageError) {
12558
- return error;
12559
- }
12560
- const { code, status } = this.classifyError(error, errorCode, statusCode);
12561
- return new _ApiPackageError(error.message, status, code, {
12562
- cause: error,
12563
- clientContext: context
12564
- });
12565
- }
12566
- /**
12567
- * Classifies an error and returns appropriate code and status
12568
- */
12569
- static classifyError(error, defaultCode, defaultStatus) {
12570
- if (error.name === "NetworkError" || error.message.includes("network")) {
12571
- return { code: API_ERROR_CODES.NETWORK_ERROR, status: 0 };
12572
- }
12573
- if (error.name === "TimeoutError" || error.message.includes("timeout")) {
12574
- return { code: API_ERROR_CODES.REQUEST_TIMEOUT, status: HTTP_STATUS.REQUEST_TIMEOUT };
12575
- }
12576
- if (error.name === "AbortError") {
12577
- return { code: API_ERROR_CODES.REQUEST_ABORTED, status: 0 };
12578
- }
12579
- return { code: defaultCode, status: defaultStatus };
12580
- }
12581
- /**
12582
- * Determines appropriate error code from ResponseError by looking up status in ERROR_DEFINITIONS
12583
- */
12584
- static determineErrorCode(error) {
12585
- if ("isCancelled" in error && error.isCancelled) {
12586
- return API_ERROR_CODES.CLIENT_CANCELLED;
12587
- }
12588
- const status = error.status ?? 0;
12589
- const errorCode = getErrorCodeByStatus(status);
12590
- if (errorCode) {
12591
- return errorCode;
12592
- }
12593
- return this.getGenericErrorCode(status);
12594
- }
12595
- /**
12596
- * Gets a generic error code based on HTTP status range
12597
- */
12598
- static getGenericErrorCode(status) {
12599
- if (status === 0) {
12600
- return API_ERROR_CODES.NETWORK_ERROR;
12601
- }
12602
- if (status >= HTTP_STATUS.BAD_REQUEST && status < HTTP_STATUS.INTERNAL_SERVER_ERROR) {
12603
- return API_ERROR_CODES.CLIENT_ERROR;
12604
- }
12605
- if (status >= HTTP_STATUS.INTERNAL_SERVER_ERROR) {
12606
- return API_ERROR_CODES.SERVER_ERROR;
12607
- }
12608
- return API_ERROR_CODES.UNKNOWN_ERROR;
12609
- }
12610
- /**
12611
- * Gets the error category from ERROR_DEFINITIONS
12612
- */
12613
- categorizeError() {
12614
- const definition = ERROR_DEFINITIONS$1[this.errorCode];
12615
- return definition?.category ?? ERROR_CATEGORY.Unknown;
12616
- }
12617
- /**
12618
- * Checks if this is a specific category of error
12619
- */
12620
- isAuthError() {
12621
- return this.category === ERROR_CATEGORY.Authentication || this.category === ERROR_CATEGORY.Authorization;
12622
- }
12623
- isValidationError() {
12624
- return this.category === ERROR_CATEGORY.Validation;
12625
- }
12626
- isNetworkError() {
12627
- return this.category === ERROR_CATEGORY.Network;
12628
- }
12629
- isServerError() {
12630
- return this.category === ERROR_CATEGORY.Server;
12631
- }
12632
- isClientError() {
12633
- return this.statusCode >= HTTP_STATUS.BAD_REQUEST && this.statusCode < HTTP_STATUS.INTERNAL_SERVER_ERROR;
12634
- }
12635
- isRetryable() {
12636
- return this.category === ERROR_CATEGORY.Network || this.category === ERROR_CATEGORY.Server || this.category === ERROR_CATEGORY.Timeout || this.statusCode === HTTP_STATUS.TOO_MANY_REQUESTS || // Rate limit
12637
- this.statusCode >= HTTP_STATUS.INTERNAL_SERVER_ERROR;
12638
- }
12639
- /**
12640
- * Converts to ErrorResponse format (as per task-020)
12641
- */
12642
- toJSON() {
12643
- return {
12644
- statusCode: this.statusCode,
12645
- errorCode: this.errorCode,
12646
- message: this.message,
12647
- errors: this.errors ?? [],
12648
- correlationId: this.correlationId,
12649
- timestamp: this.timestamp
12650
- };
12651
- }
12652
- /**
12653
- * Creates a string representation
12654
- */
12655
- toString() {
12656
- return `[${this.errorCode}] ${this.message} (Status: ${this.statusCode}, Category: ${this.category})`;
12657
- }
12658
- /**
12659
- * Check if error is an ApiPackageError
12660
- */
12661
- static isApiPackageError(error) {
12662
- return error instanceof _ApiPackageError;
12663
- }
12664
- /**
12665
- * Get user-friendly message for display
12666
- */
12667
- getUserMessage() {
12668
- const customMessage = this.getCustomUserMessage();
12669
- if (customMessage) {
12670
- return customMessage;
12671
- }
12672
- return this.getDefaultUserMessage();
12673
- }
12674
- /**
12675
- * Gets custom user message from error details if available
12676
- */
12677
- getCustomUserMessage() {
12678
- if (!this.details?.length) {
12679
- return null;
12680
- }
12681
- const userMessage = this.details.find((d) => d.field === "userMessage");
12682
- return userMessage ? userMessage.message : null;
12683
- }
12684
- /**
12685
- * Gets default user message based on error category
12686
- */
12687
- getDefaultUserMessage() {
12688
- const messages = {
12689
- [ERROR_CATEGORY.Authentication]: "Authentication failed. Please check your credentials.",
12690
- [ERROR_CATEGORY.Authorization]: "You do not have permission to perform this action.",
12691
- [ERROR_CATEGORY.Validation]: "Please check your input and try again.",
12692
- [ERROR_CATEGORY.NotFound]: "The requested resource was not found.",
12693
- [ERROR_CATEGORY.RateLimit]: "Too many requests. Please try again later.",
12694
- [ERROR_CATEGORY.Network]: "Network error. Please check your connection.",
12695
- [ERROR_CATEGORY.Timeout]: "The request timed out. Please try again.",
12696
- [ERROR_CATEGORY.Server]: "Server error. Please try again later.",
12697
- [ERROR_CATEGORY.Client]: "Client error. Please check your request.",
12698
- [ERROR_CATEGORY.Blockchain]: "Blockchain error. Please try again later.",
12699
- [ERROR_CATEGORY.ExternalService]: "External service error. Please try again later.",
12700
- [ERROR_CATEGORY.Conflict]: "Conflict detected. Please resolve and try again.",
12701
- [ERROR_CATEGORY.Cache]: "Cache error. Please try again.",
12702
- [ERROR_CATEGORY.Headers]: "Headers error. Please check your request headers.",
12703
- [ERROR_CATEGORY.Retry]: "Retry limit exceeded. Please try again later.",
12704
- [ERROR_CATEGORY.Strategy]: "Strategy error. Invalid configuration.",
12705
- [ERROR_CATEGORY.Regional]: "Regional configuration error. Please check your region settings.",
12706
- [ERROR_CATEGORY.Unknown]: "An unexpected error occurred. Please try again later."
12707
- };
12708
- return messages[this.category] ?? "An unexpected error occurred. Please try again later.";
12709
- }
12710
- };
12711
-
12712
- // src/api/errors/error-codes.ts
12713
- var API_ERROR_CODES6 = {
12714
- // Client Configuration Errors
12715
- CLIENT_INITIALIZATION_FAILED: "CLIENT_INITIALIZATION_FAILED",
12716
- // Header Errors
12717
- HEADERS_ENRICHMENT_FAILED: "HEADERS_ENRICHMENT_FAILED",
12718
- // Polling Errors
12719
- POLLING_TIMEOUT: "POLLING_TIMEOUT",
12720
- POLLING_CANCELLED: "POLLING_CANCELLED"};
12721
- var PACKAGE_STATUS_CODES3 = {
12722
- // Internal system errors
12723
- INITIALIZATION_FAILED: 1040,
12724
- OPERATION_FAILED: 1041};
12725
-
12726
- // src/api/errors/types-constants.ts
12727
- var OPERATIONS3 = {
12728
- ENRICHMENT: "enrichment",
12729
- INITIALIZATION: "initialization",
12730
- POLLING: "polling"};
12731
-
12732
- // src/api/polling/utils.ts
12733
- function isPollingActive(config) {
12734
- return (config.interval ?? 0) > 0;
12735
- }
12736
- __name(isPollingActive, "isPollingActive");
12737
- function calculatePollingDuration(config) {
12738
- if (!config.interval || !config.maxAttempts || config.maxAttempts <= 0) {
12739
- return null;
12740
- }
12741
- const intervals = config.interval * config.maxAttempts;
12742
- const delays = (config.delay ?? 0) * config.maxAttempts;
12743
- return intervals + delays;
12744
- }
12745
- __name(calculatePollingDuration, "calculatePollingDuration");
12746
- function getSSRSafePollingConfig(config) {
12747
- if (!isBrowser()) {
12748
- return {
12749
- ...config,
12750
- interval: 0,
12751
- maxAttempts: 1
12752
- };
12753
- }
12754
- return config;
12755
- }
12756
- __name(getSSRSafePollingConfig, "getSSRSafePollingConfig");
12757
- function createProgressivePolling(options = {}) {
12758
- const { baseInterval = 1e3, maxInterval = 3e4, multiplier = 1.5 } = options;
12759
- return {
12760
- interval: baseInterval,
12761
- delay: 0,
12762
- maxAttempts: -1,
12763
- shouldStop: /* @__PURE__ */ __name((_response, attempt) => {
12764
- return false;
12765
- }, "shouldStop")
11944
+ __name(getSSRSafePollingConfig, "getSSRSafePollingConfig");
11945
+ function createProgressivePolling(options = {}) {
11946
+ const { baseInterval = 1e3, maxInterval = 3e4, multiplier = 1.5 } = options;
11947
+ return {
11948
+ interval: baseInterval,
11949
+ delay: 0,
11950
+ maxAttempts: -1,
11951
+ shouldStop: /* @__PURE__ */ __name((_response, attempt) => {
11952
+ return false;
11953
+ }, "shouldStop")
12766
11954
  };
12767
11955
  }
12768
11956
  __name(createProgressivePolling, "createProgressivePolling");
@@ -12779,11 +11967,11 @@ function createConditionalPolling(options) {
12779
11967
  if (options.errorCondition?.(response)) {
12780
11968
  new ApiPackageError(
12781
11969
  "polling.error_condition",
12782
- PACKAGE_STATUS_CODES3.OPERATION_FAILED,
12783
- API_ERROR_CODES6.POLLING_CANCELLED,
11970
+ INTERNAL_STATUS_CODES.OPERATION_FAILED,
11971
+ API_ERROR_CODES$1.POLLING_CANCELLED,
12784
11972
  {
12785
11973
  context: {
12786
- operation: OPERATIONS3.POLLING,
11974
+ operation: COMMON_OPERATIONS.POLLING,
12787
11975
  reason: "Error condition met",
12788
11976
  i18n: {
12789
11977
  reason: "error_condition"
@@ -12798,11 +11986,11 @@ function createConditionalPolling(options) {
12798
11986
  if (elapsed >= options.timeoutMs) {
12799
11987
  new ApiPackageError(
12800
11988
  "polling.timeout",
12801
- PACKAGE_STATUS_CODES3.OPERATION_FAILED,
12802
- API_ERROR_CODES6.POLLING_TIMEOUT,
11989
+ INTERNAL_STATUS_CODES.OPERATION_FAILED,
11990
+ API_ERROR_CODES$1.POLLING_TIMEOUT,
12803
11991
  {
12804
11992
  context: {
12805
- operation: OPERATIONS3.POLLING,
11993
+ operation: COMMON_OPERATIONS.POLLING,
12806
11994
  timeoutMs: options.timeoutMs,
12807
11995
  elapsed,
12808
11996
  i18n: {
@@ -13969,7 +13157,7 @@ function filterToFetchffProperties(config) {
13969
13157
  maxPollingAttempts,
13970
13158
  shouldStopPolling,
13971
13159
  fetcher,
13972
- logger,
13160
+ logger: logger19,
13973
13161
  // Cache properties
13974
13162
  cacheTime,
13975
13163
  staleTime,
@@ -14062,7 +13250,7 @@ function filterToFetchffProperties(config) {
14062
13250
  if (shouldStopPolling !== void 0 && shouldStopPolling !== null)
14063
13251
  fetchffConfig.shouldStopPolling = shouldStopPolling;
14064
13252
  if (fetcher !== void 0 && fetcher !== null) fetchffConfig.fetcher = fetcher;
14065
- if (logger !== void 0 && logger !== null) fetchffConfig.logger = logger;
13253
+ if (logger19 !== void 0 && logger19 !== null) fetchffConfig.logger = logger19;
14066
13254
  if (cacheTime !== void 0) fetchffConfig.cacheTime = cacheTime;
14067
13255
  if (staleTime !== void 0) fetchffConfig.staleTime = staleTime;
14068
13256
  if (skipCache !== void 0) fetchffConfig.skipCache = skipCache;
@@ -14439,11 +13627,33 @@ function trackGlobalConfigUpdate(params) {
14439
13627
  });
14440
13628
  }
14441
13629
  __name(trackGlobalConfigUpdate, "trackGlobalConfigUpdate");
13630
+ function handleGlobalErrorSystemConfig(errorConfig) {
13631
+ const alreadyInitialized = isErrorSystemInitialized();
13632
+ if (alreadyInitialized) {
13633
+ if (errorConfig.locale) {
13634
+ setErrorLocale(errorConfig.locale);
13635
+ }
13636
+ if (errorConfig.additionalCatalogs) {
13637
+ Object.entries(errorConfig.additionalCatalogs).forEach(([locale, catalog]) => {
13638
+ addMessageCatalog(locale, catalog, true);
13639
+ });
13640
+ }
13641
+ } else {
13642
+ initializeErrorSystem({
13643
+ defaultLocale: errorConfig.locale,
13644
+ additionalCatalogs: errorConfig.additionalCatalogs
13645
+ });
13646
+ }
13647
+ }
13648
+ __name(handleGlobalErrorSystemConfig, "handleGlobalErrorSystemConfig");
14442
13649
  function setGlobalConfig(config) {
14443
13650
  try {
14444
13651
  const startTime = Date.now();
14445
13652
  const currentConfig = globalApiConfig;
14446
13653
  validateConfigObject(config);
13654
+ if (config.errors) {
13655
+ handleGlobalErrorSystemConfig(config.errors);
13656
+ }
14447
13657
  const { merged: mergedConfig, entries: configEntries } = mergeGlobalConfig(
14448
13658
  currentConfig,
14449
13659
  config
@@ -14504,7 +13714,7 @@ function resetGlobalConfig() {
14504
13714
  activeScopes: eventManager.getActiveScopes?.() ?? []
14505
13715
  };
14506
13716
  globalApiConfig = {};
14507
- eventManager.setEventScopes([...EVENT_SCOPES]);
13717
+ eventManager.setEventScopes([...EVENT_SCOPES$1]);
14508
13718
  const afterEventState = {
14509
13719
  totalEvents: eventManager.getEventStats?.()?.totalEvents ?? 0,
14510
13720
  totalListeners: eventManager.getEventStats?.()?.totalListeners ?? 0,
@@ -14618,10 +13828,6 @@ var campaignEndpoints = {
14618
13828
  createCampaign: {
14619
13829
  url: "/campaigns",
14620
13830
  method: "POST"
14621
- // Example: Override global settings for this endpoint
14622
- // cancellable: true, // Cancel previous create requests
14623
- // timeout: 60000, // Longer timeout for creation
14624
- // retry: { attempts: 1 } // Don't retry POST requests
14625
13831
  },
14626
13832
  updateCampaign: {
14627
13833
  url: "/campaigns/:id",
@@ -14634,9 +13840,6 @@ var campaignEndpoints = {
14634
13840
  getCampaignStats: {
14635
13841
  url: "/campaigns/:id/stats",
14636
13842
  method: "GET"
14637
- // Example: Cache stats for longer
14638
- // cacheTime: 600, // Cache for 10 minutes
14639
- // staleTime: 1200 // Consider stale after 20 minutes
14640
13843
  },
14641
13844
  getCampaignParticipants: {
14642
13845
  url: "/campaigns/:id/participants",
@@ -14714,6 +13917,213 @@ var pollingEndpoints = {
14714
13917
  }
14715
13918
  };
14716
13919
 
13920
+ // src/api/endpoints/infobip.ts
13921
+ var infobipEmailEndpoints = {
13922
+ // ========== Outbound Email ==========
13923
+ /**
13924
+ * POST /email/3/send - Send email (simple, with attachment support)
13925
+ * Multipart/form-data for attachments
13926
+ */
13927
+ sendEmail: {
13928
+ url: "/email/3/send",
13929
+ method: "POST"
13930
+ },
13931
+ /**
13932
+ * POST /email/4/send - Send advanced email
13933
+ * JSON payload with full customization
13934
+ */
13935
+ sendAdvancedEmail: {
13936
+ url: "/email/4/messages",
13937
+ method: "POST"
13938
+ },
13939
+ /**
13940
+ * POST /email/3/mime - Send email via MIME format
13941
+ */
13942
+ sendEmailMime: {
13943
+ url: "/email/3/mime",
13944
+ method: "POST"
13945
+ },
13946
+ // ========== Email Validation ==========
13947
+ /**
13948
+ * POST /email/2/validation - Validate single email address
13949
+ */
13950
+ validateEmail: {
13951
+ url: "/email/2/validation",
13952
+ method: "POST"
13953
+ },
13954
+ /**
13955
+ * POST /email/2/validations - Bulk validate email addresses
13956
+ * Returns 202 with validation request ID
13957
+ */
13958
+ bulkValidateEmails: {
13959
+ url: "/email/2/validations",
13960
+ method: "POST"
13961
+ },
13962
+ /**
13963
+ * GET /email/2/validations - Get validation results
13964
+ * Retrieve bulk validation results with filtering
13965
+ */
13966
+ getValidations: {
13967
+ url: "/email/2/validations",
13968
+ method: "GET",
13969
+ cacheTime: 30,
13970
+ staleTime: 60
13971
+ },
13972
+ // ========== Logs & Reports ==========
13973
+ /**
13974
+ * GET /email/1/reports - Get email delivery reports
13975
+ */
13976
+ getEmailReports: {
13977
+ url: "/email/1/reports",
13978
+ method: "GET",
13979
+ cacheTime: 30,
13980
+ staleTime: 60
13981
+ },
13982
+ /**
13983
+ * GET /email/1/logs - Get email logs
13984
+ */
13985
+ getEmailLogs: {
13986
+ url: "/email/1/logs",
13987
+ method: "GET",
13988
+ cacheTime: 60,
13989
+ staleTime: 120
13990
+ },
13991
+ // ========== Scheduled Messages (Bulk Operations) ==========
13992
+ /**
13993
+ * GET /email/1/bulks - Get scheduled email bulks
13994
+ */
13995
+ getScheduledEmails: {
13996
+ url: "/email/1/bulks",
13997
+ method: "GET"
13998
+ },
13999
+ /**
14000
+ * GET /email/1/bulks/status - Get scheduled email statuses
14001
+ */
14002
+ getScheduledEmailStatuses: {
14003
+ url: "/email/1/bulks/status",
14004
+ method: "GET"
14005
+ },
14006
+ /**
14007
+ * PUT /email/1/bulks - Reschedule emails
14008
+ */
14009
+ rescheduleEmails: {
14010
+ url: "/email/1/bulks",
14011
+ method: "PUT"
14012
+ },
14013
+ /**
14014
+ * PUT /email/1/bulks/status - Update scheduled email statuses
14015
+ */
14016
+ updateScheduledEmailStatuses: {
14017
+ url: "/email/1/bulks/status",
14018
+ method: "PUT"
14019
+ }
14020
+ };
14021
+ var infobipEndpoints = {
14022
+ ...infobipEmailEndpoints
14023
+ };
14024
+
14025
+ // src/api/endpoints/virustotal.ts
14026
+ var virusTotalEndpoints = {
14027
+ // ========== File Scanning ==========
14028
+ /**
14029
+ * POST /files - Upload file for scanning
14030
+ * Multipart/form-data with file attachment
14031
+ * See official documentation for current free tier limits:
14032
+ * https://developers.virustotal.com/reference/overview#public-vs-premium-api
14033
+ *
14034
+ * @returns {object} response - Upload response with analysis ID
14035
+ * @returns {string} response.data.id - Analysis ID for polling results
14036
+ */
14037
+ uploadFileForScanning: {
14038
+ url: "/files",
14039
+ method: "POST"
14040
+ },
14041
+ /**
14042
+ * GET /analyses/{id} - Get analysis result
14043
+ * Retrieve scan results for previously uploaded file
14044
+ *
14045
+ * @param {string} id - Analysis ID from upload response
14046
+ * @returns {object} response - Analysis result with threat details
14047
+ */
14048
+ getAnalysisResult: {
14049
+ url: "/analyses/:id",
14050
+ method: "GET",
14051
+ cacheTime: 0
14052
+ // Don't cache scan results (they update)
14053
+ },
14054
+ // ========== Health & Info ==========
14055
+ /**
14056
+ * GET /version - Get API version info (health check)
14057
+ * Simple endpoint to verify API availability
14058
+ */
14059
+ getApiVersion: {
14060
+ url: "/version",
14061
+ method: "GET",
14062
+ cacheTime: 300,
14063
+ // Cache for 5 minutes
14064
+ staleTime: 600
14065
+ }
14066
+ };
14067
+ ({
14068
+ ...virusTotalEndpoints
14069
+ });
14070
+ var cloudflareEndpoints = {
14071
+ /**
14072
+ * POST /zones/{zoneId}/purge_cache - Purge files from cache
14073
+ * Purge specific files or all files in a zone
14074
+ * Rate limits may change; see official documentation for current limits:
14075
+ * https://developers.cloudflare.com/api/operations/zone-purge#rate-limits
14076
+ *
14077
+ * @param {string} zoneId - Cloudflare Zone ID
14078
+ * @returns {object} response - Purge result with success status
14079
+ */
14080
+ cloudflarePurgeCache: {
14081
+ url: "/zones/:zoneId/purge_cache",
14082
+ method: "POST",
14083
+ cacheTime: 0
14084
+ // Don't cache purge operations
14085
+ }
14086
+ };
14087
+ var cloudFrontEndpoints = {
14088
+ /**
14089
+ * POST /{apiVersion}/distribution/{distributionId}/invalidation - Create invalidation
14090
+ * Creates an invalidation batch for specified paths
14091
+ * Rate limits may change; see the official AWS documentation for current limits:
14092
+ * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html
14093
+ * Requires AWS Signature Version 4 authentication
14094
+ *
14095
+ * @param {string} distributionId - CloudFront Distribution ID
14096
+ * @returns {object} response - Invalidation result with ID and status
14097
+ */
14098
+ cloudFrontCreateInvalidation: {
14099
+ url: `/${AWS_CLOUDFRONT_CONFIG.API_VERSION}/distribution/:distributionId/invalidation`,
14100
+ method: "POST",
14101
+ cacheTime: 0
14102
+ }
14103
+ };
14104
+ var fastlyEndpoints = {
14105
+ /**
14106
+ * POST /service/{serviceId}/purge/{url} - Purge single URL
14107
+ * Instant soft-purge of specific URL
14108
+ * Rate limit: Unlimited soft-purges. Hard-purges are limited to 1000 requests per hour per service (as of 2024-06). See Fastly documentation for updates:
14109
+ * @see https://developer.fastly.com/reference/api/purging/#rate-limits
14110
+ *
14111
+ * @param {string} serviceId - Fastly Service ID
14112
+ * @param {string} url - URL to purge (URL-encoded)
14113
+ * @returns {object} response - Purge result with status
14114
+ */
14115
+ fastlyPurgeUrl: {
14116
+ url: "/service/:serviceId/purge/:url",
14117
+ method: "POST",
14118
+ cacheTime: 0
14119
+ }
14120
+ };
14121
+ var cdnEndpoints = {
14122
+ ...cloudflareEndpoints,
14123
+ ...cloudFrontEndpoints,
14124
+ ...fastlyEndpoints
14125
+ };
14126
+
14717
14127
  // src/api/endpoints/utils.ts
14718
14128
  function getEndpointUrl(name) {
14719
14129
  return endpoints[name].url;
@@ -14886,7 +14296,15 @@ __name(validatePathParams, "validatePathParams");
14886
14296
  var endpoints = {
14887
14297
  ...campaignEndpoints,
14888
14298
  // These are only examples for the polling, none of these endpoints doesnt exist yet
14889
- ...pollingEndpoints
14299
+ ...pollingEndpoints,
14300
+ // Infobip third-party provider endpoints (Email, SMS, WhatsApp)
14301
+ ...infobipEndpoints,
14302
+ // VirusTotal third-party provider endpoints (Virus/Malware scanning)
14303
+ ...virusTotalEndpoints,
14304
+ // CDN provider endpoints (Cloudflare, CloudFront, Fastly)
14305
+ ...cloudflareEndpoints,
14306
+ ...cloudFrontEndpoints,
14307
+ ...fastlyEndpoints
14890
14308
  };
14891
14309
  var isSlowConnection = isSlowConnection$1;
14892
14310
  function isNetworkAPISupported() {
@@ -18267,6 +17685,7 @@ async function prepareRequestConfigWithEnrichedHeaders(requestConfig, clientConf
18267
17685
  return config;
18268
17686
  }
18269
17687
  __name(prepareRequestConfigWithEnrichedHeaders, "prepareRequestConfigWithEnrichedHeaders");
17688
+ new ApiLogger({ service: LOGGER_SERVICES.EXPRESS_FRAMEWORK, transport: "console" });
18270
17689
  var networkDetectionMiddleware = /* @__PURE__ */ __name((req, res, next) => {
18271
17690
  const headerInfo = getNetworkInfoFromHeaders(req.headers);
18272
17691
  const networkInfo = {
@@ -18427,6 +17846,7 @@ __name(MinimumConnectionGuard, "MinimumConnectionGuard");
18427
17846
  MinimumConnectionGuard = __decorateClass([
18428
17847
  Injectable()
18429
17848
  ], MinimumConnectionGuard);
17849
+ var logger13 = new ApiLogger({ service: LOGGER_SERVICES.NESTJS_GUARD, transport: "console" });
18430
17850
  var EnrichedHeadersGuard = class {
18431
17851
  constructor(options = {}) {
18432
17852
  this.options = options;
@@ -18441,7 +17861,7 @@ var EnrichedHeadersGuard = class {
18441
17861
  for (const requiredHeader of requiredHeaders) {
18442
17862
  if (!enrichedHeaders[requiredHeader]) {
18443
17863
  if (debug) {
18444
- console.warn(`[EnrichedHeadersGuard] Missing required header: ${requiredHeader}`);
17864
+ logger13.warn("Missing required header", { requiredHeader });
18445
17865
  }
18446
17866
  return false;
18447
17867
  }
@@ -18458,7 +17878,7 @@ var EnrichedHeadersGuard = class {
18458
17878
  const complianceHeader = enrichedHeaders["x-compliance-required"];
18459
17879
  if (!complianceHeader) {
18460
17880
  if (debug) {
18461
- console.warn("[EnrichedHeadersGuard] No compliance information available");
17881
+ logger13.warn("No compliance information available");
18462
17882
  }
18463
17883
  return false;
18464
17884
  }
@@ -18468,7 +17888,7 @@ var EnrichedHeadersGuard = class {
18468
17888
  );
18469
17889
  if (!hasRequiredCompliance) {
18470
17890
  if (debug) {
18471
- console.warn("[EnrichedHeadersGuard] Required compliance not met:", {
17891
+ logger13.warn("Required compliance not met", {
18472
17892
  required: requiredCompliance,
18473
17893
  current: currentCompliance
18474
17894
  });
@@ -18482,7 +17902,7 @@ var EnrichedHeadersGuard = class {
18482
17902
  */
18483
17903
  async buildHeadersForRequest(request, enrichedOptions, debug) {
18484
17904
  if (debug) {
18485
- console.log("[EnrichedHeadersGuard] Processing request:", {
17905
+ logger13.debug("Processing request with enriched headers guard", {
18486
17906
  method: request.method,
18487
17907
  url: request.url,
18488
17908
  userAgent: request.headers["user-agent"]
@@ -18498,7 +17918,7 @@ var EnrichedHeadersGuard = class {
18498
17918
  };
18499
17919
  const enrichedHeaders = await buildEnrichedHeaders(requestContext, enrichedOptions);
18500
17920
  if (debug) {
18501
- console.log("[EnrichedHeadersGuard] Built headers:", enrichedHeaders);
17921
+ logger13.debug("Built enriched headers in guard", { enrichedHeaders });
18502
17922
  }
18503
17923
  return enrichedHeaders;
18504
17924
  }
@@ -18530,7 +17950,9 @@ var EnrichedHeadersGuard = class {
18530
17950
  */
18531
17951
  async handleBuildError(error, request, debug) {
18532
17952
  if (debug) {
18533
- console.error("[EnrichedHeadersGuard] Error building headers:", error);
17953
+ logger13.error("Error building headers in guard", {
17954
+ error: error instanceof Error ? error.message : String(error)
17955
+ });
18534
17956
  }
18535
17957
  new ApiPackageError(
18536
17958
  "nestjs.guard.enriched_headers_failed",
@@ -18578,6 +18000,7 @@ __name(EnrichedHeadersGuard, "EnrichedHeadersGuard");
18578
18000
  EnrichedHeadersGuard = __decorateClass([
18579
18001
  Injectable()
18580
18002
  ], EnrichedHeadersGuard);
18003
+ var logger14 = new ApiLogger({ service: LOGGER_SERVICES.NESTJS_INTERCEPTOR, transport: "console" });
18581
18004
  var EnrichedHeadersInterceptor = class {
18582
18005
  constructor(options = {}) {
18583
18006
  this.options = options;
@@ -18629,7 +18052,9 @@ var EnrichedHeadersInterceptor = class {
18629
18052
  */
18630
18053
  handleContextError(error, request, debug) {
18631
18054
  if (debug) {
18632
- console.error("[EnrichedHeadersInterceptor] Error in context:", error);
18055
+ logger14.error("Error in interceptor context", {
18056
+ error: error.message
18057
+ });
18633
18058
  }
18634
18059
  new ApiPackageError(
18635
18060
  "nestjs.interceptor.context_error",
@@ -18654,7 +18079,9 @@ var EnrichedHeadersInterceptor = class {
18654
18079
  */
18655
18080
  handleBuildError(error, request, next, debug) {
18656
18081
  if (debug) {
18657
- console.error("[EnrichedHeadersInterceptor] Error building headers:", error);
18082
+ logger14.error("Error building headers in interceptor", {
18083
+ error: error instanceof Error ? error.message : String(error)
18084
+ });
18658
18085
  }
18659
18086
  new ApiPackageError(
18660
18087
  "nestjs.interceptor.enriched_headers_failed",
@@ -18698,7 +18125,9 @@ var EnrichedHeadersInterceptor = class {
18698
18125
  */
18699
18126
  handleFallbackError(error, request, debug) {
18700
18127
  if (debug) {
18701
- console.error("[EnrichedHeadersInterceptor] Error in fallback context:", error);
18128
+ logger14.error("Error in fallback context", {
18129
+ error: error.message
18130
+ });
18702
18131
  }
18703
18132
  new ApiPackageError(
18704
18133
  "nestjs.interceptor.fallback_error",
@@ -18725,7 +18154,7 @@ var EnrichedHeadersInterceptor = class {
18725
18154
  const response = http.getResponse();
18726
18155
  try {
18727
18156
  if (debug) {
18728
- console.log("[EnrichedHeadersInterceptor] Processing request:", {
18157
+ logger14.debug("Processing request with enriched headers interceptor", {
18729
18158
  method: request.method,
18730
18159
  url: request.url,
18731
18160
  userAgent: request.headers["user-agent"]
@@ -18733,7 +18162,7 @@ var EnrichedHeadersInterceptor = class {
18733
18162
  }
18734
18163
  const enrichedHeaders = await this.buildHeaders(request, enrichedOptions);
18735
18164
  if (debug) {
18736
- console.log("[EnrichedHeadersInterceptor] Built headers:", enrichedHeaders);
18165
+ logger14.debug("Built enriched headers in interceptor", { enrichedHeaders });
18737
18166
  }
18738
18167
  if (storeInRequest) {
18739
18168
  request.enrichedHeaders = enrichedHeaders;
@@ -19458,65 +18887,6 @@ var NetworkPresetNames = {
19458
18887
  BACKGROUND_SYNC: "background-sync"
19459
18888
  };
19460
18889
 
19461
- // src/api/utils/generation/request-id.ts
19462
- var REQUEST_ID_CONSTANTS = {
19463
- PREFIX_LENGTH: 4
19464
- // Length of 'req_'
19465
- };
19466
- var requestIdGenerator = createIdGenerator({
19467
- prefix: "req",
19468
- useTimestamp: false
19469
- // Use UUID for request IDs for guaranteed uniqueness
19470
- });
19471
- function generateRequestId(options) {
19472
- return requestIdGenerator(options);
19473
- }
19474
- __name(generateRequestId, "generateRequestId");
19475
- function generateContextualRequestId(method, url, options) {
19476
- const context = {};
19477
- if (method || url) {
19478
- context.method = method ?? "UNKNOWN";
19479
- context.url = url ?? "UNKNOWN";
19480
- }
19481
- return generateContextualId(context, {
19482
- prefix: "req",
19483
- ...options
19484
- });
19485
- }
19486
- __name(generateContextualRequestId, "generateContextualRequestId");
19487
- function extractBaseRequestId(contextualId) {
19488
- let id = extractBaseId(contextualId, { separator: ":", extractLast: true });
19489
- if (id.startsWith("req_")) {
19490
- id = id.substring(REQUEST_ID_CONSTANTS.PREFIX_LENGTH);
19491
- }
19492
- return id;
19493
- }
19494
- __name(extractBaseRequestId, "extractBaseRequestId");
19495
- function isValidRequestId(id) {
19496
- return isValidId(id, {
19497
- allowUuid: true,
19498
- allowTimestamp: true,
19499
- allowPrefix: true,
19500
- minLength: 5
19501
- });
19502
- }
19503
- __name(isValidRequestId, "isValidRequestId");
19504
- function generateShortRequestId(options) {
19505
- return requestIdGenerator({
19506
- useTimestamp: true,
19507
- randomLength: 8,
19508
- ...options
19509
- });
19510
- }
19511
- __name(generateShortRequestId, "generateShortRequestId");
19512
- function createRequestIdGenerator(defaultOptions = {}) {
19513
- return createIdGenerator({
19514
- prefix: "req",
19515
- ...defaultOptions
19516
- });
19517
- }
19518
- __name(createRequestIdGenerator, "createRequestIdGenerator");
19519
-
19520
18890
  // src/api/utils/async-control.ts
19521
18891
  function debounce(func, delay) {
19522
18892
  let timeoutId;
@@ -19798,6 +19168,10 @@ function getAllMediaExtensions() {
19798
19168
  }
19799
19169
  __name(getAllMediaExtensions, "getAllMediaExtensions");
19800
19170
  var MEDIA_MIME_PREFIXES = ["image/", "video/", "audio/"];
19171
+ var logger15 = new ApiLogger({
19172
+ service: LOGGER_SERVICES.CLIENT_EVENT_MANAGER,
19173
+ transport: "console"
19174
+ });
19801
19175
  var EVENT_CONSTANTS2 = {
19802
19176
  DEBUG_INFO_INTERVAL_MULTIPLIER: 5,
19803
19177
  IMPACT_THRESHOLDS: {
@@ -19814,10 +19188,10 @@ var ClientEventManager = class _ClientEventManager {
19814
19188
  if (!this.config.configOverride) {
19815
19189
  this.config.configOverride = {
19816
19190
  // By default, client emits to all scopes (merged behavior)
19817
- eventScopes: [...EVENT_SCOPES]
19191
+ eventScopes: [...EVENT_SCOPES$1]
19818
19192
  };
19819
19193
  } else {
19820
- this.config.configOverride.eventScopes ??= [...EVENT_SCOPES];
19194
+ this.config.configOverride.eventScopes ??= [...EVENT_SCOPES$1];
19821
19195
  }
19822
19196
  eventManager.setEventScopes(this.config.configOverride.eventScopes);
19823
19197
  this.setupEventHandlers();
@@ -20010,7 +19384,9 @@ var ClientEventManager = class _ClientEventManager {
20010
19384
  const registeredHandlers = [];
20011
19385
  finalHandlers.forEach((h) => {
20012
19386
  if (typeof h !== "function") {
20013
- console.warn("Invalid handler provided - not a function:", h);
19387
+ logger15.warn("Invalid handler provided - not a function", {
19388
+ handlerType: typeof h
19389
+ });
20014
19390
  return;
20015
19391
  }
20016
19392
  const wrappedHandler = /* @__PURE__ */ __name((eventData) => {
@@ -20240,7 +19616,7 @@ var ClientEventManager = class _ClientEventManager {
20240
19616
  */
20241
19617
  setupEventScopes(updates, strategy) {
20242
19618
  updates.configOverride ??= {};
20243
- updates.configOverride.eventScopes ??= strategy === "temporary" ? ["request"] : [...EVENT_SCOPES];
19619
+ updates.configOverride.eventScopes ??= strategy === "temporary" ? ["request"] : [...EVENT_SCOPES$1];
20244
19620
  if (updates.configOverride?.eventScopes) {
20245
19621
  eventManager.setEventScopes(updates.configOverride.eventScopes);
20246
19622
  } else if (this.config.configOverride?.eventScopes) {
@@ -20527,10 +19903,20 @@ var ClientEventManager = class _ClientEventManager {
20527
19903
  return this.eventManager.getActiveScopes();
20528
19904
  }
20529
19905
  /**
20530
- * Emit error event (delegates to emitErrorEvent for consistency)
19906
+ * Emit error event at CLIENT scope
19907
+ *
19908
+ * Note: ApiPackageError instances automatically emit to ALL scopes when created.
19909
+ * This method emits specifically at CLIENT scope, useful for:
19910
+ * - Re-emitting errors that were caught and handled elsewhere
19911
+ * - Manual emission timing control
19912
+ * - Client-level error broadcasting
20531
19913
  */
20532
19914
  emitError(error) {
20533
- void emitErrorEvent(error);
19915
+ emitScopedErrorEvent(API_ERROR_NAMESPACE, error, {
19916
+ scopes: ["CLIENT"],
19917
+ eventFactory: apiErrorEventFactory,
19918
+ category: error.category
19919
+ });
20534
19920
  }
20535
19921
  /**
20536
19922
  * Emit request start event
@@ -20586,11 +19972,11 @@ function setupClientEvents(client, globalConfig, clientConfig) {
20586
19972
  if (!eventConfig.configOverride?.eventScopes) {
20587
19973
  if (!eventConfig.configOverride) {
20588
19974
  eventConfig.configOverride = {
20589
- eventScopes: [...EVENT_SCOPES]
19975
+ eventScopes: [...EVENT_SCOPES$1]
20590
19976
  // All scopes (merged)
20591
19977
  };
20592
19978
  } else {
20593
- eventConfig.configOverride.eventScopes = [...EVENT_SCOPES];
19979
+ eventConfig.configOverride.eventScopes = [...EVENT_SCOPES$1];
20594
19980
  }
20595
19981
  }
20596
19982
  const eventManager2 = new ClientEventManager(client, eventConfig);
@@ -21417,8 +20803,6 @@ function mergeHeaders(...headerSets) {
21417
20803
  return result;
21418
20804
  }
21419
20805
  __name(mergeHeaders, "mergeHeaders");
21420
-
21421
- // src/api/headers/headerBuilder.ts
21422
20806
  var HeaderBuilder = class {
21423
20807
  static {
21424
20808
  __name(this, "HeaderBuilder");
@@ -21653,7 +21037,7 @@ var HeaderBuilder = class {
21653
21037
  * ```
21654
21038
  */
21655
21039
  correlationId(id) {
21656
- this._headers["x-correlation-id"] = id ?? generateCorrelationId();
21040
+ this._headers["x-correlation-id"] = id ?? generateCorrelationId("req_correlation");
21657
21041
  return this;
21658
21042
  }
21659
21043
  /**
@@ -22992,10 +22376,9 @@ function hasEncryptableFields(requestConfig, config) {
22992
22376
  return targets.some((target) => hasMatchingFieldsInTarget(target, requestConfig, config));
22993
22377
  }
22994
22378
  __name(hasEncryptableFields, "hasEncryptableFields");
22995
-
22996
- // src/api/client/helpers/interceptors.ts
22997
22379
  var DEFAULT_MAX_RETRIES = 3;
22998
22380
  var DEFAULT_SUCCESS_STATUS = HTTP_STATUS.OK;
22381
+ var logger16 = new ApiLogger({ service: LOGGER_SERVICES.INTERCEPTORS, transport: "console" });
22999
22382
  function trackHeaderChanges(beforeHeaders, afterHeaders, interceptorIndex) {
23000
22383
  const changes = [];
23001
22384
  Object.entries(afterHeaders).forEach(([key, value]) => {
@@ -23055,7 +22438,27 @@ function createOnRetryHandler(handlers) {
23055
22438
  };
23056
22439
  }
23057
22440
  __name(createOnRetryHandler, "createOnRetryHandler");
23058
- function createOnRequestHandler(handlers, enrichedHeadersConfig, encryptionConfig) {
22441
+ function normalizeHeaders4(headers2) {
22442
+ const normalized = {};
22443
+ for (const [key, value] of Object.entries(headers2 || {})) {
22444
+ normalized[key.toLowerCase()] = value;
22445
+ }
22446
+ return normalized;
22447
+ }
22448
+ __name(normalizeHeaders4, "normalizeHeaders");
22449
+ function mergeHeadersCaseInsensitive(...headerSets) {
22450
+ const result = {};
22451
+ for (const headers2 of headerSets) {
22452
+ if (!headers2) continue;
22453
+ for (const [key, value] of Object.entries(headers2)) {
22454
+ const normalizedKey = key.toLowerCase();
22455
+ result[normalizedKey] = value;
22456
+ }
22457
+ }
22458
+ return result;
22459
+ }
22460
+ __name(mergeHeadersCaseInsensitive, "mergeHeadersCaseInsensitive");
22461
+ function createOnRequestHandler(handlers, enrichedHeadersConfig, encryptionConfig, configStrategy) {
23059
22462
  return async (config) => {
23060
22463
  const performanceFactory = getPerformanceEventFactory();
23061
22464
  const requestId = generateRequestId();
@@ -23079,12 +22482,28 @@ function createOnRequestHandler(handlers, enrichedHeadersConfig, encryptionConfi
23079
22482
  "enrichedHeaders",
23080
22483
  { requestId }
23081
22484
  );
23082
- processedConfig = {
23083
- ...processedConfig,
23084
- headers: enrichedHeaders
23085
- };
22485
+ const strategy = configStrategy;
22486
+ if (strategy === "replace") {
22487
+ processedConfig = {
22488
+ ...processedConfig,
22489
+ headers: normalizeHeaders4(enrichedHeaders)
22490
+ };
22491
+ } else {
22492
+ const mergedHeaders = mergeHeadersCaseInsensitive(
22493
+ enrichedHeaders,
22494
+ // Enriched headers (x-correlation-id, x-platform-type, etc.)
22495
+ config.headers
22496
+ // Existing headers (Authorization, Content-Type, etc.) - OVERRIDE enriched
22497
+ );
22498
+ processedConfig = {
22499
+ ...processedConfig,
22500
+ headers: mergedHeaders
22501
+ };
22502
+ }
23086
22503
  } catch (error) {
23087
- console.error("Failed to enrich headers:", error);
22504
+ logger16.error("Failed to enrich headers", {
22505
+ error: error instanceof Error ? error.message : String(error)
22506
+ });
23088
22507
  }
23089
22508
  }
23090
22509
  if (encryptionConfig?.enabled) {
@@ -23094,7 +22513,9 @@ function createOnRequestHandler(handlers, enrichedHeadersConfig, encryptionConfi
23094
22513
  processedConfig = await encryptionInterceptor(processedConfig);
23095
22514
  UnifiedDebugger.getInstance().trackConfigChange({ encryption: "applied" }, "encryption");
23096
22515
  } catch (error) {
23097
- console.error("Failed to encrypt request:", error);
22516
+ logger16.error("Failed to encrypt request", {
22517
+ error: error instanceof Error ? error.message : String(error)
22518
+ });
23098
22519
  }
23099
22520
  }
23100
22521
  if (handlers && handlers.length > 0) {
@@ -23134,7 +22555,9 @@ function createOnResponseHandler(handlers, clearTemporaryOverrides2, clearOnComp
23134
22555
  processedResponse = await decryptionInterceptor(processedResponse);
23135
22556
  UnifiedDebugger.getInstance().trackConfigChange({ decryption: "applied" }, "encryption");
23136
22557
  } catch (error) {
23137
- console.error("Failed to decrypt response:", error);
22558
+ logger16.error("Failed to decrypt response", {
22559
+ error: error instanceof Error ? error.message : String(error)
22560
+ });
23138
22561
  }
23139
22562
  }
23140
22563
  if (clearOnComplete && clearTemporaryOverrides2) {
@@ -23231,8 +22654,14 @@ function setupUnifiedHandlers(params) {
23231
22654
  );
23232
22655
  const clearOnComplete = mergedConfig.configOverride?.clearOnComplete ?? globalConfig?.configOverride?.clearOnComplete ?? clientOptions?.configOverride?.clearOnComplete;
23233
22656
  const encryptionConfig = mergedConfig.encryption ?? globalConfig?.encryption ?? clientOptions?.encryption;
22657
+ const configStrategy = mergedConfig.configOverride?.strategy ?? clientOptions?.configOverride?.strategy ?? globalConfig?.configOverride?.strategy ?? "merge";
23234
22658
  return {
23235
- onRequest: createOnRequestHandler(mergedOnRequest, enrichedHeadersConfig, encryptionConfig),
22659
+ onRequest: createOnRequestHandler(
22660
+ mergedOnRequest,
22661
+ enrichedHeadersConfig,
22662
+ encryptionConfig,
22663
+ configStrategy
22664
+ ),
23236
22665
  onResponse: createOnResponseHandler(
23237
22666
  mergedOnResponse,
23238
22667
  clearTemporaryOverrides2,
@@ -23244,13 +22673,12 @@ function setupUnifiedHandlers(params) {
23244
22673
  };
23245
22674
  }
23246
22675
  __name(setupUnifiedHandlers, "setupUnifiedHandlers");
23247
-
23248
- // src/api/client/createApiClient.ts
23249
22676
  var ID_GENERATION = {
23250
22677
  BASE: 36,
23251
22678
  SUBSTR_START: 2,
23252
22679
  SUBSTR_LENGTH: 9
23253
22680
  };
22681
+ var logger17 = new ApiLogger({ service: LOGGER_SERVICES.API_CLIENT, transport: "console" });
23254
22682
  function applyStrategies(config, options) {
23255
22683
  let resolvedConfig = config;
23256
22684
  if (options.unifiedStrategy) {
@@ -23280,12 +22708,11 @@ function applyStrategies(config, options) {
23280
22708
  );
23281
22709
  }
23282
22710
  });
23283
- console.warn(
23284
- `Individual strategies will override unified strategy settings. Unified strategy: ${options.unifiedStrategy}`,
22711
+ logger17.warn("Individual strategies override unified strategy", {
22712
+ unifiedStrategy: options.unifiedStrategy,
23285
22713
  individualStrategies,
23286
- "Conflicts detected and tracked in debug report",
23287
- debuggerInstance.getConflicts()
23288
- );
22714
+ conflictsCount: debuggerInstance.getConflicts().length
22715
+ });
23289
22716
  }
23290
22717
  }
23291
22718
  resolvedConfig = applyIndividualStrategies(resolvedConfig, options);
@@ -23316,12 +22743,12 @@ async function finalizeConfig(resolvedConfig, options) {
23316
22743
  } catch (error) {
23317
22744
  new ApiPackageError(
23318
22745
  "headers.processing.failed",
23319
- PACKAGE_STATUS_CODES3.OPERATION_FAILED,
23320
- API_ERROR_CODES6.HEADERS_ENRICHMENT_FAILED,
22746
+ INTERNAL_STATUS_CODES.OPERATION_FAILED,
22747
+ API_ERROR_CODES$1.HEADERS_ENRICHMENT_FAILED,
23321
22748
  {
23322
22749
  cause: error instanceof Error ? error : void 0,
23323
22750
  context: {
23324
- operation: OPERATIONS3.ENRICHMENT,
22751
+ operation: COMMON_OPERATIONS.ENRICHMENT,
23325
22752
  originalError: error instanceof Error ? error.message : String(error),
23326
22753
  i18n: {
23327
22754
  error: error instanceof Error ? error.message : String(error)
@@ -23362,12 +22789,12 @@ __name(applyDefaultOptions, "applyDefaultOptions");
23362
22789
  function handleClientInitError(error) {
23363
22790
  throw new ApiPackageError(
23364
22791
  "client.initialization.failed",
23365
- PACKAGE_STATUS_CODES3.INITIALIZATION_FAILED,
23366
- API_ERROR_CODES6.CLIENT_INITIALIZATION_FAILED,
22792
+ INTERNAL_STATUS_CODES.INITIALIZATION_FAILED,
22793
+ API_ERROR_CODES$1.CLIENT_INITIALIZATION_FAILED,
23367
22794
  {
23368
22795
  cause: error instanceof Error ? error : void 0,
23369
22796
  context: {
23370
- operation: OPERATIONS3.INITIALIZATION,
22797
+ operation: COMMON_OPERATIONS.INITIALIZATION,
23371
22798
  originalError: error instanceof Error ? error.message : String(error),
23372
22799
  i18n: {
23373
22800
  error: error instanceof Error ? error.message : String(error)
@@ -23478,7 +22905,9 @@ function analyzeConfigChanges(previousConfig, newConfig, updates) {
23478
22905
  }
23479
22906
  __name(analyzeConfigChanges, "analyzeConfigChanges");
23480
22907
  function handleInvalidConfigUpdate(validation, updates, updateOptions) {
23481
- console.warn("Invalid configuration update:", validation.errors);
22908
+ logger17.warn("Invalid configuration update", {
22909
+ errors: validation.errors
22910
+ });
23482
22911
  UnifiedDebugger.getInstance().trackEventOperation(
23483
22912
  EVENT_OPERATIONS.CONFIG_UPDATE_FAILED,
23484
22913
  "updateConfig",
@@ -23553,6 +22982,25 @@ function trackSuccessfulConfigUpdate(params) {
23553
22982
  );
23554
22983
  }
23555
22984
  __name(trackSuccessfulConfigUpdate, "trackSuccessfulConfigUpdate");
22985
+ function handleClientErrorSystemConfig(errorConfig) {
22986
+ const alreadyInitialized = isErrorSystemInitialized();
22987
+ if (alreadyInitialized) {
22988
+ if (errorConfig.locale) {
22989
+ setErrorLocale(errorConfig.locale);
22990
+ }
22991
+ if (errorConfig.additionalCatalogs) {
22992
+ Object.entries(errorConfig.additionalCatalogs).forEach(([locale, catalog]) => {
22993
+ addMessageCatalog(locale, catalog, true);
22994
+ });
22995
+ }
22996
+ } else {
22997
+ initializeErrorSystem({
22998
+ defaultLocale: errorConfig.locale,
22999
+ additionalCatalogs: errorConfig.additionalCatalogs
23000
+ });
23001
+ }
23002
+ }
23003
+ __name(handleClientErrorSystemConfig, "handleClientErrorSystemConfig");
23556
23004
  function createUpdateConfigMethod(initialConfigState, eventManager2, client, setConfigState) {
23557
23005
  let configState = initialConfigState;
23558
23006
  return (updates, updateOptions) => {
@@ -23562,6 +23010,9 @@ function createUpdateConfigMethod(initialConfigState, eventManager2, client, set
23562
23010
  if (updates.tracking) {
23563
23011
  applyTrackingConfiguration(updates);
23564
23012
  }
23013
+ if (updates.errors) {
23014
+ handleClientErrorSystemConfig(updates.errors);
23015
+ }
23565
23016
  const validation = validateConfigUpdate(updates, updateOptions);
23566
23017
  if (!validation.valid) {
23567
23018
  handleInvalidConfigUpdate(validation, updates, updateOptions);
@@ -23590,9 +23041,62 @@ function createUpdateConfigMethod(initialConfigState, eventManager2, client, set
23590
23041
  };
23591
23042
  }
23592
23043
  __name(createUpdateConfigMethod, "createUpdateConfigMethod");
23044
+ function createFetchffClient(fetchffConfig, effectiveConfig, options, unifiedHandlers) {
23045
+ return createApiFetcher({
23046
+ ...fetchffConfig,
23047
+ baseURL: effectiveConfig.baseURL ?? options.apiUrl,
23048
+ endpoints,
23049
+ onRequest: unifiedHandlers.onRequest,
23050
+ onResponse: unifiedHandlers.onResponse,
23051
+ onError: unifiedHandlers.onError,
23052
+ onRetry: unifiedHandlers.onRetry
23053
+ });
23054
+ }
23055
+ __name(createFetchffClient, "createFetchffClient");
23056
+ function enhanceClientWithMethods(params) {
23057
+ const {
23058
+ clientWithEvents,
23059
+ stateContainer,
23060
+ eventManager: eventManager2,
23061
+ client,
23062
+ clientId,
23063
+ globalConfig,
23064
+ options
23065
+ } = params;
23066
+ clientWithEvents.updateConfig = createUpdateConfigMethod(
23067
+ stateContainer.current,
23068
+ eventManager2,
23069
+ client,
23070
+ (newState) => {
23071
+ stateContainer.current = newState;
23072
+ }
23073
+ );
23074
+ clientWithEvents.getConfig = createGetConfigMethod(
23075
+ () => stateContainer.current,
23076
+ globalConfig,
23077
+ clientId,
23078
+ options
23079
+ );
23080
+ clientWithEvents.clearTemporaryOverrides = createClearTemporaryOverridesMethod(
23081
+ () => stateContainer.current,
23082
+ (newState) => {
23083
+ stateContainer.current = newState;
23084
+ },
23085
+ client,
23086
+ eventManager2
23087
+ );
23088
+ }
23089
+ __name(enhanceClientWithMethods, "enhanceClientWithMethods");
23090
+ function initializeClientSystems(options) {
23091
+ applyTrackingConfiguration(options);
23092
+ if (options.errors) {
23093
+ handleClientErrorSystemConfig(options.errors);
23094
+ }
23095
+ }
23096
+ __name(initializeClientSystems, "initializeClientSystems");
23593
23097
  async function createApiClient(options = {}) {
23594
23098
  try {
23595
- applyTrackingConfiguration(options);
23099
+ initializeClientSystems(options);
23596
23100
  UnifiedDebugger.getInstance().clear();
23597
23101
  options = applyDefaultOptions(options);
23598
23102
  const userConfig = createPreservedConfig(options);
@@ -23600,58 +23104,43 @@ async function createApiClient(options = {}) {
23600
23104
  const mergedConfig = await finalizeConfig(resolvedConfig, options);
23601
23105
  void UnifiedDebugger.getInstance().logConflicts();
23602
23106
  const globalConfig = getGlobalConfig();
23603
- let configState = createConfigState(mergedConfig);
23107
+ const stateContainer = {
23108
+ current: createConfigState(mergedConfig)
23109
+ };
23604
23110
  if (options.configOverride) {
23605
- const result = applyConfigOverride(configState, options.configOverride);
23606
- configState = result.state;
23111
+ const result = applyConfigOverride(stateContainer.current, options.configOverride);
23112
+ stateContainer.current = result.state;
23607
23113
  }
23608
- const effectiveConfig = getEffectiveConfig(configState);
23114
+ const effectiveConfig = getEffectiveConfig(stateContainer.current);
23609
23115
  const fetchffConfig = toFetchffConfig(effectiveConfig);
23610
23116
  let clearTemporaryOverridesFn;
23611
23117
  const unifiedHandlers = setupUnifiedHandlers({
23612
23118
  mergedConfig: effectiveConfig,
23613
- // Use effective config here too
23614
23119
  enrichedHeadersConfig: options.enrichedHeaders,
23615
23120
  globalConfig,
23616
23121
  clientOptions: options,
23617
23122
  clearTemporaryOverrides: /* @__PURE__ */ __name(() => clearTemporaryOverridesFn?.(), "clearTemporaryOverrides")
23618
23123
  });
23619
- const client = createApiFetcher({
23620
- ...fetchffConfig,
23621
- baseURL: effectiveConfig.baseURL ?? options.url,
23622
- endpoints,
23623
- // Use unified handlers that handle both ApiConfig callbacks and event emissions
23624
- onRequest: unifiedHandlers.onRequest,
23625
- onResponse: unifiedHandlers.onResponse,
23626
- onError: unifiedHandlers.onError,
23627
- onRetry: unifiedHandlers.onRetry
23628
- });
23124
+ const client = createFetchffClient(fetchffConfig, effectiveConfig, options, unifiedHandlers);
23629
23125
  const clientWithEvents = setupClientEvents(client, globalConfig, options);
23630
23126
  const { eventManager: eventManager2 } = clientWithEvents;
23127
+ Object.defineProperty(clientWithEvents, "then", {
23128
+ value: void 0,
23129
+ writable: false,
23130
+ enumerable: false,
23131
+ configurable: true
23132
+ });
23631
23133
  clearTemporaryOverridesFn = /* @__PURE__ */ __name(() => eventManager2.clearTemporaryOverrides(), "clearTemporaryOverridesFn");
23632
23134
  const clientId = emitClientCreatedEvent(effectiveConfig, options);
23633
- clientWithEvents.updateConfig = createUpdateConfigMethod(
23634
- configState,
23635
- eventManager2,
23135
+ enhanceClientWithMethods({
23136
+ clientWithEvents,
23137
+ stateContainer,
23138
+ eventManager: eventManager2,
23636
23139
  client,
23637
- (newState) => {
23638
- configState = newState;
23639
- }
23640
- );
23641
- clientWithEvents.getConfig = createGetConfigMethod(
23642
- () => configState,
23643
- globalConfig,
23644
23140
  clientId,
23141
+ globalConfig,
23645
23142
  options
23646
- );
23647
- clientWithEvents.clearTemporaryOverrides = createClearTemporaryOverridesMethod(
23648
- () => configState,
23649
- (newState) => {
23650
- configState = newState;
23651
- },
23652
- client,
23653
- eventManager2
23654
- );
23143
+ });
23655
23144
  if (options.networkAware?.enabled) {
23656
23145
  setupNetworkMonitoring(clientWithEvents, options, userConfig);
23657
23146
  }
@@ -23726,18 +23215,13 @@ function createApiQuery(serviceFn, defaultOptions) {
23726
23215
  __name(createApiQuery, "createApiQuery");
23727
23216
  function createApiMutation(serviceFn, defaultOptions) {
23728
23217
  return /* @__PURE__ */ __name(function useApiMutation(serviceOptions, mutationOptions) {
23729
- const mergedMutationOptions = deepMerge(
23730
- DEFAULT_MUTATION_OPTIONS,
23731
- defaultOptions ?? {},
23732
- mutationOptions ?? {},
23733
- {
23734
- mutationFn: /* @__PURE__ */ __name(async (variables) => {
23735
- const response = await serviceFn(variables, serviceOptions);
23736
- if (response.error) throw response.error;
23737
- return response.data;
23738
- }, "mutationFn")
23739
- }
23740
- );
23218
+ const mergedMutationOptions = deepMerge(DEFAULT_MUTATION_OPTIONS, defaultOptions ?? {}, mutationOptions ?? {}, {
23219
+ mutationFn: /* @__PURE__ */ __name(async (variables) => {
23220
+ const response = await serviceFn(variables, serviceOptions);
23221
+ if (response.error) throw response.error;
23222
+ return response.data;
23223
+ }, "mutationFn")
23224
+ });
23741
23225
  return useMutation(
23742
23226
  mergedMutationOptions
23743
23227
  );
@@ -24183,6 +23667,10 @@ function getEnhancedClientHints(headers2, options) {
24183
23667
  return response;
24184
23668
  }
24185
23669
  __name(getEnhancedClientHints, "getEnhancedClientHints");
23670
+ var logger18 = new ApiLogger({
23671
+ service: LOGGER_SERVICES.NETWORK_CONFIGURATION,
23672
+ transport: "console"
23673
+ });
24186
23674
  var NetworkConfigurationManager = class {
24187
23675
  static {
24188
23676
  __name(this, "NetworkConfigurationManager");
@@ -24248,9 +23736,11 @@ var NetworkConfigurationManager = class {
24248
23736
  */
24249
23737
  registerPreset(preset) {
24250
23738
  this.availablePresets.set(preset.id, preset);
24251
- console.log(
24252
- `📋 Registered network preset: ${preset.name} (${preset.id}) for ${preset.targetQuality} quality`
24253
- );
23739
+ logger18.info("Network preset registered", {
23740
+ presetName: preset.name,
23741
+ presetId: preset.id,
23742
+ targetQuality: preset.targetQuality
23743
+ });
24254
23744
  }
24255
23745
  /**
24256
23746
  * Get all available presets
@@ -24426,7 +23916,7 @@ var NetworkConfigurationManager = class {
24426
23916
  }
24427
23917
  });
24428
23918
  this.cleanupFunctions.push(unsubscribe);
24429
- console.log("🔄 Auto preset switching enabled");
23919
+ logger18.info("Auto preset switching enabled");
24430
23920
  }
24431
23921
  /**
24432
23922
  * Disable automatic preset monitoring
@@ -24435,7 +23925,7 @@ var NetworkConfigurationManager = class {
24435
23925
  this.monitoringEnabled = false;
24436
23926
  this.cleanupFunctions.forEach((cleanup) => cleanup());
24437
23927
  this.cleanupFunctions = [];
24438
- console.log("🔄 Auto preset switching disabled");
23928
+ logger18.info("Auto preset switching disabled");
24439
23929
  }
24440
23930
  /**
24441
23931
  * Get current active overrides for debugging
@@ -24449,7 +23939,7 @@ var NetworkConfigurationManager = class {
24449
23939
  restoreAllOverrides() {
24450
23940
  const overrides = Array.from(this.activeOverrides.values());
24451
23941
  overrides.forEach((override) => override.restore());
24452
- console.log(`🔄 Restored ${overrides.length} temporary overrides`);
23942
+ logger18.info("Restored temporary overrides", { count: overrides.length });
24453
23943
  }
24454
23944
  /**
24455
23945
  * Get configuration manager stats for debugging
@@ -24701,7 +24191,7 @@ var NetworkConfigurationManager = class {
24701
24191
  changes.push("caching");
24702
24192
  }
24703
24193
  if (changes.length > 0) {
24704
- console.log(`👤 User preferences updated: ${changes.join(", ")}`);
24194
+ logger18.info("User preferences updated", { changes });
24705
24195
  }
24706
24196
  }
24707
24197
  /**
@@ -25208,7 +24698,7 @@ function useOptimisticUpdate(key, initialData) {
25208
24698
  const nextState = {
25209
24699
  data: response.data,
25210
24700
  isValidating: response.isFetching ?? false,
25211
- error: response.error ?? void 0
24701
+ error: response.error
25212
24702
  };
25213
24703
  setState(nextState);
25214
24704
  });
@@ -25685,6 +25175,684 @@ function useDeleteCampaign(serviceOptions, mutationOptions) {
25685
25175
  })(serviceOptions, mutationOptions);
25686
25176
  }
25687
25177
  __name(useDeleteCampaign, "useDeleteCampaign");
25178
+ async function sendInfobipEmail(payload, options) {
25179
+ const client = options?.apiClient ?? getDefaultApiClient();
25180
+ if (!payload.from) {
25181
+ throw new ApiPackageError(
25182
+ "Missing required field: from",
25183
+ void 0,
25184
+ API_ERROR_CODES.REQUIRED_FIELD_MISSING
25185
+ );
25186
+ }
25187
+ if (!payload.to) {
25188
+ throw new ApiPackageError(
25189
+ "Missing required field: to",
25190
+ void 0,
25191
+ API_ERROR_CODES.REQUIRED_FIELD_MISSING
25192
+ );
25193
+ }
25194
+ if (!payload.subject) {
25195
+ throw new ApiPackageError(
25196
+ "Missing required field: subject",
25197
+ void 0,
25198
+ API_ERROR_CODES.REQUIRED_FIELD_MISSING
25199
+ );
25200
+ }
25201
+ const serviceDefaults = {
25202
+ retry: { attempts: 0 },
25203
+ timeout: 15e3
25204
+ // 15 second timeout for email sends
25205
+ };
25206
+ const mergedConfig = mergeConfigs(serviceDefaults, options?.apiConfig ?? {});
25207
+ const updateOptions = {
25208
+ strategy: "temporary",
25209
+ ...options?.updateConfigOptions
25210
+ };
25211
+ if (shouldApplyConfig(mergedConfig, updateOptions)) {
25212
+ client.updateConfig(mergedConfig, updateOptions);
25213
+ }
25214
+ return client.sendEmail({
25215
+ body: payload
25216
+ });
25217
+ }
25218
+ __name(sendInfobipEmail, "sendInfobipEmail");
25219
+ async function sendInfobipAdvancedEmail(payload, options) {
25220
+ const client = options?.apiClient ?? getDefaultApiClient();
25221
+ if (!payload.messages || payload.messages.length === 0) {
25222
+ throw new ApiPackageError(
25223
+ "Missing required field: messages (must be a non-empty array)",
25224
+ void 0,
25225
+ API_ERROR_CODES.REQUIRED_FIELD_MISSING
25226
+ );
25227
+ }
25228
+ for (const [index, message] of payload.messages.entries()) {
25229
+ if (!message.sender) {
25230
+ throw new ApiPackageError(
25231
+ `Missing required field: messages[${index}].sender`,
25232
+ void 0,
25233
+ API_ERROR_CODES.REQUIRED_FIELD_MISSING
25234
+ );
25235
+ }
25236
+ if (!message.destinations || message.destinations.length === 0) {
25237
+ throw new ApiPackageError(
25238
+ `Missing required field: messages[${index}].destinations (must be a non-empty array)`,
25239
+ void 0,
25240
+ API_ERROR_CODES.REQUIRED_FIELD_MISSING
25241
+ );
25242
+ }
25243
+ if (!message.content?.subject) {
25244
+ throw new ApiPackageError(
25245
+ `Missing required field: messages[${index}].content.subject`,
25246
+ void 0,
25247
+ API_ERROR_CODES.REQUIRED_FIELD_MISSING
25248
+ );
25249
+ }
25250
+ }
25251
+ const serviceDefaults = {
25252
+ retry: { attempts: 0 },
25253
+ timeout: 15e3
25254
+ // 15 second timeout for email sends
25255
+ };
25256
+ const mergedConfig = mergeConfigs(serviceDefaults, options?.apiConfig ?? {});
25257
+ const updateOptions = {
25258
+ strategy: "temporary",
25259
+ ...options?.updateConfigOptions
25260
+ };
25261
+ if (shouldApplyConfig(mergedConfig, updateOptions)) {
25262
+ client.updateConfig(mergedConfig, updateOptions);
25263
+ }
25264
+ return client.sendAdvancedEmail({
25265
+ body: payload
25266
+ });
25267
+ }
25268
+ __name(sendInfobipAdvancedEmail, "sendInfobipAdvancedEmail");
25269
+ async function validateInfobipEmail(email, options) {
25270
+ const client = options?.apiClient ?? getDefaultApiClient();
25271
+ const payload = typeof email === "string" ? { to: email } : email;
25272
+ if (!payload?.to) {
25273
+ throw new ApiPackageError(
25274
+ "Missing required field: to (email address)",
25275
+ void 0,
25276
+ API_ERROR_CODES.REQUIRED_FIELD_MISSING
25277
+ );
25278
+ }
25279
+ if (!payload.to.includes("@")) {
25280
+ throw new ApiPackageError(
25281
+ "Invalid email format: must contain @",
25282
+ void 0,
25283
+ API_ERROR_CODES.INVALID_FORMAT
25284
+ );
25285
+ }
25286
+ const serviceDefaults = {
25287
+ retry: { attempts: 2, delay: 500 },
25288
+ cacheTime: 300,
25289
+ // Cache validation results for 5 minutes
25290
+ staleTime: 600,
25291
+ // Consider stale after 10 minutes
25292
+ timeout: 5e3
25293
+ // 5 second timeout
25294
+ };
25295
+ const mergedConfig = mergeConfigs(serviceDefaults, options?.apiConfig ?? {});
25296
+ const updateOptions = {
25297
+ strategy: "temporary",
25298
+ ...options?.updateConfigOptions
25299
+ };
25300
+ if (shouldApplyConfig(mergedConfig, updateOptions)) {
25301
+ client.updateConfig(mergedConfig, updateOptions);
25302
+ }
25303
+ return client.validateEmail({
25304
+ body: payload
25305
+ });
25306
+ }
25307
+ __name(validateInfobipEmail, "validateInfobipEmail");
25308
+ async function bulkValidateInfobipEmails(payload, options) {
25309
+ const client = options?.apiClient ?? getDefaultApiClient();
25310
+ const MAX_BULK_EMAIL_VALIDATION_SIZE = 1e4;
25311
+ if (!payload.destinations || payload.destinations.length === 0) {
25312
+ throw new ApiPackageError(
25313
+ "Missing required field: destinations (must be a non-empty array)",
25314
+ void 0,
25315
+ API_ERROR_CODES.REQUIRED_FIELD_MISSING
25316
+ );
25317
+ }
25318
+ if (payload.destinations.length > MAX_BULK_EMAIL_VALIDATION_SIZE) {
25319
+ throw new ApiPackageError(
25320
+ `Too many email addresses: maximum ${MAX_BULK_EMAIL_VALIDATION_SIZE} per request`,
25321
+ void 0,
25322
+ API_ERROR_CODES.INVALID_FORMAT
25323
+ );
25324
+ }
25325
+ const serviceDefaults = {
25326
+ retry: { attempts: 0 },
25327
+ // Don't retry bulk validation requests
25328
+ timeout: 3e4
25329
+ // 30 second timeout for bulk operations
25330
+ };
25331
+ const mergedConfig = mergeConfigs(serviceDefaults, options?.apiConfig ?? {});
25332
+ const updateOptions = {
25333
+ strategy: "temporary",
25334
+ ...options?.updateConfigOptions
25335
+ };
25336
+ if (shouldApplyConfig(mergedConfig, updateOptions)) {
25337
+ client.updateConfig(mergedConfig, updateOptions);
25338
+ }
25339
+ return client.bulkValidateEmails({
25340
+ body: payload
25341
+ });
25342
+ }
25343
+ __name(bulkValidateInfobipEmails, "bulkValidateInfobipEmails");
25344
+
25345
+ // src/api/services/infobip/email/GET/fetchEmailReports.ts
25346
+ async function fetchInfobipEmailReports(params, options) {
25347
+ const client = options?.apiClient ?? getDefaultApiClient();
25348
+ const serviceDefaults = {
25349
+ cacheTime: 30,
25350
+ // Cache for 30 seconds
25351
+ staleTime: 60,
25352
+ // Consider stale after 1 minute
25353
+ timeout: 1e4
25354
+ // 10 second timeout
25355
+ };
25356
+ const mergedConfig = mergeConfigs(serviceDefaults, options?.apiConfig ?? {});
25357
+ const updateOptions = {
25358
+ strategy: "temporary",
25359
+ ...options?.updateConfigOptions
25360
+ };
25361
+ if (shouldApplyConfig(mergedConfig, updateOptions)) {
25362
+ client.updateConfig(mergedConfig, updateOptions);
25363
+ }
25364
+ return client.getEmailReports({
25365
+ params
25366
+ });
25367
+ }
25368
+ __name(fetchInfobipEmailReports, "fetchInfobipEmailReports");
25369
+
25370
+ // src/api/services/infobip/email/GET/fetchEmailLogs.ts
25371
+ async function fetchInfobipEmailLogs(params, options) {
25372
+ const client = options?.apiClient ?? getDefaultApiClient();
25373
+ const serviceDefaults = {
25374
+ cacheTime: 60,
25375
+ // Cache for 1 minute
25376
+ staleTime: 120,
25377
+ // Consider stale after 2 minutes
25378
+ timeout: 1e4
25379
+ // 10 second timeout
25380
+ };
25381
+ const mergedConfig = mergeConfigs(serviceDefaults, options?.apiConfig ?? {});
25382
+ const updateOptions = {
25383
+ strategy: "temporary",
25384
+ ...options?.updateConfigOptions
25385
+ };
25386
+ if (shouldApplyConfig(mergedConfig, updateOptions)) {
25387
+ client.updateConfig(mergedConfig, updateOptions);
25388
+ }
25389
+ return client.getEmailLogs({
25390
+ params
25391
+ });
25392
+ }
25393
+ __name(fetchInfobipEmailLogs, "fetchInfobipEmailLogs");
25394
+
25395
+ // src/api/services/infobip/email/GET/fetchScheduledEmails.ts
25396
+ async function fetchInfobipScheduledEmails(params, options) {
25397
+ const client = options?.apiClient ?? getDefaultApiClient();
25398
+ const serviceDefaults = {
25399
+ retry: { attempts: 2, delay: 500 },
25400
+ cacheTime: 30,
25401
+ staleTime: 60,
25402
+ timeout: 1e4
25403
+ };
25404
+ const mergedConfig = mergeConfigs(serviceDefaults, options?.apiConfig ?? {});
25405
+ const updateOptions = {
25406
+ strategy: "temporary",
25407
+ ...options?.updateConfigOptions
25408
+ };
25409
+ if (shouldApplyConfig(mergedConfig, updateOptions)) {
25410
+ client.updateConfig(mergedConfig, updateOptions);
25411
+ }
25412
+ return client.getScheduledEmails({
25413
+ params
25414
+ });
25415
+ }
25416
+ __name(fetchInfobipScheduledEmails, "fetchInfobipScheduledEmails");
25417
+
25418
+ // src/api/services/infobip/email/GET/fetchScheduledEmailStatuses.ts
25419
+ async function fetchInfobipScheduledEmailStatuses(params, options) {
25420
+ const client = options?.apiClient ?? getDefaultApiClient();
25421
+ const serviceDefaults = {
25422
+ retry: { attempts: 2, delay: 500 },
25423
+ cacheTime: 30,
25424
+ staleTime: 60,
25425
+ timeout: 1e4
25426
+ };
25427
+ const mergedConfig = mergeConfigs(serviceDefaults, options?.apiConfig ?? {});
25428
+ const updateOptions = {
25429
+ strategy: "temporary",
25430
+ ...options?.updateConfigOptions
25431
+ };
25432
+ if (shouldApplyConfig(mergedConfig, updateOptions)) {
25433
+ client.updateConfig(mergedConfig, updateOptions);
25434
+ }
25435
+ return client.getScheduledEmailStatuses({
25436
+ params
25437
+ });
25438
+ }
25439
+ __name(fetchInfobipScheduledEmailStatuses, "fetchInfobipScheduledEmailStatuses");
25440
+
25441
+ // src/api/services/infobip/email/GET/fetchValidations.ts
25442
+ async function fetchInfobipValidations(params, options) {
25443
+ const client = options?.apiClient ?? getDefaultApiClient();
25444
+ const serviceDefaults = {
25445
+ retry: { attempts: 2, delay: 500 },
25446
+ cacheTime: 60,
25447
+ // Cache results for 1 minute
25448
+ staleTime: 120,
25449
+ // Consider stale after 2 minutes
25450
+ timeout: 1e4
25451
+ // 10 second timeout
25452
+ };
25453
+ const mergedConfig = mergeConfigs(serviceDefaults, options?.apiConfig ?? {});
25454
+ const updateOptions = {
25455
+ strategy: "temporary",
25456
+ ...options?.updateConfigOptions
25457
+ };
25458
+ if (shouldApplyConfig(mergedConfig, updateOptions)) {
25459
+ client.updateConfig(mergedConfig, updateOptions);
25460
+ }
25461
+ return client.getValidations({
25462
+ params
25463
+ });
25464
+ }
25465
+ __name(fetchInfobipValidations, "fetchInfobipValidations");
25466
+ async function rescheduleInfobipEmails(params, payload, options) {
25467
+ const client = options?.apiClient ?? getDefaultApiClient();
25468
+ if (!payload.sendAt) {
25469
+ throw new ApiPackageError(
25470
+ "Missing required field: sendAt",
25471
+ void 0,
25472
+ API_ERROR_CODES.REQUIRED_FIELD_MISSING
25473
+ );
25474
+ }
25475
+ const serviceDefaults = {
25476
+ retry: { attempts: 1 },
25477
+ timeout: 1e4
25478
+ };
25479
+ const mergedConfig = mergeConfigs(serviceDefaults, options?.apiConfig ?? {});
25480
+ const updateOptions = {
25481
+ strategy: "temporary",
25482
+ ...options?.updateConfigOptions
25483
+ };
25484
+ if (shouldApplyConfig(mergedConfig, updateOptions)) {
25485
+ client.updateConfig(mergedConfig, updateOptions);
25486
+ }
25487
+ return client.rescheduleEmails({
25488
+ params,
25489
+ body: payload
25490
+ });
25491
+ }
25492
+ __name(rescheduleInfobipEmails, "rescheduleInfobipEmails");
25493
+ async function updateInfobipScheduledEmailStatuses(params, payload, options) {
25494
+ const client = options?.apiClient ?? getDefaultApiClient();
25495
+ if (!payload.status) {
25496
+ throw new ApiPackageError(
25497
+ "Missing required field: status",
25498
+ void 0,
25499
+ API_ERROR_CODES.REQUIRED_FIELD_MISSING
25500
+ );
25501
+ }
25502
+ if (payload.status !== "PAUSED" && payload.status !== "PROCESSING") {
25503
+ throw new ApiPackageError(
25504
+ "Invalid status: must be PAUSED or PROCESSING",
25505
+ void 0,
25506
+ API_ERROR_CODES.INVALID_FORMAT
25507
+ );
25508
+ }
25509
+ const serviceDefaults = {
25510
+ retry: { attempts: 1 },
25511
+ timeout: 1e4
25512
+ };
25513
+ const mergedConfig = mergeConfigs(serviceDefaults, options?.apiConfig ?? {});
25514
+ const updateOptions = {
25515
+ strategy: "temporary",
25516
+ ...options?.updateConfigOptions
25517
+ };
25518
+ if (shouldApplyConfig(mergedConfig, updateOptions)) {
25519
+ client.updateConfig(mergedConfig, updateOptions);
25520
+ }
25521
+ return client.updateScheduledEmailStatuses({
25522
+ params,
25523
+ body: payload
25524
+ });
25525
+ }
25526
+ __name(updateInfobipScheduledEmailStatuses, "updateInfobipScheduledEmailStatuses");
25527
+ async function uploadFileForScanning(payload, options) {
25528
+ const client = options?.apiClient ?? getDefaultApiClient();
25529
+ if (!payload.file) {
25530
+ throw new ApiPackageError(
25531
+ "Missing required field: file",
25532
+ void 0,
25533
+ API_ERROR_CODES.REQUIRED_FIELD_MISSING
25534
+ );
25535
+ }
25536
+ if (!payload.filename) {
25537
+ throw new ApiPackageError(
25538
+ "Missing required field: filename",
25539
+ void 0,
25540
+ API_ERROR_CODES.REQUIRED_FIELD_MISSING
25541
+ );
25542
+ }
25543
+ if (payload.file.length === 0) {
25544
+ throw new ApiPackageError(
25545
+ "File buffer cannot be empty",
25546
+ void 0,
25547
+ API_ERROR_CODES.INVALID_INPUT
25548
+ );
25549
+ }
25550
+ const serviceDefaults = {
25551
+ retry: { attempts: 2 },
25552
+ // Allow retries for network issues
25553
+ timeout: 6e4
25554
+ // 60 second timeout for file uploads
25555
+ };
25556
+ const mergedConfig = mergeConfigs(serviceDefaults, options?.apiConfig ?? {});
25557
+ const updateOptions = {
25558
+ strategy: "temporary",
25559
+ ...options?.updateConfigOptions
25560
+ };
25561
+ if (shouldApplyConfig(mergedConfig, updateOptions)) {
25562
+ client.updateConfig(mergedConfig, updateOptions);
25563
+ }
25564
+ const formData = new FormData();
25565
+ const blob = new Blob([new Uint8Array(payload.file)]);
25566
+ formData.append("file", blob, payload.filename);
25567
+ return client.uploadFileForScanning({
25568
+ body: formData
25569
+ });
25570
+ }
25571
+ __name(uploadFileForScanning, "uploadFileForScanning");
25572
+ async function getAnalysisResult(payload, options) {
25573
+ const client = options?.apiClient ?? getDefaultApiClient();
25574
+ if (!payload.analysisId) {
25575
+ throw new ApiPackageError(
25576
+ "Missing required field: analysisId",
25577
+ void 0,
25578
+ API_ERROR_CODES.REQUIRED_FIELD_MISSING
25579
+ );
25580
+ }
25581
+ const serviceDefaults = {
25582
+ retry: { attempts: 3 },
25583
+ // Allow retries for polling
25584
+ timeout: 3e4,
25585
+ // 30 second timeout
25586
+ cacheTime: 0
25587
+ // Don't cache (results change as scan progresses)
25588
+ };
25589
+ const mergedConfig = mergeConfigs(serviceDefaults, options?.apiConfig ?? {});
25590
+ const updateOptions = {
25591
+ strategy: "temporary",
25592
+ ...options?.updateConfigOptions
25593
+ };
25594
+ if (shouldApplyConfig(mergedConfig, updateOptions)) {
25595
+ client.updateConfig(mergedConfig, updateOptions);
25596
+ }
25597
+ return client.getAnalysisResult({
25598
+ params: { id: payload.analysisId }
25599
+ });
25600
+ }
25601
+ __name(getAnalysisResult, "getAnalysisResult");
25602
+ async function cloudflarePurgeCache(payload, options) {
25603
+ const client = options?.apiClient ?? getDefaultApiClient();
25604
+ if (!payload.zoneId) {
25605
+ throw new ApiPackageError(
25606
+ "Missing required field: zoneId",
25607
+ HTTP_STATUS.BAD_REQUEST,
25608
+ API_ERROR_CODES.CLOUDFLARE_ZONE_NOT_FOUND
25609
+ );
25610
+ }
25611
+ if (!payload.apiToken) {
25612
+ throw new ApiPackageError(
25613
+ "Missing required field: apiToken",
25614
+ HTTP_STATUS.UNAUTHORIZED,
25615
+ API_ERROR_CODES.CLOUDFLARE_AUTHENTICATION_FAILED
25616
+ );
25617
+ }
25618
+ if (!payload.files || payload.files.length === 0) {
25619
+ throw new ApiPackageError(
25620
+ "Missing required field: files (must be non-empty array)",
25621
+ HTTP_STATUS.BAD_REQUEST,
25622
+ API_ERROR_CODES.CLOUDFLARE_INVALID_URL
25623
+ );
25624
+ }
25625
+ const serviceDefaults = {
25626
+ retry: { attempts: 2 },
25627
+ timeout: 3e4
25628
+ // 30 seconds
25629
+ };
25630
+ const mergedConfig = mergeConfigs(serviceDefaults, options?.apiConfig ?? {});
25631
+ const updateOptions = {
25632
+ strategy: "temporary",
25633
+ ...options?.updateConfigOptions
25634
+ };
25635
+ if (shouldApplyConfig(mergedConfig, updateOptions)) {
25636
+ client.updateConfig(mergedConfig, updateOptions);
25637
+ }
25638
+ return client.cloudflarePurgeCache({
25639
+ params: { zoneId: payload.zoneId },
25640
+ headers: {
25641
+ Authorization: `Bearer ${payload.apiToken}`
25642
+ },
25643
+ body: {
25644
+ files: payload.files,
25645
+ zoneId: payload.zoneId,
25646
+ apiToken: payload.apiToken
25647
+ }
25648
+ });
25649
+ }
25650
+ __name(cloudflarePurgeCache, "cloudflarePurgeCache");
25651
+ function generateAWSSignatureV4(options) {
25652
+ const {
25653
+ accessKeyId,
25654
+ secretAccessKey,
25655
+ sessionToken,
25656
+ region,
25657
+ service,
25658
+ method,
25659
+ path,
25660
+ queryString = "",
25661
+ headers: headers2,
25662
+ payload,
25663
+ host
25664
+ } = options;
25665
+ const timestamp = options.timestamp ?? (/* @__PURE__ */ new Date()).toISOString().replace(/[:-]|\.\d{3}/g, "");
25666
+ const dateStamp = timestamp.split("T")[0];
25667
+ const baseHeaders = { ...headers2 };
25668
+ if (!Object.keys(baseHeaders).some((h) => h.toLowerCase() === "host")) {
25669
+ baseHeaders["Host"] = host;
25670
+ }
25671
+ if (sessionToken) {
25672
+ baseHeaders["X-Amz-Security-Token"] = sessionToken;
25673
+ }
25674
+ baseHeaders["X-Amz-Date"] = timestamp;
25675
+ const canonicalHeaders = Object.keys(baseHeaders).sort().map((key) => `${key.toLowerCase()}:${baseHeaders[key].trim()}`).join("\n");
25676
+ const signedHeaders = Object.keys(baseHeaders).sort().map((key) => key.toLowerCase()).join(";");
25677
+ const payloadHash = crypto2.createHash("sha256").update(payload).digest("hex");
25678
+ const canonicalRequest = [
25679
+ method,
25680
+ path,
25681
+ queryString,
25682
+ canonicalHeaders + "\n",
25683
+ signedHeaders,
25684
+ payloadHash
25685
+ ].join("\n");
25686
+ const algorithm = "AWS4-HMAC-SHA256";
25687
+ const credentialScope = `${dateStamp}/${region}/${service}/aws4_request`;
25688
+ const canonicalRequestHash = crypto2.createHash("sha256").update(canonicalRequest).digest("hex");
25689
+ const stringToSign = [algorithm, timestamp, credentialScope, canonicalRequestHash].join("\n");
25690
+ const kDate = crypto2.createHmac("sha256", `AWS4${secretAccessKey}`).update(dateStamp).digest();
25691
+ const kRegion = crypto2.createHmac("sha256", kDate).update(region).digest();
25692
+ const kService = crypto2.createHmac("sha256", kRegion).update(service).digest();
25693
+ const kSigning = crypto2.createHmac("sha256", kService).update("aws4_request").digest();
25694
+ const signature = crypto2.createHmac("sha256", kSigning).update(stringToSign).digest("hex");
25695
+ const authorization = `${algorithm} Credential=${accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
25696
+ return {
25697
+ headers: baseHeaders,
25698
+ authorization
25699
+ };
25700
+ }
25701
+ __name(generateAWSSignatureV4, "generateAWSSignatureV4");
25702
+
25703
+ // src/api/utils/aws/xml/cloudfront.ts
25704
+ function generateCloudFrontInvalidationXML(paths, callerReference) {
25705
+ const items = paths.map((path) => `<Path>${escapeXml(path)}</Path>`).join("\n ");
25706
+ return `<?xml version="1.0" encoding="UTF-8"?>
25707
+ <InvalidationBatch xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
25708
+ <Paths>
25709
+ <Quantity>${paths.length}</Quantity>
25710
+ <Items>
25711
+ ${items}
25712
+ </Items>
25713
+ </Paths>
25714
+ <CallerReference>${escapeXml(callerReference)}</CallerReference>
25715
+ </InvalidationBatch>`;
25716
+ }
25717
+ __name(generateCloudFrontInvalidationXML, "generateCloudFrontInvalidationXML");
25718
+ function escapeXml(str) {
25719
+ const xmlEscapes = {
25720
+ "&": "&amp;",
25721
+ "<": "&lt;",
25722
+ ">": "&gt;",
25723
+ '"': "&quot;",
25724
+ "'": "&apos;"
25725
+ };
25726
+ return str.replace(/[&<>"']/g, (ch) => xmlEscapes[ch]);
25727
+ }
25728
+ __name(escapeXml, "escapeXml");
25729
+ function generateCloudFrontCallerReference(prefix = "api") {
25730
+ return `${prefix}-${Date.now()}`;
25731
+ }
25732
+ __name(generateCloudFrontCallerReference, "generateCloudFrontCallerReference");
25733
+
25734
+ // src/api/services/cdn/cloudfront/POST/cloudFrontCreateInvalidation.ts
25735
+ async function cloudFrontCreateInvalidation(payload, options) {
25736
+ const client = options?.apiClient ?? getDefaultApiClient();
25737
+ if (!payload.distributionId) {
25738
+ throw new ApiPackageError(
25739
+ "Missing required field: distributionId",
25740
+ HTTP_STATUS.BAD_REQUEST,
25741
+ API_ERROR_CODES.CLOUDFRONT_DISTRIBUTION_NOT_FOUND
25742
+ );
25743
+ }
25744
+ if (!payload.accessKeyId) {
25745
+ throw new ApiPackageError(
25746
+ "Missing required field: accessKeyId",
25747
+ HTTP_STATUS.UNAUTHORIZED,
25748
+ API_ERROR_CODES.CLOUDFRONT_AUTHENTICATION_FAILED
25749
+ );
25750
+ }
25751
+ if (!payload.secretAccessKey) {
25752
+ throw new ApiPackageError(
25753
+ "Missing required field: secretAccessKey",
25754
+ HTTP_STATUS.UNAUTHORIZED,
25755
+ API_ERROR_CODES.CLOUDFRONT_AUTHENTICATION_FAILED
25756
+ );
25757
+ }
25758
+ if (!payload.paths || payload.paths.length === 0) {
25759
+ throw new ApiPackageError(
25760
+ "Missing required field: paths (must be non-empty array)",
25761
+ HTTP_STATUS.BAD_REQUEST,
25762
+ API_ERROR_CODES.CLOUDFRONT_INVALID_PATH
25763
+ );
25764
+ }
25765
+ const region = payload.region ?? AWS_CLOUDFRONT_CONFIG.DEFAULT_REGION;
25766
+ const service = AWS_CLOUDFRONT_CONFIG.SERVICE_NAME;
25767
+ const host = AWS_CLOUDFRONT_CONFIG.HOST;
25768
+ const method = "POST";
25769
+ const path = `/${AWS_CLOUDFRONT_CONFIG.API_VERSION}/distribution/${payload.distributionId}/invalidation`;
25770
+ const callerReference = generateCloudFrontCallerReference("api");
25771
+ const body = generateCloudFrontInvalidationXML(payload.paths, callerReference);
25772
+ const { headers: signedHeaders, authorization } = generateAWSSignatureV4({
25773
+ accessKeyId: payload.accessKeyId,
25774
+ secretAccessKey: payload.secretAccessKey,
25775
+ sessionToken: payload.sessionToken,
25776
+ region,
25777
+ service,
25778
+ method,
25779
+ path,
25780
+ host,
25781
+ headers: {
25782
+ "Content-Type": "application/xml"
25783
+ },
25784
+ payload: body
25785
+ });
25786
+ const serviceDefaults = {
25787
+ retry: { attempts: 2 },
25788
+ timeout: 3e4
25789
+ // 30 seconds
25790
+ };
25791
+ const mergedConfig = mergeConfigs(serviceDefaults, options?.apiConfig ?? {});
25792
+ const updateOptions = {
25793
+ strategy: "temporary",
25794
+ ...options?.updateConfigOptions
25795
+ };
25796
+ if (shouldApplyConfig(mergedConfig, updateOptions)) {
25797
+ client.updateConfig(mergedConfig, updateOptions);
25798
+ }
25799
+ return client.cloudFrontCreateInvalidation({
25800
+ params: { distributionId: payload.distributionId },
25801
+ headers: {
25802
+ ...signedHeaders,
25803
+ Authorization: authorization
25804
+ },
25805
+ body
25806
+ });
25807
+ }
25808
+ __name(cloudFrontCreateInvalidation, "cloudFrontCreateInvalidation");
25809
+ async function fastlyPurgeUrl(payload, options) {
25810
+ const client = options?.apiClient ?? getDefaultApiClient();
25811
+ if (!payload.serviceId) {
25812
+ throw new ApiPackageError(
25813
+ "Missing required field: serviceId",
25814
+ HTTP_STATUS.BAD_REQUEST,
25815
+ API_ERROR_CODES.FASTLY_SERVICE_NOT_FOUND
25816
+ );
25817
+ }
25818
+ if (!payload.apiToken) {
25819
+ throw new ApiPackageError(
25820
+ "Missing required field: apiToken",
25821
+ HTTP_STATUS.UNAUTHORIZED,
25822
+ API_ERROR_CODES.FASTLY_AUTHENTICATION_FAILED
25823
+ );
25824
+ }
25825
+ if (!payload.url) {
25826
+ throw new ApiPackageError(
25827
+ "Missing required field: url",
25828
+ HTTP_STATUS.BAD_REQUEST,
25829
+ API_ERROR_CODES.FASTLY_INVALID_URL
25830
+ );
25831
+ }
25832
+ const serviceDefaults = {
25833
+ retry: { attempts: 2 },
25834
+ timeout: 15e3
25835
+ // 15 seconds
25836
+ };
25837
+ const mergedConfig = mergeConfigs(serviceDefaults, options?.apiConfig ?? {});
25838
+ const updateOptions = {
25839
+ strategy: "temporary",
25840
+ ...options?.updateConfigOptions
25841
+ };
25842
+ if (shouldApplyConfig(mergedConfig, updateOptions)) {
25843
+ client.updateConfig(mergedConfig, updateOptions);
25844
+ }
25845
+ return client.fastlyPurgeUrl({
25846
+ params: {
25847
+ serviceId: payload.serviceId,
25848
+ url: encodeURIComponent(payload.url)
25849
+ },
25850
+ headers: {
25851
+ "Fastly-Key": payload.apiToken
25852
+ }
25853
+ });
25854
+ }
25855
+ __name(fastlyPurgeUrl, "fastlyPurgeUrl");
25688
25856
  function getSSRSafeConfig(config) {
25689
25857
  if (!isBrowser()) {
25690
25858
  return {
@@ -25902,6 +26070,6 @@ __name(toFetchffRevalidationConfig, "toFetchffRevalidationConfig");
25902
26070
  resources: revalidationStrategies.static
25903
26071
  });
25904
26072
 
25905
- export { ALL_EVENTS, ApiPackageError, CACHE_EVENTS2 as CACHE_EVENTS, CLIENT_EVENTS2 as CLIENT_EVENTS, CONFIG_EVENTS2 as CONFIG_EVENTS, ClientEventManager, ClientHintsInterceptor, ConfigBuilder, DEBUG_EVENTS2 as DEBUG_EVENTS, ERROR_EVENTS2 as ERROR_EVENTS, EVENT_NAMESPACES2 as EVENT_NAMESPACES, EVENT_SCOPES2 as EVENT_SCOPES, EVENT_SCOPES_WITH_TEMPORARY, Environment, EventHelpers, EventManager, HANDLER_SCOPES, HEADER_EVENTS2 as HEADER_EVENTS, HeaderBuilder, IntervalManager, MEDIA_EXTENSIONS, MEDIA_MIME_PREFIXES, MinimumConnectionGuard, NETWORK_EVENTS2 as NETWORK_EVENTS, NetworkConfigurationManager, NetworkDetectionMiddleware, NetworkGuard, NetworkInfoParam, NetworkPresetNames, NetworkProperty, NoDataSaverGuard, PERFORMANCE_EVENTS2 as PERFORMANCE_EVENTS, RequestTracker, UnifiedDebugger, abortAllRequests, abortByPattern, abortRequest, abortSearchRequests, abortUploadRequests, addClientHintsToResponse, addInterval, addTime, analyzeComplianceIssues, analyzeConfigImpact, analyzeConflictPatterns, analyzeEventSystemIssues, analyzeHistoryPatterns, analyzePerformanceIssues, applyCacheStrategyConfig, applyConfigOverride, applyConfigPreset, applyConfigUpdate, applyCustomQualityPresetStrategies, applyHeaderPresets, applyIndividualStrategies, applyPerformancePresetConfig, applyPollingStrategy, applyPollingStrategyConfig, applyRetryStrategy, applyRetryStrategyConfig, applyRevalidationStrategy, applyTemporaryNetworkOverride, applyUnifiedStrategy, applyUnifiedStrategyToConfig, arrayOf, average, base64ToBytes, buildCacheKey, buildEndpointUrl, buildFullUrl, buildUrl, bytesToBase64, cacheKeyPatterns, cacheStrategies, calculateCacheDuration, calculatePerformanceImpact, calculatePollingDuration, calculateRequestMetrics, campaignEndpoints, canPerformHeavyOperation, checkOverrideTriggers, clamp, clampedPercentage, clearErrorHandlers, clearNetworkDebugData, clearTemporaryOverrides, cloneConfig, compactHistory, configConflictDetector, configureForEnvironment, containsAny, convertEndpointsToFetchff, createAbortError, createAdaptiveResponse, createApiClient, createCachePattern, createCacheStrategy, createCampaign, createComplianceReport, createConditionalInterval, createConditionalPolling, createConfigBuilder, createConfigHistoryEntry, createConfigState, createConflict, createCorrelationIdGenerator, createCustomPreset, createCustomUnifiedStrategy, createDate, createDebouncedAbort, createDebugReport, createDecryptionInterceptor, createDelay, createEncryptionInterceptor, createEncryptionInterceptors, createEventEmitter, createHistoryEntry, createHistorySummary, createIdGenerator, createLimitedInterval, createManagedInterval, createNetworkDetectionMiddleware, createPerformanceAnalysis, createPerformanceBenchmark, createPollingStrategy, createPreservedConfig, createProgressivePolling, createRequestIdGenerator, createRetryConfig, createRetryStrategy, createRevalidationKey, createRevalidationStrategy, createRouteGuard, createRouteScope, createScopedAbort, createStatusCodeLimits, createThrottledAbort, createTypedSubscription, createVisibilityAwarePolling, dateDiff, debounce, decrypt, deepMerge, deleteCache, deleteCampaign, detectConfigConflicts, detectConflicts, detectPlatform, determinePrecedenceReason, disableNetworkConfigDebug, enableNetworkConfigDebug, encrypt, endOfDay, endpointCacheKey, endpointCachePattern, endpointCachePatterns, endpoints, eventManager, exportKeyToBase64, extendPresets as extendRevalidationPresets, extractBaseCorrelationId, extractBaseId, extractBaseRequestId, extractCorrelationType, extractFields, extractLinkedCorrelationIds, extractUrlParams, fetchCampaign, fetchCampaignParticipants, fetchCampaignStats, fetchCampaigns, filterHistory, filterObject, findEndpointsByPattern, findMatchingPaths, flattenObject, formatDuration, formatReportForConsole, formatTimeForInterval, fromFetchffConfig, fromISOString, fromUnixTimestamp, generateApiCorrelationId, generateBaseId, generateComprehensiveReport, generateContextualCorrelationId, generateContextualId, generateContextualRequestId, generateCorrelationId, generateIV, generateIssueBreakdown, generateNetworkCorrelationId, generateRandomKey, generateRecommendations, generateRequestId, generateSessionCorrelationId, generateShortRequestId, generateTraceCorrelationId, generateUUID, getActiveOverrideKeys, getAdaptiveApiConfig, getAdaptiveBatchSize, getAdaptiveCacheDuration, getAdaptiveConfig, getAdaptivePageSize, getAdaptiveTimeout, getAllEndpointUrls, getAllFieldPaths, getAllMediaExtensions, getAppVersion, getAuthenticationType, getCache, getCacheAffectingHeaders, getCacheStrategy, getClientHintHeaders, getConfigHierarchy, getConnection, getConnectionType, getConsole, getContextHeaders, getCrypto, getDefaultApiClient, getDeviceId, getDeviceInfo, getDocument, getEffectiveConfig, getEffectiveConnectionType, getEndpointConfig, getEndpointMetadata, getEndpointParams, getEndpointUrl, getEndpointsByMethod, getEnhancedClientHints, getEntries, getEnv, getEnvironmentInfo, getEnvironmentName, getErrorCategory, getErrorCodeByStatus, getErrorDefinition, getErrorHandlers, getEventManager, getExtendedEnvironmentInfo, getFieldValue, getFileExtension, getFrameworkAdaptiveBatchSize, getFrameworkAdaptiveTimeout, getGlobal, getGlobalConfig, getHeaderFingerprint, getHeaderSummary, getISOWeek, getIntervalBoundaries, getIntervalDifference, getIntervalEnd, getIntervalStart, getJSONSize, getKeys, getLocalStorage, getLocation, getMatchingPresets, getNavigator, getNetworkConfigFromHeaders, getNetworkDebugStats, getNetworkEventStats, getNetworkInfo, getNetworkInfoFromHeaders, getNetworkInfoFromRequest, getNetworkOptimizedConfig, getNetworkPreset, getNetworkQuality, getNetworkQualityFromHeaders, getNetworkQualityScore, getNetworkQualityWithThresholds, getNetworkRTT, getNetworkSpeed, getNonCacheAffectingHeaders, getOptimizedNetworkConfig, getPresetForNetworkInfo, getPresetForQuality, getPresetNames, getProcess, getQuarter, getRelativeTime, getRetryStrategy, getPreset as getRevalidationPreset, getPresets as getRevalidationPresets, getRevalidationStrategy, getRuntimeEnvironment, getSSRSafeConfig, getSSRSafePollingConfig, getSessionStorage, getTimeComponents, getUnifiedDebugger, getUnifiedStrategy, getUnifiedStrategyNames, getUnixTimestamp, getUserAgent, getValues, getWindow, groupBy, handleArrayMerge, handleObjectMerge, hasAnyExtension, hasAuthentication, hasEncryptableFields, hasEndpoint, hasGlobal, hasIndexedDB, hasLocalStorage, hasMatchingFields, hasNavigator, hasNetworkInfo2 as hasNetworkInfoExpress, hasNetworkInfo as hasNetworkInfoNextjs, hasPathParams, hasPreset, hasProperty, hasSessionStorage, hasWebGL, hasWebPSupport, headerPresets, headers, headersContext, importKey, inBrowser, inRange, inServer, invalidationScenarios, inverseLerp, isAbortError, isArray, isBoolean, isBrowser, isBun, isCI, isCacheValid, isCellularConnection, isCryptoAvailable, isDataFresh, isDataSaverEnabled, isDataSaverEnabledFromHeaders, isDebug, isDeno, isDevelopment, isDocumentVisible, isElectron, isEmpty, isEmptyObject, isEncryptedMetadata, isError, isFunction, isFuture, isInIframe, isInRange, isInteger, isMergeableObject, isMobile, isNetworkAPISupported, isNode, isNonEmptyArray, isNonEmptyObject, isNonEmptyString2 as isNonEmptyString, isNonNegativeNumber, isNotNullish, isNullish, isNumber, isObject, isOffline, isOneOfIgnoreCase, isOnline, isPageFocused, isPast, isPlainObject, isPollingActive, isPositiveNumber, isProduction, isPromise, isReactNative, isRevalidationSupported, isSSR, isSameDay, isSameInterval, isServer, isSlowConnection, isStaging, isString, isTest, isToday, isTouchDevice, isUnifiedStrategyName, isValidCorrelationId, isValidDate, isValidEnumValue, isValidFieldPath, isValidId, isValidJSON, isValidNumber2 as isValidNumber, isValidPollingConfig, isValidRequestId, isValidStrategyName as isValidRevalidationStrategyName, isWebWorker, isWifiConnection, isWildcard, isWithinDedupeWindow, joinCampaign, jsonClone, jsonEquals, keyBy, leaveCampaign, lerp, linkCorrelationIds, logNetworkConfigReport, mapKeys, mapObject, mapRange, matchFieldPath, matchesAny, max, median, mergeCacheStrategies, mergeConfigs, mergeConflicts, mergeHeaders, mergePollingConfigs, mergePresets, mergeRetryStrategies, mergeRevalidationStrategies, mergeUnifiedStrategy, min, msToSeconds, mutate2 as mutate, networkConfigDebugger, networkConfigManager, networkDetectionMiddleware, networkPresets, networkStatus, normalizeHeaders3 as normalizeHeaders, now, nowInSeconds, omit, onOffline, onOnline, onceErrorHandler, oneOf, parseAndValidateNumber, parseFieldPath, parseId, percentage, pick, pollingEndpoints, pollingStrategies, prepareRequestConfig, prepareRequestConfigWithEnrichedHeaders, prettyStringify, processHeaders2 as processHeaders, raceRequests, randomBetween, randomInt, registerErrorHandler, registerErrorHandlers, removeCircularReferences, removeEmpty, removeNullish, removeSensitiveHeaders, removeUndefined, requestTracker, requestWithTimeout, resetGlobalConfig, resetPresets as resetRevalidationPresets, resolveConflict, retryConditions, retryStrategies, genericPresets as revalidationPresets, revalidationStrategies, round, runWithHeaders, runWithHeadersAsync, safeParseJSON, safeStringify, sanitizeHeaders2 as sanitizeHeaders, secondsToMs, sequentialRequests, setCache, setConfigWarnings, setDefaultApiClient, setErrorHandlers, setFieldValue, setGlobalConfig, setupClientEvents, setupNetworkMonitoring, setupRouteChangeCleanup, setupTemporaryOverride, shouldApplyConfig, shouldAutoRefresh, shouldPrefetch, shouldServeHighQuality, shouldUseAggressiveCaching, sleep, sortIssuesByPriority, startNetworkEventMonitoring, startOfDay, startRequestTracking, subscribe, subscribeMultiple, subscribeOnce, subscribeWithTimeout, sum, supportsBroadcastChannel, supportsFetch, supportsGeolocation, supportsIntersectionObserver, supportsLocalStorage, supportsNotifications, supportsPushNotifications, supportsRequestIdleCallback, supportsServiceWorker, supportsSessionStorage, supportsWebSocket, throttle, timeAgo, toFetchffConfig, toFetchffRevalidationConfig, toISOString, trackConfig, trackDirectCacheConfig, trackNetworkOverride, trackSpreadProperties, trackableSpread, transformFields, truncateJSON, unifiedStrategies, unregisterErrorHandlers, updateCampaign, updateGlobalConfig, useAbortableRequest, useApiConfigConflicts, useApiDebugInfo, useApiMonitor, useApiNetworkQuality, useCampaign, useCampaignParticipants, useCampaignStats, useCampaigns, useConditionalSubscription, useCreateCampaign, useDebouncedSubscription, useDeleteCampaign, useJoinCampaign, useLeaveCampaign, useMultipleSubscriptions, useOptimisticUpdate, useRealTimeData, useRequestCleanup, useRequestGroup, useRouteAwareRequest, useSubscription, useSubscriptionState, useUpdateCampaign, validateConfigUpdate, validateEncryptionConfig, validateHeaders2 as validateHeaders, validatePathParams, validatePreset, waitForOnline, withNetworkDetection, withNetworkInfo, withTimeout };
26073
+ export { ALL_EVENTS, ApiPackageError, CACHE_EVENTS2 as CACHE_EVENTS, CLIENT_EVENTS2 as CLIENT_EVENTS, CONFIG_EVENTS2 as CONFIG_EVENTS, ClientEventManager, ClientHintsInterceptor, ConfigBuilder, DEBUG_EVENTS2 as DEBUG_EVENTS, ERROR_EVENTS2 as ERROR_EVENTS, EVENT_NAMESPACES2 as EVENT_NAMESPACES, EVENT_SCOPES, EVENT_SCOPES_WITH_TEMPORARY2 as EVENT_SCOPES_WITH_TEMPORARY, Environment, EventHelpers, EventManager, HANDLER_SCOPES, HEADER_EVENTS2 as HEADER_EVENTS, HeaderBuilder, IntervalManager, MEDIA_EXTENSIONS, MEDIA_MIME_PREFIXES, MinimumConnectionGuard, NETWORK_EVENTS2 as NETWORK_EVENTS, NetworkConfigurationManager, NetworkDetectionMiddleware, NetworkGuard, NetworkInfoParam, NetworkPresetNames, NetworkProperty, NoDataSaverGuard, PERFORMANCE_EVENTS2 as PERFORMANCE_EVENTS, RequestTracker, UnifiedDebugger, abortAllRequests, abortByPattern, abortRequest, abortSearchRequests, abortUploadRequests, addClientHintsToResponse, addInterval, addTime, analyzeComplianceIssues, analyzeConfigImpact, analyzeConflictPatterns, analyzeEventSystemIssues, analyzeHistoryPatterns, analyzePerformanceIssues, applyCacheStrategyConfig, applyConfigOverride, applyConfigPreset, applyConfigUpdate, applyCustomQualityPresetStrategies, applyHeaderPresets, applyIndividualStrategies, applyPerformancePresetConfig, applyPollingStrategy, applyPollingStrategyConfig, applyRetryStrategy, applyRetryStrategyConfig, applyRevalidationStrategy, applyTemporaryNetworkOverride, applyUnifiedStrategy, applyUnifiedStrategyToConfig, arrayOf, average, base64ToBytes, buildCacheKey, buildEndpointUrl, buildFullUrl, buildUrl, bulkValidateInfobipEmails, bytesToBase64, cacheKeyPatterns, cacheStrategies, calculateCacheDuration, calculatePerformanceImpact, calculatePollingDuration, calculateRequestMetrics, campaignEndpoints, canPerformHeavyOperation, cdnEndpoints, checkOverrideTriggers, clamp, clampedPercentage, clearErrorHandlers, clearNetworkDebugData, clearTemporaryOverrides, cloneConfig, cloudFrontCreateInvalidation, cloudFrontEndpoints, cloudflareEndpoints, cloudflarePurgeCache, compactHistory, configConflictDetector, configureForEnvironment, containsAny, convertEndpointsToFetchff, createAbortError, createAdaptiveResponse, createApiClient, createCachePattern, createCacheStrategy, createCampaign, createComplianceReport, createConditionalInterval, createConditionalPolling, createConfigBuilder, createConfigHistoryEntry, createConfigState, createConflict, createCustomPreset, createCustomUnifiedStrategy, createDate, createDebouncedAbort, createDebugReport, createDecryptionInterceptor, createDelay, createEncryptionInterceptor, createEncryptionInterceptors, createEventEmitter, createHistoryEntry, createHistorySummary, createLimitedInterval, createManagedInterval, createNetworkDetectionMiddleware, createPerformanceAnalysis, createPerformanceBenchmark, createPollingStrategy, createPreservedConfig, createProgressivePolling, createRetryConfig, createRetryStrategy, createRevalidationKey, createRevalidationStrategy, createRouteGuard, createRouteScope, createScopedAbort, createStatusCodeLimits, createThrottledAbort, createTypedSubscription, createVisibilityAwarePolling, dateDiff, debounce, decrypt, deepMerge, deleteCache, deleteCampaign, detectConfigConflicts, detectConflicts, detectPlatform, determinePrecedenceReason, disableNetworkConfigDebug, enableNetworkConfigDebug, encrypt, endOfDay, endpointCacheKey, endpointCachePattern, endpointCachePatterns, endpoints, eventManager, exportKeyToBase64, extendPresets as extendRevalidationPresets, extractFields, extractUrlParams, fastlyEndpoints, fastlyPurgeUrl, fetchCampaign, fetchCampaignParticipants, fetchCampaignStats, fetchCampaigns, fetchInfobipEmailLogs, fetchInfobipEmailReports, fetchInfobipScheduledEmailStatuses, fetchInfobipScheduledEmails, fetchInfobipValidations, filterHistory, filterObject, findEndpointsByPattern, findMatchingPaths, flattenObject, formatDuration, formatReportForConsole, formatTimeForInterval, fromFetchffConfig, fromISOString, fromUnixTimestamp, generateComprehensiveReport, generateIV, generateIssueBreakdown, generateRandomKey, generateRecommendations, generateUUID, getActiveOverrideKeys, getAdaptiveApiConfig, getAdaptiveBatchSize, getAdaptiveCacheDuration, getAdaptiveConfig, getAdaptivePageSize, getAdaptiveTimeout, getAllEndpointUrls, getAllFieldPaths, getAllMediaExtensions, getAnalysisResult, getAppVersion, getAuthenticationType, getCache, getCacheAffectingHeaders, getCacheStrategy, getClientHintHeaders, getConfigHierarchy, getConnection, getConnectionType, getConsole, getContextHeaders, getCrypto, getDefaultApiClient, getDeviceId, getDeviceInfo, getDocument, getEffectiveConfig, getEffectiveConnectionType, getEndpointConfig, getEndpointMetadata, getEndpointParams, getEndpointUrl, getEndpointsByMethod, getEnhancedClientHints, getEntries, getEnv, getEnvironmentInfo, getEnvironmentName, getErrorHandlers, getEventManager, getExtendedEnvironmentInfo, getFieldValue, getFileExtension, getFrameworkAdaptiveBatchSize, getFrameworkAdaptiveTimeout, getGlobal, getGlobalConfig, getHeaderFingerprint, getHeaderSummary, getISOWeek, getIntervalBoundaries, getIntervalDifference, getIntervalEnd, getIntervalStart, getJSONSize, getKeys, getLocalStorage, getLocation, getMatchingPresets, getNavigator, getNetworkConfigFromHeaders, getNetworkDebugStats, getNetworkEventStats, getNetworkInfo, getNetworkInfoFromHeaders, getNetworkInfoFromRequest, getNetworkOptimizedConfig, getNetworkPreset, getNetworkQuality, getNetworkQualityFromHeaders, getNetworkQualityScore, getNetworkQualityWithThresholds, getNetworkRTT, getNetworkSpeed, getNonCacheAffectingHeaders, getOptimizedNetworkConfig, getPresetForNetworkInfo, getPresetForQuality, getPresetNames, getProcess, getQuarter, getRelativeTime, getRetryStrategy, getPreset as getRevalidationPreset, getPresets as getRevalidationPresets, getRevalidationStrategy, getRuntimeEnvironment, getSSRSafeConfig, getSSRSafePollingConfig, getSessionStorage, getTimeComponents, getUnifiedDebugger, getUnifiedStrategy, getUnifiedStrategyNames, getUnixTimestamp, getUserAgent, getValues, getWindow, groupBy, handleArrayMerge, handleObjectMerge, hasAnyExtension, hasAuthentication, hasEncryptableFields, hasEndpoint, hasGlobal, hasIndexedDB, hasLocalStorage, hasMatchingFields, hasNavigator, hasNetworkInfo2 as hasNetworkInfoExpress, hasNetworkInfo as hasNetworkInfoNextjs, hasPathParams, hasPreset, hasProperty, hasSessionStorage, hasWebGL, hasWebPSupport, headerPresets, headers, headersContext, importKey, inBrowser, inRange, inServer, infobipEmailEndpoints, infobipEndpoints, invalidationScenarios, inverseLerp, isAbortError, isArray, isBoolean, isBrowser, isBun, isCI, isCacheValid, isCellularConnection, isCryptoAvailable, isDataFresh, isDataSaverEnabled, isDataSaverEnabledFromHeaders, isDebug, isDeno, isDevelopment, isDocumentVisible, isElectron, isEmpty, isEmptyObject, isEncryptedMetadata, isError, isFunction, isFuture, isInIframe, isInRange, isInteger, isMergeableObject, isMobile, isNetworkAPISupported, isNode, isNonEmptyArray, isNonEmptyObject, isNonEmptyString2 as isNonEmptyString, isNonNegativeNumber, isNotNullish, isNullish, isNumber, isObject, isOffline, isOneOfIgnoreCase, isOnline, isPageFocused, isPast, isPlainObject, isPollingActive, isPositiveNumber, isProduction, isPromise, isReactNative, isRevalidationSupported, isSSR, isSameDay, isSameInterval, isServer, isSlowConnection, isStaging, isString, isTest, isToday, isTouchDevice, isUnifiedStrategyName, isValidDate, isValidEnumValue, isValidFieldPath, isValidJSON, isValidNumber2 as isValidNumber, isValidPollingConfig, isValidStrategyName as isValidRevalidationStrategyName, isWebWorker, isWifiConnection, isWildcard, isWithinDedupeWindow, joinCampaign, jsonClone, jsonEquals, keyBy, leaveCampaign, lerp, logNetworkConfigReport, mapKeys, mapObject, mapRange, matchFieldPath, matchesAny, max, median, mergeCacheStrategies, mergeConfigs, mergeConflicts, mergeHeaders, mergePollingConfigs, mergePresets, mergeRetryStrategies, mergeRevalidationStrategies, mergeUnifiedStrategy, min, msToSeconds, mutate2 as mutate, networkConfigDebugger, networkConfigManager, networkDetectionMiddleware, networkPresets, networkStatus, normalizeHeaders3 as normalizeHeaders, now, nowInSeconds, omit, onOffline, onOnline, onceErrorHandler, oneOf, parseAndValidateNumber, parseFieldPath, percentage, pick, pollingEndpoints, pollingStrategies, prepareRequestConfig, prepareRequestConfigWithEnrichedHeaders, prettyStringify, processHeaders2 as processHeaders, raceRequests, randomBetween, randomInt, registerErrorHandler, registerErrorHandlers, removeCircularReferences, removeEmpty, removeNullish, removeSensitiveHeaders, removeUndefined, requestTracker, requestWithTimeout, rescheduleInfobipEmails, resetGlobalConfig, resetPresets as resetRevalidationPresets, resolveConflict, retryConditions, retryStrategies, genericPresets as revalidationPresets, revalidationStrategies, round, runWithHeaders, runWithHeadersAsync, safeParseJSON, safeStringify, sanitizeHeaders2 as sanitizeHeaders, secondsToMs, sendInfobipAdvancedEmail, sendInfobipEmail, sequentialRequests, setCache, setConfigWarnings, setDefaultApiClient, setErrorHandlers, setFieldValue, setGlobalConfig, setupClientEvents, setupNetworkMonitoring, setupRouteChangeCleanup, setupTemporaryOverride, shouldApplyConfig, shouldAutoRefresh, shouldPrefetch, shouldServeHighQuality, shouldUseAggressiveCaching, sleep, sortIssuesByPriority, startNetworkEventMonitoring, startOfDay, startRequestTracking, subscribe, subscribeMultiple, subscribeOnce, subscribeWithTimeout, sum, supportsBroadcastChannel, supportsFetch, supportsGeolocation, supportsIntersectionObserver, supportsLocalStorage, supportsNotifications, supportsPushNotifications, supportsRequestIdleCallback, supportsServiceWorker, supportsSessionStorage, supportsWebSocket, throttle, timeAgo, toFetchffConfig, toFetchffRevalidationConfig, toISOString, trackConfig, trackDirectCacheConfig, trackNetworkOverride, trackSpreadProperties, trackableSpread, transformFields, truncateJSON, unifiedStrategies, unregisterErrorHandlers, updateCampaign, updateGlobalConfig, updateInfobipScheduledEmailStatuses, uploadFileForScanning, useAbortableRequest, useApiConfigConflicts, useApiDebugInfo, useApiMonitor, useApiNetworkQuality, useCampaign, useCampaignParticipants, useCampaignStats, useCampaigns, useConditionalSubscription, useCreateCampaign, useDebouncedSubscription, useDeleteCampaign, useJoinCampaign, useLeaveCampaign, useMultipleSubscriptions, useOptimisticUpdate, useRealTimeData, useRequestCleanup, useRequestGroup, useRouteAwareRequest, useSubscription, useSubscriptionState, useUpdateCampaign, validateConfigUpdate, validateEncryptionConfig, validateHeaders2 as validateHeaders, validateInfobipEmail, validatePathParams, validatePreset, virusTotalEndpoints, waitForOnline, withNetworkDetection, withNetworkInfo, withTimeout };
25906
26074
  //# sourceMappingURL=index.mjs.map
25907
26075
  //# sourceMappingURL=index.mjs.map