@frak-labs/core-sdk 0.1.0 → 0.1.1-beta.4dfea079

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 (130) hide show
  1. package/README.md +58 -0
  2. package/cdn/bundle.js +3 -8
  3. package/dist/actions.cjs +1 -1
  4. package/dist/actions.d.cts +3 -1400
  5. package/dist/actions.d.ts +3 -1400
  6. package/dist/actions.js +1 -1
  7. package/dist/bundle.cjs +1 -13
  8. package/dist/bundle.d.cts +4 -1927
  9. package/dist/bundle.d.ts +4 -1927
  10. package/dist/bundle.js +1 -13
  11. package/dist/computeLegacyProductId-CscYhyUi.d.cts +525 -0
  12. package/dist/computeLegacyProductId-WbD1gXV9.d.ts +525 -0
  13. package/dist/index.cjs +1 -13
  14. package/dist/index.d.cts +3 -1269
  15. package/dist/index.d.ts +3 -1269
  16. package/dist/index.js +1 -13
  17. package/dist/openSso-CC1-loUk.d.cts +1019 -0
  18. package/dist/openSso-tkqaDQLV.d.ts +1019 -0
  19. package/dist/setupClient-BjIbK6XJ.cjs +13 -0
  20. package/dist/setupClient-D_HId3e2.js +13 -0
  21. package/dist/siweAuthenticate-B_Z2OZmj.cjs +1 -0
  22. package/dist/siweAuthenticate-CQ4OfPuA.js +1 -0
  23. package/dist/siweAuthenticate-CR4Dpji6.d.cts +467 -0
  24. package/dist/siweAuthenticate-udoruuy9.d.ts +467 -0
  25. package/dist/trackEvent-CGIryq5h.cjs +1 -0
  26. package/dist/trackEvent-YfUh4jrx.js +1 -0
  27. package/package.json +24 -30
  28. package/src/actions/displayEmbeddedWallet.test.ts +194 -0
  29. package/src/actions/displayEmbeddedWallet.ts +20 -0
  30. package/src/actions/displayModal.test.ts +388 -0
  31. package/src/actions/displayModal.ts +120 -0
  32. package/src/actions/getMerchantInformation.test.ts +116 -0
  33. package/src/actions/getMerchantInformation.ts +9 -0
  34. package/src/actions/index.ts +29 -0
  35. package/src/actions/openSso.ts +116 -0
  36. package/src/actions/prepareSso.test.ts +223 -0
  37. package/src/actions/prepareSso.ts +48 -0
  38. package/src/actions/referral/processReferral.test.ts +248 -0
  39. package/src/actions/referral/processReferral.ts +232 -0
  40. package/src/actions/referral/referralInteraction.test.ts +147 -0
  41. package/src/actions/referral/referralInteraction.ts +52 -0
  42. package/src/actions/sendInteraction.ts +24 -0
  43. package/src/actions/trackPurchaseStatus.test.ts +287 -0
  44. package/src/actions/trackPurchaseStatus.ts +56 -0
  45. package/src/actions/watchWalletStatus.test.ts +372 -0
  46. package/src/actions/watchWalletStatus.ts +93 -0
  47. package/src/actions/wrapper/modalBuilder.test.ts +239 -0
  48. package/src/actions/wrapper/modalBuilder.ts +203 -0
  49. package/src/actions/wrapper/sendTransaction.test.ts +164 -0
  50. package/src/actions/wrapper/sendTransaction.ts +62 -0
  51. package/src/actions/wrapper/siweAuthenticate.test.ts +290 -0
  52. package/src/actions/wrapper/siweAuthenticate.ts +94 -0
  53. package/src/bundle.ts +2 -0
  54. package/src/clients/DebugInfo.test.ts +418 -0
  55. package/src/clients/DebugInfo.ts +182 -0
  56. package/src/clients/createIFrameFrakClient.ts +289 -0
  57. package/src/clients/index.ts +3 -0
  58. package/src/clients/setupClient.test.ts +343 -0
  59. package/src/clients/setupClient.ts +73 -0
  60. package/src/clients/transports/iframeLifecycleManager.test.ts +558 -0
  61. package/src/clients/transports/iframeLifecycleManager.ts +174 -0
  62. package/src/constants/interactionTypes.ts +15 -0
  63. package/src/constants/locales.ts +14 -0
  64. package/src/index.ts +110 -0
  65. package/src/types/client.ts +14 -0
  66. package/src/types/compression.ts +22 -0
  67. package/src/types/config.ts +117 -0
  68. package/src/types/context.ts +13 -0
  69. package/src/types/index.ts +75 -0
  70. package/src/types/lifecycle/client.ts +69 -0
  71. package/src/types/lifecycle/iframe.ts +41 -0
  72. package/src/types/lifecycle/index.ts +2 -0
  73. package/src/types/rpc/displayModal.ts +82 -0
  74. package/src/types/rpc/embedded/index.ts +68 -0
  75. package/src/types/rpc/embedded/loggedIn.ts +55 -0
  76. package/src/types/rpc/embedded/loggedOut.ts +28 -0
  77. package/src/types/rpc/interaction.ts +30 -0
  78. package/src/types/rpc/merchantInformation.ts +77 -0
  79. package/src/types/rpc/modal/final.ts +46 -0
  80. package/src/types/rpc/modal/generic.ts +46 -0
  81. package/src/types/rpc/modal/index.ts +16 -0
  82. package/src/types/rpc/modal/login.ts +36 -0
  83. package/src/types/rpc/modal/siweAuthenticate.ts +37 -0
  84. package/src/types/rpc/modal/transaction.ts +33 -0
  85. package/src/types/rpc/sso.ts +80 -0
  86. package/src/types/rpc/walletStatus.ts +29 -0
  87. package/src/types/rpc.ts +146 -0
  88. package/src/types/tracking.ts +60 -0
  89. package/src/types/transport.ts +34 -0
  90. package/src/utils/FrakContext.test.ts +407 -0
  91. package/src/utils/FrakContext.ts +158 -0
  92. package/src/utils/backendUrl.test.ts +83 -0
  93. package/src/utils/backendUrl.ts +62 -0
  94. package/src/utils/clientId.test.ts +41 -0
  95. package/src/utils/clientId.ts +40 -0
  96. package/src/utils/compression/b64.test.ts +181 -0
  97. package/src/utils/compression/b64.ts +29 -0
  98. package/src/utils/compression/compress.test.ts +123 -0
  99. package/src/utils/compression/compress.ts +11 -0
  100. package/src/utils/compression/decompress.test.ts +149 -0
  101. package/src/utils/compression/decompress.ts +11 -0
  102. package/src/utils/compression/index.ts +3 -0
  103. package/src/utils/computeLegacyProductId.ts +11 -0
  104. package/src/utils/constants.test.ts +23 -0
  105. package/src/utils/constants.ts +14 -0
  106. package/src/utils/deepLinkWithFallback.test.ts +243 -0
  107. package/src/utils/deepLinkWithFallback.ts +97 -0
  108. package/src/utils/formatAmount.test.ts +113 -0
  109. package/src/utils/formatAmount.ts +18 -0
  110. package/src/utils/getCurrencyAmountKey.test.ts +44 -0
  111. package/src/utils/getCurrencyAmountKey.ts +15 -0
  112. package/src/utils/getSupportedCurrency.test.ts +51 -0
  113. package/src/utils/getSupportedCurrency.ts +14 -0
  114. package/src/utils/getSupportedLocale.test.ts +64 -0
  115. package/src/utils/getSupportedLocale.ts +16 -0
  116. package/src/utils/iframeHelper.test.ts +450 -0
  117. package/src/utils/iframeHelper.ts +147 -0
  118. package/src/utils/index.ts +36 -0
  119. package/src/utils/merchantId.test.ts +564 -0
  120. package/src/utils/merchantId.ts +122 -0
  121. package/src/utils/sso.ts +126 -0
  122. package/src/utils/ssoUrlListener.test.ts +252 -0
  123. package/src/utils/ssoUrlListener.ts +60 -0
  124. package/src/utils/trackEvent.test.ts +180 -0
  125. package/src/utils/trackEvent.ts +31 -0
  126. package/cdn/bundle.js.LICENSE.txt +0 -10
  127. package/dist/interactions.cjs +0 -1
  128. package/dist/interactions.d.cts +0 -182
  129. package/dist/interactions.d.ts +0 -182
  130. package/dist/interactions.js +0 -1
@@ -0,0 +1,126 @@
1
+ import type { Hex } from "viem";
2
+ import type { PrepareSsoParamsType, SsoMetadata } from "../types";
3
+ import { getClientId } from "./clientId";
4
+ import { compressJsonToB64 } from "./compression/compress";
5
+
6
+ export type AppSpecificSsoMetadata = SsoMetadata & {
7
+ name: string;
8
+ css?: string;
9
+ };
10
+
11
+ /**
12
+ * The full SSO params that will be used for compression
13
+ */
14
+ export type FullSsoParams = Omit<PrepareSsoParamsType, "metadata"> & {
15
+ metadata: AppSpecificSsoMetadata;
16
+ merchantId: string;
17
+ clientId: string;
18
+ };
19
+
20
+ /**
21
+ * Generate SSO URL with compressed parameters
22
+ * This mirrors the wallet's getOpenSsoLink() function
23
+ *
24
+ * @param walletUrl - Base wallet URL (e.g., "https://wallet.frak.id")
25
+ * @param params - SSO parameters
26
+ * @param productId - Product identifier
27
+ * @param name - Application name
28
+ * @param css - Optional custom CSS
29
+ * @returns Complete SSO URL ready to open in popup or redirect
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * const ssoUrl = generateSsoUrl(
34
+ * "https://wallet.frak.id",
35
+ * { metadata: { logoUrl: "..." }, directExit: true },
36
+ * "0x123...",
37
+ * "My App"
38
+ * );
39
+ * // Returns: https://wallet.frak.id/sso?p=<compressed_base64>
40
+ * ```
41
+ */
42
+ export function generateSsoUrl(
43
+ walletUrl: string,
44
+ params: PrepareSsoParamsType,
45
+ merchantId: string,
46
+ name: string,
47
+ css?: string,
48
+ clientId?: string
49
+ ): string {
50
+ // Build full params with app-specific metadata
51
+ const fullParams: FullSsoParams = {
52
+ redirectUrl: params.redirectUrl,
53
+ directExit: params.directExit,
54
+ lang: params.lang,
55
+ merchantId,
56
+ metadata: {
57
+ name,
58
+ css,
59
+ logoUrl: params.metadata?.logoUrl,
60
+ homepageLink: params.metadata?.homepageLink,
61
+ },
62
+ clientId: clientId ?? getClientId(),
63
+ };
64
+
65
+ // Compress params to minimal format
66
+ const compressedParam = ssoParamsToCompressed(fullParams);
67
+
68
+ // Encode to base64url
69
+ const compressedString = compressJsonToB64(compressedParam);
70
+
71
+ // Build URL matching wallet's expected format: /sso?p=<compressed>
72
+ const ssoUrl = new URL(walletUrl);
73
+ ssoUrl.pathname = "/sso";
74
+ ssoUrl.searchParams.set("p", compressedString);
75
+
76
+ return ssoUrl.toString();
77
+ }
78
+
79
+ /**
80
+ * Map full sso params to compressed sso params
81
+ * @param params
82
+ */
83
+ function ssoParamsToCompressed(params: FullSsoParams): CompressedSsoData {
84
+ return {
85
+ r: params.redirectUrl,
86
+ cId: params.clientId,
87
+ d: params.directExit,
88
+ l: params.lang,
89
+ m: params.merchantId,
90
+ md: {
91
+ n: params.metadata?.name,
92
+ css: params.metadata?.css,
93
+ l: params.metadata?.logoUrl,
94
+ h: params.metadata?.homepageLink,
95
+ },
96
+ };
97
+ }
98
+
99
+ /**
100
+ * Type of compressed the sso data
101
+ */
102
+ export type CompressedSsoData = {
103
+ // Potential id from backend
104
+ id?: Hex;
105
+ // Client id
106
+ cId: string;
107
+ // redirect url
108
+ r?: string;
109
+ // direct exit
110
+ d?: boolean;
111
+ // language
112
+ l?: "en" | "fr";
113
+ // merchant id
114
+ m: string;
115
+ // metadata
116
+ md: {
117
+ // merchant name
118
+ n: string;
119
+ // custom css
120
+ css?: string;
121
+ // logo
122
+ l?: string;
123
+ // home page link
124
+ h?: string;
125
+ };
126
+ };
@@ -0,0 +1,252 @@
1
+ import type { RpcClient } from "@frak-labs/frame-connector";
2
+ import {
3
+ afterEach,
4
+ beforeEach,
5
+ describe,
6
+ expect,
7
+ it,
8
+ vi,
9
+ } from "../../tests/vitest-fixtures";
10
+ import type { FrakLifecycleEvent } from "../types";
11
+ import type { IFrameRpcSchema } from "../types/rpc";
12
+ import { setupSsoUrlListener } from "./ssoUrlListener";
13
+
14
+ describe("setupSsoUrlListener", () => {
15
+ let mockRpcClient: RpcClient<IFrameRpcSchema, FrakLifecycleEvent>;
16
+ let mockWaitForConnection: Promise<boolean>;
17
+ let originalLocation: Location;
18
+ let originalHistory: History;
19
+ let consoleLogSpy: ReturnType<typeof vi.spyOn>;
20
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
21
+
22
+ beforeEach(() => {
23
+ // Save original values
24
+ originalLocation = window.location;
25
+ originalHistory = window.history;
26
+
27
+ // Mock RPC client
28
+ mockRpcClient = {
29
+ sendLifecycle: vi.fn(),
30
+ } as any;
31
+
32
+ // Mock console methods
33
+ consoleLogSpy = vi.spyOn(console, "log").mockImplementation(() => {});
34
+ consoleErrorSpy = vi
35
+ .spyOn(console, "error")
36
+ .mockImplementation(() => {});
37
+
38
+ // Mock history.replaceState
39
+ window.history.replaceState = vi.fn();
40
+ });
41
+
42
+ afterEach(() => {
43
+ vi.clearAllMocks();
44
+ consoleLogSpy.mockRestore();
45
+ consoleErrorSpy.mockRestore();
46
+
47
+ // Restore original values
48
+ Object.defineProperty(window, "location", {
49
+ value: originalLocation,
50
+ writable: true,
51
+ });
52
+ Object.defineProperty(window, "history", {
53
+ value: originalHistory,
54
+ writable: true,
55
+ });
56
+ });
57
+
58
+ it("should do nothing when window is undefined", () => {
59
+ const originalWindow = global.window;
60
+ // @ts-expect-error - intentionally removing window for test
61
+ delete global.window;
62
+
63
+ setupSsoUrlListener(mockRpcClient, Promise.resolve(true));
64
+
65
+ expect(mockRpcClient.sendLifecycle).not.toHaveBeenCalled();
66
+
67
+ // Restore window
68
+ global.window = originalWindow;
69
+ });
70
+
71
+ it("should do nothing when no SSO parameter in URL", () => {
72
+ Object.defineProperty(window, "location", {
73
+ value: {
74
+ href: "https://example.com/test",
75
+ },
76
+ writable: true,
77
+ });
78
+
79
+ setupSsoUrlListener(mockRpcClient, Promise.resolve(true));
80
+
81
+ expect(mockRpcClient.sendLifecycle).not.toHaveBeenCalled();
82
+ expect(window.history.replaceState).not.toHaveBeenCalled();
83
+ });
84
+
85
+ it("should forward SSO data to iframe when connection is ready", async () => {
86
+ const compressedSso = "compressed-sso-data";
87
+ Object.defineProperty(window, "location", {
88
+ value: {
89
+ href: `https://example.com/test?sso=${compressedSso}`,
90
+ },
91
+ writable: true,
92
+ });
93
+
94
+ mockWaitForConnection = Promise.resolve(true);
95
+
96
+ setupSsoUrlListener(mockRpcClient, mockWaitForConnection);
97
+
98
+ await mockWaitForConnection;
99
+
100
+ // Wait for promise to resolve
101
+ await new Promise((resolve) => setTimeout(resolve, 0));
102
+
103
+ expect(mockRpcClient.sendLifecycle).toHaveBeenCalledWith({
104
+ clientLifecycle: "sso-redirect-complete",
105
+ data: { compressed: compressedSso },
106
+ });
107
+
108
+ expect(consoleLogSpy).toHaveBeenCalledWith(
109
+ "[SSO URL Listener] Forwarded compressed SSO data to iframe"
110
+ );
111
+ });
112
+
113
+ it("should clean URL immediately after detecting SSO parameter", async () => {
114
+ const compressedSso = "compressed-sso-data";
115
+ const originalUrl = `https://example.com/test?sso=${compressedSso}`;
116
+ Object.defineProperty(window, "location", {
117
+ value: {
118
+ href: originalUrl,
119
+ },
120
+ writable: true,
121
+ });
122
+
123
+ mockWaitForConnection = Promise.resolve(true);
124
+
125
+ setupSsoUrlListener(mockRpcClient, mockWaitForConnection);
126
+
127
+ // URL should be cleaned immediately, before connection resolves
128
+ expect(window.history.replaceState).toHaveBeenCalledWith(
129
+ {},
130
+ "",
131
+ "https://example.com/test"
132
+ );
133
+
134
+ expect(consoleLogSpy).toHaveBeenCalledWith(
135
+ "[SSO URL Listener] SSO parameter detected and URL cleaned"
136
+ );
137
+ });
138
+
139
+ it("should handle connection promise rejection", async () => {
140
+ const compressedSso = "compressed-sso-data";
141
+ Object.defineProperty(window, "location", {
142
+ value: {
143
+ href: `https://example.com/test?sso=${compressedSso}`,
144
+ },
145
+ writable: true,
146
+ });
147
+
148
+ const connectionError = new Error("Connection failed");
149
+ mockWaitForConnection = Promise.reject(connectionError);
150
+
151
+ setupSsoUrlListener(mockRpcClient, mockWaitForConnection);
152
+
153
+ await mockWaitForConnection.catch(() => {});
154
+
155
+ // Wait for promise to reject
156
+ await new Promise((resolve) => setTimeout(resolve, 0));
157
+
158
+ expect(mockRpcClient.sendLifecycle).not.toHaveBeenCalled();
159
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
160
+ "[SSO URL Listener] Failed to forward SSO data:",
161
+ connectionError
162
+ );
163
+ });
164
+
165
+ it("should handle URL with multiple parameters", async () => {
166
+ const compressedSso = "compressed-sso-data";
167
+ Object.defineProperty(window, "location", {
168
+ value: {
169
+ href: `https://example.com/test?param1=value1&sso=${compressedSso}&param2=value2`,
170
+ },
171
+ writable: true,
172
+ });
173
+
174
+ mockWaitForConnection = Promise.resolve(true);
175
+
176
+ setupSsoUrlListener(mockRpcClient, mockWaitForConnection);
177
+
178
+ await mockWaitForConnection;
179
+ await new Promise((resolve) => setTimeout(resolve, 0));
180
+
181
+ expect(mockRpcClient.sendLifecycle).toHaveBeenCalledWith({
182
+ clientLifecycle: "sso-redirect-complete",
183
+ data: { compressed: compressedSso },
184
+ });
185
+
186
+ // Should remove only the sso parameter
187
+ expect(window.history.replaceState).toHaveBeenCalledWith(
188
+ {},
189
+ "",
190
+ "https://example.com/test?param1=value1&param2=value2"
191
+ );
192
+ });
193
+
194
+ it("should not process empty SSO parameter", () => {
195
+ Object.defineProperty(window, "location", {
196
+ value: {
197
+ href: "https://example.com/test?sso=",
198
+ },
199
+ writable: true,
200
+ });
201
+
202
+ setupSsoUrlListener(mockRpcClient, Promise.resolve(true));
203
+
204
+ // Empty string is falsy, so it should not process
205
+ expect(window.history.replaceState).not.toHaveBeenCalled();
206
+ expect(mockRpcClient.sendLifecycle).not.toHaveBeenCalled();
207
+ });
208
+
209
+ it("should clean URL even if connection fails", async () => {
210
+ const compressedSso = "compressed-sso-data";
211
+ Object.defineProperty(window, "location", {
212
+ value: {
213
+ href: `https://example.com/test?sso=${compressedSso}`,
214
+ },
215
+ writable: true,
216
+ });
217
+
218
+ const connectionError = new Error("Connection failed");
219
+ mockWaitForConnection = Promise.reject(connectionError);
220
+
221
+ setupSsoUrlListener(mockRpcClient, mockWaitForConnection);
222
+
223
+ // URL should still be cleaned even if connection fails
224
+ expect(window.history.replaceState).toHaveBeenCalledWith(
225
+ {},
226
+ "",
227
+ "https://example.com/test"
228
+ );
229
+
230
+ await mockWaitForConnection.catch(() => {});
231
+ await new Promise((resolve) => setTimeout(resolve, 0));
232
+ });
233
+
234
+ it("should handle URL with hash", () => {
235
+ const compressedSso = "compressed-sso-data";
236
+ Object.defineProperty(window, "location", {
237
+ value: {
238
+ href: `https://example.com/test?sso=${compressedSso}#section`,
239
+ },
240
+ writable: true,
241
+ });
242
+
243
+ setupSsoUrlListener(mockRpcClient, Promise.resolve(true));
244
+
245
+ // Should preserve hash when cleaning URL
246
+ expect(window.history.replaceState).toHaveBeenCalledWith(
247
+ {},
248
+ "",
249
+ "https://example.com/test#section"
250
+ );
251
+ });
252
+ });
@@ -0,0 +1,60 @@
1
+ import type { RpcClient } from "@frak-labs/frame-connector";
2
+ import type { FrakLifecycleEvent } from "../types";
3
+ import type { IFrameRpcSchema } from "../types/rpc";
4
+
5
+ /**
6
+ * Listen for SSO redirect with compressed data in URL
7
+ * Forwards compressed data to iframe via lifecycle event
8
+ * Cleans URL immediately after detection
9
+ *
10
+ * Performance: One-shot URL check, no polling, no re-renders
11
+ *
12
+ * @param rpcClient - RPC client instance to send lifecycle events
13
+ * @param waitForConnection - Promise that resolves when iframe is connected
14
+ */
15
+ export function setupSsoUrlListener(
16
+ rpcClient: RpcClient<IFrameRpcSchema, FrakLifecycleEvent>,
17
+ waitForConnection: Promise<boolean>
18
+ ): void {
19
+ if (typeof window === "undefined") {
20
+ return;
21
+ }
22
+
23
+ // One-shot URL check - no need for MutationObserver or polling
24
+ const url = new URL(window.location.href);
25
+ const compressedSso = url.searchParams.get("sso");
26
+
27
+ // Early return if no SSO parameter
28
+ if (!compressedSso) {
29
+ return;
30
+ }
31
+
32
+ // Forward compressed data directly to iframe (no decompression on SDK side)
33
+ // Iframe will decompress and process
34
+ waitForConnection
35
+ .then(() => {
36
+ // Send lifecycle event with compressed string
37
+ // This is a one-way notification, no response expected
38
+ rpcClient.sendLifecycle({
39
+ clientLifecycle: "sso-redirect-complete",
40
+ data: { compressed: compressedSso },
41
+ });
42
+
43
+ console.log(
44
+ "[SSO URL Listener] Forwarded compressed SSO data to iframe"
45
+ );
46
+ })
47
+ .catch((error) => {
48
+ console.error(
49
+ "[SSO URL Listener] Failed to forward SSO data:",
50
+ error
51
+ );
52
+ });
53
+
54
+ // Clean URL immediately to prevent exposure in browser history
55
+ // Use replaceState to avoid navigation/re-render
56
+ url.searchParams.delete("sso");
57
+ window.history.replaceState({}, "", url.toString());
58
+
59
+ console.log("[SSO URL Listener] SSO parameter detected and URL cleaned");
60
+ }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Tests for trackEvent utility function
3
+ * Tests OpenPanel event tracking wrapper
4
+ */
5
+
6
+ import {
7
+ afterEach,
8
+ beforeEach,
9
+ describe,
10
+ expect,
11
+ it,
12
+ vi,
13
+ } from "../../tests/vitest-fixtures";
14
+ import type { FrakClient } from "../types";
15
+ import { trackEvent } from "./trackEvent";
16
+
17
+ describe("trackEvent", () => {
18
+ let mockClient: FrakClient;
19
+ let consoleDebugSpy: any;
20
+
21
+ beforeEach(() => {
22
+ // Create mock client
23
+ mockClient = {
24
+ openPanel: {
25
+ track: vi.fn(),
26
+ },
27
+ } as unknown as FrakClient;
28
+
29
+ // Spy on console.debug
30
+ consoleDebugSpy = vi
31
+ .spyOn(console, "debug")
32
+ .mockImplementation(() => {});
33
+ });
34
+
35
+ afterEach(() => {
36
+ consoleDebugSpy.mockRestore();
37
+ });
38
+
39
+ describe("success cases", () => {
40
+ it("should track event with client", () => {
41
+ trackEvent(mockClient, "share_button_clicked");
42
+
43
+ expect(mockClient.openPanel?.track).toHaveBeenCalledWith(
44
+ "share_button_clicked",
45
+ {}
46
+ );
47
+ });
48
+
49
+ it("should track event with props", () => {
50
+ const props = { userId: "123", page: "home" };
51
+ trackEvent(mockClient, "wallet_button_clicked", props);
52
+
53
+ expect(mockClient.openPanel?.track).toHaveBeenCalledWith(
54
+ "wallet_button_clicked",
55
+ props
56
+ );
57
+ });
58
+
59
+ it("should track share_modal_error event", () => {
60
+ const props = { error: "Network error" };
61
+ trackEvent(mockClient, "share_modal_error", props);
62
+
63
+ expect(mockClient.openPanel?.track).toHaveBeenCalledWith(
64
+ "share_modal_error",
65
+ props
66
+ );
67
+ });
68
+
69
+ it("should track user_referred_started event", () => {
70
+ trackEvent(mockClient, "user_referred_started");
71
+
72
+ expect(mockClient.openPanel?.track).toHaveBeenCalledWith(
73
+ "user_referred_started",
74
+ {}
75
+ );
76
+ });
77
+
78
+ it("should track user_referred_completed event", () => {
79
+ trackEvent(mockClient, "user_referred_completed");
80
+
81
+ expect(mockClient.openPanel?.track).toHaveBeenCalledWith(
82
+ "user_referred_completed",
83
+ {}
84
+ );
85
+ });
86
+
87
+ it("should track user_referred_error event", () => {
88
+ trackEvent(mockClient, "user_referred_error");
89
+
90
+ expect(mockClient.openPanel?.track).toHaveBeenCalledWith(
91
+ "user_referred_error",
92
+ {}
93
+ );
94
+ });
95
+ });
96
+
97
+ describe("without client", () => {
98
+ it("should not throw when client is undefined", () => {
99
+ expect(() => {
100
+ trackEvent(undefined, "share_button_clicked");
101
+ }).not.toThrow();
102
+ });
103
+
104
+ it("should log debug message when client is undefined", () => {
105
+ trackEvent(undefined, "wallet_button_clicked");
106
+
107
+ expect(consoleDebugSpy).toHaveBeenCalledWith(
108
+ "[Frak] No client provided, skipping event tracking"
109
+ );
110
+ });
111
+
112
+ it("should not call track when client is undefined", () => {
113
+ const trackMock = vi.fn();
114
+ const undefinedClient = undefined;
115
+
116
+ trackEvent(undefinedClient, "share_button_clicked");
117
+
118
+ expect(trackMock).not.toHaveBeenCalled();
119
+ });
120
+ });
121
+
122
+ describe("error handling", () => {
123
+ it("should catch and log errors from track()", () => {
124
+ const error = new Error("Track failed");
125
+ mockClient.openPanel = {
126
+ track: vi.fn().mockImplementation(() => {
127
+ throw error;
128
+ }),
129
+ } as any;
130
+
131
+ expect(() => {
132
+ trackEvent(mockClient, "share_button_clicked");
133
+ }).not.toThrow();
134
+
135
+ expect(consoleDebugSpy).toHaveBeenCalledWith(
136
+ "[Frak] Failed to track event:",
137
+ "share_button_clicked",
138
+ error
139
+ );
140
+ });
141
+
142
+ it("should not throw when openPanel is undefined", () => {
143
+ const clientWithoutPanel = {} as FrakClient;
144
+
145
+ expect(() => {
146
+ trackEvent(clientWithoutPanel, "wallet_button_clicked");
147
+ }).not.toThrow();
148
+ });
149
+ });
150
+
151
+ describe("edge cases", () => {
152
+ it("should handle empty props object", () => {
153
+ trackEvent(mockClient, "share_button_clicked", {});
154
+
155
+ expect(mockClient.openPanel?.track).toHaveBeenCalledWith(
156
+ "share_button_clicked",
157
+ {}
158
+ );
159
+ });
160
+
161
+ it("should handle complex props object", () => {
162
+ const complexProps = {
163
+ userId: "123",
164
+ metadata: {
165
+ page: "home",
166
+ section: "header",
167
+ },
168
+ tags: ["tag1", "tag2"],
169
+ timestamp: Date.now(),
170
+ };
171
+
172
+ trackEvent(mockClient, "user_referred_completed", complexProps);
173
+
174
+ expect(mockClient.openPanel?.track).toHaveBeenCalledWith(
175
+ "user_referred_completed",
176
+ complexProps
177
+ );
178
+ });
179
+ });
180
+ });
@@ -0,0 +1,31 @@
1
+ import type { FrakClient } from "../types";
2
+
3
+ export type FrakEvent =
4
+ | "share_button_clicked"
5
+ | "wallet_button_clicked"
6
+ | "open_in_app_clicked"
7
+ | "open_in_app_login_clicked"
8
+ | "app_not_installed"
9
+ | "share_modal_error"
10
+ | "user_referred_started"
11
+ | "user_referred_completed"
12
+ | "user_referred_error";
13
+
14
+ type EventProps = Record<string, unknown>;
15
+
16
+ export function trackEvent(
17
+ client: FrakClient | undefined,
18
+ event: FrakEvent,
19
+ props: EventProps = {}
20
+ ): void {
21
+ if (!client) {
22
+ console.debug("[Frak] No client provided, skipping event tracking");
23
+ return;
24
+ }
25
+
26
+ try {
27
+ client.openPanel?.track(event, props);
28
+ } catch (e) {
29
+ console.debug("[Frak] Failed to track event:", event, e);
30
+ }
31
+ }
@@ -1,10 +0,0 @@
1
- /*!
2
- * The buffer module from node.js, for the browser.
3
- *
4
- * @author Feross Aboukhadijeh <https://feross.org>
5
- * @license MIT
6
- */
7
-
8
- /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
9
-
10
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
@@ -1 +0,0 @@
1
- "use strict";let __rslib_import_meta_url__="undefined"==typeof document?new(require("url".replace("",""))).URL("file:"+__filename).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href;var __webpack_require__={};__webpack_require__.d=(e,r)=>{for(var t in r)__webpack_require__.o(r,t)&&!__webpack_require__.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})},__webpack_require__.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{PressInteractionEncoder:()=>PressInteractionEncoder,ReferralInteractionEncoder:()=>ReferralInteractionEncoder,RetailInteractionEncoder:()=>RetailInteractionEncoder,PurchaseInteractionEncoder:()=>PurchaseInteractionEncoder,WebShopInteractionEncoder:()=>WebShopInteractionEncoder});let external_viem_namespaceObject=require("viem"),interactionTypes={press:{openArticle:"0xc0a24ffb",readArticle:"0xd5bd0fbe"},dapp:{proofVerifiableStorageUpdate:"0x2ab2aeef",callableVerifiableStorageUpdate:"0xa07da986"},webshop:{open:"0xb311798f"},referral:{referred:"0x010cc3b9",createLink:"0xb2c0f17c"},purchase:{started:"0xd87e90c3",completed:"0x8403aeb4",unsafeCompleted:"0x4d5b14e0"},retail:{customerMeeting:"0x74489004"}},productTypes={dapp:1,press:2,webshop:3,retail:4,referral:30,purchase:31},productTypesMask=Object.entries(productTypes).reduce((e,[r,t])=>(e[r]=BigInt(1)<<BigInt(t),e),{}),PressInteractionEncoder={openArticle({articleId:e}){let r=(0,external_viem_namespaceObject.concatHex)([interactionTypes.press.openArticle,(0,external_viem_namespaceObject.pad)(e,{size:32})]);return{handlerTypeDenominator:(0,external_viem_namespaceObject.toHex)(productTypes.press),interactionData:r}},readArticle({articleId:e}){let r=(0,external_viem_namespaceObject.concatHex)([interactionTypes.press.readArticle,(0,external_viem_namespaceObject.pad)(e,{size:32})]);return{handlerTypeDenominator:(0,external_viem_namespaceObject.toHex)(productTypes.press),interactionData:r}}},ReferralInteractionEncoder={createLink:()=>({handlerTypeDenominator:(0,external_viem_namespaceObject.toHex)(productTypes.referral),interactionData:interactionTypes.referral.createLink}),referred({referrer:e}){let r=(0,external_viem_namespaceObject.concatHex)([interactionTypes.referral.referred,(0,external_viem_namespaceObject.pad)(e,{size:32})]);return{handlerTypeDenominator:(0,external_viem_namespaceObject.toHex)(productTypes.referral),interactionData:r}}},PurchaseInteractionEncoder={startPurchase({purchaseId:e}){let r=(0,external_viem_namespaceObject.concatHex)([interactionTypes.purchase.started,(0,external_viem_namespaceObject.pad)(e,{size:32})]);return{handlerTypeDenominator:(0,external_viem_namespaceObject.toHex)(productTypes.purchase),interactionData:r}},completedPurchase({purchaseId:e,proof:r}){let t=(0,external_viem_namespaceObject.encodeAbiParameters)([{type:"uint256"},{type:"bytes32[]"}],[BigInt(e),r]),a=(0,external_viem_namespaceObject.concatHex)([interactionTypes.purchase.completed,t]);return{handlerTypeDenominator:(0,external_viem_namespaceObject.toHex)(productTypes.purchase),interactionData:a}},unsafeCompletedPurchase({purchaseId:e}){let r=(0,external_viem_namespaceObject.concatHex)([interactionTypes.purchase.unsafeCompleted,(0,external_viem_namespaceObject.pad)(e,{size:32})]);return{handlerTypeDenominator:(0,external_viem_namespaceObject.toHex)(productTypes.purchase),interactionData:r}}},WebShopInteractionEncoder={open:()=>({handlerTypeDenominator:(0,external_viem_namespaceObject.toHex)(productTypes.webshop),interactionData:interactionTypes.webshop.open})},RetailInteractionEncoder={customerMeeting({agencyId:e}){let r=(0,external_viem_namespaceObject.concatHex)([interactionTypes.retail.customerMeeting,(0,external_viem_namespaceObject.pad)(e,{size:32})]);return{handlerTypeDenominator:(0,external_viem_namespaceObject.toHex)(productTypes.retail),interactionData:r}}};for(var __webpack_i__ in exports.PressInteractionEncoder=__webpack_exports__.PressInteractionEncoder,exports.PurchaseInteractionEncoder=__webpack_exports__.PurchaseInteractionEncoder,exports.ReferralInteractionEncoder=__webpack_exports__.ReferralInteractionEncoder,exports.RetailInteractionEncoder=__webpack_exports__.RetailInteractionEncoder,exports.WebShopInteractionEncoder=__webpack_exports__.WebShopInteractionEncoder,__webpack_exports__)-1===["PressInteractionEncoder","PurchaseInteractionEncoder","ReferralInteractionEncoder","RetailInteractionEncoder","WebShopInteractionEncoder"].indexOf(__webpack_i__)&&(exports[__webpack_i__]=__webpack_exports__[__webpack_i__]);Object.defineProperty(exports,"__esModule",{value:!0});