@metamask-previews/notification-services-controller 0.19.0-preview-2a6578b3 → 0.20.0-preview-224dff25

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 (176) hide show
  1. package/CHANGELOG.md +8 -1
  2. package/dist/NotificationServicesController/__fixtures__/mock-raw-notifications.cjs +22 -1
  3. package/dist/NotificationServicesController/__fixtures__/mock-raw-notifications.cjs.map +1 -1
  4. package/dist/NotificationServicesController/__fixtures__/mock-raw-notifications.d.cts +22 -0
  5. package/dist/NotificationServicesController/__fixtures__/mock-raw-notifications.d.cts.map +1 -1
  6. package/dist/NotificationServicesController/__fixtures__/mock-raw-notifications.d.mts +22 -0
  7. package/dist/NotificationServicesController/__fixtures__/mock-raw-notifications.d.mts.map +1 -1
  8. package/dist/NotificationServicesController/__fixtures__/mock-raw-notifications.mjs +22 -1
  9. package/dist/NotificationServicesController/__fixtures__/mock-raw-notifications.mjs.map +1 -1
  10. package/dist/NotificationServicesController/__fixtures__/mockResponses.cjs +2 -2
  11. package/dist/NotificationServicesController/__fixtures__/mockResponses.cjs.map +1 -1
  12. package/dist/NotificationServicesController/__fixtures__/mockResponses.mjs +2 -2
  13. package/dist/NotificationServicesController/__fixtures__/mockResponses.mjs.map +1 -1
  14. package/dist/NotificationServicesController/__fixtures__/test-utils.cjs +1 -1
  15. package/dist/NotificationServicesController/__fixtures__/test-utils.cjs.map +1 -1
  16. package/dist/NotificationServicesController/__fixtures__/test-utils.mjs +1 -1
  17. package/dist/NotificationServicesController/__fixtures__/test-utils.mjs.map +1 -1
  18. package/dist/NotificationServicesController/constants/notification-schema.cjs +0 -1
  19. package/dist/NotificationServicesController/constants/notification-schema.cjs.map +1 -1
  20. package/dist/NotificationServicesController/constants/notification-schema.d.cts.map +1 -1
  21. package/dist/NotificationServicesController/constants/notification-schema.d.mts.map +1 -1
  22. package/dist/NotificationServicesController/constants/notification-schema.mjs +0 -1
  23. package/dist/NotificationServicesController/constants/notification-schema.mjs.map +1 -1
  24. package/dist/NotificationServicesController/index.cjs +1 -3
  25. package/dist/NotificationServicesController/index.cjs.map +1 -1
  26. package/dist/NotificationServicesController/index.d.cts +2 -2
  27. package/dist/NotificationServicesController/index.d.cts.map +1 -1
  28. package/dist/NotificationServicesController/index.d.mts +2 -2
  29. package/dist/NotificationServicesController/index.d.mts.map +1 -1
  30. package/dist/NotificationServicesController/index.mjs +0 -2
  31. package/dist/NotificationServicesController/index.mjs.map +1 -1
  32. package/dist/NotificationServicesController/processors/process-notifications.cjs +1 -1
  33. package/dist/NotificationServicesController/processors/process-notifications.cjs.map +1 -1
  34. package/dist/NotificationServicesController/processors/process-notifications.d.cts.map +1 -1
  35. package/dist/NotificationServicesController/processors/process-notifications.d.mts.map +1 -1
  36. package/dist/NotificationServicesController/processors/process-notifications.mjs +1 -1
  37. package/dist/NotificationServicesController/processors/process-notifications.mjs.map +1 -1
  38. package/dist/NotificationServicesController/services/feature-announcements.cjs +1 -0
  39. package/dist/NotificationServicesController/services/feature-announcements.cjs.map +1 -1
  40. package/dist/NotificationServicesController/services/feature-announcements.d.cts +1 -0
  41. package/dist/NotificationServicesController/services/feature-announcements.d.cts.map +1 -1
  42. package/dist/NotificationServicesController/services/feature-announcements.d.mts +1 -0
  43. package/dist/NotificationServicesController/services/feature-announcements.d.mts.map +1 -1
  44. package/dist/NotificationServicesController/services/feature-announcements.mjs +1 -0
  45. package/dist/NotificationServicesController/services/feature-announcements.mjs.map +1 -1
  46. package/dist/NotificationServicesController/services/onchain-notifications.cjs +1 -4
  47. package/dist/NotificationServicesController/services/onchain-notifications.cjs.map +1 -1
  48. package/dist/NotificationServicesController/services/onchain-notifications.d.cts.map +1 -1
  49. package/dist/NotificationServicesController/services/onchain-notifications.d.mts.map +1 -1
  50. package/dist/NotificationServicesController/services/onchain-notifications.mjs +1 -4
  51. package/dist/NotificationServicesController/services/onchain-notifications.mjs.map +1 -1
  52. package/dist/NotificationServicesController/types/feature-announcement/feature-announcement.cjs.map +1 -1
  53. package/dist/NotificationServicesController/types/feature-announcement/feature-announcement.d.cts +1 -1
  54. package/dist/NotificationServicesController/types/feature-announcement/feature-announcement.d.cts.map +1 -1
  55. package/dist/NotificationServicesController/types/feature-announcement/feature-announcement.d.mts +1 -1
  56. package/dist/NotificationServicesController/types/feature-announcement/feature-announcement.d.mts.map +1 -1
  57. package/dist/NotificationServicesController/types/feature-announcement/feature-announcement.mjs.map +1 -1
  58. package/dist/NotificationServicesController/types/feature-announcement/index.cjs +0 -17
  59. package/dist/NotificationServicesController/types/feature-announcement/index.cjs.map +1 -1
  60. package/dist/NotificationServicesController/types/feature-announcement/index.d.cts +3 -3
  61. package/dist/NotificationServicesController/types/feature-announcement/index.d.cts.map +1 -1
  62. package/dist/NotificationServicesController/types/feature-announcement/index.d.mts +3 -3
  63. package/dist/NotificationServicesController/types/feature-announcement/index.d.mts.map +1 -1
  64. package/dist/NotificationServicesController/types/feature-announcement/index.mjs +1 -3
  65. package/dist/NotificationServicesController/types/feature-announcement/index.mjs.map +1 -1
  66. package/dist/NotificationServicesController/types/index.cjs +0 -19
  67. package/dist/NotificationServicesController/types/index.cjs.map +1 -1
  68. package/dist/NotificationServicesController/types/index.d.cts +5 -5
  69. package/dist/NotificationServicesController/types/index.d.cts.map +1 -1
  70. package/dist/NotificationServicesController/types/index.d.mts +5 -5
  71. package/dist/NotificationServicesController/types/index.d.mts.map +1 -1
  72. package/dist/NotificationServicesController/types/index.mjs +1 -5
  73. package/dist/NotificationServicesController/types/index.mjs.map +1 -1
  74. package/dist/NotificationServicesController/types/notification/index.cjs +0 -15
  75. package/dist/NotificationServicesController/types/notification/index.cjs.map +1 -1
  76. package/dist/NotificationServicesController/types/notification/index.d.cts +1 -1
  77. package/dist/NotificationServicesController/types/notification/index.d.cts.map +1 -1
  78. package/dist/NotificationServicesController/types/notification/index.d.mts +1 -1
  79. package/dist/NotificationServicesController/types/notification/index.d.mts.map +1 -1
  80. package/dist/NotificationServicesController/types/notification/index.mjs +1 -1
  81. package/dist/NotificationServicesController/types/notification/index.mjs.map +1 -1
  82. package/dist/NotificationServicesController/types/notification/notification.cjs.map +1 -1
  83. package/dist/NotificationServicesController/types/notification/notification.d.cts.map +1 -1
  84. package/dist/NotificationServicesController/types/notification/notification.d.mts.map +1 -1
  85. package/dist/NotificationServicesController/types/notification/notification.mjs.map +1 -1
  86. package/dist/NotificationServicesController/types/on-chain-notification/index.cjs +0 -15
  87. package/dist/NotificationServicesController/types/on-chain-notification/index.cjs.map +1 -1
  88. package/dist/NotificationServicesController/types/on-chain-notification/index.d.cts +1 -1
  89. package/dist/NotificationServicesController/types/on-chain-notification/index.d.cts.map +1 -1
  90. package/dist/NotificationServicesController/types/on-chain-notification/index.d.mts +1 -1
  91. package/dist/NotificationServicesController/types/on-chain-notification/index.d.mts.map +1 -1
  92. package/dist/NotificationServicesController/types/on-chain-notification/index.mjs +1 -1
  93. package/dist/NotificationServicesController/types/on-chain-notification/index.mjs.map +1 -1
  94. package/dist/NotificationServicesController/types/on-chain-notification/on-chain-notification.cjs.map +1 -1
  95. package/dist/NotificationServicesController/types/on-chain-notification/on-chain-notification.d.cts +1 -1
  96. package/dist/NotificationServicesController/types/on-chain-notification/on-chain-notification.d.cts.map +1 -1
  97. package/dist/NotificationServicesController/types/on-chain-notification/on-chain-notification.d.mts +1 -1
  98. package/dist/NotificationServicesController/types/on-chain-notification/on-chain-notification.d.mts.map +1 -1
  99. package/dist/NotificationServicesController/types/on-chain-notification/on-chain-notification.mjs.map +1 -1
  100. package/dist/NotificationServicesController/types/on-chain-notification/schema.cjs +2 -1
  101. package/dist/NotificationServicesController/types/on-chain-notification/schema.cjs.map +1 -1
  102. package/dist/NotificationServicesController/types/on-chain-notification/schema.d.cts.map +1 -1
  103. package/dist/NotificationServicesController/types/on-chain-notification/schema.d.mts.map +1 -1
  104. package/dist/NotificationServicesController/types/on-chain-notification/schema.mjs +2 -1
  105. package/dist/NotificationServicesController/types/on-chain-notification/schema.mjs.map +1 -1
  106. package/dist/NotificationServicesController/types/snaps/index.cjs +0 -15
  107. package/dist/NotificationServicesController/types/snaps/index.cjs.map +1 -1
  108. package/dist/NotificationServicesController/types/snaps/index.d.cts +1 -1
  109. package/dist/NotificationServicesController/types/snaps/index.d.cts.map +1 -1
  110. package/dist/NotificationServicesController/types/snaps/index.d.mts +1 -1
  111. package/dist/NotificationServicesController/types/snaps/index.d.mts.map +1 -1
  112. package/dist/NotificationServicesController/types/snaps/index.mjs +1 -1
  113. package/dist/NotificationServicesController/types/snaps/index.mjs.map +1 -1
  114. package/dist/NotificationServicesController/types/user-storage/index.cjs +0 -15
  115. package/dist/NotificationServicesController/types/user-storage/index.cjs.map +1 -1
  116. package/dist/NotificationServicesController/types/user-storage/index.d.cts +1 -1
  117. package/dist/NotificationServicesController/types/user-storage/index.d.cts.map +1 -1
  118. package/dist/NotificationServicesController/types/user-storage/index.d.mts +1 -1
  119. package/dist/NotificationServicesController/types/user-storage/index.d.mts.map +1 -1
  120. package/dist/NotificationServicesController/types/user-storage/index.mjs +1 -1
  121. package/dist/NotificationServicesController/types/user-storage/index.mjs.map +1 -1
  122. package/dist/NotificationServicesController/utils/utils.cjs.map +1 -1
  123. package/dist/NotificationServicesController/utils/utils.mjs.map +1 -1
  124. package/dist/NotificationServicesPushController/NotificationServicesPushController.cjs +1 -3
  125. package/dist/NotificationServicesPushController/NotificationServicesPushController.cjs.map +1 -1
  126. package/dist/NotificationServicesPushController/NotificationServicesPushController.d.cts +1 -3
  127. package/dist/NotificationServicesPushController/NotificationServicesPushController.d.cts.map +1 -1
  128. package/dist/NotificationServicesPushController/NotificationServicesPushController.d.mts +1 -3
  129. package/dist/NotificationServicesPushController/NotificationServicesPushController.d.mts.map +1 -1
  130. package/dist/NotificationServicesPushController/NotificationServicesPushController.mjs +1 -3
  131. package/dist/NotificationServicesPushController/NotificationServicesPushController.mjs.map +1 -1
  132. package/dist/NotificationServicesPushController/__fixtures__/mockResponse.cjs +0 -2
  133. package/dist/NotificationServicesPushController/__fixtures__/mockResponse.cjs.map +1 -1
  134. package/dist/NotificationServicesPushController/__fixtures__/mockResponse.d.cts.map +1 -1
  135. package/dist/NotificationServicesPushController/__fixtures__/mockResponse.d.mts.map +1 -1
  136. package/dist/NotificationServicesPushController/__fixtures__/mockResponse.mjs +0 -2
  137. package/dist/NotificationServicesPushController/__fixtures__/mockResponse.mjs.map +1 -1
  138. package/dist/NotificationServicesPushController/index.cjs +1 -3
  139. package/dist/NotificationServicesPushController/index.cjs.map +1 -1
  140. package/dist/NotificationServicesPushController/index.d.cts +2 -2
  141. package/dist/NotificationServicesPushController/index.d.cts.map +1 -1
  142. package/dist/NotificationServicesPushController/index.d.mts +2 -2
  143. package/dist/NotificationServicesPushController/index.d.mts.map +1 -1
  144. package/dist/NotificationServicesPushController/index.mjs +0 -2
  145. package/dist/NotificationServicesPushController/index.mjs.map +1 -1
  146. package/dist/NotificationServicesPushController/services/push/push-web.cjs +2 -1
  147. package/dist/NotificationServicesPushController/services/push/push-web.cjs.map +1 -1
  148. package/dist/NotificationServicesPushController/services/push/push-web.d.cts +1 -0
  149. package/dist/NotificationServicesPushController/services/push/push-web.d.cts.map +1 -1
  150. package/dist/NotificationServicesPushController/services/push/push-web.d.mts +1 -0
  151. package/dist/NotificationServicesPushController/services/push/push-web.d.mts.map +1 -1
  152. package/dist/NotificationServicesPushController/services/push/push-web.mjs +2 -1
  153. package/dist/NotificationServicesPushController/services/push/push-web.mjs.map +1 -1
  154. package/dist/NotificationServicesPushController/services/services.cjs +0 -2
  155. package/dist/NotificationServicesPushController/services/services.cjs.map +1 -1
  156. package/dist/NotificationServicesPushController/services/services.d.cts +1 -1
  157. package/dist/NotificationServicesPushController/services/services.d.cts.map +1 -1
  158. package/dist/NotificationServicesPushController/services/services.d.mts +1 -1
  159. package/dist/NotificationServicesPushController/services/services.d.mts.map +1 -1
  160. package/dist/NotificationServicesPushController/services/services.mjs +0 -2
  161. package/dist/NotificationServicesPushController/services/services.mjs.map +1 -1
  162. package/dist/NotificationServicesPushController/types/index.cjs +0 -15
  163. package/dist/NotificationServicesPushController/types/index.cjs.map +1 -1
  164. package/dist/NotificationServicesPushController/types/index.d.cts +1 -1
  165. package/dist/NotificationServicesPushController/types/index.d.cts.map +1 -1
  166. package/dist/NotificationServicesPushController/types/index.d.mts +1 -1
  167. package/dist/NotificationServicesPushController/types/index.d.mts.map +1 -1
  168. package/dist/NotificationServicesPushController/types/index.mjs +1 -1
  169. package/dist/NotificationServicesPushController/types/index.mjs.map +1 -1
  170. package/dist/NotificationServicesPushController/utils/get-notification-message.cjs +2 -2
  171. package/dist/NotificationServicesPushController/utils/get-notification-message.cjs.map +1 -1
  172. package/dist/NotificationServicesPushController/utils/get-notification-message.d.cts.map +1 -1
  173. package/dist/NotificationServicesPushController/utils/get-notification-message.d.mts.map +1 -1
  174. package/dist/NotificationServicesPushController/utils/get-notification-message.mjs +2 -2
  175. package/dist/NotificationServicesPushController/utils/get-notification-message.mjs.map +1 -1
  176. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../../../src/NotificationServicesController/utils/utils.ts"],"names":[],"mappings":";;;AAAA,+BAAoC;AAEpC,0DAGgC;AAEhC,8EAA4D;AAoB5D;;;;;;;GAOG;AACH,MAAM,WAAW,GAAG,CAAC,OAA4B,EAAU,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC;AAEzE;;;;;;;GAOG;AACH,MAAM,eAAe,GAAG,CAAC,OAA4B,EAAuB,EAAE,CAC5E,OAAO,CAAC;AAEV;;;;;;;;;;;;;GAaG;AACH,SAAgB,qBAAqB,CACnC,QAAgC,EAChC,KAAc;IAEd,MAAM,WAAW,GAAgB;QAC/B,CAAC,oCAAwB,CAAC,EAAE,gCAAoB;KACjD,CAAC;IAEF,QAAQ,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC3B,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,EAAE,WAAW,EAAE,CAAC;QAC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AAe,EAAE;gBACpB,sEAAsE;gBACtE,MAAM,IAAI,GAAG,IAAA,SAAM,GAAE,CAAC;gBACtB,WAAW,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG;oBAClC,CAAC,EAAE,WAAW;oBACd,CAAC,EAAE,KAAK;iBACT,CAAC;aACH;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,WAAW,CAAC;AACrB,CAAC;AA7BD,8DA6BC;AAED;;;;;;;;;GASG;AACH,SAAgB,8BAA8B,CAC5C,WAAwB,EACxB,OAAe,EACf,OAAe,EACf,IAAY,EACZ,OAAgB;IAEhB,IAAI,WAAW,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE;QAC7C,WAAW,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC;KACjD;IAED,OAAO,WAAW,CAAC;AACrB,CAAC;AAZD,wEAYC;AAED;;;;;;;;GAQG;AACI,KAAK,UAAU,WAAW,CAC/B,WAAmB,EACnB,QAAgB,EAChB,MAAyB,EACzB,IAAU;IAEV,MAAM,OAAO,GAAgB;QAC3B,MAAM;QACN,OAAO,EAAE;YACP,cAAc,EAAE,kBAAkB;YAClC,aAAa,EAAE,UAAU,WAAW,EAAE;SACvC;QACD,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;KAC3B,CAAC;IAEF,OAAO,MAAM,KAAK,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;AACxC,CAAC;AAhBD,kCAgBC","sourcesContent":["import { v4 as uuidv4 } from 'uuid';\n\nimport {\n USER_STORAGE_VERSION_KEY,\n USER_STORAGE_VERSION,\n} from '../constants/constants';\nimport type { TRIGGER_TYPES } from '../constants/notification-schema';\nimport { TRIGGERS } from '../constants/notification-schema';\nimport type { UserStorage } from '../types/user-storage/user-storage';\n\nexport type NotificationTrigger = {\n id: string;\n chainId: string;\n kind: string;\n address: string;\n enabled: boolean;\n};\n\ntype MapTriggerFn<Result> = (\n trigger: NotificationTrigger,\n) => Result | undefined;\n\ntype TraverseTriggerOpts<Result> = {\n address?: string;\n mapTrigger?: MapTriggerFn<Result>;\n};\n\n/**\n * Extracts and returns the ID from a notification trigger.\n * This utility function is primarily used as a mapping function in `traverseUserStorageTriggers`\n * to convert a full trigger object into its ID string.\n *\n * @param trigger - The notification trigger from which the ID is extracted.\n * @returns The ID of the provided notification trigger.\n */\nconst triggerToId = (trigger: NotificationTrigger): string => trigger.id;\n\n/**\n * A utility function that returns the input trigger without any transformation.\n * This function is used as the default mapping function in `traverseUserStorageTriggers`\n * when no custom mapping function is provided.\n *\n * @param trigger - The notification trigger to be returned as is.\n * @returns The same notification trigger that was passed in.\n */\nconst triggerIdentity = (trigger: NotificationTrigger): NotificationTrigger =>\n trigger;\n\n/**\n * Create a completely new user storage object with the given accounts and state.\n * This method initializes the user storage with a version key and iterates over each account to populate it with triggers.\n * Each trigger is associated with supported chains, and for each chain, a unique identifier (UUID) is generated.\n * The trigger object contains a kind (`k`) indicating the type of trigger and an enabled state (`e`).\n * The kind and enabled state are stored with abbreviated keys to reduce the JSON size.\n *\n * This is used primarily for creating a new user storage (e.g. when first signing in/enabling notification profile syncing),\n * caution is needed in case you need to remove triggers that you don't want (due to notification setting filters)\n *\n * @param accounts - An array of account objects, each optionally containing an address.\n * @param state - A boolean indicating the initial enabled state for all triggers in the user storage.\n * @returns A `UserStorage` object populated with triggers for each account and chain.\n */\nexport function initializeUserStorage(\n accounts: { address?: string }[],\n state: boolean,\n): UserStorage {\n const userStorage: UserStorage = {\n [USER_STORAGE_VERSION_KEY]: USER_STORAGE_VERSION,\n };\n\n accounts.forEach((account) => {\n const address = account.address?.toLowerCase();\n if (!address) {\n return;\n }\n if (!userStorage[address]) {\n userStorage[address] = {};\n }\n\n Object.entries(TRIGGERS).forEach(\n ([trigger, { supported_chains: supportedChains }]) => {\n supportedChains.forEach((chain) => {\n if (!userStorage[address]?.[chain]) {\n userStorage[address][chain] = {};\n }\n\n userStorage[address][chain][uuidv4()] = {\n k: trigger as TRIGGER_TYPES, // use 'k' instead of 'kind' to reduce the json weight\n e: state, // use 'e' instead of 'enabled' to reduce the json weight\n };\n });\n },\n );\n });\n\n return userStorage;\n}\n\n/**\n * Iterates over user storage to find and optionally transform notification triggers.\n * This method allows for flexible retrieval and transformation of triggers based on provided options.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @param options - Optional parameters to filter and map triggers:\n * - `address`: If provided, only triggers for this address are considered.\n * - `mapTrigger`: A function to transform each trigger. If not provided, triggers are returned as is.\n * @returns An array of triggers, potentially transformed by the `mapTrigger` function.\n */\nexport function traverseUserStorageTriggers<\n ResultTriggers = NotificationTrigger,\n>(\n userStorage: UserStorage,\n options?: TraverseTriggerOpts<ResultTriggers>,\n): ResultTriggers[] {\n const triggers: ResultTriggers[] = [];\n const mapTrigger =\n options?.mapTrigger ?? (triggerIdentity as MapTriggerFn<ResultTriggers>);\n\n for (const address in userStorage) {\n if (address === (USER_STORAGE_VERSION_KEY as unknown as string)) {\n continue;\n }\n if (options?.address && address !== options.address) {\n continue;\n }\n\n for (const chainId in userStorage[address]) {\n if (chainId in userStorage[address]) {\n for (const uuid in userStorage[address][chainId]) {\n if (uuid) {\n const mappedTrigger = mapTrigger({\n id: uuid,\n kind: userStorage[address]?.[chainId]?.[uuid]?.k,\n chainId,\n address,\n enabled: userStorage[address]?.[chainId]?.[uuid]?.e ?? false,\n });\n if (mappedTrigger) {\n triggers.push(mappedTrigger);\n }\n }\n }\n }\n }\n }\n\n return triggers;\n}\n\n/**\n * Verifies the presence of specified accounts and their chains in the user storage.\n * This method checks if each provided account exists in the user storage and if all its supported chains are present.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @param accounts - An array of account addresses to check for presence.\n * @returns A record where each key is an account address and each value is a boolean indicating whether the account and all its supported chains are present in the user storage.\n */\nexport function checkAccountsPresence(\n userStorage: UserStorage,\n accounts: string[],\n): Record<string, boolean> {\n const presenceRecord: Record<string, boolean> = {};\n\n // Initialize presence record for all accounts as false\n accounts.forEach((account) => {\n presenceRecord[account.toLowerCase()] = isAccountEnabled(\n account,\n userStorage,\n );\n });\n\n return presenceRecord;\n}\n\n/**\n * Internal method to check if a given account should be marked as enabled by introspecting user storage\n * Introspection: check if account exists; and also see if has all triggers in schema enabled\n *\n * @param accountAddress - address to check in user storage\n * @param userStorage - user storage object to traverse/introspect\n * @returns boolean if the account is enabled or disabled\n */\nfunction isAccountEnabled(\n accountAddress: string,\n userStorage: UserStorage,\n): boolean {\n const accountObject = userStorage[accountAddress?.toLowerCase()];\n\n // If the account address is not present in the userStorage, return true\n if (!accountObject) {\n return false;\n }\n\n // Check if all available chains are present\n for (const [triggerKind, triggerConfig] of Object.entries(TRIGGERS)) {\n for (const chain of triggerConfig.supported_chains) {\n if (!accountObject[chain]) {\n return false;\n }\n\n const triggerExists = Object.values(accountObject[chain]).some(\n (obj) => obj.k === triggerKind,\n );\n if (!triggerExists) {\n return false;\n }\n\n // Check if any trigger is disabled\n for (const uuid in accountObject[chain]) {\n if (!accountObject[chain][uuid].e) {\n return false;\n }\n }\n }\n }\n\n return true;\n}\n\n/**\n * Infers and returns an array of enabled notification trigger kinds from the user storage.\n * This method counts the occurrences of each kind of trigger and returns the kinds that are present.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @returns An array of trigger kinds (`TRIGGER_TYPES`) that are enabled in the user storage.\n */\nexport function inferEnabledKinds(userStorage: UserStorage): TRIGGER_TYPES[] {\n const allSupportedKinds = new Set<TRIGGER_TYPES>();\n\n traverseUserStorageTriggers(userStorage, {\n mapTrigger: (t) => {\n allSupportedKinds.add(t.kind as TRIGGER_TYPES);\n },\n });\n\n return Array.from(allSupportedKinds);\n}\n\n/**\n * Retrieves all UUIDs associated with a specific account address from the user storage.\n * This function utilizes `traverseUserStorageTriggers` with a mapping function to extract\n * just the UUIDs of the notification triggers for the given address.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @param address - The specific account address to retrieve UUIDs for.\n * @returns An array of UUID strings associated with the given account address.\n */\nexport function getUUIDsForAccount(\n userStorage: UserStorage,\n address: string,\n): string[] {\n return traverseUserStorageTriggers(userStorage, {\n address,\n mapTrigger: triggerToId,\n });\n}\n\n/**\n * Retrieves all UUIDs from the user storage, regardless of the account address or chain ID.\n * This method leverages `traverseUserStorageTriggers` with a specific mapping function (`triggerToId`)\n * to extract only the UUIDs from all notification triggers present in the user storage.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @returns An array of UUID strings from all notification triggers in the user storage.\n */\nexport function getAllUUIDs(userStorage: UserStorage): string[] {\n return traverseUserStorageTriggers(userStorage, {\n mapTrigger: triggerToId,\n });\n}\n\n/**\n * Retrieves UUIDs for notification triggers that match any of the specified kinds.\n * This method filters triggers based on their kind and returns an array of UUIDs for those that match the allowed kinds.\n * It utilizes `traverseUserStorageTriggers` with a custom mapping function that checks if a trigger's kind is in the allowed list.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @param allowedKinds - An array of kinds (as strings) to filter the triggers by.\n * @returns An array of UUID strings for triggers that match the allowed kinds.\n */\nexport function getUUIDsForKinds(\n userStorage: UserStorage,\n allowedKinds: string[],\n): string[] {\n const kindsSet = new Set(allowedKinds);\n\n return traverseUserStorageTriggers(userStorage, {\n mapTrigger: (t) => (kindsSet.has(t.kind) ? t.id : undefined),\n });\n}\n\n/**\n * Retrieves notification triggers for a specific account address that match any of the specified kinds.\n * This method filters triggers both by the account address and their kind, returning triggers that match the allowed kinds for the specified address.\n * It leverages `traverseUserStorageTriggers` with a custom mapping function to filter and return only the relevant triggers.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @param address - The specific account address for which to retrieve triggers.\n * @param allowedKinds - An array of trigger kinds (`TRIGGER_TYPES`) to filter the triggers by.\n * @returns An array of `NotificationTrigger` objects that match the allowed kinds for the specified account address.\n */\nexport function getUUIDsForAccountByKinds(\n userStorage: UserStorage,\n address: string,\n allowedKinds: TRIGGER_TYPES[],\n): NotificationTrigger[] {\n const allowedKindsSet = new Set(allowedKinds);\n return traverseUserStorageTriggers(userStorage, {\n address,\n mapTrigger: (trigger) => {\n if (allowedKindsSet.has(trigger.kind as TRIGGER_TYPES)) {\n return trigger;\n }\n return undefined;\n },\n });\n}\n\n/**\n * Upserts (updates or inserts) notification triggers for a given account across all supported chains.\n * This method ensures that each supported trigger type exists for each chain associated with the account.\n * If a trigger type does not exist for a chain, it creates a new trigger with a unique UUID.\n *\n * @param _account - The account address for which to upsert triggers. The address is normalized to lowercase.\n * @param userStorage - The user storage object to be updated with new or existing triggers.\n * @returns The updated user storage object with upserted triggers for the specified account.\n */\nexport function upsertAddressTriggers(\n _account: string,\n userStorage: UserStorage,\n): UserStorage {\n // Ensure the account exists in userStorage\n const account = _account.toLowerCase();\n userStorage[account] = userStorage[account] || {};\n\n // Iterate over each trigger and its supported chains\n for (const [trigger, { supported_chains: supportedChains }] of Object.entries(\n TRIGGERS,\n )) {\n for (const chain of supportedChains) {\n // Ensure the chain exists for the account\n userStorage[account][chain] = userStorage[account][chain] || {};\n\n // Check if the trigger exists for the chain\n const existingTrigger = Object.values(userStorage[account][chain]).find(\n (obj) => obj.k === trigger,\n );\n\n if (!existingTrigger) {\n // If the trigger doesn't exist, create a new one with a new UUID\n const uuid = uuidv4();\n userStorage[account][chain][uuid] = {\n k: trigger as TRIGGER_TYPES,\n e: false,\n };\n }\n }\n }\n\n return userStorage;\n}\n\n/**\n * Upserts (updates or inserts) notification triggers of a specific type across all accounts and chains in user storage.\n * This method ensures that a trigger of the specified type exists for each account and chain. If a trigger of the specified type\n * does not exist for an account and chain, it creates a new trigger with a unique UUID.\n *\n * @param triggerType - The type of trigger to upsert across all accounts and chains.\n * @param userStorage - The user storage object to be updated with new or existing triggers of the specified type.\n * @returns The updated user storage object with upserted triggers of the specified type for all accounts and chains.\n */\nexport function upsertTriggerTypeTriggers(\n triggerType: TRIGGER_TYPES,\n userStorage: UserStorage,\n): UserStorage {\n // Iterate over each account in userStorage\n Object.entries(userStorage).forEach(([account, chains]) => {\n if (account === (USER_STORAGE_VERSION_KEY as unknown as string)) {\n return;\n }\n\n // Iterate over each chain for the account\n Object.entries(chains).forEach(([chain, triggers]) => {\n // Check if the trigger type exists for the chain\n const existingTrigger = Object.values(triggers).find(\n (obj) => obj.k === triggerType,\n );\n\n if (!existingTrigger) {\n // If the trigger type doesn't exist, create a new one with a new UUID\n const uuid = uuidv4();\n userStorage[account][chain][uuid] = {\n k: triggerType,\n e: false,\n };\n }\n });\n });\n\n return userStorage;\n}\n\n/**\n * Toggles the enabled status of a user storage trigger.\n *\n * @param userStorage - The user storage object.\n * @param address - The user's address.\n * @param chainId - The chain ID.\n * @param uuid - The unique identifier for the trigger.\n * @param enabled - The new enabled status.\n * @returns The updated user storage object.\n */\nexport function toggleUserStorageTriggerStatus(\n userStorage: UserStorage,\n address: string,\n chainId: string,\n uuid: string,\n enabled: boolean,\n): UserStorage {\n if (userStorage?.[address]?.[chainId]?.[uuid]) {\n userStorage[address][chainId][uuid].e = enabled;\n }\n\n return userStorage;\n}\n\n/**\n * Performs an API call with automatic retries on failure.\n *\n * @param bearerToken - The JSON Web Token for authorization.\n * @param endpoint - The URL of the API endpoint to call.\n * @param method - The HTTP method ('POST' or 'DELETE').\n * @param body - The body of the request. It should be an object that can be serialized to JSON.\n * @returns A Promise that resolves to the response of the fetch request.\n */\nexport async function makeApiCall<Body>(\n bearerToken: string,\n endpoint: string,\n method: 'POST' | 'DELETE',\n body: Body,\n): Promise<Response> {\n const options: RequestInit = {\n method,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n body: JSON.stringify(body),\n };\n\n return await fetch(endpoint, options);\n}\n"]}
1
+ {"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../../../src/NotificationServicesController/utils/utils.ts"],"names":[],"mappings":";;;AAAA,+BAAoC;AAE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B,MAAyB,EACzB,IAAU;IAEV,MAAM,OAAO,GAAgB;QAC3B,MAAM;QACN,OAAO,EAAE;YACP,cAAc,EAAE,kBAAkB;YAClC,aAAa,EAAE,UAAU,WAAW,EAAE;SACvC;QACD,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;KAC3B,CAAC;IAEF,OAAO,MAAM,KAAK,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;AACxC,CAAC;AAhBD,kCAgBC","sourcesContent":["import { v4 as uuidv4 } from 'uuid';\n\nimport {\n USER_STORAGE_VERSION_KEY,\n USER_STORAGE_VERSION,\n} from '../constants/constants';\nimport type { TRIGGER_TYPES } from '../constants/notification-schema';\nimport { TRIGGERS } from '../constants/notification-schema';\nimport type { UserStorage } from '../types/user-storage/user-storage';\n\nexport type NotificationTrigger = {\n id: string;\n chainId: string;\n kind: string;\n address: string;\n enabled: boolean;\n};\n\ntype MapTriggerFn<Result> = (\n trigger: NotificationTrigger,\n) => Result | undefined;\n\ntype TraverseTriggerOpts<Result> = {\n address?: string;\n mapTrigger?: MapTriggerFn<Result>;\n};\n\n/**\n * Extracts and returns the ID from a notification trigger.\n * This utility function is primarily used as a mapping function in `traverseUserStorageTriggers`\n * to convert a full trigger object into its ID string.\n *\n * @param trigger - The notification trigger from which the ID is extracted.\n * @returns The ID of the provided notification trigger.\n */\nconst triggerToId = (trigger: NotificationTrigger): string => trigger.id;\n\n/**\n * A utility function that returns the input trigger without any transformation.\n * This function is used as the default mapping function in `traverseUserStorageTriggers`\n * when no custom mapping function is provided.\n *\n * @param trigger - The notification trigger to be returned as is.\n * @returns The same notification trigger that was passed in.\n */\nconst triggerIdentity = (trigger: NotificationTrigger): NotificationTrigger =>\n trigger;\n\n/**\n * Create a completely new user storage object with the given accounts and state.\n * This method initializes the user storage with a version key and iterates over each account to populate it with triggers.\n * Each trigger is associated with supported chains, and for each chain, a unique identifier (UUID) is generated.\n * The trigger object contains a kind (`k`) indicating the type of trigger and an enabled state (`e`).\n * The kind and enabled state are stored with abbreviated keys to reduce the JSON size.\n *\n * This is used primarily for creating a new user storage (e.g. when first signing in/enabling notification profile syncing),\n * caution is needed in case you need to remove triggers that you don't want (due to notification setting filters)\n *\n * @param accounts - An array of account objects, each optionally containing an address.\n * @param state - A boolean indicating the initial enabled state for all triggers in the user storage.\n * @returns A `UserStorage` object populated with triggers for each account and chain.\n */\nexport function initializeUserStorage(\n accounts: { address?: string }[],\n state: boolean,\n): UserStorage {\n const userStorage: UserStorage = {\n [USER_STORAGE_VERSION_KEY]: USER_STORAGE_VERSION,\n };\n\n accounts.forEach((account) => {\n const address = account.address?.toLowerCase();\n if (!address) {\n return;\n }\n if (!userStorage[address]) {\n userStorage[address] = {};\n }\n\n Object.entries(TRIGGERS).forEach(\n ([trigger, { supported_chains: supportedChains }]) => {\n supportedChains.forEach((chain) => {\n if (!userStorage[address]?.[chain]) {\n userStorage[address][chain] = {};\n }\n\n userStorage[address][chain][uuidv4()] = {\n k: trigger as TRIGGER_TYPES, // use 'k' instead of 'kind' to reduce the json weight\n e: state, // use 'e' instead of 'enabled' to reduce the json weight\n };\n });\n },\n );\n });\n\n return userStorage;\n}\n\n/**\n * Iterates over user storage to find and optionally transform notification triggers.\n * This method allows for flexible retrieval and transformation of triggers based on provided options.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @param options - Optional parameters to filter and map triggers:\n * - `address`: If provided, only triggers for this address are considered.\n * - `mapTrigger`: A function to transform each trigger. If not provided, triggers are returned as is.\n * @returns An array of triggers, potentially transformed by the `mapTrigger` function.\n */\nexport function traverseUserStorageTriggers<\n ResultTriggers = NotificationTrigger,\n>(\n userStorage: UserStorage,\n options?: TraverseTriggerOpts<ResultTriggers>,\n): ResultTriggers[] {\n const triggers: ResultTriggers[] = [];\n const mapTrigger =\n options?.mapTrigger ?? (triggerIdentity as MapTriggerFn<ResultTriggers>);\n\n for (const address in userStorage) {\n if (address === (USER_STORAGE_VERSION_KEY as unknown as string)) {\n continue;\n }\n if (options?.address && address !== options.address) {\n continue;\n }\n\n for (const chainId in userStorage[address]) {\n if (chainId in userStorage[address]) {\n for (const uuid in userStorage[address][chainId]) {\n if (uuid) {\n const mappedTrigger = mapTrigger({\n id: uuid,\n kind: userStorage[address]?.[chainId]?.[uuid]?.k,\n chainId,\n address,\n enabled: userStorage[address]?.[chainId]?.[uuid]?.e ?? false,\n });\n if (mappedTrigger) {\n triggers.push(mappedTrigger);\n }\n }\n }\n }\n }\n }\n\n return triggers;\n}\n\n/**\n * Verifies the presence of specified accounts and their chains in the user storage.\n * This method checks if each provided account exists in the user storage and if all its supported chains are present.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @param accounts - An array of account addresses to check for presence.\n * @returns A record where each key is an account address and each value is a boolean indicating whether the account and all its supported chains are present in the user storage.\n */\nexport function checkAccountsPresence(\n userStorage: UserStorage,\n accounts: string[],\n): Record<string, boolean> {\n const presenceRecord: Record<string, boolean> = {};\n\n // Initialize presence record for all accounts as false\n accounts.forEach((account) => {\n presenceRecord[account.toLowerCase()] = isAccountEnabled(\n account,\n userStorage,\n );\n });\n\n return presenceRecord;\n}\n\n/**\n * Internal method to check if a given account should be marked as enabled by introspecting user storage\n * Introspection: check if account exists; and also see if has all triggers in schema enabled\n *\n * @param accountAddress - address to check in user storage\n * @param userStorage - user storage object to traverse/introspect\n * @returns boolean if the account is enabled or disabled\n */\nfunction isAccountEnabled(\n accountAddress: string,\n userStorage: UserStorage,\n): boolean {\n const accountObject = userStorage[accountAddress?.toLowerCase()];\n\n // If the account address is not present in the userStorage, return true\n if (!accountObject) {\n return false;\n }\n\n // Check if all available chains are present\n for (const [triggerKind, triggerConfig] of Object.entries(TRIGGERS)) {\n for (const chain of triggerConfig.supported_chains) {\n if (!accountObject[chain]) {\n return false;\n }\n\n const triggerExists = Object.values(accountObject[chain]).some(\n (obj) => obj.k === (triggerKind as TRIGGER_TYPES),\n );\n if (!triggerExists) {\n return false;\n }\n\n // Check if any trigger is disabled\n for (const uuid in accountObject[chain]) {\n if (!accountObject[chain][uuid].e) {\n return false;\n }\n }\n }\n }\n\n return true;\n}\n\n/**\n * Infers and returns an array of enabled notification trigger kinds from the user storage.\n * This method counts the occurrences of each kind of trigger and returns the kinds that are present.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @returns An array of trigger kinds (`TRIGGER_TYPES`) that are enabled in the user storage.\n */\nexport function inferEnabledKinds(userStorage: UserStorage): TRIGGER_TYPES[] {\n const allSupportedKinds = new Set<TRIGGER_TYPES>();\n\n traverseUserStorageTriggers(userStorage, {\n mapTrigger: (t) => {\n allSupportedKinds.add(t.kind as TRIGGER_TYPES);\n },\n });\n\n return Array.from(allSupportedKinds);\n}\n\n/**\n * Retrieves all UUIDs associated with a specific account address from the user storage.\n * This function utilizes `traverseUserStorageTriggers` with a mapping function to extract\n * just the UUIDs of the notification triggers for the given address.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @param address - The specific account address to retrieve UUIDs for.\n * @returns An array of UUID strings associated with the given account address.\n */\nexport function getUUIDsForAccount(\n userStorage: UserStorage,\n address: string,\n): string[] {\n return traverseUserStorageTriggers(userStorage, {\n address,\n mapTrigger: triggerToId,\n });\n}\n\n/**\n * Retrieves all UUIDs from the user storage, regardless of the account address or chain ID.\n * This method leverages `traverseUserStorageTriggers` with a specific mapping function (`triggerToId`)\n * to extract only the UUIDs from all notification triggers present in the user storage.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @returns An array of UUID strings from all notification triggers in the user storage.\n */\nexport function getAllUUIDs(userStorage: UserStorage): string[] {\n return traverseUserStorageTriggers(userStorage, {\n mapTrigger: triggerToId,\n });\n}\n\n/**\n * Retrieves UUIDs for notification triggers that match any of the specified kinds.\n * This method filters triggers based on their kind and returns an array of UUIDs for those that match the allowed kinds.\n * It utilizes `traverseUserStorageTriggers` with a custom mapping function that checks if a trigger's kind is in the allowed list.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @param allowedKinds - An array of kinds (as strings) to filter the triggers by.\n * @returns An array of UUID strings for triggers that match the allowed kinds.\n */\nexport function getUUIDsForKinds(\n userStorage: UserStorage,\n allowedKinds: string[],\n): string[] {\n const kindsSet = new Set(allowedKinds);\n\n return traverseUserStorageTriggers(userStorage, {\n mapTrigger: (t) => (kindsSet.has(t.kind) ? t.id : undefined),\n });\n}\n\n/**\n * Retrieves notification triggers for a specific account address that match any of the specified kinds.\n * This method filters triggers both by the account address and their kind, returning triggers that match the allowed kinds for the specified address.\n * It leverages `traverseUserStorageTriggers` with a custom mapping function to filter and return only the relevant triggers.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @param address - The specific account address for which to retrieve triggers.\n * @param allowedKinds - An array of trigger kinds (`TRIGGER_TYPES`) to filter the triggers by.\n * @returns An array of `NotificationTrigger` objects that match the allowed kinds for the specified account address.\n */\nexport function getUUIDsForAccountByKinds(\n userStorage: UserStorage,\n address: string,\n allowedKinds: TRIGGER_TYPES[],\n): NotificationTrigger[] {\n const allowedKindsSet = new Set(allowedKinds);\n return traverseUserStorageTriggers(userStorage, {\n address,\n mapTrigger: (trigger) => {\n if (allowedKindsSet.has(trigger.kind as TRIGGER_TYPES)) {\n return trigger;\n }\n return undefined;\n },\n });\n}\n\n/**\n * Upserts (updates or inserts) notification triggers for a given account across all supported chains.\n * This method ensures that each supported trigger type exists for each chain associated with the account.\n * If a trigger type does not exist for a chain, it creates a new trigger with a unique UUID.\n *\n * @param _account - The account address for which to upsert triggers. The address is normalized to lowercase.\n * @param userStorage - The user storage object to be updated with new or existing triggers.\n * @returns The updated user storage object with upserted triggers for the specified account.\n */\nexport function upsertAddressTriggers(\n _account: string,\n userStorage: UserStorage,\n): UserStorage {\n // Ensure the account exists in userStorage\n const account = _account.toLowerCase();\n userStorage[account] = userStorage[account] || {};\n\n // Iterate over each trigger and its supported chains\n for (const [trigger, { supported_chains: supportedChains }] of Object.entries(\n TRIGGERS,\n )) {\n for (const chain of supportedChains) {\n // Ensure the chain exists for the account\n userStorage[account][chain] = userStorage[account][chain] || {};\n\n // Check if the trigger exists for the chain\n const existingTrigger = Object.values(userStorage[account][chain]).find(\n (obj) => obj.k === (trigger as TRIGGER_TYPES),\n );\n\n if (!existingTrigger) {\n // If the trigger doesn't exist, create a new one with a new UUID\n const uuid = uuidv4();\n userStorage[account][chain][uuid] = {\n k: trigger as TRIGGER_TYPES,\n e: false,\n };\n }\n }\n }\n\n return userStorage;\n}\n\n/**\n * Upserts (updates or inserts) notification triggers of a specific type across all accounts and chains in user storage.\n * This method ensures that a trigger of the specified type exists for each account and chain. If a trigger of the specified type\n * does not exist for an account and chain, it creates a new trigger with a unique UUID.\n *\n * @param triggerType - The type of trigger to upsert across all accounts and chains.\n * @param userStorage - The user storage object to be updated with new or existing triggers of the specified type.\n * @returns The updated user storage object with upserted triggers of the specified type for all accounts and chains.\n */\nexport function upsertTriggerTypeTriggers(\n triggerType: TRIGGER_TYPES,\n userStorage: UserStorage,\n): UserStorage {\n // Iterate over each account in userStorage\n Object.entries(userStorage).forEach(([account, chains]) => {\n if (account === (USER_STORAGE_VERSION_KEY as unknown as string)) {\n return;\n }\n\n // Iterate over each chain for the account\n Object.entries(chains).forEach(([chain, triggers]) => {\n // Check if the trigger type exists for the chain\n const existingTrigger = Object.values(triggers).find(\n (obj) => obj.k === triggerType,\n );\n\n if (!existingTrigger) {\n // If the trigger type doesn't exist, create a new one with a new UUID\n const uuid = uuidv4();\n userStorage[account][chain][uuid] = {\n k: triggerType,\n e: false,\n };\n }\n });\n });\n\n return userStorage;\n}\n\n/**\n * Toggles the enabled status of a user storage trigger.\n *\n * @param userStorage - The user storage object.\n * @param address - The user's address.\n * @param chainId - The chain ID.\n * @param uuid - The unique identifier for the trigger.\n * @param enabled - The new enabled status.\n * @returns The updated user storage object.\n */\nexport function toggleUserStorageTriggerStatus(\n userStorage: UserStorage,\n address: string,\n chainId: string,\n uuid: string,\n enabled: boolean,\n): UserStorage {\n if (userStorage?.[address]?.[chainId]?.[uuid]) {\n userStorage[address][chainId][uuid].e = enabled;\n }\n\n return userStorage;\n}\n\n/**\n * Performs an API call with automatic retries on failure.\n *\n * @param bearerToken - The JSON Web Token for authorization.\n * @param endpoint - The URL of the API endpoint to call.\n * @param method - The HTTP method ('POST' or 'DELETE').\n * @param body - The body of the request. It should be an object that can be serialized to JSON.\n * @returns A Promise that resolves to the response of the fetch request.\n */\nexport async function makeApiCall<Body>(\n bearerToken: string,\n endpoint: string,\n method: 'POST' | 'DELETE',\n body: Body,\n): Promise<Response> {\n const options: RequestInit = {\n method,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n body: JSON.stringify(body),\n };\n\n return await fetch(endpoint, options);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../../../src/NotificationServicesController/utils/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,aAAa;AAEpC,OAAO,EACL,wBAAwB,EACxB,oBAAoB,EACrB,mCAA+B;AAEhC,OAAO,EAAE,QAAQ,EAAE,6CAAyC;AAoB5D;;;;;;;GAOG;AACH,MAAM,WAAW,GAAG,CAAC,OAA4B,EAAU,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC;AAEzE;;;;;;;GAOG;AACH,MAAM,eAAe,GAAG,CAAC,OAA4B,EAAuB,EAAE,CAC5E,OAAO,CAAC;AAEV;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,qBAAqB,CACnC,QAAgC,EAChC,KAAc;IAEd,MAAM,WAAW,GAAgB;QAC/B,CAAC,wBAAwB,CAAC,EAAE,oBAAoB;KACjD,CAAC;IAEF,QAAQ,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC3B,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,EAAE,WAAW,EAAE,CAAC;QAC/C,IAAI,CAAC,OAAO,EAAE;YACZ,OAAO;SACR;QACD,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,EAAE;YACzB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;iBACT,CAAC;aACH;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,WAAW,CAAC;AACrB,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,8BAA8B,CAC5C,WAAwB,EACxB,OAAe,EACf,OAAe,EACf,IAAY,EACZ,OAAgB;IAEhB,IAAI,WAAW,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE;QAC7C,WAAW,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC;KACjD;IAED,OAAO,WAAW,CAAC;AACrB,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,WAAmB,EACnB,QAAgB,EAChB,MAAyB,EACzB,IAAU;IAEV,MAAM,OAAO,GAAgB;QAC3B,MAAM;QACN,OAAO,EAAE;YACP,cAAc,EAAE,kBAAkB;YAClC,aAAa,EAAE,UAAU,WAAW,EAAE;SACvC;QACD,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;KAC3B,CAAC;IAEF,OAAO,MAAM,KAAK,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import { v4 as uuidv4 } from 'uuid';\n\nimport {\n USER_STORAGE_VERSION_KEY,\n USER_STORAGE_VERSION,\n} from '../constants/constants';\nimport type { TRIGGER_TYPES } from '../constants/notification-schema';\nimport { TRIGGERS } from '../constants/notification-schema';\nimport type { UserStorage } from '../types/user-storage/user-storage';\n\nexport type NotificationTrigger = {\n id: string;\n chainId: string;\n kind: string;\n address: string;\n enabled: boolean;\n};\n\ntype MapTriggerFn<Result> = (\n trigger: NotificationTrigger,\n) => Result | undefined;\n\ntype TraverseTriggerOpts<Result> = {\n address?: string;\n mapTrigger?: MapTriggerFn<Result>;\n};\n\n/**\n * Extracts and returns the ID from a notification trigger.\n * This utility function is primarily used as a mapping function in `traverseUserStorageTriggers`\n * to convert a full trigger object into its ID string.\n *\n * @param trigger - The notification trigger from which the ID is extracted.\n * @returns The ID of the provided notification trigger.\n */\nconst triggerToId = (trigger: NotificationTrigger): string => trigger.id;\n\n/**\n * A utility function that returns the input trigger without any transformation.\n * This function is used as the default mapping function in `traverseUserStorageTriggers`\n * when no custom mapping function is provided.\n *\n * @param trigger - The notification trigger to be returned as is.\n * @returns The same notification trigger that was passed in.\n */\nconst triggerIdentity = (trigger: NotificationTrigger): NotificationTrigger =>\n trigger;\n\n/**\n * Create a completely new user storage object with the given accounts and state.\n * This method initializes the user storage with a version key and iterates over each account to populate it with triggers.\n * Each trigger is associated with supported chains, and for each chain, a unique identifier (UUID) is generated.\n * The trigger object contains a kind (`k`) indicating the type of trigger and an enabled state (`e`).\n * The kind and enabled state are stored with abbreviated keys to reduce the JSON size.\n *\n * This is used primarily for creating a new user storage (e.g. when first signing in/enabling notification profile syncing),\n * caution is needed in case you need to remove triggers that you don't want (due to notification setting filters)\n *\n * @param accounts - An array of account objects, each optionally containing an address.\n * @param state - A boolean indicating the initial enabled state for all triggers in the user storage.\n * @returns A `UserStorage` object populated with triggers for each account and chain.\n */\nexport function initializeUserStorage(\n accounts: { address?: string }[],\n state: boolean,\n): UserStorage {\n const userStorage: UserStorage = {\n [USER_STORAGE_VERSION_KEY]: USER_STORAGE_VERSION,\n };\n\n accounts.forEach((account) => {\n const address = account.address?.toLowerCase();\n if (!address) {\n return;\n }\n if (!userStorage[address]) {\n userStorage[address] = {};\n }\n\n Object.entries(TRIGGERS).forEach(\n ([trigger, { supported_chains: supportedChains }]) => {\n supportedChains.forEach((chain) => {\n if (!userStorage[address]?.[chain]) {\n userStorage[address][chain] = {};\n }\n\n userStorage[address][chain][uuidv4()] = {\n k: trigger as TRIGGER_TYPES, // use 'k' instead of 'kind' to reduce the json weight\n e: state, // use 'e' instead of 'enabled' to reduce the json weight\n };\n });\n },\n );\n });\n\n return userStorage;\n}\n\n/**\n * Iterates over user storage to find and optionally transform notification triggers.\n * This method allows for flexible retrieval and transformation of triggers based on provided options.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @param options - Optional parameters to filter and map triggers:\n * - `address`: If provided, only triggers for this address are considered.\n * - `mapTrigger`: A function to transform each trigger. If not provided, triggers are returned as is.\n * @returns An array of triggers, potentially transformed by the `mapTrigger` function.\n */\nexport function traverseUserStorageTriggers<\n ResultTriggers = NotificationTrigger,\n>(\n userStorage: UserStorage,\n options?: TraverseTriggerOpts<ResultTriggers>,\n): ResultTriggers[] {\n const triggers: ResultTriggers[] = [];\n const mapTrigger =\n options?.mapTrigger ?? (triggerIdentity as MapTriggerFn<ResultTriggers>);\n\n for (const address in userStorage) {\n if (address === (USER_STORAGE_VERSION_KEY as unknown as string)) {\n continue;\n }\n if (options?.address && address !== options.address) {\n continue;\n }\n\n for (const chainId in userStorage[address]) {\n if (chainId in userStorage[address]) {\n for (const uuid in userStorage[address][chainId]) {\n if (uuid) {\n const mappedTrigger = mapTrigger({\n id: uuid,\n kind: userStorage[address]?.[chainId]?.[uuid]?.k,\n chainId,\n address,\n enabled: userStorage[address]?.[chainId]?.[uuid]?.e ?? false,\n });\n if (mappedTrigger) {\n triggers.push(mappedTrigger);\n }\n }\n }\n }\n }\n }\n\n return triggers;\n}\n\n/**\n * Verifies the presence of specified accounts and their chains in the user storage.\n * This method checks if each provided account exists in the user storage and if all its supported chains are present.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @param accounts - An array of account addresses to check for presence.\n * @returns A record where each key is an account address and each value is a boolean indicating whether the account and all its supported chains are present in the user storage.\n */\nexport function checkAccountsPresence(\n userStorage: UserStorage,\n accounts: string[],\n): Record<string, boolean> {\n const presenceRecord: Record<string, boolean> = {};\n\n // Initialize presence record for all accounts as false\n accounts.forEach((account) => {\n presenceRecord[account.toLowerCase()] = isAccountEnabled(\n account,\n userStorage,\n );\n });\n\n return presenceRecord;\n}\n\n/**\n * Internal method to check if a given account should be marked as enabled by introspecting user storage\n * Introspection: check if account exists; and also see if has all triggers in schema enabled\n *\n * @param accountAddress - address to check in user storage\n * @param userStorage - user storage object to traverse/introspect\n * @returns boolean if the account is enabled or disabled\n */\nfunction isAccountEnabled(\n accountAddress: string,\n userStorage: UserStorage,\n): boolean {\n const accountObject = userStorage[accountAddress?.toLowerCase()];\n\n // If the account address is not present in the userStorage, return true\n if (!accountObject) {\n return false;\n }\n\n // Check if all available chains are present\n for (const [triggerKind, triggerConfig] of Object.entries(TRIGGERS)) {\n for (const chain of triggerConfig.supported_chains) {\n if (!accountObject[chain]) {\n return false;\n }\n\n const triggerExists = Object.values(accountObject[chain]).some(\n (obj) => obj.k === triggerKind,\n );\n if (!triggerExists) {\n return false;\n }\n\n // Check if any trigger is disabled\n for (const uuid in accountObject[chain]) {\n if (!accountObject[chain][uuid].e) {\n return false;\n }\n }\n }\n }\n\n return true;\n}\n\n/**\n * Infers and returns an array of enabled notification trigger kinds from the user storage.\n * This method counts the occurrences of each kind of trigger and returns the kinds that are present.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @returns An array of trigger kinds (`TRIGGER_TYPES`) that are enabled in the user storage.\n */\nexport function inferEnabledKinds(userStorage: UserStorage): TRIGGER_TYPES[] {\n const allSupportedKinds = new Set<TRIGGER_TYPES>();\n\n traverseUserStorageTriggers(userStorage, {\n mapTrigger: (t) => {\n allSupportedKinds.add(t.kind as TRIGGER_TYPES);\n },\n });\n\n return Array.from(allSupportedKinds);\n}\n\n/**\n * Retrieves all UUIDs associated with a specific account address from the user storage.\n * This function utilizes `traverseUserStorageTriggers` with a mapping function to extract\n * just the UUIDs of the notification triggers for the given address.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @param address - The specific account address to retrieve UUIDs for.\n * @returns An array of UUID strings associated with the given account address.\n */\nexport function getUUIDsForAccount(\n userStorage: UserStorage,\n address: string,\n): string[] {\n return traverseUserStorageTriggers(userStorage, {\n address,\n mapTrigger: triggerToId,\n });\n}\n\n/**\n * Retrieves all UUIDs from the user storage, regardless of the account address or chain ID.\n * This method leverages `traverseUserStorageTriggers` with a specific mapping function (`triggerToId`)\n * to extract only the UUIDs from all notification triggers present in the user storage.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @returns An array of UUID strings from all notification triggers in the user storage.\n */\nexport function getAllUUIDs(userStorage: UserStorage): string[] {\n return traverseUserStorageTriggers(userStorage, {\n mapTrigger: triggerToId,\n });\n}\n\n/**\n * Retrieves UUIDs for notification triggers that match any of the specified kinds.\n * This method filters triggers based on their kind and returns an array of UUIDs for those that match the allowed kinds.\n * It utilizes `traverseUserStorageTriggers` with a custom mapping function that checks if a trigger's kind is in the allowed list.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @param allowedKinds - An array of kinds (as strings) to filter the triggers by.\n * @returns An array of UUID strings for triggers that match the allowed kinds.\n */\nexport function getUUIDsForKinds(\n userStorage: UserStorage,\n allowedKinds: string[],\n): string[] {\n const kindsSet = new Set(allowedKinds);\n\n return traverseUserStorageTriggers(userStorage, {\n mapTrigger: (t) => (kindsSet.has(t.kind) ? t.id : undefined),\n });\n}\n\n/**\n * Retrieves notification triggers for a specific account address that match any of the specified kinds.\n * This method filters triggers both by the account address and their kind, returning triggers that match the allowed kinds for the specified address.\n * It leverages `traverseUserStorageTriggers` with a custom mapping function to filter and return only the relevant triggers.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @param address - The specific account address for which to retrieve triggers.\n * @param allowedKinds - An array of trigger kinds (`TRIGGER_TYPES`) to filter the triggers by.\n * @returns An array of `NotificationTrigger` objects that match the allowed kinds for the specified account address.\n */\nexport function getUUIDsForAccountByKinds(\n userStorage: UserStorage,\n address: string,\n allowedKinds: TRIGGER_TYPES[],\n): NotificationTrigger[] {\n const allowedKindsSet = new Set(allowedKinds);\n return traverseUserStorageTriggers(userStorage, {\n address,\n mapTrigger: (trigger) => {\n if (allowedKindsSet.has(trigger.kind as TRIGGER_TYPES)) {\n return trigger;\n }\n return undefined;\n },\n });\n}\n\n/**\n * Upserts (updates or inserts) notification triggers for a given account across all supported chains.\n * This method ensures that each supported trigger type exists for each chain associated with the account.\n * If a trigger type does not exist for a chain, it creates a new trigger with a unique UUID.\n *\n * @param _account - The account address for which to upsert triggers. The address is normalized to lowercase.\n * @param userStorage - The user storage object to be updated with new or existing triggers.\n * @returns The updated user storage object with upserted triggers for the specified account.\n */\nexport function upsertAddressTriggers(\n _account: string,\n userStorage: UserStorage,\n): UserStorage {\n // Ensure the account exists in userStorage\n const account = _account.toLowerCase();\n userStorage[account] = userStorage[account] || {};\n\n // Iterate over each trigger and its supported chains\n for (const [trigger, { supported_chains: supportedChains }] of Object.entries(\n TRIGGERS,\n )) {\n for (const chain of supportedChains) {\n // Ensure the chain exists for the account\n userStorage[account][chain] = userStorage[account][chain] || {};\n\n // Check if the trigger exists for the chain\n const existingTrigger = Object.values(userStorage[account][chain]).find(\n (obj) => obj.k === trigger,\n );\n\n if (!existingTrigger) {\n // If the trigger doesn't exist, create a new one with a new UUID\n const uuid = uuidv4();\n userStorage[account][chain][uuid] = {\n k: trigger as TRIGGER_TYPES,\n e: false,\n };\n }\n }\n }\n\n return userStorage;\n}\n\n/**\n * Upserts (updates or inserts) notification triggers of a specific type across all accounts and chains in user storage.\n * This method ensures that a trigger of the specified type exists for each account and chain. If a trigger of the specified type\n * does not exist for an account and chain, it creates a new trigger with a unique UUID.\n *\n * @param triggerType - The type of trigger to upsert across all accounts and chains.\n * @param userStorage - The user storage object to be updated with new or existing triggers of the specified type.\n * @returns The updated user storage object with upserted triggers of the specified type for all accounts and chains.\n */\nexport function upsertTriggerTypeTriggers(\n triggerType: TRIGGER_TYPES,\n userStorage: UserStorage,\n): UserStorage {\n // Iterate over each account in userStorage\n Object.entries(userStorage).forEach(([account, chains]) => {\n if (account === (USER_STORAGE_VERSION_KEY as unknown as string)) {\n return;\n }\n\n // Iterate over each chain for the account\n Object.entries(chains).forEach(([chain, triggers]) => {\n // Check if the trigger type exists for the chain\n const existingTrigger = Object.values(triggers).find(\n (obj) => obj.k === triggerType,\n );\n\n if (!existingTrigger) {\n // If the trigger type doesn't exist, create a new one with a new UUID\n const uuid = uuidv4();\n userStorage[account][chain][uuid] = {\n k: triggerType,\n e: false,\n };\n }\n });\n });\n\n return userStorage;\n}\n\n/**\n * Toggles the enabled status of a user storage trigger.\n *\n * @param userStorage - The user storage object.\n * @param address - The user's address.\n * @param chainId - The chain ID.\n * @param uuid - The unique identifier for the trigger.\n * @param enabled - The new enabled status.\n * @returns The updated user storage object.\n */\nexport function toggleUserStorageTriggerStatus(\n userStorage: UserStorage,\n address: string,\n chainId: string,\n uuid: string,\n enabled: boolean,\n): UserStorage {\n if (userStorage?.[address]?.[chainId]?.[uuid]) {\n userStorage[address][chainId][uuid].e = enabled;\n }\n\n return userStorage;\n}\n\n/**\n * Performs an API call with automatic retries on failure.\n *\n * @param bearerToken - The JSON Web Token for authorization.\n * @param endpoint - The URL of the API endpoint to call.\n * @param method - The HTTP method ('POST' or 'DELETE').\n * @param body - The body of the request. It should be an object that can be serialized to JSON.\n * @returns A Promise that resolves to the response of the fetch request.\n */\nexport async function makeApiCall<Body>(\n bearerToken: string,\n endpoint: string,\n method: 'POST' | 'DELETE',\n body: Body,\n): Promise<Response> {\n const options: RequestInit = {\n method,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n body: JSON.stringify(body),\n };\n\n return await fetch(endpoint, options);\n}\n"]}
1
+ {"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../../../src/NotificationServicesController/utils/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,aAAa;AAEpC,OAAO,EACL,wBAAwB,EACxB,oBAAoB,EACrB,mCAA+B;AAEhC,OAAO,EAAE,QAAQ,EAAE,6CAAyC;AAoB5D;;;;;;;GAOG;AACH,MAAM,WAAW,GAAG,CAAC,OAA4B,EAAU,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC;A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AC,QAAQ,EAAE,OAAO,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import { v4 as uuidv4 } from 'uuid';\n\nimport {\n USER_STORAGE_VERSION_KEY,\n USER_STORAGE_VERSION,\n} from '../constants/constants';\nimport type { TRIGGER_TYPES } from '../constants/notification-schema';\nimport { TRIGGERS } from '../constants/notification-schema';\nimport type { UserStorage } from '../types/user-storage/user-storage';\n\nexport type NotificationTrigger = {\n id: string;\n chainId: string;\n kind: string;\n address: string;\n enabled: boolean;\n};\n\ntype MapTriggerFn<Result> = (\n trigger: NotificationTrigger,\n) => Result | undefined;\n\ntype TraverseTriggerOpts<Result> = {\n address?: string;\n mapTrigger?: MapTriggerFn<Result>;\n};\n\n/**\n * Extracts and returns the ID from a notification trigger.\n * This utility function is primarily used as a mapping function in `traverseUserStorageTriggers`\n * to convert a full trigger object into its ID string.\n *\n * @param trigger - The notification trigger from which the ID is extracted.\n * @returns The ID of the provided notification trigger.\n */\nconst triggerToId = (trigger: NotificationTrigger): string => trigger.id;\n\n/**\n * A utility function that returns the input trigger without any transformation.\n * This function is used as the default mapping function in `traverseUserStorageTriggers`\n * when no custom mapping function is provided.\n *\n * @param trigger - The notification trigger to be returned as is.\n * @returns The same notification trigger that was passed in.\n */\nconst triggerIdentity = (trigger: NotificationTrigger): NotificationTrigger =>\n trigger;\n\n/**\n * Create a completely new user storage object with the given accounts and state.\n * This method initializes the user storage with a version key and iterates over each account to populate it with triggers.\n * Each trigger is associated with supported chains, and for each chain, a unique identifier (UUID) is generated.\n * The trigger object contains a kind (`k`) indicating the type of trigger and an enabled state (`e`).\n * The kind and enabled state are stored with abbreviated keys to reduce the JSON size.\n *\n * This is used primarily for creating a new user storage (e.g. when first signing in/enabling notification profile syncing),\n * caution is needed in case you need to remove triggers that you don't want (due to notification setting filters)\n *\n * @param accounts - An array of account objects, each optionally containing an address.\n * @param state - A boolean indicating the initial enabled state for all triggers in the user storage.\n * @returns A `UserStorage` object populated with triggers for each account and chain.\n */\nexport function initializeUserStorage(\n accounts: { address?: string }[],\n state: boolean,\n): UserStorage {\n const userStorage: UserStorage = {\n [USER_STORAGE_VERSION_KEY]: USER_STORAGE_VERSION,\n };\n\n accounts.forEach((account) => {\n const address = account.address?.toLowerCase();\n if (!address) {\n return;\n }\n if (!userStorage[address]) {\n userStorage[address] = {};\n }\n\n Object.entries(TRIGGERS).forEach(\n ([trigger, { supported_chains: supportedChains }]) => {\n supportedChains.forEach((chain) => {\n if (!userStorage[address]?.[chain]) {\n userStorage[address][chain] = {};\n }\n\n userStorage[address][chain][uuidv4()] = {\n k: trigger as TRIGGER_TYPES, // use 'k' instead of 'kind' to reduce the json weight\n e: state, // use 'e' instead of 'enabled' to reduce the json weight\n };\n });\n },\n );\n });\n\n return userStorage;\n}\n\n/**\n * Iterates over user storage to find and optionally transform notification triggers.\n * This method allows for flexible retrieval and transformation of triggers based on provided options.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @param options - Optional parameters to filter and map triggers:\n * - `address`: If provided, only triggers for this address are considered.\n * - `mapTrigger`: A function to transform each trigger. If not provided, triggers are returned as is.\n * @returns An array of triggers, potentially transformed by the `mapTrigger` function.\n */\nexport function traverseUserStorageTriggers<\n ResultTriggers = NotificationTrigger,\n>(\n userStorage: UserStorage,\n options?: TraverseTriggerOpts<ResultTriggers>,\n): ResultTriggers[] {\n const triggers: ResultTriggers[] = [];\n const mapTrigger =\n options?.mapTrigger ?? (triggerIdentity as MapTriggerFn<ResultTriggers>);\n\n for (const address in userStorage) {\n if (address === (USER_STORAGE_VERSION_KEY as unknown as string)) {\n continue;\n }\n if (options?.address && address !== options.address) {\n continue;\n }\n\n for (const chainId in userStorage[address]) {\n if (chainId in userStorage[address]) {\n for (const uuid in userStorage[address][chainId]) {\n if (uuid) {\n const mappedTrigger = mapTrigger({\n id: uuid,\n kind: userStorage[address]?.[chainId]?.[uuid]?.k,\n chainId,\n address,\n enabled: userStorage[address]?.[chainId]?.[uuid]?.e ?? false,\n });\n if (mappedTrigger) {\n triggers.push(mappedTrigger);\n }\n }\n }\n }\n }\n }\n\n return triggers;\n}\n\n/**\n * Verifies the presence of specified accounts and their chains in the user storage.\n * This method checks if each provided account exists in the user storage and if all its supported chains are present.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @param accounts - An array of account addresses to check for presence.\n * @returns A record where each key is an account address and each value is a boolean indicating whether the account and all its supported chains are present in the user storage.\n */\nexport function checkAccountsPresence(\n userStorage: UserStorage,\n accounts: string[],\n): Record<string, boolean> {\n const presenceRecord: Record<string, boolean> = {};\n\n // Initialize presence record for all accounts as false\n accounts.forEach((account) => {\n presenceRecord[account.toLowerCase()] = isAccountEnabled(\n account,\n userStorage,\n );\n });\n\n return presenceRecord;\n}\n\n/**\n * Internal method to check if a given account should be marked as enabled by introspecting user storage\n * Introspection: check if account exists; and also see if has all triggers in schema enabled\n *\n * @param accountAddress - address to check in user storage\n * @param userStorage - user storage object to traverse/introspect\n * @returns boolean if the account is enabled or disabled\n */\nfunction isAccountEnabled(\n accountAddress: string,\n userStorage: UserStorage,\n): boolean {\n const accountObject = userStorage[accountAddress?.toLowerCase()];\n\n // If the account address is not present in the userStorage, return true\n if (!accountObject) {\n return false;\n }\n\n // Check if all available chains are present\n for (const [triggerKind, triggerConfig] of Object.entries(TRIGGERS)) {\n for (const chain of triggerConfig.supported_chains) {\n if (!accountObject[chain]) {\n return false;\n }\n\n const triggerExists = Object.values(accountObject[chain]).some(\n (obj) => obj.k === (triggerKind as TRIGGER_TYPES),\n );\n if (!triggerExists) {\n return false;\n }\n\n // Check if any trigger is disabled\n for (const uuid in accountObject[chain]) {\n if (!accountObject[chain][uuid].e) {\n return false;\n }\n }\n }\n }\n\n return true;\n}\n\n/**\n * Infers and returns an array of enabled notification trigger kinds from the user storage.\n * This method counts the occurrences of each kind of trigger and returns the kinds that are present.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @returns An array of trigger kinds (`TRIGGER_TYPES`) that are enabled in the user storage.\n */\nexport function inferEnabledKinds(userStorage: UserStorage): TRIGGER_TYPES[] {\n const allSupportedKinds = new Set<TRIGGER_TYPES>();\n\n traverseUserStorageTriggers(userStorage, {\n mapTrigger: (t) => {\n allSupportedKinds.add(t.kind as TRIGGER_TYPES);\n },\n });\n\n return Array.from(allSupportedKinds);\n}\n\n/**\n * Retrieves all UUIDs associated with a specific account address from the user storage.\n * This function utilizes `traverseUserStorageTriggers` with a mapping function to extract\n * just the UUIDs of the notification triggers for the given address.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @param address - The specific account address to retrieve UUIDs for.\n * @returns An array of UUID strings associated with the given account address.\n */\nexport function getUUIDsForAccount(\n userStorage: UserStorage,\n address: string,\n): string[] {\n return traverseUserStorageTriggers(userStorage, {\n address,\n mapTrigger: triggerToId,\n });\n}\n\n/**\n * Retrieves all UUIDs from the user storage, regardless of the account address or chain ID.\n * This method leverages `traverseUserStorageTriggers` with a specific mapping function (`triggerToId`)\n * to extract only the UUIDs from all notification triggers present in the user storage.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @returns An array of UUID strings from all notification triggers in the user storage.\n */\nexport function getAllUUIDs(userStorage: UserStorage): string[] {\n return traverseUserStorageTriggers(userStorage, {\n mapTrigger: triggerToId,\n });\n}\n\n/**\n * Retrieves UUIDs for notification triggers that match any of the specified kinds.\n * This method filters triggers based on their kind and returns an array of UUIDs for those that match the allowed kinds.\n * It utilizes `traverseUserStorageTriggers` with a custom mapping function that checks if a trigger's kind is in the allowed list.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @param allowedKinds - An array of kinds (as strings) to filter the triggers by.\n * @returns An array of UUID strings for triggers that match the allowed kinds.\n */\nexport function getUUIDsForKinds(\n userStorage: UserStorage,\n allowedKinds: string[],\n): string[] {\n const kindsSet = new Set(allowedKinds);\n\n return traverseUserStorageTriggers(userStorage, {\n mapTrigger: (t) => (kindsSet.has(t.kind) ? t.id : undefined),\n });\n}\n\n/**\n * Retrieves notification triggers for a specific account address that match any of the specified kinds.\n * This method filters triggers both by the account address and their kind, returning triggers that match the allowed kinds for the specified address.\n * It leverages `traverseUserStorageTriggers` with a custom mapping function to filter and return only the relevant triggers.\n *\n * @param userStorage - The user storage object containing notification triggers.\n * @param address - The specific account address for which to retrieve triggers.\n * @param allowedKinds - An array of trigger kinds (`TRIGGER_TYPES`) to filter the triggers by.\n * @returns An array of `NotificationTrigger` objects that match the allowed kinds for the specified account address.\n */\nexport function getUUIDsForAccountByKinds(\n userStorage: UserStorage,\n address: string,\n allowedKinds: TRIGGER_TYPES[],\n): NotificationTrigger[] {\n const allowedKindsSet = new Set(allowedKinds);\n return traverseUserStorageTriggers(userStorage, {\n address,\n mapTrigger: (trigger) => {\n if (allowedKindsSet.has(trigger.kind as TRIGGER_TYPES)) {\n return trigger;\n }\n return undefined;\n },\n });\n}\n\n/**\n * Upserts (updates or inserts) notification triggers for a given account across all supported chains.\n * This method ensures that each supported trigger type exists for each chain associated with the account.\n * If a trigger type does not exist for a chain, it creates a new trigger with a unique UUID.\n *\n * @param _account - The account address for which to upsert triggers. The address is normalized to lowercase.\n * @param userStorage - The user storage object to be updated with new or existing triggers.\n * @returns The updated user storage object with upserted triggers for the specified account.\n */\nexport function upsertAddressTriggers(\n _account: string,\n userStorage: UserStorage,\n): UserStorage {\n // Ensure the account exists in userStorage\n const account = _account.toLowerCase();\n userStorage[account] = userStorage[account] || {};\n\n // Iterate over each trigger and its supported chains\n for (const [trigger, { supported_chains: supportedChains }] of Object.entries(\n TRIGGERS,\n )) {\n for (const chain of supportedChains) {\n // Ensure the chain exists for the account\n userStorage[account][chain] = userStorage[account][chain] || {};\n\n // Check if the trigger exists for the chain\n const existingTrigger = Object.values(userStorage[account][chain]).find(\n (obj) => obj.k === (trigger as TRIGGER_TYPES),\n );\n\n if (!existingTrigger) {\n // If the trigger doesn't exist, create a new one with a new UUID\n const uuid = uuidv4();\n userStorage[account][chain][uuid] = {\n k: trigger as TRIGGER_TYPES,\n e: false,\n };\n }\n }\n }\n\n return userStorage;\n}\n\n/**\n * Upserts (updates or inserts) notification triggers of a specific type across all accounts and chains in user storage.\n * This method ensures that a trigger of the specified type exists for each account and chain. If a trigger of the specified type\n * does not exist for an account and chain, it creates a new trigger with a unique UUID.\n *\n * @param triggerType - The type of trigger to upsert across all accounts and chains.\n * @param userStorage - The user storage object to be updated with new or existing triggers of the specified type.\n * @returns The updated user storage object with upserted triggers of the specified type for all accounts and chains.\n */\nexport function upsertTriggerTypeTriggers(\n triggerType: TRIGGER_TYPES,\n userStorage: UserStorage,\n): UserStorage {\n // Iterate over each account in userStorage\n Object.entries(userStorage).forEach(([account, chains]) => {\n if (account === (USER_STORAGE_VERSION_KEY as unknown as string)) {\n return;\n }\n\n // Iterate over each chain for the account\n Object.entries(chains).forEach(([chain, triggers]) => {\n // Check if the trigger type exists for the chain\n const existingTrigger = Object.values(triggers).find(\n (obj) => obj.k === triggerType,\n );\n\n if (!existingTrigger) {\n // If the trigger type doesn't exist, create a new one with a new UUID\n const uuid = uuidv4();\n userStorage[account][chain][uuid] = {\n k: triggerType,\n e: false,\n };\n }\n });\n });\n\n return userStorage;\n}\n\n/**\n * Toggles the enabled status of a user storage trigger.\n *\n * @param userStorage - The user storage object.\n * @param address - The user's address.\n * @param chainId - The chain ID.\n * @param uuid - The unique identifier for the trigger.\n * @param enabled - The new enabled status.\n * @returns The updated user storage object.\n */\nexport function toggleUserStorageTriggerStatus(\n userStorage: UserStorage,\n address: string,\n chainId: string,\n uuid: string,\n enabled: boolean,\n): UserStorage {\n if (userStorage?.[address]?.[chainId]?.[uuid]) {\n userStorage[address][chainId][uuid].e = enabled;\n }\n\n return userStorage;\n}\n\n/**\n * Performs an API call with automatic retries on failure.\n *\n * @param bearerToken - The JSON Web Token for authorization.\n * @param endpoint - The URL of the API endpoint to call.\n * @param method - The HTTP method ('POST' or 'DELETE').\n * @param body - The body of the request. It should be an object that can be serialized to JSON.\n * @returns A Promise that resolves to the response of the fetch request.\n */\nexport async function makeApiCall<Body>(\n bearerToken: string,\n endpoint: string,\n method: 'POST' | 'DELETE',\n body: Body,\n): Promise<Response> {\n const options: RequestInit = {\n method,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n body: JSON.stringify(body),\n };\n\n return await fetch(endpoint, options);\n}\n"]}
@@ -36,8 +36,6 @@ const metadata = {
36
36
  * It is responsible for registering and unregistering the service worker that listens for push notifications,
37
37
  * managing the FCM token, and communicating with the server to register or unregister the device for push notifications.
38
38
  * Additionally, it provides functionality to update the server with new UUIDs that should trigger push notifications.
39
- *
40
- * @augments {BaseController<typeof controllerName, NotificationServicesPushControllerState, NotificationServicesPushControllerMessenger>}
41
39
  */
42
40
  class NotificationServicesPushController extends base_controller_1.BaseController {
43
41
  constructor({ messenger, state, env, config, }) {
@@ -75,7 +73,7 @@ class NotificationServicesPushController extends base_controller_1.BaseControlle
75
73
  },
76
74
  }), "f");
77
75
  }
78
- catch (e) {
76
+ catch {
79
77
  // Do nothing, we are silently failing if push notification registration fails
80
78
  }
81
79
  }
@@ -1 +1 @@
1
- {"version":3,"file":"NotificationServicesPushController.cjs","sourceRoot":"","sources":["../../src/NotificationServicesPushController/NotificationServicesPushController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAMA,+DAA2D;AAE3D,wDAA2B;AAG3B,2DAA0E;AAC1E,sDAK6B;AAG7B,MAAM,cAAc,GAAG,oCAAoC,CAAC;AAuE/C,QAAA,YAAY,GAA4C;IACnE,QAAQ,EAAE,EAAE;CACb,CAAC;AACF,MAAM,QAAQ,GAA2D;IACvE,QAAQ,EAAE;QACR,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;KAChB;CACF,CAAC;AAgCF;;;;;;;;GAQG;AACH,MAAqB,kCAAmC,SAAQ,gCAI/D;IAOC,YAAY,EACV,SAAS,EACT,KAAK,EACL,GAAG,EACH,MAAM,GAMP;QACC,KAAK,CAAC;YACJ,SAAS;YACT,QAAQ;YACR,IAAI,EAAE,cAAc;YACpB,KAAK,EAAE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AC5B,CAAC,CAAC,CAAC;aACJ;SACF;QAAC,OAAO,KAAK,EAAE;YACd,MAAM,YAAY,GAAG,qDACnB,KACF,EAAE,CAAC;YACH,kBAAG,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;YACxB,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;SAC/B;IACH,CAAC;CACF;;IAzMG,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,4DAA4D,EAC5D,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,IAAI,CAAC,CACxC,CAAC;IACF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,6DAA6D,EAC7D,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,IAAI,CAAC,CACzC,CAAC;IACF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,mEAAmE,EACnE,IAAI,CAAC,8BAA8B,CAAC,IAAI,CAAC,IAAI,CAAC,CAC/C,CAAC;IACF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,iEAAiE,EACjE,IAAI,CAAC,4BAA4B,CAAC,IAAI,CAAC,IAAI,CAAC,CAC7C,CAAC;AACJ,CAAC,gEAED,KAAK;IACH,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CACjD,yCAAyC,CAC1C,CAAC;IACF,IAAI,CAAC,WAAW,EAAE;QAChB,kBAAG,CAAC,KAAK,CACP,oEAAoE,CACrE,CAAC;QACF,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;KACjD;IAED,OAAO,WAAW,CAAC;AACrB,CAAC;kBAlEkB,kCAAkC","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport log from 'loglevel';\n\nimport type { Types } from '../NotificationServicesController';\nimport { createRegToken, deleteRegToken } from './services/push/push-web';\nimport {\n activatePushNotifications,\n deactivatePushNotifications,\n listenToPushNotifications,\n updateTriggerPushNotifications,\n} from './services/services';\nimport type { PushNotificationEnv } from './types';\n\nconst controllerName = 'NotificationServicesPushController';\n\nexport type NotificationServicesPushControllerState = {\n fcmToken: string;\n};\n\nexport type NotificationServicesPushControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n NotificationServicesPushControllerState\n >;\n\nexport type NotificationServicesPushControllerEnablePushNotificationsAction = {\n type: `${typeof controllerName}:enablePushNotifications`;\n handler: NotificationServicesPushController['enablePushNotifications'];\n};\nexport type NotificationServicesPushControllerDisablePushNotificationsAction = {\n type: `${typeof controllerName}:disablePushNotifications`;\n handler: NotificationServicesPushController['disablePushNotifications'];\n};\nexport type NotificationServicesPushControllerUpdateTriggerPushNotificationsAction =\n {\n type: `${typeof controllerName}:updateTriggerPushNotifications`;\n handler: NotificationServicesPushController['updateTriggerPushNotifications'];\n };\nexport type NotificationServicesPushControllerSubscribeToNotificationsAction = {\n type: `${typeof controllerName}:subscribeToPushNotifications`;\n handler: NotificationServicesPushController['subscribeToPushNotifications'];\n};\n\nexport type Actions =\n | NotificationServicesPushControllerGetStateAction\n | NotificationServicesPushControllerEnablePushNotificationsAction\n | NotificationServicesPushControllerDisablePushNotificationsAction\n | NotificationServicesPushControllerUpdateTriggerPushNotificationsAction\n | NotificationServicesPushControllerSubscribeToNotificationsAction;\n\nexport type AllowedActions =\n AuthenticationController.AuthenticationControllerGetBearerToken;\n\nexport type NotificationServicesPushControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n NotificationServicesPushControllerState\n >;\n\nexport type NotificationServicesPushControllerOnNewNotificationEvent = {\n type: `${typeof controllerName}:onNewNotifications`;\n payload: [Types.INotification];\n};\n\nexport type NotificationServicesPushControllerPushNotificationClickedEvent = {\n type: `${typeof controllerName}:pushNotificationClicked`;\n payload: [Types.INotification];\n};\n\nexport type Events =\n | NotificationServicesPushControllerStateChangeEvent\n | NotificationServicesPushControllerOnNewNotificationEvent\n | NotificationServicesPushControllerPushNotificationClickedEvent;\n\nexport type AllowedEvents = never;\n\nexport type NotificationServicesPushControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\nexport const defaultState: NotificationServicesPushControllerState = {\n fcmToken: '',\n};\nconst metadata: StateMetadata<NotificationServicesPushControllerState> = {\n fcmToken: {\n persist: true,\n anonymous: true,\n },\n};\n\ntype ControllerConfig = {\n /**\n * Config to turn on/off push notifications.\n * This is currently linked to MV3 builds on extension.\n */\n isPushEnabled: boolean;\n\n /**\n * Must handle when a push notification is received.\n * You must call `registration.showNotification` or equivalent to show the notification on web/mobile\n */\n onPushNotificationReceived: (\n notification: Types.INotification,\n ) => void | Promise<void>;\n\n /**\n * Must handle when a push notification is clicked.\n * You must call `event.notification.close();` or equivalent for closing and opening notification in a new window.\n */\n onPushNotificationClicked: (\n event: NotificationEvent,\n notification?: Types.INotification,\n ) => void;\n\n /**\n * determine the config used for push notification services\n */\n platform: 'extension' | 'mobile';\n};\n\n/**\n * Manages push notifications for the application, including enabling, disabling, and updating triggers for push notifications.\n * This controller integrates with Firebase Cloud Messaging (FCM) to handle the registration and management of push notifications.\n * It is responsible for registering and unregistering the service worker that listens for push notifications,\n * managing the FCM token, and communicating with the server to register or unregister the device for push notifications.\n * Additionally, it provides functionality to update the server with new UUIDs that should trigger push notifications.\n *\n * @augments {BaseController<typeof controllerName, NotificationServicesPushControllerState, NotificationServicesPushControllerMessenger>}\n */\nexport default class NotificationServicesPushController extends BaseController<\n typeof controllerName,\n NotificationServicesPushControllerState,\n NotificationServicesPushControllerMessenger\n> {\n #pushListenerUnsubscribe: (() => void) | undefined = undefined;\n\n #env: PushNotificationEnv;\n\n #config: ControllerConfig;\n\n constructor({\n messenger,\n state,\n env,\n config,\n }: {\n messenger: NotificationServicesPushControllerMessenger;\n state: NotificationServicesPushControllerState;\n env: PushNotificationEnv;\n config: ControllerConfig;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#env = env;\n this.#config = config;\n\n this.#registerMessageHandlers();\n }\n\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:enablePushNotifications',\n this.enablePushNotifications.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:disablePushNotifications',\n this.disablePushNotifications.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:updateTriggerPushNotifications',\n this.updateTriggerPushNotifications.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:subscribeToPushNotifications',\n this.subscribeToPushNotifications.bind(this),\n );\n }\n\n async #getAndAssertBearerToken() {\n const bearerToken = await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n if (!bearerToken) {\n log.error(\n 'Failed to enable push notifications: BearerToken token is missing.',\n );\n throw new Error('BearerToken token is missing');\n }\n\n return bearerToken;\n }\n\n async subscribeToPushNotifications() {\n if (this.#pushListenerUnsubscribe) {\n this.#pushListenerUnsubscribe();\n this.#pushListenerUnsubscribe = undefined;\n }\n\n try {\n this.#pushListenerUnsubscribe = await listenToPushNotifications({\n env: this.#env,\n listenToPushReceived: async (n) => {\n this.messagingSystem.publish(\n 'NotificationServicesPushController:onNewNotifications',\n n,\n );\n await this.#config.onPushNotificationReceived(n);\n },\n listenToPushClicked: (e, n) => {\n if (n) {\n this.messagingSystem.publish(\n 'NotificationServicesPushController:pushNotificationClicked',\n n,\n );\n }\n\n this.#config.onPushNotificationClicked(e, n);\n },\n });\n } catch (e) {\n // Do nothing, we are silently failing if push notification registration fails\n }\n }\n\n /**\n * Enables push notifications for the application.\n *\n * This method sets up the necessary infrastructure for handling push notifications by:\n * 1. Registering the service worker to listen for messages.\n * 2. Fetching the Firebase Cloud Messaging (FCM) token from Firebase.\n * 3. Sending the FCM token to the server responsible for sending notifications, to register the device.\n *\n * @param UUIDs - An array of UUIDs to enable push notifications for.\n * @param fcmToken - The optional FCM token to use for push notifications.\n */\n async enablePushNotifications(UUIDs: string[], fcmToken?: string) {\n if (!this.#config.isPushEnabled) {\n return;\n }\n\n // Handle creating new reg token (if available)\n try {\n const bearerToken = await this.#getAndAssertBearerToken().catch(\n () => null,\n );\n\n // If there is a bearer token, lets try to refresh/create new reg token\n if (bearerToken) {\n // Activate Push Notifications\n const regToken = await activatePushNotifications({\n bearerToken,\n triggers: UUIDs,\n env: this.#env,\n fcmToken,\n createRegToken,\n platform: this.#config.platform,\n }).catch(() => null);\n\n if (regToken) {\n this.update((state) => {\n state.fcmToken = regToken;\n });\n }\n }\n } catch {\n // Do nothing, we are silently failing\n }\n\n // New token created, (re)subscribe to push notifications\n await this.subscribeToPushNotifications();\n }\n\n /**\n * Disables push notifications for the application.\n * This method handles the process of disabling push notifications by:\n * 1. Unregistering the service worker to stop listening for messages.\n * 2. Sending a request to the server to unregister the device using the FCM token.\n * 3. Removing the FCM token from the state to complete the process.\n *\n * @param UUIDs - An array of UUIDs for which push notifications should be disabled.\n */\n async disablePushNotifications(UUIDs: string[]) {\n if (!this.#config.isPushEnabled) {\n return;\n }\n\n const bearerToken = await this.#getAndAssertBearerToken();\n let isPushNotificationsDisabled: boolean;\n\n try {\n // Send a request to the server to unregister the token/device\n isPushNotificationsDisabled = await deactivatePushNotifications({\n bearerToken,\n triggers: UUIDs,\n env: this.#env,\n deleteRegToken,\n regToken: this.state.fcmToken,\n });\n } catch (error) {\n const errorMessage = `Failed to disable push notifications: ${\n error as string\n }`;\n log.error(errorMessage);\n throw new Error(errorMessage);\n }\n\n // Remove the FCM token from the state\n if (!isPushNotificationsDisabled) {\n return;\n }\n\n // Unsubscribe from push notifications\n this.#pushListenerUnsubscribe?.();\n\n // Update State\n if (isPushNotificationsDisabled) {\n this.update((state) => {\n state.fcmToken = '';\n });\n }\n }\n\n /**\n * Updates the triggers for push notifications.\n * This method is responsible for updating the server with the new set of UUIDs that should trigger push notifications.\n * It uses the current FCM token and a BearerToken for authentication.\n *\n * @param UUIDs - An array of UUIDs that should trigger push notifications.\n */\n async updateTriggerPushNotifications(UUIDs: string[]) {\n if (!this.#config.isPushEnabled) {\n return;\n }\n\n const bearerToken = await this.#getAndAssertBearerToken();\n\n try {\n const { fcmToken } = await updateTriggerPushNotifications({\n bearerToken,\n triggers: UUIDs,\n env: this.#env,\n createRegToken,\n deleteRegToken,\n platform: this.#config.platform,\n regToken: this.state.fcmToken,\n });\n\n // update the state with the new FCM token\n if (fcmToken) {\n this.update((state) => {\n state.fcmToken = fcmToken;\n });\n }\n } catch (error) {\n const errorMessage = `Failed to update triggers for push notifications: ${\n error as string\n }`;\n log.error(errorMessage);\n throw new Error(errorMessage);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"NotificationServicesPushController.cjs","sourceRoot":"","sources":["../../src/NotificationServicesPushController/NotificationServicesPushController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAMA,+DAA2D;AAE3D,wDAA2B;AAE3B,2DAA0E;AAC1E,sDAK6B;AAI7B,MAAM,cAAc,GAAG,oCAAoC,CAAC;AAuE/C,QAAA,YAAY,GAA4C;IACnE,QAAQ,EAAE,EAAE;CACb,CAAC;AACF,MAAM,QAAQ,GAA2D;IACvE,QAAQ,EAAE;QACR,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;KAChB;CACF,CAAC;AAgCF;;;;;;GAMG;AACH,MAAqB,kCAAmC,SAAQ,gCAI/D;IAOC,YAAY,EACV,SAAS,EACT,KAAK,EACL,GAAG,EACH,MAAM,GAMP;QACC,KAAK,CAAC;YACJ,SAAS;YACT,QAAQ;YACR,IAAI,EAAE,cAAc;YACpB,KAAK,EAAE,EAAE,GAAG,oBAAY,EAAE,GAAG,KAAK,EAAE;SACrC,CAAC,CAAC;;QAtBL,sEAAqD,SAAS,EAAC;QAEtD,0DAA0B;QAE1B,6DAA0B;QAoBj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,CAAC,CAAC;YACxB,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;SAC/B;IACH,CAAC;CACF;;IAzMG,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,4DAA4D,EAC5D,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,IAAI,CAAC,CACxC,CAAC;IACF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,6DAA6D,EAC7D,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,IAAI,CAAC,CACzC,CAAC;IACF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,mEAAmE,EACnE,IAAI,CAAC,8BAA8B,CAAC,IAAI,CAAC,IAAI,CAAC,CAC/C,CAAC;IACF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,iEAAiE,EACjE,IAAI,CAAC,4BAA4B,CAAC,IAAI,CAAC,IAAI,CAAC,CAC7C,CAAC;AACJ,CAAC,gEAED,KAAK;IACH,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CACjD,yCAAyC,CAC1C,CAAC;IACF,IAAI,CAAC,WAAW,EAAE;QAChB,kBAAG,CAAC,KAAK,CACP,oEAAoE,CACrE,CAAC;QACF,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;KACjD;IAED,OAAO,WAAW,CAAC;AACrB,CAAC;kBAlEkB,kCAAkC","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport log from 'loglevel';\n\nimport { createRegToken, deleteRegToken } from './services/push/push-web';\nimport {\n activatePushNotifications,\n deactivatePushNotifications,\n listenToPushNotifications,\n updateTriggerPushNotifications,\n} from './services/services';\nimport type { PushNotificationEnv } from './types';\nimport type { Types } from '../NotificationServicesController';\n\nconst controllerName = 'NotificationServicesPushController';\n\nexport type NotificationServicesPushControllerState = {\n fcmToken: string;\n};\n\nexport type NotificationServicesPushControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n NotificationServicesPushControllerState\n >;\n\nexport type NotificationServicesPushControllerEnablePushNotificationsAction = {\n type: `${typeof controllerName}:enablePushNotifications`;\n handler: NotificationServicesPushController['enablePushNotifications'];\n};\nexport type NotificationServicesPushControllerDisablePushNotificationsAction = {\n type: `${typeof controllerName}:disablePushNotifications`;\n handler: NotificationServicesPushController['disablePushNotifications'];\n};\nexport type NotificationServicesPushControllerUpdateTriggerPushNotificationsAction =\n {\n type: `${typeof controllerName}:updateTriggerPushNotifications`;\n handler: NotificationServicesPushController['updateTriggerPushNotifications'];\n };\nexport type NotificationServicesPushControllerSubscribeToNotificationsAction = {\n type: `${typeof controllerName}:subscribeToPushNotifications`;\n handler: NotificationServicesPushController['subscribeToPushNotifications'];\n};\n\nexport type Actions =\n | NotificationServicesPushControllerGetStateAction\n | NotificationServicesPushControllerEnablePushNotificationsAction\n | NotificationServicesPushControllerDisablePushNotificationsAction\n | NotificationServicesPushControllerUpdateTriggerPushNotificationsAction\n | NotificationServicesPushControllerSubscribeToNotificationsAction;\n\nexport type AllowedActions =\n AuthenticationController.AuthenticationControllerGetBearerToken;\n\nexport type NotificationServicesPushControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n NotificationServicesPushControllerState\n >;\n\nexport type NotificationServicesPushControllerOnNewNotificationEvent = {\n type: `${typeof controllerName}:onNewNotifications`;\n payload: [Types.INotification];\n};\n\nexport type NotificationServicesPushControllerPushNotificationClickedEvent = {\n type: `${typeof controllerName}:pushNotificationClicked`;\n payload: [Types.INotification];\n};\n\nexport type Events =\n | NotificationServicesPushControllerStateChangeEvent\n | NotificationServicesPushControllerOnNewNotificationEvent\n | NotificationServicesPushControllerPushNotificationClickedEvent;\n\nexport type AllowedEvents = never;\n\nexport type NotificationServicesPushControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\nexport const defaultState: NotificationServicesPushControllerState = {\n fcmToken: '',\n};\nconst metadata: StateMetadata<NotificationServicesPushControllerState> = {\n fcmToken: {\n persist: true,\n anonymous: true,\n },\n};\n\ntype ControllerConfig = {\n /**\n * Config to turn on/off push notifications.\n * This is currently linked to MV3 builds on extension.\n */\n isPushEnabled: boolean;\n\n /**\n * Must handle when a push notification is received.\n * You must call `registration.showNotification` or equivalent to show the notification on web/mobile\n */\n onPushNotificationReceived: (\n notification: Types.INotification,\n ) => void | Promise<void>;\n\n /**\n * Must handle when a push notification is clicked.\n * You must call `event.notification.close();` or equivalent for closing and opening notification in a new window.\n */\n onPushNotificationClicked: (\n event: NotificationEvent,\n notification?: Types.INotification,\n ) => void;\n\n /**\n * determine the config used for push notification services\n */\n platform: 'extension' | 'mobile';\n};\n\n/**\n * Manages push notifications for the application, including enabling, disabling, and updating triggers for push notifications.\n * This controller integrates with Firebase Cloud Messaging (FCM) to handle the registration and management of push notifications.\n * It is responsible for registering and unregistering the service worker that listens for push notifications,\n * managing the FCM token, and communicating with the server to register or unregister the device for push notifications.\n * Additionally, it provides functionality to update the server with new UUIDs that should trigger push notifications.\n */\nexport default class NotificationServicesPushController extends BaseController<\n typeof controllerName,\n NotificationServicesPushControllerState,\n NotificationServicesPushControllerMessenger\n> {\n #pushListenerUnsubscribe: (() => void) | undefined = undefined;\n\n readonly #env: PushNotificationEnv;\n\n readonly #config: ControllerConfig;\n\n constructor({\n messenger,\n state,\n env,\n config,\n }: {\n messenger: NotificationServicesPushControllerMessenger;\n state: NotificationServicesPushControllerState;\n env: PushNotificationEnv;\n config: ControllerConfig;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#env = env;\n this.#config = config;\n\n this.#registerMessageHandlers();\n }\n\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:enablePushNotifications',\n this.enablePushNotifications.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:disablePushNotifications',\n this.disablePushNotifications.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:updateTriggerPushNotifications',\n this.updateTriggerPushNotifications.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:subscribeToPushNotifications',\n this.subscribeToPushNotifications.bind(this),\n );\n }\n\n async #getAndAssertBearerToken() {\n const bearerToken = await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n if (!bearerToken) {\n log.error(\n 'Failed to enable push notifications: BearerToken token is missing.',\n );\n throw new Error('BearerToken token is missing');\n }\n\n return bearerToken;\n }\n\n async subscribeToPushNotifications() {\n if (this.#pushListenerUnsubscribe) {\n this.#pushListenerUnsubscribe();\n this.#pushListenerUnsubscribe = undefined;\n }\n\n try {\n this.#pushListenerUnsubscribe = await listenToPushNotifications({\n env: this.#env,\n listenToPushReceived: async (n) => {\n this.messagingSystem.publish(\n 'NotificationServicesPushController:onNewNotifications',\n n,\n );\n await this.#config.onPushNotificationReceived(n);\n },\n listenToPushClicked: (e, n) => {\n if (n) {\n this.messagingSystem.publish(\n 'NotificationServicesPushController:pushNotificationClicked',\n n,\n );\n }\n\n this.#config.onPushNotificationClicked(e, n);\n },\n });\n } catch {\n // Do nothing, we are silently failing if push notification registration fails\n }\n }\n\n /**\n * Enables push notifications for the application.\n *\n * This method sets up the necessary infrastructure for handling push notifications by:\n * 1. Registering the service worker to listen for messages.\n * 2. Fetching the Firebase Cloud Messaging (FCM) token from Firebase.\n * 3. Sending the FCM token to the server responsible for sending notifications, to register the device.\n *\n * @param UUIDs - An array of UUIDs to enable push notifications for.\n * @param fcmToken - The optional FCM token to use for push notifications.\n */\n async enablePushNotifications(UUIDs: string[], fcmToken?: string) {\n if (!this.#config.isPushEnabled) {\n return;\n }\n\n // Handle creating new reg token (if available)\n try {\n const bearerToken = await this.#getAndAssertBearerToken().catch(\n () => null,\n );\n\n // If there is a bearer token, lets try to refresh/create new reg token\n if (bearerToken) {\n // Activate Push Notifications\n const regToken = await activatePushNotifications({\n bearerToken,\n triggers: UUIDs,\n env: this.#env,\n fcmToken,\n createRegToken,\n platform: this.#config.platform,\n }).catch(() => null);\n\n if (regToken) {\n this.update((state) => {\n state.fcmToken = regToken;\n });\n }\n }\n } catch {\n // Do nothing, we are silently failing\n }\n\n // New token created, (re)subscribe to push notifications\n await this.subscribeToPushNotifications();\n }\n\n /**\n * Disables push notifications for the application.\n * This method handles the process of disabling push notifications by:\n * 1. Unregistering the service worker to stop listening for messages.\n * 2. Sending a request to the server to unregister the device using the FCM token.\n * 3. Removing the FCM token from the state to complete the process.\n *\n * @param UUIDs - An array of UUIDs for which push notifications should be disabled.\n */\n async disablePushNotifications(UUIDs: string[]) {\n if (!this.#config.isPushEnabled) {\n return;\n }\n\n const bearerToken = await this.#getAndAssertBearerToken();\n let isPushNotificationsDisabled: boolean;\n\n try {\n // Send a request to the server to unregister the token/device\n isPushNotificationsDisabled = await deactivatePushNotifications({\n bearerToken,\n triggers: UUIDs,\n env: this.#env,\n deleteRegToken,\n regToken: this.state.fcmToken,\n });\n } catch (error) {\n const errorMessage = `Failed to disable push notifications: ${\n error as string\n }`;\n log.error(errorMessage);\n throw new Error(errorMessage);\n }\n\n // Remove the FCM token from the state\n if (!isPushNotificationsDisabled) {\n return;\n }\n\n // Unsubscribe from push notifications\n this.#pushListenerUnsubscribe?.();\n\n // Update State\n if (isPushNotificationsDisabled) {\n this.update((state) => {\n state.fcmToken = '';\n });\n }\n }\n\n /**\n * Updates the triggers for push notifications.\n * This method is responsible for updating the server with the new set of UUIDs that should trigger push notifications.\n * It uses the current FCM token and a BearerToken for authentication.\n *\n * @param UUIDs - An array of UUIDs that should trigger push notifications.\n */\n async updateTriggerPushNotifications(UUIDs: string[]) {\n if (!this.#config.isPushEnabled) {\n return;\n }\n\n const bearerToken = await this.#getAndAssertBearerToken();\n\n try {\n const { fcmToken } = await updateTriggerPushNotifications({\n bearerToken,\n triggers: UUIDs,\n env: this.#env,\n createRegToken,\n deleteRegToken,\n platform: this.#config.platform,\n regToken: this.state.fcmToken,\n });\n\n // update the state with the new FCM token\n if (fcmToken) {\n this.update((state) => {\n state.fcmToken = fcmToken;\n });\n }\n } catch (error) {\n const errorMessage = `Failed to update triggers for push notifications: ${\n error as string\n }`;\n log.error(errorMessage);\n throw new Error(errorMessage);\n }\n }\n}\n"]}
@@ -1,8 +1,8 @@
1
1
  import type { RestrictedMessenger, ControllerGetStateAction, ControllerStateChangeEvent } from "@metamask/base-controller";
2
2
  import { BaseController } from "@metamask/base-controller";
3
3
  import type { AuthenticationController } from "@metamask/profile-sync-controller";
4
- import type { Types } from "../NotificationServicesController/index.cjs";
5
4
  import type { PushNotificationEnv } from "./types/index.cjs";
5
+ import type { Types } from "../NotificationServicesController/index.cjs";
6
6
  declare const controllerName = "NotificationServicesPushController";
7
7
  export type NotificationServicesPushControllerState = {
8
8
  fcmToken: string;
@@ -66,8 +66,6 @@ type ControllerConfig = {
66
66
  * It is responsible for registering and unregistering the service worker that listens for push notifications,
67
67
  * managing the FCM token, and communicating with the server to register or unregister the device for push notifications.
68
68
  * Additionally, it provides functionality to update the server with new UUIDs that should trigger push notifications.
69
- *
70
- * @augments {BaseController<typeof controllerName, NotificationServicesPushControllerState, NotificationServicesPushControllerMessenger>}
71
69
  */
72
70
  export default class NotificationServicesPushController extends BaseController<typeof controllerName, NotificationServicesPushControllerState, NotificationServicesPushControllerMessenger> {
73
71
  #private;
@@ -1 +1 @@
1
- {"version":3,"file":"NotificationServicesPushController.d.cts","sourceRoot":"","sources":["../../src/NotificationServicesPushController/NotificationServicesPushController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EAAE,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BAAmB,CAAC;QACzB,MAAM,EAAE,gBAAgB,CAAC;KAC1B;IA+CK,4BAA4B;IAgClC;;;;;;;;;;OAUG;IACG,uBAAuB,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,QAAQ,CAAC,EAAE,MAAM;IAqChE;;;;;;;;OAQG;IACG,wBAAwB,CAAC,KAAK,EAAE,MAAM,EAAE;IAyC9C;;;;;;OAMG;IACG,8BAA8B,CAAC,KAAK,EAAE,MAAM,EAAE;CAgCrD"}
1
+ {"version":3,"file":"NotificationServicesPushController.d.cts","sourceRoot":"","sources":["../../src/NotificationServicesPushController/NotificationServicesPushController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EAAE,wBAAwB,EAAE,0CAA0C;AAUlF,OAAO,KAAK,EAAE,mBAAmB,EAAE,0BAAgB;AACnD,OAAO,KAAK,EAAE,KAAK,EAAE,oDAA0C;AAE/D,QAAA,MAAM,cAAc,uCAAuC,CAAC;AAE5D,MAAM,MAAM,uCAAuC,GAAG;IACpD,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,gDAAgD,GAC1D,wBAAwB,CACtB,OAAO,cAAc,EACrB,uCAAuC,CACxC,CAAC;AAEJ,MAAM,MAAM,+DAA+D,GAAG;IAC5E,IAAI,EAAE,GAAG,OAAO,cAAc,0BAA0B,CAAC;IACzD,OAAO,EAAE,kCAAkC,CAAC,yBAAyB,CAAC,CAAC;CACxE,CAAC;AACF,MAAM,MAAM,gEAAgE,GAAG;IAC7E,IAAI,EAAE,GAAG,OAAO,cAAc,2BAA2B,CAAC;IAC1D,OAAO,EAAE,kCAAkC,CAAC,0BAA0B,CAAC,CAAC;CACzE,CAAC;AACF,MAAM,MAAM,sEAAsE,GAChF;IACE,IAAI,EAAE,GAAG,OAAO,cAAc,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,YAAY,EAAE,KAAK,CAAC,aAAa,KAC9B,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE1B;;;OAGG;IACH,yBAAyB,EAAE,CACzB,KAAK,EAAE,iBAAiB,EACxB,YAAY,CAAC,EAAE,KAAK,CAAC,aAAa,KAC/B,IAAI,CAAC;IAEV;;OAEG;IACH,QAAQ,EAAE,WAAW,GAAG,QAAQ,CAAC;CAClC,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,CAAC,OAAO,OAAO,kCAAmC,SAAQ,cAAc,CAC5E,OAAO,cAAc,EACrB,uCAAuC,EACvC,2CAA2C,CAC5C;;gBAOa,EACV,SAAS,EACT,KAAK,EACL,GAAG,EACH,MAAM,GACP,EAAE;QACD,SAAS,EAAE,2CAA2C,CAAC;QACvD,KAAK,EAAE,uCAAuC,CAAC;QAC/C,GAAG,EAAE,mBAAmB,CAAC;QACzB,MAAM,EAAE,gBAAgB,CAAC;KAC1B;IA+CK,4BAA4B;IAgClC;;;;;;;;;;OAUG;IACG,uBAAuB,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,QAAQ,CAAC,EAAE,MAAM;IAqChE;;;;;;;;OAQG;IACG,wBAAwB,CAAC,KAAK,EAAE,MAAM,EAAE;IAyC9C;;;;;;OAMG;IACG,8BAA8B,CAAC,KAAK,EAAE,MAAM,EAAE;CAgCrD"}
@@ -1,8 +1,8 @@
1
1
  import type { RestrictedMessenger, ControllerGetStateAction, ControllerStateChangeEvent } from "@metamask/base-controller";
2
2
  import { BaseController } from "@metamask/base-controller";
3
3
  import type { AuthenticationController } from "@metamask/profile-sync-controller";
4
- import type { Types } from "../NotificationServicesController/index.mjs";
5
4
  import type { PushNotificationEnv } from "./types/index.mjs";
5
+ import type { Types } from "../NotificationServicesController/index.mjs";
6
6
  declare const controllerName = "NotificationServicesPushController";
7
7
  export type NotificationServicesPushControllerState = {
8
8
  fcmToken: string;
@@ -66,8 +66,6 @@ type ControllerConfig = {
66
66
  * It is responsible for registering and unregistering the service worker that listens for push notifications,
67
67
  * managing the FCM token, and communicating with the server to register or unregister the device for push notifications.
68
68
  * Additionally, it provides functionality to update the server with new UUIDs that should trigger push notifications.
69
- *
70
- * @augments {BaseController<typeof controllerName, NotificationServicesPushControllerState, NotificationServicesPushControllerMessenger>}
71
69
  */
72
70
  export default class NotificationServicesPushController extends BaseController<typeof controllerName, NotificationServicesPushControllerState, NotificationServicesPushControllerMessenger> {
73
71
  #private;
@@ -1 +1 @@
1
- {"version":3,"file":"NotificationServicesPushController.d.mts","sourceRoot":"","sources":["../../src/NotificationServicesPushController/NotificationServicesPushController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EAAE,wBAAwB,EAAE,0CAA0C;AAGlF,OAAO,KAAK,EAAE,KAAK,EAAE,oDAA0C;AAQ/D,OAAO,KAAK,EAAE,mBAAmB,EAAE,0BAAgB;AAEnD,QAAA,MAAM,cAAc,uCAAuC,CAAC;AAE5D,MAAM,MAAM,uCAAuC,GAAG;IACpD,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,gDAAgD,GAC1D,wBAAwB,CACtB,OAAO,cAAc,EACrB,uCAAuC,CACxC,CAAC;AAEJ,MAAM,MAAM,+DAA+D,GAAG;IAC5E,IAAI,EAAE,GAAG,OAAO,cAAc,0BAA0B,CAAC;IACzD,OAAO,EAAE,kCAAkC,CAAC,yBAAyB,CAAC,CAAC;CACxE,CAAC;AACF,MAAM,MAAM,gEAAgE,GAAG;IAC7E,IAAI,EAAE,GAAG,OAAO,cAAc,2BAA2B,CAAC;IAC1D,OAAO,EAAE,kCAAkC,CAAC,0BAA0B,CAAC,CAAC;CACzE,CAAC;AACF,MAAM,MAAM,sEAAsE,GAChF;IACE,IAAI,EAAE,GAAG,OAAO,cAAc,iCAAi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,EAAE,KAAK,CAAC,aAAa,KAC9B,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE1B;;;OAGG;IACH,yBAAyB,EAAE,CACzB,KAAK,EAAE,iBAAiB,EACxB,YAAY,CAAC,EAAE,KAAK,CAAC,aAAa,KAC/B,IAAI,CAAC;IAEV;;OAEG;IACH,QAAQ,EAAE,WAAW,GAAG,QAAQ,CAAC;CAClC,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,CAAC,OAAO,OAAO,kCAAmC,SAAQ,cAAc,CAC5E,OAAO,cAAc,EACrB,uCAAuC,EACvC,2CAA2C,CAC5C;;gBAOa,EACV,SAAS,EACT,KAAK,EACL,GAAG,EACH,MAAM,GACP,EAAE;QACD,SAAS,EAAE,2CAA2C,CAAC;QACvD,KAAK,EAAE,uCAAuC,CAAC;QAC/C,GAAG,EAAE,mBAAmB,CAAC;QACzB,MAAM,EAAE,gBAAgB,CAAC;KAC1B;IA+CK,4BAA4B;IAgClC;;;;;;;;;;OAUG;IACG,uBAAuB,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,QAAQ,CAAC,EAAE,MAAM;IAqChE;;;;;;;;OAQG;IACG,wBAAwB,CAAC,KAAK,EAAE,MAAM,EAAE;IAyC9C;;;;;;OAMG;IACG,8BAA8B,CAAC,KAAK,EAAE,MAAM,EAAE;CAgCrD"}
1
+ {"version":3,"file":"NotificationServicesPushController.d.mts","sourceRoot":"","sources":["../../src/NotificationServicesPushController/NotificationServicesPushController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EAAE,wBAAwB,EAAE,0CAA0C;AAUlF,OAAO,KAAK,EAAE,mBAAmB,EAAE,0BAAgB;AACnD,OAAO,KAAK,EAAE,KAAK,EAAE,oDAA0C;AAE/D,QAAA,MAAM,cAAc,uCAA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AAC,EAAE,MAAM;IAqChE;;;;;;;;OAQG;IACG,wBAAwB,CAAC,KAAK,EAAE,MAAM,EAAE;IAyC9C;;;;;;OAMG;IACG,8BAA8B,CAAC,KAAK,EAAE,MAAM,EAAE;CAgCrD"}
@@ -37,8 +37,6 @@ const metadata = {
37
37
  * It is responsible for registering and unregistering the service worker that listens for push notifications,
38
38
  * managing the FCM token, and communicating with the server to register or unregister the device for push notifications.
39
39
  * Additionally, it provides functionality to update the server with new UUIDs that should trigger push notifications.
40
- *
41
- * @augments {BaseController<typeof controllerName, NotificationServicesPushControllerState, NotificationServicesPushControllerMessenger>}
42
40
  */
43
41
  class NotificationServicesPushController extends BaseController {
44
42
  constructor({ messenger, state, env, config, }) {
@@ -76,7 +74,7 @@ class NotificationServicesPushController extends BaseController {
76
74
  },
77
75
  }), "f");
78
76
  }
79
- catch (e) {
77
+ catch {
80
78
  // Do nothing, we are silently failing if push notification registration fails
81
79
  }
82
80
  }
@@ -1 +1 @@
1
- {"version":3,"file":"NotificationServicesPushController.mjs","sourceRoot":"","sources":["../../src/NotificationServicesPushController/NotificationServicesPushController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAMA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAE3D,OAAO,IAAG,iBAAiB;;AAG3B,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,qCAAiC;AAC1E,OAAO,EACL,yBAAyB,EACzB,2BAA2B,EAC3B,yBAAyB,EACzB,8BAA8B,EAC/B,gCAA4B;AAG7B,MAAM,cAAc,GAAG,oCAAoC,CAAC;AAuE5D,MAAM,CAAC,MAAM,YAAY,GAA4C;IACnE,QAAQ,EAAE,EAAE;CACb,CAAC;AACF,MAAM,QAAQ,GAA2D;IACvE,QAAQ,EAAE;QACR,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;KAChB;CACF,CAAC;AAgCF;;;;;;;;GAQG;AACH,MAAqB,kCAAmC,SAAQ,cAI/D;IAOC,YAAY,EACV,SA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B,KAAK,CAAC,QAAQ,GAAG,QAAQ,CAAC;gBAC5B,CAAC,CAAC,CAAC;aACJ;SACF;QAAC,OAAO,KAAK,EAAE;YACd,MAAM,YAAY,GAAG,qDACnB,KACF,EAAE,CAAC;YACH,GAAG,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;YACxB,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;SAC/B;IACH,CAAC;CACF;;IAzMG,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,4DAA4D,EAC5D,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,IAAI,CAAC,CACxC,CAAC;IACF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,6DAA6D,EAC7D,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,IAAI,CAAC,CACzC,CAAC;IACF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,mEAAmE,EACnE,IAAI,CAAC,8BAA8B,CAAC,IAAI,CAAC,IAAI,CAAC,CAC/C,CAAC;IACF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,iEAAiE,EACjE,IAAI,CAAC,4BAA4B,CAAC,IAAI,CAAC,IAAI,CAAC,CAC7C,CAAC;AACJ,CAAC,gEAED,KAAK;IACH,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CACjD,yCAAyC,CAC1C,CAAC;IACF,IAAI,CAAC,WAAW,EAAE;QAChB,GAAG,CAAC,KAAK,CACP,oEAAoE,CACrE,CAAC;QACF,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;KACjD;IAED,OAAO,WAAW,CAAC;AACrB,CAAC;eAlEkB,kCAAkC","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport log from 'loglevel';\n\nimport type { Types } from '../NotificationServicesController';\nimport { createRegToken, deleteRegToken } from './services/push/push-web';\nimport {\n activatePushNotifications,\n deactivatePushNotifications,\n listenToPushNotifications,\n updateTriggerPushNotifications,\n} from './services/services';\nimport type { PushNotificationEnv } from './types';\n\nconst controllerName = 'NotificationServicesPushController';\n\nexport type NotificationServicesPushControllerState = {\n fcmToken: string;\n};\n\nexport type NotificationServicesPushControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n NotificationServicesPushControllerState\n >;\n\nexport type NotificationServicesPushControllerEnablePushNotificationsAction = {\n type: `${typeof controllerName}:enablePushNotifications`;\n handler: NotificationServicesPushController['enablePushNotifications'];\n};\nexport type NotificationServicesPushControllerDisablePushNotificationsAction = {\n type: `${typeof controllerName}:disablePushNotifications`;\n handler: NotificationServicesPushController['disablePushNotifications'];\n};\nexport type NotificationServicesPushControllerUpdateTriggerPushNotificationsAction =\n {\n type: `${typeof controllerName}:updateTriggerPushNotifications`;\n handler: NotificationServicesPushController['updateTriggerPushNotifications'];\n };\nexport type NotificationServicesPushControllerSubscribeToNotificationsAction = {\n type: `${typeof controllerName}:subscribeToPushNotifications`;\n handler: NotificationServicesPushController['subscribeToPushNotifications'];\n};\n\nexport type Actions =\n | NotificationServicesPushControllerGetStateAction\n | NotificationServicesPushControllerEnablePushNotificationsAction\n | NotificationServicesPushControllerDisablePushNotificationsAction\n | NotificationServicesPushControllerUpdateTriggerPushNotificationsAction\n | NotificationServicesPushControllerSubscribeToNotificationsAction;\n\nexport type AllowedActions =\n AuthenticationController.AuthenticationControllerGetBearerToken;\n\nexport type NotificationServicesPushControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n NotificationServicesPushControllerState\n >;\n\nexport type NotificationServicesPushControllerOnNewNotificationEvent = {\n type: `${typeof controllerName}:onNewNotifications`;\n payload: [Types.INotification];\n};\n\nexport type NotificationServicesPushControllerPushNotificationClickedEvent = {\n type: `${typeof controllerName}:pushNotificationClicked`;\n payload: [Types.INotification];\n};\n\nexport type Events =\n | NotificationServicesPushControllerStateChangeEvent\n | NotificationServicesPushControllerOnNewNotificationEvent\n | NotificationServicesPushControllerPushNotificationClickedEvent;\n\nexport type AllowedEvents = never;\n\nexport type NotificationServicesPushControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\nexport const defaultState: NotificationServicesPushControllerState = {\n fcmToken: '',\n};\nconst metadata: StateMetadata<NotificationServicesPushControllerState> = {\n fcmToken: {\n persist: true,\n anonymous: true,\n },\n};\n\ntype ControllerConfig = {\n /**\n * Config to turn on/off push notifications.\n * This is currently linked to MV3 builds on extension.\n */\n isPushEnabled: boolean;\n\n /**\n * Must handle when a push notification is received.\n * You must call `registration.showNotification` or equivalent to show the notification on web/mobile\n */\n onPushNotificationReceived: (\n notification: Types.INotification,\n ) => void | Promise<void>;\n\n /**\n * Must handle when a push notification is clicked.\n * You must call `event.notification.close();` or equivalent for closing and opening notification in a new window.\n */\n onPushNotificationClicked: (\n event: NotificationEvent,\n notification?: Types.INotification,\n ) => void;\n\n /**\n * determine the config used for push notification services\n */\n platform: 'extension' | 'mobile';\n};\n\n/**\n * Manages push notifications for the application, including enabling, disabling, and updating triggers for push notifications.\n * This controller integrates with Firebase Cloud Messaging (FCM) to handle the registration and management of push notifications.\n * It is responsible for registering and unregistering the service worker that listens for push notifications,\n * managing the FCM token, and communicating with the server to register or unregister the device for push notifications.\n * Additionally, it provides functionality to update the server with new UUIDs that should trigger push notifications.\n *\n * @augments {BaseController<typeof controllerName, NotificationServicesPushControllerState, NotificationServicesPushControllerMessenger>}\n */\nexport default class NotificationServicesPushController extends BaseController<\n typeof controllerName,\n NotificationServicesPushControllerState,\n NotificationServicesPushControllerMessenger\n> {\n #pushListenerUnsubscribe: (() => void) | undefined = undefined;\n\n #env: PushNotificationEnv;\n\n #config: ControllerConfig;\n\n constructor({\n messenger,\n state,\n env,\n config,\n }: {\n messenger: NotificationServicesPushControllerMessenger;\n state: NotificationServicesPushControllerState;\n env: PushNotificationEnv;\n config: ControllerConfig;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#env = env;\n this.#config = config;\n\n this.#registerMessageHandlers();\n }\n\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:enablePushNotifications',\n this.enablePushNotifications.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:disablePushNotifications',\n this.disablePushNotifications.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:updateTriggerPushNotifications',\n this.updateTriggerPushNotifications.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:subscribeToPushNotifications',\n this.subscribeToPushNotifications.bind(this),\n );\n }\n\n async #getAndAssertBearerToken() {\n const bearerToken = await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n if (!bearerToken) {\n log.error(\n 'Failed to enable push notifications: BearerToken token is missing.',\n );\n throw new Error('BearerToken token is missing');\n }\n\n return bearerToken;\n }\n\n async subscribeToPushNotifications() {\n if (this.#pushListenerUnsubscribe) {\n this.#pushListenerUnsubscribe();\n this.#pushListenerUnsubscribe = undefined;\n }\n\n try {\n this.#pushListenerUnsubscribe = await listenToPushNotifications({\n env: this.#env,\n listenToPushReceived: async (n) => {\n this.messagingSystem.publish(\n 'NotificationServicesPushController:onNewNotifications',\n n,\n );\n await this.#config.onPushNotificationReceived(n);\n },\n listenToPushClicked: (e, n) => {\n if (n) {\n this.messagingSystem.publish(\n 'NotificationServicesPushController:pushNotificationClicked',\n n,\n );\n }\n\n this.#config.onPushNotificationClicked(e, n);\n },\n });\n } catch (e) {\n // Do nothing, we are silently failing if push notification registration fails\n }\n }\n\n /**\n * Enables push notifications for the application.\n *\n * This method sets up the necessary infrastructure for handling push notifications by:\n * 1. Registering the service worker to listen for messages.\n * 2. Fetching the Firebase Cloud Messaging (FCM) token from Firebase.\n * 3. Sending the FCM token to the server responsible for sending notifications, to register the device.\n *\n * @param UUIDs - An array of UUIDs to enable push notifications for.\n * @param fcmToken - The optional FCM token to use for push notifications.\n */\n async enablePushNotifications(UUIDs: string[], fcmToken?: string) {\n if (!this.#config.isPushEnabled) {\n return;\n }\n\n // Handle creating new reg token (if available)\n try {\n const bearerToken = await this.#getAndAssertBearerToken().catch(\n () => null,\n );\n\n // If there is a bearer token, lets try to refresh/create new reg token\n if (bearerToken) {\n // Activate Push Notifications\n const regToken = await activatePushNotifications({\n bearerToken,\n triggers: UUIDs,\n env: this.#env,\n fcmToken,\n createRegToken,\n platform: this.#config.platform,\n }).catch(() => null);\n\n if (regToken) {\n this.update((state) => {\n state.fcmToken = regToken;\n });\n }\n }\n } catch {\n // Do nothing, we are silently failing\n }\n\n // New token created, (re)subscribe to push notifications\n await this.subscribeToPushNotifications();\n }\n\n /**\n * Disables push notifications for the application.\n * This method handles the process of disabling push notifications by:\n * 1. Unregistering the service worker to stop listening for messages.\n * 2. Sending a request to the server to unregister the device using the FCM token.\n * 3. Removing the FCM token from the state to complete the process.\n *\n * @param UUIDs - An array of UUIDs for which push notifications should be disabled.\n */\n async disablePushNotifications(UUIDs: string[]) {\n if (!this.#config.isPushEnabled) {\n return;\n }\n\n const bearerToken = await this.#getAndAssertBearerToken();\n let isPushNotificationsDisabled: boolean;\n\n try {\n // Send a request to the server to unregister the token/device\n isPushNotificationsDisabled = await deactivatePushNotifications({\n bearerToken,\n triggers: UUIDs,\n env: this.#env,\n deleteRegToken,\n regToken: this.state.fcmToken,\n });\n } catch (error) {\n const errorMessage = `Failed to disable push notifications: ${\n error as string\n }`;\n log.error(errorMessage);\n throw new Error(errorMessage);\n }\n\n // Remove the FCM token from the state\n if (!isPushNotificationsDisabled) {\n return;\n }\n\n // Unsubscribe from push notifications\n this.#pushListenerUnsubscribe?.();\n\n // Update State\n if (isPushNotificationsDisabled) {\n this.update((state) => {\n state.fcmToken = '';\n });\n }\n }\n\n /**\n * Updates the triggers for push notifications.\n * This method is responsible for updating the server with the new set of UUIDs that should trigger push notifications.\n * It uses the current FCM token and a BearerToken for authentication.\n *\n * @param UUIDs - An array of UUIDs that should trigger push notifications.\n */\n async updateTriggerPushNotifications(UUIDs: string[]) {\n if (!this.#config.isPushEnabled) {\n return;\n }\n\n const bearerToken = await this.#getAndAssertBearerToken();\n\n try {\n const { fcmToken } = await updateTriggerPushNotifications({\n bearerToken,\n triggers: UUIDs,\n env: this.#env,\n createRegToken,\n deleteRegToken,\n platform: this.#config.platform,\n regToken: this.state.fcmToken,\n });\n\n // update the state with the new FCM token\n if (fcmToken) {\n this.update((state) => {\n state.fcmToken = fcmToken;\n });\n }\n } catch (error) {\n const errorMessage = `Failed to update triggers for push notifications: ${\n error as string\n }`;\n log.error(errorMessage);\n throw new Error(errorMessage);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"NotificationServicesPushController.mjs","sourceRoot":"","sources":["../../src/NotificationServicesPushController/NotificationServicesPushController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAMA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAE3D,OAAO,IAAG,iBAAiB;;AAE3B,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,qCAAiC;AAC1E,OAAO,EACL,yBAAyB,EACzB,2BAA2B,EAC3B,yBAAyB,EACzB,8BAA8B,EAC/B,gCAA4B;AAI7B,MAAM,cAAc,GAAG,oCAAoC,CAAC;AAuE5D,MAAM,CAAC,MAAM,YAAY,GAA4C;IACnE,QAAQ,EAAE,EAAE;CACb,CAAC;AACF,MAAM,QAAQ,GAA2D;IACvE,QAAQ,EAAE;QACR,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;KAChB;CACF,CAAC;AAgCF;;;;;;GAMG;AACH,MAAqB,kCAAmC,SAAQ,cAI/D;IAOC,YAAY,EACV,SAAS,EACT,KAAK,EACL,GAAG,EACH,MAAM,GAMP;QACC,KAAK,CAA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ACJ;SACF;QAAC,OAAO,KAAK,EAAE;YACd,MAAM,YAAY,GAAG,qDACnB,KACF,EAAE,CAAC;YACH,GAAG,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;YACxB,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;SAC/B;IACH,CAAC;CACF;;IAzMG,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,4DAA4D,EAC5D,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,IAAI,CAAC,CACxC,CAAC;IACF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,6DAA6D,EAC7D,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,IAAI,CAAC,CACzC,CAAC;IACF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,mEAAmE,EACnE,IAAI,CAAC,8BAA8B,CAAC,IAAI,CAAC,IAAI,CAAC,CAC/C,CAAC;IACF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,iEAAiE,EACjE,IAAI,CAAC,4BAA4B,CAAC,IAAI,CAAC,IAAI,CAAC,CAC7C,CAAC;AACJ,CAAC,gEAED,KAAK;IACH,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CACjD,yCAAyC,CAC1C,CAAC;IACF,IAAI,CAAC,WAAW,EAAE;QAChB,GAAG,CAAC,KAAK,CACP,oEAAoE,CACrE,CAAC;QACF,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;KACjD;IAED,OAAO,WAAW,CAAC;AACrB,CAAC;eAlEkB,kCAAkC","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport log from 'loglevel';\n\nimport { createRegToken, deleteRegToken } from './services/push/push-web';\nimport {\n activatePushNotifications,\n deactivatePushNotifications,\n listenToPushNotifications,\n updateTriggerPushNotifications,\n} from './services/services';\nimport type { PushNotificationEnv } from './types';\nimport type { Types } from '../NotificationServicesController';\n\nconst controllerName = 'NotificationServicesPushController';\n\nexport type NotificationServicesPushControllerState = {\n fcmToken: string;\n};\n\nexport type NotificationServicesPushControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n NotificationServicesPushControllerState\n >;\n\nexport type NotificationServicesPushControllerEnablePushNotificationsAction = {\n type: `${typeof controllerName}:enablePushNotifications`;\n handler: NotificationServicesPushController['enablePushNotifications'];\n};\nexport type NotificationServicesPushControllerDisablePushNotificationsAction = {\n type: `${typeof controllerName}:disablePushNotifications`;\n handler: NotificationServicesPushController['disablePushNotifications'];\n};\nexport type NotificationServicesPushControllerUpdateTriggerPushNotificationsAction =\n {\n type: `${typeof controllerName}:updateTriggerPushNotifications`;\n handler: NotificationServicesPushController['updateTriggerPushNotifications'];\n };\nexport type NotificationServicesPushControllerSubscribeToNotificationsAction = {\n type: `${typeof controllerName}:subscribeToPushNotifications`;\n handler: NotificationServicesPushController['subscribeToPushNotifications'];\n};\n\nexport type Actions =\n | NotificationServicesPushControllerGetStateAction\n | NotificationServicesPushControllerEnablePushNotificationsAction\n | NotificationServicesPushControllerDisablePushNotificationsAction\n | NotificationServicesPushControllerUpdateTriggerPushNotificationsAction\n | NotificationServicesPushControllerSubscribeToNotificationsAction;\n\nexport type AllowedActions =\n AuthenticationController.AuthenticationControllerGetBearerToken;\n\nexport type NotificationServicesPushControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n NotificationServicesPushControllerState\n >;\n\nexport type NotificationServicesPushControllerOnNewNotificationEvent = {\n type: `${typeof controllerName}:onNewNotifications`;\n payload: [Types.INotification];\n};\n\nexport type NotificationServicesPushControllerPushNotificationClickedEvent = {\n type: `${typeof controllerName}:pushNotificationClicked`;\n payload: [Types.INotification];\n};\n\nexport type Events =\n | NotificationServicesPushControllerStateChangeEvent\n | NotificationServicesPushControllerOnNewNotificationEvent\n | NotificationServicesPushControllerPushNotificationClickedEvent;\n\nexport type AllowedEvents = never;\n\nexport type NotificationServicesPushControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\nexport const defaultState: NotificationServicesPushControllerState = {\n fcmToken: '',\n};\nconst metadata: StateMetadata<NotificationServicesPushControllerState> = {\n fcmToken: {\n persist: true,\n anonymous: true,\n },\n};\n\ntype ControllerConfig = {\n /**\n * Config to turn on/off push notifications.\n * This is currently linked to MV3 builds on extension.\n */\n isPushEnabled: boolean;\n\n /**\n * Must handle when a push notification is received.\n * You must call `registration.showNotification` or equivalent to show the notification on web/mobile\n */\n onPushNotificationReceived: (\n notification: Types.INotification,\n ) => void | Promise<void>;\n\n /**\n * Must handle when a push notification is clicked.\n * You must call `event.notification.close();` or equivalent for closing and opening notification in a new window.\n */\n onPushNotificationClicked: (\n event: NotificationEvent,\n notification?: Types.INotification,\n ) => void;\n\n /**\n * determine the config used for push notification services\n */\n platform: 'extension' | 'mobile';\n};\n\n/**\n * Manages push notifications for the application, including enabling, disabling, and updating triggers for push notifications.\n * This controller integrates with Firebase Cloud Messaging (FCM) to handle the registration and management of push notifications.\n * It is responsible for registering and unregistering the service worker that listens for push notifications,\n * managing the FCM token, and communicating with the server to register or unregister the device for push notifications.\n * Additionally, it provides functionality to update the server with new UUIDs that should trigger push notifications.\n */\nexport default class NotificationServicesPushController extends BaseController<\n typeof controllerName,\n NotificationServicesPushControllerState,\n NotificationServicesPushControllerMessenger\n> {\n #pushListenerUnsubscribe: (() => void) | undefined = undefined;\n\n readonly #env: PushNotificationEnv;\n\n readonly #config: ControllerConfig;\n\n constructor({\n messenger,\n state,\n env,\n config,\n }: {\n messenger: NotificationServicesPushControllerMessenger;\n state: NotificationServicesPushControllerState;\n env: PushNotificationEnv;\n config: ControllerConfig;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#env = env;\n this.#config = config;\n\n this.#registerMessageHandlers();\n }\n\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:enablePushNotifications',\n this.enablePushNotifications.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:disablePushNotifications',\n this.disablePushNotifications.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:updateTriggerPushNotifications',\n this.updateTriggerPushNotifications.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:subscribeToPushNotifications',\n this.subscribeToPushNotifications.bind(this),\n );\n }\n\n async #getAndAssertBearerToken() {\n const bearerToken = await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n if (!bearerToken) {\n log.error(\n 'Failed to enable push notifications: BearerToken token is missing.',\n );\n throw new Error('BearerToken token is missing');\n }\n\n return bearerToken;\n }\n\n async subscribeToPushNotifications() {\n if (this.#pushListenerUnsubscribe) {\n this.#pushListenerUnsubscribe();\n this.#pushListenerUnsubscribe = undefined;\n }\n\n try {\n this.#pushListenerUnsubscribe = await listenToPushNotifications({\n env: this.#env,\n listenToPushReceived: async (n) => {\n this.messagingSystem.publish(\n 'NotificationServicesPushController:onNewNotifications',\n n,\n );\n await this.#config.onPushNotificationReceived(n);\n },\n listenToPushClicked: (e, n) => {\n if (n) {\n this.messagingSystem.publish(\n 'NotificationServicesPushController:pushNotificationClicked',\n n,\n );\n }\n\n this.#config.onPushNotificationClicked(e, n);\n },\n });\n } catch {\n // Do nothing, we are silently failing if push notification registration fails\n }\n }\n\n /**\n * Enables push notifications for the application.\n *\n * This method sets up the necessary infrastructure for handling push notifications by:\n * 1. Registering the service worker to listen for messages.\n * 2. Fetching the Firebase Cloud Messaging (FCM) token from Firebase.\n * 3. Sending the FCM token to the server responsible for sending notifications, to register the device.\n *\n * @param UUIDs - An array of UUIDs to enable push notifications for.\n * @param fcmToken - The optional FCM token to use for push notifications.\n */\n async enablePushNotifications(UUIDs: string[], fcmToken?: string) {\n if (!this.#config.isPushEnabled) {\n return;\n }\n\n // Handle creating new reg token (if available)\n try {\n const bearerToken = await this.#getAndAssertBearerToken().catch(\n () => null,\n );\n\n // If there is a bearer token, lets try to refresh/create new reg token\n if (bearerToken) {\n // Activate Push Notifications\n const regToken = await activatePushNotifications({\n bearerToken,\n triggers: UUIDs,\n env: this.#env,\n fcmToken,\n createRegToken,\n platform: this.#config.platform,\n }).catch(() => null);\n\n if (regToken) {\n this.update((state) => {\n state.fcmToken = regToken;\n });\n }\n }\n } catch {\n // Do nothing, we are silently failing\n }\n\n // New token created, (re)subscribe to push notifications\n await this.subscribeToPushNotifications();\n }\n\n /**\n * Disables push notifications for the application.\n * This method handles the process of disabling push notifications by:\n * 1. Unregistering the service worker to stop listening for messages.\n * 2. Sending a request to the server to unregister the device using the FCM token.\n * 3. Removing the FCM token from the state to complete the process.\n *\n * @param UUIDs - An array of UUIDs for which push notifications should be disabled.\n */\n async disablePushNotifications(UUIDs: string[]) {\n if (!this.#config.isPushEnabled) {\n return;\n }\n\n const bearerToken = await this.#getAndAssertBearerToken();\n let isPushNotificationsDisabled: boolean;\n\n try {\n // Send a request to the server to unregister the token/device\n isPushNotificationsDisabled = await deactivatePushNotifications({\n bearerToken,\n triggers: UUIDs,\n env: this.#env,\n deleteRegToken,\n regToken: this.state.fcmToken,\n });\n } catch (error) {\n const errorMessage = `Failed to disable push notifications: ${\n error as string\n }`;\n log.error(errorMessage);\n throw new Error(errorMessage);\n }\n\n // Remove the FCM token from the state\n if (!isPushNotificationsDisabled) {\n return;\n }\n\n // Unsubscribe from push notifications\n this.#pushListenerUnsubscribe?.();\n\n // Update State\n if (isPushNotificationsDisabled) {\n this.update((state) => {\n state.fcmToken = '';\n });\n }\n }\n\n /**\n * Updates the triggers for push notifications.\n * This method is responsible for updating the server with the new set of UUIDs that should trigger push notifications.\n * It uses the current FCM token and a BearerToken for authentication.\n *\n * @param UUIDs - An array of UUIDs that should trigger push notifications.\n */\n async updateTriggerPushNotifications(UUIDs: string[]) {\n if (!this.#config.isPushEnabled) {\n return;\n }\n\n const bearerToken = await this.#getAndAssertBearerToken();\n\n try {\n const { fcmToken } = await updateTriggerPushNotifications({\n bearerToken,\n triggers: UUIDs,\n env: this.#env,\n createRegToken,\n deleteRegToken,\n platform: this.#config.platform,\n regToken: this.state.fcmToken,\n });\n\n // update the state with the new FCM token\n if (fcmToken) {\n this.update((state) => {\n state.fcmToken = fcmToken;\n });\n }\n } catch (error) {\n const errorMessage = `Failed to update triggers for push notifications: ${\n error as string\n }`;\n log.error(errorMessage);\n throw new Error(errorMessage);\n }\n }\n}\n"]}
@@ -4,9 +4,7 @@ exports.getMockDeleteFCMRegistrationTokenResponse = exports.getMockCreateFCMRegi
4
4
  const endpoints_1 = require("../services/endpoints.cjs");
5
5
  exports.MOCK_REG_TOKEN = 'REG_TOKEN';
6
6
  exports.MOCK_LINKS_RESPONSE = {
7
- // eslint-disable-next-line @typescript-eslint/naming-convention
8
7
  trigger_ids: ['1', '2', '3'],
9
- // eslint-disable-next-line @typescript-eslint/naming-convention
10
8
  registration_tokens: [
11
9
  { token: 'reg_token_1', platform: 'portfolio' },
12
10
  { token: 'reg_token_2', platform: 'extension' },
@@ -1 +1 @@
1
- {"version":3,"file":"mockResponse.cjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/__fixtures__/mockResponse.ts"],"names":[],"mappings":";;;AAAA,yDAAqE;AASxD,QAAA,cAAc,GAAG,WAAW,CAAC;AAC7B,QAAA,mBAAmB,GAAgB;IAC9C,gEAAgE;IAChE,WAAW,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC;IAC5B,gEAAgE;IAChE,mBAAmB,EAAE;QACnB,EAAE,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE;QAC/C,EAAE,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE;KAChD;CACF,CAAC;AAEK,MAAM,4CAA4C,GAAG,GAAG,EAAE;IAC/D,OAAO;QACL,GAAG,EAAE,wCAA4B;QACjC,aAAa,EAAE,KAAK;QACpB,QAAQ,EAAE,2BAAmB;KACP,CAAC;AAC3B,CAAC,CAAC;AANW,QAAA,4CAA4C,gDAMvD;AAEK,MAAM,0CAA0C,GAAG,GAAG,EAAE;IAC7D,OAAO;QACL,GAAG,EAAE,wCAA4B;QACjC,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,IAAI;KACQ,CAAC;AAC3B,CAAC,CAAC;AANW,QAAA,0CAA0C,8CAMrD;AAEW,QAAA,iBAAiB,GAAG;IAC/B,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,WAAW;IAClB,GAAG,EAAE;QACH,QAAQ,EAAE,EAAE;QACZ,MAAM,EAAE,EAAE;QACV,IAAI,EAAE,EAAE;QACR,iBAAiB,EAAE,EAAE;KACtB;CACF,CAAC;AAEK,MAAM,yCAAyC,GAAG,GAAG,EAAE;IAC5D,OAAO;QACL,GAAG,EAAE,kEAAkE;QACvE,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,yBAAiB;KACL,CAAC;AAC3B,CAAC,CAAC;AANW,QAAA,yCAAyC,6CAMpD;AAEK,MAAM,yCAAyC,GAAG,GAAG,EAAE;IAC5D,OAAO;QACL,GAAG,EAAE,kEAAkE;QACvE,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,EAAE;KACU,CAAC;AAC3B,CAAC,CAAC;AANW,QAAA,yCAAyC,6CAMpD","sourcesContent":["import { REGISTRATION_TOKENS_ENDPOINT } from '../services/endpoints';\nimport type { LinksResult } from '../services/services';\n\ntype MockResponse = {\n url: string | RegExp;\n requestMethod: 'GET' | 'POST' | 'PUT';\n response: unknown;\n};\n\nexport const MOCK_REG_TOKEN = 'REG_TOKEN';\nexport const MOCK_LINKS_RESPONSE: LinksResult = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n trigger_ids: ['1', '2', '3'],\n // eslint-disable-next-line @typescript-eslint/naming-convention\n registration_tokens: [\n { token: 'reg_token_1', platform: 'portfolio' },\n { token: 'reg_token_2', platform: 'extension' },\n ],\n};\n\nexport const getMockRetrievePushNotificationLinksResponse = () => {\n return {\n url: REGISTRATION_TOKENS_ENDPOINT,\n requestMethod: 'GET',\n response: MOCK_LINKS_RESPONSE,\n } satisfies MockResponse;\n};\n\nexport const getMockUpdatePushNotificationLinksResponse = () => {\n return {\n url: REGISTRATION_TOKENS_ENDPOINT,\n requestMethod: 'POST',\n response: null,\n } satisfies MockResponse;\n};\n\nexport const MOCK_FCM_RESPONSE = {\n name: '',\n token: 'fcm-token',\n web: {\n endpoint: '',\n p256dh: '',\n auth: '',\n applicationPubKey: '',\n },\n};\n\nexport const getMockCreateFCMRegistrationTokenResponse = () => {\n return {\n url: /^https:\\/\\/fcmregistrations\\.googleapis\\.com\\/v1\\/projects\\/.*$/u,\n requestMethod: 'POST',\n response: MOCK_FCM_RESPONSE,\n } satisfies MockResponse;\n};\n\nexport const getMockDeleteFCMRegistrationTokenResponse = () => {\n return {\n url: /^https:\\/\\/fcmregistrations\\.googleapis\\.com\\/v1\\/projects\\/.*$/u,\n requestMethod: 'POST',\n response: {},\n } satisfies MockResponse;\n};\n"]}
1
+ {"version":3,"file":"mockResponse.cjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/__fixtures__/mockResponse.ts"],"names":[],"mappings":";;;AAAA,yDAAqE;AASxD,QAAA,cAAc,GAAG,WAAW,CAAC;AAC7B,QAAA,mBAAmB,GAAgB;IAC9C,WAAW,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC;IAC5B,mBAAmB,EAAE;QACnB,EAAE,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE;QAC/C,EAAE,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE;KAChD;CACF,CAAC;AAEK,MAAM,4CAA4C,GAAG,GAAG,EAAE;IAC/D,OAAO;QACL,GAAG,EAAE,wCAA4B;QACjC,aAAa,EAAE,KAAK;QACpB,QAAQ,EAAE,2BAAmB;KACP,CAAC;AAC3B,CAAC,CAAC;AANW,QAAA,4CAA4C,gDAMvD;AAEK,MAAM,0CAA0C,GAAG,GAAG,EAAE;IAC7D,OAAO;QACL,GAAG,EAAE,wCAA4B;QACjC,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,IAAI;KACQ,CAAC;AAC3B,CAAC,CAAC;AANW,QAAA,0CAA0C,8CAMrD;AAEW,QAAA,iBAAiB,GAAG;IAC/B,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,WAAW;IAClB,GAAG,EAAE;QACH,QAAQ,EAAE,EAAE;QACZ,MAAM,EAAE,EAAE;QACV,IAAI,EAAE,EAAE;QACR,iBAAiB,EAAE,EAAE;KACtB;CACF,CAAC;AAEK,MAAM,yCAAyC,GAAG,GAAG,EAAE;IAC5D,OAAO;QACL,GAAG,EAAE,kEAAkE;QACvE,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,yBAAiB;KACL,CAAC;AAC3B,CAAC,CAAC;AANW,QAAA,yCAAyC,6CAMpD;AAEK,MAAM,yCAAyC,GAAG,GAAG,EAAE;IAC5D,OAAO;QACL,GAAG,EAAE,kEAAkE;QACvE,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,EAAE;KACU,CAAC;AAC3B,CAAC,CAAC;AANW,QAAA,yCAAyC,6CAMpD","sourcesContent":["import { REGISTRATION_TOKENS_ENDPOINT } from '../services/endpoints';\nimport type { LinksResult } from '../services/services';\n\ntype MockResponse = {\n url: string | RegExp;\n requestMethod: 'GET' | 'POST' | 'PUT';\n response: unknown;\n};\n\nexport const MOCK_REG_TOKEN = 'REG_TOKEN';\nexport const MOCK_LINKS_RESPONSE: LinksResult = {\n trigger_ids: ['1', '2', '3'],\n registration_tokens: [\n { token: 'reg_token_1', platform: 'portfolio' },\n { token: 'reg_token_2', platform: 'extension' },\n ],\n};\n\nexport const getMockRetrievePushNotificationLinksResponse = () => {\n return {\n url: REGISTRATION_TOKENS_ENDPOINT,\n requestMethod: 'GET',\n response: MOCK_LINKS_RESPONSE,\n } satisfies MockResponse;\n};\n\nexport const getMockUpdatePushNotificationLinksResponse = () => {\n return {\n url: REGISTRATION_TOKENS_ENDPOINT,\n requestMethod: 'POST',\n response: null,\n } satisfies MockResponse;\n};\n\nexport const MOCK_FCM_RESPONSE = {\n name: '',\n token: 'fcm-token',\n web: {\n endpoint: '',\n p256dh: '',\n auth: '',\n applicationPubKey: '',\n },\n};\n\nexport const getMockCreateFCMRegistrationTokenResponse = () => {\n return {\n url: /^https:\\/\\/fcmregistrations\\.googleapis\\.com\\/v1\\/projects\\/.*$/u,\n requestMethod: 'POST',\n response: MOCK_FCM_RESPONSE,\n } satisfies MockResponse;\n};\n\nexport const getMockDeleteFCMRegistrationTokenResponse = () => {\n return {\n url: /^https:\\/\\/fcmregistrations\\.googleapis\\.com\\/v1\\/projects\\/.*$/u,\n requestMethod: 'POST',\n response: {},\n } satisfies MockResponse;\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"mockResponse.d.cts","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/__fixtures__/mockResponse.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,iCAA6B;AAQxD,eAAO,MAAM,cAAc,cAAc,CAAC;AAC1C,eAAO,MAAM,mBAAmB,EAAE,WAQjC,CAAC;AAEF,eAAO,MAAM,4CAA4C;;;;CAMxD,CAAC;AAEF,eAAO,MAAM,0CAA0C;;;;CAMtD,CAAC;AAEF,eAAO,MAAM,iBAAiB;;;;;;;;;CAS7B,CAAC;AAEF,eAAO,MAAM,yCAAyC;;;;;;;;;;;;;CAMrD,CAAC;AAEF,eAAO,MAAM,yCAAyC;;;;CAMrD,CAAC"}
1
+ {"version":3,"file":"mockResponse.d.cts","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/__fixtures__/mockResponse.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,iCAA6B;AAQxD,eAAO,MAAM,cAAc,cAAc,CAAC;AAC1C,eAAO,MAAM,mBAAmB,EAAE,WAMjC,CAAC;AAEF,eAAO,MAAM,4CAA4C;;;;CAMxD,CAAC;AAEF,eAAO,MAAM,0CAA0C;;;;CAMtD,CAAC;AAEF,eAAO,MAAM,iBAAiB;;;;;;;;;CAS7B,CAAC;AAEF,eAAO,MAAM,yCAAyC;;;;;;;;;;;;;CAMrD,CAAC;AAEF,eAAO,MAAM,yCAAyC;;;;CAMrD,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"mockResponse.d.mts","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/__fixtures__/mockResponse.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,iCAA6B;AAQxD,eAAO,MAAM,cAAc,cAAc,CAAC;AAC1C,eAAO,MAAM,mBAAmB,EAAE,WAQjC,CAAC;AAEF,eAAO,MAAM,4CAA4C;;;;CAMxD,CAAC;AAEF,eAAO,MAAM,0CAA0C;;;;CAMtD,CAAC;AAEF,eAAO,MAAM,iBAAiB;;;;;;;;;CAS7B,CAAC;AAEF,eAAO,MAAM,yCAAyC;;;;;;;;;;;;;CAMrD,CAAC;AAEF,eAAO,MAAM,yCAAyC;;;;CAMrD,CAAC"}
1
+ {"version":3,"file":"mockResponse.d.mts","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/__fixtures__/mockResponse.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,iCAA6B;AAQxD,eAAO,MAAM,cAAc,cAAc,CAAC;AAC1C,eAAO,MAAM,mBAAmB,EAAE,WAMjC,CAAC;AAEF,eAAO,MAAM,4CAA4C;;;;CAMxD,CAAC;AAEF,eAAO,MAAM,0CAA0C;;;;CAMtD,CAAC;AAEF,eAAO,MAAM,iBAAiB;;;;;;;;;CAS7B,CAAC;AAEF,eAAO,MAAM,yCAAyC;;;;;;;;;;;;;CAMrD,CAAC;AAEF,eAAO,MAAM,yCAAyC;;;;CAMrD,CAAC"}
@@ -1,9 +1,7 @@
1
1
  import { REGISTRATION_TOKENS_ENDPOINT } from "../services/endpoints.mjs";
2
2
  export const MOCK_REG_TOKEN = 'REG_TOKEN';
3
3
  export const MOCK_LINKS_RESPONSE = {
4
- // eslint-disable-next-line @typescript-eslint/naming-convention
5
4
  trigger_ids: ['1', '2', '3'],
6
- // eslint-disable-next-line @typescript-eslint/naming-convention
7
5
  registration_tokens: [
8
6
  { token: 'reg_token_1', platform: 'portfolio' },
9
7
  { token: 'reg_token_2', platform: 'extension' },
@@ -1 +1 @@
1
- {"version":3,"file":"mockResponse.mjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/__fixtures__/mockResponse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAE,kCAA8B;AASrE,MAAM,CAAC,MAAM,cAAc,GAAG,WAAW,CAAC;AAC1C,MAAM,CAAC,MAAM,mBAAmB,GAAgB;IAC9C,gEAAgE;IAChE,WAAW,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC;IAC5B,gEAAgE;IAChE,mBAAmB,EAAE;QACnB,EAAE,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE;QAC/C,EAAE,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE;KAChD;CACF,CAAC;AAEF,MAAM,CAAC,MAAM,4CAA4C,GAAG,GAAG,EAAE;IAC/D,OAAO;QACL,GAAG,EAAE,4BAA4B;QACjC,aAAa,EAAE,KAAK;QACpB,QAAQ,EAAE,mBAAmB;KACP,CAAC;AAC3B,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,0CAA0C,GAAG,GAAG,EAAE;IAC7D,OAAO;QACL,GAAG,EAAE,4BAA4B;QACjC,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,IAAI;KACQ,CAAC;AAC3B,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAC/B,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,WAAW;IAClB,GAAG,EAAE;QACH,QAAQ,EAAE,EAAE;QACZ,MAAM,EAAE,EAAE;QACV,IAAI,EAAE,EAAE;QACR,iBAAiB,EAAE,EAAE;KACtB;CACF,CAAC;AAEF,MAAM,CAAC,MAAM,yCAAyC,GAAG,GAAG,EAAE;IAC5D,OAAO;QACL,GAAG,EAAE,kEAAkE;QACvE,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,iBAAiB;KACL,CAAC;AAC3B,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,yCAAyC,GAAG,GAAG,EAAE;IAC5D,OAAO;QACL,GAAG,EAAE,kEAAkE;QACvE,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,EAAE;KACU,CAAC;AAC3B,CAAC,CAAC","sourcesContent":["import { REGISTRATION_TOKENS_ENDPOINT } from '../services/endpoints';\nimport type { LinksResult } from '../services/services';\n\ntype MockResponse = {\n url: string | RegExp;\n requestMethod: 'GET' | 'POST' | 'PUT';\n response: unknown;\n};\n\nexport const MOCK_REG_TOKEN = 'REG_TOKEN';\nexport const MOCK_LINKS_RESPONSE: LinksResult = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n trigger_ids: ['1', '2', '3'],\n // eslint-disable-next-line @typescript-eslint/naming-convention\n registration_tokens: [\n { token: 'reg_token_1', platform: 'portfolio' },\n { token: 'reg_token_2', platform: 'extension' },\n ],\n};\n\nexport const getMockRetrievePushNotificationLinksResponse = () => {\n return {\n url: REGISTRATION_TOKENS_ENDPOINT,\n requestMethod: 'GET',\n response: MOCK_LINKS_RESPONSE,\n } satisfies MockResponse;\n};\n\nexport const getMockUpdatePushNotificationLinksResponse = () => {\n return {\n url: REGISTRATION_TOKENS_ENDPOINT,\n requestMethod: 'POST',\n response: null,\n } satisfies MockResponse;\n};\n\nexport const MOCK_FCM_RESPONSE = {\n name: '',\n token: 'fcm-token',\n web: {\n endpoint: '',\n p256dh: '',\n auth: '',\n applicationPubKey: '',\n },\n};\n\nexport const getMockCreateFCMRegistrationTokenResponse = () => {\n return {\n url: /^https:\\/\\/fcmregistrations\\.googleapis\\.com\\/v1\\/projects\\/.*$/u,\n requestMethod: 'POST',\n response: MOCK_FCM_RESPONSE,\n } satisfies MockResponse;\n};\n\nexport const getMockDeleteFCMRegistrationTokenResponse = () => {\n return {\n url: /^https:\\/\\/fcmregistrations\\.googleapis\\.com\\/v1\\/projects\\/.*$/u,\n requestMethod: 'POST',\n response: {},\n } satisfies MockResponse;\n};\n"]}
1
+ {"version":3,"file":"mockResponse.mjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/__fixtures__/mockResponse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAE,kCAA8B;AASrE,MAAM,CAAC,MAAM,cAAc,GAAG,WAAW,CAAC;AAC1C,MAAM,CAAC,MAAM,mBAAmB,GAAgB;IAC9C,WAAW,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC;IAC5B,mBAAmB,EAAE;QACnB,EAAE,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE;QAC/C,EAAE,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE;KAChD;CACF,CAAC;AAEF,MAAM,CAAC,MAAM,4CAA4C,GAAG,GAAG,EAAE;IAC/D,OAAO;QACL,GAAG,EAAE,4BAA4B;QACjC,aAAa,EAAE,KAAK;QACpB,QAAQ,EAAE,mBAAmB;KACP,CAAC;AAC3B,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,0CAA0C,GAAG,GAAG,EAAE;IAC7D,OAAO;QACL,GAAG,EAAE,4BAA4B;QACjC,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,IAAI;KACQ,CAAC;AAC3B,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAC/B,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,WAAW;IAClB,GAAG,EAAE;QACH,QAAQ,EAAE,EAAE;QACZ,MAAM,EAAE,EAAE;QACV,IAAI,EAAE,EAAE;QACR,iBAAiB,EAAE,EAAE;KACtB;CACF,CAAC;AAEF,MAAM,CAAC,MAAM,yCAAyC,GAAG,GAAG,EAAE;IAC5D,OAAO;QACL,GAAG,EAAE,kEAAkE;QACvE,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,iBAAiB;KACL,CAAC;AAC3B,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,yCAAyC,GAAG,GAAG,EAAE;IAC5D,OAAO;QACL,GAAG,EAAE,kEAAkE;QACvE,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,EAAE;KACU,CAAC;AAC3B,CAAC,CAAC","sourcesContent":["import { REGISTRATION_TOKENS_ENDPOINT } from '../services/endpoints';\nimport type { LinksResult } from '../services/services';\n\ntype MockResponse = {\n url: string | RegExp;\n requestMethod: 'GET' | 'POST' | 'PUT';\n response: unknown;\n};\n\nexport const MOCK_REG_TOKEN = 'REG_TOKEN';\nexport const MOCK_LINKS_RESPONSE: LinksResult = {\n trigger_ids: ['1', '2', '3'],\n registration_tokens: [\n { token: 'reg_token_1', platform: 'portfolio' },\n { token: 'reg_token_2', platform: 'extension' },\n ],\n};\n\nexport const getMockRetrievePushNotificationLinksResponse = () => {\n return {\n url: REGISTRATION_TOKENS_ENDPOINT,\n requestMethod: 'GET',\n response: MOCK_LINKS_RESPONSE,\n } satisfies MockResponse;\n};\n\nexport const getMockUpdatePushNotificationLinksResponse = () => {\n return {\n url: REGISTRATION_TOKENS_ENDPOINT,\n requestMethod: 'POST',\n response: null,\n } satisfies MockResponse;\n};\n\nexport const MOCK_FCM_RESPONSE = {\n name: '',\n token: 'fcm-token',\n web: {\n endpoint: '',\n p256dh: '',\n auth: '',\n applicationPubKey: '',\n },\n};\n\nexport const getMockCreateFCMRegistrationTokenResponse = () => {\n return {\n url: /^https:\\/\\/fcmregistrations\\.googleapis\\.com\\/v1\\/projects\\/.*$/u,\n requestMethod: 'POST',\n response: MOCK_FCM_RESPONSE,\n } satisfies MockResponse;\n};\n\nexport const getMockDeleteFCMRegistrationTokenResponse = () => {\n return {\n url: /^https:\\/\\/fcmregistrations\\.googleapis\\.com\\/v1\\/projects\\/.*$/u,\n requestMethod: 'POST',\n response: {},\n } satisfies MockResponse;\n};\n"]}