@frak-labs/core-sdk 1.1.3 → 1.1.5-beta.5b65e64f

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 (82) hide show
  1. package/cdn/bundle.js +1 -1
  2. package/dist/actions-Cyn4asew.cjs +2 -0
  3. package/dist/actions-Cyn4asew.cjs.map +1 -0
  4. package/dist/actions-DtPVuk2e.js +2 -0
  5. package/dist/actions-DtPVuk2e.js.map +1 -0
  6. package/dist/actions.cjs +1 -1
  7. package/dist/actions.d.cts +3 -3
  8. package/dist/actions.d.ts +3 -3
  9. package/dist/actions.js +1 -1
  10. package/dist/bundle.cjs +1 -1
  11. package/dist/bundle.d.cts +5 -4
  12. package/dist/bundle.d.ts +5 -4
  13. package/dist/bundle.js +1 -1
  14. package/dist/frakContext-Bgidv-Se.js +2 -0
  15. package/dist/frakContext-Bgidv-Se.js.map +1 -0
  16. package/dist/frakContext-CeVlWFcX.cjs +2 -0
  17. package/dist/frakContext-CeVlWFcX.cjs.map +1 -0
  18. package/dist/getCurrencyAmountKey-DQcwjJiB.js +2 -0
  19. package/dist/getCurrencyAmountKey-DQcwjJiB.js.map +1 -0
  20. package/dist/getCurrencyAmountKey-h2eOiYzv.cjs +2 -0
  21. package/dist/getCurrencyAmountKey-h2eOiYzv.cjs.map +1 -0
  22. package/dist/{index-lcImYQyL.d.ts → index-BCoPwxjq.d.cts} +4 -2
  23. package/dist/{index-C5pP_9We.d.cts → index-CiHjUnfc.d.ts} +43 -6
  24. package/dist/{index-DrYZwIjb.d.ts → index-D25z5B9K.d.cts} +43 -6
  25. package/dist/{index-DR4n-QOe.d.cts → index-trhAN7q9.d.ts} +4 -2
  26. package/dist/index.cjs +1 -1
  27. package/dist/index.d.cts +4 -3
  28. package/dist/index.d.ts +4 -3
  29. package/dist/index.js +1 -1
  30. package/dist/merchantInformation--tLnowAN.d.ts +344 -0
  31. package/dist/merchantInformation-BSuahpjl.d.cts +344 -0
  32. package/dist/{openSso-BErs7_Bg.d.cts → openSso-CENLMWJx.d.ts} +4 -279
  33. package/dist/{openSso-DRLH4D9a.d.ts → openSso-CKvkAGts.d.cts} +4 -279
  34. package/dist/rewards.cjs +2 -0
  35. package/dist/rewards.cjs.map +1 -0
  36. package/dist/rewards.d.cts +101 -0
  37. package/dist/rewards.d.ts +101 -0
  38. package/dist/rewards.js +2 -0
  39. package/dist/rewards.js.map +1 -0
  40. package/dist/src-BXtnEE3a.js +2 -0
  41. package/dist/src-BXtnEE3a.js.map +1 -0
  42. package/dist/src-TpX-7MwJ.cjs +2 -0
  43. package/dist/src-TpX-7MwJ.cjs.map +1 -0
  44. package/package.json +16 -3
  45. package/src/actions/getMerchantInformation.test.ts +2 -0
  46. package/src/actions/referral/processReferral.test.ts +4 -4
  47. package/src/actions/referral/processReferral.ts +4 -4
  48. package/src/clients/createIFrameFrakClient.ts +7 -7
  49. package/src/clients/transports/iframeLifecycleManager.ts +5 -21
  50. package/src/config/sdkConfigStore.ts +6 -3
  51. package/src/context/frakContext.test.ts +55 -0
  52. package/src/context/frakContext.ts +13 -2
  53. package/src/index.ts +8 -0
  54. package/src/rewards/conditions.test.ts +60 -0
  55. package/src/rewards/conditions.ts +72 -0
  56. package/src/rewards/example.test.ts +92 -0
  57. package/src/rewards/example.ts +57 -0
  58. package/src/rewards/format.test.ts +143 -0
  59. package/src/rewards/format.ts +81 -0
  60. package/src/rewards/index.ts +27 -0
  61. package/src/rewards/select.test.ts +212 -0
  62. package/src/rewards/select.ts +132 -0
  63. package/src/rewards/value.test.ts +89 -0
  64. package/src/rewards/value.ts +73 -0
  65. package/src/types/index.ts +6 -0
  66. package/src/types/rpc/merchantInformation.ts +120 -13
  67. package/src/utils/analytics/events/lifecycle.ts +1 -1
  68. package/src/utils/analytics/events/referral.ts +3 -3
  69. package/src/utils/browser/deepLinkWithFallback.ts +4 -1
  70. package/src/utils/browser/inAppBrowser.ts +2 -2
  71. package/src/utils/cache/withCache.ts +30 -11
  72. package/src/utils/iframe/iframeHelper.test.ts +39 -0
  73. package/src/utils/iframe/iframeHelper.ts +31 -2
  74. package/src/utils/index.ts +5 -0
  75. package/src/utils/url/queryParams.test.ts +85 -0
  76. package/src/utils/url/queryParams.ts +57 -0
  77. package/dist/actions-D5rNeJC0.js +0 -1
  78. package/dist/actions-gmdNZvNh.cjs +0 -1
  79. package/dist/frakContext-Cfp7sSid.cjs +0 -1
  80. package/dist/frakContext-UEOk9Bk4.js +0 -1
  81. package/dist/src-BEMVYU3J.js +0 -1
  82. package/dist/src-C9inMs4I.cjs +0 -1
@@ -40,7 +40,10 @@ export function isChromiumAndroid(): boolean {
40
40
  *
41
41
  * Format: intent://path#Intent;scheme=<scheme>;end
42
42
  */
43
- const DEEP_LINK_SCHEME_NAME = DEEP_LINK_SCHEME.replace("://", "");
43
+ const DEEP_LINK_SCHEME_NAME = /* @__PURE__ */ DEEP_LINK_SCHEME.replace(
44
+ "://",
45
+ ""
46
+ );
44
47
 
45
48
  export function toAndroidIntentUrl(deepLink: string): string {
46
49
  // Extract everything after the scheme (e.g. "frakwallet://" or "frakwallet-dev://")
@@ -14,7 +14,7 @@ function checkIsIOS(): boolean {
14
14
  /**
15
15
  * Whether the current device runs iOS (including iPadOS 13+).
16
16
  */
17
- export const isIOS: boolean = checkIsIOS();
17
+ export const isIOS: boolean = /* @__PURE__ */ checkIsIOS();
18
18
 
19
19
  /**
20
20
  * Check if the current device is a mobile device (iOS, iPadOS, Android,
@@ -48,7 +48,7 @@ function checkInAppBrowser(): boolean {
48
48
  * Whether the current browser is a social media in-app browser
49
49
  * (Instagram, Facebook).
50
50
  */
51
- export const isInAppBrowser: boolean = checkInAppBrowser();
51
+ export const isInAppBrowser: boolean = /* @__PURE__ */ checkInAppBrowser();
52
52
 
53
53
  /**
54
54
  * Redirect to external browser from in-app WebView.
@@ -5,20 +5,35 @@ type CacheEntry<TData> = {
5
5
  created: number;
6
6
  };
7
7
 
8
- /** Global cache for in-flight promises (dedup concurrent calls) */
9
- const promiseCache = new LruMap<Promise<unknown>>(1024);
10
-
11
- /** Global cache for resolved responses (TTL-based) */
12
- const responseCache = new LruMap<CacheEntry<unknown>>(1024);
13
-
14
8
  /** Default cache time: 30 seconds */
15
9
  export const DEFAULT_CACHE_TIME = 30_000;
16
10
 
17
11
  /** Short negative cache to avoid flooding on transient failures */
18
12
  const NEGATIVE_CACHE_TIME = 1_000;
19
13
 
20
- /** Tracks recently failed keys to avoid request floods */
21
- const failureCache = new LruMap<number>(1024);
14
+ type CacheStore = {
15
+ /** In-flight promises (dedup concurrent calls) */
16
+ promiseCache: LruMap<Promise<unknown>>;
17
+ /** Resolved responses (TTL-based) */
18
+ responseCache: LruMap<CacheEntry<unknown>>;
19
+ /** Recently failed keys to avoid request floods */
20
+ failureCache: LruMap<number>;
21
+ };
22
+
23
+ // Allocate the three LruMaps lazily on first use rather than at module init.
24
+ // Eager top-level allocation is a side effect at odds with `sideEffects: false`
25
+ // and runs for every consumer that merely imports this module.
26
+ let store: CacheStore | undefined;
27
+ function caches(): CacheStore {
28
+ if (!store) {
29
+ store = {
30
+ promiseCache: new LruMap<Promise<unknown>>(1024),
31
+ responseCache: new LruMap<CacheEntry<unknown>>(1024),
32
+ failureCache: new LruMap<number>(1024),
33
+ };
34
+ }
35
+ return store;
36
+ }
22
37
 
23
38
  type WithCacheOptions = {
24
39
  /** The key to cache the data against */
@@ -47,6 +62,7 @@ export async function withCache<TData>(
47
62
  fn: () => Promise<TData>,
48
63
  { cacheKey, cacheTime = DEFAULT_CACHE_TIME }: WithCacheOptions
49
64
  ): Promise<TData> {
65
+ const { promiseCache, responseCache, failureCache } = caches();
50
66
  // Check response cache — return immediately if fresh
51
67
  if (cacheTime > 0) {
52
68
  const cached = responseCache.get(cacheKey) as
@@ -101,11 +117,13 @@ export function getCache(cacheKey: string) {
101
117
  return {
102
118
  /** Clear both the pending promise and the cached response */
103
119
  clear: () => {
120
+ const { promiseCache, responseCache } = caches();
104
121
  promiseCache.delete(cacheKey);
105
122
  responseCache.delete(cacheKey);
106
123
  },
107
124
  /** Check if a non-expired response exists */
108
125
  has: (cacheTime: number = DEFAULT_CACHE_TIME) => {
126
+ const { responseCache } = caches();
109
127
  const cached = responseCache.get(cacheKey);
110
128
  if (!cached) return false;
111
129
  return Date.now() - cached.created < cacheTime;
@@ -118,7 +136,8 @@ export function getCache(cacheKey: string) {
118
136
  * Called automatically when the client is destroyed.
119
137
  */
120
138
  export function clearAllCache() {
121
- promiseCache.clear();
122
- responseCache.clear();
123
- failureCache.clear();
139
+ if (!store) return;
140
+ store.promiseCache.clear();
141
+ store.responseCache.clear();
142
+ store.failureCache.clear();
124
143
  }
@@ -185,6 +185,45 @@ describe("iframeHelper", () => {
185
185
 
186
186
  expect(mockIframe.style.zIndex).toBe("2000001");
187
187
  });
188
+
189
+ it("should append #preload=... when config.preload is non-empty", async () => {
190
+ const config: FrakWalletSdkConfig = {
191
+ metadata: { name: "Test" },
192
+ preload: ["sharing"],
193
+ };
194
+
195
+ await createIframe({ config });
196
+
197
+ expect(mockIframe.src).toBe(
198
+ "https://wallet.frak.id/listener?clientId=mock-client-id-for-test#preload=sharing"
199
+ );
200
+ });
201
+
202
+ it("should join multiple preload options with comma", async () => {
203
+ const config: FrakWalletSdkConfig = {
204
+ metadata: { name: "Test" },
205
+ preload: ["sharing", "modal"],
206
+ };
207
+
208
+ await createIframe({ config });
209
+
210
+ expect(mockIframe.src).toBe(
211
+ "https://wallet.frak.id/listener?clientId=mock-client-id-for-test#preload=sharing,modal"
212
+ );
213
+ });
214
+
215
+ it("should omit the preload hash when config.preload is an empty array", async () => {
216
+ const config: FrakWalletSdkConfig = {
217
+ metadata: { name: "Test" },
218
+ preload: [],
219
+ };
220
+
221
+ await createIframe({ config });
222
+
223
+ expect(mockIframe.src).toBe(
224
+ "https://wallet.frak.id/listener?clientId=mock-client-id-for-test"
225
+ );
226
+ });
188
227
  });
189
228
 
190
229
  describe("changeIframeVisibility", () => {
@@ -1,6 +1,6 @@
1
1
  import { getBackendUrl } from "../../config/backendUrl";
2
2
  import { getClientId } from "../../config/clientId";
3
- import type { FrakWalletSdkConfig } from "../../types";
3
+ import type { FrakWalletSdkConfig, ListenerPreloadOption } from "../../types";
4
4
 
5
5
  /**
6
6
  * Base props for the iframe
@@ -64,7 +64,11 @@ export function createIframe({
64
64
  preconnect(walletUrl);
65
65
  preconnect(getBackendUrl(walletUrl));
66
66
 
67
- iframe.src = `${walletUrl}/listener?clientId=${encodeURIComponent(clientId)}`;
67
+ iframe.src = buildListenerUrl({
68
+ walletUrl,
69
+ clientId,
70
+ preload: config?.preload,
71
+ });
68
72
 
69
73
  return new Promise((resolve) => {
70
74
  iframe.addEventListener("load", () => resolve(iframe));
@@ -72,6 +76,31 @@ export function createIframe({
72
76
  });
73
77
  }
74
78
 
79
+ /**
80
+ * Build the listener iframe URL.
81
+ *
82
+ * Query params:
83
+ * - `clientId` — anonymous SDK client identifier used for funnel joining.
84
+ *
85
+ * Hash params (consumed by `apps/listener/app/bootstrap.ts#setupPreloadHints`):
86
+ * - `preload=modal,sharing` — idle-warms the matching Ring 1 + Ring 2 chunks.
87
+ * Skipped entirely when no preload hints are provided so the listener
88
+ * doesn't pay for warm-ups that nobody asked for.
89
+ */
90
+ function buildListenerUrl({
91
+ walletUrl,
92
+ clientId,
93
+ preload,
94
+ }: {
95
+ walletUrl: string;
96
+ clientId: string;
97
+ preload?: ListenerPreloadOption[];
98
+ }): string {
99
+ const base = `${walletUrl}/listener?clientId=${encodeURIComponent(clientId)}`;
100
+ if (!preload || preload.length === 0) return base;
101
+ return `${base}#preload=${preload.join(",")}`;
102
+ }
103
+
75
104
  /**
76
105
  * Change the visibility of the given iframe
77
106
  * @ignore
@@ -47,3 +47,8 @@ export {
47
47
  type FullSsoParams,
48
48
  generateSsoUrl,
49
49
  } from "./sso/sso";
50
+ // URL query params (case-insensitive key matching)
51
+ export {
52
+ deleteQueryParamCaseInsensitive,
53
+ getQueryParamCaseInsensitive,
54
+ } from "./url/queryParams";
@@ -0,0 +1,85 @@
1
+ import { describe, expect, it } from "../../../tests/vitest-fixtures";
2
+ import {
3
+ deleteQueryParamCaseInsensitive,
4
+ getQueryParamCaseInsensitive,
5
+ } from "./queryParams";
6
+
7
+ describe("getQueryParamCaseInsensitive", () => {
8
+ it("reads an exact-case key", () => {
9
+ const params = new URLSearchParams("frakAction=share");
10
+ expect(getQueryParamCaseInsensitive(params, "frakAction")).toBe(
11
+ "share"
12
+ );
13
+ });
14
+
15
+ it("reads a fully lowercased key (email/browser mangling)", () => {
16
+ const params = new URLSearchParams("frakaction=share");
17
+ expect(getQueryParamCaseInsensitive(params, "frakAction")).toBe(
18
+ "share"
19
+ );
20
+ });
21
+
22
+ it("reads an uppercased key", () => {
23
+ const params = new URLSearchParams("FRAKACTION=share");
24
+ expect(getQueryParamCaseInsensitive(params, "frakAction")).toBe(
25
+ "share"
26
+ );
27
+ });
28
+
29
+ it("reads a mixed-case key regardless of the lookup casing", () => {
30
+ const params = new URLSearchParams("FrAkAcTiOn=share");
31
+ expect(getQueryParamCaseInsensitive(params, "FRAKACTION")).toBe(
32
+ "share"
33
+ );
34
+ });
35
+
36
+ it("returns null when no key matches", () => {
37
+ const params = new URLSearchParams("other=1");
38
+ expect(getQueryParamCaseInsensitive(params, "frakAction")).toBeNull();
39
+ });
40
+
41
+ it("prefers the exact-case key over a case-folded duplicate", () => {
42
+ const params = new URLSearchParams("fctx=stale&fCtx=canonical");
43
+ expect(getQueryParamCaseInsensitive(params, "fCtx")).toBe("canonical");
44
+ });
45
+
46
+ it("falls back to the first case-folded variant when no exact match", () => {
47
+ const params = new URLSearchParams("fctx=first&FCTX=second");
48
+ expect(getQueryParamCaseInsensitive(params, "fCtx")).toBe("first");
49
+ });
50
+
51
+ it("preserves the value casing (only the key is normalized)", () => {
52
+ const params = new URLSearchParams("placement=Klaviyo-Post-Purchase");
53
+ expect(getQueryParamCaseInsensitive(params, "PLACEMENT")).toBe(
54
+ "Klaviyo-Post-Purchase"
55
+ );
56
+ });
57
+ });
58
+
59
+ describe("deleteQueryParamCaseInsensitive", () => {
60
+ it("deletes an exact-case key", () => {
61
+ const params = new URLSearchParams("frakAction=share&keep=me");
62
+ deleteQueryParamCaseInsensitive(params, "frakAction");
63
+ expect(params.toString()).toBe("keep=me");
64
+ });
65
+
66
+ it("deletes a lowercased key", () => {
67
+ const params = new URLSearchParams("frakaction=share&keep=me");
68
+ deleteQueryParamCaseInsensitive(params, "frakAction");
69
+ expect(params.toString()).toBe("keep=me");
70
+ });
71
+
72
+ it("deletes every case variant of the key", () => {
73
+ const params = new URLSearchParams(
74
+ "frakAction=a&frakaction=b&FRAKACTION=c&keep=me"
75
+ );
76
+ deleteQueryParamCaseInsensitive(params, "frakAction");
77
+ expect(params.toString()).toBe("keep=me");
78
+ });
79
+
80
+ it("is a no-op when the key is absent", () => {
81
+ const params = new URLSearchParams("keep=me");
82
+ deleteQueryParamCaseInsensitive(params, "frakAction");
83
+ expect(params.toString()).toBe("keep=me");
84
+ });
85
+ });
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Case-insensitive helpers for reading URL query parameters.
3
+ *
4
+ * Some email tools (Klaviyo, Omnisend, Customer.io …) and a few browsers
5
+ * lowercase the entire URL before the recipient opens it, so a mixed-case key
6
+ * authored as `frakAction` or `fCtx` can arrive as `frakaction` / `fctx`. A
7
+ * plain `searchParams.get("frakAction")` would miss it. Matching the key
8
+ * ignoring case keeps UI-triggering and referral params working regardless of
9
+ * how the link was mangled in transit.
10
+ *
11
+ * Note: only the key is normalised. An encoded value (base64url, tokens) is not
12
+ * recoverable if the same channel also lowercased the value itself.
13
+ */
14
+
15
+ /**
16
+ * Read a query parameter, matching its key case-insensitively.
17
+ *
18
+ * An exact-case match wins when present, so a canonical link is never shadowed
19
+ * by a mangled duplicate (`?fctx=stale&fCtx=real` resolves to `real`). Only when
20
+ * the exact key is absent do we scan for a case-folded variant.
21
+ *
22
+ * @returns the param value, or `null` when no key matches.
23
+ */
24
+ export function getQueryParamCaseInsensitive(
25
+ searchParams: URLSearchParams,
26
+ key: string
27
+ ): string | null {
28
+ const exact = searchParams.get(key);
29
+ if (exact !== null) return exact;
30
+
31
+ const target = key.toLowerCase();
32
+ for (const [paramKey, value] of searchParams) {
33
+ if (paramKey.toLowerCase() === target) {
34
+ return value;
35
+ }
36
+ }
37
+ return null;
38
+ }
39
+
40
+ /**
41
+ * Delete every query parameter whose key matches `key` case-insensitively.
42
+ *
43
+ * Keys are collected before deletion because mutating a `URLSearchParams`
44
+ * while iterating it skips entries.
45
+ */
46
+ export function deleteQueryParamCaseInsensitive(
47
+ searchParams: URLSearchParams,
48
+ key: string
49
+ ): void {
50
+ const target = key.toLowerCase();
51
+ const matchingKeys = [...searchParams.keys()].filter(
52
+ (paramKey) => paramKey.toLowerCase() === target
53
+ );
54
+ for (const paramKey of matchingKeys) {
55
+ searchParams.delete(paramKey);
56
+ }
57
+ }
@@ -1 +0,0 @@
1
- import{_ as e,a as t,g as n,i as r,m as i,n as a,p as o,r as s,t as c}from"./frakContext-UEOk9Bk4.js";import{Deferred as l}from"@frak-labs/frame-connector";async function u(e,t,n){return await e.request({method:`frak_displayEmbeddedWallet`,params:n?[t,e.config.metadata,n]:[t,e.config.metadata]})}async function d(e,{steps:t,metadata:n},r){return await e.request({method:`frak_displayModal`,params:r?[t,n,e.config.metadata,r]:[t,n,e.config.metadata]})}async function f(e,t,n){return await e.request({method:`frak_displaySharingPage`,params:n?[t,e.config.metadata,n]:[t,e.config.metadata]})}async function p(t){if(typeof window>`u`)return;let n=e();if(!n)return;let r=await o.resolveMerchantId();if(!r)return;let a=`frak-identity-ensured-${r}`;if(!window.sessionStorage.getItem(a))try{let e=i();(await fetch(`${e}/user/identity/ensure`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"x-wallet-sdk-auth":t,"x-frak-client-id":n},body:JSON.stringify({merchantId:r})})).ok&&window.sessionStorage.setItem(a,`1`)}catch{}}async function m(e,t){return n(()=>e.request({method:`frak_getMerchantInformation`}),{cacheKey:`frak_getMerchantInformation`,cacheTime:t?.cacheTime})}async function h(e,t){return n(()=>e.request({method:`frak_getMergeToken`}),{cacheKey:`frak_getMergeToken`,cacheTime:t?.cacheTime})}async function g(e,t){return n(()=>e.request({method:`frak_getUserReferralStatus`}),{cacheKey:`frak_getUserReferralStatus`,cacheTime:t?.cacheTime})}async function _(e,t){let{metadata:n,customizations:r}=e.config;return await e.request({method:`frak_prepareSso`,params:[t,n.name,r?.css]})}async function v(t,n){try{await t.request({method:`frak_sendInteraction`,params:[n,{clientId:e()}]})}catch{console.warn(`[Frak SDK] Failed to send interaction:`,n.type)}}function y(e,n,r){return s(n)?(t(e,`user_referred_started`,{referrerClientId:n.c,referrerWallet:n.w,walletStatus:r?.key}),v(e,{type:`arrival`,referrerClientId:n.c,referrerMerchantId:n.m,referrerWallet:n.w,referralTimestamp:n.t}),!0):a(n)?(t(e,`user_referred_started`,{referrer:n.r,walletStatus:r?.key}),v(e,{type:`arrival`,referrerWallet:n.r}),!0):!1}function b(t,n){let r=e();return!r&&!n?null:{v:2,m:t,t:Math.floor(Date.now()/1e3),...r?{c:r}:{},...n?{w:n}:{}}}function x(t,n){return s(t)?t.w&&n?.wallet?r(t.w,n.wallet):t.c?e()===t.c:!1:a(t)&&n?.wallet?r(t.r,n.wallet):!1}function S(e,{walletStatus:n,frakContext:r,options:i}){if(!r)return`no-referrer`;if(x(r,n))return`self-referral`;if(!y(e,r,n))return`no-referrer`;let a=s(r)?r.m:i?.merchantId,o=i?.alwaysAppendUrl&&a?b(a,n?.wallet):null;return c.replaceUrl({url:window.location?.href,context:o}),t(e,`user_referred_completed`,{status:`success`}),`success`}async function C(e,{options:t}={}){let n=c.parse({url:window.location.href}),r=await D(e);try{return S(e,{walletStatus:r,frakContext:n,options:t})}catch(e){console.warn(`Error processing referral`,{error:e})}}const w=`frak:referral-success`;async function T(e){try{await C(e)===`success`&&window.dispatchEvent(new Event(w))}catch(e){console.warn(`[Frak] Referral setup failed`,e)}}async function E(t){if(typeof window>`u`){console.warn(`[Frak] No window found, can't track purchase`);return}let n=window.sessionStorage.getItem(`frak-wallet-interaction-token`),r=e();if(!n&&!r){console.warn(`[Frak] No identity found, skipping purchase check`);return}let a=t.merchantId??await o.resolveMerchantId();if(!a){console.warn(`[Frak] No merchant id found, skipping purchase check`);return}let s={Accept:`application/json`,"Content-Type":`application/json`};n&&(s[`x-wallet-sdk-auth`]=n),r&&(s[`x-frak-client-id`]=r);let c=i();await fetch(`${c}/user/track/purchase`,{method:`POST`,headers:s,body:JSON.stringify({customerId:t.customerId,orderId:t.orderId,token:t.token,merchantId:a})})}function D(e,t){if(!t)return e.request({method:`frak_listenToWalletStatus`}).then(t=>(O(e,t),t));let n=new l,r=!1;return e.listenerRequest({method:`frak_listenToWalletStatus`},i=>{O(e,i),t(i),r||=(n.resolve(i),!0)}),n.promise}function O(e,t){typeof window>`u`||(e.openPanel?.setGlobalProperties({wallet:t.wallet??null}),t.interactionToken?(window.sessionStorage.setItem(`frak-wallet-interaction-token`,t.interactionToken),p(t.interactionToken)):window.sessionStorage.removeItem(`frak-wallet-interaction-token`))}function k(e,{metadata:t,login:n}){return A(e,{steps:{login:n??{}},metadata:t})}function A(e,t){function n(n){return A(e,{...t,steps:{...t.steps,sendTransaction:n}})}function r(n){return A(e,{...t,steps:{...t.steps,final:{...n,action:{key:`reward`}}}})}function i(n,r){return A(e,{...t,steps:{...t.steps,final:{...r,action:{key:`sharing`,options:n}}}})}async function a(n,r){return n&&(t.metadata=n(t.metadata??{})),await d(e,t,r)}return{params:t,sendTx:n,reward:r,sharing:i,display:a}}async function j(e,{tx:t,metadata:n}){return(await d(e,{metadata:n,steps:{login:{},sendTransaction:{tx:t}}})).sendTransaction}function M(e=96){let t=Math.ceil(e/2),n=``;if(typeof crypto<`u`&&crypto.getRandomValues){let e=new Uint8Array(t);crypto.getRandomValues(e);for(let t=0;t<e.length;t++)n+=e[t].toString(16).padStart(2,`0`)}else for(let e=0;e<t;e++)n+=(Math.random()*256|0).toString(16).padStart(2,`0`);return n.substring(0,e)}async function N(e,{siwe:t,metadata:n}){let r=e.config?.domain??window.location.host,i=t?.statement??`I confirm that I want to use my Frak wallet on: ${e.config.metadata.name}`;return(await d(e,{metadata:n,steps:{login:{},siweAuthenticate:{siwe:{...t,statement:i,nonce:t?.nonce??M(),uri:t?.uri??`https://${r}`,version:t?.version??`1`,domain:r}}}})).siweAuthenticate}export{d as _,E as a,C as c,_ as d,g as f,f as g,p as h,D as i,S as l,m,j as n,w as o,h as p,k as r,T as s,N as t,v as u,u as v};
@@ -1 +0,0 @@
1
- const e=require(`./frakContext-Cfp7sSid.cjs`);let t=require(`@frak-labs/frame-connector`);async function n(e,t,n){return await e.request({method:`frak_displayEmbeddedWallet`,params:n?[t,e.config.metadata,n]:[t,e.config.metadata]})}async function r(e,{steps:t,metadata:n},r){return await e.request({method:`frak_displayModal`,params:r?[t,n,e.config.metadata,r]:[t,n,e.config.metadata]})}async function i(e,t,n){return await e.request({method:`frak_displaySharingPage`,params:n?[t,e.config.metadata,n]:[t,e.config.metadata]})}async function a(t){if(typeof window>`u`)return;let n=e._();if(!n)return;let r=await e.p.resolveMerchantId();if(!r)return;let i=`frak-identity-ensured-${r}`;if(!window.sessionStorage.getItem(i))try{let a=e.m();(await fetch(`${a}/user/identity/ensure`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"x-wallet-sdk-auth":t,"x-frak-client-id":n},body:JSON.stringify({merchantId:r})})).ok&&window.sessionStorage.setItem(i,`1`)}catch{}}async function o(t,n){return e.g(()=>t.request({method:`frak_getMerchantInformation`}),{cacheKey:`frak_getMerchantInformation`,cacheTime:n?.cacheTime})}async function s(t,n){return e.g(()=>t.request({method:`frak_getMergeToken`}),{cacheKey:`frak_getMergeToken`,cacheTime:n?.cacheTime})}async function c(t,n){return e.g(()=>t.request({method:`frak_getUserReferralStatus`}),{cacheKey:`frak_getUserReferralStatus`,cacheTime:n?.cacheTime})}async function l(e,t){let{metadata:n,customizations:r}=e.config;return await e.request({method:`frak_prepareSso`,params:[t,n.name,r?.css]})}async function u(t,n){try{await t.request({method:`frak_sendInteraction`,params:[n,{clientId:e._()}]})}catch{console.warn(`[Frak SDK] Failed to send interaction:`,n.type)}}function d(t,n,r){return e.r(n)?(e.a(t,`user_referred_started`,{referrerClientId:n.c,referrerWallet:n.w,walletStatus:r?.key}),u(t,{type:`arrival`,referrerClientId:n.c,referrerMerchantId:n.m,referrerWallet:n.w,referralTimestamp:n.t}),!0):e.n(n)?(e.a(t,`user_referred_started`,{referrer:n.r,walletStatus:r?.key}),u(t,{type:`arrival`,referrerWallet:n.r}),!0):!1}function f(t,n){let r=e._();return!r&&!n?null:{v:2,m:t,t:Math.floor(Date.now()/1e3),...r?{c:r}:{},...n?{w:n}:{}}}function p(t,n){return e.r(t)?t.w&&n?.wallet?e.i(t.w,n.wallet):t.c?e._()===t.c:!1:e.n(t)&&n?.wallet?e.i(t.r,n.wallet):!1}function m(t,{walletStatus:n,frakContext:r,options:i}){if(!r)return`no-referrer`;if(p(r,n))return`self-referral`;if(!d(t,r,n))return`no-referrer`;let a=e.r(r)?r.m:i?.merchantId,o=i?.alwaysAppendUrl&&a?f(a,n?.wallet):null;return e.t.replaceUrl({url:window.location?.href,context:o}),e.a(t,`user_referred_completed`,{status:`success`}),`success`}async function h(t,{options:n}={}){let r=e.t.parse({url:window.location.href}),i=await y(t);try{return m(t,{walletStatus:i,frakContext:r,options:n})}catch(e){console.warn(`Error processing referral`,{error:e})}}const g=`frak:referral-success`;async function _(e){try{await h(e)===`success`&&window.dispatchEvent(new Event(g))}catch(e){console.warn(`[Frak] Referral setup failed`,e)}}async function v(t){if(typeof window>`u`){console.warn(`[Frak] No window found, can't track purchase`);return}let n=window.sessionStorage.getItem(`frak-wallet-interaction-token`),r=e._();if(!n&&!r){console.warn(`[Frak] No identity found, skipping purchase check`);return}let i=t.merchantId??await e.p.resolveMerchantId();if(!i){console.warn(`[Frak] No merchant id found, skipping purchase check`);return}let a={Accept:`application/json`,"Content-Type":`application/json`};n&&(a[`x-wallet-sdk-auth`]=n),r&&(a[`x-frak-client-id`]=r);let o=e.m();await fetch(`${o}/user/track/purchase`,{method:`POST`,headers:a,body:JSON.stringify({customerId:t.customerId,orderId:t.orderId,token:t.token,merchantId:i})})}function y(e,n){if(!n)return e.request({method:`frak_listenToWalletStatus`}).then(t=>(b(e,t),t));let r=new t.Deferred,i=!1;return e.listenerRequest({method:`frak_listenToWalletStatus`},t=>{b(e,t),n(t),i||=(r.resolve(t),!0)}),r.promise}function b(e,t){typeof window>`u`||(e.openPanel?.setGlobalProperties({wallet:t.wallet??null}),t.interactionToken?(window.sessionStorage.setItem(`frak-wallet-interaction-token`,t.interactionToken),a(t.interactionToken)):window.sessionStorage.removeItem(`frak-wallet-interaction-token`))}function x(e,{metadata:t,login:n}){return S(e,{steps:{login:n??{}},metadata:t})}function S(e,t){function n(n){return S(e,{...t,steps:{...t.steps,sendTransaction:n}})}function i(n){return S(e,{...t,steps:{...t.steps,final:{...n,action:{key:`reward`}}}})}function a(n,r){return S(e,{...t,steps:{...t.steps,final:{...r,action:{key:`sharing`,options:n}}}})}async function o(n,i){return n&&(t.metadata=n(t.metadata??{})),await r(e,t,i)}return{params:t,sendTx:n,reward:i,sharing:a,display:o}}async function C(e,{tx:t,metadata:n}){return(await r(e,{metadata:n,steps:{login:{},sendTransaction:{tx:t}}})).sendTransaction}function w(e=96){let t=Math.ceil(e/2),n=``;if(typeof crypto<`u`&&crypto.getRandomValues){let e=new Uint8Array(t);crypto.getRandomValues(e);for(let t=0;t<e.length;t++)n+=e[t].toString(16).padStart(2,`0`)}else for(let e=0;e<t;e++)n+=(Math.random()*256|0).toString(16).padStart(2,`0`);return n.substring(0,e)}async function T(e,{siwe:t,metadata:n}){let i=e.config?.domain??window.location.host,a=t?.statement??`I confirm that I want to use my Frak wallet on: ${e.config.metadata.name}`;return(await r(e,{metadata:n,steps:{login:{},siweAuthenticate:{siwe:{...t,statement:a,nonce:t?.nonce??w(),uri:t?.uri??`https://${i}`,version:t?.version??`1`,domain:i}}}})).siweAuthenticate}Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`g`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,`v`,{enumerable:!0,get:function(){return n}});
@@ -1 +0,0 @@
1
- let e=require(`@frak-labs/frame-connector`);const t=`frak-client-id`;function n(){return typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}function r(){if(typeof window>`u`||!window.localStorage)return console.warn(`[Frak SDK] No Window / localStorage available to save the clientId`),n();let e=localStorage.getItem(t);return e||(e=n(),localStorage.setItem(t,e)),e}var i=class extends Map{maxSize;constructor(e){super(),this.maxSize=e}get(e){let t=super.get(e);return super.has(e)&&(super.delete(e),super.set(e,t)),t}set(e,t){if(super.has(e)&&super.delete(e),super.set(e,t),this.maxSize&&this.size>this.maxSize){let e=super.keys().next().value;e!==void 0&&super.delete(e)}return this}};const a=new i(1024),o=new i(1024),s=new i(1024);async function c(e,{cacheKey:t,cacheTime:n=3e4}){if(n>0){let e=o.get(t);if(e&&Date.now()-e.created<n)return e.data}let r=s.get(t);if(r&&Date.now()-r<1e3)throw Error(`Cache: ${t} recently failed, backing off`);let i=a.get(t);i||(i=e(),a.set(t,i));try{let e=await i;return o.set(t,{data:e,created:Date.now()}),s.delete(t),e}catch(e){throw s.set(t,Date.now()),e}finally{a.delete(t)}}function l(){a.clear(),o.clear(),s.clear()}const u=`https://backend.frak.id`;function d(e){return e.includes(`localhost:3000`)||e.includes(`localhost:3010`)}function f(e){return d(e)?`https://localhost:3030`:e.includes(`wallet-dev.frak.id`)||e.includes(`wallet.gcp-dev.frak.id`)?`https://backend.gcp-dev.frak.id`:u}function p(e){if(e)return f(e);if(typeof window<`u`){let e=window.FrakSetup?.client?.config?.walletUrl;if(e)return f(e)}return u}const m=`__frakSdkConfig`,h=`frak-config-cache`,g=`frak-merchant-id`,_={key:h},v=typeof window<`u`;function y(){return{isResolved:!1,merchantId:``}}let b=null;function x(){if(!v)return null;try{let e=localStorage.getItem(_.key);if(!e)return null;let t=JSON.parse(e);return t.config?.isResolved?(b=t,t):null}catch{return null}}function S(){return(b??x())?.config}function C(){let e=b??x();return e?Date.now()-e.timestamp<3e4:!1}function ee(e){if(!(!v||!e.isResolved))try{let t={config:e,timestamp:Date.now()};localStorage.setItem(_.key,JSON.stringify(t)),b=t}catch{}}function w(){if(v){b=null;try{localStorage.removeItem(_.key)}catch{}}}function T(){v&&(window[m]||(window[m]=S()??y()))}T();function E(){return v?window[m]??y():y()}function D(e){v&&window.dispatchEvent(new CustomEvent(`frak:config`,{detail:e}))}function O(e){return e??(v?window.location.hostname:``)}async function te(e,t,n){try{let r=p(t),i=n?`&lang=${encodeURIComponent(n)}`:``,a=await fetch(`${r}/user/merchant/resolve?domain=${encodeURIComponent(e)}${i}`);if(!a.ok){console.warn(`[Frak SDK] Merchant lookup failed for domain ${e}: ${a.status}`);return}let o=await a.json();if(v)try{sessionStorage.setItem(g,o.merchantId)}catch{}return o}catch(e){console.warn(`[Frak SDK] Failed to fetch merchant config:`,e);return}}const k={getConfig:E,get isResolved(){return E().isResolved},get isCacheFresh(){return C()},setCacheScope(e,t){_.key=`${h}:${`${e}:${t??``}`}`,b=null},setConfig(e){if(v&&(window[m]=e),ee(e),D(e),v&&e.merchantId)try{sessionStorage.setItem(g,e.merchantId)}catch{}},reset(){let e=S()??y();v&&(window[m]=e),D(e)},clearCache(){if(w(),l(),v)try{sessionStorage.removeItem(g)}catch{}},resolve(e,t,n){let r=O(e);return r?c(async()=>{let e=await te(r,t,n);if(!e)throw Error(`Config resolution returned empty`);return e},{cacheKey:`sdkConfig:${r}:${n??``}`,cacheTime:1/0}).catch(()=>void 0):Promise.resolve(void 0)},getMerchantId(){let e=E();if(e.isResolved&&e.merchantId)return e.merchantId;if(v)try{return sessionStorage.getItem(g)??void 0}catch{}},async resolveMerchantId(e,t){return k.getMerchantId()||(await k.resolve(e,t))?.merchantId}};function A(e){return btoa(Array.from(e,e=>String.fromCharCode(e)).join(``)).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function j(e){let t=e.length%4;return Uint8Array.from(atob(e.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(e.length+(t===0?0:4-t),`=`)),e=>e.charCodeAt(0))}function M(t){return A((0,e.jsonEncode)(t))}function N(e,t,n,r,i,a){let o=M(P({redirectUrl:t.redirectUrl,directExit:t.directExit,lang:t.lang,merchantId:n,metadata:{name:r,css:a,logoUrl:t.metadata?.logoUrl,homepageLink:t.metadata?.homepageLink},clientId:i})),s=new URL(e);return s.pathname=`/sso`,s.searchParams.set(`p`,o),s.toString()}function P(e){return{r:e.redirectUrl,cId:e.clientId,d:e.directExit,l:e.lang,m:e.merchantId,md:{n:e.metadata?.name,css:e.metadata?.css,l:e.metadata?.logoUrl,h:e.metadata?.homepageLink}}}const F=`menubar=no,status=no,scrollbars=no,fullscreen=no,width=500, height=800`,I=`frak-sso`;async function ne(e,t){let{metadata:n,customizations:i,walletUrl:a}=e.config,o={...t,directExit:t.directExit??!t.redirectUrl};if(o.openInSameWindow??!!o.redirectUrl)return await e.request({method:`frak_openSso`,params:[o,n.name,i?.css]});let s=o.ssoPopupUrl??N(a??`https://wallet.frak.id`,o,await k.resolveMerchantId()??``,n.name,r(),i?.css),c=window.open(s,I,F);if(!c)throw Error(`Popup was blocked. Please allow popups for this site.`);return c.focus(),await e.request({method:`frak_openSso`,params:[o,n.name,i?.css]})??{}}function re(e,t,n){if(!e){console.debug(`[Frak] No client provided, skipping event tracking`);return}try{e.openPanel?.track(t,n)}catch(e){console.debug(`[Frak] Failed to track event:`,t,e)}}const ie=/^0x[a-fA-F0-9]{40}$/;function L(e){return typeof e==`string`&&ie.test(e)}function ae(e,t){return e.toLowerCase()===t.toLowerCase()}function R(e){let t=new Uint8Array(20);for(let n=0;n<20;n++){let r=Number.parseInt(e.substring(2+n*2,4+n*2),16);if(Number.isNaN(r))throw Error(`Invalid address: ${e}`);t[n]=r}return t}const z=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function B(e){let t=`0x`;for(let n=0;n<20;n++)t+=z[e[n]];return t}function V(e){return`r`in e&&!(`v`in e)}function H(e){return`v`in e&&e.v===2}const U=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function W(e){return typeof e==`string`&&U.test(e)}function G(e){let t=e.replace(/-/g,``),n=new Uint8Array(16);for(let e=0;e<16;e++)n[e]=Number.parseInt(t.substring(e*2,e*2+2),16);return n}function K(e){let t=``;for(let n=0;n<16;n++)t+=e[n].toString(16).padStart(2,`0`);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`}function q(e){if(!W(e.m)||!Number.isInteger(e.t)||e.t<0||e.t>4294967295)return null;let t=typeof e.c==`string`&&e.c.length>0,n=typeof e.w==`string`&&L(e.w);if(!t&&!n||t&&!W(e.c))return null;let r=new Uint8Array(21+(t?16:0)+(n?20:0)),i=new DataView(r.buffer,r.byteOffset,r.byteLength),a=0;return r[a++]=2|(t?16:0)|(n?32:0),r.set(G(e.m),a),a+=16,i.setUint32(a,e.t,!1),a+=4,t&&(r.set(G(e.c),a),a+=16),n&&(r.set(R(e.w),a),a+=20),r}function oe(e){if(e.length<21)return null;let t=e[0];if((t&15)!=2||t&192)return null;let n=(t&16)!=0,r=(t&32)!=0;if(!n&&!r)return null;let i=21+(n?16:0)+(r?20:0);if(e.length!==i)return null;let a=1,o=K(e.subarray(a,a+16));a+=16;let s=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(a,!1);a+=4;let c={v:2,m:o,t:s};if(n&&(c.c=K(e.subarray(a,a+16)),a+=16),r){let t=B(e.subarray(a,a+20));if(!L(t))return null;c.w=t,a+=20}return c}const J=`fCtx`;function Y(e){if(e)try{if(H(e)){let t=q(e);return t?A(t):void 0}return A(R(e.r))}catch(t){console.error(`Error compressing Frak context`,{e:t,context:e})}}function X(e){if(!(!e||e.length===0))try{let t=j(e);if(t.length!==20)return oe(t)||void 0;let n=B(t);if(L(n))return{r:n}}catch(t){console.error(`Error decompressing Frak context`,{e:t,context:e})}}function se({url:e}){if(!e)return null;let t=new URL(e).searchParams.get(J);return t?X(t):null}function ce(e){return{utm_source:e.utmSource??`frak`,utm_medium:e.utmMedium??void 0,utm_campaign:e.utmCampaign??void 0,utm_content:e.utmContent,utm_term:e.utmTerm,via:e.via??void 0,ref:e.ref??void 0}}function le(e,t){let n=ce(t??{});for(let[t,r]of Object.entries(n))r===void 0||r===``||e.searchParams.has(t)||e.searchParams.set(t,r)}function Z({url:e,context:t,attribution:n}){if(!e)return null;let r=Y(t);if(!r)return null;let i=new URL(e);return i.searchParams.set(J,r),le(i,n),i.toString()}function Q(e){let t=new URL(e);return t.searchParams.delete(J),t.toString()}function $({url:e,context:t}){if(!window.location?.href||typeof window>`u`){console.error(`No window found, can't update context`);return}let n=e??window.location.href,r;r=t===null?Q(n):Z({url:n,context:t}),r&&window.history.replaceState(null,``,r.toString())}const ue={compress:Y,decompress:X,parse:se,update:Z,remove:Q,replaceUrl:$};Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return re}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,`g`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return ae}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return ne}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return ue}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return M}});
@@ -1 +0,0 @@
1
- import{jsonEncode as e}from"@frak-labs/frame-connector";const t=`frak-client-id`;function n(){return typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}function r(){if(typeof window>`u`||!window.localStorage)return console.warn(`[Frak SDK] No Window / localStorage available to save the clientId`),n();let e=localStorage.getItem(t);return e||(e=n(),localStorage.setItem(t,e)),e}var i=class extends Map{maxSize;constructor(e){super(),this.maxSize=e}get(e){let t=super.get(e);return super.has(e)&&(super.delete(e),super.set(e,t)),t}set(e,t){if(super.has(e)&&super.delete(e),super.set(e,t),this.maxSize&&this.size>this.maxSize){let e=super.keys().next().value;e!==void 0&&super.delete(e)}return this}};const a=new i(1024),o=new i(1024),s=new i(1024);async function c(e,{cacheKey:t,cacheTime:n=3e4}){if(n>0){let e=o.get(t);if(e&&Date.now()-e.created<n)return e.data}let r=s.get(t);if(r&&Date.now()-r<1e3)throw Error(`Cache: ${t} recently failed, backing off`);let i=a.get(t);i||(i=e(),a.set(t,i));try{let e=await i;return o.set(t,{data:e,created:Date.now()}),s.delete(t),e}catch(e){throw s.set(t,Date.now()),e}finally{a.delete(t)}}function l(){a.clear(),o.clear(),s.clear()}const u=`https://backend.frak.id`;function d(e){return e.includes(`localhost:3000`)||e.includes(`localhost:3010`)}function f(e){return d(e)?`https://localhost:3030`:e.includes(`wallet-dev.frak.id`)||e.includes(`wallet.gcp-dev.frak.id`)?`https://backend.gcp-dev.frak.id`:u}function p(e){if(e)return f(e);if(typeof window<`u`){let e=window.FrakSetup?.client?.config?.walletUrl;if(e)return f(e)}return u}const m=`__frakSdkConfig`,h=`frak-config-cache`,g=`frak-merchant-id`,_={key:h},v=typeof window<`u`;function y(){return{isResolved:!1,merchantId:``}}let b=null;function x(){if(!v)return null;try{let e=localStorage.getItem(_.key);if(!e)return null;let t=JSON.parse(e);return t.config?.isResolved?(b=t,t):null}catch{return null}}function S(){return(b??x())?.config}function C(){let e=b??x();return e?Date.now()-e.timestamp<3e4:!1}function ee(e){if(!(!v||!e.isResolved))try{let t={config:e,timestamp:Date.now()};localStorage.setItem(_.key,JSON.stringify(t)),b=t}catch{}}function w(){if(v){b=null;try{localStorage.removeItem(_.key)}catch{}}}function T(){v&&(window[m]||(window[m]=S()??y()))}T();function E(){return v?window[m]??y():y()}function D(e){v&&window.dispatchEvent(new CustomEvent(`frak:config`,{detail:e}))}function O(e){return e??(v?window.location.hostname:``)}async function te(e,t,n){try{let r=p(t),i=n?`&lang=${encodeURIComponent(n)}`:``,a=await fetch(`${r}/user/merchant/resolve?domain=${encodeURIComponent(e)}${i}`);if(!a.ok){console.warn(`[Frak SDK] Merchant lookup failed for domain ${e}: ${a.status}`);return}let o=await a.json();if(v)try{sessionStorage.setItem(g,o.merchantId)}catch{}return o}catch(e){console.warn(`[Frak SDK] Failed to fetch merchant config:`,e);return}}const k={getConfig:E,get isResolved(){return E().isResolved},get isCacheFresh(){return C()},setCacheScope(e,t){_.key=`${h}:${`${e}:${t??``}`}`,b=null},setConfig(e){if(v&&(window[m]=e),ee(e),D(e),v&&e.merchantId)try{sessionStorage.setItem(g,e.merchantId)}catch{}},reset(){let e=S()??y();v&&(window[m]=e),D(e)},clearCache(){if(w(),l(),v)try{sessionStorage.removeItem(g)}catch{}},resolve(e,t,n){let r=O(e);return r?c(async()=>{let e=await te(r,t,n);if(!e)throw Error(`Config resolution returned empty`);return e},{cacheKey:`sdkConfig:${r}:${n??``}`,cacheTime:1/0}).catch(()=>void 0):Promise.resolve(void 0)},getMerchantId(){let e=E();if(e.isResolved&&e.merchantId)return e.merchantId;if(v)try{return sessionStorage.getItem(g)??void 0}catch{}},async resolveMerchantId(e,t){return k.getMerchantId()||(await k.resolve(e,t))?.merchantId}};function A(e){return btoa(Array.from(e,e=>String.fromCharCode(e)).join(``)).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function j(e){let t=e.length%4;return Uint8Array.from(atob(e.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(e.length+(t===0?0:4-t),`=`)),e=>e.charCodeAt(0))}function M(t){return A(e(t))}function N(e,t,n,r,i,a){let o=M(P({redirectUrl:t.redirectUrl,directExit:t.directExit,lang:t.lang,merchantId:n,metadata:{name:r,css:a,logoUrl:t.metadata?.logoUrl,homepageLink:t.metadata?.homepageLink},clientId:i})),s=new URL(e);return s.pathname=`/sso`,s.searchParams.set(`p`,o),s.toString()}function P(e){return{r:e.redirectUrl,cId:e.clientId,d:e.directExit,l:e.lang,m:e.merchantId,md:{n:e.metadata?.name,css:e.metadata?.css,l:e.metadata?.logoUrl,h:e.metadata?.homepageLink}}}const F=`menubar=no,status=no,scrollbars=no,fullscreen=no,width=500, height=800`,I=`frak-sso`;async function ne(e,t){let{metadata:n,customizations:i,walletUrl:a}=e.config,o={...t,directExit:t.directExit??!t.redirectUrl};if(o.openInSameWindow??!!o.redirectUrl)return await e.request({method:`frak_openSso`,params:[o,n.name,i?.css]});let s=o.ssoPopupUrl??N(a??`https://wallet.frak.id`,o,await k.resolveMerchantId()??``,n.name,r(),i?.css),c=window.open(s,I,F);if(!c)throw Error(`Popup was blocked. Please allow popups for this site.`);return c.focus(),await e.request({method:`frak_openSso`,params:[o,n.name,i?.css]})??{}}function re(e,t,n){if(!e){console.debug(`[Frak] No client provided, skipping event tracking`);return}try{e.openPanel?.track(t,n)}catch(e){console.debug(`[Frak] Failed to track event:`,t,e)}}const ie=/^0x[a-fA-F0-9]{40}$/;function L(e){return typeof e==`string`&&ie.test(e)}function ae(e,t){return e.toLowerCase()===t.toLowerCase()}function R(e){let t=new Uint8Array(20);for(let n=0;n<20;n++){let r=Number.parseInt(e.substring(2+n*2,4+n*2),16);if(Number.isNaN(r))throw Error(`Invalid address: ${e}`);t[n]=r}return t}const z=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function B(e){let t=`0x`;for(let n=0;n<20;n++)t+=z[e[n]];return t}function V(e){return`r`in e&&!(`v`in e)}function H(e){return`v`in e&&e.v===2}const U=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function W(e){return typeof e==`string`&&U.test(e)}function G(e){let t=e.replace(/-/g,``),n=new Uint8Array(16);for(let e=0;e<16;e++)n[e]=Number.parseInt(t.substring(e*2,e*2+2),16);return n}function K(e){let t=``;for(let n=0;n<16;n++)t+=e[n].toString(16).padStart(2,`0`);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`}function q(e){if(!W(e.m)||!Number.isInteger(e.t)||e.t<0||e.t>4294967295)return null;let t=typeof e.c==`string`&&e.c.length>0,n=typeof e.w==`string`&&L(e.w);if(!t&&!n||t&&!W(e.c))return null;let r=new Uint8Array(21+(t?16:0)+(n?20:0)),i=new DataView(r.buffer,r.byteOffset,r.byteLength),a=0;return r[a++]=2|(t?16:0)|(n?32:0),r.set(G(e.m),a),a+=16,i.setUint32(a,e.t,!1),a+=4,t&&(r.set(G(e.c),a),a+=16),n&&(r.set(R(e.w),a),a+=20),r}function oe(e){if(e.length<21)return null;let t=e[0];if((t&15)!=2||t&192)return null;let n=(t&16)!=0,r=(t&32)!=0;if(!n&&!r)return null;let i=21+(n?16:0)+(r?20:0);if(e.length!==i)return null;let a=1,o=K(e.subarray(a,a+16));a+=16;let s=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(a,!1);a+=4;let c={v:2,m:o,t:s};if(n&&(c.c=K(e.subarray(a,a+16)),a+=16),r){let t=B(e.subarray(a,a+20));if(!L(t))return null;c.w=t,a+=20}return c}const J=`fCtx`;function Y(e){if(e)try{if(H(e)){let t=q(e);return t?A(t):void 0}return A(R(e.r))}catch(t){console.error(`Error compressing Frak context`,{e:t,context:e})}}function X(e){if(!(!e||e.length===0))try{let t=j(e);if(t.length!==20)return oe(t)||void 0;let n=B(t);if(L(n))return{r:n}}catch(t){console.error(`Error decompressing Frak context`,{e:t,context:e})}}function se({url:e}){if(!e)return null;let t=new URL(e).searchParams.get(J);return t?X(t):null}function ce(e){return{utm_source:e.utmSource??`frak`,utm_medium:e.utmMedium??void 0,utm_campaign:e.utmCampaign??void 0,utm_content:e.utmContent,utm_term:e.utmTerm,via:e.via??void 0,ref:e.ref??void 0}}function le(e,t){let n=ce(t??{});for(let[t,r]of Object.entries(n))r===void 0||r===``||e.searchParams.has(t)||e.searchParams.set(t,r)}function Z({url:e,context:t,attribution:n}){if(!e)return null;let r=Y(t);if(!r)return null;let i=new URL(e);return i.searchParams.set(J,r),le(i,n),i.toString()}function Q(e){let t=new URL(e);return t.searchParams.delete(J),t.toString()}function $({url:e,context:t}){if(!window.location?.href||typeof window>`u`){console.error(`No window found, can't update context`);return}let n=e??window.location.href,r;r=t===null?Q(n):Z({url:n,context:t}),r&&window.history.replaceState(null,``,r.toString())}const ue={compress:Y,decompress:X,parse:se,update:Z,remove:Q,replaceUrl:$};export{r as _,re as a,I as c,j as d,A as f,c as g,l as h,ae as i,N as l,p as m,V as n,ne as o,k as p,H as r,F as s,ue as t,M as u};
@@ -1 +0,0 @@
1
- import{_ as e,d as t,h as n,m as r,p as i}from"./frakContext-UEOk9Bk4.js";import{Deferred as a,FrakRpcError as o,RpcErrorCodes as s,createRpcClient as c,jsonDecode as l}from"@frak-labs/frame-connector";import{OpenPanel as u}from"@openpanel/web";const d=`nexus-wallet-backup`,f=`frakwallet://`;function p(e,t){if(typeof window>`u`)return;let n=new URL(window.location.href),r=n.searchParams.get(`sso`);r&&(t.then(()=>{e.sendLifecycle({clientLifecycle:`sso-redirect-complete`,data:{compressed:r}}),console.log(`[SSO URL Listener] Forwarded compressed SSO data to iframe`)}).catch(e=>{console.error(`[SSO URL Listener] Failed to forward SSO data:`,e)}),n.searchParams.delete(`sso`),window.history.replaceState({},``,n.toString()),console.log(`[SSO URL Listener] SSO parameter detected and URL cleaned`))}function m(){let e=navigator.userAgent;return/Android/i.test(e)&&/Chrome\/\d+/i.test(e)}const h=f.replace(`://`,``);function g(e){return`intent://${e.slice(13)}#Intent;scheme=${h};end`}function _(e,t){let n=t?.timeout??2500,r=!1,i=()=>{document.hidden&&(r=!0)};document.addEventListener(`visibilitychange`,i);let a=m()&&v(e)?g(e):e;window.location.href=a,setTimeout(()=>{document.removeEventListener(`visibilitychange`,i),r||t?.onFallback?.()},n)}function v(e){return e.startsWith(f)}const y={id:`frak-wallet`,name:`frak-wallet`,title:`Frak Wallet`,allow:`publickey-credentials-get *; clipboard-write; web-share *`,style:{width:`0`,height:`0`,border:`0`,position:`absolute`,zIndex:2000001,top:`-1000px`,left:`-1000px`,colorScheme:`auto`}};function b({walletBaseUrl:t,config:n}){let i=document.querySelector(`#frak-wallet`);i&&i.remove();let a=document.createElement(`iframe`);a.id=y.id,a.name=y.name,a.allow=y.allow,a.style.zIndex=y.style.zIndex.toString(),x({iframe:a,isVisible:!1});let o=n?.walletUrl??t??`https://wallet.frak.id`,s=e();return C(o),C(r(o)),a.src=`${o}/listener?clientId=${encodeURIComponent(s)}`,new Promise(e=>{a.addEventListener(`load`,()=>e(a)),document.body.appendChild(a)})}function x({iframe:e,isVisible:t}){if(!t){e.style.width=`0`,e.style.height=`0`,e.style.border=`0`,e.style.position=`fixed`,e.style.top=`-1000px`,e.style.left=`-1000px`;return}e.style.position=`fixed`,e.style.top=`0`,e.style.left=`0`,e.style.width=`100%`,e.style.height=`100%`,e.style.pointerEvents=`auto`}function S(e=`/listener`){if(!window.opener)return null;let t=t=>{try{return t.location.origin===window.location.origin&&t.location.pathname===e}catch{return!1}};if(t(window.opener))return window.opener;try{let e=window.opener.frames;for(let n=0;n<e.length;n++)if(t(e[n]))return e[n];return null}catch(t){return console.error(`[findIframeInOpener] Error finding iframe with pathname ${e}:`,t),null}}function C(e){if(!(typeof document>`u`))try{let t=new URL(e).origin,n=`link[rel="preconnect"][data-frak-preconnect="${t}"]`;if(document.head.querySelector(n))return;let r=document.createElement(`link`);r.rel=`preconnect`,r.href=t,r.crossOrigin=``,r.dataset.frakPreconnect=t,document.head.appendChild(r)}catch{}}const w=(()=>{if(typeof navigator>`u`)return!1;let e=navigator.userAgent;if(!(/iPhone|iPad|iPod/i.test(e)||/Macintosh/i.test(e)&&navigator.maxTouchPoints>1))return!1;let t=e.toLowerCase();return t.includes(`instagram`)||t.includes(`fban`)||t.includes(`fbav`)||t.includes(`facebook`)})();function T(e){e?localStorage.setItem(d,e):localStorage.removeItem(d)}function E(e,t){try{let n=new URL(e);if(!n.searchParams.has(`u`))return e;let r=k(window.location.href,t);return n.searchParams.delete(`u`),n.searchParams.append(`u`,r),n.toString()}catch{return e}}function D(e){let t=new URL(window.location.href);e&&t.searchParams.set(`fmt`,e);let n=t.protocol===`http:`?`x-safari-http`:`x-safari-https`;window.location.href=`${n}://${t.host}${t.pathname}${t.search}${t.hash}`}function O(e){return e.includes(`/common/social`)}function k(e,t){if(!t)return e;try{let n=new URL(e);return n.searchParams.set(`fmt`,t),n.toString()}catch{return`${e}${e.includes(`?`)?`&`:`?`}fmt=${encodeURIComponent(t)}`}}function A(e,t,n,r,i){if(i){let e=E(t,r);window.open(e,`_blank`);return}if(v(t)){let i=E(t,r);_(i,{onFallback:()=>{e.contentWindow?.postMessage({clientLifecycle:`deep-link-failed`,data:{originalUrl:i}},n)}})}else if(w&&O(t))D(r);else{let e=E(t,r);window.location.href=e}}function j({iframe:e,targetOrigin:t}){let n=new a;return{handleEvent:r=>{if(!(`iframeLifecycle`in r))return;let{iframeLifecycle:i,data:a}=r;switch(i){case`connected`:n.resolve(!0);break;case`do-backup`:T(a.backup);break;case`remove-backup`:localStorage.removeItem(d);break;case`show`:case`hide`:x({iframe:e,isVisible:i===`show`});break;case`redirect`:A(e,a.baseRedirectUrl,t,a.mergeToken,a.openInNewTab);break}},isConnected:n.promise}}function M({config:t,iframe:r}){let l=t?.walletUrl??`https://wallet.frak.id`,d=typeof navigator<`u`?navigator.language?.split(`-`)[0]:void 0,f=t.metadata.lang??(d===`en`||d===`fr`?d:void 0),p=t.domain??(typeof window<`u`?window.location.hostname:``);i.setCacheScope(p,f),i.reset();let m=i.isCacheFresh?void 0:i.resolve(t.domain,t.walletUrl,f),h=j({iframe:r,targetOrigin:l}),g=new a,_=Date.now();if(!r.contentWindow)throw new o(s.configError,`The iframe does not have a content window`);let v=c({emittingTransport:r.contentWindow,listeningTransport:window,targetOrigin:l,middleware:[{async onRequest(e,t){if(!await h.isConnected)throw new o(s.clientNotConnected,`The iframe provider isn't connected yet`);return await g.promise,t}}],lifecycleHandlers:{iframeLifecycle:(e,t)=>{h.handleEvent(e)}}}),y=N(v,h),b=async()=>{y(),v.cleanup(),r.remove(),n(),i.clearCache(),i.reset()},x;{console.log(`[Frak SDK] Initializing OpenPanel`),x=new u({apiUrl:`https://op-api.gcp.frak.id`,clientId:`f305d11d-b93b-487c-80d4-92deb7903e98`,trackScreenViews:!0,trackOutgoingLinks:!0,trackAttributes:!1,filter:({type:t,payload:n})=>(t!==`track`||!n?.properties||`sdkVersion`in n.properties||(n.properties={...n.properties,sdkVersion:`1.1.3`,userAnonymousClientId:e()}),!0)}),x.setGlobalProperties({sdkVersion:`1.1.3`,userAnonymousClientId:e()}),x.init(),x.track(`sdk_initialized`,{sdkVersion:`1.1.3`});let t=!1,n=setTimeout(()=>{t||(t=!0,x?.track(`sdk_iframe_handshake_failed`,{reason:`timeout`}))},3e4);h.isConnected.then(()=>{t||(t=!0,clearTimeout(n),x?.track(`sdk_iframe_connected`,{handshake_duration_ms:Date.now()-_}))}).catch(()=>{t||(t=!0,clearTimeout(n),x?.track(`sdk_iframe_handshake_failed`,{reason:`unknown`}))})}let S=P({config:t,rpcClient:v,lifecycleManager:h,configPromise:m,contextSent:g,openPanel:x}).then(()=>{}).catch(e=>{throw g.reject(e),e});return{config:t,waitForConnection:h.isConnected,waitForSetup:S,request:v.request,listenerRequest:v.listen,destroy:b,openPanel:x}}function N(e,t){let n,r,i=()=>e.sendLifecycle({clientLifecycle:`heartbeat`});async function a(){i(),n=setInterval(i,250),r=setTimeout(()=>{o(),console.log(`Heartbeat timeout: connection failed`)},3e4),await t.isConnected,o()}function o(){n&&clearInterval(n),r&&clearTimeout(r)}return a(),o}async function P({config:t,rpcClient:n,lifecycleManager:r,configPromise:a,contextSent:o,openPanel:s}){await r.isConnected,p(n,r.isConnected);let c=new URL(window.location.href),l=c.searchParams.get(`fmt`)??void 0;l&&(c.searchParams.delete(`fmt`),window.history.replaceState({},``,c.toString()));let u=e=>{let n=e?.merchantId??t.metadata.merchantId??``,r=e?.domain??``,a=e?.allowedDomains??[],o=e?.sdkConfig,s=o?.attribution||t.attribution?{...t.attribution,...o?.attribution}:void 0;i.setConfig(o?{isResolved:!0,merchantId:n,domain:r,allowedDomains:a,hasRawSdkConfig:!0,name:o.name??t.metadata.name,logoUrl:o.logoUrl??t.metadata.logoUrl,homepageLink:o.homepageLink??t.metadata.homepageLink,lang:o.lang??t.metadata.lang,currency:o.currency??t.metadata.currency,hidden:o.hidden,css:o.css,translations:o.translations,placements:o.placements,components:o.components,attribution:s}:{isResolved:!0,merchantId:n,domain:r,allowedDomains:a,name:t.metadata.name,logoUrl:t.metadata.logoUrl,homepageLink:t.metadata.homepageLink,lang:t.metadata.lang,currency:t.metadata.currency,attribution:s})},f=!1,m=t=>{let r=f?void 0:l;f=!0;let i=t.hasRawSdkConfig?{name:t.name,logoUrl:t.logoUrl,homepageLink:t.homepageLink,lang:t.lang,currency:t.currency,hidden:t.hidden,css:t.css,translations:t.translations,placements:t.placements,attribution:t.attribution}:t.attribution?{attribution:t.attribution}:void 0,a=e();if(s){let e=s.global??{};s.setGlobalProperties({...e,merchantId:t.merchantId,domain:t.domain??``})}n.sendLifecycle({clientLifecycle:`resolved-config`,data:{merchantId:t.merchantId,domain:t.domain??``,allowedDomains:t.allowedDomains??[],sourceUrl:window.location.href,...a&&{sdkAnonymousId:a},...r&&{pendingMergeToken:r},...i&&{sdkConfig:i}}})};i.isResolved&&(m(i.getConfig()),o.resolve()),a&&(u(await a),m(i.getConfig()),o.resolve());async function h(){let e=t.customizations?.css;e&&n.sendLifecycle({clientLifecycle:`modal-css`,data:{cssLink:e}})}async function g(){let e=t.customizations?.i18n;e&&n.sendLifecycle({clientLifecycle:`modal-i18n`,data:{i18n:e}})}async function _(){if(typeof window>`u`)return;let e=window.localStorage.getItem(d);e&&n.sendLifecycle({clientLifecycle:`restore-backup`,data:{backup:e}})}(await Promise.allSettled([h(),g(),_()])).some(e=>e.status===`rejected`)&&s?.track(`sdk_iframe_handshake_failed`,{reason:`asset_push`})}function F(){if(typeof navigator>`u`)return!1;let e=navigator.userAgent;return!!(/iPhone|iPad|iPod/i.test(e)||/Macintosh/i.test(e)&&navigator.maxTouchPoints>1)}const I=F();function L(){return typeof navigator>`u`?!1:I?!0:/Android|webOS|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function R(){if(typeof navigator>`u`)return!1;let e=navigator.userAgent.toLowerCase();return e.includes(`instagram`)||e.includes(`fban`)||e.includes(`fbav`)||e.includes(`facebook`)}const z=R();function B(e){I&&e.startsWith(`https://`)?window.location.href=`x-safari-https://${e.slice(8)}`:I&&e.startsWith(`http://`)?window.location.href=`x-safari-http://${e.slice(7)}`:window.location.href=`https://backend.frak.id/common/social?u=${encodeURIComponent(e)}`}function V(e){return l(t(e))}const H={eur:`fr-FR`,usd:`en-US`,gbp:`en-GB`};function U(e){return e&&e in H?e:`eur`}function W(e){return e?H[e]??H.eur:H.eur}function G(e,t){let n=W(t),r=U(t);return e.toLocaleString(n,{style:`currency`,currency:r,minimumFractionDigits:0,maximumFractionDigits:2})}function K(e){return e?`${e}Amount`:`eurAmount`}async function q({config:e}){let t=J(e),n=await b({config:t});if(!n){console.error(`Failed to create iframe`);return}let r=M({config:t,iframe:n});if(await r.waitForSetup,!await r.waitForConnection){console.error(`Failed to connect to client`);return}return r}function J(e){let t=U(e.metadata?.currency);return{...e,metadata:{...e.metadata,currency:t}}}function Y({perCall:e,defaults:t,productUtmContent:n}){if(e===null)return;let r=e!==void 0,i=t!==void 0&&Object.keys(t).length>0;if(!r&&!i&&!(n!==void 0&&n!==``))return;let a={...t,...e??{}},o=n??e?.utmContent;return o!==void 0&&o!==``?a.utmContent=o:delete a.utmContent,a}export{U as a,z as c,M as d,y as f,f as h,G as i,L as l,_ as m,q as n,V as o,S as p,K as r,I as s,Y as t,B as u};
@@ -1 +0,0 @@
1
- const e=require(`./frakContext-Cfp7sSid.cjs`);let t=require(`@frak-labs/frame-connector`),n=require(`@openpanel/web`);const r=`nexus-wallet-backup`,i=`frakwallet://`;function a(e,t){if(typeof window>`u`)return;let n=new URL(window.location.href),r=n.searchParams.get(`sso`);r&&(t.then(()=>{e.sendLifecycle({clientLifecycle:`sso-redirect-complete`,data:{compressed:r}}),console.log(`[SSO URL Listener] Forwarded compressed SSO data to iframe`)}).catch(e=>{console.error(`[SSO URL Listener] Failed to forward SSO data:`,e)}),n.searchParams.delete(`sso`),window.history.replaceState({},``,n.toString()),console.log(`[SSO URL Listener] SSO parameter detected and URL cleaned`))}function o(){let e=navigator.userAgent;return/Android/i.test(e)&&/Chrome\/\d+/i.test(e)}const s=i.replace(`://`,``);function c(e){return`intent://${e.slice(13)}#Intent;scheme=${s};end`}function l(e,t){let n=t?.timeout??2500,r=!1,i=()=>{document.hidden&&(r=!0)};document.addEventListener(`visibilitychange`,i);let a=o()&&u(e)?c(e):e;window.location.href=a,setTimeout(()=>{document.removeEventListener(`visibilitychange`,i),r||t?.onFallback?.()},n)}function u(e){return e.startsWith(i)}const d={id:`frak-wallet`,name:`frak-wallet`,title:`Frak Wallet`,allow:`publickey-credentials-get *; clipboard-write; web-share *`,style:{width:`0`,height:`0`,border:`0`,position:`absolute`,zIndex:2000001,top:`-1000px`,left:`-1000px`,colorScheme:`auto`}};function f({walletBaseUrl:t,config:n}){let r=document.querySelector(`#frak-wallet`);r&&r.remove();let i=document.createElement(`iframe`);i.id=d.id,i.name=d.name,i.allow=d.allow,i.style.zIndex=d.style.zIndex.toString(),p({iframe:i,isVisible:!1});let a=n?.walletUrl??t??`https://wallet.frak.id`,o=e._();return h(a),h(e.m(a)),i.src=`${a}/listener?clientId=${encodeURIComponent(o)}`,new Promise(e=>{i.addEventListener(`load`,()=>e(i)),document.body.appendChild(i)})}function p({iframe:e,isVisible:t}){if(!t){e.style.width=`0`,e.style.height=`0`,e.style.border=`0`,e.style.position=`fixed`,e.style.top=`-1000px`,e.style.left=`-1000px`;return}e.style.position=`fixed`,e.style.top=`0`,e.style.left=`0`,e.style.width=`100%`,e.style.height=`100%`,e.style.pointerEvents=`auto`}function m(e=`/listener`){if(!window.opener)return null;let t=t=>{try{return t.location.origin===window.location.origin&&t.location.pathname===e}catch{return!1}};if(t(window.opener))return window.opener;try{let e=window.opener.frames;for(let n=0;n<e.length;n++)if(t(e[n]))return e[n];return null}catch(t){return console.error(`[findIframeInOpener] Error finding iframe with pathname ${e}:`,t),null}}function h(e){if(!(typeof document>`u`))try{let t=new URL(e).origin,n=`link[rel="preconnect"][data-frak-preconnect="${t}"]`;if(document.head.querySelector(n))return;let r=document.createElement(`link`);r.rel=`preconnect`,r.href=t,r.crossOrigin=``,r.dataset.frakPreconnect=t,document.head.appendChild(r)}catch{}}const g=(()=>{if(typeof navigator>`u`)return!1;let e=navigator.userAgent;if(!(/iPhone|iPad|iPod/i.test(e)||/Macintosh/i.test(e)&&navigator.maxTouchPoints>1))return!1;let t=e.toLowerCase();return t.includes(`instagram`)||t.includes(`fban`)||t.includes(`fbav`)||t.includes(`facebook`)})();function _(e){e?localStorage.setItem(r,e):localStorage.removeItem(r)}function v(e,t){try{let n=new URL(e);if(!n.searchParams.has(`u`))return e;let r=x(window.location.href,t);return n.searchParams.delete(`u`),n.searchParams.append(`u`,r),n.toString()}catch{return e}}function y(e){let t=new URL(window.location.href);e&&t.searchParams.set(`fmt`,e);let n=t.protocol===`http:`?`x-safari-http`:`x-safari-https`;window.location.href=`${n}://${t.host}${t.pathname}${t.search}${t.hash}`}function b(e){return e.includes(`/common/social`)}function x(e,t){if(!t)return e;try{let n=new URL(e);return n.searchParams.set(`fmt`,t),n.toString()}catch{return`${e}${e.includes(`?`)?`&`:`?`}fmt=${encodeURIComponent(t)}`}}function S(e,t,n,r,i){if(i){let e=v(t,r);window.open(e,`_blank`);return}if(u(t)){let i=v(t,r);l(i,{onFallback:()=>{e.contentWindow?.postMessage({clientLifecycle:`deep-link-failed`,data:{originalUrl:i}},n)}})}else if(g&&b(t))y(r);else{let e=v(t,r);window.location.href=e}}function C({iframe:e,targetOrigin:n}){let i=new t.Deferred;return{handleEvent:t=>{if(!(`iframeLifecycle`in t))return;let{iframeLifecycle:a,data:o}=t;switch(a){case`connected`:i.resolve(!0);break;case`do-backup`:_(o.backup);break;case`remove-backup`:localStorage.removeItem(r);break;case`show`:case`hide`:p({iframe:e,isVisible:a===`show`});break;case`redirect`:S(e,o.baseRedirectUrl,n,o.mergeToken,o.openInNewTab);break}},isConnected:i.promise}}function w({config:r,iframe:i}){let a=r?.walletUrl??`https://wallet.frak.id`,o=typeof navigator<`u`?navigator.language?.split(`-`)[0]:void 0,s=r.metadata.lang??(o===`en`||o===`fr`?o:void 0),c=r.domain??(typeof window<`u`?window.location.hostname:``);e.p.setCacheScope(c,s),e.p.reset();let l=e.p.isCacheFresh?void 0:e.p.resolve(r.domain,r.walletUrl,s),u=C({iframe:i,targetOrigin:a}),d=new t.Deferred,f=Date.now();if(!i.contentWindow)throw new t.FrakRpcError(t.RpcErrorCodes.configError,`The iframe does not have a content window`);let p=(0,t.createRpcClient)({emittingTransport:i.contentWindow,listeningTransport:window,targetOrigin:a,middleware:[{async onRequest(e,n){if(!await u.isConnected)throw new t.FrakRpcError(t.RpcErrorCodes.clientNotConnected,`The iframe provider isn't connected yet`);return await d.promise,n}}],lifecycleHandlers:{iframeLifecycle:(e,t)=>{u.handleEvent(e)}}}),m=T(p,u),h=async()=>{m(),p.cleanup(),i.remove(),e.h(),e.p.clearCache(),e.p.reset()},g;{console.log(`[Frak SDK] Initializing OpenPanel`),g=new n.OpenPanel({apiUrl:`https://op-api.gcp.frak.id`,clientId:`f305d11d-b93b-487c-80d4-92deb7903e98`,trackScreenViews:!0,trackOutgoingLinks:!0,trackAttributes:!1,filter:({type:t,payload:n})=>(t!==`track`||!n?.properties||`sdkVersion`in n.properties||(n.properties={...n.properties,sdkVersion:`1.1.3`,userAnonymousClientId:e._()}),!0)}),g.setGlobalProperties({sdkVersion:`1.1.3`,userAnonymousClientId:e._()}),g.init(),g.track(`sdk_initialized`,{sdkVersion:`1.1.3`});let t=!1,r=setTimeout(()=>{t||(t=!0,g?.track(`sdk_iframe_handshake_failed`,{reason:`timeout`}))},3e4);u.isConnected.then(()=>{t||(t=!0,clearTimeout(r),g?.track(`sdk_iframe_connected`,{handshake_duration_ms:Date.now()-f}))}).catch(()=>{t||(t=!0,clearTimeout(r),g?.track(`sdk_iframe_handshake_failed`,{reason:`unknown`}))})}let _=E({config:r,rpcClient:p,lifecycleManager:u,configPromise:l,contextSent:d,openPanel:g}).then(()=>{}).catch(e=>{throw d.reject(e),e});return{config:r,waitForConnection:u.isConnected,waitForSetup:_,request:p.request,listenerRequest:p.listen,destroy:h,openPanel:g}}function T(e,t){let n,r,i=()=>e.sendLifecycle({clientLifecycle:`heartbeat`});async function a(){i(),n=setInterval(i,250),r=setTimeout(()=>{o(),console.log(`Heartbeat timeout: connection failed`)},3e4),await t.isConnected,o()}function o(){n&&clearInterval(n),r&&clearTimeout(r)}return a(),o}async function E({config:t,rpcClient:n,lifecycleManager:i,configPromise:o,contextSent:s,openPanel:c}){await i.isConnected,a(n,i.isConnected);let l=new URL(window.location.href),u=l.searchParams.get(`fmt`)??void 0;u&&(l.searchParams.delete(`fmt`),window.history.replaceState({},``,l.toString()));let d=n=>{let r=n?.merchantId??t.metadata.merchantId??``,i=n?.domain??``,a=n?.allowedDomains??[],o=n?.sdkConfig,s=o?.attribution||t.attribution?{...t.attribution,...o?.attribution}:void 0;e.p.setConfig(o?{isResolved:!0,merchantId:r,domain:i,allowedDomains:a,hasRawSdkConfig:!0,name:o.name??t.metadata.name,logoUrl:o.logoUrl??t.metadata.logoUrl,homepageLink:o.homepageLink??t.metadata.homepageLink,lang:o.lang??t.metadata.lang,currency:o.currency??t.metadata.currency,hidden:o.hidden,css:o.css,translations:o.translations,placements:o.placements,components:o.components,attribution:s}:{isResolved:!0,merchantId:r,domain:i,allowedDomains:a,name:t.metadata.name,logoUrl:t.metadata.logoUrl,homepageLink:t.metadata.homepageLink,lang:t.metadata.lang,currency:t.metadata.currency,attribution:s})},f=!1,p=t=>{let r=f?void 0:u;f=!0;let i=t.hasRawSdkConfig?{name:t.name,logoUrl:t.logoUrl,homepageLink:t.homepageLink,lang:t.lang,currency:t.currency,hidden:t.hidden,css:t.css,translations:t.translations,placements:t.placements,attribution:t.attribution}:t.attribution?{attribution:t.attribution}:void 0,a=e._();if(c){let e=c.global??{};c.setGlobalProperties({...e,merchantId:t.merchantId,domain:t.domain??``})}n.sendLifecycle({clientLifecycle:`resolved-config`,data:{merchantId:t.merchantId,domain:t.domain??``,allowedDomains:t.allowedDomains??[],sourceUrl:window.location.href,...a&&{sdkAnonymousId:a},...r&&{pendingMergeToken:r},...i&&{sdkConfig:i}}})};e.p.isResolved&&(p(e.p.getConfig()),s.resolve()),o&&(d(await o),p(e.p.getConfig()),s.resolve());async function m(){let e=t.customizations?.css;e&&n.sendLifecycle({clientLifecycle:`modal-css`,data:{cssLink:e}})}async function h(){let e=t.customizations?.i18n;e&&n.sendLifecycle({clientLifecycle:`modal-i18n`,data:{i18n:e}})}async function g(){if(typeof window>`u`)return;let e=window.localStorage.getItem(r);e&&n.sendLifecycle({clientLifecycle:`restore-backup`,data:{backup:e}})}(await Promise.allSettled([m(),h(),g()])).some(e=>e.status===`rejected`)&&c?.track(`sdk_iframe_handshake_failed`,{reason:`asset_push`})}function D(){if(typeof navigator>`u`)return!1;let e=navigator.userAgent;return!!(/iPhone|iPad|iPod/i.test(e)||/Macintosh/i.test(e)&&navigator.maxTouchPoints>1)}const O=D();function k(){return typeof navigator>`u`?!1:O?!0:/Android|webOS|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function A(){if(typeof navigator>`u`)return!1;let e=navigator.userAgent.toLowerCase();return e.includes(`instagram`)||e.includes(`fban`)||e.includes(`fbav`)||e.includes(`facebook`)}const j=A();function M(e){O&&e.startsWith(`https://`)?window.location.href=`x-safari-https://${e.slice(8)}`:O&&e.startsWith(`http://`)?window.location.href=`x-safari-http://${e.slice(7)}`:window.location.href=`https://backend.frak.id/common/social?u=${encodeURIComponent(e)}`}function N(n){return(0,t.jsonDecode)(e.d(n))}const P={eur:`fr-FR`,usd:`en-US`,gbp:`en-GB`};function F(e){return e&&e in P?e:`eur`}function I(e){return e?P[e]??P.eur:P.eur}function L(e,t){let n=I(t),r=F(t);return e.toLocaleString(n,{style:`currency`,currency:r,minimumFractionDigits:0,maximumFractionDigits:2})}function R(e){return e?`${e}Amount`:`eurAmount`}async function z({config:e}){let t=B(e),n=await f({config:t});if(!n){console.error(`Failed to create iframe`);return}let r=w({config:t,iframe:n});if(await r.waitForSetup,!await r.waitForConnection){console.error(`Failed to connect to client`);return}return r}function B(e){let t=F(e.metadata?.currency);return{...e,metadata:{...e.metadata,currency:t}}}function V({perCall:e,defaults:t,productUtmContent:n}){if(e===null)return;let r=e!==void 0,i=t!==void 0&&Object.keys(t).length>0;if(!r&&!i&&!(n!==void 0&&n!==``))return;let a={...t,...e??{}},o=n??e?.utmContent;return o!==void 0&&o!==``?a.utmContent=o:delete a.utmContent,a}Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return M}});