@metamask-previews/notification-services-controller 0.21.0-preview-de5d7291 → 0.21.0-preview-5575cd05

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 (111) hide show
  1. package/dist/NotificationServicesController/NotificationServicesController.cjs +62 -74
  2. package/dist/NotificationServicesController/NotificationServicesController.cjs.map +1 -1
  3. package/dist/NotificationServicesController/NotificationServicesController.d.cts +10 -34
  4. package/dist/NotificationServicesController/NotificationServicesController.d.cts.map +1 -1
  5. package/dist/NotificationServicesController/NotificationServicesController.d.mts +10 -34
  6. package/dist/NotificationServicesController/NotificationServicesController.d.mts.map +1 -1
  7. package/dist/NotificationServicesController/NotificationServicesController.mjs +62 -74
  8. package/dist/NotificationServicesController/NotificationServicesController.mjs.map +1 -1
  9. package/dist/NotificationServicesController/index.cjs +1 -0
  10. package/dist/NotificationServicesController/index.cjs.map +1 -1
  11. package/dist/NotificationServicesController/index.d.cts +1 -0
  12. package/dist/NotificationServicesController/index.d.cts.map +1 -1
  13. package/dist/NotificationServicesController/index.d.mts +1 -0
  14. package/dist/NotificationServicesController/index.d.mts.map +1 -1
  15. package/dist/NotificationServicesController/index.mjs +1 -0
  16. package/dist/NotificationServicesController/index.mjs.map +1 -1
  17. package/dist/NotificationServicesPushController/NotificationServicesPushController.cjs +54 -45
  18. package/dist/NotificationServicesPushController/NotificationServicesPushController.cjs.map +1 -1
  19. package/dist/NotificationServicesPushController/NotificationServicesPushController.d.cts +16 -17
  20. package/dist/NotificationServicesPushController/NotificationServicesPushController.d.cts.map +1 -1
  21. package/dist/NotificationServicesPushController/NotificationServicesPushController.d.mts +16 -17
  22. package/dist/NotificationServicesPushController/NotificationServicesPushController.d.mts.map +1 -1
  23. package/dist/NotificationServicesPushController/NotificationServicesPushController.mjs +55 -46
  24. package/dist/NotificationServicesPushController/NotificationServicesPushController.mjs.map +1 -1
  25. package/dist/NotificationServicesPushController/__fixtures__/mockMessenger.cjs +14 -0
  26. package/dist/NotificationServicesPushController/__fixtures__/mockMessenger.cjs.map +1 -0
  27. package/dist/NotificationServicesPushController/__fixtures__/mockMessenger.d.cts +3 -0
  28. package/dist/NotificationServicesPushController/__fixtures__/mockMessenger.d.cts.map +1 -0
  29. package/dist/NotificationServicesPushController/__fixtures__/mockMessenger.d.mts +3 -0
  30. package/dist/NotificationServicesPushController/__fixtures__/mockMessenger.d.mts.map +1 -0
  31. package/dist/NotificationServicesPushController/__fixtures__/mockMessenger.mjs +10 -0
  32. package/dist/NotificationServicesPushController/__fixtures__/mockMessenger.mjs.map +1 -0
  33. package/dist/NotificationServicesPushController/services/services.cjs +3 -26
  34. package/dist/NotificationServicesPushController/services/services.cjs.map +1 -1
  35. package/dist/NotificationServicesPushController/services/services.d.cts +1 -15
  36. package/dist/NotificationServicesPushController/services/services.d.cts.map +1 -1
  37. package/dist/NotificationServicesPushController/services/services.d.mts +1 -15
  38. package/dist/NotificationServicesPushController/services/services.d.mts.map +1 -1
  39. package/dist/NotificationServicesPushController/services/services.mjs +2 -24
  40. package/dist/NotificationServicesPushController/services/services.mjs.map +1 -1
  41. package/dist/NotificationServicesPushController/types/index.cjs.map +1 -1
  42. package/dist/NotificationServicesPushController/types/index.d.cts +1 -0
  43. package/dist/NotificationServicesPushController/types/index.d.cts.map +1 -1
  44. package/dist/NotificationServicesPushController/types/index.d.mts +1 -0
  45. package/dist/NotificationServicesPushController/types/index.d.mts.map +1 -1
  46. package/dist/NotificationServicesPushController/types/index.mjs.map +1 -1
  47. package/dist/NotificationServicesPushController/{services/push/index.cjs → types/push-service-interface.cjs} +1 -1
  48. package/dist/NotificationServicesPushController/types/push-service-interface.cjs.map +1 -0
  49. package/dist/NotificationServicesPushController/types/push-service-interface.d.cts +30 -0
  50. package/dist/NotificationServicesPushController/types/push-service-interface.d.cts.map +1 -0
  51. package/dist/NotificationServicesPushController/types/push-service-interface.d.mts +30 -0
  52. package/dist/NotificationServicesPushController/types/push-service-interface.d.mts.map +1 -0
  53. package/dist/NotificationServicesPushController/types/push-service-interface.mjs +2 -0
  54. package/dist/NotificationServicesPushController/types/push-service-interface.mjs.map +1 -0
  55. package/dist/NotificationServicesPushController/utils/get-notification-message.cjs +1 -19
  56. package/dist/NotificationServicesPushController/utils/get-notification-message.cjs.map +1 -1
  57. package/dist/NotificationServicesPushController/utils/get-notification-message.d.cts +0 -7
  58. package/dist/NotificationServicesPushController/utils/get-notification-message.d.cts.map +1 -1
  59. package/dist/NotificationServicesPushController/utils/get-notification-message.d.mts +0 -7
  60. package/dist/NotificationServicesPushController/utils/get-notification-message.d.mts.map +1 -1
  61. package/dist/NotificationServicesPushController/utils/get-notification-message.mjs +0 -17
  62. package/dist/NotificationServicesPushController/utils/get-notification-message.mjs.map +1 -1
  63. package/dist/NotificationServicesPushController/web/index.cjs +8 -0
  64. package/dist/NotificationServicesPushController/web/index.cjs.map +1 -0
  65. package/dist/NotificationServicesPushController/web/index.d.cts +2 -0
  66. package/dist/NotificationServicesPushController/web/index.d.cts.map +1 -0
  67. package/dist/NotificationServicesPushController/web/index.d.mts +2 -0
  68. package/dist/NotificationServicesPushController/web/index.d.mts.map +1 -0
  69. package/dist/NotificationServicesPushController/web/index.mjs +2 -0
  70. package/dist/NotificationServicesPushController/web/index.mjs.map +1 -0
  71. package/dist/NotificationServicesPushController/web/push-utils.cjs +170 -0
  72. package/dist/NotificationServicesPushController/web/push-utils.cjs.map +1 -0
  73. package/dist/NotificationServicesPushController/web/push-utils.d.cts +37 -0
  74. package/dist/NotificationServicesPushController/web/push-utils.d.cts.map +1 -0
  75. package/dist/NotificationServicesPushController/web/push-utils.d.mts +37 -0
  76. package/dist/NotificationServicesPushController/web/push-utils.d.mts.map +1 -0
  77. package/dist/NotificationServicesPushController/web/push-utils.mjs +168 -0
  78. package/dist/NotificationServicesPushController/web/push-utils.mjs.map +1 -0
  79. package/dist/shared/index.cjs +19 -0
  80. package/dist/shared/index.cjs.map +1 -0
  81. package/dist/shared/index.d.cts +3 -0
  82. package/dist/shared/index.d.cts.map +1 -0
  83. package/dist/shared/index.d.mts +3 -0
  84. package/dist/shared/index.d.mts.map +1 -0
  85. package/dist/shared/index.mjs +3 -0
  86. package/dist/shared/index.mjs.map +1 -0
  87. package/dist/shared/is-onchain-notification.cjs +22 -0
  88. package/dist/shared/is-onchain-notification.cjs.map +1 -0
  89. package/dist/shared/is-onchain-notification.d.cts +9 -0
  90. package/dist/shared/is-onchain-notification.d.cts.map +1 -0
  91. package/dist/shared/is-onchain-notification.d.mts +9 -0
  92. package/dist/shared/is-onchain-notification.d.mts.map +1 -0
  93. package/dist/shared/is-onchain-notification.mjs +18 -0
  94. package/dist/shared/is-onchain-notification.mjs.map +1 -0
  95. package/package.json +11 -1
  96. package/push-services/web/package.json +150 -0
  97. package/dist/NotificationServicesPushController/constants.cjs +0 -14
  98. package/dist/NotificationServicesPushController/constants.cjs.map +0 -1
  99. package/dist/NotificationServicesPushController/constants.d.cts +0 -11
  100. package/dist/NotificationServicesPushController/constants.d.cts.map +0 -1
  101. package/dist/NotificationServicesPushController/constants.d.mts +0 -11
  102. package/dist/NotificationServicesPushController/constants.d.mts.map +0 -1
  103. package/dist/NotificationServicesPushController/constants.mjs +0 -11
  104. package/dist/NotificationServicesPushController/constants.mjs.map +0 -1
  105. package/dist/NotificationServicesPushController/services/push/index.cjs.map +0 -1
  106. package/dist/NotificationServicesPushController/services/push/index.d.cts +0 -6
  107. package/dist/NotificationServicesPushController/services/push/index.d.cts.map +0 -1
  108. package/dist/NotificationServicesPushController/services/push/index.d.mts +0 -6
  109. package/dist/NotificationServicesPushController/services/push/index.d.mts.map +0 -1
  110. package/dist/NotificationServicesPushController/services/push/index.mjs +0 -2
  111. package/dist/NotificationServicesPushController/services/push/index.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"get-notification-message.mjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/utils/get-notification-message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE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AAI,WAAW,GAAkB,IAAI,CAAC;IACtC,IAAI;QACF,WAAW;YACT,8DAA8D;YAC9D,mBAAmB,EAAE,cAAc,EAAE,CAAC,CAAQ,CAAC;gBAC/C,mBAAmB,CAAC,kBAAkB;gBACtC,IAAI,CAAC;KACR;IAAC,MAAM;QACN,WAAW,GAAG,mBAAmB,CAAC,kBAAkB,IAAI,IAAI,CAAC;KAC9D;IAED,OAAO;QACL,KAAK,EAAE,mBAAmB,CAAC,KAAK,IAAI,EAAE;QACtC,WAAW,EAAE,WAAW,IAAI,EAAE,EAAE,mCAAmC;KACpE,CAAC;AACJ,CAAC","sourcesContent":["import { getAmount, formatAmount } from './get-notification-data';\nimport type { Types } from '../../NotificationServicesController';\nimport { Constants } from '../../NotificationServicesController';\n\nexport type TranslationKeys = {\n pushPlatformNotificationsFundsSentTitle: () => string;\n pushPlatformNotificationsFundsSentDescriptionDefault: () => string;\n pushPlatformNotificationsFundsSentDescription: (\n ...args: [string, string]\n ) => string;\n pushPlatformNotificationsFundsReceivedTitle: () => string;\n pushPlatformNotificationsFundsReceivedDescriptionDefault: () => string;\n pushPlatformNotificationsFundsReceivedDescription: (\n ...args: [string, string]\n ) => string;\n pushPlatformNotificationsSwapCompletedTitle: () => string;\n pushPlatformNotificationsSwapCompletedDescription: () => string;\n pushPlatformNotificationsNftSentTitle: () => string;\n pushPlatformNotificationsNftSentDescription: () => string;\n pushPlatformNotificationsNftReceivedTitle: () => string;\n pushPlatformNotificationsNftReceivedDescription: () => string;\n pushPlatformNotificationsStakingRocketpoolStakeCompletedTitle: () => string;\n pushPlatformNotificationsStakingRocketpoolStakeCompletedDescription: () => string;\n pushPlatformNotificationsStakingRocketpoolUnstakeCompletedTitle: () => string;\n pushPlatformNotificationsStakingRocketpoolUnstakeCompletedDescription: () => string;\n pushPlatformNotificationsStakingLidoStakeCompletedTitle: () => string;\n pushPlatformNotificationsStakingLidoStakeCompletedDescription: () => string;\n pushPlatformNotificationsStakingLidoStakeReadyToBeWithdrawnTitle: () => string;\n pushPlatformNotificationsStakingLidoStakeReadyToBeWithdrawnDescription: () => string;\n pushPlatformNotificationsStakingLidoWithdrawalRequestedTitle: () => string;\n pushPlatformNotificationsStakingLidoWithdrawalRequestedDescription: () => string;\n pushPlatformNotificationsStakingLidoWithdrawalCompletedTitle: () => string;\n pushPlatformNotificationsStakingLidoWithdrawalCompletedDescription: () => string;\n};\n\ntype PushNotificationMessage = {\n title: string;\n description: string;\n};\n\ntype NotificationMessage<N extends Types.INotification> = {\n title: string | null;\n defaultDescription: string | null;\n getDescription?: (n: N) => string | null;\n};\n\ntype NotificationMessageDict = {\n [K in Constants.TRIGGER_TYPES]?: NotificationMessage<\n Extract<Types.INotification, { type: K }>\n >;\n};\n\n/**\n * On Chain Push Notification Messages.\n * This is a list of all the push notifications we support. Update this for synced notifications on mobile and extension\n *\n * @param translationKeys - all translations supported\n * @returns A translation push message object.\n */\nexport const createOnChainPushNotificationMessages = (\n translationKeys: TranslationKeys,\n): NotificationMessageDict => {\n type TranslationFn = <K extends keyof TranslationKeys>(\n ...args: [K, ...Parameters<TranslationKeys[K]>]\n ) => string;\n const t: TranslationFn = (...args) => {\n const [key, ...otherArgs] = args;\n\n // Coerce types for the translation function\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const fn: any = translationKeys[key];\n return fn(...otherArgs);\n };\n\n return {\n erc20_sent: {\n title: t('pushPlatformNotificationsFundsSentTitle'),\n defaultDescription: t(\n 'pushPlatformNotificationsFundsSentDescriptionDefault',\n ),\n getDescription: (n) => {\n const symbol = n?.data?.token?.symbol;\n const tokenAmount = n?.data?.token?.amount;\n const tokenDecimals = n?.data?.token?.decimals;\n if (!symbol || !tokenAmount || !tokenDecimals) {\n return null;\n }\n\n const amount = getAmount(tokenAmount, tokenDecimals, {\n shouldEllipse: true,\n });\n return t(\n 'pushPlatformNotificationsFundsSentDescription',\n amount,\n symbol,\n );\n },\n },\n eth_sent: {\n title: t('pushPlatformNotificationsFundsSentTitle'),\n defaultDescription: t(\n 'pushPlatformNotificationsFundsSentDescriptionDefault',\n ),\n getDescription: (n) => {\n const symbol = getChainSymbol(n?.chain_id);\n const tokenAmount = n?.data?.amount?.eth;\n if (!symbol || !tokenAmount) {\n return null;\n }\n\n const amount = formatAmount(parseFloat(tokenAmount), {\n shouldEllipse: true,\n });\n return t(\n 'pushPlatformNotificationsFundsSentDescription',\n amount,\n symbol,\n );\n },\n },\n erc20_received: {\n title: t('pushPlatformNotificationsFundsReceivedTitle'),\n defaultDescription: t(\n 'pushPlatformNotificationsFundsReceivedDescriptionDefault',\n ),\n getDescription: (n) => {\n const symbol = n?.data?.token?.symbol;\n const tokenAmount = n?.data?.token?.amount;\n const tokenDecimals = n?.data?.token?.decimals;\n if (!symbol || !tokenAmount || !tokenDecimals) {\n return null;\n }\n\n const amount = getAmount(tokenAmount, tokenDecimals, {\n shouldEllipse: true,\n });\n return t(\n 'pushPlatformNotificationsFundsReceivedDescription',\n amount,\n symbol,\n );\n },\n },\n eth_received: {\n title: t('pushPlatformNotificationsFundsReceivedTitle'),\n defaultDescription: t(\n 'pushPlatformNotificationsFundsReceivedDescriptionDefault',\n ),\n getDescription: (n) => {\n const symbol = getChainSymbol(n?.chain_id);\n const tokenAmount = n?.data?.amount?.eth;\n if (!symbol || !tokenAmount) {\n return null;\n }\n\n const amount = formatAmount(parseFloat(tokenAmount), {\n shouldEllipse: true,\n });\n return t(\n 'pushPlatformNotificationsFundsReceivedDescription',\n amount,\n symbol,\n );\n },\n },\n metamask_swap_completed: {\n title: t('pushPlatformNotificationsSwapCompletedTitle'),\n defaultDescription: t(\n 'pushPlatformNotificationsSwapCompletedDescription',\n ),\n },\n erc721_sent: {\n title: t('pushPlatformNotificationsNftSentTitle'),\n defaultDescription: t('pushPlatformNotificationsNftSentDescription'),\n },\n erc1155_sent: {\n title: t('pushPlatformNotificationsNftSentTitle'),\n defaultDescription: t('pushPlatformNotificationsNftSentDescription'),\n },\n erc721_received: {\n title: t('pushPlatformNotificationsNftReceivedTitle'),\n defaultDescription: t('pushPlatformNotificationsNftReceivedDescription'),\n },\n erc1155_received: {\n title: t('pushPlatformNotificationsNftReceivedTitle'),\n defaultDescription: t('pushPlatformNotificationsNftReceivedDescription'),\n },\n rocketpool_stake_completed: {\n title: t('pushPlatformNotificationsStakingRocketpoolStakeCompletedTitle'),\n defaultDescription: t(\n 'pushPlatformNotificationsStakingRocketpoolStakeCompletedDescription',\n ),\n },\n rocketpool_unstake_completed: {\n title: t(\n 'pushPlatformNotificationsStakingRocketpoolUnstakeCompletedTitle',\n ),\n defaultDescription: t(\n 'pushPlatformNotificationsStakingRocketpoolUnstakeCompletedDescription',\n ),\n },\n lido_stake_completed: {\n title: t('pushPlatformNotificationsStakingLidoStakeCompletedTitle'),\n defaultDescription: t(\n 'pushPlatformNotificationsStakingLidoStakeCompletedDescription',\n ),\n },\n lido_stake_ready_to_be_withdrawn: {\n title: t(\n 'pushPlatformNotificationsStakingLidoStakeReadyToBeWithdrawnTitle',\n ),\n defaultDescription: t(\n 'pushPlatformNotificationsStakingLidoStakeReadyToBeWithdrawnDescription',\n ),\n },\n lido_withdrawal_requested: {\n title: t('pushPlatformNotificationsStakingLidoWithdrawalRequestedTitle'),\n defaultDescription: t(\n 'pushPlatformNotificationsStakingLidoWithdrawalRequestedDescription',\n ),\n },\n lido_withdrawal_completed: {\n title: t('pushPlatformNotificationsStakingLidoWithdrawalCompletedTitle'),\n defaultDescription: t(\n 'pushPlatformNotificationsStakingLidoWithdrawalCompletedDescription',\n ),\n },\n };\n};\n\n/**\n * Retrieves the symbol associated with a given chain ID.\n *\n * @param chainId - The ID of the chain.\n * @returns The symbol associated with the chain ID, or null if not found.\n */\nfunction getChainSymbol(chainId: number) {\n return Constants.CHAIN_SYMBOLS[chainId] ?? null;\n}\n\n/**\n * Checks if the given value is an OnChainRawNotification object.\n *\n * @param n - The value to check.\n * @returns True if the value is an OnChainRawNotification object, false otherwise.\n */\nexport function isOnChainNotification(\n n: unknown,\n): n is Types.OnChainRawNotification {\n const assumed = n as Types.OnChainRawNotification;\n\n // We don't have a validation/parsing library to check all possible types of an on chain notification\n // It is safe enough just to check \"some\" fields, and catch any errors down the line if the shape is bad.\n const isValidEnoughToBeOnChainNotification = [\n assumed?.id,\n assumed?.data,\n assumed?.trigger_id,\n ].every((field) => field !== undefined);\n return isValidEnoughToBeOnChainNotification;\n}\n\n/**\n * Creates a push notification message based on the given on-chain raw notification.\n *\n * @param n - processed notification.\n * @param translations - translates keys into text\n * @returns The push notification message object, or null if the notification is invalid.\n */\nexport function createOnChainPushNotificationMessage(\n n: Types.INotification,\n translations: TranslationKeys,\n): PushNotificationMessage | null {\n if (!n?.type) {\n return null;\n }\n const notificationMessage =\n createOnChainPushNotificationMessages(translations)[n.type];\n\n if (!notificationMessage) {\n return null;\n }\n\n let description: string | null = null;\n try {\n description =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n notificationMessage?.getDescription?.(n as any) ??\n notificationMessage.defaultDescription ??\n null;\n } catch {\n description = notificationMessage.defaultDescription ?? null;\n }\n\n return {\n title: notificationMessage.title ?? '', // Ensure title is always a string\n description: description ?? '', // Fallback to empty string if null\n };\n}\n"]}
1
+ {"version":3,"file":"get-notification-message.mjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/utils/get-notification-message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,oCAAgC;AAElE,OAAO,EAAE,SAAS,EAAE,uDAA6C;AAkDjE;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,qCAAqC,GAAG,CACnD,eAAgC,EACP,EAAE;IAI3B,MAAM,CAAC,GAAkB,CAAC,GAAG,IAAI,EAAE,EAAE;QACnC,MAAM,CAAC,GAAG,EAAE,GAAG,SAAS,CAAC,GAAG,IAAI,CAAC;QAEjC,4CAA4C;QAC5C,8DAA8D;QAC9D,MAAM,EAAE,GAAQ,eAAe,CAAC,GAAG,CAAC,CAAC;QACrC,OAAO,EAAE,CAAC,GAAG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CAAC,8DAA8D,CAAC;YACxE,kBAAkB,EAAE,CAAC,CACnB,oEAAoE,CACrE;SACF;KACF,CAAC;AACJ,CAAC,CAAC;AAEF;;;;;GAKG;AACH,SAAS,cAAc,CAAC,OAAe;IACrC,OAAO,SAAS,CAAC,aAAa,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC;AAClD,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,oCAAoC,CAClD,CAAsB,EACtB,YAA6B;IAE7B,IAAI,CAAC,CAAC,EAAE,IAAI,EAAE;QACZ,OAAO,IAAI,CAAC;KACb;IACD,MAAM,mBAAmB,GACvB,qCAAqC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IAE9D,IAAI,CAAC,mBAAmB,EAAE;QACxB,OAAO,IAAI,CAAC;KACb;IAED,IAAI,WAAW,GAAkB,IAAI,CAAC;IACtC,IAAI;QACF,WAAW;YACT,8DAA8D;YAC9D,mBAAmB,EAAE,cAAc,EAAE,CAAC,CAAQ,CAAC;gBAC/C,mBAAmB,CAAC,kBAAkB;gBACtC,IAAI,CAAC;KACR;IAAC,MAAM;QACN,WAAW,GAAG,mBAAmB,CAAC,kBAAkB,IAAI,IAAI,CAAC;KAC9D;IAED,OAAO;QACL,KAAK,EAAE,mBAAmB,CAAC,KAAK,IAAI,EAAE;QACtC,WAAW,EAAE,WAAW,IAAI,EAAE,EAAE,mCAAmC;KACpE,CAAC;AACJ,CAAC","sourcesContent":["import { getAmount, formatAmount } from './get-notification-data';\nimport type { Types } from '../../NotificationServicesController';\nimport { Constants } from '../../NotificationServicesController';\n\nexport type TranslationKeys = {\n pushPlatformNotificationsFundsSentTitle: () => string;\n pushPlatformNotificationsFundsSentDescriptionDefault: () => string;\n pushPlatformNotificationsFundsSentDescription: (\n ...args: [string, string]\n ) => string;\n pushPlatformNotificationsFundsReceivedTitle: () => string;\n pushPlatformNotificationsFundsReceivedDescriptionDefault: () => string;\n pushPlatformNotificationsFundsReceivedDescription: (\n ...args: [string, string]\n ) => string;\n pushPlatformNotificationsSwapCompletedTitle: () => string;\n pushPlatformNotificationsSwapCompletedDescription: () => string;\n pushPlatformNotificationsNftSentTitle: () => string;\n pushPlatformNotificationsNftSentDescription: () => string;\n pushPlatformNotificationsNftReceivedTitle: () => string;\n pushPlatformNotificationsNftReceivedDescription: () => string;\n pushPlatformNotificationsStakingRocketpoolStakeCompletedTitle: () => string;\n pushPlatformNotificationsStakingRocketpoolStakeCompletedDescription: () => string;\n pushPlatformNotificationsStakingRocketpoolUnstakeCompletedTitle: () => string;\n pushPlatformNotificationsStakingRocketpoolUnstakeCompletedDescription: () => string;\n pushPlatformNotificationsStakingLidoStakeCompletedTitle: () => string;\n pushPlatformNotificationsStakingLidoStakeCompletedDescription: () => string;\n pushPlatformNotificationsStakingLidoStakeReadyToBeWithdrawnTitle: () => string;\n pushPlatformNotificationsStakingLidoStakeReadyToBeWithdrawnDescription: () => string;\n pushPlatformNotificationsStakingLidoWithdrawalRequestedTitle: () => string;\n pushPlatformNotificationsStakingLidoWithdrawalRequestedDescription: () => string;\n pushPlatformNotificationsStakingLidoWithdrawalCompletedTitle: () => string;\n pushPlatformNotificationsStakingLidoWithdrawalCompletedDescription: () => string;\n};\n\ntype PushNotificationMessage = {\n title: string;\n description: string;\n};\n\ntype NotificationMessage<N extends Types.INotification> = {\n title: string | null;\n defaultDescription: string | null;\n getDescription?: (n: N) => string | null;\n};\n\ntype NotificationMessageDict = {\n [K in Constants.TRIGGER_TYPES]?: NotificationMessage<\n Extract<Types.INotification, { type: K }>\n >;\n};\n\n/**\n * On Chain Push Notification Messages.\n * This is a list of all the push notifications we support. Update this for synced notifications on mobile and extension\n *\n * @param translationKeys - all translations supported\n * @returns A translation push message object.\n */\nexport const createOnChainPushNotificationMessages = (\n translationKeys: TranslationKeys,\n): NotificationMessageDict => {\n type TranslationFn = <K extends keyof TranslationKeys>(\n ...args: [K, ...Parameters<TranslationKeys[K]>]\n ) => string;\n const t: TranslationFn = (...args) => {\n const [key, ...otherArgs] = args;\n\n // Coerce types for the translation function\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const fn: any = translationKeys[key];\n return fn(...otherArgs);\n };\n\n return {\n erc20_sent: {\n title: t('pushPlatformNotificationsFundsSentTitle'),\n defaultDescription: t(\n 'pushPlatformNotificationsFundsSentDescriptionDefault',\n ),\n getDescription: (n) => {\n const symbol = n?.data?.token?.symbol;\n const tokenAmount = n?.data?.token?.amount;\n const tokenDecimals = n?.data?.token?.decimals;\n if (!symbol || !tokenAmount || !tokenDecimals) {\n return null;\n }\n\n const amount = getAmount(tokenAmount, tokenDecimals, {\n shouldEllipse: true,\n });\n return t(\n 'pushPlatformNotificationsFundsSentDescription',\n amount,\n symbol,\n );\n },\n },\n eth_sent: {\n title: t('pushPlatformNotificationsFundsSentTitle'),\n defaultDescription: t(\n 'pushPlatformNotificationsFundsSentDescriptionDefault',\n ),\n getDescription: (n) => {\n const symbol = getChainSymbol(n?.chain_id);\n const tokenAmount = n?.data?.amount?.eth;\n if (!symbol || !tokenAmount) {\n return null;\n }\n\n const amount = formatAmount(parseFloat(tokenAmount), {\n shouldEllipse: true,\n });\n return t(\n 'pushPlatformNotificationsFundsSentDescription',\n amount,\n symbol,\n );\n },\n },\n erc20_received: {\n title: t('pushPlatformNotificationsFundsReceivedTitle'),\n defaultDescription: t(\n 'pushPlatformNotificationsFundsReceivedDescriptionDefault',\n ),\n getDescription: (n) => {\n const symbol = n?.data?.token?.symbol;\n const tokenAmount = n?.data?.token?.amount;\n const tokenDecimals = n?.data?.token?.decimals;\n if (!symbol || !tokenAmount || !tokenDecimals) {\n return null;\n }\n\n const amount = getAmount(tokenAmount, tokenDecimals, {\n shouldEllipse: true,\n });\n return t(\n 'pushPlatformNotificationsFundsReceivedDescription',\n amount,\n symbol,\n );\n },\n },\n eth_received: {\n title: t('pushPlatformNotificationsFundsReceivedTitle'),\n defaultDescription: t(\n 'pushPlatformNotificationsFundsReceivedDescriptionDefault',\n ),\n getDescription: (n) => {\n const symbol = getChainSymbol(n?.chain_id);\n const tokenAmount = n?.data?.amount?.eth;\n if (!symbol || !tokenAmount) {\n return null;\n }\n\n const amount = formatAmount(parseFloat(tokenAmount), {\n shouldEllipse: true,\n });\n return t(\n 'pushPlatformNotificationsFundsReceivedDescription',\n amount,\n symbol,\n );\n },\n },\n metamask_swap_completed: {\n title: t('pushPlatformNotificationsSwapCompletedTitle'),\n defaultDescription: t(\n 'pushPlatformNotificationsSwapCompletedDescription',\n ),\n },\n erc721_sent: {\n title: t('pushPlatformNotificationsNftSentTitle'),\n defaultDescription: t('pushPlatformNotificationsNftSentDescription'),\n },\n erc1155_sent: {\n title: t('pushPlatformNotificationsNftSentTitle'),\n defaultDescription: t('pushPlatformNotificationsNftSentDescription'),\n },\n erc721_received: {\n title: t('pushPlatformNotificationsNftReceivedTitle'),\n defaultDescription: t('pushPlatformNotificationsNftReceivedDescription'),\n },\n erc1155_received: {\n title: t('pushPlatformNotificationsNftReceivedTitle'),\n defaultDescription: t('pushPlatformNotificationsNftReceivedDescription'),\n },\n rocketpool_stake_completed: {\n title: t('pushPlatformNotificationsStakingRocketpoolStakeCompletedTitle'),\n defaultDescription: t(\n 'pushPlatformNotificationsStakingRocketpoolStakeCompletedDescription',\n ),\n },\n rocketpool_unstake_completed: {\n title: t(\n 'pushPlatformNotificationsStakingRocketpoolUnstakeCompletedTitle',\n ),\n defaultDescription: t(\n 'pushPlatformNotificationsStakingRocketpoolUnstakeCompletedDescription',\n ),\n },\n lido_stake_completed: {\n title: t('pushPlatformNotificationsStakingLidoStakeCompletedTitle'),\n defaultDescription: t(\n 'pushPlatformNotificationsStakingLidoStakeCompletedDescription',\n ),\n },\n lido_stake_ready_to_be_withdrawn: {\n title: t(\n 'pushPlatformNotificationsStakingLidoStakeReadyToBeWithdrawnTitle',\n ),\n defaultDescription: t(\n 'pushPlatformNotificationsStakingLidoStakeReadyToBeWithdrawnDescription',\n ),\n },\n lido_withdrawal_requested: {\n title: t('pushPlatformNotificationsStakingLidoWithdrawalRequestedTitle'),\n defaultDescription: t(\n 'pushPlatformNotificationsStakingLidoWithdrawalRequestedDescription',\n ),\n },\n lido_withdrawal_completed: {\n title: t('pushPlatformNotificationsStakingLidoWithdrawalCompletedTitle'),\n defaultDescription: t(\n 'pushPlatformNotificationsStakingLidoWithdrawalCompletedDescription',\n ),\n },\n };\n};\n\n/**\n * Retrieves the symbol associated with a given chain ID.\n *\n * @param chainId - The ID of the chain.\n * @returns The symbol associated with the chain ID, or null if not found.\n */\nfunction getChainSymbol(chainId: number) {\n return Constants.CHAIN_SYMBOLS[chainId] ?? null;\n}\n\n/**\n * Creates a push notification message based on the given on-chain raw notification.\n *\n * @param n - processed notification.\n * @param translations - translates keys into text\n * @returns The push notification message object, or null if the notification is invalid.\n */\nexport function createOnChainPushNotificationMessage(\n n: Types.INotification,\n translations: TranslationKeys,\n): PushNotificationMessage | null {\n if (!n?.type) {\n return null;\n }\n const notificationMessage =\n createOnChainPushNotificationMessages(translations)[n.type];\n\n if (!notificationMessage) {\n return null;\n }\n\n let description: string | null = null;\n try {\n description =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n notificationMessage?.getDescription?.(n as any) ??\n notificationMessage.defaultDescription ??\n null;\n } catch {\n description = notificationMessage.defaultDescription ?? null;\n }\n\n return {\n title: notificationMessage.title ?? '', // Ensure title is always a string\n description: description ?? '', // Fallback to empty string if null\n };\n}\n"]}
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createSubscribeToPushNotifications = exports.deleteRegToken = exports.createRegToken = void 0;
4
+ var push_utils_1 = require("./push-utils.cjs");
5
+ Object.defineProperty(exports, "createRegToken", { enumerable: true, get: function () { return push_utils_1.createRegToken; } });
6
+ Object.defineProperty(exports, "deleteRegToken", { enumerable: true, get: function () { return push_utils_1.deleteRegToken; } });
7
+ Object.defineProperty(exports, "createSubscribeToPushNotifications", { enumerable: true, get: function () { return push_utils_1.createSubscribeToPushNotifications; } });
8
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/web/index.ts"],"names":[],"mappings":";;;AAAA,+CAIsB;AAHpB,4GAAA,cAAc,OAAA;AACd,4GAAA,cAAc,OAAA;AACd,gIAAA,kCAAkC,OAAA","sourcesContent":["export {\n createRegToken,\n deleteRegToken,\n createSubscribeToPushNotifications,\n} from './push-utils';\n"]}
@@ -0,0 +1,2 @@
1
+ export { createRegToken, deleteRegToken, createSubscribeToPushNotifications, } from "./push-utils.cjs";
2
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/web/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,cAAc,EACd,kCAAkC,GACnC,yBAAqB"}
@@ -0,0 +1,2 @@
1
+ export { createRegToken, deleteRegToken, createSubscribeToPushNotifications, } from "./push-utils.mjs";
2
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/web/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,cAAc,EACd,kCAAkC,GACnC,yBAAqB"}
@@ -0,0 +1,2 @@
1
+ export { createRegToken, deleteRegToken, createSubscribeToPushNotifications } from "./push-utils.mjs";
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/web/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,cAAc,EACd,kCAAkC,EACnC,yBAAqB","sourcesContent":["export {\n createRegToken,\n deleteRegToken,\n createSubscribeToPushNotifications,\n} from './push-utils';\n"]}
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createSubscribeToPushNotifications = exports.deleteRegToken = exports.createRegToken = exports.supportedCache = void 0;
7
+ const app_1 = require("firebase/app");
8
+ const messaging_1 = require("firebase/messaging");
9
+ const sw_1 = require("firebase/messaging/sw");
10
+ const loglevel_1 = __importDefault(require("loglevel"));
11
+ const NotificationServicesController_1 = require("../../NotificationServicesController/index.cjs");
12
+ const to_raw_notification_1 = require("../../shared/to-raw-notification.cjs");
13
+ // Exported to help testing
14
+ // eslint-disable-next-line import-x/no-mutable-exports
15
+ exports.supportedCache = null;
16
+ const getPushAvailability = async () => {
17
+ exports.supportedCache ?? (exports.supportedCache = await (0, sw_1.isSupported)());
18
+ return exports.supportedCache;
19
+ };
20
+ const createFirebaseApp = async (env) => {
21
+ try {
22
+ return (0, app_1.getApp)();
23
+ }
24
+ catch {
25
+ const firebaseConfig = {
26
+ apiKey: env.apiKey,
27
+ authDomain: env.authDomain,
28
+ storageBucket: env.storageBucket,
29
+ projectId: env.projectId,
30
+ messagingSenderId: env.messagingSenderId,
31
+ appId: env.appId,
32
+ measurementId: env.measurementId,
33
+ };
34
+ return (0, app_1.initializeApp)(firebaseConfig);
35
+ }
36
+ };
37
+ const getFirebaseMessaging = async (env) => {
38
+ const supported = await getPushAvailability();
39
+ if (!supported) {
40
+ return null;
41
+ }
42
+ const app = await createFirebaseApp(env);
43
+ return (0, sw_1.getMessaging)(app);
44
+ };
45
+ /**
46
+ * Creates a registration token for Firebase Cloud Messaging.
47
+ *
48
+ * @param env - env to configure push notifications
49
+ * @returns A promise that resolves with the registration token or null if an error occurs.
50
+ */
51
+ async function createRegToken(env) {
52
+ try {
53
+ const messaging = await getFirebaseMessaging(env);
54
+ if (!messaging) {
55
+ return null;
56
+ }
57
+ const token = await (0, messaging_1.getToken)(messaging, {
58
+ serviceWorkerRegistration: self.registration,
59
+ vapidKey: env.vapidKey,
60
+ });
61
+ return token;
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ }
67
+ exports.createRegToken = createRegToken;
68
+ /**
69
+ * Deletes the Firebase Cloud Messaging registration token.
70
+ *
71
+ * @param env - env to configure push notifications
72
+ * @returns A promise that resolves with true if the token was successfully deleted, false otherwise.
73
+ */
74
+ async function deleteRegToken(env) {
75
+ try {
76
+ const messaging = await getFirebaseMessaging(env);
77
+ if (!messaging) {
78
+ return true;
79
+ }
80
+ await (0, messaging_1.deleteToken)(messaging);
81
+ return true;
82
+ }
83
+ catch {
84
+ return false;
85
+ }
86
+ }
87
+ exports.deleteRegToken = deleteRegToken;
88
+ /**
89
+ * Service Worker Listener for when push notifications are received.
90
+ *
91
+ * @param env - push notification environment
92
+ * @param handler - handler to actually showing notification, MUST BE PROVIDED
93
+ * @returns unsubscribe handler
94
+ */
95
+ async function listenToPushNotificationsReceived(env, handler) {
96
+ const messaging = await getFirebaseMessaging(env);
97
+ if (!messaging) {
98
+ return null;
99
+ }
100
+ const unsubscribePushNotifications = (0, sw_1.onBackgroundMessage)(messaging,
101
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
102
+ async (payload) => {
103
+ try {
104
+ const data = payload?.data?.data ? JSON.parse(payload?.data?.data) : undefined;
105
+ if (!data) {
106
+ return;
107
+ }
108
+ const notificationData = (0, to_raw_notification_1.toRawOnChainNotification)(data);
109
+ const notification = NotificationServicesController_1.Processors.processNotification(notificationData);
110
+ await handler(notification);
111
+ }
112
+ catch (error) {
113
+ // Do Nothing, cannot parse a bad notification
114
+ loglevel_1.default.error('Unable to send push notification:', {
115
+ notification: payload?.data?.data,
116
+ error,
117
+ });
118
+ throw new Error('Unable to send push notification');
119
+ }
120
+ });
121
+ const unsubscribe = () => unsubscribePushNotifications();
122
+ return unsubscribe;
123
+ }
124
+ /**
125
+ * Service Worker Listener for when a notification is clicked
126
+ *
127
+ * @param handler - listen to NotificationEvent from the service worker
128
+ * @returns unsubscribe handler
129
+ */
130
+ function listenToPushNotificationsClicked(handler) {
131
+ const clickHandler = (event) => {
132
+ // Get Data
133
+ const data = event?.notification?.data;
134
+ handler(event, data);
135
+ };
136
+ self.addEventListener('notificationclick', clickHandler);
137
+ const unsubscribe = () => self.removeEventListener('notificationclick', clickHandler);
138
+ return unsubscribe;
139
+ }
140
+ /**
141
+ * A creator function that assists creating web-specific push notification subscription:
142
+ * 1. Creates subscriptions for receiving and clicking notifications
143
+ * 2. Creates click events when a notification is clicked
144
+ * 3. Publishes controller messenger events
145
+ *
146
+ * @param props - props for this creator function.
147
+ * @param props.onReceivedHandler - allows the developer to handle showing a notification
148
+ * @param props.onClickHandler - allows the developer to handle clicking the notification
149
+ * @param props.messenger - the controller messenger to publish the `onNewNotifications` and `pushNotificationsClicked` events
150
+ * @returns a function that can be used by the controller
151
+ */
152
+ function createSubscribeToPushNotifications(props) {
153
+ return async function (env) {
154
+ const onBackgroundMessageSub = await listenToPushNotificationsReceived(env, async (notification) => {
155
+ props.messenger.publish('NotificationServicesPushController:onNewNotifications', notification);
156
+ await props.onReceivedHandler(notification);
157
+ });
158
+ const onClickSub = listenToPushNotificationsClicked((event, notification) => {
159
+ props.messenger.publish('NotificationServicesPushController:pushNotificationClicked', notification);
160
+ props.onClickHandler(event, notification);
161
+ });
162
+ const unsubscribe = () => {
163
+ onBackgroundMessageSub?.();
164
+ onClickSub();
165
+ };
166
+ return unsubscribe;
167
+ };
168
+ }
169
+ exports.createSubscribeToPushNotifications = createSubscribeToPushNotifications;
170
+ //# sourceMappingURL=push-utils.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"push-utils.cjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/web/push-utils.ts"],"names":[],"mappings":";;;;;;AAIA,sCAAqD;AACrD,kDAA2D;AAC3D,8CAI+B;AAE/B,wDAA2B;AAG3B,mGAAkE;AAClE,8EAA4E;AAM5E,2BAA2B;AAC3B,uDAAuD;AAC5C,QAAA,cAAc,GA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AC,KAAK,EAAE,YAAY,CAAC,CAAC;QAC5C,CAAC,CACF,CAAC;QAEF,MAAM,WAAW,GAAG,GAAG,EAAE;YACvB,sBAAsB,EAAE,EAAE,CAAC;YAC3B,UAAU,EAAE,CAAC;QACf,CAAC,CAAC;QAEF,OAAO,WAAW,CAAC;IACrB,CAAC,CAAC;AACJ,CAAC;AAtCD,gFAsCC","sourcesContent":["// We are defining that this file uses a webworker global scope.\n// eslint-disable-next-line spaced-comment\n/// <reference lib=\"webworker\" />\nimport type { FirebaseApp } from 'firebase/app';\nimport { getApp, initializeApp } from 'firebase/app';\nimport { getToken, deleteToken } from 'firebase/messaging';\nimport {\n getMessaging,\n onBackgroundMessage,\n isSupported,\n} from 'firebase/messaging/sw';\nimport type { Messaging, MessagePayload } from 'firebase/messaging/sw';\nimport log from 'loglevel';\n\nimport type { Types } from '../../NotificationServicesController';\nimport { Processors } from '../../NotificationServicesController';\nimport { toRawOnChainNotification } from '../../shared/to-raw-notification';\nimport type { NotificationServicesPushControllerMessenger } from '../NotificationServicesPushController';\nimport type { PushNotificationEnv } from '../types/firebase';\n\ndeclare const self: ServiceWorkerGlobalScope;\n\n// Exported to help testing\n// eslint-disable-next-line import-x/no-mutable-exports\nexport let supportedCache: boolean | null = null;\n\nconst getPushAvailability = async () => {\n supportedCache ??= await isSupported();\n return supportedCache;\n};\n\nconst createFirebaseApp = async (\n env: PushNotificationEnv,\n): Promise<FirebaseApp> => {\n try {\n return getApp();\n } catch {\n const firebaseConfig = {\n apiKey: env.apiKey,\n authDomain: env.authDomain,\n storageBucket: env.storageBucket,\n projectId: env.projectId,\n messagingSenderId: env.messagingSenderId,\n appId: env.appId,\n measurementId: env.measurementId,\n };\n return initializeApp(firebaseConfig);\n }\n};\n\nconst getFirebaseMessaging = async (\n env: PushNotificationEnv,\n): Promise<Messaging | null> => {\n const supported = await getPushAvailability();\n if (!supported) {\n return null;\n }\n\n const app = await createFirebaseApp(env);\n return getMessaging(app);\n};\n\n/**\n * Creates a registration token for Firebase Cloud Messaging.\n *\n * @param env - env to configure push notifications\n * @returns A promise that resolves with the registration token or null if an error occurs.\n */\nexport async function createRegToken(\n env: PushNotificationEnv,\n): Promise<string | null> {\n try {\n const messaging = await getFirebaseMessaging(env);\n if (!messaging) {\n return null;\n }\n\n const token = await getToken(messaging, {\n serviceWorkerRegistration: self.registration,\n vapidKey: env.vapidKey,\n });\n return token;\n } catch {\n return null;\n }\n}\n\n/**\n * Deletes the Firebase Cloud Messaging registration token.\n *\n * @param env - env to configure push notifications\n * @returns A promise that resolves with true if the token was successfully deleted, false otherwise.\n */\nexport async function deleteRegToken(\n env: PushNotificationEnv,\n): Promise<boolean> {\n try {\n const messaging = await getFirebaseMessaging(env);\n if (!messaging) {\n return true;\n }\n\n await deleteToken(messaging);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Service Worker Listener for when push notifications are received.\n *\n * @param env - push notification environment\n * @param handler - handler to actually showing notification, MUST BE PROVIDED\n * @returns unsubscribe handler\n */\nasync function listenToPushNotificationsReceived(\n env: PushNotificationEnv,\n handler: (notification: Types.INotification) => void | Promise<void>,\n): Promise<(() => void) | null> {\n const messaging = await getFirebaseMessaging(env);\n if (!messaging) {\n return null;\n }\n\n const unsubscribePushNotifications = onBackgroundMessage(\n messaging,\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (payload: MessagePayload) => {\n try {\n const data: Types.UnprocessedOnChainRawNotification | undefined =\n payload?.data?.data ? JSON.parse(payload?.data?.data) : undefined;\n\n if (!data) {\n return;\n }\n\n const notificationData = toRawOnChainNotification(data);\n const notification = Processors.processNotification(notificationData);\n await handler(notification);\n } catch (error) {\n // Do Nothing, cannot parse a bad notification\n log.error('Unable to send push notification:', {\n notification: payload?.data?.data,\n error,\n });\n throw new Error('Unable to send push notification');\n }\n },\n );\n\n const unsubscribe = () => unsubscribePushNotifications();\n return unsubscribe;\n}\n\n/**\n * Service Worker Listener for when a notification is clicked\n *\n * @param handler - listen to NotificationEvent from the service worker\n * @returns unsubscribe handler\n */\nfunction listenToPushNotificationsClicked(\n handler: (e: NotificationEvent, notification: Types.INotification) => void,\n) {\n const clickHandler = (event: NotificationEvent) => {\n // Get Data\n const data: Types.INotification = event?.notification?.data;\n handler(event, data);\n };\n\n self.addEventListener('notificationclick', clickHandler);\n const unsubscribe = () =>\n self.removeEventListener('notificationclick', clickHandler);\n return unsubscribe;\n}\n\n/**\n * A creator function that assists creating web-specific push notification subscription:\n * 1. Creates subscriptions for receiving and clicking notifications\n * 2. Creates click events when a notification is clicked\n * 3. Publishes controller messenger events\n *\n * @param props - props for this creator function.\n * @param props.onReceivedHandler - allows the developer to handle showing a notification\n * @param props.onClickHandler - allows the developer to handle clicking the notification\n * @param props.messenger - the controller messenger to publish the `onNewNotifications` and `pushNotificationsClicked` events\n * @returns a function that can be used by the controller\n */\nexport function createSubscribeToPushNotifications(props: {\n onReceivedHandler: (\n notification: Types.INotification,\n ) => void | Promise<void>;\n onClickHandler: (\n e: NotificationEvent,\n notification: Types.INotification,\n ) => void;\n messenger: NotificationServicesPushControllerMessenger;\n}) {\n return async function (env: PushNotificationEnv) {\n const onBackgroundMessageSub = await listenToPushNotificationsReceived(\n env,\n async (notification) => {\n props.messenger.publish(\n 'NotificationServicesPushController:onNewNotifications',\n notification,\n );\n await props.onReceivedHandler(notification);\n },\n );\n const onClickSub = listenToPushNotificationsClicked(\n (event, notification) => {\n props.messenger.publish(\n 'NotificationServicesPushController:pushNotificationClicked',\n notification,\n );\n props.onClickHandler(event, notification);\n },\n );\n\n const unsubscribe = () => {\n onBackgroundMessageSub?.();\n onClickSub();\n };\n\n return unsubscribe;\n };\n}\n"]}
@@ -0,0 +1,37 @@
1
+ /// <reference lib="webworker" />
2
+ import type { Types } from "../../NotificationServicesController/index.cjs";
3
+ import type { NotificationServicesPushControllerMessenger } from "../NotificationServicesPushController.cjs";
4
+ import type { PushNotificationEnv } from "../types/firebase.cjs";
5
+ export declare let supportedCache: boolean | null;
6
+ /**
7
+ * Creates a registration token for Firebase Cloud Messaging.
8
+ *
9
+ * @param env - env to configure push notifications
10
+ * @returns A promise that resolves with the registration token or null if an error occurs.
11
+ */
12
+ export declare function createRegToken(env: PushNotificationEnv): Promise<string | null>;
13
+ /**
14
+ * Deletes the Firebase Cloud Messaging registration token.
15
+ *
16
+ * @param env - env to configure push notifications
17
+ * @returns A promise that resolves with true if the token was successfully deleted, false otherwise.
18
+ */
19
+ export declare function deleteRegToken(env: PushNotificationEnv): Promise<boolean>;
20
+ /**
21
+ * A creator function that assists creating web-specific push notification subscription:
22
+ * 1. Creates subscriptions for receiving and clicking notifications
23
+ * 2. Creates click events when a notification is clicked
24
+ * 3. Publishes controller messenger events
25
+ *
26
+ * @param props - props for this creator function.
27
+ * @param props.onReceivedHandler - allows the developer to handle showing a notification
28
+ * @param props.onClickHandler - allows the developer to handle clicking the notification
29
+ * @param props.messenger - the controller messenger to publish the `onNewNotifications` and `pushNotificationsClicked` events
30
+ * @returns a function that can be used by the controller
31
+ */
32
+ export declare function createSubscribeToPushNotifications(props: {
33
+ onReceivedHandler: (notification: Types.INotification) => void | Promise<void>;
34
+ onClickHandler: (e: NotificationEvent, notification: Types.INotification) => void;
35
+ messenger: NotificationServicesPushControllerMessenger;
36
+ }): (env: PushNotificationEnv) => Promise<() => void>;
37
+ //# sourceMappingURL=push-utils.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"push-utils.d.cts","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/web/push-utils.ts"],"names":[],"mappings":";AAcA,OAAO,KAAK,EAAE,KAAK,EAAE,uDAA6C;AAGlE,OAAO,KAAK,EAAE,2CAA2C,EAAE,kDAA8C;AACzG,OAAO,KAAK,EAAE,mBAAmB,EAAE,8BAA0B;AAM7D,eAAO,IAAI,cAAc,EAAE,OAAO,GAAG,IAAW,CAAC;AAsCjD;;;;;GAKG;AACH,wBAAsB,cAAc,CAClC,GAAG,EAAE,mBAAmB,GACvB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAexB;AAED;;;;;GAKG;AACH,wBAAsB,cAAc,CAClC,GAAG,EAAE,mBAAmB,GACvB,OAAO,CAAC,OAAO,CAAC,CAYlB;AAqED;;;;;;;;;;;GAWG;AACH,wBAAgB,kCAAkC,CAAC,KAAK,EAAE;IACxD,iBAAiB,EAAE,CACjB,YAAY,EAAE,KAAK,CAAC,aAAa,KAC9B,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1B,cAAc,EAAE,CACd,CAAC,EAAE,iBAAiB,EACpB,YAAY,EAAE,KAAK,CAAC,aAAa,KAC9B,IAAI,CAAC;IACV,SAAS,EAAE,2CAA2C,CAAC;CACxD,SAC6B,mBAAmB,yBA4BhD"}
@@ -0,0 +1,37 @@
1
+ /// <reference lib="webworker" />
2
+ import type { Types } from "../../NotificationServicesController/index.mjs";
3
+ import type { NotificationServicesPushControllerMessenger } from "../NotificationServicesPushController.mjs";
4
+ import type { PushNotificationEnv } from "../types/firebase.mjs";
5
+ export declare let supportedCache: boolean | null;
6
+ /**
7
+ * Creates a registration token for Firebase Cloud Messaging.
8
+ *
9
+ * @param env - env to configure push notifications
10
+ * @returns A promise that resolves with the registration token or null if an error occurs.
11
+ */
12
+ export declare function createRegToken(env: PushNotificationEnv): Promise<string | null>;
13
+ /**
14
+ * Deletes the Firebase Cloud Messaging registration token.
15
+ *
16
+ * @param env - env to configure push notifications
17
+ * @returns A promise that resolves with true if the token was successfully deleted, false otherwise.
18
+ */
19
+ export declare function deleteRegToken(env: PushNotificationEnv): Promise<boolean>;
20
+ /**
21
+ * A creator function that assists creating web-specific push notification subscription:
22
+ * 1. Creates subscriptions for receiving and clicking notifications
23
+ * 2. Creates click events when a notification is clicked
24
+ * 3. Publishes controller messenger events
25
+ *
26
+ * @param props - props for this creator function.
27
+ * @param props.onReceivedHandler - allows the developer to handle showing a notification
28
+ * @param props.onClickHandler - allows the developer to handle clicking the notification
29
+ * @param props.messenger - the controller messenger to publish the `onNewNotifications` and `pushNotificationsClicked` events
30
+ * @returns a function that can be used by the controller
31
+ */
32
+ export declare function createSubscribeToPushNotifications(props: {
33
+ onReceivedHandler: (notification: Types.INotification) => void | Promise<void>;
34
+ onClickHandler: (e: NotificationEvent, notification: Types.INotification) => void;
35
+ messenger: NotificationServicesPushControllerMessenger;
36
+ }): (env: PushNotificationEnv) => Promise<() => void>;
37
+ //# sourceMappingURL=push-utils.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"push-utils.d.mts","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/web/push-utils.ts"],"names":[],"mappings":";AAcA,OAAO,KAAK,EAAE,KAAK,EAAE,uDAA6C;AAGlE,OAAO,KAAK,EAAE,2CAA2C,EAAE,kDAA8C;AACzG,OAAO,KAAK,EAAE,mBAAmB,EAAE,8BAA0B;AAM7D,eAAO,IAAI,cAAc,EAAE,OAAO,GAAG,IAAW,CAAC;AAsCjD;;;;;GAKG;AACH,wBAAsB,cAAc,CAClC,GAAG,EAAE,mBAAmB,GACvB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAexB;AAED;;;;;GAKG;AACH,wBAAsB,cAAc,CAClC,GAAG,EAAE,mBAAmB,GACvB,OAAO,CAAC,OAAO,CAAC,CAYlB;AAqED;;;;;;;;;;;GAWG;AACH,wBAAgB,kCAAkC,CAAC,KAAK,EAAE;IACxD,iBAAiB,EAAE,CACjB,YAAY,EAAE,KAAK,CAAC,aAAa,KAC9B,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1B,cAAc,EAAE,CACd,CAAC,EAAE,iBAAiB,EACpB,YAAY,EAAE,KAAK,CAAC,aAAa,KAC9B,IAAI,CAAC;IACV,SAAS,EAAE,2CAA2C,CAAC;CACxD,SAC6B,mBAAmB,yBA4BhD"}
@@ -0,0 +1,168 @@
1
+ function $importDefault(module) {
2
+ if (module?.__esModule) {
3
+ return module.default;
4
+ }
5
+ return module;
6
+ }
7
+ import { getApp, initializeApp } from "firebase/app";
8
+ import { getToken, deleteToken } from "firebase/messaging";
9
+ import { getMessaging, onBackgroundMessage, isSupported } from "firebase/messaging/sw";
10
+ import $log from "loglevel";
11
+ const log = $importDefault($log);
12
+ import { Processors } from "../../NotificationServicesController/index.mjs";
13
+ import { toRawOnChainNotification } from "../../shared/to-raw-notification.mjs";
14
+ // Exported to help testing
15
+ // eslint-disable-next-line import-x/no-mutable-exports
16
+ export let supportedCache = null;
17
+ const getPushAvailability = async () => {
18
+ supportedCache ?? (supportedCache = await isSupported());
19
+ return supportedCache;
20
+ };
21
+ const createFirebaseApp = async (env) => {
22
+ try {
23
+ return getApp();
24
+ }
25
+ catch {
26
+ const firebaseConfig = {
27
+ apiKey: env.apiKey,
28
+ authDomain: env.authDomain,
29
+ storageBucket: env.storageBucket,
30
+ projectId: env.projectId,
31
+ messagingSenderId: env.messagingSenderId,
32
+ appId: env.appId,
33
+ measurementId: env.measurementId,
34
+ };
35
+ return initializeApp(firebaseConfig);
36
+ }
37
+ };
38
+ const getFirebaseMessaging = async (env) => {
39
+ const supported = await getPushAvailability();
40
+ if (!supported) {
41
+ return null;
42
+ }
43
+ const app = await createFirebaseApp(env);
44
+ return getMessaging(app);
45
+ };
46
+ /**
47
+ * Creates a registration token for Firebase Cloud Messaging.
48
+ *
49
+ * @param env - env to configure push notifications
50
+ * @returns A promise that resolves with the registration token or null if an error occurs.
51
+ */
52
+ export async function createRegToken(env) {
53
+ try {
54
+ const messaging = await getFirebaseMessaging(env);
55
+ if (!messaging) {
56
+ return null;
57
+ }
58
+ const token = await getToken(messaging, {
59
+ serviceWorkerRegistration: self.registration,
60
+ vapidKey: env.vapidKey,
61
+ });
62
+ return token;
63
+ }
64
+ catch {
65
+ return null;
66
+ }
67
+ }
68
+ /**
69
+ * Deletes the Firebase Cloud Messaging registration token.
70
+ *
71
+ * @param env - env to configure push notifications
72
+ * @returns A promise that resolves with true if the token was successfully deleted, false otherwise.
73
+ */
74
+ export async function deleteRegToken(env) {
75
+ try {
76
+ const messaging = await getFirebaseMessaging(env);
77
+ if (!messaging) {
78
+ return true;
79
+ }
80
+ await deleteToken(messaging);
81
+ return true;
82
+ }
83
+ catch {
84
+ return false;
85
+ }
86
+ }
87
+ /**
88
+ * Service Worker Listener for when push notifications are received.
89
+ *
90
+ * @param env - push notification environment
91
+ * @param handler - handler to actually showing notification, MUST BE PROVIDED
92
+ * @returns unsubscribe handler
93
+ */
94
+ async function listenToPushNotificationsReceived(env, handler) {
95
+ const messaging = await getFirebaseMessaging(env);
96
+ if (!messaging) {
97
+ return null;
98
+ }
99
+ const unsubscribePushNotifications = onBackgroundMessage(messaging,
100
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
101
+ async (payload) => {
102
+ try {
103
+ const data = payload?.data?.data ? JSON.parse(payload?.data?.data) : undefined;
104
+ if (!data) {
105
+ return;
106
+ }
107
+ const notificationData = toRawOnChainNotification(data);
108
+ const notification = Processors.processNotification(notificationData);
109
+ await handler(notification);
110
+ }
111
+ catch (error) {
112
+ // Do Nothing, cannot parse a bad notification
113
+ log.error('Unable to send push notification:', {
114
+ notification: payload?.data?.data,
115
+ error,
116
+ });
117
+ throw new Error('Unable to send push notification');
118
+ }
119
+ });
120
+ const unsubscribe = () => unsubscribePushNotifications();
121
+ return unsubscribe;
122
+ }
123
+ /**
124
+ * Service Worker Listener for when a notification is clicked
125
+ *
126
+ * @param handler - listen to NotificationEvent from the service worker
127
+ * @returns unsubscribe handler
128
+ */
129
+ function listenToPushNotificationsClicked(handler) {
130
+ const clickHandler = (event) => {
131
+ // Get Data
132
+ const data = event?.notification?.data;
133
+ handler(event, data);
134
+ };
135
+ self.addEventListener('notificationclick', clickHandler);
136
+ const unsubscribe = () => self.removeEventListener('notificationclick', clickHandler);
137
+ return unsubscribe;
138
+ }
139
+ /**
140
+ * A creator function that assists creating web-specific push notification subscription:
141
+ * 1. Creates subscriptions for receiving and clicking notifications
142
+ * 2. Creates click events when a notification is clicked
143
+ * 3. Publishes controller messenger events
144
+ *
145
+ * @param props - props for this creator function.
146
+ * @param props.onReceivedHandler - allows the developer to handle showing a notification
147
+ * @param props.onClickHandler - allows the developer to handle clicking the notification
148
+ * @param props.messenger - the controller messenger to publish the `onNewNotifications` and `pushNotificationsClicked` events
149
+ * @returns a function that can be used by the controller
150
+ */
151
+ export function createSubscribeToPushNotifications(props) {
152
+ return async function (env) {
153
+ const onBackgroundMessageSub = await listenToPushNotificationsReceived(env, async (notification) => {
154
+ props.messenger.publish('NotificationServicesPushController:onNewNotifications', notification);
155
+ await props.onReceivedHandler(notification);
156
+ });
157
+ const onClickSub = listenToPushNotificationsClicked((event, notification) => {
158
+ props.messenger.publish('NotificationServicesPushController:pushNotificationClicked', notification);
159
+ props.onClickHandler(event, notification);
160
+ });
161
+ const unsubscribe = () => {
162
+ onBackgroundMessageSub?.();
163
+ onClickSub();
164
+ };
165
+ return unsubscribe;
166
+ };
167
+ }
168
+ //# sourceMappingURL=push-utils.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"push-utils.mjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/web/push-utils.ts"],"names":[],"mappings":";;;;;;AAIA,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,qBAAqB;AACrD,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,2BAA2B;AAC3D,OAAO,EACL,YAAY,EACZ,mBAAmB,EACnB,WAAW,EACZ,8BAA8B;AAE/B,OAAO,IAAG,iBAAiB;;AAG3B,OAAO,EAAE,UAAU,EAAE,uDAA6C;AAClE,OAAO,EAAE,wBAAwB,EAAE,6CAAyC;AAM5E,2BAA2B;AAC3B,uDAAuD;AACvD,MAAM,CAAC,IAAI,cAAc,GAAmB,IAAI,CAAC;AAEjD,MAAM,mBAAmB,GAAG,KAAK,IAAI,EAAE;IACrC,cAAc,KAAd,cAAc,GAAK,MAAM,WAAW,EAAE,EAAC;IACvC,OAAO,cAAc,CAAC;AACxB,CAAC,CAAC;AAEF,MAAM,iBAAiB,GAAG,KAAK,EAC7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// eslint-disable-next-line spaced-comment\n/// <reference lib=\"webworker\" />\nimport type { FirebaseApp } from 'firebase/app';\nimport { getApp, initializeApp } from 'firebase/app';\nimport { getToken, deleteToken } from 'firebase/messaging';\nimport {\n getMessaging,\n onBackgroundMessage,\n isSupported,\n} from 'firebase/messaging/sw';\nimport type { Messaging, MessagePayload } from 'firebase/messaging/sw';\nimport log from 'loglevel';\n\nimport type { Types } from '../../NotificationServicesController';\nimport { Processors } from '../../NotificationServicesController';\nimport { toRawOnChainNotification } from '../../shared/to-raw-notification';\nimport type { NotificationServicesPushControllerMessenger } from '../NotificationServicesPushController';\nimport type { PushNotificationEnv } from '../types/firebase';\n\ndeclare const self: ServiceWorkerGlobalScope;\n\n// Exported to help testing\n// eslint-disable-next-line import-x/no-mutable-exports\nexport let supportedCache: boolean | null = null;\n\nconst getPushAvailability = async () => {\n supportedCache ??= await isSupported();\n return supportedCache;\n};\n\nconst createFirebaseApp = async (\n env: PushNotificationEnv,\n): Promise<FirebaseApp> => {\n try {\n return getApp();\n } catch {\n const firebaseConfig = {\n apiKey: env.apiKey,\n authDomain: env.authDomain,\n storageBucket: env.storageBucket,\n projectId: env.projectId,\n messagingSenderId: env.messagingSenderId,\n appId: env.appId,\n measurementId: env.measurementId,\n };\n return initializeApp(firebaseConfig);\n }\n};\n\nconst getFirebaseMessaging = async (\n env: PushNotificationEnv,\n): Promise<Messaging | null> => {\n const supported = await getPushAvailability();\n if (!supported) {\n return null;\n }\n\n const app = await createFirebaseApp(env);\n return getMessaging(app);\n};\n\n/**\n * Creates a registration token for Firebase Cloud Messaging.\n *\n * @param env - env to configure push notifications\n * @returns A promise that resolves with the registration token or null if an error occurs.\n */\nexport async function createRegToken(\n env: PushNotificationEnv,\n): Promise<string | null> {\n try {\n const messaging = await getFirebaseMessaging(env);\n if (!messaging) {\n return null;\n }\n\n const token = await getToken(messaging, {\n serviceWorkerRegistration: self.registration,\n vapidKey: env.vapidKey,\n });\n return token;\n } catch {\n return null;\n }\n}\n\n/**\n * Deletes the Firebase Cloud Messaging registration token.\n *\n * @param env - env to configure push notifications\n * @returns A promise that resolves with true if the token was successfully deleted, false otherwise.\n */\nexport async function deleteRegToken(\n env: PushNotificationEnv,\n): Promise<boolean> {\n try {\n const messaging = await getFirebaseMessaging(env);\n if (!messaging) {\n return true;\n }\n\n await deleteToken(messaging);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Service Worker Listener for when push notifications are received.\n *\n * @param env - push notification environment\n * @param handler - handler to actually showing notification, MUST BE PROVIDED\n * @returns unsubscribe handler\n */\nasync function listenToPushNotificationsReceived(\n env: PushNotificationEnv,\n handler: (notification: Types.INotification) => void | Promise<void>,\n): Promise<(() => void) | null> {\n const messaging = await getFirebaseMessaging(env);\n if (!messaging) {\n return null;\n }\n\n const unsubscribePushNotifications = onBackgroundMessage(\n messaging,\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (payload: MessagePayload) => {\n try {\n const data: Types.UnprocessedOnChainRawNotification | undefined =\n payload?.data?.data ? JSON.parse(payload?.data?.data) : undefined;\n\n if (!data) {\n return;\n }\n\n const notificationData = toRawOnChainNotification(data);\n const notification = Processors.processNotification(notificationData);\n await handler(notification);\n } catch (error) {\n // Do Nothing, cannot parse a bad notification\n log.error('Unable to send push notification:', {\n notification: payload?.data?.data,\n error,\n });\n throw new Error('Unable to send push notification');\n }\n },\n );\n\n const unsubscribe = () => unsubscribePushNotifications();\n return unsubscribe;\n}\n\n/**\n * Service Worker Listener for when a notification is clicked\n *\n * @param handler - listen to NotificationEvent from the service worker\n * @returns unsubscribe handler\n */\nfunction listenToPushNotificationsClicked(\n handler: (e: NotificationEvent, notification: Types.INotification) => void,\n) {\n const clickHandler = (event: NotificationEvent) => {\n // Get Data\n const data: Types.INotification = event?.notification?.data;\n handler(event, data);\n };\n\n self.addEventListener('notificationclick', clickHandler);\n const unsubscribe = () =>\n self.removeEventListener('notificationclick', clickHandler);\n return unsubscribe;\n}\n\n/**\n * A creator function that assists creating web-specific push notification subscription:\n * 1. Creates subscriptions for receiving and clicking notifications\n * 2. Creates click events when a notification is clicked\n * 3. Publishes controller messenger events\n *\n * @param props - props for this creator function.\n * @param props.onReceivedHandler - allows the developer to handle showing a notification\n * @param props.onClickHandler - allows the developer to handle clicking the notification\n * @param props.messenger - the controller messenger to publish the `onNewNotifications` and `pushNotificationsClicked` events\n * @returns a function that can be used by the controller\n */\nexport function createSubscribeToPushNotifications(props: {\n onReceivedHandler: (\n notification: Types.INotification,\n ) => void | Promise<void>;\n onClickHandler: (\n e: NotificationEvent,\n notification: Types.INotification,\n ) => void;\n messenger: NotificationServicesPushControllerMessenger;\n}) {\n return async function (env: PushNotificationEnv) {\n const onBackgroundMessageSub = await listenToPushNotificationsReceived(\n env,\n async (notification) => {\n props.messenger.publish(\n 'NotificationServicesPushController:onNewNotifications',\n notification,\n );\n await props.onReceivedHandler(notification);\n },\n );\n const onClickSub = listenToPushNotificationsClicked(\n (event, notification) => {\n props.messenger.publish(\n 'NotificationServicesPushController:pushNotificationClicked',\n notification,\n );\n props.onClickHandler(event, notification);\n },\n );\n\n const unsubscribe = () => {\n onBackgroundMessageSub?.();\n onClickSub();\n };\n\n return unsubscribe;\n };\n}\n"]}
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./is-onchain-notification.cjs"), exports);
18
+ __exportStar(require("./to-raw-notification.cjs"), exports);
19
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../../src/shared/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,gEAA0C;AAC1C,4DAAsC","sourcesContent":["export * from './is-onchain-notification';\nexport * from './to-raw-notification';\n"]}
@@ -0,0 +1,3 @@
1
+ export * from "./is-onchain-notification.cjs";
2
+ export * from "./to-raw-notification.cjs";
3
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../../src/shared/index.ts"],"names":[],"mappings":"AAAA,8CAA0C;AAC1C,0CAAsC"}
@@ -0,0 +1,3 @@
1
+ export * from "./is-onchain-notification.mjs";
2
+ export * from "./to-raw-notification.mjs";
3
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../../src/shared/index.ts"],"names":[],"mappings":"AAAA,8CAA0C;AAC1C,0CAAsC"}
@@ -0,0 +1,3 @@
1
+ export * from "./is-onchain-notification.mjs";
2
+ export * from "./to-raw-notification.mjs";
3
+ //# sourceMappingURL=index.mjs.map