@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,146 @@
1
+ import type { FrakWalletSdkConfig } from "./config";
2
+ import type {
3
+ ModalRpcMetadata,
4
+ ModalRpcStepsInput,
5
+ ModalRpcStepsResultType,
6
+ } from "./rpc/displayModal";
7
+ import type {
8
+ DisplayEmbeddedWalletParamsType,
9
+ DisplayEmbeddedWalletResultType,
10
+ } from "./rpc/embedded";
11
+ import type { SendInteractionParamsType } from "./rpc/interaction";
12
+ import type { GetMerchantInformationReturnType } from "./rpc/merchantInformation";
13
+ import type {
14
+ OpenSsoParamsType,
15
+ OpenSsoReturnType,
16
+ PrepareSsoParamsType,
17
+ PrepareSsoReturnType,
18
+ } from "./rpc/sso";
19
+ import type { WalletStatusReturnType } from "./rpc/walletStatus";
20
+
21
+ /**
22
+ * RPC interface that's used for the iframe communication
23
+ *
24
+ * Define all the methods available within the iFrame RPC client with response type annotations
25
+ *
26
+ * @group RPC Schema
27
+ *
28
+ * @remarks
29
+ * Each method in the schema now includes a ResponseType field that indicates:
30
+ * - "promise": One-shot request that resolves once
31
+ * - "stream": Streaming request that can emit multiple values
32
+ *
33
+ * ### Methods:
34
+ *
35
+ * #### frak_listenToWalletStatus
36
+ * - Params: None
37
+ * - Returns: {@link WalletStatusReturnType}
38
+ * - Response Type: stream (emits updates when wallet status changes)
39
+ *
40
+ * #### frak_displayModal
41
+ * - Params: [requests: {@link ModalRpcStepsInput}, metadata?: {@link ModalRpcMetadata}, configMetadata: {@link FrakWalletSdkConfig}["metadata"]]
42
+ * - Returns: {@link ModalRpcStepsResultType}
43
+ * - Response Type: promise (one-shot)
44
+ *
45
+ * #### frak_sso
46
+ * - Params: [params: {@link OpenSsoParamsType}, name: string, customCss?: string]
47
+ * - Returns: {@link OpenSsoReturnType}
48
+ * - Response Type: promise (one-shot)
49
+ *
50
+ * #### frak_getMerchantInformation
51
+ * - Params: None
52
+ * - Returns: {@link GetMerchantInformationReturnType}
53
+ * - Response Type: promise (one-shot)
54
+ *
55
+ * #### frak_displayEmbeddedWallet
56
+ * - Params: [request: {@link DisplayEmbeddedWalletParamsType}, metadata: {@link FrakWalletSdkConfig}["metadata"]]
57
+ * - Returns: {@link DisplayEmbeddedWalletResultType}
58
+ * - Response Type: promise (one-shot)
59
+ */
60
+ export type IFrameRpcSchema = [
61
+ /**
62
+ * Method used to listen to the wallet status
63
+ * This is a streaming method that emits updates when wallet status changes
64
+ */
65
+ {
66
+ Method: "frak_listenToWalletStatus";
67
+ Parameters?: undefined;
68
+ ReturnType: WalletStatusReturnType;
69
+ },
70
+ /**
71
+ * Method to display a modal with the provided steps
72
+ * This is a one-shot request
73
+ */
74
+ {
75
+ Method: "frak_displayModal";
76
+ Parameters: [
77
+ requests: ModalRpcStepsInput,
78
+ metadata: ModalRpcMetadata | undefined,
79
+ configMetadata: FrakWalletSdkConfig["metadata"],
80
+ ];
81
+ ReturnType: ModalRpcStepsResultType;
82
+ },
83
+ /**
84
+ * Method to prepare SSO (generate URL for popup)
85
+ * Returns the SSO URL that should be opened in a popup
86
+ * Only used for popup flows (not redirect flows)
87
+ */
88
+ {
89
+ Method: "frak_prepareSso";
90
+ Parameters: [
91
+ params: PrepareSsoParamsType,
92
+ name: string,
93
+ customCss?: string,
94
+ ];
95
+ ReturnType: PrepareSsoReturnType;
96
+ },
97
+ /**
98
+ * Method to open/trigger SSO
99
+ * Either triggers redirect (if openInSameWindow/redirectUrl)
100
+ * Or waits for popup completion (if popup mode)
101
+ * This method handles BOTH redirect and popup flows
102
+ */
103
+ {
104
+ Method: "frak_openSso";
105
+ Parameters: [
106
+ params: OpenSsoParamsType,
107
+ name: string,
108
+ customCss?: string,
109
+ ];
110
+ ReturnType: OpenSsoReturnType;
111
+ },
112
+ /**
113
+ * Method to get current merchant information
114
+ * - Is merchant registered?
115
+ * - Does it have running campaign?
116
+ * - Estimated reward on actions
117
+ * This is a one-shot request
118
+ */
119
+ {
120
+ Method: "frak_getMerchantInformation";
121
+ Parameters?: undefined;
122
+ ReturnType: GetMerchantInformationReturnType;
123
+ },
124
+ /**
125
+ * Method to show the embedded wallet, with potential customization
126
+ * This is a one-shot request
127
+ */
128
+ {
129
+ Method: "frak_displayEmbeddedWallet";
130
+ Parameters: [
131
+ request: DisplayEmbeddedWalletParamsType,
132
+ metadata: FrakWalletSdkConfig["metadata"],
133
+ ];
134
+ ReturnType: DisplayEmbeddedWalletResultType;
135
+ },
136
+ /**
137
+ * Method to send interactions (arrival, sharing, custom events)
138
+ * Fire-and-forget method - no return value expected
139
+ * merchantId and clientId are resolved from context
140
+ */
141
+ {
142
+ Method: "frak_sendInteraction";
143
+ Parameters: [interaction: SendInteractionParamsType];
144
+ ReturnType: undefined;
145
+ },
146
+ ];
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Types for arrival tracking and referral attribution
3
+ * @category Tracking
4
+ */
5
+
6
+ import type { Address } from "viem";
7
+
8
+ /**
9
+ * UTM parameters for marketing attribution
10
+ * @category Tracking
11
+ */
12
+ export type UtmParams = {
13
+ source?: string;
14
+ medium?: string;
15
+ campaign?: string;
16
+ term?: string;
17
+ content?: string;
18
+ };
19
+
20
+ /**
21
+ * Parameters for tracking an arrival event
22
+ * @category Tracking
23
+ */
24
+ export type TrackArrivalParams = {
25
+ /**
26
+ * The referrer wallet address (from fCtx URL param)
27
+ */
28
+ referrerWallet?: Address;
29
+ /**
30
+ * The landing page URL (defaults to current page)
31
+ */
32
+ landingUrl?: string;
33
+ /**
34
+ * UTM parameters for marketing attribution
35
+ */
36
+ utmParams?: UtmParams;
37
+ };
38
+
39
+ /**
40
+ * Result from tracking an arrival event
41
+ * @category Tracking
42
+ */
43
+ export type TrackArrivalResult = {
44
+ success: boolean;
45
+ identityGroupId?: string;
46
+ touchpointId?: string;
47
+ error?: string;
48
+ };
49
+
50
+ /**
51
+ * Internal params passed to the trackArrival action
52
+ * Includes merchantId resolved from config or fetch
53
+ * @internal
54
+ */
55
+ export type TrackArrivalInternalParams = TrackArrivalParams & {
56
+ /**
57
+ * The merchant ID (UUID from dashboard)
58
+ */
59
+ merchantId: string;
60
+ };
@@ -0,0 +1,34 @@
1
+ import type { LifecycleMessage, RpcClient } from "@frak-labs/frame-connector";
2
+ import type { ClientLifecycleEvent, IFrameLifecycleEvent } from "./lifecycle";
3
+ import type { IFrameRpcSchema } from "./rpc";
4
+
5
+ /**
6
+ * IFrame transport interface
7
+ */
8
+ export type IFrameTransport = {
9
+ /**
10
+ * Wait for the connection to be established
11
+ */
12
+ waitForConnection: Promise<boolean>;
13
+ /**
14
+ * Wait for the setup to be done
15
+ */
16
+ waitForSetup: Promise<void>;
17
+ /**
18
+ * Function used to perform a single request via the iframe transport
19
+ */
20
+ request: RpcClient<IFrameRpcSchema, LifecycleMessage>["request"];
21
+ /**
22
+ * Function used to listen to a request response via the iframe transport
23
+ */
24
+ listenerRequest: RpcClient<IFrameRpcSchema, LifecycleMessage>["listen"];
25
+ /**
26
+ * Function used to destroy the iframe transport
27
+ */
28
+ destroy: () => Promise<void>;
29
+ };
30
+
31
+ /**
32
+ * Represent an iframe event
33
+ */
34
+ export type FrakLifecycleEvent = IFrameLifecycleEvent | ClientLifecycleEvent;
@@ -0,0 +1,407 @@
1
+ /**
2
+ * Tests for FrakContextManager utility
3
+ * Tests Frak context compression, URL parsing, and management
4
+ */
5
+
6
+ import { mockWindowHistory } from "@frak-labs/test-foundation";
7
+ import type { Address } from "viem";
8
+ import {
9
+ afterEach,
10
+ beforeEach,
11
+ describe,
12
+ expect,
13
+ it,
14
+ vi,
15
+ } from "../../tests/vitest-fixtures";
16
+ import type { FrakContext } from "../types";
17
+ import { FrakContextManager } from "./FrakContext";
18
+
19
+ describe("FrakContextManager", () => {
20
+ let consoleErrorSpy: any;
21
+
22
+ beforeEach(() => {
23
+ consoleErrorSpy = vi
24
+ .spyOn(console, "error")
25
+ .mockImplementation(() => {});
26
+ });
27
+
28
+ afterEach(() => {
29
+ consoleErrorSpy.mockRestore();
30
+ });
31
+
32
+ describe("compress", () => {
33
+ it("should compress context with referrer address", () => {
34
+ const context: Partial<FrakContext> = {
35
+ r: "0x1234567890123456789012345678901234567890" as Address,
36
+ };
37
+
38
+ const result = FrakContextManager.compress(context);
39
+
40
+ expect(result).toBeDefined();
41
+ expect(typeof result).toBe("string");
42
+ expect(result?.length).toBeGreaterThan(0);
43
+ // Base64url should not contain +, /, or =
44
+ expect(result).not.toMatch(/[+/=]/);
45
+ });
46
+
47
+ it("should return undefined when context has no referrer", () => {
48
+ const context: Partial<FrakContext> = {};
49
+
50
+ const result = FrakContextManager.compress(context);
51
+
52
+ expect(result).toBeUndefined();
53
+ });
54
+
55
+ it("should return undefined when context is undefined", () => {
56
+ const result = FrakContextManager.compress(undefined);
57
+
58
+ expect(result).toBeUndefined();
59
+ });
60
+
61
+ it("should handle compression errors gracefully", () => {
62
+ const invalidContext = {
63
+ r: "invalid-address" as Address,
64
+ };
65
+
66
+ const result = FrakContextManager.compress(invalidContext);
67
+
68
+ expect(consoleErrorSpy).toHaveBeenCalled();
69
+ expect(result).toBeUndefined();
70
+ });
71
+ });
72
+
73
+ describe("decompress", () => {
74
+ it("should decompress valid base64url context", () => {
75
+ // First compress a context
76
+ const originalContext: FrakContext = {
77
+ r: "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd" as Address,
78
+ };
79
+ const compressed = FrakContextManager.compress(originalContext);
80
+
81
+ // Then decompress it
82
+ const result = FrakContextManager.decompress(compressed);
83
+
84
+ expect(result).toBeDefined();
85
+ expect(result?.r).toBe(
86
+ "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd"
87
+ );
88
+ });
89
+
90
+ it("should return undefined for empty string", () => {
91
+ const result = FrakContextManager.decompress("");
92
+
93
+ expect(result).toBeUndefined();
94
+ });
95
+
96
+ it("should return undefined for undefined input", () => {
97
+ const result = FrakContextManager.decompress(undefined);
98
+
99
+ expect(result).toBeUndefined();
100
+ });
101
+
102
+ it("should handle decompression errors gracefully", () => {
103
+ const result = FrakContextManager.decompress(
104
+ "invalid-base64url!@#"
105
+ );
106
+
107
+ expect(consoleErrorSpy).toHaveBeenCalled();
108
+ expect(result).toBeUndefined();
109
+ });
110
+
111
+ it("should round-trip compress and decompress", () => {
112
+ const original: FrakContext = {
113
+ r: "0x1234567890123456789012345678901234567890" as Address,
114
+ };
115
+
116
+ const compressed = FrakContextManager.compress(original);
117
+ const decompressed = FrakContextManager.decompress(compressed);
118
+
119
+ expect(decompressed).toEqual(original);
120
+ });
121
+ });
122
+
123
+ describe("parse", () => {
124
+ it("should parse URL with fCtx parameter", () => {
125
+ const context: FrakContext = {
126
+ r: "0x1234567890123456789012345678901234567890" as Address,
127
+ };
128
+ const compressed = FrakContextManager.compress(context);
129
+ const url = `https://example.com?fCtx=${compressed}`;
130
+
131
+ const result = FrakContextManager.parse({ url });
132
+
133
+ expect(result).toBeDefined();
134
+ expect(result?.r).toBe(
135
+ "0x1234567890123456789012345678901234567890"
136
+ );
137
+ });
138
+
139
+ it("should return null for URL without fCtx parameter", () => {
140
+ const url = "https://example.com?other=param";
141
+
142
+ const result = FrakContextManager.parse({ url });
143
+
144
+ expect(result).toBeNull();
145
+ });
146
+
147
+ it("should return null for empty URL", () => {
148
+ const result = FrakContextManager.parse({ url: "" });
149
+
150
+ expect(result).toBeNull();
151
+ });
152
+
153
+ it("should parse URL with multiple parameters", () => {
154
+ const context: FrakContext = {
155
+ r: "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd" as Address,
156
+ };
157
+ const compressed = FrakContextManager.compress(context);
158
+ const url = `https://example.com?foo=bar&fCtx=${compressed}&baz=qux`;
159
+
160
+ const result = FrakContextManager.parse({ url });
161
+
162
+ expect(result).toBeDefined();
163
+ expect(result?.r).toBe(
164
+ "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd"
165
+ );
166
+ });
167
+
168
+ it("should return undefined for malformed fCtx parameter", () => {
169
+ // Use a string that will fail base64url decoding
170
+ const url = "https://example.com?fCtx=!!!invalid!!!";
171
+
172
+ const result = FrakContextManager.parse({ url });
173
+
174
+ // Should handle the error and return undefined
175
+ expect(result).toBeUndefined();
176
+ });
177
+ });
178
+
179
+ describe("update", () => {
180
+ it("should add fCtx to URL without existing context", () => {
181
+ const url = "https://example.com";
182
+ const context: FrakContext = {
183
+ r: "0x1234567890123456789012345678901234567890" as Address,
184
+ };
185
+
186
+ const result = FrakContextManager.update({ url, context });
187
+
188
+ expect(result).toBeDefined();
189
+ expect(result).toContain("fCtx=");
190
+ expect(result).toContain("https://example.com");
191
+ });
192
+
193
+ it("should merge with existing context in URL", () => {
194
+ const existingContext: FrakContext = {
195
+ r: "0x1234567890123456789012345678901234567890" as Address,
196
+ };
197
+ const compressed = FrakContextManager.compress(existingContext);
198
+ const url = `https://example.com?fCtx=${compressed}`;
199
+
200
+ const newContext: FrakContext = {
201
+ r: "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd" as Address,
202
+ };
203
+
204
+ const result = FrakContextManager.update({
205
+ url,
206
+ context: newContext,
207
+ });
208
+
209
+ expect(result).toBeDefined();
210
+ expect(result).toContain("fCtx=");
211
+
212
+ // Parse the result and check it has the new referrer
213
+ const parsedResult = FrakContextManager.parse({ url: result! });
214
+ expect(parsedResult?.r).toBe(
215
+ "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd"
216
+ );
217
+ });
218
+
219
+ it("should return null when URL is undefined", () => {
220
+ const context: FrakContext = {
221
+ r: "0x1234567890123456789012345678901234567890" as Address,
222
+ };
223
+
224
+ const result = FrakContextManager.update({
225
+ url: undefined,
226
+ context,
227
+ });
228
+
229
+ expect(result).toBeNull();
230
+ });
231
+
232
+ it("should return null when context has no referrer", () => {
233
+ const url = "https://example.com";
234
+ const context: Partial<FrakContext> = {};
235
+
236
+ const result = FrakContextManager.update({ url, context });
237
+
238
+ expect(result).toBeNull();
239
+ });
240
+
241
+ it("should preserve other URL parameters", () => {
242
+ const url = "https://example.com?foo=bar&baz=qux";
243
+ const context: FrakContext = {
244
+ r: "0x1234567890123456789012345678901234567890" as Address,
245
+ };
246
+
247
+ const result = FrakContextManager.update({ url, context });
248
+
249
+ expect(result).toContain("foo=bar");
250
+ expect(result).toContain("baz=qux");
251
+ expect(result).toContain("fCtx=");
252
+ });
253
+
254
+ it("should preserve URL hash", () => {
255
+ const url = "https://example.com#section";
256
+ const context: FrakContext = {
257
+ r: "0x1234567890123456789012345678901234567890" as Address,
258
+ };
259
+
260
+ const result = FrakContextManager.update({ url, context });
261
+
262
+ expect(result).toContain("#section");
263
+ expect(result).toContain("fCtx=");
264
+ });
265
+ });
266
+
267
+ describe("remove", () => {
268
+ it("should remove fCtx parameter from URL", () => {
269
+ const context: FrakContext = {
270
+ r: "0x1234567890123456789012345678901234567890" as Address,
271
+ };
272
+ const compressed = FrakContextManager.compress(context);
273
+ const url = `https://example.com?fCtx=${compressed}`;
274
+
275
+ const result = FrakContextManager.remove(url);
276
+
277
+ expect(result).toBe("https://example.com/");
278
+ expect(result).not.toContain("fCtx");
279
+ });
280
+
281
+ it("should preserve other parameters when removing fCtx", () => {
282
+ const context: FrakContext = {
283
+ r: "0x1234567890123456789012345678901234567890" as Address,
284
+ };
285
+ const compressed = FrakContextManager.compress(context);
286
+ const url = `https://example.com?foo=bar&fCtx=${compressed}&baz=qux`;
287
+
288
+ const result = FrakContextManager.remove(url);
289
+
290
+ expect(result).toContain("foo=bar");
291
+ expect(result).toContain("baz=qux");
292
+ expect(result).not.toContain("fCtx");
293
+ });
294
+
295
+ it("should handle URL without fCtx parameter", () => {
296
+ const url = "https://example.com?foo=bar";
297
+
298
+ const result = FrakContextManager.remove(url);
299
+
300
+ expect(result).toContain("foo=bar");
301
+ expect(result).not.toContain("fCtx");
302
+ });
303
+
304
+ it("should preserve URL hash", () => {
305
+ const url = "https://example.com?fCtx=test#section";
306
+
307
+ const result = FrakContextManager.remove(url);
308
+
309
+ expect(result).toContain("#section");
310
+ expect(result).not.toContain("fCtx");
311
+ });
312
+ });
313
+
314
+ describe("replaceUrl", () => {
315
+ const mockAddress =
316
+ "0x1234567890123456789012345678901234567890" as Address;
317
+
318
+ beforeEach(() => {
319
+ // Mock window.location.href
320
+ Object.defineProperty(window, "location", {
321
+ writable: true,
322
+ value: {
323
+ href: "https://example.com/page",
324
+ },
325
+ });
326
+
327
+ // Mock window.history using our test utility
328
+ mockWindowHistory(vi);
329
+ });
330
+
331
+ it("should update window.location with context", () => {
332
+ const url = "https://example.com/test";
333
+ const context: FrakContext = { r: mockAddress };
334
+
335
+ FrakContextManager.replaceUrl({ url, context });
336
+
337
+ const historySpy = vi.mocked(window.history.replaceState);
338
+ expect(historySpy).toHaveBeenCalledTimes(1);
339
+ expect(historySpy).toHaveBeenCalledWith(
340
+ null,
341
+ "",
342
+ expect.stringContaining("fCtx=")
343
+ );
344
+
345
+ const calledUrl = historySpy.mock.calls[0]?.[2] as string;
346
+ expect(calledUrl).toContain("https://example.com/test");
347
+ expect(calledUrl).toContain("fCtx=");
348
+ });
349
+
350
+ it("should use provided URL instead of window.location.href", () => {
351
+ const customUrl = "https://custom.com/path";
352
+ const context: FrakContext = { r: mockAddress };
353
+
354
+ FrakContextManager.replaceUrl({ url: customUrl, context });
355
+
356
+ const historySpy = vi.mocked(window.history.replaceState);
357
+ const calledUrl = historySpy.mock.calls[0]?.[2] as string;
358
+
359
+ expect(calledUrl).toContain("https://custom.com/path");
360
+ expect(calledUrl).not.toContain("https://example.com/page");
361
+ });
362
+
363
+ it("should remove fCtx when context is null", () => {
364
+ const url = "https://example.com/test?fCtx=existing";
365
+
366
+ FrakContextManager.replaceUrl({ url, context: null });
367
+
368
+ const historySpy = vi.mocked(window.history.replaceState);
369
+ expect(historySpy).toHaveBeenCalledTimes(1);
370
+
371
+ const calledUrl = historySpy.mock.calls[0]?.[2] as string;
372
+ expect(calledUrl).not.toContain("fCtx=");
373
+ });
374
+
375
+ it("should not call replaceState when context has no referrer", () => {
376
+ const url = "https://example.com/test";
377
+ const context: Partial<FrakContext> = {};
378
+
379
+ FrakContextManager.replaceUrl({ url, context });
380
+
381
+ const historySpy = vi.mocked(window.history.replaceState);
382
+ expect(historySpy).not.toHaveBeenCalled();
383
+ });
384
+
385
+ it("should handle missing window gracefully", () => {
386
+ // Remove window.location to simulate missing window
387
+ Object.defineProperty(window, "location", {
388
+ writable: true,
389
+ value: undefined,
390
+ });
391
+
392
+ const url = "https://example.com/test";
393
+ const context: FrakContext = { r: mockAddress };
394
+
395
+ // Should not throw error
396
+ expect(() => {
397
+ FrakContextManager.replaceUrl({ url, context });
398
+ }).not.toThrow();
399
+
400
+ const historySpy = vi.mocked(window.history.replaceState);
401
+ expect(historySpy).not.toHaveBeenCalled();
402
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
403
+ "No window found, can't update context"
404
+ );
405
+ });
406
+ });
407
+ });