@webex/contact-center 3.13.0-next.12 → 3.13.0-next.13

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 (37) hide show
  1. package/ai-docs/contact-center-spec.md +387 -0
  2. package/dist/cc.js +7 -7
  3. package/dist/cc.js.map +1 -1
  4. package/dist/services/core/Utils.js +21 -2
  5. package/dist/services/core/Utils.js.map +1 -1
  6. package/dist/services/core/aqm-reqs.js +1 -1
  7. package/dist/services/core/aqm-reqs.js.map +1 -1
  8. package/dist/services/core/websocket/connection-service.js +18 -1
  9. package/dist/services/core/websocket/connection-service.js.map +1 -1
  10. package/dist/services/core/websocket/keepalive.worker.js +0 -9
  11. package/dist/services/core/websocket/keepalive.worker.js.map +1 -1
  12. package/dist/services/task/TaskManager.js +9 -1
  13. package/dist/services/task/TaskManager.js.map +1 -1
  14. package/dist/services/task/TaskUtils.js +7 -4
  15. package/dist/services/task/TaskUtils.js.map +1 -1
  16. package/dist/types/services/core/Utils.d.ts +9 -0
  17. package/dist/types/services/core/websocket/keepalive.worker.d.ts +1 -1
  18. package/dist/webex.js +1 -1
  19. package/package.json +1 -1
  20. package/src/cc.ts +19 -11
  21. package/src/services/core/Utils.ts +19 -0
  22. package/src/services/core/ai-docs/core-spec.md +808 -0
  23. package/src/services/core/aqm-reqs.ts +1 -1
  24. package/src/services/core/websocket/connection-service.ts +21 -2
  25. package/src/services/core/websocket/keepalive.worker.js +0 -9
  26. package/src/services/task/TaskManager.ts +12 -1
  27. package/src/services/task/TaskUtils.ts +10 -9
  28. package/src/services/task/ai-docs/task-spec.md +1511 -0
  29. package/test/unit/spec/cc.ts +124 -0
  30. package/test/unit/spec/services/core/Utils.ts +27 -0
  31. package/test/unit/spec/services/core/aqm-reqs.ts +18 -0
  32. package/test/unit/spec/services/core/websocket/connection-service.ts +29 -0
  33. package/test/unit/spec/services/core/websocket/keepalive.worker.ts +18 -0
  34. package/test/unit/spec/services/task/TaskManager.ts +52 -0
  35. package/test/unit/spec/services/task/TaskUtils.ts +51 -0
  36. package/umd/contact-center.min.js +2 -2
  37. package/umd/contact-center.min.js.map +1 -1
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.stripDialPlanChars = exports.isValidDialNumber = exports.isRecord = exports.isAllowedUrlHost = exports.getStationLoginErrorData = exports.getErrorDetails = exports.getDestAgentIdForCBT = exports.getConsultedAgentId = exports.generateTaskErrorObject = exports.deriveConsultTransferDestinationType = exports.createErrDetailsObject = exports.calculateDestType = exports.calculateDestAgentId = exports.buildConsultConferenceParamData = void 0;
6
+ exports.stripDialPlanChars = exports.sanitizeForObservability = exports.isValidDialNumber = exports.isRecord = exports.isAllowedUrlHost = exports.getStationLoginErrorData = exports.getErrorDetails = exports.getDestAgentIdForCBT = exports.getConsultedAgentId = exports.generateTaskErrorObject = exports.deriveConsultTransferDestinationType = exports.createErrDetailsObject = exports.calculateDestType = exports.calculateDestAgentId = exports.buildConsultConferenceParamData = void 0;
7
7
  var Err = _interopRequireWildcard(require("./Err"));
8
8
  var _types = require("../../types");
9
9
  var _loggerProxy = _interopRequireDefault(require("../../logger-proxy"));
@@ -14,6 +14,25 @@ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e
14
14
  function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
15
15
  /** Returns whether a value is a non-null object with string keys. */
16
16
  const isRecord = value => typeof value === 'object' && value !== null;
17
+ exports.isRecord = isRecord;
18
+ const MAX_SANITIZED_OBSERVABILITY_VALUE_LENGTH = 200;
19
+
20
+ /**
21
+ * Sanitizes an untrusted remote string before it reaches logs or metrics by stripping
22
+ * CR/LF and other control characters and capping its length, blocking log/metrics
23
+ * injection while leaving legitimate values effectively unchanged.
24
+ *
25
+ * @param value - The untrusted remote value to sanitize.
26
+ * @returns The sanitized string, or an empty string when the value is not a string.
27
+ */
28
+ const sanitizeForObservability = value => {
29
+ if (typeof value !== 'string') {
30
+ return '';
31
+ }
32
+
33
+ // eslint-disable-next-line no-control-regex
34
+ return value.replace(/[\x00-\x1f\x7f]/g, '').slice(0, MAX_SANITIZED_OBSERVABILITY_VALUE_LENGTH);
35
+ };
17
36
 
18
37
  /**
19
38
  * Extracts common error details from a Webex request payload.
@@ -23,7 +42,7 @@ const isRecord = value => typeof value === 'object' && value !== null;
23
42
  * @private
24
43
  * @ignore
25
44
  */
26
- exports.isRecord = isRecord;
45
+ exports.sanitizeForObservability = sanitizeForObservability;
27
46
  const getCommonErrorDetails = errObj => {
28
47
  return {
29
48
  trackingId: errObj?.headers?.trackingid || errObj?.headers?.TrackingID,
@@ -1 +1 @@
1
- {"version":3,"names":["Err","_interopRequireWildcard","require","_types","_loggerProxy","_interopRequireDefault","_WebexRequest","_types2","_constants","e","__esModule","default","t","WeakMap","r","n","o","i","f","__proto__","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","isRecord","value","exports","getCommonErrorDetails","errObj","trackingId","headers","trackingid","TrackingID","msg","body","stripDialPlanChars","input","strippedChars","charsToStrip","Set","split","filter","c","join","isValidDialNumber","dialPlanEntries","LoggerProxy","warn","module","method","length","log","some","entry","sanitizedInput","regex","RegExp","test","name","isAllowedUrlHost","url","allowedDomains","hostname","URL","toLowerCase","domain","endsWith","error","getStationLoginErrorData","failure","loginOption","duplicateLocationMessage","LoginOption","EXTENSION","AGENT_DN","errorCodeMessageMap","DUPLICATE_LOCATION","message","fieldName","INVALID_DIAL_NUMBER","defaultMessage","defaultFieldName","reason","data","getErrorDetails","methodName","moduleName","errData","details","WebexRequest","getInstance","uploadLogs","correlationId","err","Error","generateTaskErrorObject","errorMsg","fallbackMessage","errorMessage","errorType","errorData","reasonCode","createErrDetailsObject","Details","getConsultedAgentId","media","agentId","consultParticipants","consultedParticipantId","keys","forEach","key","mType","STATE_CONSULT","participants","includes","id","find","participant","getDestAgentIdForCBT","interaction","consultingAgent","destAgentIdForCBT","foundEntry","entries","pType","PARTICIPANT_TYPES","DN","type","AGENT","dn","calculateDestAgentId","destAgentIdCBT","EP_DN","epId","calculateDestType","destinationaegntId","destAgentType","undefined","CONSULT_TRANSFER_DESTINATION_TYPE","DIALNUMBER","ENTRYPOINT","buildConsultConferenceParamData","dataPassed","interactionIdPassed","to","destAgentId","destinationType","String","trim","normalizedDestinationType","toUpperCase","replace","DESTINATION_TYPE","QUEUE","interactionId","deriveConsultTransferDestinationType","taskData","destType","normalizedDestType"],"sources":["Utils.ts"],"sourcesContent":["import * as Err from './Err';\nimport {LoginOption, WebexRequestPayload} from '../../types';\nimport {Failure, AugmentedError} from './GlobalTypes';\nimport LoggerProxy from '../../logger-proxy';\nimport WebexRequest from './WebexRequest';\nimport {\n ConsultConferenceData,\n consultConferencePayloadData,\n ConsultTransferDestinationType,\n TaskData,\n CONSULT_TRANSFER_DESTINATION_TYPE,\n DESTINATION_TYPE,\n Interaction,\n InteractionParticipant,\n} from '../task/types';\nimport {PARTICIPANT_TYPES, STATE_CONSULT} from './constants';\nimport {DialPlan} from '../config/types';\n\n/** Returns whether a value is a non-null object with string keys. */\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null;\n\n/**\n * Extracts common error details from a Webex request payload.\n *\n * @param errObj - The Webex request payload object.\n * @returns An object containing the tracking ID and message body.\n * @private\n * @ignore\n */\nconst getCommonErrorDetails = (errObj: WebexRequestPayload) => {\n return {\n trackingId: errObj?.headers?.trackingid || errObj?.headers?.TrackingID,\n msg: errObj?.body,\n };\n};\n\n/**\n * Strips characters defined in the dial plan entry from the input string.\n *\n * @param input - The dial number to sanitize\n * @param strippedChars - String of characters to remove from the input\n * @returns The sanitized input with specified characters removed\n */\nexport const stripDialPlanChars = (input: string, strippedChars: string): string => {\n if (!strippedChars) {\n return input;\n }\n\n const charsToStrip = new Set(strippedChars.split(''));\n\n return input\n .split('')\n .filter((c) => !charsToStrip.has(c))\n .join('');\n};\n\n/**\n * Validates a dial number against the provided dial plan regex patterns.\n * A number is valid if it matches at least one regex pattern in the dial plans.\n * Skips validation when no dial plan entries are configured, deferring to the server.\n *\n * @param input - The dial number to validate\n * @param dialPlanEntries - Array of dial plan entries containing regex patterns\n * @returns true if the input matches at least one dial plan regex pattern or no entries are configured, false otherwise\n */\nexport const isValidDialNumber = (\n input: string,\n dialPlanEntries: DialPlan['dialPlanEntity']\n): boolean => {\n if (!input) {\n LoggerProxy.warn('Dial number is empty or undefined.', {\n module: 'Utils',\n method: 'isValidDialNumber',\n });\n\n return false;\n }\n\n if (!dialPlanEntries || dialPlanEntries.length === 0) {\n LoggerProxy.log(\n 'No dial plan entries found. Skipping client-side validation, deferring to server.',\n {module: 'Utils', method: 'isValidDialNumber'}\n );\n\n return true;\n }\n\n return dialPlanEntries.some((entry) => {\n try {\n const sanitizedInput = stripDialPlanChars(input, entry.strippedChars);\n const regex = new RegExp(entry.regex);\n\n return regex.test(sanitizedInput);\n } catch (e) {\n LoggerProxy.warn(`Failed to validate dial number against entry \"${entry.name}\": ${e}`, {\n module: 'Utils',\n method: 'isValidDialNumber',\n });\n\n return false;\n }\n });\n};\n\n/**\n * Checks whether a URL's hostname is, or is a subdomain of, one of the allowed domains.\n *\n * @param url - The candidate URL to validate\n * @param allowedDomains - Domains (or domain suffixes) the URL's hostname must match\n * @returns true when the URL parses and its hostname matches an allowed domain, false otherwise\n */\nexport const isAllowedUrlHost = (\n url: string | undefined | null,\n allowedDomains: string[]\n): boolean => {\n if (!url) {\n return false;\n }\n\n try {\n const hostname = new URL(url).hostname.toLowerCase();\n\n return allowedDomains.some((domain) => hostname === domain || hostname.endsWith(`.${domain}`));\n } catch (error) {\n return false;\n }\n};\n\nexport const getStationLoginErrorData = (failure: Failure, loginOption: LoginOption) => {\n let duplicateLocationMessage = 'This value is already in use';\n\n if (loginOption === LoginOption.EXTENSION) {\n duplicateLocationMessage = 'This extension is already in use';\n }\n\n if (loginOption === LoginOption.AGENT_DN) {\n duplicateLocationMessage =\n 'Dial number is in use. Try a different one. For help, reach out to your administrator or support team.';\n }\n\n const errorCodeMessageMap = {\n DUPLICATE_LOCATION: {\n message: duplicateLocationMessage,\n fieldName: loginOption,\n },\n INVALID_DIAL_NUMBER: {\n message:\n 'Enter a valid dial number. For help, reach out to your administrator or support team.',\n fieldName: loginOption,\n },\n };\n\n const defaultMessage = 'An error occurred while logging in to the station';\n const defaultFieldName = 'generic';\n\n const reason = failure?.data?.reason || '';\n\n return {\n message: errorCodeMessageMap[reason]?.message || defaultMessage,\n fieldName: errorCodeMessageMap[reason]?.fieldName || defaultFieldName,\n };\n};\n\n/**\n * Extracts error details and logs the error. Also uploads logs for the error unless it is a silent relogin agent not found error.\n *\n * @param error - The error object, expected to have a `details` property of type Failure.\n * @param methodName - The name of the method where the error occurred.\n * @param moduleName - The name of the module where the error occurred.\n * @returns An object containing the error instance and the reason string.\n * @public\n * @example\n * const details = getErrorDetails(error, 'fetchData', 'DataModule');\n * if (details.error) { handleError(details.error); }\n * @ignore\n */\nexport const getErrorDetails = (error: any, methodName: string, moduleName: string) => {\n let errData = {message: '', fieldName: ''};\n\n const failure = error.details as Failure;\n const reason = failure?.data?.reason ?? `Error while performing ${methodName}`;\n\n if (!(reason === 'AGENT_NOT_FOUND' && methodName === 'silentRelogin')) {\n LoggerProxy.error(`${methodName} failed with reason: ${reason}`, {\n module: moduleName,\n method: methodName,\n trackingId: failure?.trackingId,\n });\n // we can add more conditions here if not needed for specific cases eg: silentReLogin\n WebexRequest.getInstance().uploadLogs({\n correlationId: failure?.trackingId,\n });\n }\n\n if (methodName === 'stationLogin') {\n errData = getStationLoginErrorData(failure, error.loginOption);\n\n LoggerProxy.error(\n `${methodName} failed with reason: ${reason}, message: ${errData.message}, fieldName: ${errData.fieldName}`,\n {\n module: moduleName,\n method: methodName,\n trackingId: failure?.trackingId,\n }\n );\n }\n\n const err = new Error(reason ?? `Error while performing ${methodName}`);\n // @ts-ignore - add custom property to the error object for backward compatibility\n err.data = errData;\n\n return {\n error: err,\n reason,\n };\n};\n\n/**\n * Extracts error details from task API errors and logs them. Also uploads logs for the error.\n * This handles the specific error format returned by task API calls.\n *\n * @param error - The error object from task API calls with structure: {id: string, details: {trackingId: string, msg: {...}}}\n * @param methodName - The name of the method where the error occurred.\n * @param moduleName - The name of the module where the error occurred.\n * @returns AugmentedError containing structured error details on err.data for metrics and logging\n * @public\n * @example\n * const taskError = generateTaskErrorObject(error, 'transfer', 'TaskModule');\n * throw taskError.error;\n * @ignore\n */\nexport const generateTaskErrorObject = (\n error: any,\n methodName: string,\n moduleName: string\n): AugmentedError => {\n const trackingId = error?.details?.trackingId || error?.trackingId || '';\n const errorMsg = error?.details?.msg;\n\n const fallbackMessage =\n (error && typeof error.message === 'string' && error.message) ||\n `Error while performing ${methodName}`;\n const errorMessage = errorMsg?.errorMessage || fallbackMessage;\n const errorType =\n errorMsg?.errorType ||\n (error && typeof error.name === 'string' && error.name) ||\n 'Unknown Error';\n const errorData = errorMsg?.errorData || '';\n const reasonCode = errorMsg?.reasonCode || 0;\n\n // Log and upload for Task API formatted errors\n LoggerProxy.error(`${methodName} failed: ${errorMessage} (${errorType})`, {\n module: moduleName,\n method: methodName,\n trackingId,\n });\n WebexRequest.getInstance().uploadLogs({\n correlationId: trackingId,\n });\n\n const reason = `${errorType}: ${errorMessage}${errorData ? ` (${errorData})` : ''}`;\n const err: AugmentedError = new Error(reason);\n err.data = {\n message: errorMessage,\n errorType,\n errorData,\n reasonCode,\n trackingId,\n };\n\n return err;\n};\n\n/**\n * Creates an error details object suitable for use with the Err.Details class.\n *\n * @param errObj - The Webex request payload object.\n * @returns An instance of Err.Details with the generic failure message and extracted details.\n * @public\n * @example\n * const errDetails = createErrDetailsObject(webexRequestPayload);\n * @ignore\n */\nexport const createErrDetailsObject = (errObj: WebexRequestPayload) => {\n const details = getCommonErrorDetails(errObj);\n\n return new Err.Details('Service.reqs.generic.failure', details);\n};\n\n/*\n/**\n * Gets the consulted agent ID from the media object by finding the agent\n * in the consult media participants (excluding the current agent).\n *\n * @param media - The media object from the interaction\n * @param agentId - The current agent's ID to exclude from the search\n * @returns The consulted agent ID, or empty string if none found\n */\nexport const getConsultedAgentId = (media: Interaction['media'], agentId: string): string => {\n let consultParticipants: string[] = [];\n let consultedParticipantId = '';\n\n Object.keys(media).forEach((key) => {\n if (media[key].mType === STATE_CONSULT) {\n consultParticipants = media[key].participants;\n }\n });\n\n if (consultParticipants.includes(agentId)) {\n const id = consultParticipants.find((participant) => participant !== agentId);\n consultedParticipantId = id || consultedParticipantId;\n }\n\n return consultedParticipantId;\n};\n\n/**\n * Gets the destination agent ID for CBT (Capacity Based Team) scenarios.\n * CBT refers to teams created in Control Hub with capacity-based routing\n * (as opposed to agent-based routing). This handles cases where the consulted\n * participant is not directly in participants but can be found by matching\n * the dial number (dn).\n *\n * @param interaction - The interaction object\n * @param consultingAgent - The consulting agent identifier\n * @returns The destination agent ID for CBT scenarios, or empty string if none found\n */\nexport const getDestAgentIdForCBT = (interaction: Interaction, consultingAgent: string): string => {\n const participants = interaction.participants;\n let destAgentIdForCBT = '';\n\n // Check if this is a CBT scenario (consultingAgent exists but not directly in participants)\n if (consultingAgent && !participants[consultingAgent]) {\n const foundEntry = Object.entries(participants).find(\n ([, participant]: [string, Interaction['participants'][string]]) => {\n return (\n participant.pType.toLowerCase() === PARTICIPANT_TYPES.DN &&\n participant.type === PARTICIPANT_TYPES.AGENT &&\n participant.dn === consultingAgent\n );\n }\n );\n\n if (foundEntry) {\n destAgentIdForCBT = foundEntry[0];\n }\n }\n\n return destAgentIdForCBT;\n};\n\n/**\n * Calculates the destination agent ID for consult operations.\n *\n * @param interaction - The interaction object\n * @param agentId - The current agent's ID\n * @returns The destination agent ID\n */\nexport const calculateDestAgentId = (interaction: Interaction, agentId: string): string => {\n const consultingAgent = getConsultedAgentId(interaction.media, agentId);\n\n // Check if this is a CBT (Capacity Based Team) scenario\n // If not CBT, the function will return empty string and we'll use the normal flow\n const destAgentIdCBT = getDestAgentIdForCBT(interaction, consultingAgent);\n if (destAgentIdCBT) {\n return destAgentIdCBT;\n }\n\n const participant = interaction.participants[consultingAgent];\n if (!participant) {\n return '';\n }\n\n if (participant.type === PARTICIPANT_TYPES.EP_DN) {\n return (participant as InteractionParticipant & {epId?: string}).epId ?? '';\n }\n\n return participant.id ?? '';\n};\n\n/**\n * Calculates the destination agent ID for fetching destination type.\n *\n * @param interaction - The interaction object\n * @param agentId - The current agent's ID\n * @returns The destination agent ID for determining destination type\n */\nexport const calculateDestType = (interaction: Interaction, agentId: string): string => {\n const consultingAgent = getConsultedAgentId(interaction.media, agentId);\n\n // Check if this is a CBT (Capacity Based Team) scenario, otherwise use consultingAgent\n const destAgentIdCBT = getDestAgentIdForCBT(interaction, consultingAgent);\n const destinationaegntId = destAgentIdCBT || consultingAgent;\n const destAgentType = destinationaegntId\n ? interaction.participants[destinationaegntId]?.pType\n : undefined;\n if (destAgentType) {\n if (destAgentType === 'DN') {\n return CONSULT_TRANSFER_DESTINATION_TYPE.DIALNUMBER;\n }\n if (destAgentType === 'EP-DN') {\n return CONSULT_TRANSFER_DESTINATION_TYPE.ENTRYPOINT;\n }\n // Keep the existing destinationType if it's something else (like \"agent\" or \"Agent\")\n // Convert \"Agent\" to lowercase for consistency\n\n return destAgentType.toLowerCase();\n }\n\n return CONSULT_TRANSFER_DESTINATION_TYPE.AGENT;\n};\n\n/**\n * Gets the destination agent ID from participants.\n * Finds a participant who is not the current agent and is an agent type.\n *\n * @param participants - The participants object from interaction\n * @param agentId - The current agent's ID\n * @returns The destination agent ID, or undefined if none found\n */\nexport const buildConsultConferenceParamData = (\n dataPassed: consultConferencePayloadData,\n interactionIdPassed: string\n): {interactionId: string; data: ConsultConferenceData} => {\n const data: ConsultConferenceData = {\n ...('agentId' in dataPassed && {agentId: dataPassed.agentId}),\n to: dataPassed.destAgentId,\n destinationType: '',\n };\n\n if ('destinationType' in dataPassed) {\n const destinationType = String(dataPassed.destinationType || '').trim();\n const normalizedDestinationType = destinationType.toUpperCase().replace(/[-_\\s]/g, '');\n\n if (normalizedDestinationType === 'DN' || normalizedDestinationType === 'DIALNUMBER') {\n data.destinationType = DESTINATION_TYPE.DIALNUMBER;\n } else if (normalizedDestinationType === 'EPDN' || normalizedDestinationType === 'ENTRYPOINT') {\n data.destinationType = DESTINATION_TYPE.ENTRYPOINT;\n } else if (normalizedDestinationType === 'QUEUE') {\n data.destinationType = DESTINATION_TYPE.QUEUE;\n } else if (normalizedDestinationType === 'AGENT') {\n data.destinationType = DESTINATION_TYPE.AGENT;\n } else {\n data.destinationType = destinationType as ConsultConferenceData['destinationType'];\n }\n } else {\n data.destinationType = DESTINATION_TYPE.AGENT;\n }\n\n return {\n interactionId: interactionIdPassed,\n data,\n };\n};\n\n/**\n * Derives the consult transfer destination type based on task data.\n * This function determines the appropriate destination type for a consult transfer\n * by examining the destination type stored in the task data.\n *\n * @param taskData - The task data containing destination information\n * @returns The derived consult transfer destination type\n * @public\n */\nexport const deriveConsultTransferDestinationType = (\n taskData: TaskData\n): ConsultTransferDestinationType => {\n const destType = taskData?.destinationType;\n const normalizedDestType = String(destType || '')\n .toUpperCase()\n .replace(/[-_\\s]/g, '');\n\n // Map destination types to consult transfer destination types\n if (normalizedDestType === 'DN' || normalizedDestType === 'DIALNUMBER') {\n return CONSULT_TRANSFER_DESTINATION_TYPE.DIALNUMBER;\n }\n if (normalizedDestType === 'EPDN' || normalizedDestType === 'ENTRYPOINT') {\n return CONSULT_TRANSFER_DESTINATION_TYPE.ENTRYPOINT;\n }\n if (normalizedDestType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OAAOf,yCAAiC,CAACV,KAAK;AAChD,CAAC;AAACvG,OAAA,CAAAkI,oCAAA,GAAAA,oCAAA","ignoreList":[]}
1
+ {"version":3,"names":["Err","_interopRequireWildcard","require","_types","_loggerProxy","_interopRequireDefault","_WebexRequest","_types2","_constants","e","__esModule","default","t","WeakMap","r","n","o","i","f","__proto__","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","isRecord","value","exports","MAX_SANITIZED_OBSERVABILITY_VALUE_LENGTH","sanitizeForObservability","replace","slice","getCommonErrorDetails","errObj","trackingId","headers","trackingid","TrackingID","msg","body","stripDialPlanChars","input","strippedChars","charsToStrip","Set","split","filter","c","join","isValidDialNumber","dialPlanEntries","LoggerProxy","warn","module","method","length","log","some","entry","sanitizedInput","regex","RegExp","test","name","isAllowedUrlHost","url","allowedDomains","hostname","URL","toLowerCase","domain","endsWith","error","getStationLoginErrorData","failure","loginOption","duplicateLocationMessage","LoginOption","EXTENSION","AGENT_DN","errorCodeMessageMap","DUPLICATE_LOCATION","message","fieldName","INVALID_DIAL_NUMBER","defaultMessage","defaultFieldName","reason","data","getErrorDetails","methodName","moduleName","errData","details","WebexRequest","getInstance","uploadLogs","correlationId","err","Error","generateTaskErrorObject","errorMsg","fallbackMessage","errorMessage","errorType","errorData","reasonCode","createErrDetailsObject","Details","getConsultedAgentId","media","agentId","consultParticipants","consultedParticipantId","keys","forEach","key","mType","STATE_CONSULT","participants","includes","id","find","participant","getDestAgentIdForCBT","interaction","consultingAgent","destAgentIdForCBT","foundEntry","entries","pType","PARTICIPANT_TYPES","DN","type","AGENT","dn","calculateDestAgentId","destAgentIdCBT","EP_DN","epId","calculateDestType","destinationaegntId","destAgentType","undefined","CONSULT_TRANSFER_DESTINATION_TYPE","DIALNUMBER","ENTRYPOINT","buildConsultConferenceParamData","dataPassed","interactionIdPassed","to","destAgentId","destinationType","String","trim","normalizedDestinationType","toUpperCase","DESTINATION_TYPE","QUEUE","interactionId","deriveConsultTransferDestinationType","taskData","destType","normalizedDestType"],"sources":["Utils.ts"],"sourcesContent":["import * as Err from './Err';\nimport {LoginOption, WebexRequestPayload} from '../../types';\nimport {Failure, AugmentedError} from './GlobalTypes';\nimport LoggerProxy from '../../logger-proxy';\nimport WebexRequest from './WebexRequest';\nimport {\n ConsultConferenceData,\n consultConferencePayloadData,\n ConsultTransferDestinationType,\n TaskData,\n CONSULT_TRANSFER_DESTINATION_TYPE,\n DESTINATION_TYPE,\n Interaction,\n InteractionParticipant,\n} from '../task/types';\nimport {PARTICIPANT_TYPES, STATE_CONSULT} from './constants';\nimport {DialPlan} from '../config/types';\n\n/** Returns whether a value is a non-null object with string keys. */\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null;\n\nconst MAX_SANITIZED_OBSERVABILITY_VALUE_LENGTH = 200;\n\n/**\n * Sanitizes an untrusted remote string before it reaches logs or metrics by stripping\n * CR/LF and other control characters and capping its length, blocking log/metrics\n * injection while leaving legitimate values effectively unchanged.\n *\n * @param value - The untrusted remote value to sanitize.\n * @returns The sanitized string, or an empty string when the value is not a string.\n */\nexport const sanitizeForObservability = (value: unknown): string => {\n if (typeof value !== 'string') {\n return '';\n }\n\n // eslint-disable-next-line no-control-regex\n return value.replace(/[\\x00-\\x1f\\x7f]/g, '').slice(0, MAX_SANITIZED_OBSERVABILITY_VALUE_LENGTH);\n};\n\n/**\n * Extracts common error details from a Webex request payload.\n *\n * @param errObj - The Webex request payload object.\n * @returns An object containing the tracking ID and message body.\n * @private\n * @ignore\n */\nconst getCommonErrorDetails = (errObj: WebexRequestPayload) => {\n return {\n trackingId: errObj?.headers?.trackingid || errObj?.headers?.TrackingID,\n msg: errObj?.body,\n };\n};\n\n/**\n * Strips characters defined in the dial plan entry from the input string.\n *\n * @param input - The dial number to sanitize\n * @param strippedChars - String of characters to remove from the input\n * @returns The sanitized input with specified characters removed\n */\nexport const stripDialPlanChars = (input: string, strippedChars: string): string => {\n if (!strippedChars) {\n return input;\n }\n\n const charsToStrip = new Set(strippedChars.split(''));\n\n return input\n .split('')\n .filter((c) => !charsToStrip.has(c))\n .join('');\n};\n\n/**\n * Validates a dial number against the provided dial plan regex patterns.\n * A number is valid if it matches at least one regex pattern in the dial plans.\n * Skips validation when no dial plan entries are configured, deferring to the server.\n *\n * @param input - The dial number to validate\n * @param dialPlanEntries - Array of dial plan entries containing regex patterns\n * @returns true if the input matches at least one dial plan regex pattern or no entries are configured, false otherwise\n */\nexport const isValidDialNumber = (\n input: string,\n dialPlanEntries: DialPlan['dialPlanEntity']\n): boolean => {\n if (!input) {\n LoggerProxy.warn('Dial number is empty or undefined.', {\n module: 'Utils',\n method: 'isValidDialNumber',\n });\n\n return false;\n }\n\n if (!dialPlanEntries || dialPlanEntries.length === 0) {\n LoggerProxy.log(\n 'No dial plan entries found. Skipping client-side validation, deferring to server.',\n {module: 'Utils', method: 'isValidDialNumber'}\n );\n\n return true;\n }\n\n return dialPlanEntries.some((entry) => {\n try {\n const sanitizedInput = stripDialPlanChars(input, entry.strippedChars);\n const regex = new RegExp(entry.regex);\n\n return regex.test(sanitizedInput);\n } catch (e) {\n LoggerProxy.warn(`Failed to validate dial number against entry \"${entry.name}\": ${e}`, {\n module: 'Utils',\n method: 'isValidDialNumber',\n });\n\n return false;\n }\n });\n};\n\n/**\n * Checks whether a URL's hostname is, or is a subdomain of, one of the allowed domains.\n *\n * @param url - The candidate URL to validate\n * @param allowedDomains - Domains (or domain suffixes) the URL's hostname must match\n * @returns true when the URL parses and its hostname matches an allowed domain, false otherwise\n */\nexport const isAllowedUrlHost = (\n url: string | undefined | null,\n allowedDomains: string[]\n): boolean => {\n if (!url) {\n return false;\n }\n\n try {\n const hostname = new URL(url).hostname.toLowerCase();\n\n return allowedDomains.some((domain) => hostname === domain || hostname.endsWith(`.${domain}`));\n } catch (error) {\n return false;\n }\n};\n\nexport const getStationLoginErrorData = (failure: Failure, loginOption: LoginOption) => {\n let duplicateLocationMessage = 'This value is already in use';\n\n if (loginOption === LoginOption.EXTENSION) {\n duplicateLocationMessage = 'This extension is already in use';\n }\n\n if (loginOption === LoginOption.AGENT_DN) {\n duplicateLocationMessage =\n 'Dial number is in use. Try a different one. For help, reach out to your administrator or support team.';\n }\n\n const errorCodeMessageMap = {\n DUPLICATE_LOCATION: {\n message: duplicateLocationMessage,\n fieldName: loginOption,\n },\n INVALID_DIAL_NUMBER: {\n message:\n 'Enter a valid dial number. For help, reach out to your administrator or support team.',\n fieldName: loginOption,\n },\n };\n\n const defaultMessage = 'An error occurred while logging in to the station';\n const defaultFieldName = 'generic';\n\n const reason = failure?.data?.reason || '';\n\n return {\n message: errorCodeMessageMap[reason]?.message || defaultMessage,\n fieldName: errorCodeMessageMap[reason]?.fieldName || defaultFieldName,\n };\n};\n\n/**\n * Extracts error details and logs the error. Also uploads logs for the error unless it is a silent relogin agent not found error.\n *\n * @param error - The error object, expected to have a `details` property of type Failure.\n * @param methodName - The name of the method where the error occurred.\n * @param moduleName - The name of the module where the error occurred.\n * @returns An object containing the error instance and the reason string.\n * @public\n * @example\n * const details = getErrorDetails(error, 'fetchData', 'DataModule');\n * if (details.error) { handleError(details.error); }\n * @ignore\n */\nexport const getErrorDetails = (error: any, methodName: string, moduleName: string) => {\n let errData = {message: '', fieldName: ''};\n\n const failure = error.details as Failure;\n const reason = failure?.data?.reason ?? `Error while performing ${methodName}`;\n\n if (!(reason === 'AGENT_NOT_FOUND' && methodName === 'silentRelogin')) {\n LoggerProxy.error(`${methodName} failed with reason: ${reason}`, {\n module: moduleName,\n method: methodName,\n trackingId: failure?.trackingId,\n });\n // we can add more conditions here if not needed for specific cases eg: silentReLogin\n WebexRequest.getInstance().uploadLogs({\n correlationId: failure?.trackingId,\n });\n }\n\n if (methodName === 'stationLogin') {\n errData = getStationLoginErrorData(failure, error.loginOption);\n\n LoggerProxy.error(\n `${methodName} failed with reason: ${reason}, message: ${errData.message}, fieldName: ${errData.fieldName}`,\n {\n module: moduleName,\n method: methodName,\n trackingId: failure?.trackingId,\n }\n );\n }\n\n const err = new Error(reason ?? `Error while performing ${methodName}`);\n // @ts-ignore - add custom property to the error object for backward compatibility\n err.data = errData;\n\n return {\n error: err,\n reason,\n };\n};\n\n/**\n * Extracts error details from task API errors and logs them. Also uploads logs for the error.\n * This handles the specific error format returned by task API calls.\n *\n * @param error - The error object from task API calls with structure: {id: string, details: {trackingId: string, msg: {...}}}\n * @param methodName - The name of the method where the error occurred.\n * @param moduleName - The name of the module where the error occurred.\n * @returns AugmentedError containing structured error details on err.data for metrics and logging\n * @public\n * @example\n * const taskError = generateTaskErrorObject(error, 'transfer', 'TaskModule');\n * throw taskError.error;\n * @ignore\n */\nexport const generateTaskErrorObject = (\n error: any,\n methodName: string,\n moduleName: string\n): AugmentedError => {\n const trackingId = error?.details?.trackingId || error?.trackingId || '';\n const errorMsg = error?.details?.msg;\n\n const fallbackMessage =\n (error && typeof error.message === 'string' && error.message) ||\n `Error while performing ${methodName}`;\n const errorMessage = errorMsg?.errorMessage || fallbackMessage;\n const errorType =\n errorMsg?.errorType ||\n (error && typeof error.name === 'string' && error.name) ||\n 'Unknown Error';\n const errorData = errorMsg?.errorData || '';\n const reasonCode = errorMsg?.reasonCode || 0;\n\n // Log and upload for Task API formatted errors\n LoggerProxy.error(`${methodName} failed: ${errorMessage} (${errorType})`, {\n module: moduleName,\n method: methodName,\n trackingId,\n });\n WebexRequest.getInstance().uploadLogs({\n correlationId: trackingId,\n });\n\n const reason = `${errorType}: ${errorMessage}${errorData ? ` (${errorData})` : ''}`;\n const err: AugmentedError = new Error(reason);\n err.data = {\n message: errorMessage,\n errorType,\n errorData,\n reasonCode,\n trackingId,\n };\n\n return err;\n};\n\n/**\n * Creates an error details object suitable for use with the Err.Details class.\n *\n * @param errObj - The Webex request payload object.\n * @returns An instance of Err.Details with the generic failure message and extracted details.\n * @public\n * @example\n * const errDetails = createErrDetailsObject(webexRequestPayload);\n * @ignore\n */\nexport const createErrDetailsObject = (errObj: WebexRequestPayload) => {\n const details = getCommonErrorDetails(errObj);\n\n return new Err.Details('Service.reqs.generic.failure', details);\n};\n\n/*\n/**\n * Gets the consulted agent ID from the media object by finding the agent\n * in the consult media participants (excluding the current agent).\n *\n * @param media - The media object from the interaction\n * @param agentId - The current agent's ID to exclude from the search\n * @returns The consulted agent ID, or empty string if none found\n */\nexport const getConsultedAgentId = (media: Interaction['media'], agentId: string): string => {\n let consultParticipants: string[] = [];\n let consultedParticipantId = '';\n\n Object.keys(media).forEach((key) => {\n if (media[key].mType === STATE_CONSULT) {\n consultParticipants = media[key].participants;\n }\n });\n\n if (consultParticipants.includes(agentId)) {\n const id = consultParticipants.find((participant) => participant !== agentId);\n consultedParticipantId = id || consultedParticipantId;\n }\n\n return consultedParticipantId;\n};\n\n/**\n * Gets the destination agent ID for CBT (Capacity Based Team) scenarios.\n * CBT refers to teams created in Control Hub with capacity-based routing\n * (as opposed to agent-based routing). This handles cases where the consulted\n * participant is not directly in participants but can be found by matching\n * the dial number (dn).\n *\n * @param interaction - The interaction object\n * @param consultingAgent - The consulting agent identifier\n * @returns The destination agent ID for CBT scenarios, or empty string if none found\n */\nexport const getDestAgentIdForCBT = (interaction: Interaction, consultingAgent: string): string => {\n const participants = interaction.participants;\n let destAgentIdForCBT = '';\n\n // Check if this is a CBT scenario (consultingAgent exists but not directly in participants)\n if (consultingAgent && !participants[consultingAgent]) {\n const foundEntry = Object.entries(participants).find(\n ([, participant]: [string, Interaction['participants'][string]]) => {\n return (\n participant.pType.toLowerCase() === PARTICIPANT_TYPES.DN &&\n participant.type === PARTICIPANT_TYPES.AGENT &&\n participant.dn === consultingAgent\n );\n }\n );\n\n if (foundEntry) {\n destAgentIdForCBT = foundEntry[0];\n }\n }\n\n return destAgentIdForCBT;\n};\n\n/**\n * Calculates the destination agent ID for consult operations.\n *\n * @param interaction - The interaction object\n * @param agentId - The current agent's ID\n * @returns The destination agent ID\n */\nexport const calculateDestAgentId = (interaction: Interaction, agentId: string): string => {\n const consultingAgent = getConsultedAgentId(interaction.media, agentId);\n\n // Check if this is a CBT (Capacity Based Team) scenario\n // If not CBT, the function will return empty string and we'll use the normal flow\n const destAgentIdCBT = getDestAgentIdForCBT(interaction, consultingAgent);\n if (destAgentIdCBT) {\n return destAgentIdCBT;\n }\n\n const participant = interaction.participants[consultingAgent];\n if (!participant) {\n return '';\n }\n\n if (participant.type === PARTICIPANT_TYPES.EP_DN) {\n return (participant as InteractionParticipant & {epId?: string}).epId ?? '';\n }\n\n return participant.id ?? '';\n};\n\n/**\n * Calculates the destination agent ID for fetching destination type.\n *\n * @param interaction - The interaction object\n * @param agentId - The current agent's ID\n * @returns The destination agent ID for determining destination type\n */\nexport const calculateDestType = (interaction: Interaction, agentId: string): string => {\n const consultingAgent = getConsultedAgentId(interaction.media, agentId);\n\n // Check if this is a CBT (Capacity Based Team) scenario, otherwise use consultingAgent\n const destAgentIdCBT = getDestAgentIdForCBT(interaction, consultingAgent);\n const destinationaegntId = destAgentIdCBT || consultingAgent;\n const destAgentType = destinationaegntId\n ? interaction.participants[destinationaegntId]?.pType\n : undefined;\n if (destAgentType) {\n if (destAgentType === 'DN') {\n return CONSULT_TRANSFER_DESTINATION_TYPE.DIALNUMBER;\n }\n if (destAgentType === 'EP-DN') {\n return CONSULT_TRANSFER_DESTINATION_TYPE.ENTRYPOINT;\n }\n // Keep the existing destinationType if it's something else (like \"agent\" or \"Agent\")\n // Convert \"Agent\" to lowercase for consistency\n\n return destAgentType.toLowerCase();\n }\n\n return CONSULT_TRANSFER_DESTINATION_TYPE.AGENT;\n};\n\n/**\n * Gets the destination agent ID from participants.\n * Finds a participant who is not the current agent and is an agent type.\n *\n * @param participants - The participants object from interaction\n * @param agentId - The current agent's ID\n * @returns The destination agent ID, or undefined if none found\n */\nexport const buildConsultConferenceParamData = (\n dataPassed: consultConferencePayloadData,\n interactionIdPassed: string\n): {interactionId: string; data: ConsultConferenceData} => {\n const data: ConsultConferenceData = {\n ...('agentId' in dataPassed && {agentId: dataPassed.agentId}),\n to: dataPassed.destAgentId,\n destinationType: '',\n };\n\n if ('destinationType' in dataPassed) {\n const destinationType = String(dataPassed.destinationType || '').trim();\n const normalizedDestinationType = destinationType.toUpperCase().replace(/[-_\\s]/g, '');\n\n if (normalizedDestinationType === 'DN' || normalizedDestinationType === 'DIALNUMBER') {\n data.destinationType = DESTINATION_TYPE.DIALNUMBER;\n } else if (normalizedDestinationType === 'EPDN' || normalizedDestinationType === 'ENTRYPOINT') {\n data.destinationType = DESTINATION_TYPE.ENTRYPOINT;\n } else if (normalizedDestinationType === 'QUEUE') {\n data.destinationType = DESTINATION_TYPE.QUEUE;\n } else if (normalizedDestinationType === 'AGENT') {\n data.destinationType = DESTINATION_TYPE.AGENT;\n } else {\n data.destinationType = destinationType as ConsultConferenceData['destinationType'];\n }\n } else {\n data.destinationType = DESTINATION_TYPE.AGENT;\n }\n\n return {\n interactionId: interactionIdPassed,\n data,\n };\n};\n\n/**\n * Derives the consult transfer destination type based on task data.\n * This function determines the appropriate destination type for a consult transfer\n * by examining the destination type stored in the task data.\n *\n * @param taskData - The task data containing destination information\n * @returns The derived consult transfer destination type\n * @public\n */\nexport const deriveConsultTransferDestinationType = (\n taskData: TaskData\n): ConsultTransferDestinationType => {\n const destType = taskData?.destinationType;\n const normalizedDestType = String(destType || '')\n .toUpperCase()\n .replace(/[-_\\s]/g, '');\n\n // Map destination types to consult transfer destination types\n if (normalizedDestType === 'DN' || normalizedDestType === 'DIALNUMBER') {\n return CONSULT_TRANSFER_DESTINATION_TYPE.DIALNUMBER;\n }\n if (normalizedDestType === 'EPDN' || normalizedDestType === 'ENTRYPOINT') {\n return CONSULT_TRANSFER_DESTINATION_TYPE.ENTRYPOINT;\n }\n if (normalizedDestType === 'QUEUE') {\n return CONSULT_TRANSFER_DESTINATION_TYPE.QUEUE;\n }\n\n // Default to agent if no specific type matches\n return CONSULT_TRANSFER_DESTINATION_TYPE.AGENT;\n};\n"],"mappings":";;;;;;AAAA,IAAAA,GAAA,GAAAC,uBAAA,CAAAC,OAAA;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MAAM,IAAIA,kBAAkB,KAAK,YAAY,EAAE;IACxE,OAAOnB,yCAAiC,CAACE,UAAU;EACrD;EACA,IAAIiB,kBAAkB,KAAK,OAAO,EAAE;IAClC,OAAOnB,yCAAiC,CAACc,KAAK;EAChD;;EAEA;EACA,OAAOd,yCAAiC,CAACV,KAAK;AAChD,CAAC;AAAC3G,OAAA,CAAAqI,oCAAA,GAAAA,oCAAA","ignoreList":[]}
@@ -253,7 +253,7 @@ class AqmReqs {
253
253
  static typeMapCheck(typeMap, msg) {
254
254
  const typeField = typeMap.typeField || 'type';
255
255
  const msgType = msg[typeField];
256
- if (typeMap.conditions && typeMap.conditions[msgType]) {
256
+ if (typeMap.conditions && Object.prototype.hasOwnProperty.call(typeMap.conditions, msgType)) {
257
257
  const condition = typeMap.conditions[msgType];
258
258
  for (const field of Object.keys(condition)) {
259
259
  if (!msg[field] || msg[field] !== condition[field]) {
@@ -1 +1 @@
1
- {"version":3,"names":["Err","_interopRequireWildcard","require","_types","_loggerProxy","_interopRequireDefault","_constants","_constants2","_WebexRequest","e","__esModule","default","t","WeakMap","r","n","o","i","f","__proto__","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","AqmReqs","pendingRequests","pendingNotifCancelrequest","constructor","webSocketManager","webexRequest","WebexRequest","getInstance","on","onMessage","bind","req","c","p","cbRes","makeAPIRequest","reqEmpty","createPromise","Promise","resolve","reject","keySuccess","bindPrint","notifSuccess","keyFail","notifFail","keyCancel","notifCancel","k","timeout","Details","key","msg","isClear","clear","check","bindCheck","handle","alternateBind","alternateBindKey","error","errId","LoggerProxy","log","module","AQM_REQS_FILE","method","METHODS","CREATE_PROMISE","err","response","request","service","host","resource","url","data","HTTP_METHODS","POST","GET","body","then","res","catch","headers","Authorization","Message","window","setTimeout","redactSensitiveLogs","JSON","stringify","TIMEOUT_REQ","result","keys","filter","prop","value","Array","isArray","join","slice","__typeMap","typeMapCheck","bindValue","msgValue","includes","typeMap","typeField","msgType","conditions","condition","field","event","parse","type","info","ON_MESSAGE","keepalive","isHandled","kReq","thisReq","kReqAlt","exports"],"sources":["aqm-reqs.ts"],"sourcesContent":["import {Msg} from './GlobalTypes';\nimport * as Err from './Err';\nimport {HTTP_METHODS, WebexRequestPayload} from '../../types';\nimport LoggerProxy from '../../logger-proxy';\nimport {CbRes, Conf, ConfEmpty, Pending, Req, Res, ResEmpty} from './types';\nimport {TIMEOUT_REQ, METHODS} from './constants';\nimport {AQM_REQS_FILE} from '../../constants';\nimport WebexRequest from './WebexRequest';\nimport {WebSocketManager} from './websocket/WebSocketManager';\n\nexport default class AqmReqs {\n private pendingRequests: Record<string, Pending> = {};\n private pendingNotifCancelrequest: Record<string, Pending> = {};\n private webexRequest: WebexRequest;\n private webSocketManager: WebSocketManager;\n\n constructor(webSocketManager: WebSocketManager) {\n this.webexRequest = WebexRequest.getInstance();\n this.webSocketManager = webSocketManager;\n this.webSocketManager.on('message', this.onMessage.bind(this));\n }\n\n /**\n * Creates a request function for an API call with parameters\n * @param c - The configuration for the request\n * @returns A function that makes the API request\n */\n req<TRes, TErr, TReq>(c: Conf<TRes, TErr, TReq>): Res<TRes, TReq> {\n return (p: TReq, cbRes?: CbRes<TRes>) => this.makeAPIRequest(c(p), cbRes);\n }\n\n /**\n * Creates a request function for an API call with no parameters\n * @param c - The configuration for the request\n * @returns A function that makes the API request\n */\n reqEmpty<TRes, TErr>(c: ConfEmpty<TRes, TErr>): ResEmpty<TRes> {\n return (cbRes?: CbRes<TRes>) => this.makeAPIRequest(c(), cbRes);\n }\n\n /**\n * Makes an API request\n * @param c - The request configuration\n * @param cbRes - The callback for the response\n * @returns A promise that resolves with the response or rejects with an error\n */\n private async makeAPIRequest<TRes, TErr>(c: Req<TRes, TErr>, cbRes?: CbRes<TRes>): Promise<TRes> {\n return this.createPromise(c, cbRes);\n }\n\n /**\n * Creates a promise for an API request\n * @param c - The request configuration\n * @param cbRes - The callback for the response\n * @returns A promise that resolves with the response or rejects with an error\n */\n private createPromise<TRes, TErr>(c: Req<TRes, TErr>, cbRes?: CbRes<TRes>) {\n return new Promise<TRes>((resolve, reject) => {\n const keySuccess = this.bindPrint(c.notifSuccess.bind);\n const keyFail = c.notifFail ? this.bindPrint(c.notifFail.bind) : null;\n const keyCancel = c.notifCancel?.bind ? this.bindPrint(c.notifCancel.bind) : null;\n let k = '';\n if (this.pendingRequests[keySuccess]) {\n k = keySuccess;\n }\n if (keyFail && this.pendingRequests[keyFail]) {\n k += keyFail;\n }\n if (k && c.timeout !== 'disabled') {\n reject(\n new Err.Details('Service.aqm.reqs.Pending', {\n key: k,\n msg: 'The request has been already created, multiple requests are not allowed.',\n })\n );\n\n return;\n }\n\n let isClear = false;\n const clear = () => {\n delete this.pendingRequests[keySuccess];\n if (keyFail) {\n delete this.pendingRequests[keyFail];\n }\n if (keyCancel) {\n delete this.pendingNotifCancelrequest[keyCancel];\n }\n isClear = true;\n };\n\n this.pendingRequests[keySuccess] = {\n check: (msg: Msg) => this.bindCheck(c.notifSuccess.bind, msg),\n handle: (msg: Msg) => {\n clear();\n resolve(msg as any);\n },\n };\n if (keyCancel) {\n this.pendingRequests[keySuccess].alternateBind = keyCancel;\n this.pendingNotifCancelrequest[keyCancel] = {\n check: (msg: Msg) => this.bindCheck(c.notifCancel?.bind, msg),\n handle: (msg: Msg) => {\n const alternateBindKey = this.pendingNotifCancelrequest[keyCancel].alternateBind;\n if (alternateBindKey) {\n this.pendingRequests[alternateBindKey].handle(msg);\n }\n },\n alternateBind: keySuccess,\n };\n }\n\n if (keyFail) {\n this.pendingRequests[keyFail] = {\n check: (msg: Msg) => this.bindCheck(c.notifFail!.bind, msg),\n handle: (msg: Msg) => {\n clear();\n const notifFail = c.notifFail!;\n if ('errId' in notifFail) {\n const error = new Err.Details(notifFail.errId, msg as any);\n\n // The raw routing-failure payload/error is never logged verbatim; only a\n // redacted, non-sensitive diagnostic is emitted regardless of redactSensitiveLogs.\n LoggerProxy.log('Routing request failed (sensitive details redacted)', {\n module: AQM_REQS_FILE,\n method: METHODS.CREATE_PROMISE,\n });\n reject(error);\n } else {\n reject(notifFail.err(msg as any));\n }\n },\n };\n }\n let response: WebexRequestPayload | null = null;\n this.webexRequest\n .request({\n service: c.host ?? '',\n resource: c.url,\n // eslint-disable-next-line no-nested-ternary\n method: c.method ? c.method : c.data ? HTTP_METHODS.POST : HTTP_METHODS.GET,\n\n body: c.data,\n })\n .then((res: any) => {\n response = res;\n if (cbRes) {\n cbRes(res);\n }\n })\n .catch((error: WebexRequestPayload) => {\n clear();\n if (error?.headers) {\n error.headers.Authorization = '*';\n }\n if (error?.headers) {\n error.headers.Authorization = '*';\n }\n if (typeof c.err === 'function') {\n reject(c.err(error));\n } else if (typeof c.err === 'string') {\n reject(new Err.Message(c.err));\n } else {\n reject(new Err.Message('Service.aqm.reqs.GenericRequestError'));\n }\n });\n\n if (c.timeout !== 'disabled') {\n window.setTimeout(\n () => {\n if (isClear) {\n return;\n }\n clear();\n if (response?.headers) {\n response.headers.Authorization = '*';\n }\n if (c.redactSensitiveLogs) {\n LoggerProxy.error('Routing request timeout (sensitive details redacted)', {\n module: AQM_REQS_FILE,\n method: METHODS.CREATE_PROMISE,\n });\n } else {\n LoggerProxy.error(\n `Routing request timeout${keySuccess}${JSON.stringify(response)}${c.url}`,\n {\n module: AQM_REQS_FILE,\n method: METHODS.CREATE_PROMISE,\n }\n );\n }\n reject(\n new Err.Details('Service.aqm.reqs.Timeout', {\n key: keySuccess,\n response: response!,\n })\n );\n },\n c.timeout && c.timeout > 0 ? c.timeout : TIMEOUT_REQ\n );\n }\n });\n }\n\n /**\n * Converts a bind object to a string representation\n * @param bind - The bind object to convert\n * @returns A string representation of the bind object\n */\n private bindPrint(bind: any): string {\n let result = '';\n for (const key of Object.keys(bind).filter((prop) => prop !== '__typeMap')) {\n const value = bind[key];\n\n if (Array.isArray(value)) {\n result += `${key}=[${value.join(',')}],`;\n } else if (typeof value === 'object' && value !== null) {\n result += `${key}=(${this.bindPrint(value)}),`;\n } else {\n result += `${key}=${value},`;\n }\n }\n\n return result ? result.slice(0, -1) : result;\n }\n\n /**\n * Checks if a message matches a bind object\n * @param bind - The bind object to check against\n * @param msg - The message to check\n * @returns True if the message matches the bind object, false otherwise\n */\n private bindCheck(bind: any, msg: any): boolean {\n // Handle type-dependent field matching if __typeMap is present\n if (bind.__typeMap && typeof bind.__typeMap === 'object') {\n if (!AqmReqs.typeMapCheck(bind.__typeMap, msg)) {\n return false;\n }\n }\n\n for (const key of Object.keys(bind).filter((prop) => prop !== '__typeMap')) {\n const bindValue = bind[key];\n const msgValue = msg[key];\n\n if (Array.isArray(bindValue)) {\n // Check if the message value matches any of the values in the array\n if (!bindValue.includes(msgValue)) {\n return false;\n }\n } else if (typeof bindValue === 'object' && bindValue !== null) {\n if (typeof msgValue === 'object' && msgValue !== null) {\n if (!this.bindCheck(bindValue, msgValue)) {\n return false;\n }\n } else {\n return false;\n }\n } else if (!msgValue || msgValue !== bindValue) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Checks type-dependent field conditions defined in __typeMap.\n * @param typeMap - The type map to check against\n * @param msg - The message to check\n * @returns True if the message matches the type map, false otherwise\n * The typeMap has the shape:\n * { typeField: \"type\", conditions: { EventA: { field: value }, EventB: { field: value } } }\n * It reads msg[typeField] to determine which condition set to apply,\n * then verifies all fields in that condition match the message.\n */\n private static typeMapCheck(typeMap: any, msg: any): boolean {\n const typeField = typeMap.typeField || 'type';\n const msgType = msg[typeField];\n\n if (typeMap.conditions && typeMap.conditions[msgType]) {\n const condition = typeMap.conditions[msgType];\n for (const field of Object.keys(condition)) {\n if (!msg[field] || msg[field] !== condition[field]) {\n return false;\n }\n }\n\n return true;\n }\n\n return false;\n }\n\n /**\n * Handles incoming messages from the WebSocket (must be a lambda fn)\n * @param msg - The message to handle\n * @returns\n */\n private readonly onMessage = (msg: any) => {\n const event = JSON.parse(msg);\n if (event.type === 'Welcome') {\n LoggerProxy.info(`Welcome message from Notifs Websocket`, {\n module: AQM_REQS_FILE,\n method: METHODS.ON_MESSAGE,\n });\n\n return;\n }\n\n if (event.keepalive === 'true') {\n return;\n }\n\n if (event.type === 'AgentReloginFailed') {\n LoggerProxy.info('Silently handling the agent relogin fail', {\n module: AQM_REQS_FILE,\n method: METHODS.ON_MESSAGE,\n });\n }\n\n let isHandled = false;\n\n const kReq = Object.keys(this.pendingRequests);\n for (const thisReq of kReq) {\n const req = this.pendingRequests[thisReq];\n if (req.check(event)) {\n req.handle(event);\n isHandled = true;\n break;\n }\n }\n // pendingNotifCancelrequest stores the secondary bind key, checks for the secondary bind key and handles the event\n const kReqAlt = Object.keys(this.pendingNotifCancelrequest);\n for (const thisReq of kReqAlt) {\n const req = this.pendingNotifCancelrequest[thisReq];\n if (req.check(event)) {\n req.handle(event);\n isHandled = true;\n }\n }\n\n // TODO: add event emitter for unhandled events to replicate event.listen or .on\n\n if (!isHandled) {\n LoggerProxy.info(`event=missingEventHandler | [AqmReqs] missing routing message handler`, {\n module: AQM_REQS_FILE,\n method: METHODS.ON_MESSAGE,\n });\n }\n };\n}\n"],"mappings":";;;;;;AACA,IAAAA,GAAA,GAAAC,uBAAA,CAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,YAAA,GAAAC,sBAAA,CAAAH,OAAA;AAEA,IAAAI,UAAA,GAAAJ,OAAA;AACA,IAAAK,WAAA,GAAAL,OAAA;AACA,IAAAM,aAAA,GAAAH,sBAAA,CAAAH,OAAA;AAA0C,SAAAG,uBAAAI,CAAA,WAAAA,CAAA,IAAAA,CAAA,CAAAC,UAAA,GAAAD,CAAA,KAAAE,OAAA,EAAAF,CAAA;AAAA,SAAAR,wBAAAQ,CAAA,EAAAG,CAAA,6BAAAC,OAAA,MAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAZ,uBAAA,YAAAA,CAAAQ,CAAA,EAAAG,CAAA,SAAAA,CAAA,IAAAH,CAAA,IAAAA,CAAA,CAAAC,UAAA,SAAAD,CA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D,KAAK,CAAC;QACjBM,SAAS,GAAG,IAAI;QAChB;MACF;IACF;IACA;IACA,MAAMG,OAAO,GAAGzG,MAAM,CAAC6E,IAAI,CAAC,IAAI,CAACxE,yBAAyB,CAAC;IAC3D,KAAK,MAAMmG,OAAO,IAAIC,OAAO,EAAE;MAC7B,MAAM3F,GAAG,GAAG,IAAI,CAACT,yBAAyB,CAACmG,OAAO,CAAC;MACnD,IAAI1F,GAAG,CAACwB,KAAK,CAAC0D,KAAK,CAAC,EAAE;QACpBlF,GAAG,CAAC0B,MAAM,CAACwD,KAAK,CAAC;QACjBM,SAAS,GAAG,IAAI;MAClB;IACF;;IAEA;;IAEA,IAAI,CAACA,SAAS,EAAE;MACdzD,oBAAW,CAACsD,IAAI,CAAC,uEAAuE,EAAE;QACxFpD,MAAM,EAAEC,yBAAa;QACrBC,MAAM,EAAEC,kBAAO,CAACkD;MAClB,CAAC,CAAC;IACJ;EACF,CAAC;AACH;AAACM,OAAA,CAAAxH,OAAA,GAAAiB,OAAA","ignoreList":[]}
1
+ {"version":3,"names":["Err","_interopRequireWildcard","require","_types","_loggerProxy","_interopRequireDefault","_constants","_constants2","_WebexRequest","e","__esModule","default","t","WeakMap","r","n","o","i","f","__proto__","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","AqmReqs","pendingRequests","pendingNotifCancelrequest","constructor","webSocketManager","webexRequest","WebexRequest","getInstance","on","onMessage","bind","req","c","p","cbRes","makeAPIRequest","reqEmpty","createPromise","Promise","resolve","reject","keySuccess","bindPrint","notifSuccess","keyFail","notifFail","keyCancel","notifCancel","k","timeout","Details","key","msg","isClear","clear","check","bindCheck","handle","alternateBind","alternateBindKey","error","errId","LoggerProxy","log","module","AQM_REQS_FILE","method","METHODS","CREATE_PROMISE","err","response","request","service","host","resource","url","data","HTTP_METHODS","POST","GET","body","then","res","catch","headers","Authorization","Message","window","setTimeout","redactSensitiveLogs","JSON","stringify","TIMEOUT_REQ","result","keys","filter","prop","value","Array","isArray","join","slice","__typeMap","typeMapCheck","bindValue","msgValue","includes","typeMap","typeField","msgType","conditions","prototype","condition","field","event","parse","type","info","ON_MESSAGE","keepalive","isHandled","kReq","thisReq","kReqAlt","exports"],"sources":["aqm-reqs.ts"],"sourcesContent":["import {Msg} from './GlobalTypes';\nimport * as Err from './Err';\nimport {HTTP_METHODS, WebexRequestPayload} from '../../types';\nimport LoggerProxy from '../../logger-proxy';\nimport {CbRes, Conf, ConfEmpty, Pending, Req, Res, ResEmpty} from './types';\nimport {TIMEOUT_REQ, METHODS} from './constants';\nimport {AQM_REQS_FILE} from '../../constants';\nimport WebexRequest from './WebexRequest';\nimport {WebSocketManager} from './websocket/WebSocketManager';\n\nexport default class AqmReqs {\n private pendingRequests: Record<string, Pending> = {};\n private pendingNotifCancelrequest: Record<string, Pending> = {};\n private webexRequest: WebexRequest;\n private webSocketManager: WebSocketManager;\n\n constructor(webSocketManager: WebSocketManager) {\n this.webexRequest = WebexRequest.getInstance();\n this.webSocketManager = webSocketManager;\n this.webSocketManager.on('message', this.onMessage.bind(this));\n }\n\n /**\n * Creates a request function for an API call with parameters\n * @param c - The configuration for the request\n * @returns A function that makes the API request\n */\n req<TRes, TErr, TReq>(c: Conf<TRes, TErr, TReq>): Res<TRes, TReq> {\n return (p: TReq, cbRes?: CbRes<TRes>) => this.makeAPIRequest(c(p), cbRes);\n }\n\n /**\n * Creates a request function for an API call with no parameters\n * @param c - The configuration for the request\n * @returns A function that makes the API request\n */\n reqEmpty<TRes, TErr>(c: ConfEmpty<TRes, TErr>): ResEmpty<TRes> {\n return (cbRes?: CbRes<TRes>) => this.makeAPIRequest(c(), cbRes);\n }\n\n /**\n * Makes an API request\n * @param c - The request configuration\n * @param cbRes - The callback for the response\n * @returns A promise that resolves with the response or rejects with an error\n */\n private async makeAPIRequest<TRes, TErr>(c: Req<TRes, TErr>, cbRes?: CbRes<TRes>): Promise<TRes> {\n return this.createPromise(c, cbRes);\n }\n\n /**\n * Creates a promise for an API request\n * @param c - The request configuration\n * @param cbRes - The callback for the response\n * @returns A promise that resolves with the response or rejects with an error\n */\n private createPromise<TRes, TErr>(c: Req<TRes, TErr>, cbRes?: CbRes<TRes>) {\n return new Promise<TRes>((resolve, reject) => {\n const keySuccess = this.bindPrint(c.notifSuccess.bind);\n const keyFail = c.notifFail ? this.bindPrint(c.notifFail.bind) : null;\n const keyCancel = c.notifCancel?.bind ? this.bindPrint(c.notifCancel.bind) : null;\n let k = '';\n if (this.pendingRequests[keySuccess]) {\n k = keySuccess;\n }\n if (keyFail && this.pendingRequests[keyFail]) {\n k += keyFail;\n }\n if (k && c.timeout !== 'disabled') {\n reject(\n new Err.Details('Service.aqm.reqs.Pending', {\n key: k,\n msg: 'The request has been already created, multiple requests are not allowed.',\n })\n );\n\n return;\n }\n\n let isClear = false;\n const clear = () => {\n delete this.pendingRequests[keySuccess];\n if (keyFail) {\n delete this.pendingRequests[keyFail];\n }\n if (keyCancel) {\n delete this.pendingNotifCancelrequest[keyCancel];\n }\n isClear = true;\n };\n\n this.pendingRequests[keySuccess] = {\n check: (msg: Msg) => this.bindCheck(c.notifSuccess.bind, msg),\n handle: (msg: Msg) => {\n clear();\n resolve(msg as any);\n },\n };\n if (keyCancel) {\n this.pendingRequests[keySuccess].alternateBind = keyCancel;\n this.pendingNotifCancelrequest[keyCancel] = {\n check: (msg: Msg) => this.bindCheck(c.notifCancel?.bind, msg),\n handle: (msg: Msg) => {\n const alternateBindKey = this.pendingNotifCancelrequest[keyCancel].alternateBind;\n if (alternateBindKey) {\n this.pendingRequests[alternateBindKey].handle(msg);\n }\n },\n alternateBind: keySuccess,\n };\n }\n\n if (keyFail) {\n this.pendingRequests[keyFail] = {\n check: (msg: Msg) => this.bindCheck(c.notifFail!.bind, msg),\n handle: (msg: Msg) => {\n clear();\n const notifFail = c.notifFail!;\n if ('errId' in notifFail) {\n const error = new Err.Details(notifFail.errId, msg as any);\n\n // The raw routing-failure payload/error is never logged verbatim; only a\n // redacted, non-sensitive diagnostic is emitted regardless of redactSensitiveLogs.\n LoggerProxy.log('Routing request failed (sensitive details redacted)', {\n module: AQM_REQS_FILE,\n method: METHODS.CREATE_PROMISE,\n });\n reject(error);\n } else {\n reject(notifFail.err(msg as any));\n }\n },\n };\n }\n let response: WebexRequestPayload | null = null;\n this.webexRequest\n .request({\n service: c.host ?? '',\n resource: c.url,\n // eslint-disable-next-line no-nested-ternary\n method: c.method ? c.method : c.data ? HTTP_METHODS.POST : HTTP_METHODS.GET,\n\n body: c.data,\n })\n .then((res: any) => {\n response = res;\n if (cbRes) {\n cbRes(res);\n }\n })\n .catch((error: WebexRequestPayload) => {\n clear();\n if (error?.headers) {\n error.headers.Authorization = '*';\n }\n if (error?.headers) {\n error.headers.Authorization = '*';\n }\n if (typeof c.err === 'function') {\n reject(c.err(error));\n } else if (typeof c.err === 'string') {\n reject(new Err.Message(c.err));\n } else {\n reject(new Err.Message('Service.aqm.reqs.GenericRequestError'));\n }\n });\n\n if (c.timeout !== 'disabled') {\n window.setTimeout(\n () => {\n if (isClear) {\n return;\n }\n clear();\n if (response?.headers) {\n response.headers.Authorization = '*';\n }\n if (c.redactSensitiveLogs) {\n LoggerProxy.error('Routing request timeout (sensitive details redacted)', {\n module: AQM_REQS_FILE,\n method: METHODS.CREATE_PROMISE,\n });\n } else {\n LoggerProxy.error(\n `Routing request timeout${keySuccess}${JSON.stringify(response)}${c.url}`,\n {\n module: AQM_REQS_FILE,\n method: METHODS.CREATE_PROMISE,\n }\n );\n }\n reject(\n new Err.Details('Service.aqm.reqs.Timeout', {\n key: keySuccess,\n response: response!,\n })\n );\n },\n c.timeout && c.timeout > 0 ? c.timeout : TIMEOUT_REQ\n );\n }\n });\n }\n\n /**\n * Converts a bind object to a string representation\n * @param bind - The bind object to convert\n * @returns A string representation of the bind object\n */\n private bindPrint(bind: any): string {\n let result = '';\n for (const key of Object.keys(bind).filter((prop) => prop !== '__typeMap')) {\n const value = bind[key];\n\n if (Array.isArray(value)) {\n result += `${key}=[${value.join(',')}],`;\n } else if (typeof value === 'object' && value !== null) {\n result += `${key}=(${this.bindPrint(value)}),`;\n } else {\n result += `${key}=${value},`;\n }\n }\n\n return result ? result.slice(0, -1) : result;\n }\n\n /**\n * Checks if a message matches a bind object\n * @param bind - The bind object to check against\n * @param msg - The message to check\n * @returns True if the message matches the bind object, false otherwise\n */\n private bindCheck(bind: any, msg: any): boolean {\n // Handle type-dependent field matching if __typeMap is present\n if (bind.__typeMap && typeof bind.__typeMap === 'object') {\n if (!AqmReqs.typeMapCheck(bind.__typeMap, msg)) {\n return false;\n }\n }\n\n for (const key of Object.keys(bind).filter((prop) => prop !== '__typeMap')) {\n const bindValue = bind[key];\n const msgValue = msg[key];\n\n if (Array.isArray(bindValue)) {\n // Check if the message value matches any of the values in the array\n if (!bindValue.includes(msgValue)) {\n return false;\n }\n } else if (typeof bindValue === 'object' && bindValue !== null) {\n if (typeof msgValue === 'object' && msgValue !== null) {\n if (!this.bindCheck(bindValue, msgValue)) {\n return false;\n }\n } else {\n return false;\n }\n } else if (!msgValue || msgValue !== bindValue) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Checks type-dependent field conditions defined in __typeMap.\n * @param typeMap - The type map to check against\n * @param msg - The message to check\n * @returns True if the message matches the type map, false otherwise\n * The typeMap has the shape:\n * { typeField: \"type\", conditions: { EventA: { field: value }, EventB: { field: value } } }\n * It reads msg[typeField] to determine which condition set to apply,\n * then verifies all fields in that condition match the message.\n */\n private static typeMapCheck(typeMap: any, msg: any): boolean {\n const typeField = typeMap.typeField || 'type';\n const msgType = msg[typeField];\n\n if (typeMap.conditions && Object.prototype.hasOwnProperty.call(typeMap.conditions, msgType)) {\n const condition = typeMap.conditions[msgType];\n for (const field of Object.keys(condition)) {\n if (!msg[field] || msg[field] !== condition[field]) {\n return false;\n }\n }\n\n return true;\n }\n\n return false;\n }\n\n /**\n * Handles incoming messages from the WebSocket (must be a lambda fn)\n * @param msg - The message to handle\n * @returns\n */\n private readonly onMessage = (msg: any) => {\n const event = JSON.parse(msg);\n if (event.type === 'Welcome') {\n LoggerProxy.info(`Welcome message from Notifs Websocket`, {\n module: AQM_REQS_FILE,\n method: METHODS.ON_MESSAGE,\n });\n\n return;\n }\n\n if (event.keepalive === 'true') {\n return;\n }\n\n if (event.type === 'AgentReloginFailed') {\n LoggerProxy.info('Silently handling the agent relogin fail', {\n module: AQM_REQS_FILE,\n method: METHODS.ON_MESSAGE,\n });\n }\n\n let isHandled = false;\n\n const kReq = Object.keys(this.pendingRequests);\n for (const thisReq of kReq) {\n const req = this.pendingRequests[thisReq];\n if (req.check(event)) {\n req.handle(event);\n isHandled = true;\n break;\n }\n }\n // pendingNotifCancelrequest stores the secondary bind key, checks for the secondary bind key and handles the event\n const kReqAlt = Object.keys(this.pendingNotifCancelrequest);\n for (const thisReq of kReqAlt) {\n const req = this.pendingNotifCancelrequest[thisReq];\n if (req.check(event)) {\n req.handle(event);\n isHandled = true;\n }\n }\n\n // TODO: add event emitter for unhandled events to replicate event.listen or .on\n\n if (!isHandled) {\n LoggerProxy.info(`event=missingEventHandler | [AqmReqs] missing routing message handler`, {\n module: AQM_REQS_FILE,\n method: METHODS.ON_MESSAGE,\n });\n }\n };\n}\n"],"mappings":";;;;;;AACA,IAAAA,GAAA,GAAAC,uBAAA,CAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,YAAA,GAAAC,sBAAA,CAAAH,OAAA;AAEA,IAAAI,UAAA,GAAAJ,OAAA;AACA,IAAAK,WAAA,GAAAL,OAAA;AACA,IAAAM,aAAA,GAAAH,sBAAA,CAAAH,OAAA;AAA0C,SAAAG,uBAAAI,CAAA,WAAAA,CAAA,IAAAA,CAAA,CAAAC,UAAA,GAAAD,CAAA,KAAAE,OAAA,EAAAF,CAAA;AAAA,SAAAR,wBAAAQ,CAAA,EAAAG,CAAA,6BAAAC,OAAA,MAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAZ,uBAAA,YAAA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AM1F,GAAG,GAAG,IAAI,CAACV,eAAe,CAACqG,OAAO,CAAC;MACzC,IAAI3F,GAAG,CAACwB,KAAK,CAAC2D,KAAK,CAAC,EAAE;QACpBnF,GAAG,CAAC0B,MAAM,CAACyD,KAAK,CAAC;QACjBM,SAAS,GAAG,IAAI;QAChB;MACF;IACF;IACA;IACA,MAAMG,OAAO,GAAG1G,MAAM,CAAC6E,IAAI,CAAC,IAAI,CAACxE,yBAAyB,CAAC;IAC3D,KAAK,MAAMoG,OAAO,IAAIC,OAAO,EAAE;MAC7B,MAAM5F,GAAG,GAAG,IAAI,CAACT,yBAAyB,CAACoG,OAAO,CAAC;MACnD,IAAI3F,GAAG,CAACwB,KAAK,CAAC2D,KAAK,CAAC,EAAE;QACpBnF,GAAG,CAAC0B,MAAM,CAACyD,KAAK,CAAC;QACjBM,SAAS,GAAG,IAAI;MAClB;IACF;;IAEA;;IAEA,IAAI,CAACA,SAAS,EAAE;MACd1D,oBAAW,CAACuD,IAAI,CAAC,uEAAuE,EAAE;QACxFrD,MAAM,EAAEC,yBAAa;QACrBC,MAAM,EAAEC,kBAAO,CAACmD;MAClB,CAAC,CAAC;IACJ;EACF,CAAC;AACH;AAACM,OAAA,CAAAzH,OAAA,GAAAiB,OAAA","ignoreList":[]}
@@ -9,6 +9,7 @@ var _loggerProxy = _interopRequireDefault(require("../../../logger-proxy"));
9
9
  var _constants = require("../constants");
10
10
  var _constants2 = require("../../../constants");
11
11
  var _constants3 = require("../../constants");
12
+ var _Utils = require("../Utils");
12
13
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
13
14
  class ConnectionService extends _events.EventEmitter {
14
15
  connectionProp = {
@@ -67,7 +68,23 @@ class ConnectionService extends _events.EventEmitter {
67
68
  this.connectionProp = prop;
68
69
  }
69
70
  onPing = event => {
70
- const parsedEvent = JSON.parse(event);
71
+ let parsedEvent;
72
+ try {
73
+ parsedEvent = JSON.parse(event);
74
+ } catch (error) {
75
+ _loggerProxy.default.error(`onPing failed to parse payload: ${error?.message}`, {
76
+ module: _constants2.CONNECTION_SERVICE_FILE,
77
+ method: _constants.METHODS.ON_PING
78
+ });
79
+ return;
80
+ }
81
+ if (!(0, _Utils.isRecord)(parsedEvent)) {
82
+ _loggerProxy.default.error(`onPing received non-object payload, ignoring`, {
83
+ module: _constants2.CONNECTION_SERVICE_FILE,
84
+ method: _constants.METHODS.ON_PING
85
+ });
86
+ return;
87
+ }
71
88
  if (this.reconnectingTimer) {
72
89
  clearTimeout(this.reconnectingTimer);
73
90
  }
@@ -1 +1 @@
1
- {"version":3,"names":["_events","require","_loggerProxy","_interopRequireDefault","_constants","_constants2","_constants3","e","__esModule","default","ConnectionService","EventEmitter","connectionProp","lostConnectionRecoveryTimeout","LOST_CONNECTION_RECOVERY_TIMEOUT","wsDisconnectAllowed","WS_DISCONNECT_ALLOWED","constructor","options","webSocketManager","subscribeRequest","isConnectionLost","isRestoreFailed","isSocketReconnected","isKeepAlive","setupEventListeners","on","onPing","bind","onSocketClose","dispatchConnectionEvent","socketReconnected","event","isSocketClosed","handleConnectionLost","LoggerProxy","info","module","CONNECTION_SERVICE_FILE","method","METHODS","DISPATCH_CONNECTION_EVENT","emit","clearTimerOnRestoreFailed","reconnectInterval","clearInterval","handleRestoreFailed","shouldReconnect","updateConnectionData","setConnectionProp","prop","parsedEvent","JSON","parse","reconnectingTimer","clearTimeout","restoreTimer","keepalive","setTimeout","handleSocketClose","HANDLE_SOCKET_CLOSE","onlineStatus","navigator","onLine","initWebSocket","body","resource","SUBSCRIBE_API","Error","setInterval","CONNECTIVITY_CHECK_INTERVAL","exports"],"sources":["connection-service.ts"],"sourcesContent":["import {EventEmitter} from 'events';\nimport {WebSocketManager} from './WebSocketManager';\nimport LoggerProxy from '../../../logger-proxy';\nimport {ConnectionServiceOptions, ConnectionLostDetails, ConnectionProp} from './types';\nimport {\n LOST_CONNECTION_RECOVERY_TIMEOUT,\n WS_DISCONNECT_ALLOWED,\n CONNECTIVITY_CHECK_INTERVAL,\n METHODS,\n} from '../constants';\nimport {CONNECTION_SERVICE_FILE} from '../../../constants';\nimport {SubscribeRequest} from '../../../types';\nimport {SUBSCRIBE_API} from '../../constants';\n\nexport class ConnectionService extends EventEmitter {\n private connectionProp: ConnectionProp = {\n lostConnectionRecoveryTimeout: LOST_CONNECTION_RECOVERY_TIMEOUT,\n };\n\n private wsDisconnectAllowed = WS_DISCONNECT_ALLOWED;\n private reconnectingTimer: ReturnType<typeof setTimeout>;\n private restoreTimer: ReturnType<typeof setTimeout>;\n private isConnectionLost: boolean;\n private isRestoreFailed: boolean;\n private isSocketReconnected: boolean;\n private isKeepAlive: boolean;\n private reconnectInterval: ReturnType<typeof setInterval>;\n private webSocketManager: WebSocketManager;\n private subscribeRequest: SubscribeRequest;\n\n constructor(options: ConnectionServiceOptions) {\n super();\n this.webSocketManager = options.webSocketManager;\n this.subscribeRequest = options.subscribeRequest;\n\n this.isConnectionLost = false;\n this.isRestoreFailed = false;\n this.isSocketReconnected = false;\n this.isKeepAlive = false;\n\n this.setupEventListeners();\n }\n\n private setupEventListeners() {\n this.webSocketManager.on('message', this.onPing.bind(this));\n this.webSocketManager.on('socketClose', this.onSocketClose.bind(this));\n }\n\n private dispatchConnectionEvent(socketReconnected = false): void {\n const event: ConnectionLostDetails = {\n isConnectionLost: this.isConnectionLost,\n isRestoreFailed: this.isRestoreFailed,\n isSocketReconnected:\n !this.webSocketManager.isSocketClosed && (socketReconnected || this.isSocketReconnected),\n isKeepAlive: this.isKeepAlive,\n };\n this.webSocketManager.handleConnectionLost(event);\n LoggerProxy.info(`Dispatching connection event`, {\n module: CONNECTION_SERVICE_FILE,\n method: METHODS.DISPATCH_CONNECTION_EVENT,\n });\n this.emit('connectionLost', event);\n }\n\n private handleConnectionLost = (): void => {\n this.isConnectionLost = true;\n this.dispatchConnectionEvent();\n };\n\n private clearTimerOnRestoreFailed = async () => {\n if (this.reconnectInterval) {\n clearInterval(this.reconnectInterval);\n }\n };\n\n private handleRestoreFailed = async () => {\n this.isRestoreFailed = true;\n this.webSocketManager.shouldReconnect = false;\n this.dispatchConnectionEvent();\n await this.clearTimerOnRestoreFailed();\n };\n\n private updateConnectionData = (): void => {\n this.isRestoreFailed = false;\n this.isConnectionLost = false;\n this.isSocketReconnected = false;\n };\n\n public setConnectionProp(prop: ConnectionProp): void {\n this.connectionProp = prop;\n }\n\n private onPing = (event: any): void => {\n const parsedEvent = JSON.parse(event);\n if (this.reconnectingTimer) {\n clearTimeout(this.reconnectingTimer);\n }\n if (this.restoreTimer) {\n clearTimeout(this.restoreTimer);\n }\n this.isKeepAlive = parsedEvent.keepalive === 'true';\n\n if (\n ((this.isConnectionLost && !this.isRestoreFailed) || this.isKeepAlive) &&\n !this.isSocketReconnected\n ) {\n this.updateConnectionData();\n this.dispatchConnectionEvent();\n } else if (this.isSocketReconnected && this.isKeepAlive) {\n this.updateConnectionData();\n this.dispatchConnectionEvent(true);\n }\n\n this.reconnectingTimer = setTimeout(this.handleConnectionLost, this.wsDisconnectAllowed);\n this.restoreTimer = setTimeout(\n this.handleRestoreFailed,\n this.connectionProp && this.connectionProp.lostConnectionRecoveryTimeout\n );\n };\n\n private handleSocketClose = async (): Promise<void> => {\n LoggerProxy.info(`event=socketConnectionRetry | Trying to reconnect to websocket`, {\n module: CONNECTION_SERVICE_FILE,\n method: METHODS.HANDLE_SOCKET_CLOSE,\n });\n const onlineStatus = navigator.onLine;\n if (onlineStatus) {\n await this.webSocketManager.initWebSocket({\n body: this.subscribeRequest,\n resource: SUBSCRIBE_API,\n });\n await this.clearTimerOnRestoreFailed();\n this.isSocketReconnected = true;\n } else {\n throw new Error('event=socketConnectionRetry | browser network not available');\n }\n };\n\n private onSocketClose = (): void => {\n this.clearTimerOnRestoreFailed();\n\n this.reconnectInterval = setInterval(async () => {\n await this.handleSocketClose();\n }, CONNECTIVITY_CHECK_INTERVAL);\n };\n}\n"],"mappings":";;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,YAAA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;MACtC,IAAI,CAACpB,mBAAmB,GAAG,IAAI;IACjC,CAAC,MAAM;MACL,MAAM,IAAI6C,KAAK,CAAC,6DAA6D,CAAC;IAChF;EACF,CAAC;EAEOvC,aAAa,GAAGA,CAAA,KAAY;IAClC,IAAI,CAACc,yBAAyB,CAAC,CAAC;IAEhC,IAAI,CAACC,iBAAiB,GAAGyB,WAAW,CAAC,YAAY;MAC/C,MAAM,IAAI,CAACV,iBAAiB,CAAC,CAAC;IAChC,CAAC,EAAEW,sCAA2B,CAAC;EACjC,CAAC;AACH;AAACC,OAAA,CAAA7D,iBAAA,GAAAA,iBAAA","ignoreList":[]}
1
+ {"version":3,"names":["_events","require","_loggerProxy","_interopRequireDefault","_constants","_constants2","_constants3","_Utils","e","__esModule","default","ConnectionService","EventEmitter","connectionProp","lostConnectionRecoveryTimeout","LOST_CONNECTION_RECOVERY_TIMEOUT","wsDisconnectAllowed","WS_DISCONNECT_ALLOWED","constructor","options","webSocketManager","subscribeRequest","isConnectionLost","isRestoreFailed","isSocketReconnected","isKeepAlive","setupEventListeners","on","onPing","bind","onSocketClose","dispatchConnectionEvent","socketReconnected","event","isSocketClosed","handleConnectionLost","LoggerProxy","info","module","CONNECTION_SERVICE_FILE","method","METHODS","DISPATCH_CONNECTION_EVENT","emit","clearTimerOnRestoreFailed","reconnectInterval","clearInterval","handleRestoreFailed","shouldReconnect","updateConnectionData","setConnectionProp","prop","parsedEvent","JSON","parse","error","message","ON_PING","isRecord","reconnectingTimer","clearTimeout","restoreTimer","keepalive","setTimeout","handleSocketClose","HANDLE_SOCKET_CLOSE","onlineStatus","navigator","onLine","initWebSocket","body","resource","SUBSCRIBE_API","Error","setInterval","CONNECTIVITY_CHECK_INTERVAL","exports"],"sources":["connection-service.ts"],"sourcesContent":["import {EventEmitter} from 'events';\nimport {WebSocketManager} from './WebSocketManager';\nimport LoggerProxy from '../../../logger-proxy';\nimport {ConnectionServiceOptions, ConnectionLostDetails, ConnectionProp} from './types';\nimport {\n LOST_CONNECTION_RECOVERY_TIMEOUT,\n WS_DISCONNECT_ALLOWED,\n CONNECTIVITY_CHECK_INTERVAL,\n METHODS,\n} from '../constants';\nimport {CONNECTION_SERVICE_FILE} from '../../../constants';\nimport {SubscribeRequest} from '../../../types';\nimport {SUBSCRIBE_API} from '../../constants';\nimport {isRecord} from '../Utils';\n\nexport class ConnectionService extends EventEmitter {\n private connectionProp: ConnectionProp = {\n lostConnectionRecoveryTimeout: LOST_CONNECTION_RECOVERY_TIMEOUT,\n };\n\n private wsDisconnectAllowed = WS_DISCONNECT_ALLOWED;\n private reconnectingTimer: ReturnType<typeof setTimeout>;\n private restoreTimer: ReturnType<typeof setTimeout>;\n private isConnectionLost: boolean;\n private isRestoreFailed: boolean;\n private isSocketReconnected: boolean;\n private isKeepAlive: boolean;\n private reconnectInterval: ReturnType<typeof setInterval>;\n private webSocketManager: WebSocketManager;\n private subscribeRequest: SubscribeRequest;\n\n constructor(options: ConnectionServiceOptions) {\n super();\n this.webSocketManager = options.webSocketManager;\n this.subscribeRequest = options.subscribeRequest;\n\n this.isConnectionLost = false;\n this.isRestoreFailed = false;\n this.isSocketReconnected = false;\n this.isKeepAlive = false;\n\n this.setupEventListeners();\n }\n\n private setupEventListeners() {\n this.webSocketManager.on('message', this.onPing.bind(this));\n this.webSocketManager.on('socketClose', this.onSocketClose.bind(this));\n }\n\n private dispatchConnectionEvent(socketReconnected = false): void {\n const event: ConnectionLostDetails = {\n isConnectionLost: this.isConnectionLost,\n isRestoreFailed: this.isRestoreFailed,\n isSocketReconnected:\n !this.webSocketManager.isSocketClosed && (socketReconnected || this.isSocketReconnected),\n isKeepAlive: this.isKeepAlive,\n };\n this.webSocketManager.handleConnectionLost(event);\n LoggerProxy.info(`Dispatching connection event`, {\n module: CONNECTION_SERVICE_FILE,\n method: METHODS.DISPATCH_CONNECTION_EVENT,\n });\n this.emit('connectionLost', event);\n }\n\n private handleConnectionLost = (): void => {\n this.isConnectionLost = true;\n this.dispatchConnectionEvent();\n };\n\n private clearTimerOnRestoreFailed = async () => {\n if (this.reconnectInterval) {\n clearInterval(this.reconnectInterval);\n }\n };\n\n private handleRestoreFailed = async () => {\n this.isRestoreFailed = true;\n this.webSocketManager.shouldReconnect = false;\n this.dispatchConnectionEvent();\n await this.clearTimerOnRestoreFailed();\n };\n\n private updateConnectionData = (): void => {\n this.isRestoreFailed = false;\n this.isConnectionLost = false;\n this.isSocketReconnected = false;\n };\n\n public setConnectionProp(prop: ConnectionProp): void {\n this.connectionProp = prop;\n }\n\n private onPing = (event: unknown): void => {\n let parsedEvent: unknown;\n try {\n parsedEvent = JSON.parse(event as string);\n } catch (error) {\n LoggerProxy.error(`onPing failed to parse payload: ${(error as Error)?.message}`, {\n module: CONNECTION_SERVICE_FILE,\n method: METHODS.ON_PING,\n });\n\n return;\n }\n if (!isRecord(parsedEvent)) {\n LoggerProxy.error(`onPing received non-object payload, ignoring`, {\n module: CONNECTION_SERVICE_FILE,\n method: METHODS.ON_PING,\n });\n\n return;\n }\n if (this.reconnectingTimer) {\n clearTimeout(this.reconnectingTimer);\n }\n if (this.restoreTimer) {\n clearTimeout(this.restoreTimer);\n }\n this.isKeepAlive = parsedEvent.keepalive === 'true';\n\n if (\n ((this.isConnectionLost && !this.isRestoreFailed) || this.isKeepAlive) &&\n !this.isSocketReconnected\n ) {\n this.updateConnectionData();\n this.dispatchConnectionEvent();\n } else if (this.isSocketReconnected && this.isKeepAlive) {\n this.updateConnectionData();\n this.dispatchConnectionEvent(true);\n }\n\n this.reconnectingTimer = setTimeout(this.handleConnectionLost, this.wsDisconnectAllowed);\n this.restoreTimer = setTimeout(\n this.handleRestoreFailed,\n this.connectionProp && this.connectionProp.lostConnectionRecoveryTimeout\n );\n };\n\n private handleSocketClose = async (): Promise<void> => {\n LoggerProxy.info(`event=socketConnectionRetry | Trying to reconnect to websocket`, {\n module: CONNECTION_SERVICE_FILE,\n method: METHODS.HANDLE_SOCKET_CLOSE,\n });\n const onlineStatus = navigator.onLine;\n if (onlineStatus) {\n await this.webSocketManager.initWebSocket({\n body: this.subscribeRequest,\n resource: SUBSCRIBE_API,\n });\n await this.clearTimerOnRestoreFailed();\n this.isSocketReconnected = true;\n } else {\n throw new Error('event=socketConnectionRetry | browser network not available');\n }\n };\n\n private onSocketClose = (): void => {\n this.clearTimerOnRestoreFailed();\n\n this.reconnectInterval = setInterval(async () => {\n await this.handleSocketClose();\n }, CONNECTIVITY_CHECK_INTERVAL);\n };\n}\n"],"mappings":";;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,YAAA,GAAAC,sBAAA,CAAAF,OAAA;AAEA,IAAAG,UAAA,GAAAH,OAAA;AAMA,IAAAI,WAAA,GAAAJ,OAAA;AAEA,IAAAK,WAAA,GAAAL,OAAA;AACA,IAAAM,MAAA,GAAAN,OAAA;AAAkC,SAAAE,uBAAAK,CAAA,WAAAA,CAAA,IAAAA,CAAA,CAAAC,UAAA,GAAAD,CAAA,KAAAE,OAAA,EAAAF,CAAA;AAE3B,MAAMG,iBAAiB,SAASC,oBAAY,CAAC;EAC1CC,cAAc,GAAmB;IACvCC,6BAA6B,EAAEC;EACjC,CAAC;EAEOC,mBAAmB,GAAGC,gCAAqB;EAWnDC,WAAWA,CAACC,OAAiC,EAAE;IAC7C,KAAK,CAAC,CAAC;IACP,IAAI,CAACC,gBAAgB,GAAGD,OAAO,CAACC,gBAAgB;IAChD,IAAI,CAACC,gBAAgB,GAAGF,OAAO,CAACE,gBAAgB;IAEhD,IAAI,CAACC,gBAAgB,GAAG,KAAK;IAC7B,IAAI,CAACC,eAAe,GAAG,KAAK;IAC5B,IAAI,CAACC,mBAAmB,GAAG,KAAK;IAChC,IAAI,CAACC,WAAW,GAAG,KAAK;IAExB,IAAI,CAACC,mBAAmB,CAAC,CAAC;EAC5B;EAEQA,mBAAmBA,CAAA,EAAG;IAC5B,IAAI,CAACN,gBAAgB,CAACO,EAAE,CAAC,SAAS,EAAE,IAAI,CAACC,MAAM,CAACC,IAAI,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@@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.default = void 0;
7
7
  // TODO: Try to find alternative to using Blob and script here
8
8
  const workerScript = `
9
- console.log("*** Keepalive Worker Thread ***");
10
9
  let intervalId, intervalDuration, timeOutId, isSocketClosed, closeSocketTimeout;
11
10
  let initialised = false;
12
11
  let initiateWebSocketClosure = false;
@@ -21,10 +20,6 @@ const resetOfflineHandler = function () {
21
20
 
22
21
  const checkOnlineStatus = function () {
23
22
  const onlineStatus = navigator.onLine;
24
- console.log(
25
- \`[WebSocketStatus] event=checkOnlineStatus | online status=\`,
26
- onlineStatus
27
- );
28
23
  return onlineStatus;
29
24
  };
30
25
 
@@ -58,7 +53,6 @@ addEventListener("message", (event) => {
58
53
  if (event.data?.type === "start") {
59
54
  intervalDuration = event.data?.intervalDuration || 4000;
60
55
  closeSocketTimeout = event.data?.closeSocketTimeout || 5000;
61
- console.log("event=Websocket startWorker | keepalive Worker started");
62
56
  intervalId = setInterval(
63
57
  (checkIfSocketClosed) => {
64
58
  checkNetworkStatus();
@@ -72,7 +66,6 @@ addEventListener("message", (event) => {
72
66
  }
73
67
 
74
68
  if (event.data?.type === "terminate" && intervalId) {
75
- console.log("event=Websocket terminateWorker | keepalive Worker stopped");
76
69
  clearInterval(intervalId);
77
70
  intervalId = null;
78
71
  resetOfflineHandler();
@@ -81,12 +74,10 @@ addEventListener("message", (event) => {
81
74
 
82
75
  // Listen for online and offline events
83
76
  self.addEventListener('online', () => {
84
- console.log('Network status: online');
85
77
  checkNetworkStatus();
86
78
  });
87
79
 
88
80
  self.addEventListener('offline', () => {
89
- console.log('Network status: offline');
90
81
  checkNetworkStatus();
91
82
  });
92
83
  `;
@@ -1 +1 @@
1
- {"version":3,"names":["workerScript","_default","exports","default"],"sources":["keepalive.worker.js"],"sourcesContent":["// TODO: Try to find alternative to using Blob and script here\nconst workerScript = `\nconsole.log(\"*** Keepalive Worker Thread ***\");\nlet intervalId, intervalDuration, timeOutId, isSocketClosed, closeSocketTimeout;\nlet initialised = false;\nlet initiateWebSocketClosure = false;\n\nconst resetOfflineHandler = function () {\n if (timeOutId) {\n initialised = false;\n clearTimeout(timeOutId);\n timeOutId = null;\n }\n};\n\nconst checkOnlineStatus = function () {\n const onlineStatus = navigator.onLine;\n console.log(\n \\`[WebSocketStatus] event=checkOnlineStatus | online status=\\`,\n onlineStatus\n );\n return onlineStatus;\n};\n\n// Checks network status and if it's offline then force closes WebSocket\nconst checkNetworkStatus = function () {\n const onlineStatus = checkOnlineStatus();\n postMessage({ type: \"keepalive\", onlineStatus });\n if (!onlineStatus && !initialised) {\n initialised = true;\n // Sets a timeout of 16s, checks if socket didn't close then it closes forcefully\n timeOutId = setTimeout(() => {\n if (!isSocketClosed) {\n initiateWebSocketClosure = true;\n postMessage({ type: \"closeSocket\" });\n }\n }, closeSocketTimeout);\n }\n\n if (onlineStatus && initialised) {\n initialised = false;\n }\n\n if (initiateWebSocketClosure) {\n initiateWebSocketClosure = false;\n clearTimeout(timeOutId);\n timeOutId = null;\n }\n};\n\naddEventListener(\"message\", (event) => {\n if (event.data?.type === \"start\") {\n intervalDuration = event.data?.intervalDuration || 4000;\n closeSocketTimeout = event.data?.closeSocketTimeout || 5000;\n console.log(\"event=Websocket startWorker | keepalive Worker started\");\n intervalId = setInterval(\n (checkIfSocketClosed) => {\n checkNetworkStatus();\n isSocketClosed = checkIfSocketClosed;\n },\n intervalDuration,\n event.data?.isSocketClosed\n );\n\n resetOfflineHandler();\n }\n\n if (event.data?.type === \"terminate\" && intervalId) {\n console.log(\"event=Websocket terminateWorker | keepalive Worker stopped\");\n clearInterval(intervalId);\n intervalId = null;\n resetOfflineHandler();\n }\n});\n\n// Listen for online and offline events\nself.addEventListener('online', () => {\n console.log('Network status: online');\n checkNetworkStatus();\n});\n\nself.addEventListener('offline', () => {\n console.log('Network status: offline');\n checkNetworkStatus();\n});\n`;\n\nexport default workerScript;\n"],"mappings":";;;;;;AAAA;AACA,MAAMA,YAAY,GAAG;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AAAC,IAAAC,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEaH,YAAY","ignoreList":[]}
1
+ {"version":3,"names":["workerScript","_default","exports","default"],"sources":["keepalive.worker.js"],"sourcesContent":["// TODO: Try to find alternative to using Blob and script here\nconst workerScript = `\nlet intervalId, intervalDuration, timeOutId, isSocketClosed, closeSocketTimeout;\nlet initialised = false;\nlet initiateWebSocketClosure = false;\n\nconst resetOfflineHandler = function () {\n if (timeOutId) {\n initialised = false;\n clearTimeout(timeOutId);\n timeOutId = null;\n }\n};\n\nconst checkOnlineStatus = function () {\n const onlineStatus = navigator.onLine;\n return onlineStatus;\n};\n\n// Checks network status and if it's offline then force closes WebSocket\nconst checkNetworkStatus = function () {\n const onlineStatus = checkOnlineStatus();\n postMessage({ type: \"keepalive\", onlineStatus });\n if (!onlineStatus && !initialised) {\n initialised = true;\n // Sets a timeout of 16s, checks if socket didn't close then it closes forcefully\n timeOutId = setTimeout(() => {\n if (!isSocketClosed) {\n initiateWebSocketClosure = true;\n postMessage({ type: \"closeSocket\" });\n }\n }, closeSocketTimeout);\n }\n\n if (onlineStatus && initialised) {\n initialised = false;\n }\n\n if (initiateWebSocketClosure) {\n initiateWebSocketClosure = false;\n clearTimeout(timeOutId);\n timeOutId = null;\n }\n};\n\naddEventListener(\"message\", (event) => {\n if (event.data?.type === \"start\") {\n intervalDuration = event.data?.intervalDuration || 4000;\n closeSocketTimeout = event.data?.closeSocketTimeout || 5000;\n intervalId = setInterval(\n (checkIfSocketClosed) => {\n checkNetworkStatus();\n isSocketClosed = checkIfSocketClosed;\n },\n intervalDuration,\n event.data?.isSocketClosed\n );\n\n resetOfflineHandler();\n }\n\n if (event.data?.type === \"terminate\" && intervalId) {\n clearInterval(intervalId);\n intervalId = null;\n resetOfflineHandler();\n }\n});\n\n// Listen for online and offline events\nself.addEventListener('online', () => {\n checkNetworkStatus();\n});\n\nself.addEventListener('offline', () => {\n checkNetworkStatus();\n});\n`;\n\nexport default workerScript;\n"],"mappings":";;;;;;AAAA;AACA,MAAMA,YAAY,GAAG;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AAAC,IAAAC,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEaH,YAAY","ignoreList":[]}
@@ -1357,7 +1357,15 @@ class TaskManager extends _events.default {
1357
1357
  const action = _constants2.TRANSCRIPT_EVENT_MAP[eventType];
1358
1358
  if (!action || !this.apiAIAssistant) return;
1359
1359
  if (this.configFlags?.aiFeature?.realtimeTranscripts?.enable !== true) return;
1360
- this.apiAIAssistant.sendEvent(this.agentId, interactionId, _types3.AIAssistantEventType.CUSTOM_EVENT, _types3.AIAssistantEventName.GET_TRANSCRIPTS, {
1360
+ const trimmedId = interactionId.trim();
1361
+ if (!(0, _TaskUtils.isNonEmptyString)(trimmedId)) {
1362
+ _loggerProxy.default.error(`Rejected transcript ${action} event with invalid interactionId`, {
1363
+ module: _constants.TASK_MANAGER_FILE,
1364
+ method: _constants2.METHODS.REQUEST_REAL_TIME_TRANSCRIPTS
1365
+ });
1366
+ return;
1367
+ }
1368
+ this.apiAIAssistant.sendEvent(this.agentId, trimmedId, _types3.AIAssistantEventType.CUSTOM_EVENT, _types3.AIAssistantEventName.GET_TRANSCRIPTS, {
1361
1369
  action
1362
1370
  }).catch(error => {
1363
1371
  _loggerProxy.default.error(`Failed to send transcript ${action} event`, {