@clerk/clerk-js 6.0.0-snapshot.v20251211120550 → 6.0.0-snapshot.v20251215203425

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 (63) hide show
  1. package/dist/clerk.browser.js +6 -6
  2. package/dist/clerk.chips.browser.js +6 -6
  3. package/dist/clerk.headless.browser.js +6 -6
  4. package/dist/clerk.headless.js +6 -6
  5. package/dist/clerk.js +6 -6
  6. package/dist/clerk.legacy.browser.js +1 -1
  7. package/dist/clerk.mjs +6 -6
  8. package/dist/clerk.no-rhc.js +6 -6
  9. package/dist/clerk.no-rhc.mjs +6 -6
  10. package/dist/types/core/clerk.d.ts +0 -1
  11. package/dist/types/core/resources/Token.d.ts +1 -1
  12. package/dist/types/utils/errorThrower.d.ts +1 -1
  13. package/dist/types/utils/web3.d.ts +2 -2
  14. package/package.json +3 -3
  15. /package/dist/{308_clerk.headless_20ea57_6.0.0-snapshot.v20251211120550.js → 308_clerk.headless_e60092_6.0.0-snapshot.v20251215203425.js} +0 -0
  16. /package/dist/{415_clerk.headless_20ea57_6.0.0-snapshot.v20251211120550.js → 415_clerk.headless_e60092_6.0.0-snapshot.v20251215203425.js} +0 -0
  17. /package/dist/{507_clerk.browser_33ec98_6.0.0-snapshot.v20251211120550.js → 507_clerk.browser_e30104_6.0.0-snapshot.v20251215203425.js} +0 -0
  18. /package/dist/{507_clerk.chips.browser_22651e_6.0.0-snapshot.v20251211120550.js → 507_clerk.chips.browser_39f293_6.0.0-snapshot.v20251215203425.js} +0 -0
  19. /package/dist/{507_clerk.headless.browser_d97075_6.0.0-snapshot.v20251211120550.js → 507_clerk.headless.browser_524209_6.0.0-snapshot.v20251215203425.js} +0 -0
  20. /package/dist/{507_clerk.headless_20ea57_6.0.0-snapshot.v20251211120550.js → 507_clerk.headless_e60092_6.0.0-snapshot.v20251215203425.js} +0 -0
  21. /package/dist/{507_clerk.legacy.browser_62573d_6.0.0-snapshot.v20251211120550.js → 507_clerk.legacy.browser_87c30b_6.0.0-snapshot.v20251215203425.js} +0 -0
  22. /package/dist/{521_clerk.headless_20ea57_6.0.0-snapshot.v20251211120550.js → 521_clerk.headless_e60092_6.0.0-snapshot.v20251215203425.js} +0 -0
  23. /package/dist/{527_clerk.browser_33ec98_6.0.0-snapshot.v20251211120550.js → 527_clerk.browser_e30104_6.0.0-snapshot.v20251215203425.js} +0 -0
  24. /package/dist/{527_clerk.chips.browser_22651e_6.0.0-snapshot.v20251211120550.js → 527_clerk.chips.browser_39f293_6.0.0-snapshot.v20251215203425.js} +0 -0
  25. /package/dist/{527_clerk.headless.browser_d97075_6.0.0-snapshot.v20251211120550.js → 527_clerk.headless.browser_524209_6.0.0-snapshot.v20251215203425.js} +0 -0
  26. /package/dist/{527_clerk.legacy.browser_62573d_6.0.0-snapshot.v20251211120550.js → 527_clerk.legacy.browser_87c30b_6.0.0-snapshot.v20251215203425.js} +0 -0
  27. /package/dist/{604_clerk.headless_20ea57_6.0.0-snapshot.v20251211120550.js → 604_clerk.headless_e60092_6.0.0-snapshot.v20251215203425.js} +0 -0
  28. /package/dist/{694_clerk.headless_20ea57_6.0.0-snapshot.v20251211120550.js → 694_clerk.headless_e60092_6.0.0-snapshot.v20251215203425.js} +0 -0
  29. /package/dist/{783_clerk.headless_20ea57_6.0.0-snapshot.v20251211120550.js → 783_clerk.headless_e60092_6.0.0-snapshot.v20251215203425.js} +0 -0
  30. /package/dist/{973_clerk.headless_20ea57_6.0.0-snapshot.v20251211120550.js → 973_clerk.headless_e60092_6.0.0-snapshot.v20251215203425.js} +0 -0
  31. /package/dist/{base-account-sdk_clerk.browser_33ec98_6.0.0-snapshot.v20251211120550.js → base-account-sdk_clerk.browser_e30104_6.0.0-snapshot.v20251215203425.js} +0 -0
  32. /package/dist/{base-account-sdk_clerk.chips.browser_22651e_6.0.0-snapshot.v20251211120550.js → base-account-sdk_clerk.chips.browser_39f293_6.0.0-snapshot.v20251215203425.js} +0 -0
  33. /package/dist/{base-account-sdk_clerk.headless.browser_d97075_6.0.0-snapshot.v20251211120550.js → base-account-sdk_clerk.headless.browser_524209_6.0.0-snapshot.v20251215203425.js} +0 -0
  34. /package/dist/{base-account-sdk_clerk.legacy.browser_62573d_6.0.0-snapshot.v20251211120550.js → base-account-sdk_clerk.legacy.browser_87c30b_6.0.0-snapshot.v20251215203425.js} +0 -0
  35. /package/dist/{coinbase-wallet-sdk_clerk.browser_33ec98_6.0.0-snapshot.v20251211120550.js → coinbase-wallet-sdk_clerk.browser_e30104_6.0.0-snapshot.v20251215203425.js} +0 -0
  36. /package/dist/{coinbase-wallet-sdk_clerk.chips.browser_22651e_6.0.0-snapshot.v20251211120550.js → coinbase-wallet-sdk_clerk.chips.browser_39f293_6.0.0-snapshot.v20251215203425.js} +0 -0
  37. /package/dist/{coinbase-wallet-sdk_clerk.headless.browser_d97075_6.0.0-snapshot.v20251211120550.js → coinbase-wallet-sdk_clerk.headless.browser_524209_6.0.0-snapshot.v20251215203425.js} +0 -0
  38. /package/dist/{coinbase-wallet-sdk_clerk.legacy.browser_62573d_6.0.0-snapshot.v20251211120550.js → coinbase-wallet-sdk_clerk.legacy.browser_87c30b_6.0.0-snapshot.v20251215203425.js} +0 -0
  39. /package/dist/{cookieSuffix_clerk.browser_33ec98_6.0.0-snapshot.v20251211120550.js → cookieSuffix_clerk.browser_e30104_6.0.0-snapshot.v20251215203425.js} +0 -0
  40. /package/dist/{cookieSuffix_clerk.chips.browser_22651e_6.0.0-snapshot.v20251211120550.js → cookieSuffix_clerk.chips.browser_39f293_6.0.0-snapshot.v20251215203425.js} +0 -0
  41. /package/dist/{cookieSuffix_clerk.headless.browser_d97075_6.0.0-snapshot.v20251211120550.js → cookieSuffix_clerk.headless.browser_524209_6.0.0-snapshot.v20251215203425.js} +0 -0
  42. /package/dist/{cookieSuffix_clerk.headless_20ea57_6.0.0-snapshot.v20251211120550.js → cookieSuffix_clerk.headless_e60092_6.0.0-snapshot.v20251215203425.js} +0 -0
  43. /package/dist/{cookieSuffix_clerk.legacy.browser_62573d_6.0.0-snapshot.v20251211120550.js → cookieSuffix_clerk.legacy.browser_87c30b_6.0.0-snapshot.v20251215203425.js} +0 -0
  44. /package/dist/{query-core-vendors_clerk.browser_33ec98_6.0.0-snapshot.v20251211120550.js → query-core-vendors_clerk.browser_e30104_6.0.0-snapshot.v20251215203425.js} +0 -0
  45. /package/dist/{query-core-vendors_clerk.chips.browser_22651e_6.0.0-snapshot.v20251211120550.js → query-core-vendors_clerk.chips.browser_39f293_6.0.0-snapshot.v20251215203425.js} +0 -0
  46. /package/dist/{query-core-vendors_clerk.headless.browser_d97075_6.0.0-snapshot.v20251211120550.js → query-core-vendors_clerk.headless.browser_524209_6.0.0-snapshot.v20251215203425.js} +0 -0
  47. /package/dist/{query-core-vendors_clerk.legacy.browser_62573d_6.0.0-snapshot.v20251211120550.js → query-core-vendors_clerk.legacy.browser_87c30b_6.0.0-snapshot.v20251215203425.js} +0 -0
  48. /package/dist/{stripe-vendors_clerk.browser_33ec98_6.0.0-snapshot.v20251211120550.js → stripe-vendors_clerk.browser_e30104_6.0.0-snapshot.v20251215203425.js} +0 -0
  49. /package/dist/{stripe-vendors_clerk.chips.browser_22651e_6.0.0-snapshot.v20251211120550.js → stripe-vendors_clerk.chips.browser_39f293_6.0.0-snapshot.v20251215203425.js} +0 -0
  50. /package/dist/{stripe-vendors_clerk.headless.browser_d97075_6.0.0-snapshot.v20251211120550.js → stripe-vendors_clerk.headless.browser_524209_6.0.0-snapshot.v20251215203425.js} +0 -0
  51. /package/dist/{stripe-vendors_clerk.legacy.browser_62573d_6.0.0-snapshot.v20251211120550.js → stripe-vendors_clerk.legacy.browser_87c30b_6.0.0-snapshot.v20251215203425.js} +0 -0
  52. /package/dist/{vendors_clerk.browser_33ec98_6.0.0-snapshot.v20251211120550.js → vendors_clerk.browser_e30104_6.0.0-snapshot.v20251215203425.js} +0 -0
  53. /package/dist/{vendors_clerk.chips.browser_22651e_6.0.0-snapshot.v20251211120550.js → vendors_clerk.chips.browser_39f293_6.0.0-snapshot.v20251215203425.js} +0 -0
  54. /package/dist/{vendors_clerk.headless.browser_d97075_6.0.0-snapshot.v20251211120550.js → vendors_clerk.headless.browser_524209_6.0.0-snapshot.v20251215203425.js} +0 -0
  55. /package/dist/{vendors_clerk.legacy.browser_62573d_6.0.0-snapshot.v20251211120550.js → vendors_clerk.legacy.browser_87c30b_6.0.0-snapshot.v20251215203425.js} +0 -0
  56. /package/dist/{zxcvbn-common_clerk.browser_33ec98_6.0.0-snapshot.v20251211120550.js → zxcvbn-common_clerk.browser_e30104_6.0.0-snapshot.v20251215203425.js} +0 -0
  57. /package/dist/{zxcvbn-common_clerk.chips.browser_22651e_6.0.0-snapshot.v20251211120550.js → zxcvbn-common_clerk.chips.browser_39f293_6.0.0-snapshot.v20251215203425.js} +0 -0
  58. /package/dist/{zxcvbn-common_clerk.headless.browser_d97075_6.0.0-snapshot.v20251211120550.js → zxcvbn-common_clerk.headless.browser_524209_6.0.0-snapshot.v20251215203425.js} +0 -0
  59. /package/dist/{zxcvbn-common_clerk.legacy.browser_62573d_6.0.0-snapshot.v20251211120550.js → zxcvbn-common_clerk.legacy.browser_87c30b_6.0.0-snapshot.v20251215203425.js} +0 -0
  60. /package/dist/{zxcvbn-ts-core_clerk.browser_33ec98_6.0.0-snapshot.v20251211120550.js → zxcvbn-ts-core_clerk.browser_e30104_6.0.0-snapshot.v20251215203425.js} +0 -0
  61. /package/dist/{zxcvbn-ts-core_clerk.chips.browser_22651e_6.0.0-snapshot.v20251211120550.js → zxcvbn-ts-core_clerk.chips.browser_39f293_6.0.0-snapshot.v20251215203425.js} +0 -0
  62. /package/dist/{zxcvbn-ts-core_clerk.headless.browser_d97075_6.0.0-snapshot.v20251211120550.js → zxcvbn-ts-core_clerk.headless.browser_524209_6.0.0-snapshot.v20251215203425.js} +0 -0
  63. /package/dist/{zxcvbn-ts-core_clerk.legacy.browser_62573d_6.0.0-snapshot.v20251211120550.js → zxcvbn-ts-core_clerk.legacy.browser_87c30b_6.0.0-snapshot.v20251215203425.js} +0 -0
package/dist/clerk.js CHANGED
@@ -42,7 +42,7 @@ Try increasing the nonce or find the latest nonce with \`getTransactionCount\`.`
42
42
  `;return a.nonce&&(r+=` nonce: ${a.nonce}
43
43
  `),a.balance&&(r+=` balance: ${a.balance}
44
44
  `),a.code&&(r+=` code: ${a.code}
45
- `),a.state&&(r+=" state:\n",r+=s(a.state)),a.stateDiff&&(r+=" stateDiff:\n",r+=s(a.stateDiff)),r}," State Override:\n").slice(0,-1)}},897:function(e,t,a){"use strict";a.d(t,{Kc:()=>l,Kz:()=>o,Sq:()=>c,Vg:()=>s,WA:()=>u,aO:()=>n,n3:()=>i}),a(5071),a(2239);var r=a(5382);function n(e){let t=Object.entries(e).map(([e,t])=>void 0===t||!1===t?null:[e,t]).filter(Boolean),a=t.reduce((e,[t])=>Math.max(e,t.length),0);return t.map(([e,t])=>` ${`${e}:`.padEnd(a+1)} ${t}`).join("\n")}class i extends r.C{constructor(){super("Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.\nUse `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others.",{name:"FeeConflictError"})}}r.C;class s extends r.C{constructor({transaction:e}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",n(e),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}r.C,r.C,r.C,r.C;class o extends r.C{constructor({blockHash:e,blockNumber:t,blockTag:a,hash:r,index:n}){let i="Transaction";a&&void 0!==n&&(i=`Transaction at block time "${a}" at index "${n}"`),e&&void 0!==n&&(i=`Transaction at block hash "${e}" at index "${n}"`),t&&void 0!==n&&(i=`Transaction at block number "${t}" at index "${n}"`),r&&(i=`Transaction with hash "${r}"`),super(`${i} could not be found.`,{name:"TransactionNotFoundError"})}}class l extends r.C{constructor({hash:e}){super(`Transaction receipt with hash "${e}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}}class c extends r.C{constructor({receipt:e}){super(`Transaction with hash "${e.transactionHash}" reverted.`,{metaMessages:['The receipt marked the transaction as "reverted". This could mean that the function on the contract you are trying to call threw an error.'," ","You can attempt to extract the revert reason by:","- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract","- using the `call` Action with raw `data`"],name:"TransactionReceiptRevertedError"}),Object.defineProperty(this,"receipt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.receipt=e}}class u extends r.C{constructor({hash:e}){super(`Timed out while waiting for transaction with hash "${e}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}},7124:function(e,t,a){"use strict";a.d(t,{I:()=>n,R:()=>r});let r=e=>e,n=e=>e},3896:function(e,t,a){"use strict";a.d(t,{n:()=>f});var r=a(2935),n=a(9938),i=a(9785),s=a(8887),o=a(9278),l=a(9110),c=a(2320),u=a(948),d=a(5615);function h(e,t={}){void 0!==t.size&&(0,u.Sl)(e,{size:t.size});let a=(0,d.My)(e,t);return(0,u.ME)(a,t)}var m=a(8669),p=a(9646);function f(e,t){let a="string"==typeof t?(0,m.aT)(t):t,f=(0,i.l)(a);if(0===(0,s.E)(a)&&e.length>0)throw new r.O;if((0,s.E)(t)&&32>(0,s.E)(t))throw new r.Iy({data:"string"==typeof t?t:(0,d.My)(t),params:e,size:(0,s.E)(t)});let b=0,y=[];for(let t=0;t<e.length;++t){let a=e[t];f.setPosition(b);let[i,s]=function e(t,a,{staticPosition:i}){let s=(0,p.k)(a.type);if(s){let[r,n]=s;return function(t,a,{length:r,staticPosition:n}){if(!r){let r=n+h(t.readBytes(32)),i=r+32;t.setPosition(r);let s=h(t.readBytes(32)),o=g(a),l=0,c=[];for(let r=0;r<s;++r){t.setPosition(i+(o?32*r:l));let[n,s]=e(t,a,{staticPosition:i});l+=s,c.push(n)}return t.setPosition(n+32),[c,32]}if(g(a)){let i=n+h(t.readBytes(32)),s=[];for(let n=0;n<r;++n){t.setPosition(i+32*n);let[r]=e(t,a,{staticPosition:i});s.push(r)}return t.setPosition(n+32),[s,32]}let i=0,s=[];for(let o=0;o<r;++o){let[r,o]=e(t,a,{staticPosition:n+i});i+=o,s.push(r)}return[s,i]}(t,{...a,type:n},{length:r,staticPosition:i})}if("tuple"===a.type)return function(t,a,{staticPosition:r}){let n=0===a.components.length||a.components.some(({name:e})=>!e),i=n?[]:{},s=0;if(g(a)){let o=r+h(t.readBytes(32));for(let r=0;r<a.components.length;++r){let l=a.components[r];t.setPosition(o+s);let[c,u]=e(t,l,{staticPosition:o});s+=u,i[n?r:l?.name]=c}return t.setPosition(r+32),[i,32]}for(let o=0;o<a.components.length;++o){let l=a.components[o],[c,u]=e(t,l,{staticPosition:r});i[n?o:l?.name]=c,s+=u}return[i,s]}(t,a,{staticPosition:i});if("address"===a.type){let e;return e=t.readBytes(32),[(0,n.o)((0,d.My)((0,o.A1)(e,-20))),32]}if("bool"===a.type)return[function(e,t={}){let a=e;if(void 0!==t.size&&((0,u.Sl)(a,{size:t.size}),a=(0,l.B)(a)),a.length>1||a[0]>1)throw new c.xO(a);return!!a[0]}(t.readBytes(32),{size:32}),32];if(a.type.startsWith("bytes"))return function(e,t,{staticPosition:a}){let[r,n]=t.type.split("bytes");if(!n){let t=h(e.readBytes(32));e.setPosition(a+t);let r=h(e.readBytes(32));if(0===r)return e.setPosition(a+32),["0x",32];let n=e.readBytes(r);return e.setPosition(a+32),[(0,d.My)(n),32]}return[(0,d.My)(e.readBytes(Number.parseInt(n,10),32)),32]}(t,a,{staticPosition:i});if(a.type.startsWith("uint")||a.type.startsWith("int")){var m,f;let e,r,n;return m=t,e=(f=a).type.startsWith("int"),r=Number.parseInt(f.type.split("int")[1]||"256",10),n=m.readBytes(32),[r>48?function(e,t={}){void 0!==t.size&&(0,u.Sl)(e,{size:t.size});let a=(0,d.My)(e,t);return(0,u.uU)(a,t)}(n,{signed:e}):h(n,{signed:e}),32]}if("string"===a.type)return function(e,{staticPosition:t}){let a=h(e.readBytes(32));e.setPosition(t+a);let r=h(e.readBytes(32));if(0===r)return e.setPosition(t+32),["",32];let n=e.readBytes(r,32),i=function(e,t={}){let a=e;return void 0!==t.size&&((0,u.Sl)(a,{size:t.size}),a=(0,l.B)(a,{dir:"right"})),new TextDecoder().decode(a)}((0,l.B)(n));return e.setPosition(t+32),[i,32]}(t,{staticPosition:i});throw new r.j(a.type,{docsPath:"/docs/contract/decodeAbiParameters"})}(f,a,{staticPosition:0});b+=s,y.push(i)}return y}function g(e){let{type:t}=e;if("string"===t||"bytes"===t||t.endsWith("[]"))return!0;if("tuple"===t)return e.components?.some(g);let a=(0,p.k)(e.type);return!!(a&&g({...e,type:a[1]}))}},1859:function(e,t,a){"use strict";a.d(t,{W:()=>c});var r=a(3858),n=a(2935),i=a(9278),s=a(606),o=a(3896),l=a(6854);function c(e){let{abi:t,data:a}=e,c=(0,i.di)(a,0,4);if("0x"===c)throw new n.O;let u=[...t||[],r.Mc,r.J9].find(e=>"error"===e.type&&c===(0,s.V)((0,l.B)(e)));if(!u)throw new n.Wq(c,{docsPath:"/docs/contract/decodeErrorResult"});return{abiItem:u,args:"inputs"in u&&u.inputs&&u.inputs.length>0?(0,o.n)(u.inputs,(0,i.di)(a,4)):void 0,errorName:u.name}}},2406:function(e,t,a){"use strict";a.d(t,{J:()=>l});var r=a(2935),n=a(9278),i=a(606),s=a(3896),o=a(6854);function l(e){let{abi:t,data:a}=e,l=(0,n.di)(a,0,4),c=t.find(e=>"function"===e.type&&l===(0,i.V)((0,o.B)(e)));if(!c)throw new r.EB(l,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:c.name,args:"inputs"in c&&c.inputs&&c.inputs.length>0?(0,s.n)(c.inputs,(0,n.di)(a,4)):void 0}}},2987:function(e,t,a){"use strict";a.d(t,{e:()=>o});var r=a(2935),n=a(3896),i=a(401);let s="/docs/contract/decodeFunctionResult";function o(e){let{abi:t,args:a,functionName:o,data:l}=e,c=t[0];if(o){let e=(0,i.iY)({abi:t,args:a,name:o});if(!e)throw new r.Iz(o,{docsPath:s});c=e}if("function"!==c.type)throw new r.Iz(void 0,{docsPath:s});if(!c.outputs)throw new r.MR(c.name,{docsPath:s});let u=(0,n.n)(c.outputs,l);return u&&u.length>1?u:u&&1===u.length?u[0]:void 0}},9646:function(e,t,a){"use strict";a.d(t,{h:()=>p,k:()=>g});var r=a(2935),n=a(4309),i=a(5382),s=a(2320),o=a(9188),l=a(7122),c=a(5969),u=a(8887),d=a(9278),h=a(5615),m=a(3072);function p(e,t){if(e.length!==t.length)throw new r.YE({expectedLength:e.length,givenLength:t.length});let a=f(function({params:e,values:t}){let a=[];for(let p=0;p<e.length;p++)a.push(function e({param:t,value:a}){let p=g(t.type);if(p){let[n,i]=p;return function(t,{length:a,param:n}){let i=null===a;if(!Array.isArray(t))throw new r.dm(t);if(!i&&t.length!==a)throw new r.Nc({expectedLength:a,givenLength:t.length,type:`${n.type}[${a}]`});let s=!1,o=[];for(let a=0;a<t.length;a++){let r=e({param:n,value:t[a]});r.dynamic&&(s=!0),o.push(r)}if(i||s){let e=f(o);if(i){let t=(0,h.cK)(o.length,{size:32});return{dynamic:!0,encoded:o.length>0?(0,l.xW)([t,e]):t}}if(s)return{dynamic:!0,encoded:e}}return{dynamic:!1,encoded:(0,l.xW)(o.map(({encoded:e})=>e))}}(a,{length:n,param:{...t,type:i}})}if("tuple"===t.type)return function(t,{param:a}){let r=!1,n=[];for(let i=0;i<a.components.length;i++){let s=a.components[i],o=Array.isArray(t)?i:s.name,l=e({param:s,value:t[o]});n.push(l),l.dynamic&&(r=!0)}return{dynamic:r,encoded:r?f(n):(0,l.xW)(n.map(({encoded:e})=>e))}}(a,{param:t});if("address"===t.type){var b=a;if(!(0,o.P)(b))throw new n.M({address:b});return{dynamic:!1,encoded:(0,c.db)(b.toLowerCase())}}if("bool"===t.type){var y=a;if("boolean"!=typeof y)throw new i.C(`Invalid boolean value: "${y}" (type: ${typeof y}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:(0,c.db)((0,h.$P)(y))}}if(t.type.startsWith("uint")||t.type.startsWith("int")){let e=t.type.startsWith("int"),[,,r="256"]=m.Ge.exec(t.type)??[];return function(e,{signed:t,size:a=256}){if("number"==typeof a){let r=2n**(BigInt(a)-(t?1n:0n))-1n,n=t?-r-1n:0n;if(e>r||e<n)throw new s.Ty({max:r.toString(),min:n.toString(),signed:t,size:a/8,value:e.toString()})}return{dynamic:!1,encoded:(0,h.cK)(e,{size:32,signed:t})}}(a,{signed:e,size:Number(r)})}if(t.type.startsWith("bytes"))return function(e,{param:t}){let[,a]=t.type.split("bytes"),n=(0,u.E)(e);if(!a){let t=e;return n%32!=0&&(t=(0,c.db)(t,{dir:"right",size:32*Math.ceil((e.length-2)/2/32)})),{dynamic:!0,encoded:(0,l.xW)([(0,c.db)((0,h.cK)(n,{size:32})),t])}}if(n!==Number.parseInt(a,10))throw new r.gH({expectedSize:Number.parseInt(a,10),value:e});return{dynamic:!1,encoded:(0,c.db)(e,{dir:"right"})}}(a,{param:t});if("string"===t.type){var w=a;let e=(0,h.i3)(w),t=Math.ceil((0,u.E)(e)/32),r=[];for(let a=0;a<t;a++)r.push((0,c.db)((0,d.di)(e,32*a,(a+1)*32),{dir:"right"}));return{dynamic:!0,encoded:(0,l.xW)([(0,c.db)((0,h.cK)((0,u.E)(e),{size:32})),...r])}}throw new r.nK(t.type,{docsPath:"/docs/contract/encodeAbiParameters"})}({param:e[p],value:t[p]}));return a}({params:e,values:t}));return 0===a.length?"0x":a}function f(e){let t=0;for(let a=0;a<e.length;a++){let{dynamic:r,encoded:n}=e[a];r?t+=32:t+=(0,u.E)(n)}let a=[],r=[],n=0;for(let i=0;i<e.length;i++){let{dynamic:s,encoded:o}=e[i];s?(a.push((0,h.cK)(t+n,{size:32})),r.push(o),n+=(0,u.E)(o)):a.push(o)}return(0,l.xW)([...a,...r])}function g(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}},5745:function(e,t,a){"use strict";a.d(t,{m:()=>o});var r=a(2935),n=a(7122),i=a(9646);let s="/docs/contract/encodeDeployData";function o(e){let{abi:t,args:a,bytecode:o}=e;if(!a||0===a.length)return o;let l=t.find(e=>"type"in e&&"constructor"===e.type);if(!l)throw new r.YW({docsPath:s});if(!("inputs"in l)||!l.inputs||0===l.inputs.length)throw new r.YF({docsPath:s});let c=(0,i.h)(l.inputs,a);return(0,n.aP)([o,c])}},5823:function(e,t,a){"use strict";a.d(t,{p:()=>u});var r=a(7122),n=a(9646),i=a(2935),s=a(606),o=a(6854),l=a(401);let c="/docs/contract/encodeFunctionData";function u(e){let{args:t}=e,{abi:a,functionName:u}=1===e.abi.length&&e.functionName?.startsWith("0x")?e:function(e){let{abi:t,args:a,functionName:r}=e,n=t[0];if(r){let e=(0,l.iY)({abi:t,args:a,name:r});if(!e)throw new i.Iz(r,{docsPath:c});n=e}if("function"!==n.type)throw new i.Iz(void 0,{docsPath:c});return{abi:[n],functionName:(0,s.V)((0,o.B)(n))}}(e),d=a[0],h="inputs"in d&&d.inputs?(0,n.h)(d.inputs,t??[]):void 0;return(0,r.aP)([u,h??"0x"])}},6854:function(e,t,a){"use strict";a.d(t,{A:()=>i,B:()=>n});var r=a(2935);function n(e,{includeName:t=!1}={}){if("function"!==e.type&&"event"!==e.type&&"error"!==e.type)throw new r.d_(e.type);return`${e.name}(${i(e.inputs,{includeName:t})})`}function i(e,{includeName:t=!1}={}){return e?e.map(e=>(function(e,{includeName:t}){return e.type.startsWith("tuple")?`(${i(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")})(e,{includeName:t})).join(t?", ":","):""}},401:function(e,t,a){"use strict";a.d(t,{iY:()=>l});var r=a(2935),n=a(8097),i=a(9188),s=a(9262),o=a(606);function l(e){let t,{abi:a,args:l=[],name:c}=e,u=(0,n.q)(c,{strict:!1}),d=a.filter(e=>u?"function"===e.type?(0,o.V)(e)===c:"event"===e.type&&(0,s.h)(e)===c:"name"in e&&e.name===c);if(0!==d.length){if(1===d.length)return d[0];for(let e of d){if("inputs"in e){if(!l||0===l.length){if(!e.inputs||0===e.inputs.length)return e;continue}if(e.inputs&&0!==e.inputs.length&&e.inputs.length===l.length&&l.every((t,a)=>{let r="inputs"in e&&e.inputs[a];return!!r&&function e(t,a){let r=typeof t,n=a.type;switch(n){case"address":return(0,i.P)(t,{strict:!1});case"bool":return"boolean"===r;case"function":case"string":return"string"===r;default:if("tuple"===n&&"components"in a)return Object.values(a.components).every((a,r)=>e(Object.values(t)[r],a));if(/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n))return"number"===r||"bigint"===r;if(/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n))return"string"===r||t instanceof Uint8Array;if(/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n))return Array.isArray(t)&&t.every(t=>e(t,{...a,type:n.replace(/(\[[0-9]{0,}\])$/,"")}));return!1}}(t,r)})){if(t&&"inputs"in t&&t.inputs){let a=function e(t,a,r){for(let n in t){let s=t[n],o=a[n];if("tuple"===s.type&&"tuple"===o.type&&"components"in s&&"components"in o)return e(s.components,o.components,r[n]);let l=[s.type,o.type];if(l.includes("address")&&l.includes("bytes20")||(l.includes("address")&&l.includes("string")||l.includes("address")&&l.includes("bytes"))&&(0,i.P)(r[n],{strict:!1}))return l}}(e.inputs,t.inputs,l);if(a)throw new r.nM({abiItem:e,type:a[0]},{abiItem:t,type:a[1]})}t=e}}}return t||d[0]}}},9938:function(e,t,a){"use strict";a.d(t,{b:()=>u,o:()=>c});var r=a(4309),n=a(8669),i=a(4811),s=a(4106),o=a(9188);let l=new s.A(8192);function c(e,t){if(l.has(`${e}.${t}`))return l.get(`${e}.${t}`);let a=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),r=(0,i.S)((0,n.Af)(a),"bytes"),s=(t?a.substring(`${t}0x`.length):a).split("");for(let e=0;e<40;e+=2)r[e>>1]>>4>=8&&s[e]&&(s[e]=s[e].toUpperCase()),(15&r[e>>1])>=8&&s[e+1]&&(s[e+1]=s[e+1].toUpperCase());let o=`0x${s.join("")}`;return l.set(`${e}.${t}`,o),o}function u(e,t){if(!(0,o.P)(e,{strict:!1}))throw new r.M({address:e});return c(e,t)}},9188:function(e,t,a){"use strict";a.d(t,{P:()=>o});var r=a(4106),n=a(9938);let i=/^0x[a-fA-F0-9]{40}$/,s=new r.A(8192);function o(e,t){let{strict:a=!0}=t??{},r=`${e}.${a}`;if(s.has(r))return s.get(r);let o=!!i.test(e)&&(e.toLowerCase()===e||!a||(0,n.o)(e)===e);return s.set(r,o),o}},3950:function(e,t,a){"use strict";a.d(t,{h:()=>i});var r=a(4309),n=a(9188);function i(e,t){if(!(0,n.P)(e,{strict:!1}))throw new r.M({address:e});if(!(0,n.P)(t,{strict:!1}))throw new r.M({address:t});return e.toLowerCase()===t.toLowerCase()}},3330:function(e,t,a){"use strict";a.d(t,{offchainLookupSignature:()=>b,offchainLookup:()=>w});var r=a(4016),n=a(7998),i=a(5382),s=a(7124);class o extends i.C{constructor({callbackSelector:e,cause:t,data:a,extraData:r,sender:n,urls:i}){super(t.shortMessage||"An error occurred while fetching for an offchain result.",{cause:t,metaMessages:[...t.metaMessages||[],t.metaMessages?.length?"":[],"Offchain Gateway Call:",i&&[" Gateway URL(s):",...i.map(e=>` ${(0,s.I)(e)}`)],` Sender: ${n}`,` Data: ${a}`,` Callback selector: ${e}`,` Extra data: ${r}`].flat(),name:"OffchainLookupError"})}}class l extends i.C{constructor({result:e,url:t}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${(0,s.I)(t)}`,`Response: ${(0,n.A)(e)}`],name:"OffchainLookupResponseMalformedError"})}}class c extends i.C{constructor({sender:e,to:t}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${t}`,`OffchainLookup sender address: ${e}`],name:"OffchainLookupSenderMismatchError"})}}var u=a(236),d=a(1859),h=a(9646),m=a(3950),p=a(7122),f=a(8097),g=a(876);let b="0x556f1830",y={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]};async function w(e,{blockNumber:t,blockTag:a,data:n,to:i}){let{args:s}=(0,d.W)({data:n,abi:[y]}),[l,u,f,b,w]=s,{ccipRead:v}=e,x=v&&"function"==typeof v?.request?v.request:k;try{if(!(0,m.h)(i,l))throw new c({sender:l,to:i});let n=u.includes(g.J)?await (0,g.X)({data:f,ccipRequest:x}):await x({data:f,sender:l,urls:u}),{data:s}=await (0,r.T)(e,{blockNumber:t,blockTag:a,data:(0,p.xW)([b,(0,h.h)([{type:"bytes"},{type:"bytes"}],[n,w])]),to:i});return s}catch(e){throw new o({callbackSelector:b,cause:e,data:n,extraData:w,sender:l,urls:u})}}async function k({data:e,sender:t,urls:a}){let r=Error("An unknown error occurred.");for(let i=0;i<a.length;i++){let s=a[i],o=s.includes("{data}")?"GET":"POST",c="POST"===o?{data:e,sender:t}:void 0,d="POST"===o?{"Content-Type":"application/json"}:{};try{let a,i=await fetch(s.replace("{sender}",t.toLowerCase()).replace("{data}",e),{body:JSON.stringify(c),headers:d,method:o});if(a=i.headers.get("Content-Type")?.startsWith("application/json")?(await i.json()).data:await i.text(),!i.ok){r=new u.Ci({body:c,details:a?.error?(0,n.A)(a.error):i.statusText,headers:i.headers,status:i.status,url:s});continue}if(!(0,f.q)(a)){r=new l({result:a,url:s});continue}return a}catch(e){r=new u.Ci({body:c,details:e.message,url:s})}}throw r}},3228:function(e,t,a){"use strict";a.d(t,{M:()=>n});var r=a(372);function n({blockNumber:e,chain:t,contract:a}){let n=t?.contracts?.[a];if(!n)throw new r.rj({chain:t,contract:{name:a}});if(e&&n.blockCreated&&n.blockCreated>e)throw new r.rj({blockNumber:e,chain:t,contract:{name:a,blockCreated:n.blockCreated}});return n.address}},9785:function(e,t,a){"use strict";a.d(t,{l:()=>i});var r=a(9799);let n={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:1/0,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new r.hX({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new r.SK({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new r.B4({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new r.B4({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let a=t??this.position;return this.assertPosition(a+e-1),this.bytes.subarray(a,a+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,255&e),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let a=this.inspectBytes(e);return this.position+=t??e,a},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===1/0)return;let e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};function i(e,{recursiveReadLimit:t=8192}={}){let a=Object.create(n);return a.bytes=e,a.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),a.positionReadCount=new Map,a.recursiveReadLimit=t,a}},7122:function(e,t,a){"use strict";function r(e){return"string"==typeof e[0]?n(e):function(e){let t=0;for(let a of e)t+=a.length;let a=new Uint8Array(t),r=0;for(let t of e)a.set(t,r),r+=t.length;return a}(e)}function n(e){return`0x${e.reduce((e,t)=>e+t.replace("0x",""),"")}`}a.d(t,{aP:()=>n,xW:()=>r})},8097:function(e,t,a){"use strict";function r(e,{strict:t=!0}={}){return!!e&&"string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x"))}a.d(t,{q:()=>r})},5969:function(e,t,a){"use strict";a.d(t,{db:()=>i,eV:()=>n});var r=a(5229);function n(e,{dir:t,size:a=32}={}){return"string"==typeof e?i(e,{dir:t,size:a}):function(e,{dir:t,size:a=32}={}){if(null===a)return e;if(e.length>a)throw new r.Fl({size:e.length,targetSize:a,type:"bytes"});let n=new Uint8Array(a);for(let r=0;r<a;r++){let i="right"===t;n[i?r:a-r-1]=e[i?r:e.length-r-1]}return n}(e,{dir:t,size:a})}function i(e,{dir:t,size:a=32}={}){if(null===a)return e;let n=e.replace("0x","");if(n.length>2*a)throw new r.Fl({size:Math.ceil(n.length/2),targetSize:a,type:"hex"});return`0x${n["right"===t?"padEnd":"padStart"](2*a,"0")}`}},8887:function(e,t,a){"use strict";a.d(t,{E:()=>n});var r=a(8097);function n(e){return(0,r.q)(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}},9278:function(e,t,a){"use strict";a.d(t,{A1:()=>c,di:()=>s,iN:()=>u});var r=a(5229),n=a(8097),i=a(8887);function s(e,t,a,{strict:r}={}){return(0,n.q)(e,{strict:!1})?u(e,t,a,{strict:r}):c(e,t,a,{strict:r})}function o(e,t){if("number"==typeof t&&t>0&&t>(0,i.E)(e)-1)throw new r.ii({offset:t,position:"start",size:(0,i.E)(e)})}function l(e,t,a){if("number"==typeof t&&"number"==typeof a&&(0,i.E)(e)!==a-t)throw new r.ii({offset:a,position:"end",size:(0,i.E)(e)})}function c(e,t,a,{strict:r}={}){o(e,t);let n=e.slice(t,a);return r&&l(n,t,a),n}function u(e,t,a,{strict:r}={}){o(e,t);let n=`0x${e.replace("0x","").slice((t??0)*2,(a??e.length)*2)}`;return r&&l(n,t,a),n}},9110:function(e,t,a){"use strict";function r(e,{dir:t="left"}={}){let a="string"==typeof e?e.replace("0x",""):e,n=0;for(let e=0;e<a.length-1;e++)if("0"===a["left"===t?e:a.length-e-1].toString())n++;else break;return(a="left"===t?a.slice(n):a.slice(0,a.length-n),"string"==typeof e)?(1===a.length&&"right"===t&&(a=`${a}0`),`0x${a.length%2==1?`0${a}`:a}`):a}a.d(t,{B:()=>r})},948:function(e,t,a){"use strict";a.d(t,{IQ:()=>d,ME:()=>u,Nx:()=>c,Sl:()=>o,uU:()=>l});var r=a(2320),n=a(8887),i=a(9110),s=a(8669);function o(e,{size:t}){if((0,n.E)(e)>t)throw new r.u({givenSize:(0,n.E)(e),maxSize:t})}function l(e,t={}){let{signed:a}=t;t.size&&o(e,{size:t.size});let r=BigInt(e);if(!a)return r;let n=(e.length-2)/2;return r<=(1n<<8n*BigInt(n)-1n)-1n?r:r-BigInt(`0x${"f".padStart(2*n,"f")}`)-1n}function c(e,t={}){let a=e;if(t.size&&(o(a,{size:t.size}),a=(0,i.B)(a)),"0x00"===(0,i.B)(a))return!1;if("0x01"===(0,i.B)(a))return!0;throw new r.H2(a)}function u(e,t={}){return Number(l(e,t))}function d(e,t={}){let a=(0,s.aT)(e);return t.size&&(o(a,{size:t.size}),a=(0,i.B)(a,{dir:"right"})),new TextDecoder().decode(a)}},8669:function(e,t,a){"use strict";a.d(t,{Af:()=>h,ZJ:()=>c,aT:()=>d});var r=a(5382),n=a(8097),i=a(5969),s=a(948),o=a(5615);let l=new TextEncoder;function c(e,t={}){var a,r;return"number"==typeof e||"bigint"==typeof e?(a=e,r=t,d((0,o.cK)(a,r))):"boolean"==typeof e?function(e,t={}){let a=new Uint8Array(1);return(a[0]=Number(e),"number"==typeof t.size)?((0,s.Sl)(a,{size:t.size}),(0,i.eV)(a,{size:t.size})):a}(e,t):(0,n.q)(e)?d(e,t):h(e,t)}function u(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function d(e,t={}){let a=e;t.size&&((0,s.Sl)(a,{size:t.size}),a=(0,i.eV)(a,{dir:"right",size:t.size}));let n=a.slice(2);n.length%2&&(n=`0${n}`);let o=n.length/2,l=new Uint8Array(o);for(let e=0,t=0;e<o;e++){let a=u(n.charCodeAt(t++)),i=u(n.charCodeAt(t++));if(void 0===a||void 0===i)throw new r.C(`Invalid byte sequence ("${n[t-2]}${n[t-1]}" in "${n}").`);l[e]=16*a+i}return l}function h(e,t={}){let a=l.encode(e);return"number"==typeof t.size?((0,s.Sl)(a,{size:t.size}),(0,i.eV)(a,{dir:"right",size:t.size})):a}},5615:function(e,t,a){"use strict";a.d(t,{$P:()=>l,My:()=>c,cK:()=>u,i3:()=>h,nj:()=>o});var r=a(2320),n=a(5969),i=a(948);let s=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function o(e,t={}){return"number"==typeof e||"bigint"==typeof e?u(e,t):"string"==typeof e?h(e,t):"boolean"==typeof e?l(e,t):c(e,t)}function l(e,t={}){let a=`0x${Number(e)}`;return"number"==typeof t.size?((0,i.Sl)(a,{size:t.size}),(0,n.eV)(a,{size:t.size})):a}function c(e,t={}){let a="";for(let t=0;t<e.length;t++)a+=s[e[t]];let r=`0x${a}`;return"number"==typeof t.size?((0,i.Sl)(r,{size:t.size}),(0,n.eV)(r,{dir:"right",size:t.size})):r}function u(e,t={}){let a,{signed:i,size:s}=t,o=BigInt(e);s?a=i?(1n<<8n*BigInt(s)-1n)-1n:2n**(8n*BigInt(s))-1n:"number"==typeof e&&(a=BigInt(Number.MAX_SAFE_INTEGER));let l="bigint"==typeof a&&i?-a-1n:0;if(a&&o>a||o<l){let t="bigint"==typeof e?"n":"";throw new r.Ty({max:a?`${a}${t}`:void 0,min:`${l}${t}`,signed:i,size:s,value:`${e}${t}`})}let c=`0x${(i&&o<0?(1n<<BigInt(8*s))+BigInt(o):o).toString(16)}`;return s?(0,n.eV)(c,{size:s}):c}let d=new TextEncoder;function h(e,t={}){return c(d.encode(e),t)}},876:function(e,t,a){"use strict";a.d(t,{X:()=>g,J:()=>f});var r=a(8036),n=a(3858),i=a(2406),s=a(2935),o=a(7122),l=a(606),c=a(9646),u=a(6854),d=a(401);let h="/docs/contract/encodeErrorResult";function m(e){let{abi:t,errorName:a,args:r}=e,n=t[0];if(a){let e=(0,d.iY)({abi:t,args:r,name:a});if(!e)throw new s.yy(a,{docsPath:h});n=e}if("error"!==n.type)throw new s.yy(void 0,{docsPath:h});let i=(0,u.B)(n),m=(0,l.V)(i),p="0x";if(r&&r.length>0){if(!n.inputs)throw new s.ZP(n.name,{docsPath:h});p=(0,c.h)(n.inputs,r)}return(0,o.aP)([m,p])}let p="/docs/contract/encodeFunctionResult",f="x-batch-gateway:true";async function g(e){let{data:t,ccipRequest:a}=e,{args:[o]}=(0,i.J)({abi:r.b2,data:t}),l=[],u=[];return await Promise.all(o.map(async(e,t)=>{try{u[t]=e.urls.includes(f)?await g({data:e.data,ccipRequest:a}):await a(e),l[t]=!1}catch(e){var i;l[t]=!0,u[t]="HttpRequestError"===(i=e).name&&i.status?m({abi:r.b2,errorName:"HttpError",args:[i.status,i.shortMessage]}):m({abi:[n.Mc],errorName:"Error",args:["shortMessage"in i?i.shortMessage:i.message]})}})),function(e){let{abi:t,functionName:a,result:r}=e,n=t[0];if(a){let e=(0,d.iY)({abi:t,name:a});if(!e)throw new s.Iz(a,{docsPath:p});n=e}if("function"!==n.type)throw new s.Iz(void 0,{docsPath:p});if(!n.outputs)throw new s.MR(n.name,{docsPath:p});let i=(()=>{if(0===n.outputs.length)return[];if(1===n.outputs.length)return[r];if(Array.isArray(r))return r;throw new s.dm(r)})();return(0,c.h)(n.outputs,i)}({abi:r.b2,functionName:"query",result:[l,u]})}},5009:function(e,t,a){"use strict";a.d(t,{d:()=>s});var r=a(1020),n=a(2385),i=a(9277);function s(e,{docsPath:t,...a}){let s,o=(s=(0,i.l)(e,a))instanceof n.RM?e:s;return new r.zX(o,{docsPath:t,...a})}},9277:function(e,t,a){"use strict";a.d(t,{l:()=>i});var r=a(5382),n=a(2385);function i(e,t){let a=(e.details||"").toLowerCase(),i=e instanceof r.C?e.walk(e=>e?.code===n.A7.code):e;return i instanceof r.C?new n.A7({cause:e,message:i.details}):n.A7.nodeMessage.test(a)?new n.A7({cause:e,message:e.details}):n.BG.nodeMessage.test(a)?new n.BG({cause:e,maxFeePerGas:t?.maxFeePerGas}):n.jj.nodeMessage.test(a)?new n.jj({cause:e,maxFeePerGas:t?.maxFeePerGas}):n.K0.nodeMessage.test(a)?new n.K0({cause:e,nonce:t?.nonce}):n.Oh.nodeMessage.test(a)?new n.Oh({cause:e,nonce:t?.nonce}):n.vW.nodeMessage.test(a)?new n.vW({cause:e,nonce:t?.nonce}):n.k5.nodeMessage.test(a)?new n.k5({cause:e}):n.lY.nodeMessage.test(a)?new n.lY({cause:e,gas:t?.gas}):n.Fo.nodeMessage.test(a)?new n.Fo({cause:e,gas:t?.gas}):n.uC.nodeMessage.test(a)?new n.uC({cause:e}):n.lN.nodeMessage.test(a)?new n.lN({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas}):new n.RM({cause:e})}},8286:function(e,t,a){"use strict";function r(e,{format:t}){if(!t)return{};let a={};return!function t(r){for(let n of Object.keys(r))n in e&&(a[n]=e[n]),r[n]&&"object"==typeof r[n]&&!Array.isArray(r[n])&&t(r[n])}(t(e||{})),a}a.d(t,{o:()=>r})},5430:function(e,t,a){"use strict";a.d(t,{Bv:()=>i});var r=a(5615);let n={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function i(e,t){let a={};return void 0!==e.authorizationList&&(a.authorizationList=e.authorizationList.map(e=>({address:e.address,r:e.r?(0,r.cK)(BigInt(e.r)):e.r,s:e.s?(0,r.cK)(BigInt(e.s)):e.s,chainId:(0,r.cK)(e.chainId),nonce:(0,r.cK)(e.nonce),...void 0!==e.yParity?{yParity:(0,r.cK)(e.yParity)}:{},...void 0!==e.v&&void 0===e.yParity?{v:(0,r.cK)(e.v)}:{}}))),void 0!==e.accessList&&(a.accessList=e.accessList),void 0!==e.blobVersionedHashes&&(a.blobVersionedHashes=e.blobVersionedHashes),void 0!==e.blobs&&("string"!=typeof e.blobs[0]?a.blobs=e.blobs.map(e=>(0,r.My)(e)):a.blobs=e.blobs),void 0!==e.data&&(a.data=e.data),e.account&&(a.from=e.account.address),void 0!==e.from&&(a.from=e.from),void 0!==e.gas&&(a.gas=(0,r.cK)(e.gas)),void 0!==e.gasPrice&&(a.gasPrice=(0,r.cK)(e.gasPrice)),void 0!==e.maxFeePerBlobGas&&(a.maxFeePerBlobGas=(0,r.cK)(e.maxFeePerBlobGas)),void 0!==e.maxFeePerGas&&(a.maxFeePerGas=(0,r.cK)(e.maxFeePerGas)),void 0!==e.maxPriorityFeePerGas&&(a.maxPriorityFeePerGas=(0,r.cK)(e.maxPriorityFeePerGas)),void 0!==e.nonce&&(a.nonce=(0,r.cK)(e.nonce)),void 0!==e.to&&(a.to=e.to),void 0!==e.type&&(a.type=n[e.type]),void 0!==e.value&&(a.value=(0,r.cK)(e.value)),a}},4811:function(e,t,a){"use strict";a.d(t,{S:()=>o});var r=a(4588),n=a(8097),i=a(8669),s=a(5615);function o(e,t){let a=(0,r.lY)((0,n.q)(e,{strict:!1})?(0,i.ZJ)(e):e);return"bytes"===(t||"hex")?a:(0,s.nj)(a)}},9262:function(e,t,a){"use strict";a.d(t,{h:()=>r});let r=a(1265).k},606:function(e,t,a){"use strict";a.d(t,{V:()=>i});var r=a(9278),n=a(1265);let i=e=>(0,r.di)((0,n.k)(e),0,4)},1265:function(e,t,a){"use strict";a.d(t,{k:()=>c});var r=a(8669),n=a(4811),i=a(1999);let s=/^tuple(?<array>(\[(\d*)\])*)$/;function o(e){let t="",a=e.length;for(let r=0;r<a;r++)t+=function e(t){let a=t.type;if(s.test(t.type)&&"components"in t){a="(";let r=t.components.length;for(let n=0;n<r;n++)a+=e(t.components[n]),n<r-1&&(a+=", ");let n=(0,i.Yv)(s,t.type);return a+=`)${n?.array??""}`,e({...t,type:a})}return("indexed"in t&&t.indexed&&(a=`${a} indexed`),t.name)?`${a} ${t.name}`:a}(e[r]),r!==a-1&&(t+=", ");return t}var l=a(5382);function c(e){var t;return t=function(e){let t=!0,a="",r=0,n="",i=!1;for(let s=0;s<e.length;s++){let o=e[s];if(["(",")",","].includes(o)&&(t=!0),"("===o&&r++,")"===o&&r--,t){if(0===r){if(" "===o&&["event","function",""].includes(n))n="";else if(n+=o,")"===o){i=!0;break}continue}if(" "===o){","!==e[s-1]&&","!==a&&",("!==a&&(a="",t=!1);continue}n+=o,a+=o}}if(!i)throw new l.C("Unable to normalize signature.");return n}((()=>"string"==typeof e?e:"function"===e.type?`function ${e.name}(${o(e.inputs)})${e.stateMutability&&"nonpayable"!==e.stateMutability?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${o(e.outputs)})`:""}`:"event"===e.type?`event ${e.name}(${o(e.inputs)})`:"error"===e.type?`error ${e.name}(${o(e.inputs)})`:"constructor"===e.type?`constructor(${o(e.inputs)})${"payable"===e.stateMutability?" payable":""}`:"fallback"===e.type?`fallback() external${"payable"===e.stateMutability?" payable":""}`:"receive() external payable")()),(0,n.S)((0,r.ZJ)(t))}},4106:function(e,t,a){"use strict";a.d(t,{A:()=>r});class r extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){let t=super.get(e);return super.has(e)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){let e=this.keys().next().value;e&&this.delete(e)}return this}}},6944:function(e,t,a){"use strict";a.d(t,{u:()=>i});var r=a(1050);let n=new Map;function i({fn:e,id:t,shouldSplitBatch:a,wait:i=0,sort:s}){let o=async()=>{let t=c();l();let a=t.map(({args:e})=>e);0!==a.length&&e(a).then(e=>{s&&Array.isArray(e)&&e.sort(s);for(let a=0;a<t.length;a++){let{resolve:r}=t[a];r?.([e[a],e])}}).catch(e=>{for(let a=0;a<t.length;a++){let{reject:r}=t[a];r?.(e)}})},l=()=>n.delete(t),c=()=>n.get(t)||[],u=e=>n.set(t,[...c(),e]);return{flush:l,async schedule(e){let{promise:t,resolve:n,reject:s}=(0,r.Y)();return(a?.([...c().map(({args:e})=>e),e])&&o(),c().length>0)?u({args:e,resolve:n,reject:s}):(u({args:e,resolve:n,reject:s}),setTimeout(o,i)),t}}}},1050:function(e,t,a){"use strict";function r(){let e=()=>void 0,t=()=>void 0;return{promise:new Promise((a,r)=>{e=a,t=r}),resolve:e,reject:t}}a.d(t,{Y:()=>r})},3072:function(e,t,a){"use strict";a.d(t,{BD:()=>n,D5:()=>r,Ge:()=>i});let r=/^(.*)\[([0-9]*)\]$/,n=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,i=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/},2882:function(e,t,a){"use strict";a.d(t,{yH:()=>c});var r=a(4309),n=a(5229),i=a(3412),s=a(9188),o=a(5615);function l(e){if(e&&0!==e.length)return e.reduce((e,{slot:t,value:a})=>{if(66!==t.length)throw new n.NV({size:t.length,targetSize:66,type:"hex"});if(66!==a.length)throw new n.NV({size:a.length,targetSize:66,type:"hex"});return e[t]=a,e},{})}function c(e){if(!e)return;let t={};for(let{address:a,...n}of e){if(!(0,s.P)(a,{strict:!1}))throw new r.M({address:a});if(t[a])throw new i.Hi({address:a});t[a]=function(e){let{balance:t,nonce:a,state:r,stateDiff:n,code:s}=e,c={};if(void 0!==s&&(c.code=s),void 0!==t&&(c.balance=(0,o.cK)(t)),void 0!==a&&(c.nonce=(0,o.cK)(a)),void 0!==r&&(c.state=l(r)),void 0!==n){if(c.state)throw new i.ft;c.stateDiff=l(n)}return c}(n)}return t}},7998:function(e,t,a){"use strict";a.d(t,{A:()=>r});let r=(e,t,a)=>JSON.stringify(e,(e,a)=>{let r="bigint"==typeof a?a.toString():a;return"function"==typeof t?t(e,r):r},a)},7846:function(e,t,a){"use strict";a.d(t,{c:()=>c});var r=a(6540);let n=2n**256n-1n;var i=a(4309),s=a(2385),o=a(897),l=a(9188);function c(e){let{account:t,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,to:d}=e,h=t?(0,r.J)(t):void 0;if(h&&!(0,l.P)(h.address))throw new i.M({address:h.address});if(d&&!(0,l.P)(d))throw new i.M({address:d});if(void 0!==a&&(void 0!==c||void 0!==u))throw new o.n3;if(c&&c>n)throw new s.BG({maxFeePerGas:c});if(u&&c&&u>c)throw new s.lN({maxFeePerGas:c,maxPriorityFeePerGas:u})}},5071:function(e,t,a){"use strict";a.d(t,{c:()=>i});var r=a(6993),n=a(9644);function i(e,t="wei"){return(0,n.J)(e,r.eL[t])}},2239:function(e,t,a){"use strict";a.d(t,{Q:()=>i});var r=a(6993),n=a(9644);function i(e,t="wei"){return(0,n.J)(e,r.sz[t])}},9644:function(e,t,a){"use strict";function r(e,t){let a=e.toString(),r=a.startsWith("-");r&&(a=a.slice(1));let[n,i]=[(a=a.padStart(t,"0")).slice(0,a.length-t),a.slice(a.length-t)];return i=i.replace(/(0+)$/,""),`${r?"-":""}${n||"0"}${i?`.${i}`:""}`}a.d(t,{J:()=>r})}},r={};function n(e){var t=r[e];if(void 0!==t)return t.exports;var i=r[e]={exports:{}};return a[e].call(i.exports,i,i.exports,n),i.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,n.t=function(a,r){if(1&r&&(a=this(a)),8&r||"object"==typeof a&&a&&(4&r&&a.__esModule||16&r&&"function"==typeof a.then))return a;var i=Object.create(null);n.r(i);var s={};e=e||[null,t({}),t([]),t(t)];for(var o=2&r&&a;("object"==typeof o||"function"==typeof o)&&!~e.indexOf(o);o=t(o))Object.getOwnPropertyNames(o).forEach(e=>{s[e]=()=>a[e]});return s.default=()=>a,n.d(i,s),i},n.d=(e,t)=>{for(var a in t)n.o(t,a)&&!n.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,get:t[a]})},n.g=(()=>{if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}})(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};(()=>{"use strict";let e,t,a,r;function s(){return"undefined"!=typeof window}n.r(i),n.d(i,{EmailLinkError:()=>z,isUserLockedError:()=>R,ClerkAPIResponseError:()=>v,EmailLinkErrorCodeStatus:()=>A,isKnownError:()=>O,Clerk:()=>nz,isMetamaskError:()=>M,EmailLinkErrorCode:()=>S,ClerkRuntimeError:()=>E,isClerkRuntimeError:()=>U,isClerkAPIResponseError:()=>T,isEmailLinkError:()=>B}),n(653);let o=RegExp("bot|spider|crawl|APIs-Google|AdsBot|Googlebot|mediapartners|Google Favicon|FeedFetcher|Google-Read-Aloud|DuplexWeb-Google|googleweblight|bing|yandex|baidu|duckduck|yahoo|ecosia|ia_archiver|facebook|instagram|pinterest|reddit|slack|twitter|whatsapp|youtube|semrush","i");function l(){var e;let t=s()?window?.navigator:null;return!!t&&!((e=t?.userAgent)&&o.test(e))&&!t?.webdriver}function c(){let e=s()?window?.navigator:null;if(!e)return!1;let t=e?.onLine;return e?.connection?.rtt!==0&&e?.connection?.downlink!==0&&t}function u(){return c()&&l()}let d=(e,t,a,r,n)=>{let{notify:i}=n||{},s=e.get(a);s||(s=[],e.set(a,s)),s.push(r),i&&t.has(a)&&r(t.get(a))},h=(e,t,a)=>(e.get(t)||[]).map(e=>e(a)),m=(e,t,a)=>{let r=e.get(t);r&&(a?r.splice(r.indexOf(a)>>>0,1):e.set(t,[]))},p=()=>{let e=new Map,t=new Map,a=new Map;return{on:(...a)=>d(e,t,...a),prioritizedOn:(...e)=>d(a,t,...e),emit:(r,n)=>{t.set(r,n),h(a,r,n),h(e,r,n)},off:(...t)=>m(e,...t),prioritizedOff:(...e)=>m(a,...e),internal:{retrieveListeners:t=>e.get(t)||[]}}},f="status";function g(e){return function(t){let a=t??this;if(!a)throw TypeError(`${e.kind||e.name} type guard requires an error object`);return a instanceof e}}var b,y,w=class{static kind="ClerkApiError";code;message;longMessage;meta;constructor(e){const t={code:e.code,message:e.message,longMessage:e.long_message,meta:{paramName:e.meta?.param_name,sessionId:e.meta?.session_id,emailAddresses:e.meta?.email_addresses,identifiers:e.meta?.identifiers,zxcvbn:e.meta?.zxcvbn,plan:e.meta?.plan,isPlanUpgradePossible:e.meta?.is_plan_upgrade_possible}};this.code=t.code,this.message=t.message,this.longMessage=t.longMessage,this.meta=t.meta}};g(w);var k=class e extends Error{static kind="ClerkError";clerkError=!0;code;longMessage;docsUrl;cause;get name(){return this.constructor.name}constructor(t){super(new.target.formatMessage(new.target.kind,t.message,t.code,t.docsUrl),{cause:t.cause}),Object.setPrototypeOf(this,e.prototype),this.code=t.code,this.docsUrl=t.docsUrl,this.longMessage=t.longMessage,this.cause=t.cause}toString(){return`[${this.name}]
45
+ `),a.state&&(r+=" state:\n",r+=s(a.state)),a.stateDiff&&(r+=" stateDiff:\n",r+=s(a.stateDiff)),r}," State Override:\n").slice(0,-1)}},897:function(e,t,a){"use strict";a.d(t,{Kc:()=>l,Kz:()=>o,Sq:()=>c,Vg:()=>s,WA:()=>u,aO:()=>n,n3:()=>i}),a(5071),a(2239);var r=a(5382);function n(e){let t=Object.entries(e).map(([e,t])=>void 0===t||!1===t?null:[e,t]).filter(Boolean),a=t.reduce((e,[t])=>Math.max(e,t.length),0);return t.map(([e,t])=>` ${`${e}:`.padEnd(a+1)} ${t}`).join("\n")}class i extends r.C{constructor(){super("Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.\nUse `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others.",{name:"FeeConflictError"})}}r.C;class s extends r.C{constructor({transaction:e}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",n(e),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}r.C,r.C,r.C,r.C;class o extends r.C{constructor({blockHash:e,blockNumber:t,blockTag:a,hash:r,index:n}){let i="Transaction";a&&void 0!==n&&(i=`Transaction at block time "${a}" at index "${n}"`),e&&void 0!==n&&(i=`Transaction at block hash "${e}" at index "${n}"`),t&&void 0!==n&&(i=`Transaction at block number "${t}" at index "${n}"`),r&&(i=`Transaction with hash "${r}"`),super(`${i} could not be found.`,{name:"TransactionNotFoundError"})}}class l extends r.C{constructor({hash:e}){super(`Transaction receipt with hash "${e}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}}class c extends r.C{constructor({receipt:e}){super(`Transaction with hash "${e.transactionHash}" reverted.`,{metaMessages:['The receipt marked the transaction as "reverted". This could mean that the function on the contract you are trying to call threw an error.'," ","You can attempt to extract the revert reason by:","- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract","- using the `call` Action with raw `data`"],name:"TransactionReceiptRevertedError"}),Object.defineProperty(this,"receipt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.receipt=e}}class u extends r.C{constructor({hash:e}){super(`Timed out while waiting for transaction with hash "${e}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}},7124:function(e,t,a){"use strict";a.d(t,{I:()=>n,R:()=>r});let r=e=>e,n=e=>e},3896:function(e,t,a){"use strict";a.d(t,{n:()=>f});var r=a(2935),n=a(9938),i=a(9785),s=a(8887),o=a(9278),l=a(9110),c=a(2320),u=a(948),d=a(5615);function h(e,t={}){void 0!==t.size&&(0,u.Sl)(e,{size:t.size});let a=(0,d.My)(e,t);return(0,u.ME)(a,t)}var m=a(8669),p=a(9646);function f(e,t){let a="string"==typeof t?(0,m.aT)(t):t,f=(0,i.l)(a);if(0===(0,s.E)(a)&&e.length>0)throw new r.O;if((0,s.E)(t)&&32>(0,s.E)(t))throw new r.Iy({data:"string"==typeof t?t:(0,d.My)(t),params:e,size:(0,s.E)(t)});let b=0,y=[];for(let t=0;t<e.length;++t){let a=e[t];f.setPosition(b);let[i,s]=function e(t,a,{staticPosition:i}){let s=(0,p.k)(a.type);if(s){let[r,n]=s;return function(t,a,{length:r,staticPosition:n}){if(!r){let r=n+h(t.readBytes(32)),i=r+32;t.setPosition(r);let s=h(t.readBytes(32)),o=g(a),l=0,c=[];for(let r=0;r<s;++r){t.setPosition(i+(o?32*r:l));let[n,s]=e(t,a,{staticPosition:i});l+=s,c.push(n)}return t.setPosition(n+32),[c,32]}if(g(a)){let i=n+h(t.readBytes(32)),s=[];for(let n=0;n<r;++n){t.setPosition(i+32*n);let[r]=e(t,a,{staticPosition:i});s.push(r)}return t.setPosition(n+32),[s,32]}let i=0,s=[];for(let o=0;o<r;++o){let[r,o]=e(t,a,{staticPosition:n+i});i+=o,s.push(r)}return[s,i]}(t,{...a,type:n},{length:r,staticPosition:i})}if("tuple"===a.type)return function(t,a,{staticPosition:r}){let n=0===a.components.length||a.components.some(({name:e})=>!e),i=n?[]:{},s=0;if(g(a)){let o=r+h(t.readBytes(32));for(let r=0;r<a.components.length;++r){let l=a.components[r];t.setPosition(o+s);let[c,u]=e(t,l,{staticPosition:o});s+=u,i[n?r:l?.name]=c}return t.setPosition(r+32),[i,32]}for(let o=0;o<a.components.length;++o){let l=a.components[o],[c,u]=e(t,l,{staticPosition:r});i[n?o:l?.name]=c,s+=u}return[i,s]}(t,a,{staticPosition:i});if("address"===a.type){let e;return e=t.readBytes(32),[(0,n.o)((0,d.My)((0,o.A1)(e,-20))),32]}if("bool"===a.type)return[function(e,t={}){let a=e;if(void 0!==t.size&&((0,u.Sl)(a,{size:t.size}),a=(0,l.B)(a)),a.length>1||a[0]>1)throw new c.xO(a);return!!a[0]}(t.readBytes(32),{size:32}),32];if(a.type.startsWith("bytes"))return function(e,t,{staticPosition:a}){let[r,n]=t.type.split("bytes");if(!n){let t=h(e.readBytes(32));e.setPosition(a+t);let r=h(e.readBytes(32));if(0===r)return e.setPosition(a+32),["0x",32];let n=e.readBytes(r);return e.setPosition(a+32),[(0,d.My)(n),32]}return[(0,d.My)(e.readBytes(Number.parseInt(n,10),32)),32]}(t,a,{staticPosition:i});if(a.type.startsWith("uint")||a.type.startsWith("int")){var m,f;let e,r,n;return m=t,e=(f=a).type.startsWith("int"),r=Number.parseInt(f.type.split("int")[1]||"256",10),n=m.readBytes(32),[r>48?function(e,t={}){void 0!==t.size&&(0,u.Sl)(e,{size:t.size});let a=(0,d.My)(e,t);return(0,u.uU)(a,t)}(n,{signed:e}):h(n,{signed:e}),32]}if("string"===a.type)return function(e,{staticPosition:t}){let a=h(e.readBytes(32));e.setPosition(t+a);let r=h(e.readBytes(32));if(0===r)return e.setPosition(t+32),["",32];let n=e.readBytes(r,32),i=function(e,t={}){let a=e;return void 0!==t.size&&((0,u.Sl)(a,{size:t.size}),a=(0,l.B)(a,{dir:"right"})),new TextDecoder().decode(a)}((0,l.B)(n));return e.setPosition(t+32),[i,32]}(t,{staticPosition:i});throw new r.j(a.type,{docsPath:"/docs/contract/decodeAbiParameters"})}(f,a,{staticPosition:0});b+=s,y.push(i)}return y}function g(e){let{type:t}=e;if("string"===t||"bytes"===t||t.endsWith("[]"))return!0;if("tuple"===t)return e.components?.some(g);let a=(0,p.k)(e.type);return!!(a&&g({...e,type:a[1]}))}},1859:function(e,t,a){"use strict";a.d(t,{W:()=>c});var r=a(3858),n=a(2935),i=a(9278),s=a(606),o=a(3896),l=a(6854);function c(e){let{abi:t,data:a}=e,c=(0,i.di)(a,0,4);if("0x"===c)throw new n.O;let u=[...t||[],r.Mc,r.J9].find(e=>"error"===e.type&&c===(0,s.V)((0,l.B)(e)));if(!u)throw new n.Wq(c,{docsPath:"/docs/contract/decodeErrorResult"});return{abiItem:u,args:"inputs"in u&&u.inputs&&u.inputs.length>0?(0,o.n)(u.inputs,(0,i.di)(a,4)):void 0,errorName:u.name}}},2406:function(e,t,a){"use strict";a.d(t,{J:()=>l});var r=a(2935),n=a(9278),i=a(606),s=a(3896),o=a(6854);function l(e){let{abi:t,data:a}=e,l=(0,n.di)(a,0,4),c=t.find(e=>"function"===e.type&&l===(0,i.V)((0,o.B)(e)));if(!c)throw new r.EB(l,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:c.name,args:"inputs"in c&&c.inputs&&c.inputs.length>0?(0,s.n)(c.inputs,(0,n.di)(a,4)):void 0}}},2987:function(e,t,a){"use strict";a.d(t,{e:()=>o});var r=a(2935),n=a(3896),i=a(401);let s="/docs/contract/decodeFunctionResult";function o(e){let{abi:t,args:a,functionName:o,data:l}=e,c=t[0];if(o){let e=(0,i.iY)({abi:t,args:a,name:o});if(!e)throw new r.Iz(o,{docsPath:s});c=e}if("function"!==c.type)throw new r.Iz(void 0,{docsPath:s});if(!c.outputs)throw new r.MR(c.name,{docsPath:s});let u=(0,n.n)(c.outputs,l);return u&&u.length>1?u:u&&1===u.length?u[0]:void 0}},9646:function(e,t,a){"use strict";a.d(t,{h:()=>p,k:()=>g});var r=a(2935),n=a(4309),i=a(5382),s=a(2320),o=a(9188),l=a(7122),c=a(5969),u=a(8887),d=a(9278),h=a(5615),m=a(3072);function p(e,t){if(e.length!==t.length)throw new r.YE({expectedLength:e.length,givenLength:t.length});let a=f(function({params:e,values:t}){let a=[];for(let p=0;p<e.length;p++)a.push(function e({param:t,value:a}){let p=g(t.type);if(p){let[n,i]=p;return function(t,{length:a,param:n}){let i=null===a;if(!Array.isArray(t))throw new r.dm(t);if(!i&&t.length!==a)throw new r.Nc({expectedLength:a,givenLength:t.length,type:`${n.type}[${a}]`});let s=!1,o=[];for(let a=0;a<t.length;a++){let r=e({param:n,value:t[a]});r.dynamic&&(s=!0),o.push(r)}if(i||s){let e=f(o);if(i){let t=(0,h.cK)(o.length,{size:32});return{dynamic:!0,encoded:o.length>0?(0,l.xW)([t,e]):t}}if(s)return{dynamic:!0,encoded:e}}return{dynamic:!1,encoded:(0,l.xW)(o.map(({encoded:e})=>e))}}(a,{length:n,param:{...t,type:i}})}if("tuple"===t.type)return function(t,{param:a}){let r=!1,n=[];for(let i=0;i<a.components.length;i++){let s=a.components[i],o=Array.isArray(t)?i:s.name,l=e({param:s,value:t[o]});n.push(l),l.dynamic&&(r=!0)}return{dynamic:r,encoded:r?f(n):(0,l.xW)(n.map(({encoded:e})=>e))}}(a,{param:t});if("address"===t.type){var b=a;if(!(0,o.P)(b))throw new n.M({address:b});return{dynamic:!1,encoded:(0,c.db)(b.toLowerCase())}}if("bool"===t.type){var y=a;if("boolean"!=typeof y)throw new i.C(`Invalid boolean value: "${y}" (type: ${typeof y}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:(0,c.db)((0,h.$P)(y))}}if(t.type.startsWith("uint")||t.type.startsWith("int")){let e=t.type.startsWith("int"),[,,r="256"]=m.Ge.exec(t.type)??[];return function(e,{signed:t,size:a=256}){if("number"==typeof a){let r=2n**(BigInt(a)-(t?1n:0n))-1n,n=t?-r-1n:0n;if(e>r||e<n)throw new s.Ty({max:r.toString(),min:n.toString(),signed:t,size:a/8,value:e.toString()})}return{dynamic:!1,encoded:(0,h.cK)(e,{size:32,signed:t})}}(a,{signed:e,size:Number(r)})}if(t.type.startsWith("bytes"))return function(e,{param:t}){let[,a]=t.type.split("bytes"),n=(0,u.E)(e);if(!a){let t=e;return n%32!=0&&(t=(0,c.db)(t,{dir:"right",size:32*Math.ceil((e.length-2)/2/32)})),{dynamic:!0,encoded:(0,l.xW)([(0,c.db)((0,h.cK)(n,{size:32})),t])}}if(n!==Number.parseInt(a,10))throw new r.gH({expectedSize:Number.parseInt(a,10),value:e});return{dynamic:!1,encoded:(0,c.db)(e,{dir:"right"})}}(a,{param:t});if("string"===t.type){var w=a;let e=(0,h.i3)(w),t=Math.ceil((0,u.E)(e)/32),r=[];for(let a=0;a<t;a++)r.push((0,c.db)((0,d.di)(e,32*a,(a+1)*32),{dir:"right"}));return{dynamic:!0,encoded:(0,l.xW)([(0,c.db)((0,h.cK)((0,u.E)(e),{size:32})),...r])}}throw new r.nK(t.type,{docsPath:"/docs/contract/encodeAbiParameters"})}({param:e[p],value:t[p]}));return a}({params:e,values:t}));return 0===a.length?"0x":a}function f(e){let t=0;for(let a=0;a<e.length;a++){let{dynamic:r,encoded:n}=e[a];r?t+=32:t+=(0,u.E)(n)}let a=[],r=[],n=0;for(let i=0;i<e.length;i++){let{dynamic:s,encoded:o}=e[i];s?(a.push((0,h.cK)(t+n,{size:32})),r.push(o),n+=(0,u.E)(o)):a.push(o)}return(0,l.xW)([...a,...r])}function g(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}},5745:function(e,t,a){"use strict";a.d(t,{m:()=>o});var r=a(2935),n=a(7122),i=a(9646);let s="/docs/contract/encodeDeployData";function o(e){let{abi:t,args:a,bytecode:o}=e;if(!a||0===a.length)return o;let l=t.find(e=>"type"in e&&"constructor"===e.type);if(!l)throw new r.YW({docsPath:s});if(!("inputs"in l)||!l.inputs||0===l.inputs.length)throw new r.YF({docsPath:s});let c=(0,i.h)(l.inputs,a);return(0,n.aP)([o,c])}},5823:function(e,t,a){"use strict";a.d(t,{p:()=>u});var r=a(7122),n=a(9646),i=a(2935),s=a(606),o=a(6854),l=a(401);let c="/docs/contract/encodeFunctionData";function u(e){let{args:t}=e,{abi:a,functionName:u}=1===e.abi.length&&e.functionName?.startsWith("0x")?e:function(e){let{abi:t,args:a,functionName:r}=e,n=t[0];if(r){let e=(0,l.iY)({abi:t,args:a,name:r});if(!e)throw new i.Iz(r,{docsPath:c});n=e}if("function"!==n.type)throw new i.Iz(void 0,{docsPath:c});return{abi:[n],functionName:(0,s.V)((0,o.B)(n))}}(e),d=a[0],h="inputs"in d&&d.inputs?(0,n.h)(d.inputs,t??[]):void 0;return(0,r.aP)([u,h??"0x"])}},6854:function(e,t,a){"use strict";a.d(t,{A:()=>i,B:()=>n});var r=a(2935);function n(e,{includeName:t=!1}={}){if("function"!==e.type&&"event"!==e.type&&"error"!==e.type)throw new r.d_(e.type);return`${e.name}(${i(e.inputs,{includeName:t})})`}function i(e,{includeName:t=!1}={}){return e?e.map(e=>(function(e,{includeName:t}){return e.type.startsWith("tuple")?`(${i(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")})(e,{includeName:t})).join(t?", ":","):""}},401:function(e,t,a){"use strict";a.d(t,{iY:()=>l});var r=a(2935),n=a(8097),i=a(9188),s=a(9262),o=a(606);function l(e){let t,{abi:a,args:l=[],name:c}=e,u=(0,n.q)(c,{strict:!1}),d=a.filter(e=>u?"function"===e.type?(0,o.V)(e)===c:"event"===e.type&&(0,s.h)(e)===c:"name"in e&&e.name===c);if(0!==d.length){if(1===d.length)return d[0];for(let e of d){if("inputs"in e){if(!l||0===l.length){if(!e.inputs||0===e.inputs.length)return e;continue}if(e.inputs&&0!==e.inputs.length&&e.inputs.length===l.length&&l.every((t,a)=>{let r="inputs"in e&&e.inputs[a];return!!r&&function e(t,a){let r=typeof t,n=a.type;switch(n){case"address":return(0,i.P)(t,{strict:!1});case"bool":return"boolean"===r;case"function":case"string":return"string"===r;default:if("tuple"===n&&"components"in a)return Object.values(a.components).every((a,r)=>e(Object.values(t)[r],a));if(/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n))return"number"===r||"bigint"===r;if(/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n))return"string"===r||t instanceof Uint8Array;if(/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n))return Array.isArray(t)&&t.every(t=>e(t,{...a,type:n.replace(/(\[[0-9]{0,}\])$/,"")}));return!1}}(t,r)})){if(t&&"inputs"in t&&t.inputs){let a=function e(t,a,r){for(let n in t){let s=t[n],o=a[n];if("tuple"===s.type&&"tuple"===o.type&&"components"in s&&"components"in o)return e(s.components,o.components,r[n]);let l=[s.type,o.type];if(l.includes("address")&&l.includes("bytes20")||(l.includes("address")&&l.includes("string")||l.includes("address")&&l.includes("bytes"))&&(0,i.P)(r[n],{strict:!1}))return l}}(e.inputs,t.inputs,l);if(a)throw new r.nM({abiItem:e,type:a[0]},{abiItem:t,type:a[1]})}t=e}}}return t||d[0]}}},9938:function(e,t,a){"use strict";a.d(t,{b:()=>u,o:()=>c});var r=a(4309),n=a(8669),i=a(4811),s=a(4106),o=a(9188);let l=new s.A(8192);function c(e,t){if(l.has(`${e}.${t}`))return l.get(`${e}.${t}`);let a=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),r=(0,i.S)((0,n.Af)(a),"bytes"),s=(t?a.substring(`${t}0x`.length):a).split("");for(let e=0;e<40;e+=2)r[e>>1]>>4>=8&&s[e]&&(s[e]=s[e].toUpperCase()),(15&r[e>>1])>=8&&s[e+1]&&(s[e+1]=s[e+1].toUpperCase());let o=`0x${s.join("")}`;return l.set(`${e}.${t}`,o),o}function u(e,t){if(!(0,o.P)(e,{strict:!1}))throw new r.M({address:e});return c(e,t)}},9188:function(e,t,a){"use strict";a.d(t,{P:()=>o});var r=a(4106),n=a(9938);let i=/^0x[a-fA-F0-9]{40}$/,s=new r.A(8192);function o(e,t){let{strict:a=!0}=t??{},r=`${e}.${a}`;if(s.has(r))return s.get(r);let o=!!i.test(e)&&(e.toLowerCase()===e||!a||(0,n.o)(e)===e);return s.set(r,o),o}},3950:function(e,t,a){"use strict";a.d(t,{h:()=>i});var r=a(4309),n=a(9188);function i(e,t){if(!(0,n.P)(e,{strict:!1}))throw new r.M({address:e});if(!(0,n.P)(t,{strict:!1}))throw new r.M({address:t});return e.toLowerCase()===t.toLowerCase()}},3330:function(e,t,a){"use strict";a.d(t,{offchainLookupSignature:()=>b,offchainLookup:()=>w});var r=a(4016),n=a(7998),i=a(5382),s=a(7124);class o extends i.C{constructor({callbackSelector:e,cause:t,data:a,extraData:r,sender:n,urls:i}){super(t.shortMessage||"An error occurred while fetching for an offchain result.",{cause:t,metaMessages:[...t.metaMessages||[],t.metaMessages?.length?"":[],"Offchain Gateway Call:",i&&[" Gateway URL(s):",...i.map(e=>` ${(0,s.I)(e)}`)],` Sender: ${n}`,` Data: ${a}`,` Callback selector: ${e}`,` Extra data: ${r}`].flat(),name:"OffchainLookupError"})}}class l extends i.C{constructor({result:e,url:t}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${(0,s.I)(t)}`,`Response: ${(0,n.A)(e)}`],name:"OffchainLookupResponseMalformedError"})}}class c extends i.C{constructor({sender:e,to:t}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${t}`,`OffchainLookup sender address: ${e}`],name:"OffchainLookupSenderMismatchError"})}}var u=a(236),d=a(1859),h=a(9646),m=a(3950),p=a(7122),f=a(8097),g=a(876);let b="0x556f1830",y={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]};async function w(e,{blockNumber:t,blockTag:a,data:n,to:i}){let{args:s}=(0,d.W)({data:n,abi:[y]}),[l,u,f,b,w]=s,{ccipRead:v}=e,x=v&&"function"==typeof v?.request?v.request:k;try{if(!(0,m.h)(i,l))throw new c({sender:l,to:i});let n=u.includes(g.J)?await (0,g.X)({data:f,ccipRequest:x}):await x({data:f,sender:l,urls:u}),{data:s}=await (0,r.T)(e,{blockNumber:t,blockTag:a,data:(0,p.xW)([b,(0,h.h)([{type:"bytes"},{type:"bytes"}],[n,w])]),to:i});return s}catch(e){throw new o({callbackSelector:b,cause:e,data:n,extraData:w,sender:l,urls:u})}}async function k({data:e,sender:t,urls:a}){let r=Error("An unknown error occurred.");for(let i=0;i<a.length;i++){let s=a[i],o=s.includes("{data}")?"GET":"POST",c="POST"===o?{data:e,sender:t}:void 0,d="POST"===o?{"Content-Type":"application/json"}:{};try{let a,i=await fetch(s.replace("{sender}",t.toLowerCase()).replace("{data}",e),{body:JSON.stringify(c),headers:d,method:o});if(a=i.headers.get("Content-Type")?.startsWith("application/json")?(await i.json()).data:await i.text(),!i.ok){r=new u.Ci({body:c,details:a?.error?(0,n.A)(a.error):i.statusText,headers:i.headers,status:i.status,url:s});continue}if(!(0,f.q)(a)){r=new l({result:a,url:s});continue}return a}catch(e){r=new u.Ci({body:c,details:e.message,url:s})}}throw r}},3228:function(e,t,a){"use strict";a.d(t,{M:()=>n});var r=a(372);function n({blockNumber:e,chain:t,contract:a}){let n=t?.contracts?.[a];if(!n)throw new r.rj({chain:t,contract:{name:a}});if(e&&n.blockCreated&&n.blockCreated>e)throw new r.rj({blockNumber:e,chain:t,contract:{name:a,blockCreated:n.blockCreated}});return n.address}},9785:function(e,t,a){"use strict";a.d(t,{l:()=>i});var r=a(9799);let n={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:1/0,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new r.hX({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new r.SK({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new r.B4({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new r.B4({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let a=t??this.position;return this.assertPosition(a+e-1),this.bytes.subarray(a,a+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,255&e),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let a=this.inspectBytes(e);return this.position+=t??e,a},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===1/0)return;let e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};function i(e,{recursiveReadLimit:t=8192}={}){let a=Object.create(n);return a.bytes=e,a.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),a.positionReadCount=new Map,a.recursiveReadLimit=t,a}},7122:function(e,t,a){"use strict";function r(e){return"string"==typeof e[0]?n(e):function(e){let t=0;for(let a of e)t+=a.length;let a=new Uint8Array(t),r=0;for(let t of e)a.set(t,r),r+=t.length;return a}(e)}function n(e){return`0x${e.reduce((e,t)=>e+t.replace("0x",""),"")}`}a.d(t,{aP:()=>n,xW:()=>r})},8097:function(e,t,a){"use strict";function r(e,{strict:t=!0}={}){return!!e&&"string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x"))}a.d(t,{q:()=>r})},5969:function(e,t,a){"use strict";a.d(t,{db:()=>i,eV:()=>n});var r=a(5229);function n(e,{dir:t,size:a=32}={}){return"string"==typeof e?i(e,{dir:t,size:a}):function(e,{dir:t,size:a=32}={}){if(null===a)return e;if(e.length>a)throw new r.Fl({size:e.length,targetSize:a,type:"bytes"});let n=new Uint8Array(a);for(let r=0;r<a;r++){let i="right"===t;n[i?r:a-r-1]=e[i?r:e.length-r-1]}return n}(e,{dir:t,size:a})}function i(e,{dir:t,size:a=32}={}){if(null===a)return e;let n=e.replace("0x","");if(n.length>2*a)throw new r.Fl({size:Math.ceil(n.length/2),targetSize:a,type:"hex"});return`0x${n["right"===t?"padEnd":"padStart"](2*a,"0")}`}},8887:function(e,t,a){"use strict";a.d(t,{E:()=>n});var r=a(8097);function n(e){return(0,r.q)(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}},9278:function(e,t,a){"use strict";a.d(t,{A1:()=>c,di:()=>s,iN:()=>u});var r=a(5229),n=a(8097),i=a(8887);function s(e,t,a,{strict:r}={}){return(0,n.q)(e,{strict:!1})?u(e,t,a,{strict:r}):c(e,t,a,{strict:r})}function o(e,t){if("number"==typeof t&&t>0&&t>(0,i.E)(e)-1)throw new r.ii({offset:t,position:"start",size:(0,i.E)(e)})}function l(e,t,a){if("number"==typeof t&&"number"==typeof a&&(0,i.E)(e)!==a-t)throw new r.ii({offset:a,position:"end",size:(0,i.E)(e)})}function c(e,t,a,{strict:r}={}){o(e,t);let n=e.slice(t,a);return r&&l(n,t,a),n}function u(e,t,a,{strict:r}={}){o(e,t);let n=`0x${e.replace("0x","").slice((t??0)*2,(a??e.length)*2)}`;return r&&l(n,t,a),n}},9110:function(e,t,a){"use strict";function r(e,{dir:t="left"}={}){let a="string"==typeof e?e.replace("0x",""):e,n=0;for(let e=0;e<a.length-1;e++)if("0"===a["left"===t?e:a.length-e-1].toString())n++;else break;return(a="left"===t?a.slice(n):a.slice(0,a.length-n),"string"==typeof e)?(1===a.length&&"right"===t&&(a=`${a}0`),`0x${a.length%2==1?`0${a}`:a}`):a}a.d(t,{B:()=>r})},948:function(e,t,a){"use strict";a.d(t,{IQ:()=>d,ME:()=>u,Nx:()=>c,Sl:()=>o,uU:()=>l});var r=a(2320),n=a(8887),i=a(9110),s=a(8669);function o(e,{size:t}){if((0,n.E)(e)>t)throw new r.u({givenSize:(0,n.E)(e),maxSize:t})}function l(e,t={}){let{signed:a}=t;t.size&&o(e,{size:t.size});let r=BigInt(e);if(!a)return r;let n=(e.length-2)/2;return r<=(1n<<8n*BigInt(n)-1n)-1n?r:r-BigInt(`0x${"f".padStart(2*n,"f")}`)-1n}function c(e,t={}){let a=e;if(t.size&&(o(a,{size:t.size}),a=(0,i.B)(a)),"0x00"===(0,i.B)(a))return!1;if("0x01"===(0,i.B)(a))return!0;throw new r.H2(a)}function u(e,t={}){return Number(l(e,t))}function d(e,t={}){let a=(0,s.aT)(e);return t.size&&(o(a,{size:t.size}),a=(0,i.B)(a,{dir:"right"})),new TextDecoder().decode(a)}},8669:function(e,t,a){"use strict";a.d(t,{Af:()=>h,ZJ:()=>c,aT:()=>d});var r=a(5382),n=a(8097),i=a(5969),s=a(948),o=a(5615);let l=new TextEncoder;function c(e,t={}){var a,r;return"number"==typeof e||"bigint"==typeof e?(a=e,r=t,d((0,o.cK)(a,r))):"boolean"==typeof e?function(e,t={}){let a=new Uint8Array(1);return(a[0]=Number(e),"number"==typeof t.size)?((0,s.Sl)(a,{size:t.size}),(0,i.eV)(a,{size:t.size})):a}(e,t):(0,n.q)(e)?d(e,t):h(e,t)}function u(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function d(e,t={}){let a=e;t.size&&((0,s.Sl)(a,{size:t.size}),a=(0,i.eV)(a,{dir:"right",size:t.size}));let n=a.slice(2);n.length%2&&(n=`0${n}`);let o=n.length/2,l=new Uint8Array(o);for(let e=0,t=0;e<o;e++){let a=u(n.charCodeAt(t++)),i=u(n.charCodeAt(t++));if(void 0===a||void 0===i)throw new r.C(`Invalid byte sequence ("${n[t-2]}${n[t-1]}" in "${n}").`);l[e]=16*a+i}return l}function h(e,t={}){let a=l.encode(e);return"number"==typeof t.size?((0,s.Sl)(a,{size:t.size}),(0,i.eV)(a,{dir:"right",size:t.size})):a}},5615:function(e,t,a){"use strict";a.d(t,{$P:()=>l,My:()=>c,cK:()=>u,i3:()=>h,nj:()=>o});var r=a(2320),n=a(5969),i=a(948);let s=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function o(e,t={}){return"number"==typeof e||"bigint"==typeof e?u(e,t):"string"==typeof e?h(e,t):"boolean"==typeof e?l(e,t):c(e,t)}function l(e,t={}){let a=`0x${Number(e)}`;return"number"==typeof t.size?((0,i.Sl)(a,{size:t.size}),(0,n.eV)(a,{size:t.size})):a}function c(e,t={}){let a="";for(let t=0;t<e.length;t++)a+=s[e[t]];let r=`0x${a}`;return"number"==typeof t.size?((0,i.Sl)(r,{size:t.size}),(0,n.eV)(r,{dir:"right",size:t.size})):r}function u(e,t={}){let a,{signed:i,size:s}=t,o=BigInt(e);s?a=i?(1n<<8n*BigInt(s)-1n)-1n:2n**(8n*BigInt(s))-1n:"number"==typeof e&&(a=BigInt(Number.MAX_SAFE_INTEGER));let l="bigint"==typeof a&&i?-a-1n:0;if(a&&o>a||o<l){let t="bigint"==typeof e?"n":"";throw new r.Ty({max:a?`${a}${t}`:void 0,min:`${l}${t}`,signed:i,size:s,value:`${e}${t}`})}let c=`0x${(i&&o<0?(1n<<BigInt(8*s))+BigInt(o):o).toString(16)}`;return s?(0,n.eV)(c,{size:s}):c}let d=new TextEncoder;function h(e,t={}){return c(d.encode(e),t)}},876:function(e,t,a){"use strict";a.d(t,{X:()=>g,J:()=>f});var r=a(8036),n=a(3858),i=a(2406),s=a(2935),o=a(7122),l=a(606),c=a(9646),u=a(6854),d=a(401);let h="/docs/contract/encodeErrorResult";function m(e){let{abi:t,errorName:a,args:r}=e,n=t[0];if(a){let e=(0,d.iY)({abi:t,args:r,name:a});if(!e)throw new s.yy(a,{docsPath:h});n=e}if("error"!==n.type)throw new s.yy(void 0,{docsPath:h});let i=(0,u.B)(n),m=(0,l.V)(i),p="0x";if(r&&r.length>0){if(!n.inputs)throw new s.ZP(n.name,{docsPath:h});p=(0,c.h)(n.inputs,r)}return(0,o.aP)([m,p])}let p="/docs/contract/encodeFunctionResult",f="x-batch-gateway:true";async function g(e){let{data:t,ccipRequest:a}=e,{args:[o]}=(0,i.J)({abi:r.b2,data:t}),l=[],u=[];return await Promise.all(o.map(async(e,t)=>{try{u[t]=e.urls.includes(f)?await g({data:e.data,ccipRequest:a}):await a(e),l[t]=!1}catch(e){var i;l[t]=!0,u[t]="HttpRequestError"===(i=e).name&&i.status?m({abi:r.b2,errorName:"HttpError",args:[i.status,i.shortMessage]}):m({abi:[n.Mc],errorName:"Error",args:["shortMessage"in i?i.shortMessage:i.message]})}})),function(e){let{abi:t,functionName:a,result:r}=e,n=t[0];if(a){let e=(0,d.iY)({abi:t,name:a});if(!e)throw new s.Iz(a,{docsPath:p});n=e}if("function"!==n.type)throw new s.Iz(void 0,{docsPath:p});if(!n.outputs)throw new s.MR(n.name,{docsPath:p});let i=(()=>{if(0===n.outputs.length)return[];if(1===n.outputs.length)return[r];if(Array.isArray(r))return r;throw new s.dm(r)})();return(0,c.h)(n.outputs,i)}({abi:r.b2,functionName:"query",result:[l,u]})}},5009:function(e,t,a){"use strict";a.d(t,{d:()=>s});var r=a(1020),n=a(2385),i=a(9277);function s(e,{docsPath:t,...a}){let s,o=(s=(0,i.l)(e,a))instanceof n.RM?e:s;return new r.zX(o,{docsPath:t,...a})}},9277:function(e,t,a){"use strict";a.d(t,{l:()=>i});var r=a(5382),n=a(2385);function i(e,t){let a=(e.details||"").toLowerCase(),i=e instanceof r.C?e.walk(e=>e?.code===n.A7.code):e;return i instanceof r.C?new n.A7({cause:e,message:i.details}):n.A7.nodeMessage.test(a)?new n.A7({cause:e,message:e.details}):n.BG.nodeMessage.test(a)?new n.BG({cause:e,maxFeePerGas:t?.maxFeePerGas}):n.jj.nodeMessage.test(a)?new n.jj({cause:e,maxFeePerGas:t?.maxFeePerGas}):n.K0.nodeMessage.test(a)?new n.K0({cause:e,nonce:t?.nonce}):n.Oh.nodeMessage.test(a)?new n.Oh({cause:e,nonce:t?.nonce}):n.vW.nodeMessage.test(a)?new n.vW({cause:e,nonce:t?.nonce}):n.k5.nodeMessage.test(a)?new n.k5({cause:e}):n.lY.nodeMessage.test(a)?new n.lY({cause:e,gas:t?.gas}):n.Fo.nodeMessage.test(a)?new n.Fo({cause:e,gas:t?.gas}):n.uC.nodeMessage.test(a)?new n.uC({cause:e}):n.lN.nodeMessage.test(a)?new n.lN({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas}):new n.RM({cause:e})}},8286:function(e,t,a){"use strict";function r(e,{format:t}){if(!t)return{};let a={};return!function t(r){for(let n of Object.keys(r))n in e&&(a[n]=e[n]),r[n]&&"object"==typeof r[n]&&!Array.isArray(r[n])&&t(r[n])}(t(e||{})),a}a.d(t,{o:()=>r})},5430:function(e,t,a){"use strict";a.d(t,{Bv:()=>i});var r=a(5615);let n={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function i(e,t){let a={};return void 0!==e.authorizationList&&(a.authorizationList=e.authorizationList.map(e=>({address:e.address,r:e.r?(0,r.cK)(BigInt(e.r)):e.r,s:e.s?(0,r.cK)(BigInt(e.s)):e.s,chainId:(0,r.cK)(e.chainId),nonce:(0,r.cK)(e.nonce),...void 0!==e.yParity?{yParity:(0,r.cK)(e.yParity)}:{},...void 0!==e.v&&void 0===e.yParity?{v:(0,r.cK)(e.v)}:{}}))),void 0!==e.accessList&&(a.accessList=e.accessList),void 0!==e.blobVersionedHashes&&(a.blobVersionedHashes=e.blobVersionedHashes),void 0!==e.blobs&&("string"!=typeof e.blobs[0]?a.blobs=e.blobs.map(e=>(0,r.My)(e)):a.blobs=e.blobs),void 0!==e.data&&(a.data=e.data),e.account&&(a.from=e.account.address),void 0!==e.from&&(a.from=e.from),void 0!==e.gas&&(a.gas=(0,r.cK)(e.gas)),void 0!==e.gasPrice&&(a.gasPrice=(0,r.cK)(e.gasPrice)),void 0!==e.maxFeePerBlobGas&&(a.maxFeePerBlobGas=(0,r.cK)(e.maxFeePerBlobGas)),void 0!==e.maxFeePerGas&&(a.maxFeePerGas=(0,r.cK)(e.maxFeePerGas)),void 0!==e.maxPriorityFeePerGas&&(a.maxPriorityFeePerGas=(0,r.cK)(e.maxPriorityFeePerGas)),void 0!==e.nonce&&(a.nonce=(0,r.cK)(e.nonce)),void 0!==e.to&&(a.to=e.to),void 0!==e.type&&(a.type=n[e.type]),void 0!==e.value&&(a.value=(0,r.cK)(e.value)),a}},4811:function(e,t,a){"use strict";a.d(t,{S:()=>o});var r=a(4588),n=a(8097),i=a(8669),s=a(5615);function o(e,t){let a=(0,r.lY)((0,n.q)(e,{strict:!1})?(0,i.ZJ)(e):e);return"bytes"===(t||"hex")?a:(0,s.nj)(a)}},9262:function(e,t,a){"use strict";a.d(t,{h:()=>r});let r=a(1265).k},606:function(e,t,a){"use strict";a.d(t,{V:()=>i});var r=a(9278),n=a(1265);let i=e=>(0,r.di)((0,n.k)(e),0,4)},1265:function(e,t,a){"use strict";a.d(t,{k:()=>c});var r=a(8669),n=a(4811),i=a(1999);let s=/^tuple(?<array>(\[(\d*)\])*)$/;function o(e){let t="",a=e.length;for(let r=0;r<a;r++)t+=function e(t){let a=t.type;if(s.test(t.type)&&"components"in t){a="(";let r=t.components.length;for(let n=0;n<r;n++)a+=e(t.components[n]),n<r-1&&(a+=", ");let n=(0,i.Yv)(s,t.type);return a+=`)${n?.array??""}`,e({...t,type:a})}return("indexed"in t&&t.indexed&&(a=`${a} indexed`),t.name)?`${a} ${t.name}`:a}(e[r]),r!==a-1&&(t+=", ");return t}var l=a(5382);function c(e){var t;return t=function(e){let t=!0,a="",r=0,n="",i=!1;for(let s=0;s<e.length;s++){let o=e[s];if(["(",")",","].includes(o)&&(t=!0),"("===o&&r++,")"===o&&r--,t){if(0===r){if(" "===o&&["event","function",""].includes(n))n="";else if(n+=o,")"===o){i=!0;break}continue}if(" "===o){","!==e[s-1]&&","!==a&&",("!==a&&(a="",t=!1);continue}n+=o,a+=o}}if(!i)throw new l.C("Unable to normalize signature.");return n}((()=>"string"==typeof e?e:"function"===e.type?`function ${e.name}(${o(e.inputs)})${e.stateMutability&&"nonpayable"!==e.stateMutability?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${o(e.outputs)})`:""}`:"event"===e.type?`event ${e.name}(${o(e.inputs)})`:"error"===e.type?`error ${e.name}(${o(e.inputs)})`:"constructor"===e.type?`constructor(${o(e.inputs)})${"payable"===e.stateMutability?" payable":""}`:"fallback"===e.type?`fallback() external${"payable"===e.stateMutability?" payable":""}`:"receive() external payable")()),(0,n.S)((0,r.ZJ)(t))}},4106:function(e,t,a){"use strict";a.d(t,{A:()=>r});class r extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){let t=super.get(e);return super.has(e)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){let e=this.keys().next().value;e&&this.delete(e)}return this}}},6944:function(e,t,a){"use strict";a.d(t,{u:()=>i});var r=a(1050);let n=new Map;function i({fn:e,id:t,shouldSplitBatch:a,wait:i=0,sort:s}){let o=async()=>{let t=c();l();let a=t.map(({args:e})=>e);0!==a.length&&e(a).then(e=>{s&&Array.isArray(e)&&e.sort(s);for(let a=0;a<t.length;a++){let{resolve:r}=t[a];r?.([e[a],e])}}).catch(e=>{for(let a=0;a<t.length;a++){let{reject:r}=t[a];r?.(e)}})},l=()=>n.delete(t),c=()=>n.get(t)||[],u=e=>n.set(t,[...c(),e]);return{flush:l,async schedule(e){let{promise:t,resolve:n,reject:s}=(0,r.Y)();return(a?.([...c().map(({args:e})=>e),e])&&o(),c().length>0)?u({args:e,resolve:n,reject:s}):(u({args:e,resolve:n,reject:s}),setTimeout(o,i)),t}}}},1050:function(e,t,a){"use strict";function r(){let e=()=>void 0,t=()=>void 0;return{promise:new Promise((a,r)=>{e=a,t=r}),resolve:e,reject:t}}a.d(t,{Y:()=>r})},3072:function(e,t,a){"use strict";a.d(t,{BD:()=>n,D5:()=>r,Ge:()=>i});let r=/^(.*)\[([0-9]*)\]$/,n=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,i=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/},2882:function(e,t,a){"use strict";a.d(t,{yH:()=>c});var r=a(4309),n=a(5229),i=a(3412),s=a(9188),o=a(5615);function l(e){if(e&&0!==e.length)return e.reduce((e,{slot:t,value:a})=>{if(66!==t.length)throw new n.NV({size:t.length,targetSize:66,type:"hex"});if(66!==a.length)throw new n.NV({size:a.length,targetSize:66,type:"hex"});return e[t]=a,e},{})}function c(e){if(!e)return;let t={};for(let{address:a,...n}of e){if(!(0,s.P)(a,{strict:!1}))throw new r.M({address:a});if(t[a])throw new i.Hi({address:a});t[a]=function(e){let{balance:t,nonce:a,state:r,stateDiff:n,code:s}=e,c={};if(void 0!==s&&(c.code=s),void 0!==t&&(c.balance=(0,o.cK)(t)),void 0!==a&&(c.nonce=(0,o.cK)(a)),void 0!==r&&(c.state=l(r)),void 0!==n){if(c.state)throw new i.ft;c.stateDiff=l(n)}return c}(n)}return t}},7998:function(e,t,a){"use strict";a.d(t,{A:()=>r});let r=(e,t,a)=>JSON.stringify(e,(e,a)=>{let r="bigint"==typeof a?a.toString():a;return"function"==typeof t?t(e,r):r},a)},7846:function(e,t,a){"use strict";a.d(t,{c:()=>c});var r=a(6540);let n=2n**256n-1n;var i=a(4309),s=a(2385),o=a(897),l=a(9188);function c(e){let{account:t,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,to:d}=e,h=t?(0,r.J)(t):void 0;if(h&&!(0,l.P)(h.address))throw new i.M({address:h.address});if(d&&!(0,l.P)(d))throw new i.M({address:d});if(void 0!==a&&(void 0!==c||void 0!==u))throw new o.n3;if(c&&c>n)throw new s.BG({maxFeePerGas:c});if(u&&c&&u>c)throw new s.lN({maxFeePerGas:c,maxPriorityFeePerGas:u})}},5071:function(e,t,a){"use strict";a.d(t,{c:()=>i});var r=a(6993),n=a(9644);function i(e,t="wei"){return(0,n.J)(e,r.eL[t])}},2239:function(e,t,a){"use strict";a.d(t,{Q:()=>i});var r=a(6993),n=a(9644);function i(e,t="wei"){return(0,n.J)(e,r.sz[t])}},9644:function(e,t,a){"use strict";function r(e,t){let a=e.toString(),r=a.startsWith("-");r&&(a=a.slice(1));let[n,i]=[(a=a.padStart(t,"0")).slice(0,a.length-t),a.slice(a.length-t)];return i=i.replace(/(0+)$/,""),`${r?"-":""}${n||"0"}${i?`.${i}`:""}`}a.d(t,{J:()=>r})}},r={};function n(e){var t=r[e];if(void 0!==t)return t.exports;var i=r[e]={exports:{}};return a[e].call(i.exports,i,i.exports,n),i.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,n.t=function(a,r){if(1&r&&(a=this(a)),8&r||"object"==typeof a&&a&&(4&r&&a.__esModule||16&r&&"function"==typeof a.then))return a;var i=Object.create(null);n.r(i);var s={};e=e||[null,t({}),t([]),t(t)];for(var o=2&r&&a;("object"==typeof o||"function"==typeof o)&&!~e.indexOf(o);o=t(o))Object.getOwnPropertyNames(o).forEach(e=>{s[e]=()=>a[e]});return s.default=()=>a,n.d(i,s),i},n.d=(e,t)=>{for(var a in t)n.o(t,a)&&!n.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,get:t[a]})},n.g=(()=>{if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}})(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};(()=>{"use strict";let e,t,a,r;function s(){return"undefined"!=typeof window}n.r(i),n.d(i,{EmailLinkError:()=>_,isUserLockedError:()=>M,ClerkAPIResponseError:()=>v,EmailLinkErrorCodeStatus:()=>S,isKnownError:()=>q,Clerk:()=>n_,isMetamaskError:()=>U,EmailLinkErrorCode:()=>z,ClerkRuntimeError:()=>A,isClerkRuntimeError:()=>T,isClerkAPIResponseError:()=>O,isEmailLinkError:()=>R}),n(653);let o=RegExp("bot|spider|crawl|APIs-Google|AdsBot|Googlebot|mediapartners|Google Favicon|FeedFetcher|Google-Read-Aloud|DuplexWeb-Google|googleweblight|bing|yandex|baidu|duckduck|yahoo|ecosia|ia_archiver|facebook|instagram|pinterest|reddit|slack|twitter|whatsapp|youtube|semrush","i");function l(){var e;let t=s()?window?.navigator:null;return!!t&&!((e=t?.userAgent)&&o.test(e))&&!t?.webdriver}function c(){let e=s()?window?.navigator:null;if(!e)return!1;let t=e?.onLine;return e?.connection?.rtt!==0&&e?.connection?.downlink!==0&&t}function u(){return c()&&l()}let d=(e,t,a,r,n)=>{let{notify:i}=n||{},s=e.get(a);s||(s=[],e.set(a,s)),s.push(r),i&&t.has(a)&&r(t.get(a))},h=(e,t,a)=>(e.get(t)||[]).map(e=>e(a)),m=(e,t,a)=>{let r=e.get(t);r&&(a?r.splice(r.indexOf(a)>>>0,1):e.set(t,[]))},p=()=>{let e=new Map,t=new Map,a=new Map;return{on:(...a)=>d(e,t,...a),prioritizedOn:(...e)=>d(a,t,...e),emit:(r,n)=>{t.set(r,n),h(a,r,n),h(e,r,n)},off:(...t)=>m(e,...t),prioritizedOff:(...e)=>m(a,...e),internal:{retrieveListeners:t=>e.get(t)||[]}}},f="status";function g(e){return function(t){let a=t??this;if(!a)throw TypeError(`${e.kind||e.name} type guard requires an error object`);return a instanceof e}}var b,y,w=class{static kind="ClerkApiError";code;message;longMessage;meta;constructor(e){const t={code:e.code,message:e.message,longMessage:e.long_message,meta:{paramName:e.meta?.param_name,sessionId:e.meta?.session_id,emailAddresses:e.meta?.email_addresses,identifiers:e.meta?.identifiers,zxcvbn:e.meta?.zxcvbn,plan:e.meta?.plan,isPlanUpgradePossible:e.meta?.is_plan_upgrade_possible}};this.code=t.code,this.message=t.message,this.longMessage=t.longMessage,this.meta=t.meta}};g(w);var k=class e extends Error{static kind="ClerkError";clerkError=!0;code;longMessage;docsUrl;cause;get name(){return this.constructor.name}constructor(t){super(new.target.formatMessage(new.target.kind,t.message,t.code,t.docsUrl),{cause:t.cause}),Object.setPrototypeOf(this,e.prototype),this.code=t.code,this.docsUrl=t.docsUrl,this.longMessage=t.longMessage,this.cause=t.cause}toString(){return`[${this.name}]
46
46
  Message:${this.message}`}static formatMessage(e,t,a,r){let n="Clerk:",i=RegExp(n.replace(" ","\\s*"),"i");return t=t.replace(i,""),t=`${n} ${t.trim()}
47
47
 
48
48
  (code="${a}")
@@ -53,10 +53,10 @@ Docs: ${r}`),t}},v=class e extends k{static kind="ClerkAPIResponseError";status;
53
53
  Message:${this.message}
54
54
  Status:${this.status}
55
55
  Serialized errors: ${this.errors.map(e=>JSON.stringify(e))}`;return this.clerkTraceId&&(e+=`
56
- Clerk Trace ID: ${this.clerkTraceId}`),e}static formatMessage(e,t,a,r){return t}};let x=g(v);var j=class e extends v{static kind="MissingExpiredTokenError";static ERROR_CODE="missing_expired_token";static STATUS=422;static is(t){return x(t)&&t.status===e.STATUS&&t.errors.length>0&&t.errors[0].code===e.ERROR_CODE}};let _=Object.freeze({InvalidProxyUrlErrorMessage:"The proxyUrl passed to Clerk is invalid. The expected value for proxyUrl is an absolute URL or a relative path with a leading '/'. (key={{url}})",InvalidPublishableKeyErrorMessage:"The publishableKey passed to Clerk is invalid. You can get your Publishable key at https://dashboard.clerk.com/last-active?path=api-keys. (key={{key}})",MissingPublishableKeyErrorMessage:"Missing publishableKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.",MissingSecretKeyErrorMessage:"Missing secretKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.",MissingClerkProvider:"{{source}} can only be used within the <ClerkProvider /> component. Learn more: https://clerk.com/docs/components/clerk-provider"});var z=class e extends Error{code;constructor(t){super(t),this.code=t,this.name="EmailLinkError",Object.setPrototypeOf(this,e.prototype)}};let S={Expired:"expired",Failed:"failed",ClientMismatch:"client_mismatch"},A={Expired:"expired",Failed:"failed",ClientMismatch:"client_mismatch"};var E=class e extends k{static kind="ClerkRuntimeError";clerkRuntimeError=!0;constructor(t,a){super({...a,message:t}),Object.setPrototypeOf(this,e.prototype)}};let I=g(E);var C=class extends E{code;constructor(e,{code:t}){super(e,{code:t}),this.code=t}};function P(e){return["captcha_invalid","captcha_not_enabled","captcha_missing_token"].includes(e.errors[0].code)}function q(e){let t=e?.status;return!!t&&t>=400&&t<500}function O(e){return T(e)||M(e)||U(e)}function T(e){return e&&"clerkError"in e}function U(e){return"clerkRuntimeError"in e}function M(e){return"code"in e&&[4001,32602,32603].includes(e.code)&&"message"in e}function R(e){return T(e)&&e.errors?.[0]?.code==="user_locked"}function B(e){return"EmailLinkError"===e.name}function N(e){for(let[t,a]of Object.entries({isClerkApiResponseError:x,isClerkRuntimeError:I}))Object.assign(e,{[t]:a});return e}let D=(e,t)=>!!(e.isSignedIn&&t?.authConfig.singleSessionMode),F=(e,t)=>!t?.commerceSettings.billing.user.enabled&&!t?.commerceSettings.billing.organization.enabled,L=(e,t)=>!t?.apiKeysSettings?.user_api_keys_enabled,W=(e,t)=>!t?.apiKeysSettings?.orgs_api_keys_enabled,K="__clerk_synced",H="suffixed_cookies",V="__clerk_satellite_url",G="clerk-captcha",J="clerk-invisible-captcha";var Z=n(1006);let $=new Set,Y=e=>{$.has(e)||($.add(e),console.warn(e))},Q=(e,t)=>{let a={};for(let r in e)a[r]=t(e[r],r);return a},X=(e,t)=>{let a={};for(let r in e)e[r]&&t(e[r])&&(a[r]=e[r]);return a};function ee(e){return e?e.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace(/-|_/,"")):""}function et(e){return e?e.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`):""}let ea=e=>{let t=a=>{if(!a)return a;if(Array.isArray(a))return a.map(e=>"object"==typeof e||Array.isArray(e)?t(e):e);let r={...a};for(let a of Object.keys(r)){let n=e(a.toString());n!==a&&(r[n]=r[a],delete r[a]),"object"==typeof r[n]&&(r[n]=t(r[n]))}return r};return t},er=ea(et),en=ea(ee);function ei(e){if("boolean"==typeof e)return e;if(null==e)return!1;if("string"==typeof e){if("true"===e.toLowerCase())return!0;if("false"===e.toLowerCase())return!1}let t=parseInt(e,10);return!isNaN(t)&&t>0}let es=RegExp("/{1,}","g"),eo=[".lcl.dev",".lclstage.dev",".lclclerk.com"],el=[".accounts.dev",".accountsstage.dev",".accounts.lclclerk.com"],ec=[".lcl.dev",".stg.dev",".lclstage.dev",".stgstage.dev",".dev.lclclerk.com",".stg.lclclerk.com",".accounts.lclclerk.com","accountsstage.dev","accounts.dev"],eu=e=>"undefined"!=typeof atob&&"function"==typeof atob?atob(e):"undefined"!=typeof global&&global.Buffer?new global.Buffer(e,"base64").toString():e,ed="pk_live_";function eh(e){if(!e.endsWith("$"))return!1;let t=e.slice(0,-1);return!t.includes("$")&&t.includes(".")}function em(e,t={}){let a;if(!(e=e||"")||!ep(e)){if(t.fatal&&!e)throw Error("Publishable key is missing. Ensure that your publishable key is correctly configured. Double-check your environment configuration for your keys, or access them here: https://dashboard.clerk.com/last-active?path=api-keys");if(t.fatal&&!ep(e))throw Error("Publishable key not valid.");return null}let r=e.startsWith(ed)?"production":"development";try{a=eu(e.split("_")[2])}catch{if(t.fatal)throw Error("Publishable key not valid: Failed to decode key.");return null}if(!eh(a)){if(t.fatal)throw Error("Publishable key not valid: Decoded key has invalid format.");return null}let n=a.slice(0,-1);return t.proxyUrl?n=t.proxyUrl:"development"!==r&&t.domain&&t.isSatellite&&(n=`clerk.${t.domain}`),{instanceType:r,frontendApi:n}}function ep(e=""){try{if(!(e.startsWith(ed)||e.startsWith("pk_test_")))return!1;let t=e.split("_");if(3!==t.length)return!1;let a=t[2];if(!a)return!1;return eh(eu(a))}catch{return!1}}async function ef(e,t=globalThis.crypto.subtle){var a;let r=new TextEncoder().encode(e);return(a=String.fromCharCode(...new Uint8Array(await t.digest("sha-1",r))),"undefined"!=typeof btoa&&"function"==typeof btoa?btoa(a):"undefined"!=typeof global&&global.Buffer?new global.Buffer(a).toString("base64"):a).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}let eg=(e,t)=>`${e}_${t}`,eb=/^[a-zA-Z][a-zA-Z\d+\-.]*?:/,ey=(e,t={})=>{if(null==e||!e||"object"!=typeof e)return"";let a=new URLSearchParams;return Object.keys(e).forEach(r=>{let n=t.keyEncoder?t.keyEncoder(r):r,i=e[r];if(Array.isArray(i))i.forEach(e=>void 0!==e&&a.append(n,e||""));else{if(void 0===i)return;"object"==typeof i&&null!==i?a.append(n,JSON.stringify(i)):a.append(n,String(i??""))}}),a.toString()},ew="http://clerk-dummy",ek=["javascript:"],{isDevOrStagingUrl:ev}=(r=new Map,{isDevOrStagingUrl:e=>{if(!e)return!1;let t="string"==typeof e?e:e.hostname,a=r.get(t);return void 0===a&&(a=ec.some(e=>t.endsWith(e)),r.set(t,a)),a}}),ex=new Map;function ej(e){return e.replace("clerk.","")}function e_(e,t={}){let{base:a,hashPath:r,hashSearch:n,searchParams:i,hashSearchParams:s,...o}=e,l=new URL(a||"","undefined"!=typeof window&&window.location?window.location.href:"http://react-native-fake-base-url");if(i instanceof URLSearchParams&&i.forEach((e,t)=>{null!=e&&l.searchParams.set(et(t),e)}),Object.assign(l,o),r||n||s){var c;let e,t=new URL(ew+l.hash.substring(1));for(let[a,i]of(c=t.pathname,t.pathname=[c,r||""].filter(e=>e).join("/").replace(es,"/"),Object.entries((e={},new URLSearchParams(n||"").forEach((t,a)=>{if(a in e){let r=e[a];Array.isArray(r)?r.push(t):e[a]=[r,t]}else e[a]=t}),e))))t.searchParams.append(a,i);if(s)for(let e of Array.isArray(s)?s:[s])(e instanceof URLSearchParams||"object"==typeof e)&&new URLSearchParams(e).forEach((e,a)=>{null!=e&&t.searchParams.set(et(a),e)});let a=t.href.replace(ew,"");"/"!==a&&(l.hash=a)}let{stringify:u,skipOrigin:d}=t;return u?d?l.href.replace(l.origin,""):l.href:l}function ez(e){return void 0===window.location&&"string"==typeof e?e:(e=new URL(e.toString(),window.location.origin)).href.replace(e.origin,"")}let eS=e=>(e||"").replace(/\/+$/,"");function eA(e,t){try{return new URL(e)}catch{return new URL(e,t)}}let eE=[/\0/,/^\/\//,/[\x00-\x1F]/],eI=["/oauth/authorize"],eC=["/v1/verify","/v1/tickets/accept","/oauth/authorize-with-immediate-redirect","/oauth/end_session"];var eP=class e{static keys=["signInForceRedirectUrl","signInFallbackRedirectUrl","signUpForceRedirectUrl","signUpFallbackRedirectUrl","redirectUrl"];static preserved=["redirectUrl"];options;fromOptions;fromProps;fromSearchParams;mode;constructor(e,t={},a={},r){this.options=e,this.fromOptions=this.#A(e||{}),this.fromProps=this.#A(t||{}),this.fromSearchParams=this.#E(a||{}),this.mode=r}getAfterSignInUrl(){return this.#I("signIn")}getAfterSignUpUrl(){return this.#I("signUp")}getPreservedSearchParams(){return this.#C(this.#P())}toSearchParams(){return this.#C(this.#q())}#C(e){return new URLSearchParams(Object.entries(Object.fromEntries(Object.entries(e).map(([e,t])=>[et(e),t]))).reduce((e,[t,a])=>(null!=a&&(e[t]=a),e),{}))}#P(){return Object.fromEntries(Object.entries({...this.fromSearchParams}).filter(([t])=>e.preserved.includes(t)))}#q(){let e=this.fromSearchParams.signUpForceRedirectUrl||this.fromProps.signUpForceRedirectUrl||this.fromOptions.signUpForceRedirectUrl,t=this.fromSearchParams.signUpFallbackRedirectUrl||this.fromProps.signUpFallbackRedirectUrl||this.fromOptions.signUpFallbackRedirectUrl,a=this.fromSearchParams.signInForceRedirectUrl||this.fromProps.signInForceRedirectUrl||this.fromOptions.signInForceRedirectUrl,r={signUpForceRedirectUrl:e,signUpFallbackRedirectUrl:t,signInFallbackRedirectUrl:this.fromSearchParams.signInFallbackRedirectUrl||this.fromProps.signInFallbackRedirectUrl||this.fromOptions.signInFallbackRedirectUrl,signInForceRedirectUrl:a,redirectUrl:this.fromSearchParams.redirectUrl};return e&&delete r.signUpFallbackRedirectUrl,a&&delete r.signInFallbackRedirectUrl,r}#I(e){let t,a=`${e}ForceRedirectUrl`,r=`${e}FallbackRedirectUrl`;return(t=this.fromSearchParams[a]||this.fromProps[a]||this.fromOptions[a],t||=this.fromSearchParams.redirectUrl,(t||=this.fromSearchParams[r]||this.fromProps[r]||this.fromOptions[r])||"modal"!==this.mode)?t||"/":window.location.href}#A(t){let a={};return e.keys.forEach(e=>{a[e]=t[e]}),Q(this.#O(this.#T(X(a,Boolean))),e=>e.toString())}#E(t){let a={};return e.keys.forEach(e=>{t instanceof URLSearchParams?a[e]=t.get(et(e)):a[e]=t[et(e)]}),Q(this.#O(this.#T(X(a,Boolean))),e=>e.toString())}#T(e){return Q(e,e=>eA(e,window.location.origin))}#O=e=>{let t,a;return X(e,(t=this.options?.allowedRedirectOrigins,a=window.location.origin,e=>{let r=e;if("string"==typeof r&&(r=eA(r,a)),!t)return!0;let n=a===r.origin,i=!function(e){if(function(e){if(!function(e){if(!e)return!1;try{return new URL(e),!0}catch{return!1}}(e))return!1;let t=new URL(e).protocol;return ek.some(e=>e===t)}(e))return!0;for(let t of eE)if(t.test(e.pathname))return!0;return!1}(r)&&(n||t.map(e=>"string"==typeof e?(e=>{try{return Z(e)}catch(t){throw Error(`Invalid pattern: ${e}.
56
+ Clerk Trace ID: ${this.clerkTraceId}`),e}static formatMessage(e,t,a,r){return t}};let x=g(v),j=Object.freeze({InvalidProxyUrlErrorMessage:"The proxyUrl passed to Clerk is invalid. The expected value for proxyUrl is an absolute URL or a relative path with a leading '/'. (key={{url}})",InvalidPublishableKeyErrorMessage:"The publishableKey passed to Clerk is invalid. You can get your Publishable key at https://dashboard.clerk.com/last-active?path=api-keys. (key={{key}})",MissingPublishableKeyErrorMessage:"Missing publishableKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.",MissingSecretKeyErrorMessage:"Missing secretKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.",MissingClerkProvider:"{{source}} can only be used within the <ClerkProvider /> component. Learn more: https://clerk.com/docs/components/clerk-provider"});var _=class e extends Error{code;constructor(t){super(t),this.code=t,this.name="EmailLinkError",Object.setPrototypeOf(this,e.prototype)}};let z={Expired:"expired",Failed:"failed",ClientMismatch:"client_mismatch"},S={Expired:"expired",Failed:"failed",ClientMismatch:"client_mismatch"};var A=class e extends k{static kind="ClerkRuntimeError";clerkRuntimeError=!0;constructor(t,a){super({...a,message:t}),Object.setPrototypeOf(this,e.prototype)}};let E=g(A);var I=class extends A{code;constructor(e,{code:t}){super(e,{code:t}),this.code=t}};function C(e){return["captcha_invalid","captcha_not_enabled","captcha_missing_token"].includes(e.errors[0].code)}function P(e){let t=e?.status;return!!t&&t>=400&&t<500}function q(e){return O(e)||U(e)||T(e)}function O(e){return e&&"clerkError"in e}function T(e){return"clerkRuntimeError"in e}function U(e){return"code"in e&&[4001,32602,32603].includes(e.code)&&"message"in e}function M(e){return O(e)&&e.errors?.[0]?.code==="user_locked"}function R(e){return"EmailLinkError"===e.name}function B(e){for(let[t,a]of Object.entries({isClerkApiResponseError:x,isClerkRuntimeError:E}))Object.assign(e,{[t]:a});return e}let N=(e,t)=>!!(e.isSignedIn&&t?.authConfig.singleSessionMode),D=(e,t)=>!t?.commerceSettings.billing.user.enabled&&!t?.commerceSettings.billing.organization.enabled,F=(e,t)=>!t?.apiKeysSettings?.user_api_keys_enabled,L=(e,t)=>!t?.apiKeysSettings?.orgs_api_keys_enabled,W="__clerk_synced",K="suffixed_cookies",H="__clerk_satellite_url",V="clerk-captcha",G="clerk-invisible-captcha";var J=n(1006);let Z=new Set,$=e=>{Z.has(e)||(Z.add(e),console.warn(e))},Y=(e,t)=>{let a={};for(let r in e)a[r]=t(e[r],r);return a},Q=(e,t)=>{let a={};for(let r in e)e[r]&&t(e[r])&&(a[r]=e[r]);return a};function X(e){return e?e.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace(/-|_/,"")):""}function ee(e){return e?e.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`):""}let et=e=>{let t=a=>{if(!a)return a;if(Array.isArray(a))return a.map(e=>"object"==typeof e||Array.isArray(e)?t(e):e);let r={...a};for(let a of Object.keys(r)){let n=e(a.toString());n!==a&&(r[n]=r[a],delete r[a]),"object"==typeof r[n]&&(r[n]=t(r[n]))}return r};return t},ea=et(ee),er=et(X);function en(e){if("boolean"==typeof e)return e;if(null==e)return!1;if("string"==typeof e){if("true"===e.toLowerCase())return!0;if("false"===e.toLowerCase())return!1}let t=parseInt(e,10);return!isNaN(t)&&t>0}let ei=RegExp("/{1,}","g"),es=[".lcl.dev",".lclstage.dev",".lclclerk.com"],eo=[".accounts.dev",".accountsstage.dev",".accounts.lclclerk.com"],el=[".lcl.dev",".stg.dev",".lclstage.dev",".stgstage.dev",".dev.lclclerk.com",".stg.lclclerk.com",".accounts.lclclerk.com","accountsstage.dev","accounts.dev"],ec=e=>"undefined"!=typeof atob&&"function"==typeof atob?atob(e):"undefined"!=typeof global&&global.Buffer?new global.Buffer(e,"base64").toString():e,eu="pk_live_";function ed(e){if(!e.endsWith("$"))return!1;let t=e.slice(0,-1);return!t.includes("$")&&t.includes(".")}function eh(e,t={}){let a;if(!(e=e||"")||!em(e)){if(t.fatal&&!e)throw Error("Publishable key is missing. Ensure that your publishable key is correctly configured. Double-check your environment configuration for your keys, or access them here: https://dashboard.clerk.com/last-active?path=api-keys");if(t.fatal&&!em(e))throw Error("Publishable key not valid.");return null}let r=e.startsWith(eu)?"production":"development";try{a=ec(e.split("_")[2])}catch{if(t.fatal)throw Error("Publishable key not valid: Failed to decode key.");return null}if(!ed(a)){if(t.fatal)throw Error("Publishable key not valid: Decoded key has invalid format.");return null}let n=a.slice(0,-1);return t.proxyUrl?n=t.proxyUrl:"development"!==r&&t.domain&&t.isSatellite&&(n=`clerk.${t.domain}`),{instanceType:r,frontendApi:n}}function em(e=""){try{if(!(e.startsWith(eu)||e.startsWith("pk_test_")))return!1;let t=e.split("_");if(3!==t.length)return!1;let a=t[2];if(!a)return!1;return ed(ec(a))}catch{return!1}}async function ep(e,t=globalThis.crypto.subtle){var a;let r=new TextEncoder().encode(e);return(a=String.fromCharCode(...new Uint8Array(await t.digest("sha-1",r))),"undefined"!=typeof btoa&&"function"==typeof btoa?btoa(a):"undefined"!=typeof global&&global.Buffer?new global.Buffer(a).toString("base64"):a).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}let ef=(e,t)=>`${e}_${t}`,eg=/^[a-zA-Z][a-zA-Z\d+\-.]*?:/,eb=(e,t={})=>{if(null==e||!e||"object"!=typeof e)return"";let a=new URLSearchParams;return Object.keys(e).forEach(r=>{let n=t.keyEncoder?t.keyEncoder(r):r,i=e[r];if(Array.isArray(i))i.forEach(e=>void 0!==e&&a.append(n,e||""));else{if(void 0===i)return;"object"==typeof i&&null!==i?a.append(n,JSON.stringify(i)):a.append(n,String(i??""))}}),a.toString()},ey="http://clerk-dummy",ew=["javascript:"],{isDevOrStagingUrl:ek}=(r=new Map,{isDevOrStagingUrl:e=>{if(!e)return!1;let t="string"==typeof e?e:e.hostname,a=r.get(t);return void 0===a&&(a=el.some(e=>t.endsWith(e)),r.set(t,a)),a}}),ev=new Map;function ex(e){return e.replace("clerk.","")}function ej(e,t={}){let{base:a,hashPath:r,hashSearch:n,searchParams:i,hashSearchParams:s,...o}=e,l=new URL(a||"","undefined"!=typeof window&&window.location?window.location.href:"http://react-native-fake-base-url");if(i instanceof URLSearchParams&&i.forEach((e,t)=>{null!=e&&l.searchParams.set(ee(t),e)}),Object.assign(l,o),r||n||s){var c;let e,t=new URL(ey+l.hash.substring(1));for(let[a,i]of(c=t.pathname,t.pathname=[c,r||""].filter(e=>e).join("/").replace(ei,"/"),Object.entries((e={},new URLSearchParams(n||"").forEach((t,a)=>{if(a in e){let r=e[a];Array.isArray(r)?r.push(t):e[a]=[r,t]}else e[a]=t}),e))))t.searchParams.append(a,i);if(s)for(let e of Array.isArray(s)?s:[s])(e instanceof URLSearchParams||"object"==typeof e)&&new URLSearchParams(e).forEach((e,a)=>{null!=e&&t.searchParams.set(ee(a),e)});let a=t.href.replace(ey,"");"/"!==a&&(l.hash=a)}let{stringify:u,skipOrigin:d}=t;return u?d?l.href.replace(l.origin,""):l.href:l}function e_(e){return void 0===window.location&&"string"==typeof e?e:(e=new URL(e.toString(),window.location.origin)).href.replace(e.origin,"")}let ez=e=>(e||"").replace(/\/+$/,"");function eS(e,t){try{return new URL(e)}catch{return new URL(e,t)}}let eA=[/\0/,/^\/\//,/[\x00-\x1F]/],eE=["/oauth/authorize"],eI=["/v1/verify","/v1/tickets/accept","/oauth/authorize-with-immediate-redirect","/oauth/end_session"];var eC=class e{static keys=["signInForceRedirectUrl","signInFallbackRedirectUrl","signUpForceRedirectUrl","signUpFallbackRedirectUrl","redirectUrl"];static preserved=["redirectUrl"];options;fromOptions;fromProps;fromSearchParams;mode;constructor(e,t={},a={},r){this.options=e,this.fromOptions=this.#A(e||{}),this.fromProps=this.#A(t||{}),this.fromSearchParams=this.#E(a||{}),this.mode=r}getAfterSignInUrl(){return this.#I("signIn")}getAfterSignUpUrl(){return this.#I("signUp")}getPreservedSearchParams(){return this.#C(this.#P())}toSearchParams(){return this.#C(this.#q())}#C(e){return new URLSearchParams(Object.entries(Object.fromEntries(Object.entries(e).map(([e,t])=>[ee(e),t]))).reduce((e,[t,a])=>(null!=a&&(e[t]=a),e),{}))}#P(){return Object.fromEntries(Object.entries({...this.fromSearchParams}).filter(([t])=>e.preserved.includes(t)))}#q(){let e=this.fromSearchParams.signUpForceRedirectUrl||this.fromProps.signUpForceRedirectUrl||this.fromOptions.signUpForceRedirectUrl,t=this.fromSearchParams.signUpFallbackRedirectUrl||this.fromProps.signUpFallbackRedirectUrl||this.fromOptions.signUpFallbackRedirectUrl,a=this.fromSearchParams.signInForceRedirectUrl||this.fromProps.signInForceRedirectUrl||this.fromOptions.signInForceRedirectUrl,r={signUpForceRedirectUrl:e,signUpFallbackRedirectUrl:t,signInFallbackRedirectUrl:this.fromSearchParams.signInFallbackRedirectUrl||this.fromProps.signInFallbackRedirectUrl||this.fromOptions.signInFallbackRedirectUrl,signInForceRedirectUrl:a,redirectUrl:this.fromSearchParams.redirectUrl};return e&&delete r.signUpFallbackRedirectUrl,a&&delete r.signInFallbackRedirectUrl,r}#I(e){let t,a=`${e}ForceRedirectUrl`,r=`${e}FallbackRedirectUrl`;return(t=this.fromSearchParams[a]||this.fromProps[a]||this.fromOptions[a],t||=this.fromSearchParams.redirectUrl,(t||=this.fromSearchParams[r]||this.fromProps[r]||this.fromOptions[r])||"modal"!==this.mode)?t||"/":window.location.href}#A(t){let a={};return e.keys.forEach(e=>{a[e]=t[e]}),Y(this.#O(this.#T(Q(a,Boolean))),e=>e.toString())}#E(t){let a={};return e.keys.forEach(e=>{t instanceof URLSearchParams?a[e]=t.get(ee(e)):a[e]=t[ee(e)]}),Y(this.#O(this.#T(Q(a,Boolean))),e=>e.toString())}#T(e){return Y(e,e=>eS(e,window.location.origin))}#O=e=>{let t,a;return Q(e,(t=this.options?.allowedRedirectOrigins,a=window.location.origin,e=>{let r=e;if("string"==typeof r&&(r=eS(r,a)),!t)return!0;let n=a===r.origin,i=!function(e){if(function(e){if(!function(e){if(!e)return!1;try{return new URL(e),!0}catch{return!1}}(e))return!1;let t=new URL(e).protocol;return ew.some(e=>e===t)}(e))return!0;for(let t of eA)if(t.test(e.pathname))return!0;return!1}(r)&&(n||t.map(e=>"string"==typeof e?(e=>{try{return J(e)}catch(t){throw Error(`Invalid pattern: ${e}.
57
57
  Consult the documentation of glob-to-regexp here: https://www.npmjs.com/package/glob-to-regexp.
58
- ${t.message}`)}})(eS(e)):e).some(e=>e.test(eS(r.origin))));return i||Y(`Clerk: Redirect URL ${r} is not on one of the allowedRedirectOrigins, falling back to the default redirect URL.`),i}))}};let eq="__clerk_netlify_cache_bust",eO=["__clerk_status","__clerk_created_session","__clerk_invitation_token","__clerk_ticket","__clerk_modal_state","__clerk_handshake","__clerk_handshake_nonce","__clerk_help",eq,K,V,H];function eT(e){return new URL(window.location.href).searchParams.get(e)||null}function eU(e){let t=new URL(window.location.href);t.searchParams.has(e)&&(t.searchParams.delete(e),window.history.replaceState(window.history.state,"",t))}function eM(e){let t=new URLSearchParams(window.location.search),a=e||new URLSearchParams;for(let e of eO){let r=t.get(e);r&&a.set(e,r)}return a}let eR={"choose-organization":"choose-organization","reset-password":"reset-password"},eB=e=>`/tasks/${eR[e.key]}`;function eN(e,{navigate:t,baseUrl:a}){let r=e.currentTask;if(r){var n;let e;return t((n={base:a},e=eM(),e_({base:n.base,hashPath:eB(r),searchParams:e},{stringify:!0})))}}let eD=e=>`🔒 Clerk:
58
+ ${t.message}`)}})(ez(e)):e).some(e=>e.test(ez(r.origin))));return i||$(`Clerk: Redirect URL ${r} is not on one of the allowedRedirectOrigins, falling back to the default redirect URL.`),i}))}};let eP="__clerk_netlify_cache_bust",eq=["__clerk_status","__clerk_created_session","__clerk_invitation_token","__clerk_ticket","__clerk_modal_state","__clerk_handshake","__clerk_handshake_nonce","__clerk_help",eP,W,H,K];function eO(e){return new URL(window.location.href).searchParams.get(e)||null}function eT(e){let t=new URL(window.location.href);t.searchParams.has(e)&&(t.searchParams.delete(e),window.history.replaceState(window.history.state,"",t))}function eU(e){let t=new URLSearchParams(window.location.search),a=e||new URLSearchParams;for(let e of eq){let r=t.get(e);r&&a.set(e,r)}return a}let eM={"choose-organization":"choose-organization","reset-password":"reset-password"},eR=e=>`/tasks/${eM[e.key]}`;function eB(e,{navigate:t,baseUrl:a}){let r=e.currentTask;if(r){var n;let e;return t((n={base:a},e=eU(),ej({base:n.base,hashPath:eR(r),searchParams:e},{stringify:!0})))}}let eN=e=>`🔒 Clerk:
59
59
  ${e.trim()}
60
- (This notice only appears in development)`,eF={cannotRenderComponentWhenSessionExists:"The <SignUp/> and <SignIn/> components cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the Home URL instead.",cannotRenderSignUpComponentWhenSessionExists:"The <SignUp/> component cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the value set in `afterSignUp` URL instead.",cannotRenderSignUpComponentWhenTaskExists:"The <SignUp/> component cannot render when a user has a pending task, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the task instead.",cannotRenderComponentWhenTaskDoesNotExist:"<TaskChooseOrganization/> cannot render unless a session task is pending. Clerk is redirecting to the value set in `redirectUrlComplete` instead.",cannotRenderSignInComponentWhenSessionExists:"The <SignIn/> component cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the `afterSignIn` URL instead.",cannotRenderSignInComponentWhenTaskExists:"The <SignIn/> component cannot render when a user has a pending task, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the task instead.",cannotRenderComponentWhenUserDoesNotExist:"<UserProfile/> cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotRenderComponentWhenOrgDoesNotExist:"<OrganizationProfile/> cannot render unless an organization is active. Since no organization is currently active, this is no-op.",cannotRenderAnyOrganizationComponent:e=>eD(`The <${e}/> cannot be rendered when the feature is turned off. Visit 'dashboard.clerk.com' to enable the feature. Since the feature is turned off, this is no-op.`),cannotRenderAnyBillingComponent:e=>eD(`The <${e}/> component cannot be rendered when billing is disabled. Visit 'https://dashboard.clerk.com/last-active?path=billing/settings' to follow the necessary steps to enable billing. Since billing is disabled, this is no-op.`),cannotOpenUserProfile:"The UserProfile modal cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotOpenCheckout:"The Checkout drawer cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotOpenSignInOrSignUp:"The SignIn or SignUp modals do not render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, this is no-op.",cannotRenderAPIKeysComponent:"The <APIKeys/> component cannot be rendered when API keys is disabled. Since API keys is disabled, this is no-op.",cannotRenderAPIKeysComponentForOrgWhenUnauthorized:"The <APIKeys/> component cannot be rendered for an organization unless a user has the required permissions. Since the user does not have the necessary permissions, this is no-op.",cannotRenderAPIKeysComponentForUserWhenDisabled:"The <APIKeys/> component cannot be rendered when user API keys are disabled. Since user API keys are disabled, this is no-op.",cannotRenderAPIKeysComponentForOrgWhenDisabled:"The <APIKeys/> component cannot be rendered when organization API keys are disabled. Since organization API keys are disabled, this is no-op."};for(let e of Object.keys(eF)){let t=eF[e];"function"!=typeof t&&(eF[e]=eD(t))}let eL="clerk:beforeunload",eW=["http:","https:","wails:","chrome-extension:"];function eK(e){let t=new URL(e,window.location.href);window.dispatchEvent(new CustomEvent(eL)),window.location.href=t.href}function eH(e){return/^http(s)?:\/\//.test(e||"")}function eV(e){return e.startsWith("/")}var eG=class{#c;#U=864e5;constructor(e){this.#c=e}isEventThrottled(e){let t=Date.now(),a=this.#M(e),r=this.#c.getItem(a);return!!r&&!(t-r>this.#U)||(this.#c.setItem(a,t),!1)}#M(e){let{sk:t,pk:a,payload:r,...n}=e,i={...r,...n};return JSON.stringify(Object.keys({...r,...n}).sort().map(e=>i[e]))}},eJ=class{#R="clerk_telemetry_throttler";getItem(e){return this.#B()[e]}setItem(e,t){try{let a=this.#B();a[e]=t,localStorage.setItem(this.#R,JSON.stringify(a))}catch(e){e instanceof DOMException&&("QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)&&localStorage.length>0&&localStorage.removeItem(this.#R)}}removeItem(e){try{let t=this.#B();delete t[e],localStorage.setItem(this.#R,JSON.stringify(t))}catch{}}#B(){try{let e=localStorage.getItem(this.#R);if(!e)return{};return JSON.parse(e)}catch{return{}}}static isSupported(){return"undefined"!=typeof window&&!!window.localStorage}},eZ=class{#c=new Map;#N=1e4;getItem(e){return this.#c.size>this.#N?void this.#c.clear():this.#c.get(e)}setItem(e,t){this.#c.set(e,t)}removeItem(e){this.#c.delete(e)}};let e$=new Set(["error","warn","info","debug","trace"]);var eY=class{#D;#F;#L={};#W=[];#K=null;constructor(e){this.#D={maxBufferSize:e.maxBufferSize??5,samplingRate:e.samplingRate??1,perEventSampling:e.perEventSampling??!0,disabled:e.disabled??!1,debug:e.debug??!1,endpoint:"https://clerk-telemetry.com"},e.clerkVersion||"undefined"!=typeof window?this.#L.clerkVersion=e.clerkVersion??"":this.#L.clerkVersion="",this.#L.sdk=e.sdk,this.#L.sdkVersion=e.sdkVersion,this.#L.publishableKey=e.publishableKey??"";const t=em(e.publishableKey);t&&(this.#L.instanceType=t.instanceType),e.secretKey&&(this.#L.secretKey=e.secretKey.substring(0,16)),this.#F=new eG(eJ.isSupported()?new eJ:new eZ)}get isEnabled(){return!("development"!==this.#L.instanceType||this.#D.disabled||"undefined"!=typeof process&&process.env&&ei(process.env.CLERK_TELEMETRY_DISABLED)||"undefined"!=typeof window&&window?.navigator?.webdriver)}get isDebug(){return this.#D.debug||"undefined"!=typeof process&&process.env&&ei(process.env.CLERK_TELEMETRY_DEBUG)}record(e){try{let t=this.#H(e.event,e.payload);if(this.#V(t.event,t),!this.#G(t,e.eventSamplingRate))return;this.#W.push({kind:"event",value:t}),this.#J()}catch(e){console.error("[clerk/telemetry] Error recording telemetry event",e)}}recordLog(e){try{if(!this.#Z(e))return;let t="string"==typeof e?.level&&e$.has(e.level),a="string"==typeof e?.message&&e.message.trim().length>0,r=null,n=e?.timestamp;if("number"==typeof n||"string"==typeof n){let e=new Date(n);Number.isNaN(e.getTime())||(r=e)}if(!t||!a||null===r){this.isDebug&&"undefined"!=typeof console&&console.warn("[clerk/telemetry] Dropping invalid telemetry log entry",{levelIsValid:t,messageIsValid:a,timestampIsValid:null!==r});return}let i=this.#$(),s={sdk:i.name,sdkv:i.version,cv:this.#L.clerkVersion??"",lvl:e.level,msg:e.message,ts:r.toISOString(),pk:this.#L.publishableKey||null,payload:this.#Y(e.context)};this.#W.push({kind:"log",value:s}),this.#J()}catch(e){console.error("[clerk/telemetry] Error recording telemetry log entry",e)}}#G(e,t){return this.isEnabled&&!this.isDebug&&this.#Q(e,t)}#Z(e){return!0}#Q(e,t){let a=Math.random();return!!(a<=this.#D.samplingRate&&(!1===this.#D.perEventSampling||void 0===t||a<=t))&&!this.#F.isEventThrottled(e)}#J(){if("undefined"==typeof window)return void this.#X();if(this.#W.length>=this.#D.maxBufferSize){this.#K&&("undefined"!=typeof cancelIdleCallback?cancelIdleCallback(Number(this.#K)):clearTimeout(Number(this.#K))),this.#X();return}this.#K||("requestIdleCallback"in window?this.#K=requestIdleCallback(()=>{this.#X(),this.#K=null}):this.#K=setTimeout(()=>{this.#X(),this.#K=null},0))}#X(){let e=[...this.#W];if(this.#W=[],this.#K=null,0===e.length)return;let t=e.filter(e=>"event"===e.kind).map(e=>e.value),a=e.filter(e=>"log"===e.kind).map(e=>e.value);t.length>0&&fetch(new URL("/v1/event",this.#D.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({events:t})}).catch(()=>void 0),a.length>0&&fetch(new URL("/v1/logs",this.#D.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({logs:a})}).catch(()=>void 0)}#V(e,t){this.isDebug&&(void 0!==console.groupCollapsed?(console.groupCollapsed("[clerk/telemetry]",e),console.log(t),console.groupEnd()):console.log("[clerk/telemetry]",e,t))}#$(){let e={name:this.#L.sdk,version:this.#L.sdkVersion};if("undefined"!=typeof window){let t=window;if(t.Clerk){let a=t.Clerk;if("object"==typeof a&&null!==a&&"constructor"in a&&"function"==typeof a.constructor&&a.constructor.sdkMetadata){let{name:t,version:r}=a.constructor.sdkMetadata;void 0!==t&&(e.name=t),void 0!==r&&(e.version=r)}}}return e}#H(e,t){let a=this.#$();return{event:e,cv:this.#L.clerkVersion??"",it:this.#L.instanceType??"",sdk:a.name,sdkv:a.version,...this.#L.publishableKey?{pk:this.#L.publishableKey}:{},...this.#L.secretKey?{sk:this.#L.secretKey}:{},payload:t}}#Y(e){if(null==e||"object"!=typeof e)return null;try{let t=JSON.parse(JSON.stringify(e));if(t&&"object"==typeof t&&!Array.isArray(t))return t;return null}catch{return null}}};let eQ="COMPONENT_MOUNTED",eX=new Set(["SignIn","SignUp"]);function e1(e){return function(t,a,r){return{event:e,eventSamplingRate:e===eQ?eX.has(t)?1:.1:.1,payload:{component:t,appearanceProp:!!a?.appearance,theme:!!a?.appearance?.theme,elements:!!a?.appearance?.elements,variables:!!a?.appearance?.variables,...r}}}}function e0(e,t,a){return e1(eQ)(e,t,a)}function e2(e,t,a){return e1("COMPONENT_OPENED")(e,t,a)}function e9(e){return"string"==typeof e?e:"object"==typeof e&&null!==e&&"name"in e&&"string"==typeof e.name?e.name:void 0}function e3(e,t,a){return"function"==typeof e?e(t):void 0!==e?e:void 0!==a?a:void 0}let e5=(...e)=>{},e6=!1,e8=null,e4=!1,e7=[];function te(e,t,a,r){e6&&(e7.push({level:e,message:t,context:a,source:r,ts:Date.now()}),e7.length>200&&e7.shift())}async function tt(e){try{if(!e6||e8)return;let{getDebugLogger:t}=await Promise.resolve().then(n.bind(n,9854)),a=await t({logLevel:e?.logLevel,telemetryCollector:e?.telemetryCollector});if(a&&(e8=a)&&0!==e7.length){for(let e of e7){let t={...e.context||{},__preInit:!0,__preInitTs:e.ts};switch(e.level){case"error":e8.error(e.message,t,e.source);break;case"warn":e8.warn(e.message,t,e.source);break;case"info":e8.info(e.message,t,e.source);break;case"debug":e8.debug(e.message,t,e.source)}}e7.length=0}}catch(e){try{console.debug?.("Debug logger initialization failed",e)}catch{}return}}let ta={debug(e,t,a){e8?e8.debug(e,t,a):te("debug",e,t,a)},error(e,t,a){e8?e8.error(e,t,a):te("error",e,t,a)},info(e,t,a){e8?e8.info(e,t,a):te("info",e,t,a)},warn(e,t,a){e8?e8.warn(e,t,a):te("warn",e,t,a)}},tr={initialDelay:125,maxDelayBetweenRetries:0,factor:2,shouldRetry:(e,t)=>t<5,retryImmediately:!1,jitter:!0},tn=async e=>new Promise(t=>setTimeout(t,e)),ti=(e,t)=>t?e*(1+Math.random()):e,ts=async(e,t={})=>{var a;let r,n=0,{shouldRetry:i,initialDelay:s,maxDelayBetweenRetries:o,factor:l,retryImmediately:c,jitter:u,onBeforeRetry:d}={...tr,...t},h=(a={initialDelay:s,maxDelayBetweenRetries:o,factor:l,jitter:u},r=0,async()=>{let e;await tn((e=ti(e=a.initialDelay*Math.pow(a.factor,r),a.jitter),Math.min(a.maxDelayBetweenRetries||e,e))),r++});for(;;)try{return await e()}catch(e){if(!i(e,++n))throw e;d&&await d(n),c&&1===n?await tn(ti(100,u)):await h()}},to=async e=>ts(e,{initialDelay:100,shouldRetry:(e,t)=>t<=3,retryImmediately:!0,factor:2});class tl{#ee={"@zxcvbn-ts/core":()=>to(()=>Promise.resolve().then(n.bind(n,7010))),"@zxcvbn-ts/language-common":()=>to(()=>Promise.resolve().then(n.bind(n,655))),"@base-org/account":()=>to(()=>Promise.resolve().then(n.bind(n,1965))),"@coinbase/wallet-sdk":()=>to(()=>Promise.resolve().then(n.bind(n,2804))),"@stripe/stripe-js":()=>to(()=>Promise.resolve().then(n.bind(n,5608)))};import(e){return this.#ee[e]?this.#ee[e]():Promise.resolve(void 0)}}let tc=(e=!1)=>{let t,a;if(!e)return{track:async e=>{await e()},isUnloading:()=>!1};let r=(t=!1,a=()=>t=!0,{startListening:()=>{window.addEventListener("beforeunload",a),window.addEventListener(eL,a)},stopListening:()=>{window.removeEventListener("beforeunload",a),window.removeEventListener(eL,a)},isUnloading:()=>t});return{track:async e=>{r.startListening(),await e(),r.stopListening()},isUnloading:r.isUnloading}},tu=e=>({amount:e.amount,amountFormatted:e.amount_formatted,currency:e.currency,currencySymbol:e.currency_symbol}),td=e=>{let t={grandTotal:tu(e.grand_total),subtotal:tu(e.subtotal),taxTotal:tu(e.tax_total)};return"past_due"in e&&(t.pastDue=e.past_due?tu(e.past_due):null),"credit"in e&&(t.credit=e.credit?tu(e.credit):null),"total_due_now"in e&&(t.totalDueNow=tu(e.total_due_now)),"total_due_after_free_trial"in e&&(t.totalDueAfterFreeTrial=e.total_due_after_free_trial?tu(e.total_due_after_free_trial):null),t};function th(e,t=""){return e.errors&&!!e.errors.find(e=>e.code===t)}let tm=function({packageName:e,customMessages:t}){let a=e;function r(e,t){if(!t)return`${a}: ${e}`;let r=e;for(let a of e.matchAll(/{{([a-zA-Z0-9-_]+)}}/g)){let e=(t[a[1]]||"").toString();r=r.replace(`{{${a[1]}}}`,e)}return`${a}: ${r}`}let n={..._,...t};return{setPackageName({packageName:e}){return"string"==typeof e&&(a=e),this},setMessages({customMessages:e}){return Object.assign(n,e||{}),this},throwInvalidPublishableKeyError(e){throw Error(r(n.InvalidPublishableKeyErrorMessage,e))},throwInvalidProxyUrl(e){throw Error(r(n.InvalidProxyUrlErrorMessage,e))},throwMissingPublishableKeyError(){throw Error(r(n.MissingPublishableKeyErrorMessage))},throwMissingSecretKeyError(){throw Error(r(n.MissingSecretKeyErrorMessage))},throwMissingClerkProviderError(e){throw Error(r(n.MissingClerkProvider,e))},throw(e){throw Error(r(e))}}}({packageName:"@clerk/clerk-js"});function tp(e){return decodeURIComponent(globalThis.atob(e.replace(/_/g,"/").replace(/-/g,"+")).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""))}function tf(e){let t=(e||"").split("."),[a,r,n]=t;if(3!==t.length||!a||!r||!n)throw Error("JWT could not be decoded");let i=JSON.parse(tp(r)),s={__raw:e};return Object.keys(i).forEach(e=>{s[e]=i[e]}),{encoded:{header:a,payload:r,signature:n},header:JSON.parse(tp(a)),claims:s}}function tg(){if(!s())return null;try{let e=navigator?.language;if(!e||"string"!=typeof e||""===e.trim())return null;return e}catch{return null}}function tb(){return void 0!==globalThis.document}function ty(){if(!function(){if(!tb())return!1;try{return window.self!==window.top}catch{return!0}}())return!1;try{return window.top?.location.href,!1}catch{return!0}}var tw=class e{#et=[];#ea={metamask:"MetaMask",okx_wallet:"OKX Wallet"};static #er=null;constructor(){if("undefined"==typeof window)return;window.addEventListener("eip6963:announceProvider",this.#en),window.dispatchEvent(new Event("eip6963:requestProvider"))}static getInstance(){return e.#er||(e.#er=new e),e.#er}get=e=>{let t=this.#et.find(t=>t.info.name===this.#ea[e])?.provider;return void 0!==t?t:window.ethereum};#en=e=>{this.#et.some(t=>t.info.uuid===e.detail.info.uuid)||this.#et.push(e.detail)}};let tk=()=>(function(e){async function t(e){let{provider:t}=e,a=await d(t);if(!a)return"";let r=await a.request({method:"eth_requestAccounts"});return r&&r[0]||""}async function a(e){let{identifier:t,nonce:a,provider:r}=e,n=await d(r);return n?await n.request({method:"personal_sign",params:[`0x${a.split("").map(e=>e.charCodeAt(0).toString(16).padStart(2,"0")).join("")}`,t]}):""}async function r(){return await t({provider:"metamask"})}async function n(){return await t({provider:"coinbase_wallet"})}async function i(){return await t({provider:"okx_wallet"})}async function s(){return await t({provider:"base"})}async function o(e){return await a({...e,provider:"metamask"})}async function l(e){return await a({...e,provider:"coinbase_wallet"})}async function c(e){return await a({...e,provider:"okx_wallet"})}async function u(e){return await a({...e,provider:"base"})}async function d(t){if("coinbase_wallet"===t){let t=await e.import("@coinbase/wallet-sdk");return t?t.createCoinbaseWalletSDK({preference:{options:"all"}}).getProvider():null}if("base"===t)try{let t=await e.import("@base-org/account");if(!t)return null;return t.createBaseAccountSDK({appName:"undefined"!=typeof window&&window.Clerk?.__internal_environment?.displayConfig?.applicationName||"undefined"!=typeof document&&document.title||"Web3 Application"}).getProvider()}catch{return null}return tw.getInstance().get(t)}return{getWeb3Identifier:t,generateWeb3Signature:a,getMetamaskIdentifier:r,getCoinbaseWalletIdentifier:n,getOKXWalletIdentifier:i,getBaseIdentifier:s,generateSignatureWithMetamask:o,generateSignatureWithCoinbaseWallet:l,generateSignatureWithOKXWallet:c,generateSignatureWithBase:u}})(new tl),tv="environment",tx=JSON.stringify,tj=JSON.parse;class t_{static _key(e){return`__clerk_${e}`}static isExpired(e){return!!e.exp&&Date.now()>e.exp}static setItem(e,t,a){try{let r={value:t,...a&&{exp:Date.now()+a}};window.localStorage.setItem(this._key(e),tx(r))}catch{}}static getItem(e,t){try{let a=window.localStorage.getItem(this._key(e));if(!a)return t;let r=tj(a);if(!r)return t;if(this.isExpired(r))return this.removeItem(e),t;return r?.value??t}catch{return t}}static removeItem(e){try{window.localStorage.removeItem(this._key(e))}catch{}}}let tz="ClerkJS:";function tS(e=""){throw Error(`${tz} Something went wrong initializing Clerk in development mode.${e&&` ${e}`}`)}function tA(e){throw Error(`${tz} Something went wrong initializing Clerk during the ${e} flow. Please contact support.`)}function tE(e){throw Error(`${tz} You need to start a ${e} flow by calling ${e}.create() first.`)}function tI(e,t){throw Error(`${tz} Strategy "${t}" is not a valid strategy for ${e}.`)}function tC(e){throw Error(`${tz} You need to start a ${e} flow by calling ${e}.create({ identifier: 'your web3 wallet address' }) first`)}function tP(e=""){throw Error(`${tz} Missing '${e}' option`)}function tq(e,t){throw Error(`${tz} Response: ${e||0} not supported yet.
61
- For more information contact us at ${t}`)}function tO(e){throw Error(`${tz} Missing publicKey. When calling 'navigator.credentials.${e}()' it is required to pass a publicKey object.`)}async function tT(e="",t){let{async:a,defer:r,beforeLoad:n,crossOrigin:i,nonce:s}=t||{};return ts(()=>new Promise((t,o)=>{e||o(Error("loadScript cannot be called without a src")),document&&document.body||o(Error("loadScript cannot be called when document does not exist"));let l=document.createElement("script");i&&l.setAttribute("crossorigin",i),l.async=a||!1,l.defer=r||!1,l.addEventListener("load",()=>{l.remove(),t(l)}),l.addEventListener("error",t=>{l.remove(),o(t.error??Error(`failed to load script: ${e}`))}),l.src=e,l.nonce=s,n?.(l),document.body.appendChild(l)}),{shouldRetry:(e,t)=>t<=5})}async function tU(e){return window.turnstile||await tM(e).catch(()=>{throw{captchaError:"captcha_script_failed_to_load"}}),window.turnstile}async function tM(e){try{return await tT("https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",{defer:!0,nonce:e})}catch(e){throw console.warn("Clerk: Failed to load the CAPTCHA script from Cloudflare. If you see a CSP error in your browser, please add the necessary CSP rules to your app. Visit https://clerk.com/docs/security/clerk-csp for more information."),e}}function tR(e){try{let t=e.getAttribute("data-cl-theme")||void 0,a=e.getAttribute("data-cl-language")||void 0,r=e.getAttribute("data-cl-size")||void 0;return{theme:t,language:a,size:r}}catch{return{theme:void 0,language:void 0,size:void 0}}}let tB=async e=>{let t,a,r,n,{siteKey:i,widgetType:s,invisibleSiteKey:o,nonce:l}=e,{modalContainerQuerySelector:c,modalWrapperQuerySelector:u,closeModal:d,openModal:h}=e,m=await tU(l),p=[],f="",g="",b=i,y=0,w=null,k="invisible";if(c&&u){w=s,n=c,k="modal";try{await h?.()}catch{throw{captchaError:"modal_component_not_ready"}}let e=await new Promise(e=>{if(document.querySelector(c))return e(document.querySelector(c));let t=new MutationObserver(()=>{document.querySelector(c)&&(t.disconnect(),e(document.querySelector(c)))});t.observe(document.body,{childList:!0,subtree:!0})});if(e){let{theme:n,language:i,size:s}=tR(e);t=n,r=i,a=s}}if(!n&&"smart"===s){let e=document.getElementById(G);if(e){k="smart",w="smart",n=`#${G}`,e.style.maxHeight="0";let{theme:i,language:s,size:o}=tR(e);t=i,r=s,a=o}else console.error("Cannot initialize Smart CAPTCHA widget because the `clerk-captcha` DOM element was not found; falling back to Invisible CAPTCHA widget. If you are using a custom flow, visit https://clerk.com/docs/guides/development/custom-flows/bot-sign-up-protection for instructions")}if(!n){k="invisible",b=o,w="invisible",n=`.${J}`;let e=document.createElement("div");e.classList.add(J),e.style.display="none",document.body.appendChild(e)}let v=async()=>new Promise((i,s)=>{try{let o=m.render(n,{sitekey:b,appearance:"interaction-only",theme:t||"auto",size:a||"normal",language:r||"auto",action:e.action,retry:"never","refresh-expired":"auto",callback:function(e){d?.(),i([e,o])},"before-interactive-callback":()=>{if(u){let e=document.querySelector(u);e?.style.setProperty("visibility","visible"),e?.style.setProperty("pointer-events","all")}else{let e=document.getElementById(G);e&&(e.style.maxHeight="unset",e.style.minHeight="compact"===a?"140px":"68px",e.style.marginBottom="1.5rem")}},"error-callback":function(e){var t;(p.push(e),y<2&&(t=e.toString(),["crashed","undefined_error","102","103","104","106","110600","300","600"].find(e=>t.startsWith(e))))?setTimeout(()=>{m.reset(o),y++},250):s([p.join(","),o])},"unsupported-callback":function(){return s(["This browser is not supported by the CAPTCHA.",o]),!0}})}catch(e){s([e,void 0])}});try{[f,g]=await v(),m.remove(g)}catch([e,t]){throw t&&m.remove(t),{captchaError:e}}finally{if("modal"===k&&d?.(),"invisible"===k){let e=document.querySelector(`.${J}`);e&&document.body.removeChild(e)}if("smart"===k){let e=document.getElementById(G);e&&(e.style.maxHeight="0",e.style.minHeight="unset",e.style.marginBottom="unset")}}return{captchaToken:f,captchaWidgetType:w}},tN=e=>{let t=e.__internal_environment,a=t?t.displayConfig.captchaProvider:"turnstile",r=e.__internal_getOption?.("nonce");return{captchaSiteKey:t?t.displayConfig.captchaPublicKey:null,captchaWidgetType:t?t.displayConfig.captchaWidgetType:null,captchaProvider:a,captchaPublicKeyInvisible:t?t.displayConfig.captchaPublicKeyInvisible:null,canUseCaptcha:t?t.userSettings.signUp.captcha_enabled&&e.isStandardBrowser:null,nonce:r||void 0}};class tD{clerk;constructor(e){this.clerk=e}async invisible(e){let{captchaSiteKey:t,canUseCaptcha:a,captchaPublicKeyInvisible:r,nonce:n}=tN(this.clerk);return a&&t&&r?{...await tB({action:e?.action,captchaProvider:"turnstile",invisibleSiteKey:r,nonce:e?.nonce||n||void 0,siteKey:r,widgetType:"invisible"}).catch(e=>e.captchaError?{captchaError:e.captchaError}:{captchaError:e?.message||e||"unexpected_captcha_error"}),captchaAction:e?.action}:{captchaError:"captcha_unavailable",captchaAction:e?.action}}async managedOrInvisible(e){let{captchaSiteKey:t,canUseCaptcha:a,captchaWidgetType:r,captchaProvider:n,captchaPublicKeyInvisible:i,nonce:s}=tN(this.clerk);if(a&&t&&i){let a=await tB({captchaProvider:n,invisibleSiteKey:i,nonce:s||void 0,siteKey:t,widgetType:r,...e}).catch(t=>t.captchaError?{captchaError:t.captchaError}:e?.action==="verify"?{captchaError:t?.message||t||"unexpected_captcha_error"}:void 0);return e?.action==="verify"?{...a,captchaAction:"verify"}:a}return e?.action==="verify"?{captchaError:"captcha_unavailable",captchaAction:e?.action}:{}}async managedInModal(e){return this.managedOrInvisible({modalWrapperQuerySelector:"#cl-modal-captcha-wrapper",modalContainerQuerySelector:"#cl-modal-captcha-container",openModal:()=>this.clerk.__internal_openBlankCaptchaModal(),closeModal:()=>this.clerk.__internal_closeBlankCaptchaModal(),action:e?.action})}}class tF{client;CaptchaChallengeImpl;static instance;inflightException=null;captchaRetryCount=0;MAX_RETRY_ATTEMPTS=3;static getInstance(){return tF.instance||(tF.instance=new tF(aM,tD)),tF.instance}constructor(e,t){this.client=e,this.CaptchaChallengeImpl=t}async execute(e,t){if(this.captchaAttemptsExceeded())throw new E("Security verification failed. Please try again by refreshing the page, clearing your browser cookies, or using a different web browser.",{code:"captcha_client_attempts_exceeded"});try{return this.inflightException&&await this.inflightException,await t()}catch(r){let a;if(!T(r)||U(r)&&"network_error"===r.code||r.errors[0]?.code!=="requires_captcha")throw r;if(this.inflightException)return await this.inflightException,await t();this.inflightException=new Promise(e=>a=e);try{let t=await this.managedChallenge(e);t?.captchaError!=="modal_component_not_ready"&&(await this.client.getOrCreateInstance().__internal_sendCaptchaToken(t),this.captchaRetryCount=0)}catch(e){throw this.captchaRetryCount++,e}finally{a(),this.inflightException=null}return await t()}}managedChallenge(e){return new this.CaptchaChallengeImpl(e).managedInModal({action:"verify"})}captchaAttemptsExceeded=()=>this.captchaRetryCount>=this.MAX_RETRY_ATTEMPTS}class tL{static clerk;id;pathRoot="";static get fapiClient(){return tL.clerk.getFapiClient()}async reload(e){let{rotatingTokenNonce:t}=e||{};return this._baseGet({forceUpdateClient:!0,rotatingTokenNonce:t})}isNew(){return!this.id}static async _fetch(e,t={}){return tF.getInstance().execute(this.clerk,()=>this._baseFetch(e,t))}static async _baseFetch(e,t={}){let a;tL.fapiClient||function(){throw Error(`${tz} Missing FAPI client in resources.`)}();let{fetchMaxTries:r}=t;try{a=await tL.fapiClient.request(e,{fetchMaxTries:r})}catch(t){if(this.shouldRethrowOfflineNetworkErrors())throw new E(t?.message||t,{code:"network_error"});if(!u())return ta.warn("Network request failed while offline, returning null",{method:e.method,path:e.path},"baseResource"),null;throw t}let{payload:n,status:i,statusText:s,headers:o}=a;if(o){let e=o.get("x-country");this.clerk.__internal_setCountry(e?e.toLowerCase():null)}if(("GET"!==e.method||t.forceUpdateClient)&&this._updateClient(n),i>=200&&i<=299)return n;if(i>=400){let e=n?.errors,t=e?.[0]?.long_message,a=e?.[0]?.code;401===i&&"requires_captcha"!==a&&await tL.clerk.handleUnauthenticated(),function(e,t){var a;if(!t||!t[0])return;let r=t[0],n=r.long_message;if("origin_invalid"===r.code&&((a=tL.clerk.publishableKey).startsWith("live_")||a.startsWith("pk_live_"))){let a=tL.clerk.frontendApi.replace("clerk.","");throw new v(`Clerk: Production Keys are only allowed for domain "${a}".
62
- API Error: ${n}`,{data:t,status:e})}}(i,e);let r={data:e,status:i};if(429===i&&o){let e=o.get("retry-after");if(e){let t=parseInt(e,10);isNaN(t)||(r.retryAfter=t)}}throw new v(t||s,r)}return null}static _updateClient(e){if(!e)return;let t=e.client||e.meta?.client;t&&tL.clerk&&tL.clerk.updateClient(aM.getOrCreateInstance().fromJSON(t))}path(e){let t=this.pathRoot;if(this.isNew())return t;let a=t.replace(/[^/]$/,"$&/")+encodeURIComponent(this.id);return e?a.replace(/[^/]$/,"$&/")+encodeURIComponent(e):a}withDefault(e,t){return e??t}async _baseGet(e={}){let t=await tL._fetch({method:"GET",path:this.path(),rotatingTokenNonce:e.rotatingTokenNonce},e);return this.fromJSON(t?.response||t)}async _baseMutate(e){let{action:t,body:a,method:r,path:n}=e,i=await tL._fetch({method:r,path:n||this.path(t),body:a});return this.fromJSON(i?.response||i)}async _baseMutateBypass(e){let{action:t,body:a,method:r,path:n}=e,i=await tL._baseFetch({method:r,path:n||this.path(t),body:a});return this.fromJSON(i?.response||i)}async _basePost(e={}){return this._baseMutate({...e,method:"POST"})}async _basePostBypass(e={}){return this._baseMutateBypass({...e,method:"POST"})}async _basePut(e={}){return this._baseMutate({...e,method:"PUT"})}async _basePatch(e={}){return this._baseMutate({...e,method:"PATCH"})}async _baseDelete(e={}){await this._baseMutate({...e,method:"DELETE"})}static shouldRethrowOfflineNetworkErrors(){let e=tL.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}function tW(e){let t=new Date(e||new Date);return t instanceof Date&&!isNaN(t.getTime())?t:new Date}class tK extends tL{pathRoot="/api_keys";id;type;name;subject;scopes;claims;revoked;revocationReason;expired;expiration;createdBy;description;secret;lastUsedAt;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.type=e.type,this.name=e.name,this.subject=e.subject,this.scopes=e.scopes,this.claims=e.claims,this.revoked=e.revoked,this.revocationReason=e.revocation_reason,this.expired=e.expired,this.expiration=e.expiration?tW(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?tW(e.last_used_at):null,this.updatedAt=tW(e.updated_at),this.createdAt=tW(e.created_at)),this}__internal_toSnapshot(){return{object:"api_key",id:this.id,type:this.type,name:this.name,subject:this.subject,scopes:this.scopes,claims:this.claims,revoked:this.revoked,revocation_reason:this.revocationReason,expired:this.expired,expiration:this.expiration?this.expiration.getTime():null,created_by:this.createdBy,description:this.description,last_used_at:this.lastUsedAt?this.lastUsedAt.getTime():null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class tH extends tL{claimedAt=null;reverification=!1;singleSessionMode=!1;preferredChannels=null;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.claimedAt=this.withDefault(e.claimed_at?tW(e.claimed_at):null,this.claimedAt),this.reverification=this.withDefault(e.reverification,this.reverification),this.singleSessionMode=this.withDefault(e.single_session_mode,this.singleSessionMode),this.preferredChannels=this.withDefault(e.preferred_channels,this.preferredChannels)),this}__internal_toSnapshot(){return{claimed_at:this.claimedAt?this.claimedAt.getTime():null,id:this.id??"",object:"auth_config",reverification:this.reverification,single_session_mode:this.singleSessionMode}}}(b=y||(y={}))[b.None=0]="None",b[b.Mutable=1]="Mutable",b[b.Watching=2]="Watching",b[b.RecursedCheck=4]="RecursedCheck",b[b.Recursed=8]="Recursed",b[b.Dirty=16]="Dirty",b[b.Pending=32]="Pending";let tV=[],{link:tG,unlink:tJ,propagate:tZ,checkDirty:t$,endTracking:tY,startTracking:tQ,shallowPropagate:tX}=function({update:e,notify:t,unwatched:a}){let r=0;return{link:function(e,t){let a,n=t.depsTail;if(void 0!==n&&n.dep===e)return;if(4&t.flags&&void 0!==(a=void 0!==n?n.nextDep:t.deps)&&a.dep===e){a.version=r,t.depsTail=a;return}let i=e.subsTail;if(void 0!==i&&i.version===r&&i.sub===t)return;let s=t.depsTail=e.subsTail={version:r,dep:e,sub:t,prevDep:n,nextDep:a,prevSub:i,nextSub:void 0};void 0!==a&&(a.prevDep=s),void 0!==n?n.nextDep=s:t.deps=s,void 0!==i?i.nextSub=s:e.subs=s},unlink:n,propagate:function(e){let a,r=e.nextSub;t:for(;;){let n=e.sub,i=n.flags;if(3&i&&(60&i?12&i?4&i?!(48&i)&&function(e,t){let a=t.depsTail;if(void 0!==a){let r=t.deps;do{if(r===e)return!0;if(r===a)break;r=r.nextDep}while(void 0!==r)}return!1}(e,n)?(n.flags=40|i,i&=1):i=0:n.flags=-9&i|32:i=0:n.flags=32|i,2&i&&t(n),1&i)){let t=n.subs;if(void 0!==t){e=t,void 0!==t.nextSub&&(a={value:r,prev:a},r=e.nextSub);continue}}if(void 0!==(e=r)){r=e.nextSub;continue}for(;void 0!==a;)if(e=a.value,a=a.prev,void 0!==e){r=e.nextSub;continue t}break}},checkDirty:function(t,a){let r,n=0;t:for(;;){let s=t.dep,o=s.flags,l=!1;if(16&a.flags)l=!0;else if((17&o)==17){if(e(s)){let e=s.subs;void 0!==e.nextSub&&i(e),l=!0}}else if((33&o)==33){(void 0!==t.nextSub||void 0!==t.prevSub)&&(r={value:t,prev:r}),t=s.deps,a=s,++n;continue}if(!l&&void 0!==t.nextDep){t=t.nextDep;continue}for(;n;){--n;let s=a.subs,o=void 0!==s.nextSub;if(o?(t=r.value,r=r.prev):t=s,l){if(e(a)){o&&i(s),a=t.sub;continue}}else a.flags&=-33;if(a=t.sub,void 0!==t.nextDep){t=t.nextDep;continue t}l=!1}return l}},endTracking:function(e){let t=e.depsTail,a=void 0!==t?t.nextDep:e.deps;for(;void 0!==a;)a=n(a,e);e.flags&=-5},startTracking:function(e){++r,e.depsTail=void 0,e.flags=-57&e.flags|4},shallowPropagate:i};function n(e,t=e.sub){let r=e.dep,i=e.prevDep,s=e.nextDep,o=e.nextSub,l=e.prevSub;return void 0!==s?s.prevDep=i:t.depsTail=i,void 0!==i?i.nextDep=s:t.deps=s,void 0!==o?o.prevSub=l:r.subsTail=l,void 0!==l?l.nextSub=o:void 0===(r.subs=o)&&a(r),s}function i(e){do{let a=e.sub,r=e.nextSub,n=a.flags;(48&n)==32&&(a.flags=16|n,2&n&&t(a)),e=r}while(void 0!==e)}}({update:e=>"getter"in e?t8(e):t4(e,e.value),notify:function e(t){let a=t.flags;if(!(64&a)){t.flags=64|a;let r=t.subs;void 0!==r?e(r.sub):tV[t2++]=t}},unwatched(e){if("getter"in e){let t=e.deps;if(void 0!==t){e.flags=17;do t=tJ(t,e);while(void 0!==t)}}else"previousValue"in e||aa.call(e)}}),t1=0,t0=0,t2=0;function t9(t){let a=e;return e=t,a}function t3(e){return at.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function t5(e){return ae.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function t6(a){let r={fn:a,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?tG(r,e):void 0!==t&&tG(r,t);let n=t9(r);try{r.fn()}finally{t9(n)}return aa.bind(r)}function t8(e){let t=t9(e);tQ(e);try{let t=e.value;return t!==(e.value=e.getter(t))}finally{t9(t),tY(e)}}function t4(e,t){return e.flags=1,e.previousValue!==(e.previousValue=t)}function t7(){for(;t0<t2;){let e=tV[t0];tV[t0++]=void 0,function e(t,a){if(16&a||32&a&&t$(t.deps,t)){let e=t9(t);tQ(t);try{t.fn()}finally{t9(e),tY(t)}return}32&a&&(t.flags=-33&a);let r=t.deps;for(;void 0!==r;){let t=r.dep,a=t.flags;64&a&&e(t,t.flags=-65&a),r=r.nextDep}}(e,e.flags&=-65)}t0=0,t2=0}function ae(){let a=this.flags;if(16&a||32&a&&t$(this.deps,this)){if(t8(this)){let e=this.subs;void 0!==e&&tX(e)}}else 32&a&&(this.flags=-33&a);return void 0!==e?tG(this,e):void 0!==t&&tG(this,t),this.value}function at(...t){if(t.length){let e=t[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(tZ(e),t1||t7())}}else{let t=this.value;if(16&this.flags&&t4(this,t)){let e=this.subs;void 0!==e&&tX(e)}return void 0!==e&&tG(this,e),t}}function aa(){let e=this.deps;for(;void 0!==e;)e=tJ(e,this);let t=this.subs;void 0!==t&&tJ(t),this.flags=0}function ar(e){let{pageSize:t,initialPage:a,...r}=e||{},n=t??10;return new URLSearchParams({...Object.entries(r).reduce((e,[t,a])=>(void 0!==a&&(e[t]=a),e),{}),limit:n+"",offset:((a??1)-1)*n+""})}class an{static #ei="/billing";static path(e,t){let{orgId:a}=t||{},r=a?`/organizations/${a}`:"/me";return`${r}${an.#ei}${e}`}getPlans=async e=>{let{for:t,...a}=e||{},r={...a,payer_type:"organization"===t?"org":"user"};return await tL._fetch({path:`${an.#ei}/plans`,method:"GET",search:ar(r)}).then(e=>{let{data:t,total_count:a}=e;return{total_count:a,data:t.map(e=>new a_(e))}})};getPlan=async e=>new a_(await tL._fetch({path:`${an.#ei}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await tL._fetch({path:an.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new aA(e?.response));getStatements=async e=>{let{orgId:t,...a}=e;return await tL._fetch({path:an.path("/statements",{orgId:t}),method:"GET",search:ar(a)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new az(e))}})};getStatement=async e=>new az((await tL._fetch({path:an.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:t,...a}=e;return await tL._fetch({path:an.path("/payment_attempts",{orgId:t}),method:"GET",search:ar(a)}).then(e=>{let{data:t,total_count:a}=e;return{total_count:a,data:t.map(e=>new ab(e))}})};getPaymentAttempt=async e=>new ab(await tL._fetch({path:an.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:t,...a}=e;return new af((await tL._fetch({path:an.path("/checkouts",{orgId:t}),method:"POST",body:a}))?.response)}}let ai=t3({resource:null}),as=t3({error:null}),ao=t3({status:"idle"}),al=t5(()=>{let e=ai().resource,t=as().error,a=ao().status;return{errors:am(t,{identifier:null,password:null,code:null}),fetchStatus:a,signIn:e?e.__internal_future:null}}),ac=t3({resource:null}),au=t3({error:null}),ad=t3({status:"idle"}),ah=t5(()=>{let e=ac().resource,t=au().error,a=ad().status;return{errors:am(t,{firstName:null,lastName:null,emailAddress:null,phoneNumber:null,password:null,username:null,code:null,captcha:null,legalAccepted:null}),fetchStatus:a,signUp:e?e.__internal_future:null}});function am(e,t){let a={fields:{...t},raw:null,global:null};if(!e)return a;if(!T(e))return a.raw=[e],a.global=[N(e)],a;function r(e){return"meta"in e&&e.meta&&"paramName"in e.meta&&void 0!==e.meta.paramName}return e.errors.some(r)?e.errors.forEach(e=>{if(a.raw?a.raw.push(e):a.raw=[e],r(e)){let t=ee(e.meta.paramName);t in a.fields&&(a.fields[t]=e)}}):(a.raw=[e],a.global=[N(e)]),a}class ap extends tL{id;createdAt;updatedAt;imageUrl;userId=null;email;firstName;lastName;organizationId=null;organizationName;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,e.created_at&&(this.createdAt=tW(e.created_at)),e.updated_at&&(this.updatedAt=tW(e.updated_at)),this.imageUrl=e.image_url,this.userId=e.user_id,this.email=e.email,this.firstName=e.first_name,this.lastName=e.last_name,this.organizationId=e.organization_id,this.organizationName=e.organization_name),this}}class af extends tL{id;externalClientSecret;externalGatewayId;paymentMethod;plan;planPeriod;planPeriodStart;status;totals;isImmediatePlanChange;freeTrialEndsAt;payer;needsPaymentMethod;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.externalClientSecret=e.external_client_secret,this.externalGatewayId=e.external_gateway_id,this.paymentMethod=e.payment_method?new ax(e.payment_method):void 0,this.plan=new a_(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=td(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=tW(e.free_trial_ends_at)),this.payer=new ap(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>ts(()=>this._basePatch({path:an.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,t){if(!T(e)||t>=4)return!1;let a=e?.status,r=409===a&&e.errors?.[0]?.code==="checkout_already_in_progress";return a>=500||r}})}class ag{resource=new af(null);config;signals;pendingOperations=new Map;constructor(e,t){this.config=t,this.signals=e,this.signals.resourceSignal({resource:this})}get status(){return this.resource.status??"needs_initialization"}get externalClientSecret(){return this.resource.externalClientSecret}get externalGatewayId(){return this.resource.externalGatewayId}get plan(){return this.resource.plan}get planPeriod(){return this.resource.planPeriod}get totals(){return this.resource.totals}get isImmediatePlanChange(){return this.resource.isImmediatePlanChange}get freeTrialEndsAt(){return this.resource.freeTrialEndsAt}get payer(){return this.resource.payer}get paymentMethod(){return this.resource.paymentMethod??null}get planPeriodStart(){return this.resource.planPeriodStart}get needsPaymentMethod(){return this.resource.needsPaymentMethod}async start(){return this.runAsyncCheckoutTask("start",async()=>{let e=await af.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new af(null),this.signals.resourceSignal({resource:this})})}async confirm(e){if(!this.resource.id)throw Error("Clerk: `start()` must be called before `confirm()`");return this.runAsyncCheckoutTask("confirm",async()=>{await this.resource.confirm(e)})}async finalize(e){let{navigate:t}=e||{};return this.runAsyncCheckoutTask("finalize",async()=>{if("completed"!==this.resource.status)throw Error("Clerk: `confirm()` must be called before `finalize()`");await af.clerk.setActive({session:af.clerk.session?.id,navigate:t})})}runAsyncCheckoutTask(e,t,a){var r,n,i;return void 0===af.clerk.user?(console.warn("Clerk: Checkout operations cannot be performed during transitive state"),{error:null}):(r=this,n=this.signals,i=this.pendingOperations,async(e,t,a)=>{if(i.get(e))return i.get(e);let s=(async()=>{++t1,n.errorSignal({error:null}),n.fetchSignal({status:"fetching"}),a?.(),--t1||t7(),++t1;try{return await t(),n.resourceSignal({resource:r}),{error:null}}catch(e){return n.errorSignal({error:e}),{error:e}}finally{i.delete(e),n.fetchSignal({status:"idle"}),--t1||t7()}})();return i.set(e,s),s})(e,t,a)}}class ab extends tL{id;amount;failedAt=null;paidAt=null;updatedAt;paymentMethod=null;subscriptionItem;chargeType;status;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.amount=tu(e.amount),this.paidAt=e.paid_at?tW(e.paid_at):null,this.failedAt=e.failed_at?tW(e.failed_at):null,this.updatedAt=tW(e.updated_at),this.paymentMethod=e.payment_method?new ax(e.payment_method):null,this.subscriptionItem=new aE(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}let ay="/payment_methods",aw=async e=>{let{orgId:t,...a}=e;return new aj((await tL._fetch({path:an.path(`${ay}/initialize`,{orgId:t}),method:"POST",body:a}))?.response)},ak=async e=>{let{orgId:t,...a}=e;return new ax((await tL._fetch({path:an.path(ay,{orgId:t}),method:"POST",body:a}))?.response)},av=async e=>{let{orgId:t,...a}=e??{};return await tL._fetch({path:an.path(ay,{orgId:t}),method:"GET",search:ar(a)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new ax(e))}})};class ax extends tL{id;last4=null;paymentType;cardType=null;isDefault;isRemovable;status;walletType;expiryYear;expiryMonth;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.last4=e.last4,this.paymentType=e.payment_type,this.cardType=e.card_type,this.isDefault=e.is_default,this.isRemovable=e.is_removable,this.status=e.status,this.walletType=e.wallet_type,this.expiryYear=e.expiry_year,this.expiryMonth=e.expiry_month,this.createdAt=null==e.created_at?e.created_at:tW(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:tW(e.updated_at)),this}async remove(e){let{orgId:t}=e??{};return new aB((await tL._fetch({path:an.path(`/payment_methods/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:t}=e??{};return await tL._fetch({path:an.path("/payers/default_payment_method",{orgId:t}),method:"PUT",body:{payment_method_id:this.id}}),null}}class aj extends tL{externalClientSecret;externalGatewayId;paymentMethodOrder;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.externalClientSecret=e.external_client_secret,this.externalGatewayId=e.external_gateway_id,this.paymentMethodOrder=e.payment_method_order??["card"]),this}}class a_ extends tL{id;name;fee;annualFee=null;annualMonthlyFee=null;description=null;isDefault;isRecurring;hasBaseFee;forPayerType;publiclyVisible;slug;avatarUrl=null;features;freeTrialDays;freeTrialEnabled;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.fee=tu(e.fee),this.annualFee=e.annual_fee?tu(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?tu(e.annual_monthly_fee):null,this.description=e.description,this.isDefault=e.is_default,this.isRecurring=e.is_recurring,this.hasBaseFee=e.has_base_fee,this.forPayerType=e.for_payer_type,this.publiclyVisible=e.publicly_visible,this.slug=e.slug,this.avatarUrl=e.avatar_url,this.freeTrialDays=this.withDefault(e.free_trial_days,null),this.freeTrialEnabled=this.withDefault(e.free_trial_enabled,!1),this.features=(e.features||[]).map(e=>new rs(e))),this}}class az extends tL{id;status;timestamp;totals;groups;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.timestamp=tW(e.timestamp),this.totals=td(e.totals),this.groups=e.groups.map(e=>new aS(e))),this}}class aS{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=tW(e.timestamp),this.items=e.items.map(e=>new ab(e))),this}}class aA extends tL{id;status;activeAt;createdAt;pastDueAt;updatedAt;nextPayment;subscriptionItems;eligibleForFreeTrial;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.createdAt=tW(e.created_at),this.updatedAt=e.updated_at?tW(e.updated_at):null,this.activeAt=tW(e.active_at),this.pastDueAt=e.past_due_at?tW(e.past_due_at):null,e.next_payment&&(this.nextPayment={amount:tu(e.next_payment.amount),date:tW(e.next_payment.date)}),this.subscriptionItems=(e.subscription_items||[]).map(e=>new aE(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1)),this}}class aE extends tL{id;plan;planPeriod;status;createdAt;periodStart;periodEnd;canceledAt;pastDueAt;amount;credit;isFreeTrial;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.plan=new a_(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.createdAt=tW(e.created_at),this.pastDueAt=e.past_due_at?tW(e.past_due_at):null,this.periodStart=tW(e.period_start),this.periodEnd=e.period_end?tW(e.period_end):null,this.canceledAt=e.canceled_at?tW(e.canceled_at):null,this.amount=e.amount?tu(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:tu(e.credit.amount)}:void 0,this.isFreeTrial=this.withDefault(e.is_free_trial,!1)),this}async cancel(e){let{orgId:t}=e;return new aB((await tL._fetch({path:an.path(`/subscription_items/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}}let aI={build:(e,t,a)=>[e,t,a].filter(Boolean).join("-"),parse:(e,t,a)=>{let r=aI.extractTemplate(e,t,a);return{organizationId:a,sessionId:t,template:r}},extractTemplate:(e,t,a)=>{if(e===t||a&&e===`${t}-${a}`)return;let r=e.slice(t.length+1);return a&&r.endsWith(`-${a}`)&&(r=r.slice(0,-(a.length+1))),r||void 0}},aC="clerk",aP=10,aq={broadcast:!0},aO={broadcast:!1};class aT{prefix;data;static fromKey(e){let[t,a,r=""]=e.split("::");return new aT(t,{audience:r,tokenId:a})}constructor(e,t){this.prefix=e,this.data=t,this.prefix=e,this.data=t}toKey(){let{tokenId:e,audience:t}=this.data;return[this.prefix,e,t||""].join("::")}}let aU=((e=aC)=>{let t=new Map,a=Math.random().toString(36).slice(2),r=null,n=()=>r||("undefined"==typeof BroadcastChannel?null:((r=new BroadcastChannel("clerk:session_token")).addEventListener("message",e=>{s(e)}),r));n();let i=(a,r=aP)=>{n();let i=new aT(e,a),s=t.get(i.toKey());if(!s)return;let o=Math.floor(Date.now()/1e3)-s.createdAt;if(s.expiresIn-o<(r||1)+5){void 0!==s.timeoutId&&clearTimeout(s.timeoutId),t.delete(i.toKey());return}return s.entry},s=async({data:e})=>{let t,r=aI.build(e.sessionId,e.template,e.organizationId);if(e.tokenId!==r)return void ta.warn("Ignoring token broadcast with mismatched tokenId",{expectedTokenId:r,organizationId:e.organizationId,receivedTokenId:e.tokenId,tabId:a,template:e.template,traceId:e.traceId},"tokenCache");try{t=new rH({id:e.tokenId,jwt:e.tokenRaw,object:"token"})}catch(t){ta.warn("Failed to parse token from broadcast, skipping cache update",{error:t,tabId:a,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");return}let n=t.jwt?.claims?.iat,s=t.jwt?.claims?.exp;if(!n||!s)return void ta.warn("Token missing iat/exp claim, skipping cache update",{tabId:a,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");try{let t=i({tokenId:e.tokenId});if(t){let r=await t.tokenResolver,i=r.jwt?.claims?.iat;if(i&&i>=n)return void ta.debug("Ignoring older token broadcast",{existingIat:i,incomingIat:n,tabId:a,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}}catch(t){ta.warn("Existing entry compare failed; proceeding with broadcast update",{error:t,tabId:a,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}ta.info("Updating token cache from broadcast",{iat:n,organizationId:e.organizationId,tabId:a,template:e.template,tokenId:e.tokenId,traceId:e.traceId},"tokenCache"),o({createdAt:n,tokenId:e.tokenId,tokenResolver:Promise.resolve(t)},aO)},o=(n,i=aq)=>{let s=new aT(e,{audience:n.audience,tokenId:n.tokenId}).toKey(),o=Math.floor(Date.now()/1e3),l={createdAt:n.createdAt??o,entry:n,expiresIn:void 0},c=()=>{let e=t.get(s);e===l&&(void 0!==e.timeoutId&&clearTimeout(e.timeoutId),t.delete(s))};n.tokenResolver.then(e=>{let t=e.jwt?.claims;if(!t||"number"!=typeof t.exp||"number"!=typeof t.iat)return c();let s=t.exp-t.iat;l.expiresIn=s;let o=setTimeout(c,1e3*s);l.timeoutId=o,"function"==typeof o.unref&&o.unref();let u=r;if(u&&i.broadcast){let r=e.getRawString();if(r&&t.sid){let e=t.sid,i=t.org_id||t.o?.id,s=aI.extractTemplate(n.tokenId,e,i),o=aI.build(e,s,i);if(n.tokenId===o){let t=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;ta.info("Broadcasting token update to other tabs",{organizationId:i,sessionId:e,tabId:a,template:s,tokenId:n.tokenId,traceId:t},"tokenCache");let o={organizationId:i,sessionId:e,template:s,tokenId:n.tokenId,tokenRaw:r,traceId:t};u.postMessage(o)}}}}).catch(()=>{c()}),t.set(s,l)};return{clear:()=>{t.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId)}),t.clear()},close:()=>{r&&(r.close(),r=null)},get:i,set:e=>{n(),o(e,aq)},size:()=>t.size}})();class aM extends tL{static instance;pathRoot="/client";sessions=[];signUp=new rL;signIn=new rN;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return aM.instance||(aM.instance=new aM(e)),aM.instance}static clearInstance(){aM.instance=null}static isClientResource(e){return!!e&&e instanceof aM}constructor(e=null){super(),this.fromJSON(e)}get signUpAttempt(){return this.signUp}get signInAttempt(){return this.signIn}get signedInSessions(){return this.sessions.filter(e=>"active"===e.status||"pending"===e.status)}create(){return this._basePut()}fetch({fetchMaxTries:e}={}){return this._baseGet({fetchMaxTries:e})}async destroy(){return this._baseDelete({path:"/client"}).then(()=>{aU.clear(),this.id="",this.sessions=[],this.signUp=new rL(null),this.signIn=new rN(null),this.lastActiveSessionId=null,this.lastAuthenticationStrategy=null,this.cookieExpiresAt=null,this.createdAt=null,this.updatedAt=null})}removeSessions(){return this._baseDelete({path:this.path()+"/sessions"}).then(e=>(aU.clear(),e))}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return tL.fapiClient.buildUrl({method:"GET",path:"/client/touch",pathPrefix:"v1",search:{redirect_url:e.toString()}}).toString()}__internal_sendCaptchaToken(e){return this._basePostBypass({body:e,path:this.path()+"/verify"})}fromJSON(e){return e&&(this.id=e.id,this.sessions=(e.sessions||[]).map(e=>new rC(e)),this.signUp=new rL(e.sign_up),this.signIn=new rN(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?tW(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=tW(e.created_at||void 0),this.updatedAt=tW(e.updated_at||void 0)),this}__internal_toSnapshot(){return{object:"client",id:this.id||"",sessions:this.sessions.map(e=>e.__internal_toSnapshot()),sign_up:this.signUp.__internal_toSnapshot(),sign_in:this.signIn.__internal_toSnapshot(),last_active_session_id:this.lastActiveSessionId,captcha_bypass:this.captchaBypass,cookie_expires_at:this.cookieExpiresAt?this.cookieExpiresAt.getTime():null,last_authentication_strategy:this.lastAuthenticationStrategy??null,created_at:this.createdAt?.getTime()??null,updated_at:this.updatedAt?.getTime()??null}}path(){return this.pathRoot}}class aR extends tL{billing={stripePublishableKey:null,organization:{enabled:!1,hasPaidPlans:!1},user:{enabled:!1,hasPaidPlans:!1}};constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.billing.stripePublishableKey=e.billing.stripe_publishable_key,this.billing.organization.enabled=e.billing.organization.enabled,this.billing.organization.hasPaidPlans=e.billing.organization.has_paid_plans,this.billing.user.enabled=e.billing.user.enabled,this.billing.user.hasPaidPlans=e.billing.user.has_paid_plans),this}__internal_toSnapshot(){return{billing:{stripe_publishable_key:this.billing.stripePublishableKey,organization:{enabled:this.billing.organization.enabled,has_paid_plans:this.billing.organization.hasPaidPlans},user:{enabled:this.billing.user.enabled,has_paid_plans:this.billing.user.hasPaidPlans}}}}}class aB{object="";id;slug;deleted=!1;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.object=e.object,this.id=e.id,this.slug=e.slug,this.deleted=e.deleted),this}}class aN extends tL{afterCreateOrganizationUrl="";afterJoinWaitlistUrl="";afterLeaveOrganizationUrl="";afterSignInUrl="";afterSignOutAllUrl="";afterSignOutOneUrl="";afterSignOutUrl="";afterSignUpUrl="";afterSwitchSessionUrl="";applicationName="";backendHost="";branded=!1;captchaHeartbeat=!1;captchaHeartbeatIntervalMs;captchaOauthBypass=["oauth_google","oauth_microsoft","oauth_apple"];captchaProvider="turnstile";captchaPublicKey=null;captchaPublicKeyInvisible=null;captchaWidgetType=null;clerkJSVersion;createOrganizationUrl="";faviconImageUrl="";googleOneTapClientId;homeUrl="";id="";instanceEnvironmentType="";logoImageUrl="";organizationProfileUrl="";preferredSignInStrategy="password";privacyPolicyUrl="";showDevModeWarning=!1;signInUrl="";signUpUrl="";supportEmail="";termsUrl="";theme={};userProfileUrl="";waitlistUrl="";constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.afterCreateOrganizationUrl=this.withDefault(e.after_create_organization_url,this.afterCreateOrganizationUrl),this.afterJoinWaitlistUrl=this.withDefault(e.after_join_waitlist_url,this.afterJoinWaitlistUrl),this.afterLeaveOrganizationUrl=this.withDefault(e.after_leave_organization_url,this.afterLeaveOrganizationUrl),this.afterSignInUrl=this.withDefault(e.after_sign_in_url,this.afterSignInUrl),this.afterSignOutAllUrl=this.withDefault(e.after_sign_out_all_url,this.afterSignOutAllUrl),this.afterSignOutOneUrl=this.withDefault(e.after_sign_out_one_url,this.afterSignOutOneUrl),this.afterSignUpUrl=this.withDefault(e.after_sign_up_url,this.afterSignUpUrl),this.afterSwitchSessionUrl=this.withDefault(e.after_switch_session_url,this.afterSwitchSessionUrl),this.applicationName=this.withDefault(e.application_name,this.applicationName),this.branded=this.withDefault(e.branded,this.branded),this.captchaHeartbeat=this.withDefault(e.captcha_heartbeat,this.captchaHeartbeat),this.captchaHeartbeatIntervalMs=this.withDefault(e.captcha_heartbeat_interval_ms,this.captchaHeartbeatIntervalMs),this.captchaOauthBypass=this.withDefault(e.captcha_oauth_bypass,this.captchaOauthBypass),this.captchaProvider=this.withDefault(e.captcha_provider,this.captchaProvider),this.captchaPublicKey=this.withDefault(e.captcha_public_key,this.captchaPublicKey),this.captchaPublicKeyInvisible=this.withDefault(e.captcha_public_key_invisible,this.captchaPublicKeyInvisible),this.captchaWidgetType=this.withDefault(e.captcha_widget_type,this.captchaWidgetType),this.clerkJSVersion=this.withDefault(e.clerk_js_version,this.clerkJSVersion),this.createOrganizationUrl=this.withDefault(e.create_organization_url,this.createOrganizationUrl),this.faviconImageUrl=this.withDefault(e.favicon_image_url,this.faviconImageUrl),this.googleOneTapClientId=this.withDefault(e.google_one_tap_client_id,this.googleOneTapClientId),this.homeUrl=this.withDefault(e.home_url,this.homeUrl),this.id=this.withDefault(e.id,this.id),this.instanceEnvironmentType=this.withDefault(e.instance_environment_type,this.instanceEnvironmentType),this.logoImageUrl=this.withDefault(e.logo_image_url,this.logoImageUrl),this.organizationProfileUrl=this.withDefault(e.organization_profile_url,this.organizationProfileUrl),this.preferredSignInStrategy=this.withDefault(e.preferred_sign_in_strategy,this.preferredSignInStrategy),this.privacyPolicyUrl=this.withDefault(e.privacy_policy_url,this.privacyPolicyUrl),this.showDevModeWarning=this.withDefault(e.show_devmode_warning,this.showDevModeWarning),this.signInUrl=this.withDefault(e.sign_in_url,this.signInUrl),this.signUpUrl=this.withDefault(e.sign_up_url,this.signUpUrl),this.supportEmail=this.withDefault(e.support_email,this.supportEmail),this.termsUrl=this.withDefault(e.terms_url,this.termsUrl),this.theme=this.withDefault(e.theme,this.theme),this.userProfileUrl=this.withDefault(e.user_profile_url,this.userProfileUrl),this.waitlistUrl=this.withDefault(e.waitlist_url,this.waitlistUrl)),this}__internal_toSnapshot(){return{object:"display_config",after_create_organization_url:this.afterCreateOrganizationUrl,after_join_waitlist_url:this.afterJoinWaitlistUrl,after_leave_organization_url:this.afterLeaveOrganizationUrl,after_sign_in_url:this.afterSignInUrl,after_sign_out_all_url:this.afterSignOutAllUrl,after_sign_out_one_url:this.afterSignOutOneUrl,after_sign_up_url:this.afterSignUpUrl,after_switch_session_url:this.afterSwitchSessionUrl,application_name:this.applicationName,branded:this.branded,captcha_heartbeat_interval_ms:this.captchaHeartbeatIntervalMs,captcha_heartbeat:this.captchaHeartbeat,captcha_oauth_bypass:this.captchaOauthBypass,captcha_provider:this.captchaProvider,captcha_public_key_invisible:this.captchaPublicKeyInvisible,captcha_public_key:this.captchaPublicKey,captcha_widget_type:this.captchaWidgetType,clerk_js_version:this.clerkJSVersion,create_organization_url:this.createOrganizationUrl,favicon_image_url:this.faviconImageUrl,google_one_tap_client_id:this.googleOneTapClientId,home_url:this.homeUrl,id:this.id,instance_environment_type:this.instanceEnvironmentType,logo_image_url:this.logoImageUrl,organization_profile_url:this.organizationProfileUrl,preferred_sign_in_strategy:this.preferredSignInStrategy,privacy_policy_url:this.privacyPolicyUrl,show_devmode_warning:this.showDevModeWarning,sign_in_url:this.signInUrl,sign_up_url:this.signUpUrl,support_email:this.supportEmail,terms_url:this.termsUrl,theme:this.theme,user_profile_url:this.userProfileUrl,waitlist_url:this.waitlistUrl}}}var aD='const respond=r=>{self.postMessage(r)},workerToTabIds={};self.addEventListener("message",r=>{const e=r.data;switch(e.type){case"setTimeout":workerToTabIds[e.id]=setTimeout(()=>{respond({id:e.id}),delete workerToTabIds[e.id]},e.ms);break;case"clearTimeout":workerToTabIds[e.id]&&(clearTimeout(workerToTabIds[e.id]),delete workerToTabIds[e.id]);break;case"setInterval":workerToTabIds[e.id]=setInterval(()=>{respond({id:e.id})},e.ms);break;case"clearInterval":workerToTabIds[e.id]&&(clearInterval(workerToTabIds[e.id]),delete workerToTabIds[e.id]);break}});\n';let aF=(e,t={})=>{if("undefined"==typeof Worker)return null;try{let a=new Blob([e],{type:"application/javascript; charset=utf-8"}),r=globalThis.URL.createObjectURL(a);return new Worker(r,t)}catch{return console.warn("Clerk: Cannot create worker from blob. Consider adding worker-src blob:; to your CSP"),null}},aL=()=>{let e=0,t=()=>e++,a=new Map,r=(e,t)=>e?.postMessage(t),n=e=>{a.get(e.data.id)?.()},i=aF(aD,{name:"clerk-timers"});if(i?.addEventListener("message",n),!i)return{setTimeout:globalThis.setTimeout.bind(globalThis),setInterval:globalThis.setInterval.bind(globalThis),clearTimeout:globalThis.clearTimeout.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis),cleanup:e5};let s=()=>{i||(i=aF(aD,{name:"clerk-timers"}),i?.addEventListener("message",n))};return{setTimeout:(e,n)=>{s();let o=t();return a.set(o,()=>{e(),a.delete(o)}),r(i,{type:"setTimeout",id:o,ms:n}),o},setInterval:(e,n)=>{s();let o=t();return a.set(o,e),r(i,{type:"setInterval",id:o,ms:n}),o},clearTimeout:e=>{s(),a.delete(e),r(i,{type:"clearTimeout",id:e})},clearInterval:e=>{s(),a.delete(e),r(i,{type:"clearInterval",id:e})},cleanup:()=>{i&&(i.terminate(),i=null,a.clear())}}};function aW({delayInMs:e}={delayInMs:1e3}){let t,a=aL(),r=!1,n=()=>{t&&(a.clearTimeout(t),a.cleanup()),r=!0},i=async s=>{r=!1,await s(n),r||(t=a.setTimeout(()=>{i(s)},e))};return{run:i,stop:n}}class aK extends tL{id;emailAddress="";matchesSsoConnection=!1;linkedTo=[];verification;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}create(){return this._basePost({body:{email_address:this.emailAddress}})}prepareVerification=e=>this._basePost({action:"prepare_verification",body:{...e}});attemptVerification=e=>{let{code:t}=e||{};return this._basePost({action:"attempt_verification",body:{code:t}})};createEmailLinkFlow=()=>{let{run:e,stop:t}=aW();return{startEmailLinkFlow:async({redirectUrl:a})=>(await this.prepareVerification({strategy:"email_link",redirectUrl:a}),new Promise((a,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),a(e))}).catch(e=>{t(),r(e)}))})),cancelEmailLinkFlow:t}};createEnterpriseSSOLinkFlow=()=>{let{run:e,stop:t}=aW();return{startEnterpriseSSOLinkFlow:async({redirectUrl:a})=>{if(!(await this.prepareVerification({strategy:"enterprise_sso",redirectUrl:a})).verification.externalVerificationRedirectURL)throw Error("Unexpected: External verification redirect URL is missing");return new Promise((a,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),a(e))}).catch(e=>{t(),r(e)}))})},cancelEnterpriseSSOLinkFlow:t}};destroy=()=>this._baseDelete();toString=()=>this.emailAddress;fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.verification=new a0(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new ro(e))),this}__internal_toSnapshot(){return{object:"email_address",id:this.id,email_address:this.emailAddress,verification:this.verification.__internal_toSnapshot(),linked_to:this.linkedTo.map(e=>e.__internal_toSnapshot()),matches_sso_connection:this.matchesSsoConnection}}}var aH=class{static encode(e){return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}static decode(e){let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),a=t.length,r=new Uint8Array(a);for(let e=0;e<a;e++)r[e]=t.charCodeAt(e);return r.buffer}};async function aV(e){try{let t=await navigator.credentials.create({publicKey:e});if(!t)return{error:new C("Browser failed to create credential",{code:"passkey_registration_failed"}),publicKeyCredential:null};return{publicKeyCredential:t,error:null}}catch(e){var t;return{error:"InvalidStateError"===(t=e).name?new C(t.message,{code:"passkey_already_exists"}):"NotAllowedError"===t.name?new C(t.message,{code:"passkey_registration_cancelled"}):aZ(t),publicKeyCredential:null}}}let aG=new class{controller;__abort(){if(!this.controller)return;let e=Error();e.name="AbortError",this.controller.abort(e)}createAbortSignal(){this.__abort();let e=new AbortController;return this.controller=e,e.signal}abort(){this.__abort(),this.controller=void 0}};async function aJ({publicKeyOptions:e,conditionalUI:t}){try{let a=await navigator.credentials.get({publicKey:e,mediation:t?"conditional":"optional",signal:aG.createAbortSignal()});if(!a)return{error:new C("Browser failed to get credential",{code:"passkey_retrieval_failed"}),publicKeyCredential:null};return{publicKeyCredential:a,error:null}}catch(e){var a;return{error:"NotAllowedError"===(a=e).name?new C(a.message,{code:"passkey_retrieval_cancelled"}):aZ(a),publicKeyCredential:null}}}function aZ(e){return"AbortError"===e.name?new C(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new C(e.message,{code:"passkey_invalid_rpID_or_domain"}):e}function a$(e){let t=a1(e.challenge),a=(e.allowCredentials||[]).map(e=>({...e,id:a1(e.id)}));return{...e,allowCredentials:a,challenge:t}}function aY(e){return{type:e.type,id:e.id,rawId:aX(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function aQ(e){let t=e.response;return{...aY(e),response:{clientDataJSON:aX(t.clientDataJSON),authenticatorData:aX(t.authenticatorData),signature:aX(t.signature),userHandle:t.userHandle?aX(t.userHandle):null}}}let aX=aH.encode.bind(aH),a1=aH.decode.bind(aH);class a0 extends tL{pathRoot="";status=null;strategy=null;nonce=null;message=null;externalVerificationRedirectURL=null;attempts=null;expireAt=null;error=null;verifiedAtClient=null;channel;constructor(e){super(),this.fromJSON(e)}verifiedFromTheSameClient=()=>this.verifiedAtClient===tL.clerk?.client?.id;fromJSON(e){return e&&(this.status=e.status,this.verifiedAtClient=e.verified_at_client,this.strategy=e.strategy,this.nonce=e.nonce||null,this.message=e.message||null,e.external_verification_redirect_url?this.externalVerificationRedirectURL=new URL(e.external_verification_redirect_url):this.externalVerificationRedirectURL=null,this.attempts=e.attempts,this.expireAt=tW(e.expire_at||void 0),this.error=e.error?new w(e.error):null,this.channel=e.channel||void 0),this}__internal_toSnapshot(){var e;return{object:"verification",id:this.id||"",status:this.status,strategy:this.strategy,nonce:this.nonce,message:this.message,external_verification_redirect_url:this.externalVerificationRedirectURL?.toString()||null,attempts:this.attempts,expire_at:this.expireAt?.getTime()||null,error:(e=this.error,{code:e?.code||"",message:e?.message||"",long_message:e?.longMessage,meta:{param_name:e?.meta?.paramName,session_id:e?.meta?.sessionId,email_addresses:e?.meta?.emailAddresses,identifiers:e?.meta?.identifiers,zxcvbn:e?.meta?.zxcvbn,plan:e?.meta?.plan,is_plan_upgrade_possible:e?.meta?.isPlanUpgradePossible}}),verified_at_client:this.verifiedAtClient}}}class a2 extends a0{publicKey=null;constructor(e){super(e),this.fromJSON(e)}fromJSON(e){var t;let a,r,n;return super.fromJSON(e),e?.nonce&&(this.publicKey=(a=a1((t=JSON.parse(e.nonce)).user.id),r=a1(t.challenge),n=(t.excludeCredentials||[]).map(e=>({...e,id:a1(e.id)})),{...t,excludeCredentials:n,challenge:r,user:{...t.user,id:a}})),this}}class a9{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new a3(e.email_address),this.phoneNumber=new a3(e.phone_number),this.web3Wallet=new a3(e.web3_wallet),this.externalAccount=new a0(e.external_account)):(this.emailAddress=new a3(null),this.phoneNumber=new a3(null),this.web3Wallet=new a3(null),this.externalAccount=new a0(null))}__internal_toSnapshot(){return{email_address:this.emailAddress.__internal_toSnapshot(),phone_number:this.phoneNumber.__internal_toSnapshot(),web3_wallet:this.web3Wallet.__internal_toSnapshot(),external_account:this.externalAccount.__internal_toSnapshot()}}}class a3 extends a0{nextAction;supportedStrategies;constructor(e){super(e),e?(this.nextAction=e.next_action,this.supportedStrategies=e.supported_strategies):(this.nextAction="",this.supportedStrategies=[])}__internal_toSnapshot(){return{...super.__internal_toSnapshot(),next_action:this.nextAction,supported_strategies:this.supportedStrategies}}}class a5 extends tL{id;protocol;provider;providerUserId=null;active;emailAddress="";firstName="";lastName="";publicMetadata={};verification=null;enterpriseConnection=null;lastAuthenticatedAt=null;enterpriseConnectionId=null;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.provider=e.provider,this.protocol=e.protocol,this.providerUserId=e.provider_user_id,this.active=e.active,this.emailAddress=e.email_address,this.firstName=e.first_name,this.lastName=e.last_name,this.publicMetadata=e.public_metadata,this.lastAuthenticatedAt=e.last_authenticated_at?tW(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new a0(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new a6(e.enterprise_connection))),this}__internal_toSnapshot(){return{object:"enterprise_account",id:this.id,provider:this.provider,protocol:this.protocol,provider_user_id:this.providerUserId,active:this.active,email_address:this.emailAddress,first_name:this.firstName,last_name:this.lastName,public_metadata:this.publicMetadata,verification:this.verification?.__internal_toSnapshot()||null,enterprise_connection:this.enterpriseConnection?.__internal_toSnapshot()||null,last_authenticated_at:this.lastAuthenticatedAt?this.lastAuthenticatedAt.getTime():null,enterprise_connection_id:this.enterpriseConnectionId}}}class a6 extends tL{id;active;allowIdpInitiated;allowSubdomains;disableAdditionalIdentifications;domain;logoPublicUrl="";name;protocol;provider;syncUserAttributes;createdAt;updatedAt;enterpriseConnectionId="";constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.domain=e.domain,this.active=e.active,this.provider=e.provider,this.logoPublicUrl=e.logo_public_url,this.syncUserAttributes=e.sync_user_attributes,this.allowSubdomains=e.allow_subdomains,this.allowIdpInitiated=e.allow_idp_initiated,this.disableAdditionalIdentifications=e.disable_additional_identifications,this.createdAt=tW(e.created_at),this.updatedAt=tW(e.updated_at),this.enterpriseConnectionId=e.enterprise_connection_id),this}__internal_toSnapshot(){return{object:"enterprise_account_connection",id:this.id,name:this.name,domain:this.domain,active:this.active,protocol:this.protocol,provider:this.provider,logo_public_url:this.logoPublicUrl,sync_user_attributes:this.syncUserAttributes,allow_subdomains:this.allowSubdomains,allow_idp_initiated:this.allowIdpInitiated,disable_additional_identifications:this.disableAdditionalIdentifications,enterprise_connection_id:this.enterpriseConnectionId,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}let a8="token:update",a4="user:signOut",a7="environment:update",re="session:tokenResolved",rt=p();class ra extends tL{user_api_keys_enabled=!1;orgs_api_keys_enabled=!1;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.user_api_keys_enabled=e.user_api_keys_enabled,this.orgs_api_keys_enabled=e.orgs_api_keys_enabled),this}__internal_toSnapshot(){return{user_api_keys_enabled:this.user_api_keys_enabled,orgs_api_keys_enabled:this.orgs_api_keys_enabled}}}class rr extends tL{actions={adminDelete:!1};domains={enabled:!1,enrollmentModes:[],defaultRole:null};slug={disabled:!1};enabled=!1;maxAllowedMemberships=1;forceOrganizationSelection;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(e.actions&&(this.actions.adminDelete=this.withDefault(e.actions.admin_delete,this.actions.adminDelete)),e.domains&&(this.domains.enabled=this.withDefault(e.domains.enabled,this.domains.enabled),this.domains.enrollmentModes=this.withDefault(e.domains.enrollment_modes,this.domains.enrollmentModes),this.domains.defaultRole=this.withDefault(e.domains.default_role,this.domains.defaultRole)),e.slug&&(this.slug.disabled=this.withDefault(e.slug.disabled,this.slug.disabled)),this.enabled=this.withDefault(e.enabled,this.enabled),this.maxAllowedMemberships=this.withDefault(e.max_allowed_memberships,this.maxAllowedMemberships),this.forceOrganizationSelection=this.withDefault(e.force_organization_selection,this.forceOrganizationSelection)),this}__internal_toSnapshot(){return{actions:{admin_delete:this.actions.adminDelete},domains:{enabled:this.domains.enabled,enrollment_modes:this.domains.enrollmentModes,default_role:this.domains.defaultRole},enabled:this.enabled,max_allowed_memberships:this.maxAllowedMemberships}}}class rn extends tL{static instance;authConfig=new tH;displayConfig=new aN;maintenanceMode=!1;clientDebugMode=!1;pathRoot="/environment";userSettings=new rQ;organizationSettings=new rr;commerceSettings=new aR;apiKeysSettings=new ra;protectConfig=new rx;static getInstance(){return rn.instance||(rn.instance=new rn),rn.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new tH(e.auth_config),this.displayConfig=new aN(e.display_config),this.maintenanceMode=this.withDefault(e.maintenance_mode,this.maintenanceMode),this.clientDebugMode=this.withDefault(e.client_debug_mode,this.clientDebugMode),this.organizationSettings=new rr(e.organization_settings),this.userSettings=new rQ(e.user_settings),this.commerceSettings=new aR(e.commerce_settings),this.apiKeysSettings=new ra(e.api_keys_settings),this.protectConfig=new rx(e.protect_config)),this}fetch({touch:e,fetchMaxTries:t}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:t})).then(e=>(rt.emit(a7,null),e))}isDevelopmentOrStaging=()=>!this.isProduction();isProduction=()=>"production"===this.displayConfig.instanceEnvironmentType;isSingleSession=()=>this.authConfig.singleSessionMode;onWindowLocationHost=()=>this.displayConfig.backendHost===window.location.host;__internal_toSnapshot(){return{object:"environment",auth_config:this.authConfig.__internal_toSnapshot(),display_config:this.displayConfig.__internal_toSnapshot(),id:this.id??"",maintenance_mode:this.maintenanceMode,client_debug_mode:this.clientDebugMode,organization_settings:this.organizationSettings.__internal_toSnapshot(),user_settings:this.userSettings.__internal_toSnapshot(),commerce_settings:this.commerceSettings.__internal_toSnapshot(),api_keys_settings:this.apiKeysSettings.__internal_toSnapshot(),protect_config:this.protectConfig.__internal_toSnapshot()}}async __internal_enableEnvironmentSetting(e){await this._basePatch({path:"/dev_tools/enable_environment_setting",body:e})}}class ri extends tL{id;identificationId;provider;providerUserId="";emailAddress="";approvedScopes="";firstName="";lastName="";imageUrl="";username="";phoneNumber="";publicMetadata={};label="";verification=null;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}reauthorize=e=>{let{additionalScopes:t,redirectUrl:a}=e||{};return this._basePatch({action:"reauthorize",body:{additional_scope:t,redirect_url:a}})};destroy=()=>this._baseDelete();fromJSON(e){return e&&(this.id=e.id,this.identificationId=e.identification_id,this.providerUserId=e.provider_user_id,this.approvedScopes=e.approved_scopes,this.imageUrl=e.image_url,this.emailAddress=e.email_address,this.firstName=e.first_name,this.lastName=e.last_name,this.provider=(e.provider||"").replace("oauth_",""),this.username=e.username,this.phoneNumber=e.phone_number,this.publicMetadata=e.public_metadata,this.label=e.label,e.verification&&(this.verification=new a0(e.verification))),this}__internal_toSnapshot(){return{object:"external_account",id:this.id,identification_id:this.identificationId,provider:this.provider,provider_user_id:this.providerUserId,email_address:this.emailAddress,approved_scopes:this.approvedScopes,first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl,username:this.username,phone_number:this.phoneNumber,public_metadata:this.publicMetadata,label:this.label,verification:this.verification?.__internal_toSnapshot()||null}}providerSlug(){return this.provider}providerTitle(){let e;return[(e=this.providerSlug()||"").charAt(0).toUpperCase()+e.slice(1),"Account"].join(" ")}accountIdentifier(){return this.username||this.emailAddress||this.label}}class rs extends tL{id;name;description=null;slug;avatarUrl=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.description=e.description,this.slug=e.slug,this.avatarUrl=e.avatar_url),this}}class ro extends tL{id;type;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.type=e.type),this}__internal_toSnapshot(){return{object:"identification_link",id:this.id,type:this.type}}}class rl extends tL{id;name=null;publicUrl=null;static async create(e,t={}){let a,r=t;return"string"==typeof t.file?(r=t.file,a=new Headers({"Content-Type":"application/octet-stream"})):t.file&&(r=new FormData).append("file",t.file),new rl((await tL._fetch({path:e,method:"POST",body:r,headers:a}))?.response)}static async delete(e){return new rl((await tL._fetch({path:e,method:"DELETE"}))?.response)}constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.publicUrl=e.public_url),this}}class rc extends tL{id;name;organizationId;enrollmentMode;verification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:t}){return new rc((await tL._fetch({path:`/organizations/${e}/domains`,method:"POST",body:{name:t}}))?.response)}prepareAffiliationVerification=async e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/prepare_affiliation_verification`,method:"POST",body:e});attemptAffiliationVerification=async e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/attempt_affiliation_verification`,method:"POST",body:e});updateEnrollmentMode=e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/update_enrollment_mode`,body:e});delete=()=>this._baseDelete({path:`/organizations/${this.organizationId}/domains/${this.id}`});fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.organizationId=e.organization_id,this.enrollmentMode=e.enrollment_mode,this.affiliationEmailAddress=e.affiliation_email_address,this.totalPendingSuggestions=e.total_pending_suggestions,this.totalPendingInvitations=e.total_pending_invitations,e.verification?this.verification={status:e.verification.status,strategy:e.verification.strategy,attempts:e.verification.attempts,expiresAt:tW(e.verification.expires_at)}:this.verification=null),this}}class ru extends tL{id;organizationId;status;publicUserData;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}accept=async()=>await this._basePost({path:`/organizations/${this.organizationId}/membership_requests/${this.id}/accept`});reject=async()=>await this._basePost({path:`/organizations/${this.organizationId}/membership_requests/${this.id}/reject`});fromJSON(e){return e&&(this.id=e.id,this.organizationId=e.organization_id,this.status=e.status,this.createdAt=tW(e.created_at),this.updatedAt=tW(e.updated_at),e.public_user_data&&(this.publicUserData=new rj(e.public_user_data))),this}}class rd extends tL{id;key;name;description;type;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.key=e.key,this.name=e.name,this.description=e.description,this.type=e.type,this.createdAt=tW(e.created_at),this.updatedAt=tW(e.updated_at)),this}}class rh extends tL{id;key;name;description;permissions=[];createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.key=e.key,this.name=e.name,this.description=e.description,this.permissions=e.permissions.map(e=>new rd(e)),this.createdAt=tW(e.created_at),this.updatedAt=tW(e.updated_at)),this}}class rm extends tL{pathRoot="/organizations";id;name;slug;imageUrl;hasImage;publicMetadata={};adminDeleteEnabled;createdAt;updatedAt;membersCount=0;pendingInvitationsCount=0;maxAllowedMemberships;constructor(e){super(),this.fromJSON(e)}static async create(e){return new rm((await tL._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new rm((await tL._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await tL._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:ar(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rh(e))}});getDomains=async e=>await tL._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:ar(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rc(e))}});getDomain=async({domainId:e})=>new rc((await tL._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getMembershipRequests=async e=>await tL._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:ar(e)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new ru(e))}});createDomain=async e=>rc.create(this.id,{name:e});getMemberships=async e=>await tL._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:ar({...e,paginated:!0})}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rf(e))}});getInvitations=async e=>await tL._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:ar(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rp(e))}});addMember=async({userId:e,role:t})=>await tL._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:t}}).then(e=>new rf(e?.response));inviteMember=async e=>rp.create(this.id,e);inviteMembers=async e=>rp.createBulk(this.id,e);updateMember=async({userId:e,role:t})=>await tL._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:t}}).then(e=>new rf(e?.response));removeMember=async e=>await tL._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new rf(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let t,a;return null===e?await tL._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new rm(e?.response)):("string"==typeof e?(t=e,a=new Headers({"Content-Type":"application/octet-stream"})):(t=new FormData).append("file",e),await tL._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:t,headers:a}).then(e=>new rm(e?.response)))};initializePaymentMethod=e=>aw({...e,orgId:this.id});addPaymentMethod=e=>ak({...e,orgId:this.id});getPaymentMethods=e=>av({...e,orgId:this.id});fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.slug=e.slug,this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.publicMetadata=e.public_metadata||{},this.membersCount=e.members_count||0,this.pendingInvitationsCount=e.pending_invitations_count||0,this.maxAllowedMemberships=e.max_allowed_memberships||0,this.adminDeleteEnabled=e.admin_delete_enabled||!1,this.createdAt=tW(e.created_at),this.updatedAt=tW(e.updated_at)),this}__internal_toSnapshot(){return{object:"organization",id:this.id,name:this.name,slug:this.slug,image_url:this.imageUrl,has_image:this.hasImage,public_metadata:this.publicMetadata,members_count:this.membersCount,pending_invitations_count:this.pendingInvitationsCount,max_allowed_memberships:this.maxAllowedMemberships,admin_delete_enabled:this.adminDeleteEnabled,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async reload(e){let{rotatingTokenNonce:t}=e||{},a=(await tL._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:t},{forceUpdateClient:!0}))?.response;return this.fromJSON(a)}}class rp extends tL{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:t,role:a}){return new rp((await tL._fetch({path:`/organizations/${e}/invitations`,method:"POST",body:{email_address:t,role:a}}))?.response)}static async createBulk(e,t){let{emailAddresses:a,role:r}=t;return((await tL._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:a,role:r}}))?.response).map(e=>new rp(e))}constructor(e){super(),this.fromJSON(e)}revoke=async()=>await this._basePost({path:`/organizations/${this.organizationId}/invitations/${this.id}/revoke`});fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.organizationId=e.organization_id,this.publicMetadata=e.public_metadata,this.role=e.role,this.roleName=e.role_name,this.status=e.status,this.createdAt=tW(e.created_at),this.updatedAt=tW(e.updated_at)),this}}class rf extends tL{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await tL._fetch({path:"/me/organization_memberships",method:"GET",search:ar({...e,paginated:!0})}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rf(e))}});destroy=async()=>await this._baseDelete({path:`/organizations/${this.organization.id}/memberships/${this.publicUserData?.userId}`});update=async({role:e})=>await this._basePatch({path:`/organizations/${this.organization.id}/memberships/${this.publicUserData?.userId}`,body:{role:e}});fromJSON(e){return e&&(this.id=e.id,this.organization=new rm(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new rj(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=tW(e.created_at),this.updatedAt=tW(e.updated_at)),this}__internal_toSnapshot(){return{object:"organization_membership",id:this.id,organization:this.organization.__internal_toSnapshot(),public_metadata:this.publicMetadata,public_user_data:this.publicUserData?.__internal_toSnapshot(),permissions:this.permissions,role:this.role,role_name:this.roleName,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}reload(e){throw Error(`${tz} Calling OrganizationMembership.reload is not currently supported. Please contact support.`)}}class rg extends tL{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await tL._fetch({path:"/me/organization_suggestions",method:"GET",search:ar(e)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rg(e))}})}accept=async()=>await this._basePost({path:`/me/organization_suggestions/${this.id}/accept`});fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.publicOrganizationData={hasImage:e.public_organization_data.has_image,imageUrl:e.public_organization_data.image_url,name:e.public_organization_data.name,id:e.public_organization_data.id,slug:e.public_organization_data.slug},this.createdAt=tW(e.created_at),this.updatedAt=tW(e.updated_at)),this}}function rb(){return l()&&"function"==typeof window.PublicKeyCredential}async function ry(){try{return rb()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function rw(){try{return"undefined"!=typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class rk extends tL{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return tL._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new rk(e?.response))}static async attemptVerification(e,t){let a,r=(a=t.response,{...aY(t),response:{clientDataJSON:aX(a.clientDataJSON),attestationObject:aX(a.attestationObject),transports:a.getTransports()}});return tL._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new rk(e?.response))}static async registerPasskey(){let e=rk.clerk.__internal_isWebAuthnSupported||rb,t=rk.clerk.__internal_createPublicCredentials||aV,a=rk.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||rw;if(!e())throw new C("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let r=await this.create(),{verification:n}=r,i=n?.publicKey;if(i||tO("create"),i.authenticatorSelection?.authenticatorAttachment==="platform"&&!await a())throw new C("Registration requires a platform authenticator but the device does not support it.",{code:"passkey_pa_not_supported"});let{publicKeyCredential:s,error:o}=await t(i);if(!s)throw o;return this.attemptVerification(r.id,s)}update=e=>this._basePatch({body:e});delete=async()=>new aB((await tL._fetch({path:this.path(),method:"DELETE"}))?.response);fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.lastUsedAt=e.last_used_at?tW(e.last_used_at):null,this.createdAt=tW(e.created_at),this.updatedAt=tW(e.updated_at),e.verification&&(this.verification=new a2(e.verification))),this}__internal_toSnapshot(){return{object:"passkey",id:this.id,name:this.name,verification:this.verification?.__internal_toSnapshot()||null,last_used_at:this.lastUsedAt?.getTime()||null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class rv extends tL{id;phoneNumber="";reservedForSecondFactor=!1;defaultSecondFactor=!1;linkedTo=[];verification;backupCodes;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}create=()=>this._basePost({body:{phone_number:this.phoneNumber}});prepareVerification=()=>this._basePost({action:"prepare_verification",body:{strategy:"phone_code"}});attemptVerification=e=>{let{code:t}=e||{};return this._basePost({action:"attempt_verification",body:{code:t}})};setReservedForSecondFactor=e=>{let{reserved:t}=e||{};return this._basePatch({body:{reserved_for_second_factor:t}})};makeDefaultSecondFactor=()=>this._basePatch({body:{default_second_factor:!0}});destroy=()=>this._baseDelete();toString=()=>{let e=this.phoneNumber.match(/^(\d{3})(\d{3})(\d{4})$/);return e?"("+e[1]+") "+e[2]+"-"+e[3]:this.phoneNumber};fromJSON(e){return e&&(this.id=e.id,this.phoneNumber=e.phone_number,this.reservedForSecondFactor=e.reserved_for_second_factor,this.defaultSecondFactor=e.default_second_factor,this.verification=new a0(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new ro(e)),this.backupCodes=e.backup_codes),this}__internal_toSnapshot(){return{object:"phone_number",id:this.id||"",phone_number:this.phoneNumber,reserved_for_second_factor:this.reservedForSecondFactor,default_second_factor:this.defaultSecondFactor,verification:this.verification.__internal_toSnapshot(),linked_to:this.linkedTo.map(e=>e.__internal_toSnapshot()),backup_codes:this.backupCodes}}}class rx extends tL{id="";loaders;rollout;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=this.withDefault(e.id,this.id),this.loaders=this.withDefault(e.loaders,this.loaders)),this}__internal_toSnapshot(){return{object:"protect_config",id:this.id,loaders:this.loaders}}}class rj{firstName;lastName;imageUrl;hasImage;identifier;userId;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.firstName=e.first_name||null,this.lastName=e.last_name||null,this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.identifier=e.identifier||"",this.userId=e.user_id),this}__internal_toSnapshot(){return{first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl,has_image:this.hasImage,identifier:this.identifier,user_id:this.userId}}}let r_={strict_mfa:{afterMinutes:10,level:"multi_factor"},strict:{afterMinutes:10,level:"second_factor"},moderate:{afterMinutes:60,level:"second_factor"},lax:{afterMinutes:1440,level:"second_factor"}},rz=new Set(["first_factor","second_factor","multi_factor"]),rS=new Set(["strict_mfa","strict","moderate","lax"]),rA=(e,t)=>{let{org:a,user:r}=rE(e),[n,i]=t.split(":"),s=i||n;return"org"===n?a.includes(s):"user"===n?r.includes(s):[...a,...r].includes(s)},rE=e=>{let t=e?e.split(",").map(e=>e.trim()):[];return{org:t.filter(e=>e.split(":")[0].includes("o")).map(e=>e.split(":")[1]),user:t.filter(e=>e.split(":")[0].includes("u")).map(e=>e.split(":")[1])}};class rI extends tL{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new a0(null);secondFactorVerification=new a0(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new rC(e.session),this.level=e.level,this.supportedFirstFactors=en(e.supported_first_factors),this.supportedSecondFactors=en(e.supported_second_factors),this.firstFactorVerification=new a0(e.first_factor_verification),this.secondFactorVerification=new a0(e.second_factor_verification)),this}}class rC extends tL{pathRoot="/client/sessions";id;status;lastActiveAt;lastActiveToken;lastActiveOrganizationId;actor;user;publicUserData;factorVerificationAge=null;tasks=null;expireAt;abandonAt;createdAt;updatedAt;static isSessionResource(e){return!!e&&e instanceof rC}constructor(e){super(),this.fromJSON(e),this.#es(this.lastActiveToken)}end=()=>(aU.clear(),this._basePost({action:"end"}));remove=()=>(aU.clear(),this._basePost({action:"remove"}));touch=()=>this._basePost({action:"touch",body:{active_organization_id:this.lastActiveOrganizationId}}).then(e=>(e.lastActiveToken&&rt.emit(a8,{token:e.lastActiveToken}),e));clearCache=()=>aU.clear();getToken=async e=>ts(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,t)=>!q(e)&&t<=8});checkAuthorization=e=>{let t,a=(this.user?.organizationMemberships||[]).find(e=>e.organization.id===this.lastActiveOrganizationId);return(t={userId:this.user?.id,factorVerificationAge:this.factorVerificationAge,orgId:a?.id,orgRole:a?.role,orgPermissions:a?.permissions,features:this.lastActiveToken?.jwt?.claims.fea||"",plans:this.lastActiveToken?.jwt?.claims.pla||""},e=>{if(!t.userId)return!1;let a=((e,t)=>{let{features:a,plans:r}=t;return e.feature&&a?rA(a,e.feature):e.plan&&r?rA(r,e.plan):null})(e,t),r=((e,t)=>{let{orgId:a,orgRole:r,orgPermissions:n}=t;return(e.role||e.permission)&&a&&r&&n?e.permission?n.includes(e.permission.replace(/^(org:)*/,"org:")):e.role?r.replace(/^(org:)*/,"org:")===e.role.replace(/^(org:)*/,"org:"):null:null})(e,t),n=((e,{factorVerificationAge:t})=>{if(!e.reverification||!t)return null;let a=(e=>{let t,a;if(!e)return!1;let r="string"==typeof e&&rS.has(e),n="object"==typeof e&&(t=e.level,rz.has(t))&&"number"==typeof(a=e.afterMinutes)&&a>0;return(!!r||!!n)&&(e=>"string"==typeof e?r_[e]:e).bind(null,e)})(e.reverification);if(!a)return null;let{level:r,afterMinutes:n}=a(),[i,s]=t,o=-1!==i?n>i:null,l=-1!==s?n>s:null;switch(r){case"first_factor":return o;case"second_factor":return -1!==s?l:o;case"multi_factor":return -1===s?o:o&&l}})(e,t);return[a||r,n].some(e=>null===e)?[a||r,n].some(e=>!0===e):[a||r,n].every(e=>!0===e)})(e)};#es=e=>{e&&aU.set({tokenId:this.#eo(),tokenResolver:Promise.resolve(e)})};#eo(e,t){let a=void 0===t?this.lastActiveOrganizationId:t;return aI.build(this.id,e,a)}startVerification=async({level:e})=>new rI((await tL._fetch({method:"POST",path:`/client/sessions/${this.id}/verify`,body:{level:e}}))?.response);prepareFirstFactorVerification=async e=>{let t;switch(e.strategy){case"email_code":t={emailAddressId:e.emailAddressId};break;case"phone_code":t={phoneNumberId:e.phoneNumberId,default:e.default};break;case"passkey":t={};break;case"enterprise_sso":t={emailAddressId:e.emailAddressId,enterpriseConnectionId:e.enterpriseConnectionId,redirectUrl:e.redirectUrl};break;default:tI("Session.prepareFirstFactorVerification",e.strategy)}return new rI((await tL._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_first_factor`,body:{...t,strategy:e.strategy}}))?.response)};attemptFirstFactorVerification=async e=>{let t;return t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(aQ(e.publicKeyCredential))}:{...e},new rI((await tL._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_first_factor`,body:{...t,strategy:e.strategy}}))?.response)};verifyWithPasskey=async()=>{let{nonce:e=null}=(await this.prepareFirstFactorVerification({strategy:"passkey"})).firstFactorVerification,t=rC.clerk.__internal_isWebAuthnSupported||rb,a=rC.clerk.__internal_getPublicCredentials||aJ;if(!t())throw new C("Passkeys are not supported",{code:"passkey_not_supported"});let r=e?a$(JSON.parse(e)):null;r||tO("get");let{publicKeyCredential:n,error:i}=await a({publicKeyOptions:r,conditionalUI:!1});if(!n)throw i;return this.attemptFirstFactorVerification({strategy:"passkey",publicKeyCredential:n})};prepareSecondFactorVerification=async e=>new rI((await tL._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new rI((await tL._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_second_factor`,body:e}))?.response);fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.expireAt=tW(e.expire_at),this.abandonAt=tW(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=tW(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.createdAt=tW(e.created_at),this.updatedAt=tW(e.updated_at),this.user=new rJ(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new rj(e.public_user_data)),this.lastActiveToken=e.last_active_token?new rH(e.last_active_token):null),this}__internal_toSnapshot(){return{object:"session",id:this.id,status:this.status,expire_at:this.expireAt.getTime(),abandon_at:this.abandonAt.getTime(),factor_verification_age:this.factorVerificationAge,last_active_at:this.lastActiveAt.getTime(),last_active_organization_id:this.lastActiveOrganizationId,actor:this.actor,tasks:this.tasks,user:this.user?.__internal_toSnapshot()||null,public_user_data:this.publicUserData.__internal_toSnapshot(),last_active_token:this.lastActiveToken?.__internal_toSnapshot()||null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async _getToken(e){if(!this.user)return null;let{leewayInSeconds:t,template:a,skipCache:r=!1}=e||{},n=void 0===e?.organizationId?this.lastActiveOrganizationId:e?.organizationId;if(!a&&Number(t)>=60)throw Error("Leeway can not exceed the token lifespan (60 seconds)");let i=this.#eo(a,n),s=r?void 0:aU.get({tokenId:i},t),o=!a&&n===this.lastActiveOrganizationId;if(s){ta.debug("Using cached token (no fetch needed)",{tokenId:i},"session");let e=await s.tokenResolver;return o&&rt.emit(a8,{token:e}),e.getRawString()||null}ta.info("Fetching new token from API",{organizationId:n,template:a,tokenId:i},"session");let l=a?`${this.path()}/tokens/${a}`:`${this.path()}/tokens`,c=a?{}:{organizationId:n},u=this.lastActiveToken?.getRawString()??rC.clerk.__internal_getSessionCookie?.(),d=rH.create(l,c,r?{debug:"skip_cache"}:void 0).catch(e=>{if(j.is(e)&&u)return rH.create(l,{...c},{expired_token:u});throw e});return aU.set({tokenId:i,tokenResolver:d}),d.then(e=>(o&&(rt.emit(a8,{token:e}),e.jwt&&(this.lastActiveToken=e,rt.emit(re,null))),e.getRawString()||null))}get currentTask(){let[e]=this.tasks??[];return e}}class rP extends tL{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}static retrieve(){let e=tL.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new rP(e,"/me/sessions"))).catch(()=>[])}revoke(){return this._basePost({action:"revoke",body:{}})}fromJSON(e){let t;return e?(this.id=e.id,this.status=e.status,this.expireAt=tW(e.expire_at),this.abandonAt=tW(e.abandon_at),this.lastActiveAt=tW(e.last_active_at||void 0),this.latestActivity={id:(t=e.latest_activity??{}).id,deviceType:t.device_type,browserName:t.browser_name,browserVersion:t.browser_version,country:t.country,city:t.city,isMobile:t.is_mobile,ipAddress:t.ip_address},this.actor=e.actor,this):this}}let rq=(e,t,a)=>{let{onValidation:r=e5,onValidationComplexity:n=e5}=a||{},{show_zxcvbn:i,validatePassword:s}=t,o=e=>((e,t)=>{let{max_length:a,min_length:r,require_special_char:n,require_lowercase:i,require_numbers:s,require_uppercase:o}=t,l=(e=>{let t;if(e.allowed_special_characters){let a=e.allowed_special_characters.replace("[","\\[");a=a.replace("]","\\]"),t=RegExp(`[${a}]`)}else t=/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/;return(e,{minLength:a,maxLength:r})=>({max_length:e.length<r,min_length:e.length>=a,require_numbers:/\d/.test(e),require_lowercase:/[a-z]/.test(e),require_uppercase:/[A-Z]/.test(e),require_special_char:t.test(e)})})(t)(e,{maxLength:t.max_length,minLength:t.min_length}),c={max_length:a,min_length:r,require_special_char:n,require_lowercase:i,require_numbers:s,require_uppercase:o},u=new Map;for(let e in c)c[e]&&!l[e]&&u.set(e,!0);return Object.freeze(Object.fromEntries(u))})(e,t),l=(({min_zxcvbn_strength:e,onResult:t})=>a=>r=>{let n=a(r);return(t?.(n),n.score>=e&&n.score<3)?{state:"pass",keys:["unstable__errors.zxcvbn.couldBeStronger"],result:n}:n.score>=e?{state:"excellent",result:n}:{state:"fail",keys:["unstable__errors.zxcvbn.notEnough",...n.feedback.suggestions.map(e=>`unstable__errors.zxcvbn.suggestions.${e}`)],result:n}})(t),c={};return(t,a)=>{let{onValidation:u=r,onValidationComplexity:d=n}=a||{};if(!s)return;let h=o(t);d(0===Object.keys(h).length),c={...c,complexity:h},i&&e().then(e=>{let a=l(e)(t);u({...c={...c,strength:a},strength:a})}),c.complexity&&0===Object.keys(c.complexity).length&&i||u(c)}};function rO(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function rT(e,t,a,r,n){if(!e.client||!r.popup)return;let i=rO(e.frontendApi),{redirectUrl:s}=r,o=new URL(s);o.searchParams.set("sign_in_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("sign_up_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("intent",t);let l=e.buildUrlWithAuth(o.toString()),c=e.buildUrlWithAuth(`${i}/popup-callback`),u=e.buildUrlWithAuth(`${i}/popup-callback?return_url=${encodeURIComponent(l)}`),d=async t=>{if(t.origin!==i)return;let a=!1;if(t.data.session){if(!e.client?.sessions.find(e=>e.id===t.data.session))try{await e.client?.reload()}catch(e){console.error(e)}await e.setActive({session:t.data.session,redirectUrl:r.redirectUrlComplete}),a=!0}else t.data.return_url&&(e.navigate(t.data.return_url),a=!0);a&&window.removeEventListener("message",d)};window.addEventListener("message",d),await a({...r,redirectUrlComplete:c,redirectUrl:u},n)}function rU(e,{redirectCallbackUrl:t,redirectUrl:a}){let r=rO(e.frontendApi),n=new URL(t);n.searchParams.set("sign_in_force_redirect_url",a),n.searchParams.set("sign_up_force_redirect_url",a);let i=e.buildUrlWithAuth(n.toString()),s=e.buildUrlWithAuth(`${r}/popup-callback`);return{redirectCallbackUrl:e.buildUrlWithAuth(`${r}/popup-callback?return_url=${encodeURIComponent(i)}`),redirectUrl:s}}function rM(e,t){return new Promise((a,r)=>{if(!e.client||!t.popup)return void r();let n=async t=>{t.origin===rO(e.frontendApi)&&(t.data.session||t.data.return_url?(window.removeEventListener("message",n),a()):r())};window.addEventListener("message",n),t.popup.location.href=t.externalVerificationRedirectURL.toString()})}async function rR(e,t){rt.emit("resource:error",{resource:e,error:null}),rt.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await t(),error:null}}catch(t){return rt.emit("resource:error",{resource:e,error:t}),{error:t}}finally{rt.emit("resource:fetch",{resource:e,status:"idle"})}}let rB=()=>{var e;return(e=new tl,{loadZxcvbn:()=>Promise.all([e.import("@zxcvbn-ts/core"),e.import("@zxcvbn-ts/language-common")]).then(([e,t])=>{if(!e||!t)throw Error("Failed to load zxcvbn modules");let{zxcvbnOptions:a,zxcvbn:r}=e,{dictionary:n,adjacencyGraphs:i}=t;return a.setOptions({dictionary:{...n},graphs:i}),r})}).loadZxcvbn};class rN extends tL{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new a0(null);secondFactorVerification=new a0(null);identifier=null;createdSessionId=null;userData=new rZ(null);clientTrustState;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&ta.debug("SignIn.status",{id:this.id,from:t,to:e})}__internal_future=new rD(this);__internal_basePost=this._basePost.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=e=>{ta.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let t=tg();return this._basePost({path:this.pathRoot,body:t?{locale:t,...e}:e})};resetPassword=e=>this._basePost({body:e,action:"reset_password"});prepareFirstFactor=e=>{let t;switch(ta.debug("SignIn.prepareFirstFactor",{id:this.id,strategy:e.strategy}),e.strategy){case"passkey":t={};break;case"email_link":t={emailAddressId:e.emailAddressId,redirectUrl:e.redirectUrl};break;case"email_code":case"reset_password_email_code":t={emailAddressId:e.emailAddressId};break;case"phone_code":t={phoneNumberId:e.phoneNumberId,default:e.default,channel:e.channel};break;case"web3_metamask_signature":case"web3_base_signature":case"web3_coinbase_wallet_signature":case"web3_okx_wallet_signature":t={web3WalletId:e.web3WalletId};break;case"reset_password_phone_code":t={phoneNumberId:e.phoneNumberId};break;case"enterprise_sso":t={redirectUrl:e.redirectUrl,actionCompleteRedirectUrl:e.actionCompleteRedirectUrl,oidcPrompt:e.oidcPrompt,enterpriseConnectionId:e.enterpriseConnectionId};break;default:tI("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...t,strategy:e.strategy},action:"prepare_first_factor"})};attemptFirstFactor=e=>{let t;return ta.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(aQ(e.publicKeyCredential))}:{...e},this._basePost({body:{...t,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:t}=aW();return{startEmailLinkFlow:async({emailAddressId:a,redirectUrl:r})=>{this.id||tE("SignIn");let n={strategy:"email_link",emailAddressId:a,redirectUrl:r},i="needs_second_factor"===this.status,s=i?"secondFactorVerification":"firstFactorVerification";return i?await this.prepareSecondFactor(n):await this.prepareFirstFactor(n),new Promise((a,r)=>{e(()=>this.reload().then(e=>{let r=e[s].status;("verified"===r||"expired"===r)&&(t(),a(e))}).catch(e=>{t(),r(e)}))})},cancelEmailLinkFlow:t}};prepareSecondFactor=e=>(ta.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(ta.debug("SignIn.attemptSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_second_factor"}));authenticateWithRedirectOrPopup=async(e,t)=>{let{strategy:a,redirectUrlComplete:r,identifier:n,oidcPrompt:i,continueSignIn:s,enterpriseConnectionId:o}=e||{},l=rN.clerk.buildUrlWithAuth(e.redirectUrl);this.id&&s||await this.create({strategy:a,identifier:n,redirectUrl:l,actionCompleteRedirectUrl:r}),"enterprise_sso"===a&&await this.prepareFirstFactor({strategy:a,redirectUrl:l,actionCompleteRedirectUrl:r,oidcPrompt:i,enterpriseConnectionId:o});let{status:c,externalVerificationRedirectURL:u}=this.firstFactorVerification;"unverified"===c&&u?t(u):tq(c,rN.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eK);authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||tP("popup"),rT(rN.clerk,"signIn",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e.toString()})};authenticateWithWeb3=async e=>{let t,{identifier:a,generateSignature:r,strategy:n="web3_metamask_signature"}=e||{},i=n.replace("web3_","").replace("_signature","");"function"!=typeof r&&tP("generateSignature"),await this.create({identifier:a});let s=this.supportedFirstFactors?.find(e=>e.strategy===n);s||tC("SignIn"),await this.prepareFirstFactor(s);let{message:o}=this.firstFactorVerification;o||tC("SignIn");try{t=await r({identifier:a,nonce:o,provider:i})}catch(e){if("coinbase_wallet"===i&&4001===e.code)t=await r({identifier:a,nonce:o,provider:i});else throw e}return this.attemptFirstFactor({signature:t,strategy:n})};authenticateWithMetamask=async()=>{let e=await tk().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tk().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await tk().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tk().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await tk().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tk().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await tk().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tk().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithPasskey=async e=>{let{flow:t}=e||{},a=rN.clerk.__internal_isWebAuthnSupported||rb,r=rN.clerk.__internal_getPublicCredentials||aJ,n=rN.clerk.__internal_isWebAuthnAutofillSupported||ry;if(!a())throw new C("Passkeys are not supported",{code:"passkey_not_supported"});if("autofill"===t||"discoverable"===t)await this.create({strategy:"passkey"});else{let e=this.supportedFirstFactors.find(e=>"passkey"===e.strategy);e||function(){throw Error(`${tz} You need to start a SignIn flow by calling SignIn.create({ strategy: 'passkey' }) first`)}(),await this.prepareFirstFactor(e)}let{nonce:i}=this.firstFactorVerification,s=i?a$(JSON.parse(i)):null;s||tO("get");let o=!1;"autofill"===t&&(o=await n());let{publicKeyCredential:l,error:c}=await r({publicKeyOptions:s,conditionalUI:o});if(!l)throw c;return this.attemptFirstFactor({publicKeyCredential:l,strategy:"passkey"})};validatePassword=(e,t)=>{if(rN.clerk.__internal_environment?.userSettings.passwordSettings)return rq(rB(),{...rN.clerk.__internal_environment?.userSettings.passwordSettings,validatePassword:!0})(e,t)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.supportedIdentifiers=e.supported_identifiers,this.identifier=e.identifier,this.supportedFirstFactors=en(e.supported_first_factors),this.supportedSecondFactors=en(e.supported_second_factors),this.firstFactorVerification=new a0(e.first_factor_verification),this.secondFactorVerification=new a0(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new rZ(e.user_data),this.clientTrustState=e.client_trust_state??void 0),rt.emit("resource:update",{resource:this}),this}__internal_toSnapshot(){return{object:"sign_in",id:this.id||"",status:this.status||null,supported_identifiers:this.supportedIdentifiers,supported_first_factors:er(this.supportedFirstFactors),supported_second_factors:er(this.supportedSecondFactors),first_factor_verification:this.firstFactorVerification.__internal_toSnapshot(),second_factor_verification:this.secondFactorVerification.__internal_toSnapshot(),identifier:this.identifier,created_session_id:this.createdSessionId,user_data:this.userData.__internal_toSnapshot()}}}class rD{emailCode={sendCode:this.sendEmailCode.bind(this),verifyCode:this.verifyEmailCode.bind(this)};emailLink={sendLink:this.sendEmailLink.bind(this),waitForVerification:this.waitForEmailLinkVerification.bind(this),get verification(){if(!s())return null;const e=eT("__clerk_status"),t=eT("__clerk_created_session");if(!e||!t)return null;const a="verified"===e&&void 0!==rN.clerk.client&&rN.clerk.client.sessions.some(e=>e.id===t);return{status:e,createdSessionId:t,verifiedFromTheSameClient:a}}};resetPasswordEmailCode={sendCode:this.sendResetPasswordEmailCode.bind(this),verifyCode:this.verifyResetPasswordEmailCode.bind(this),submitPassword:this.submitResetPassword.bind(this)};phoneCode={sendCode:this.sendPhoneCode.bind(this),verifyCode:this.verifyPhoneCode.bind(this)};mfa={sendPhoneCode:this.sendMFAPhoneCode.bind(this),verifyPhoneCode:this.verifyMFAPhoneCode.bind(this),verifyTOTP:this.verifyTOTP.bind(this),verifyBackupCode:this.verifyBackupCode.bind(this)};#el=!1;#ec;constructor(e){this.#ec=e}get id(){return this.#ec.id}get identifier(){return this.#ec.identifier}get createdSessionId(){return this.#ec.createdSessionId}get userData(){return this.#ec.userData}get status(){return this.#ec.status||"needs_identifier"}get supportedFirstFactors(){return this.#ec.supportedFirstFactors??[]}get supportedSecondFactors(){return this.#ec.supportedSecondFactors??[]}get isTransferable(){return"transferable"===this.#ec.firstFactorVerification.status}get existingSession(){if("failed"===this.#ec.firstFactorVerification.status&&this.#ec.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.#ec.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.#ec.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.#ec.firstFactorVerification}get secondFactorVerification(){return this.#ec.secondFactorVerification}get hasBeenFinalized(){return this.#el}async sendResetPasswordEmailCode(){if(!this.#ec.id)throw Error("Cannot reset password without a sign in.");return rR(this.#ec,async()=>{let e=this.#ec.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new E("Reset password email code factor not found",{code:"factor_not_found"});let{emailAddressId:t}=e;await this.#ec.__internal_basePost({body:{emailAddressId:t,strategy:"reset_password_email_code"},action:"prepare_first_factor"})})}async verifyResetPasswordEmailCode(e){let{code:t}=e;return rR(this.#ec,async()=>{await this.#ec.__internal_basePost({body:{code:t,strategy:"reset_password_email_code"},action:"attempt_first_factor"})})}async submitResetPassword(e){let{password:t,signOutOfOtherSessions:a=!0}=e;return rR(this.#ec,async()=>{await this.#ec.__internal_basePost({body:{password:t,signOutOfOtherSessions:a},action:"reset_password"})})}async _create(e){let t=tg();await this.#ec.__internal_basePost({path:this.#ec.pathRoot,body:t?{locale:t,...e}:e})}async create(e){return rR(this.#ec,async()=>{await this._create(e)})}async password(e){if([e.identifier,e.emailAddress,e.phoneNumber].filter(Boolean).length>1)throw Error("Only one of identifier, emailAddress, or phoneNumber can be provided");return rR(this.#ec,async()=>{let t=e.identifier||e.emailAddress||e.phoneNumber,a=this.#ec.identifier,r=tg();await this.#ec.__internal_basePost({path:this.#ec.pathRoot,body:{identifier:t||a,password:e.password,...r?{locale:r}:{}}})})}async sendEmailCode(e={}){let{emailAddress:t,emailAddressId:a}=e;if(!this.#ec.id&&a)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#ec.id&&!t)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return rR(this.#ec,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:a});if(!e)throw new E("Email code factor not found",{code:"factor_not_found"});await this.#ec.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor"})})}async verifyEmailCode(e){let{code:t}=e;return rR(this.#ec,async()=>{await this.#ec.__internal_basePost({body:{code:t,strategy:"email_code"},action:"attempt_first_factor"})})}async sendEmailLink(e){let{emailAddress:t,verificationUrl:a,emailAddressId:r}=e;if(!this.#ec.id&&r)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#ec.id&&!t)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return rR(this.#ec,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:r});if(!e)throw new E("Email link factor not found",{code:"factor_not_found"});let n=a;try{new URL(a)}catch{n=window.location.origin+a}await this.#ec.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:n,strategy:"email_link"},action:"prepare_first_factor"})})}async waitForEmailLinkVerification(){return rR(this.#ec,async()=>{let{run:e,stop:t}=aW();await new Promise((a,r)=>{e(async()=>{try{let e=await this.#ec.__internal_baseGet(),r=e.firstFactorVerification.status;("verified"===r||"expired"===r)&&(t(),a(e))}catch(e){t(),r(e)}})})})}async sendPhoneCode(e={}){let{phoneNumber:t,phoneNumberId:a,channel:r="sms"}=e;if(!this.#ec.id&&a)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.#ec.id&&!t)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return rR(this.#ec,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:a});if(!e)throw new E("Phone code factor not found",{code:"factor_not_found"});await this.#ec.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:r},action:"prepare_first_factor"})})}async verifyPhoneCode(e){let{code:t}=e;return rR(this.#ec,async()=>{await this.#ec.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_first_factor"})})}async sso(e){let{strategy:t,redirectUrl:a,redirectCallbackUrl:r,popup:n,oidcPrompt:i,enterpriseConnectionId:s,identifier:o}=e;return rR(this.#ec,async()=>{let e=a;try{new URL(a)}catch{e=window.location.origin+a}let l={redirectUrl:rN.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(n){let t=rU(rN.clerk,{redirectCallbackUrl:l.redirectUrl,redirectUrl:e});l.redirectUrl=t.redirectCallbackUrl,l.actionCompleteRedirectUrl=t.redirectUrl}await this._create({strategy:t,...l,identifier:o}),"enterprise_sso"===t&&await this.#ec.__internal_basePost({body:{...l,oidcPrompt:i,enterpriseConnectionId:s,strategy:"enterprise_sso"},action:"prepare_first_factor"});let{status:c,externalVerificationRedirectURL:u}=this.#ec.firstFactorVerification;"unverified"===c&&u&&(n?(await rM(rN.clerk,{popup:n,externalVerificationRedirectURL:u}),await this.#ec.reload()):eK(u))})}async web3(e){let{strategy:t}=e,a=t.replace("web3_","").replace("_signature","");return rR(this.#ec,async()=>{let e,r,n;switch(a){case"metamask":e=await tk().getMetamaskIdentifier(),r=tk().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await tk().getCoinbaseWalletIdentifier(),r=tk().generateSignatureWithCoinbaseWallet;break;case"base":e=await tk().getBaseIdentifier(),r=tk().generateSignatureWithBase;break;case"okx_wallet":e=await tk().getOKXWalletIdentifier(),r=tk().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${a}`)}await this._create({identifier:e});let i=this.#ec.supportedFirstFactors?.find(e=>e.strategy===t);if(!i)throw new E("Web3 first factor not found",{code:"factor_not_found"});await this.#ec.__internal_basePost({body:{web3WalletId:i.web3WalletId,strategy:t},action:"prepare_first_factor"});let{message:s}=this.firstFactorVerification;if(!s)throw new E("Web3 nonce not found",{code:"web3_nonce_not_found"});try{n=await r({identifier:e,nonce:s})}catch(t){if("coinbase_wallet"===a&&4001===t.code)n=await r({identifier:e,nonce:s});else throw t}await this.#ec.__internal_basePost({body:{signature:n,strategy:t},action:"attempt_first_factor"})})}async passkey(e){let{flow:t}=e||{},a=rN.clerk.__internal_isWebAuthnSupported||rb,r=rN.clerk.__internal_getPublicCredentials||aJ,n=rN.clerk.__internal_isWebAuthnAutofillSupported||ry;if(!a())throw new C("Passkeys are not supported",{code:"passkey_not_supported"});return rR(this.#ec,async()=>{if("autofill"===t||"discoverable"===t)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new E("Passkey factor not found",{code:"factor_not_found"});await this.#ec.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor"})}let{nonce:e}=this.firstFactorVerification,a=e?a$(JSON.parse(e)):null;if(!a)throw new E("Missing public key options",{code:"missing_public_key_options"});let i=!1;"autofill"===t&&(i=await n());let{publicKeyCredential:s,error:o}=await r({publicKeyOptions:a,conditionalUI:i});if(!s)throw new C(o.message,{code:"passkey_retrieval_failed"});await this.#ec.__internal_basePost({body:{publicKeyCredential:JSON.stringify(aQ(s)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return rR(this.#ec,async()=>{let e=this.#ec.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new E("Phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:t}=e;await this.#ec.__internal_basePost({body:{phoneNumberId:t,strategy:"phone_code"},action:"prepare_second_factor"})})}async verifyMFAPhoneCode(e){let{code:t}=e;return rR(this.#ec,async()=>{await this.#ec.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:t}=e;return rR(this.#ec,async()=>{await this.#ec.__internal_basePost({body:{code:t,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:t}=e;return rR(this.#ec,async()=>{await this.#ec.__internal_basePost({body:{code:t,strategy:"backup_code"},action:"attempt_second_factor"})})}async ticket(e){let t=e?.ticket??eT("__clerk_ticket");return this.create({ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};if(!this.#ec.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return rR(this.#ec,async()=>{rN.clerk.client&&!rN.clerk.client.sessions.some(e=>e.id===this.#ec.createdSessionId)&&await rN.clerk.client.reload(),this.#el=!0,await rN.clerk.setActive({session:this.#ec.createdSessionId,navigate:t})})}selectFirstFactor({strategy:e,emailAddressId:t,phoneNumberId:a}){if(!this.#ec.supportedFirstFactors)return null;if(t){let a=this.#ec.supportedFirstFactors.find(a=>a.strategy===e&&a.emailAddressId===t);if(a)return a}if(a){let t=this.#ec.supportedFirstFactors.find(t=>t.strategy===e&&t.phoneNumberId===a);if(t)return t}let r=this.#ec.supportedFirstFactors.find(t=>t.strategy===e&&t.safeIdentifier===this.#ec.identifier);if(r)return r;let n=this.#ec.supportedFirstFactors.find(t=>t.strategy===e);return n||null}}function rF(e){let{unsafeMetadata:t}={...e},a=t?"object"==typeof t?JSON.stringify(t):t:"";return{...e,...t?{unsafeMetadata:a}:{}}}class rL extends tL{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new a9(null);username=null;firstName=null;lastName=null;emailAddress=null;phoneNumber=null;web3wallet=null;externalAccount;hasPassword=!1;unsafeMetadata={};createdSessionId=null;createdUserId=null;abandonAt=null;legalAcceptedAt=null;locale=null;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&ta.debug("SignUp.status",{id:this.id,from:t,to:e})}__internal_future=new rW(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{ta.debug("SignUp.create",{id:this.id,strategy:e.strategy});let t={...e};if(!t.locale){let e=tg();e&&(t.locale=e)}if(!this.clientBypass()&&!this.shouldBypassCaptchaForAttempt(e)){let e=new tD(rL.clerk),a=await e.managedOrInvisible({action:"signup"});if(!a)throw new E("",{code:"captcha_unavailable"});t={...t,...a}}if(t.transfer&&this.shouldBypassCaptchaForAttempt(t)){let e=rL.clerk.client?.signIn.firstFactorVerification.strategy;e&&(t={...t,strategy:e})}return this._basePost({path:this.pathRoot,body:rF(t)})};prepareVerification=e=>(ta.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(ta.debug("SignUp.attemptVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_verification"}));prepareEmailAddressVerification=e=>this.prepareVerification(e||{strategy:"email_code"});attemptEmailAddressVerification=e=>this.attemptVerification({...e,strategy:"email_code"});createEmailLinkFlow=()=>{let{run:e,stop:t}=aW();return{startEmailLinkFlow:async({redirectUrl:a})=>(this.id||tE("SignUp"),await this.prepareEmailAddressVerification({strategy:"email_link",redirectUrl:a}),new Promise((a,r)=>{e(()=>this.reload().then(e=>{let r=e.verifications.emailAddress.status;("verified"===r||"expired"===r)&&(t(),a(e))}).catch(e=>{t(),r(e)}))})),cancelEmailLinkFlow:t}};preparePhoneNumberVerification=e=>this.prepareVerification(e||{strategy:"phone_code"});attemptPhoneNumberVerification=e=>this.attemptVerification({...e,strategy:"phone_code"});prepareWeb3WalletVerification=e=>this.prepareVerification({strategy:"web3_metamask_signature",...e});attemptWeb3WalletVerification=async e=>{let{signature:t,strategy:a="web3_metamask_signature"}=e;return this.attemptVerification({signature:t,strategy:a})};authenticateWithWeb3=async e=>{let t,{generateSignature:a,identifier:r,unsafeMetadata:n,strategy:i="web3_metamask_signature",legalAccepted:s}=e||{},o=i.replace("web3_","").replace("_signature","");"function"!=typeof a&&tP("generateSignature");let l=r||this.web3wallet;await this.create({web3Wallet:l,unsafeMetadata:n,legalAccepted:s}),await this.prepareWeb3WalletVerification({strategy:i});let{message:c}=this.verifications.web3Wallet;c||tC("SignUp");try{t=await a({identifier:r,nonce:c,provider:o})}catch(e){if("coinbase_wallet"===o&&4001===e.code)t=await a({identifier:r,nonce:c,provider:o});else throw e}return this.attemptWeb3WalletVerification({signature:t,strategy:i})};authenticateWithMetamask=async e=>{let t=await tk().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tk().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let t=await tk().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tk().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let t=await tk().getBaseIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tk().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let t=await tk().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tk().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithRedirectOrPopup=async(e,t)=>{let{redirectUrl:a,redirectUrlComplete:r,strategy:n,continueSignUp:i=!1,unsafeMetadata:s,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:u}=e,d=rL.clerk.buildUrlWithAuth(a),h=()=>{let e={strategy:n,redirectUrl:d,actionCompleteRedirectUrl:r,unsafeMetadata:s,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:u};return i&&this.id?this.update(e):this.create(e)},{verifications:m}=await h().catch(async e=>{if(T(e)&&P(e))return await rL.clerk.__internal_environment.reload(),h();throw e}),{externalAccount:p}=m,{status:f,externalVerificationRedirectURL:g}=p;"unverified"===f&&g?t(g):tq(f,rL.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eK);authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||tP("popup"),rT(rL.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:rF(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,t)=>{if(rL.clerk.__internal_environment?.userSettings.passwordSettings)return rq(rB(),{...rL.clerk.__internal_environment?.userSettings.passwordSettings,validatePassword:!0})(e,t)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.requiredFields=e.required_fields,this.optionalFields=e.optional_fields,this.missingFields=e.missing_fields,this.unverifiedFields=e.unverified_fields,this.verifications=new a9(e.verifications),this.username=e.username,this.firstName=e.first_name,this.lastName=e.last_name,this.emailAddress=e.email_address,this.phoneNumber=e.phone_number,this.hasPassword=e.has_password,this.unsafeMetadata=e.unsafe_metadata,this.createdSessionId=e.created_session_id,this.createdUserId=e.created_user_id,this.abandonAt=e.abandon_at,this.web3wallet=e.web3_wallet,this.legalAcceptedAt=e.legal_accepted_at,this.locale=e.locale),rt.emit("resource:update",{resource:this}),this}__internal_toSnapshot(){return{object:"sign_up",id:this.id||"",status:this.status||null,required_fields:this.requiredFields,optional_fields:this.optionalFields,missing_fields:this.missingFields,unverified_fields:this.unverifiedFields,verifications:this.verifications.__internal_toSnapshot(),username:this.username,first_name:this.firstName,last_name:this.lastName,email_address:this.emailAddress,phone_number:this.phoneNumber,has_password:this.hasPassword,unsafe_metadata:this.unsafeMetadata,created_session_id:this.createdSessionId,created_user_id:this.createdUserId,abandon_at:this.abandonAt,web3_wallet:this.web3wallet,legal_accepted_at:this.legalAcceptedAt,locale:this.locale,external_account:this.externalAccount,external_account_strategy:this.externalAccount?.strategy}}clientBypass(){return rL.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){if(!e.strategy)return!1;let t=rL.clerk.__internal_environment.displayConfig.captchaOauthBypass;return!!(t.some(t=>t===e.strategy)||e.transfer&&t.some(e=>e===rL.clerk.client.signIn.firstFactorVerification.strategy))}__experimental_getEnterpriseConnections=()=>tL._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new rK(e)))}class rW{verifications={sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)};#el=!1;#ec;constructor(e){this.#ec=e}get id(){return this.#ec.id}get requiredFields(){return this.#ec.requiredFields}get optionalFields(){return this.#ec.optionalFields}get missingFields(){return this.#ec.missingFields}get status(){return this.#ec.status||"missing_requirements"}get username(){return this.#ec.username}get firstName(){return this.#ec.firstName}get lastName(){return this.#ec.lastName}get emailAddress(){return this.#ec.emailAddress}get phoneNumber(){return this.#ec.phoneNumber}get web3Wallet(){return this.#ec.web3wallet}get hasPassword(){return this.#ec.hasPassword}get unsafeMetadata(){return this.#ec.unsafeMetadata}get createdSessionId(){return this.#ec.createdSessionId}get createdUserId(){return this.#ec.createdUserId}get abandonAt(){return this.#ec.abandonAt}get legalAcceptedAt(){return this.#ec.legalAcceptedAt}get locale(){return this.#ec.locale}get unverifiedFields(){return this.#ec.unverifiedFields}get isTransferable(){return"transferable"===this.#ec.verifications.externalAccount.status&&this.#ec.verifications.externalAccount.error?.code==="external_account_exists"}get existingSession(){if(("failed"===this.#ec.verifications.externalAccount.status||"unverified"===this.#ec.verifications.externalAccount.status)&&this.#ec.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.#ec.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.#ec.verifications.externalAccount.error?.meta?.sessionId}}get hasBeenFinalized(){return this.#el}async getCaptchaToken(){let e=new tD(rL.clerk),t=await e.managedOrInvisible({action:"signup"});if(!t)throw Error("Captcha challenge failed");let{captchaError:a,captchaToken:r,captchaWidgetType:n}=t;return{captchaToken:r,captchaWidgetType:n,captchaError:a}}async _create(e){let{captchaToken:t,captchaWidgetType:a,captchaError:r}=await this.getCaptchaToken(),n={transfer:e.transfer,captchaToken:t,captchaWidgetType:a,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rF(e.unsafeMetadata):void 0,locale:e.locale??tg()};await this.#ec.__internal_basePost({path:this.#ec.pathRoot,body:n})}async create(e){return rR(this.#ec,async()=>{await this._create(e)})}async update(e){return rR(this.#ec,async()=>{let t={...e,unsafeMetadata:e.unsafeMetadata?rF(e.unsafeMetadata):void 0};await this.#ec.__internal_basePatch({path:this.#ec.pathRoot,body:t})})}async password(e){return rR(this.#ec,async()=>{let{captchaToken:t,captchaWidgetType:a,captchaError:r}=await this.getCaptchaToken(),n={strategy:"password",captchaToken:t,captchaWidgetType:a,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rF(e.unsafeMetadata):void 0};await this.#ec.__internal_basePost({path:this.#ec.pathRoot,body:n})})}async sendEmailCode(){return rR(this.#ec,async()=>{await this.#ec.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:t}=e;return rR(this.#ec,async()=>{await this.#ec.__internal_basePost({body:{strategy:"email_code",code:t},action:"attempt_verification"})})}async sendPhoneCode(e){let{phoneNumber:t,channel:a="sms"}=e;return rR(this.#ec,async()=>{if(!this.#ec.id){let{captchaToken:e,captchaWidgetType:a,captchaError:r}=await this.getCaptchaToken();await this.#ec.__internal_basePost({path:this.#ec.pathRoot,body:{phoneNumber:t,captchaToken:e,captchaWidgetType:a,captchaError:r}})}await this.#ec.__internal_basePost({body:{strategy:"phone_code",channel:a},action:"prepare_verification"})})}async verifyPhoneCode(e){let{code:t}=e;return rR(this.#ec,async()=>{await this.#ec.__internal_basePost({body:{strategy:"phone_code",code:t},action:"attempt_verification"})})}async sso(e){let{strategy:t,redirectUrl:a,redirectCallbackUrl:r,unsafeMetadata:n,legalAccepted:i,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,popup:c}=e;return rR(this.#ec,async()=>{let{captchaToken:e,captchaWidgetType:u,captchaError:d}=await this.getCaptchaToken(),h=a;try{new URL(a)}catch{h=window.location.origin+a}let m={redirectUrl:rL.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:h};if(c){let e=rU(rL.clerk,{redirectCallbackUrl:m.redirectUrl,redirectUrl:h});m.redirectUrl=e.redirectCallbackUrl,m.actionCompleteRedirectUrl=e.redirectUrl}let p=()=>this.#ec.__internal_basePost({path:this.#ec.pathRoot,body:{strategy:t,...m,unsafeMetadata:n,legalAccepted:i,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,captchaToken:e,captchaWidgetType:u,captchaError:d}});await p().catch(async e=>{if(T(e)&&P(e))return await rL.clerk.__internal_environment.reload(),p();throw e});let{status:f,externalVerificationRedirectURL:g}=this.#ec.verifications.externalAccount;"unverified"===f&&g&&(c?(await rM(rL.clerk,{popup:c,externalVerificationRedirectURL:g}),await this.#ec.reload()):eK(g))})}async web3(e){let{strategy:t,unsafeMetadata:a,legalAccepted:r}=e,n=t.replace("web3_","").replace("_signature","");return rR(this.#ec,async()=>{let e,i,s;switch(n){case"metamask":e=await tk().getMetamaskIdentifier(),i=tk().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await tk().getCoinbaseWalletIdentifier(),i=tk().generateSignatureWithCoinbaseWallet;break;case"base":e=await tk().getBaseIdentifier(),i=tk().generateSignatureWithBase;break;case"okx_wallet":e=await tk().getOKXWalletIdentifier(),i=tk().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${n}`)}let o=e||this.#ec.web3wallet;await this._create({web3Wallet:o,unsafeMetadata:a,legalAccepted:r}),await this.#ec.__internal_basePost({body:{strategy:t},action:"prepare_verification"});let{message:l}=this.#ec.verifications.web3Wallet;l||tC("SignUp");try{s=await i({identifier:e,nonce:l})}catch(t){if("coinbase_wallet"===n&&4001===t.code)s=await i({identifier:e,nonce:l});else throw t}await this.#ec.__internal_basePost({body:{signature:s,strategy:t},action:"attempt_verification"})})}async ticket(e){let t=e?.ticket??eT("__clerk_ticket");return this.create({...e,ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};return rR(this.#ec,async()=>{if(!this.#ec.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#el=!0,await rL.clerk.setActive({session:this.#ec.createdSessionId,navigate:t})})}}class rK extends tL{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class rH extends tL{pathRoot="tokens";jwt;static async create(e,t={},a={}){return new rH(await tL._fetch({method:"POST",path:e,body:t,search:a}),e)}constructor(e,t){super(),t&&(this.pathRoot=t),e?.jwt&&(this.jwt=tf(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=tf(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class rV extends tL{pathRoot="/me";id="";secret;uri;verified=!1;backupCodes;updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.secret=e.secret,this.uri=e.uri,this.verified=e.verified,this.backupCodes=e.backup_codes,this.updatedAt=tW(e.updated_at),this.createdAt=tW(e.created_at)),this}}class rG extends tL{pathRoot="/me";id;codes=[];updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.codes=e.codes,this.updatedAt=tW(e.updated_at),this.createdAt=tW(e.created_at)),this}}class rJ extends tL{pathRoot="/me";id="";externalId=null;username=null;emailAddresses=[];phoneNumbers=[];web3Wallets=[];externalAccounts=[];enterpriseAccounts=[];passkeys=[];organizationMemberships=[];passwordEnabled=!1;firstName=null;lastName=null;fullName=null;primaryEmailAddressId=null;primaryEmailAddress=null;primaryPhoneNumberId=null;primaryPhoneNumber=null;primaryWeb3WalletId=null;primaryWeb3Wallet=null;imageUrl="";hasImage=!1;twoFactorEnabled=!1;totpEnabled=!1;backupCodeEnabled=!1;publicMetadata={};unsafeMetadata={};createOrganizationEnabled=!1;createOrganizationsLimit=null;deleteSelfEnabled=!1;lastSignInAt=null;legalAcceptedAt=null;updatedAt=null;createdAt=null;cachedSessionsWithActivities=null;static isUserResource(e){return!!e&&e instanceof rJ}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case aK:return this.primaryEmailAddressId===e.id;case rv:return this.primaryPhoneNumberId===e.id;case rX:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:t}=e||{};return new aK({email_address:t},this.path()+"/email_addresses/").create()};createPasskey=()=>rk.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:t}=e||{};return new rv({phone_number:t},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:t}=e||{};return new rX({web3_wallet:t},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:t,redirectUrl:a,additionalScopes:r}=e||{};return new ri((await tL._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:t,redirect_url:a,additional_scope:r}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new rV((await tL._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new rV((await tL._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new aB((await tL._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new rG((await tL._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=e=>this._basePatch({body:rF(e)});updatePassword=e=>this._basePost({body:e,path:`${this.path()}/change_password`});removePassword=e=>this._basePost({body:e,path:`${this.path()}/remove_password`});delete=()=>this._baseDelete({path:"/me"}).then(e=>(rt.emit(a4,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await rP.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:t}=e||{};return null===t?rl.delete(`${this.path()}/profile_image`):rl.create(`${this.path()}/profile_image`,{file:t})};getOrganizationInvitations=e=>r$.retrieve(e);getOrganizationSuggestions=e=>rg.retrieve(e);getOrganizationMemberships=e=>rf.retrieve(e);leaveOrganization=async e=>new aB((await tL._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);initializePaymentMethod=e=>aw(e);addPaymentMethod=e=>ak(e);getPaymentMethods=e=>av(e);get verifiedExternalAccounts(){return this.externalAccounts.filter(e=>e.verification?.status=="verified")}get unverifiedExternalAccounts(){return this.externalAccounts.filter(e=>e.verification?.status!="verified")}get verifiedWeb3Wallets(){return this.web3Wallets.filter(e=>e.verification?.status=="verified")}get hasVerifiedEmailAddress(){return this.emailAddresses.filter(e=>"verified"===e.verification.status).length>0}get hasVerifiedPhoneNumber(){return this.phoneNumbers.filter(e=>"verified"===e.verification.status).length>0}fromJSON(e){return e&&(this.id=e.id,this.externalId=e.external_id||null,this.firstName=e.first_name||null,this.lastName=e.last_name||null,(this.firstName||this.lastName)&&(this.fullName=(({firstName:e,lastName:t,name:a})=>a||[e,t].join(" ").trim()||"")({firstName:this.firstName,lastName:this.lastName})),this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.username=e.username||null,this.passwordEnabled=e.password_enabled||!1,this.emailAddresses=(e.email_addresses||[]).map(e=>new aK(e,this.path()+"/email_addresses")),this.primaryEmailAddressId=e.primary_email_address_id||null,this.primaryEmailAddress=this.emailAddresses.find(({id:e})=>e===this.primaryEmailAddressId)||null,this.phoneNumbers=(e.phone_numbers||[]).map(e=>new rv(e,this.path()+"/phone_numbers")),this.primaryPhoneNumberId=e.primary_phone_number_id||null,this.primaryPhoneNumber=this.phoneNumbers.find(({id:e})=>e===this.primaryPhoneNumberId)||null,this.web3Wallets=(e.web3_wallets||[]).map(e=>new rX(e,this.path()+"/web3_wallets")),this.primaryWeb3WalletId=e.primary_web3_wallet_id||null,this.primaryWeb3Wallet=this.web3Wallets.find(({id:e})=>e===this.primaryWeb3WalletId)||null,this.externalAccounts=(e.external_accounts||[]).map(e=>new ri(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new rk(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new rf(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new a5(e,this.path()+"/enterprise_accounts")),this.publicMetadata=e.public_metadata||{},this.unsafeMetadata=e.unsafe_metadata||{},this.totpEnabled=e.totp_enabled||!1,this.backupCodeEnabled=e.backup_code_enabled||!1,this.twoFactorEnabled=e.two_factor_enabled||!1,this.createOrganizationEnabled=e.create_organization_enabled||!1,this.createOrganizationsLimit=e.create_organizations_limit||null,this.deleteSelfEnabled=e.delete_self_enabled||!1,e.last_sign_in_at&&(this.lastSignInAt=tW(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=tW(e.legal_accepted_at)),this.updatedAt=tW(e.updated_at||void 0),this.createdAt=tW(e.created_at||void 0)),this}__internal_toSnapshot(){return{object:"user",id:this.id,external_id:this.externalId,first_name:this.firstName,last_name:this.lastName,username:this.username,public_metadata:this.publicMetadata,unsafe_metadata:this.unsafeMetadata,image_url:this.imageUrl,has_image:this.hasImage,email_addresses:this.emailAddresses.map(e=>e.__internal_toSnapshot()),phone_numbers:this.phoneNumbers.map(e=>e.__internal_toSnapshot()),web3_wallets:this.web3Wallets.map(e=>e.__internal_toSnapshot()),external_accounts:this.externalAccounts.map(e=>e.__internal_toSnapshot()),passkeys:this.passkeys.map(e=>e.__internal_toSnapshot()),organization_memberships:this.organizationMemberships.map(e=>e.__internal_toSnapshot()),enterprise_accounts:this.enterpriseAccounts.map(e=>e.__internal_toSnapshot()),totp_enabled:this.totpEnabled,backup_code_enabled:this.backupCodeEnabled,two_factor_enabled:this.twoFactorEnabled,create_organization_enabled:this.createOrganizationEnabled,create_organizations_limit:this.createOrganizationsLimit,delete_self_enabled:this.deleteSelfEnabled,primary_email_address_id:this.primaryEmailAddressId,primary_phone_number_id:this.primaryPhoneNumberId,primary_web3_wallet_id:this.primaryWeb3WalletId,password_enabled:this.passwordEnabled,profile_image_id:this.imageUrl,last_sign_in_at:this.lastSignInAt?.getTime()||null,legal_accepted_at:this.legalAcceptedAt?.getTime()||null,updated_at:this.updatedAt?.getTime()||null,created_at:this.createdAt?.getTime()||null}}}class rZ{firstName;lastName;imageUrl;hasImage;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.firstName=e.first_name,this.lastName=e.last_name,this.imageUrl=e.image_url??void 0,this.hasImage=e.has_image??void 0),this}__internal_toSnapshot(){return{first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl||null,has_image:this.hasImage||null}}}class r$ extends tL{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await tL._fetch({path:"/me/organization_invitations",method:"GET",search:ar(e)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new r$(e))}})}constructor(e){super(),this.fromJSON(e)}accept=async()=>await this._basePost({path:`/me/organization_invitations/${this.id}/accept`});fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.publicOrganizationData={hasImage:e.public_organization_data.has_image,imageUrl:e.public_organization_data.image_url,name:e.public_organization_data.name,id:e.public_organization_data.id,slug:e.public_organization_data.slug},this.publicMetadata=e.public_metadata,this.role=e.role,this.status=e.status,this.createdAt=tW(e.created_at),this.updatedAt=tW(e.updated_at)),this}}let rY={enabled:!1,first_factors:[],name:"phone_number",required:!1,second_factors:[],used_for_first_factor:!1,used_for_second_factor:!1,verifications:[],verify_at_sign_up:!1};class rQ extends tL{id=void 0;actions={create_organization:!1,delete_self:!1};attributes={email_address:{enabled:!0,first_factors:["email_code"],name:"email_address",required:!0,second_factors:[],used_for_first_factor:!0,used_for_second_factor:!1,verifications:["email_code"],verify_at_sign_up:!0},phone_number:{...rY,name:"phone_number"},username:{...rY,name:"username"},web3_wallet:{...rY,name:"web3_wallet"},first_name:{...rY,name:"first_name"},last_name:{...rY,name:"last_name"},password:{enabled:!0,first_factors:[],name:"password",required:!0,second_factors:[],used_for_first_factor:!1,used_for_second_factor:!1,verifications:[],verify_at_sign_up:!1},authenticator_app:{...rY,name:"authenticator_app"},backup_code:{...rY,name:"backup_code"},passkey:{...rY,name:"passkey"}};enterpriseSSO={enabled:!1};passkeySettings={allow_autofill:!1,show_sign_in_button:!1};passwordSettings={};signIn={second_factor:{required:!1,enabled:!1}};signUp={allowlist_only:!1,captcha_enabled:!1,legal_consent_enabled:!1,mode:"public",progressive:!0};social={};usernameSettings={};get authenticatableSocialStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled&&e.authenticatable).map(([,e])=>e.strategy).sort():[]}get enabledFirstFactorIdentifiers(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&!e.startsWith("web3")).map(([e])=>e):[]}get socialProviderStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled).map(([,e])=>e.strategy).sort():[]}get web3FirstFactors(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&e.startsWith("web3")).map(([,e])=>e.first_factors).flat():[]}get alternativePhoneCodeChannels(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&"phone_number"===e).map(([,e])=>e?.channels?.filter(e=>"sms"!==e)||[]).flat():[]}constructor(e=null){super(),this.fromJSON(e)}get instanceIsPasswordBased(){return!!(this.attributes?.password?.enabled&&this.attributes.password?.required)}get hasValidAuthFactor(){return!!(this.attributes?.email_address?.enabled||this.attributes?.phone_number?.enabled||this.attributes.password?.required&&this.attributes.username?.required)}fromJSON(e){return e&&(this.attributes=this.withDefault(e.attributes?Object.fromEntries(Object.entries(e.attributes).map(e=>[e[0],{...e[1],name:e[0]}])):null,this.attributes),this.actions=this.withDefault(e.actions,this.actions),this.enterpriseSSO=this.withDefault(e.enterprise_sso,this.enterpriseSSO),this.passkeySettings=this.withDefault(e.passkey_settings,this.passkeySettings),this.passwordSettings=e.password_settings?{...e.password_settings,min_length:Math.max(e.password_settings?.min_length??8,8),max_length:e.password_settings?.max_length===0?72:Math.min(e.password_settings?.max_length??72,72)}:this.passwordSettings,this.signIn=this.withDefault(e.sign_in,this.signIn),this.signUp=this.withDefault(e.sign_up,this.signUp),this.social=this.withDefault(e.social,this.social),this.usernameSettings=e.username_settings?{...e.username_settings,min_length:Math.max(e.username_settings?.min_length??4,4),max_length:Math.min(e.username_settings?.max_length??64,64)}:this.usernameSettings),this}__internal_toSnapshot(){return{actions:this.actions,attributes:this.attributes,passkey_settings:this.passkeySettings,password_settings:this.passwordSettings,sign_in:this.signIn,sign_up:this.signUp,social:this.social}}}class rX extends tL{id;web3Wallet="";verification;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}create(){return this._basePost({body:{web3_wallet:this.web3Wallet}})}prepareVerification=e=>this._basePost({action:"prepare_verification",body:{...e}});attemptVerification=e=>{let{signature:t}=e;return this._basePost({action:"attempt_verification",body:{signature:t}})};destroy(){return this._baseDelete()}toString(){return this.web3Wallet}fromJSON(e){return e&&(this.id=e.id,this.web3Wallet=e.web3_wallet,this.verification=new a0(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}class r1 extends tL{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=tW(e.updated_at),this.createdAt=tW(e.created_at)),this}static async join(e){return new r1((await tL._fetch({path:"/waitlist",method:"POST",body:e}))?.response)}}function r0(e,t){var a,r;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||(a=t,r=e,a.organizationMemberships.length!==r.organizationMemberships.length||a.organizationMemberships[0]?.updatedAt!==r.organizationMemberships[0]?.updatedAt)}function r2(e,t){return!function(e,t){if(!e&&t||e&&!t)return!0;if(!e&&e===t)return!1;if(!e||!t)return!0;try{if(aM.isClientResource(e))return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.sessions.length!==t.sessions.length;if(rC.isSessionResource(e)){var a,r;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.lastActiveToken?.jwt?.claims?.__raw!==t.lastActiveToken?.jwt?.claims?.__raw||function(e,t){if(e.lastActiveOrganizationId!==t.lastActiveOrganizationId)return!0;let a=e.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId),r=t.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId);return a?.permissions?.length!==r?.permissions?.length}(e,t)||(a=e,r=t,!!a.user!=!!r.user||!!a.user&&!!r.user&&r0(a.user,r.user))}if(rJ.isUserResource(e))return r0(e,t)}catch{}return!0}(e,t)?e:t}let r9="__clerk_db_jwt";function r3(e,t){let a=new URL(e),r=a.searchParams.get(r9);a.searchParams.delete(r9);let n=r||t;return n&&a.searchParams.set(r9,n),a}let r5=e=>{let t=new URL(e);return t.searchParams.delete(r9),t},r6=e=>{let t=new URL(e);return t.searchParams.delete("__dev_session"),t.hash=decodeURI(t.hash).replace(/__clerk_db_jwt\[(.*)\]/,""),t.href.endsWith("#")&&(t.hash=""),t};function r8(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var r in a)e[r]=a[r]}return e}var r4=function e(t,a){function r(e,r,n){if("undefined"!=typeof document){"number"==typeof(n=r8({},a,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var s in n)n[s]&&(i+="; "+s,!0!==n[s]&&(i+="="+n[s].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+i}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var a=document.cookie?document.cookie.split("; "):[],r={},n=0;n<a.length;n++){var i=a[n].split("="),s=i.slice(1).join("=");try{var o=decodeURIComponent(i[0]);if(r[o]=t.read(s,o),e===o)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",r8({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,r8({},this.attributes,t))},withConverter:function(t){return e(r8({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(a)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});function r7(e){return{get:()=>r4.get(e),set(t,a={}){r4.set(e,t,a)},remove(t){r4.remove(e,t)}}}let ne=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function nt(e,t){let a=function(e){try{return new Date(e||new Date)}catch{return new Date}}(e);return a.setFullYear(a.getFullYear()+t),a}let na=r7("__clerk_test_etld"),nr="__client_uat",nn="__session",ni=()=>{let e=ty()?"None":"Lax",t=ne(e);return{sameSite:e,secure:t,partitioned:!1}};async function ns(e){let t;try{t=await ef(e)}catch(o){var a;a=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,$.has(a)||(console.log(a),$.add(a));let{default:r}=await Promise.resolve().then(n.t.bind(n,180,23)),{default:i}=await Promise.resolve().then(n.t.bind(n,3413,23)),s=r(e);t=i.stringify(s).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}return t}let no=()=>{let e=ty()?"None":"Lax",t=ne(e);return{sameSite:e,secure:t}};var nl=n(5945),nc=n.n(nl);class nu{lock=(function(e){let t=new(nc());return window.addEventListener("beforeunload",async()=>{await t.releaseLock(e)}),{acquireLockAndRun:async a=>{if("locks"in navigator&&isSecureContext){let t=new AbortController,r=setTimeout(()=>t.abort(),4999);return await navigator.locks.request(e,{signal:t.signal},async()=>(clearTimeout(r),await a())).catch(()=>!1)}if(await t.acquireLock(e,5e3))try{return await a()}finally{await t.releaseLock(e)}}}})("clerk.lock.refreshSessionToken");workerTimers=aL();timerId=null;initiated=!1;startPollingForSessionToken(e){if(this.timerId||this.initiated)return;let t=async()=>{this.initiated=!0,await this.lock.acquireLockAndRun(e),this.timerId=this.workerTimers.setTimeout(t,5e3)};t()}stopPollingForSessionToken(){null!=this.timerId&&(this.workerTimers.clearTimeout(this.timerId),this.timerId=null),this.initiated=!1}}class nd{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,t,a,r){let n=await ns(e.publishableKey),i=new nd(e,t,n,a,r);return await i.setup(),i}constructor(e,t,r,n,i){this.clerk=e,this.instanceType=n,this.clerkEventBus=i,rt.on(a8,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),rt.on(a4,()=>this.handleSignOut()),this.refreshTokenOnFocus(),this.startPollingForToken(),this.clientUat=(e=>{let t=r7(nr),r=r7(eg(nr,e));return{set:e=>{let n=nt(Date.now(),1),i=ty()?"None":"Strict",s=ne(i),o=function(e=window.location.hostname,t=na){if(a)return a;if(["localhost","127.0.0.1","0.0.0.0"].includes(e))return e;let r=e.split(".");if(1===r.length)return e;for(let e=r.length-2;e>=0;e--){let n=r.slice(e).join(".");if(t.set("1",{domain:n}),"1"===t.get())return t.remove({domain:n}),a=n,n;t.remove({domain:n})}}(),l="0";e&&e.updatedAt&&e.signedInSessions.length>0&&(l=Math.floor(e.updatedAt.getTime()/1e3).toString()),r.remove(),t.remove(),r.set(l,{domain:o,expires:n,partitioned:!1,sameSite:i,secure:s}),t.set(l,{domain:o,expires:n,partitioned:!1,sameSite:i,secure:s})},get:()=>parseInt(r.get()||t.get()||"0",10)}})(r),this.sessionCookie=(e=>{let t=r7(nn),a=r7(eg(nn,e)),r=()=>{let e=ni();t.remove(e),a.remove(e)};return{set:e=>{let n=nt(Date.now(),1),{sameSite:i,secure:s,partitioned:o}=ni();o&&r(),t.set(e,{expires:n,sameSite:i,secure:s,partitioned:o}),a.set(e,{expires:n,sameSite:i,secure:s,partitioned:o})},remove:r,get:()=>a.get()||t.get()}})(r),this.activeCookie=(()=>{let e=r7("clerk_active_context"),t={secure:ne("None")};return{set:a=>{e.set(a,t)},get:()=>e.get(),remove:()=>e.remove(t)}})(),this.devBrowser=function({cookieSuffix:e,frontendApi:t,fapiClient:a}){let r,n,i=(r=r7(r9),n=r7(eg(r9,e)),{get:()=>n.get()||r.get(),set:e=>{let t=nt(Date.now(),1),{sameSite:a,secure:i}=no();n.set(e,{expires:t,sameSite:a,secure:i}),r.set(e,{expires:t,sameSite:a,secure:i})},remove:()=>{let e=no();n.remove(e),r.remove(e)}});function s(){return i.get()}function o(e){i.set(e)}function l(){i.remove()}return{clear:function(){l()},setup:async function(){var e;let r;if(!ev(t))return;a.onBeforeRequest(e=>{let t=s();t&&e?.url&&(e.url=r3(e.url,t))}),a.onAfterResponse((e,t)=>{let a=t?.headers?.get("Clerk-Db-Jwt");a&&o(a)});let n=(r=(e=new URL(window.location.href)).searchParams.get(r9)||"",r5(r6(e)).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",r5(r6(e))),r);if(n)return void o(n);if(i.get())return;let l=a.buildUrl({path:"/dev_browser"}),c=await fetch(l.toString(),{method:"POST"});if(!c.ok){let e=function(e=[]){return e.length>0?e.map(e=>new w(e)):[]}((await c.json()).errors);e[0]?tS(e[0].longMessage):tS()}let u=await c.json();o(u?.id)},getDevBrowserJWT:s,setDevBrowserJWT:o,removeDevBrowserJWT:l}}({frontendApi:e.frontendApi,fapiClient:t,cookieSuffix:r})}async setup(){return"production"===this.instanceType?this.setupProduction():this.setupDevelopment()}isSignedOut(){return this.clerk.loaded?!!this.clerk.user:0>=this.clientUat.get()}async handleUnauthenticatedDevBrowser(){this.devBrowser.clear(),await this.devBrowser.setup()}decorateUrlWithDevBrowserToken(e){let t=this.devBrowser.getDevBrowserJWT();if(!t)throw Error(`${tz} Missing dev browser jwt. Please contact support.`);return r3(e,t)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new nu,this.poller.startPollingForSessionToken(()=>this.refreshSessionToken()))}stopPollingForToken(){this.poller&&(this.poller.stopPollingForSessionToken(),this.poller=null)}refreshTokenOnFocus(){window.addEventListener("focus",()=>{"visible"===document.visibilityState&&this.refreshSessionToken({updateCookieImmediately:!0})})}async refreshSessionToken({updateCookieImmediately:e=!1}={}){if(this.clerk.session)try{let t=await this.clerk.session.getToken();e&&this.updateSessionCookie(t)}catch(e){return this.handleGetTokenError(e)}}updateSessionCookie(e){if(document.hasFocus()||this.isCurrentContextActive())return e||u()||ta.warn("Removing session cookie (offline)",{sessionId:this.clerk.session?.id},"authCookieService"),this.setActiveContextInStorage(),e?this.sessionCookie.set(e):this.sessionCookie.remove()}setClientUatCookieForDevelopmentInstances(){"production"!==this.instanceType&&this.inCustomDevelopmentDomain()&&this.clientUat.set(this.clerk.client)}inCustomDevelopmentDomain(){let e=this.clerk.frontendApi.replace("clerk.","");return!window.location.host.endsWith(e)}handleGetTokenError(e){if(T(e)||U(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(q(e))return void this.clerk.handleUnauthenticated().catch(e5);this.clerkEventBus.emit(f,"degraded")}}handleSignOut(){this.activeCookie.remove(),this.sessionCookie.remove(),this.setClientUatCookieForDevelopmentInstances()}setActiveContextInStorage(){let e=this.clerk.session?.id||"",t=this.clerk.organization?.id||"",a=`${e}:${t}`;":"!==a?this.activeCookie.set(a):this.activeCookie.remove()}isCurrentContextActive(){let e=this.activeCookie.get();if(!e)return!0;let[t,a]=e.split(":"),r=this.clerk.session?.id||"",n=this.clerk.organization?.id||"";return t===r&&a===n}getSessionCookie(){return this.sessionCookie.get()}}class nh{clerk;captchaChallenge;timers;constructor(e,t=new tD(e),a=aL()){this.clerk=e,this.captchaChallenge=t,this.timers=a}async start(){this.isEnabled()&&(await this.challengeAndSend(),this.timers.setInterval(()=>{this.challengeAndSend()},this.intervalInMs()))}async challengeAndSend(){if(!(!this.clerk.client||this.clientBypass()))try{let e=await this.captchaChallenge.invisible({action:"heartbeat"});await this.clerk.client.__internal_sendCaptchaToken(e)}catch{}}isEnabled(){return!!this.clerk.__internal_environment?.displayConfig?.captchaHeartbeat}clientBypass(){return this.clerk.client?.captchaBypass}intervalInMs(){return this.clerk.__internal_environment?.displayConfig?.captchaHeartbeatIntervalMs??6e5}}let nm=["/client","/waitlist"];class np{async getBaseFapiProxyOptions(){let e=await tL.clerk.session?.getToken();if(!e)throw new E("No valid session token available",{code:"no_session_token"});return{pathPrefix:"",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},credentials:"same-origin"}}async getAll(e){return tL._fetch({...await this.getBaseFapiProxyOptions(),method:"GET",path:"/api_keys",search:ar({...e,subject:e?.subject??tL.clerk.organization?.id??tL.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:t,total_count:a}=e;return{total_count:a,data:t.map(e=>new tK(e))}})}async create(e){return new tK(await tL._fetch({...await this.getBaseFapiProxyOptions(),path:"/api_keys",method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??tL.clerk.organization?.id??tL.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new tK(await tL._fetch({...await this.getBaseFapiProxyOptions(),method:"POST",path:`/api_keys/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let nf=new Map;class ng{#eu=!1;load(e){let t=e?.protectConfig;if(t?.loaders&&Array.isArray(t.loaders)&&0!==t.loaders.length&&!this.#eu){if(s())for(let e of(this.#eu=!0,t.loaders))try{this.applyLoader(e)}catch(e){Y(`[protect] failed to apply loader: ${e}`)}}}applyLoader(e){if(void 0!==e.rollout){let t=e.rollout;if("number"!=typeof t||t<0)return void Y(`[protect] loader rollout value is invalid: ${t}`);if(0===t||Math.random()>t)return}let t=e.type||"script",a=e.target||"body",r=document.createElement(t);if(e.attributes)for(let[t,a]of Object.entries(e.attributes))switch(typeof a){case"string":case"number":case"boolean":r.setAttribute(t,String(a));break;default:Y(`[protect] loader attribute is invalid type: ${t}=${a}`)}switch(e.textContent&&"string"==typeof e.textContent&&(r.textContent=e.textContent),a){case"head":document.head.appendChild(r);break;case"body":document.body.appendChild(r);break;default:if(a?.startsWith("#")){let e=document.getElementById(a.substring(1));if(!e)return void Y(`[protect] loader target element not found: ${a}`);e.appendChild(r);return}Y(`[protect] loader target is invalid: ${a}`)}}}class nb{signInResourceSignal=ai;signInErrorSignal=as;signInFetchSignal=ao;signInSignal=al;signUpResourceSignal=ac;signUpErrorSignal=au;signUpFetchSignal=ad;signUpSignal=ah;__internal_effect=t6;__internal_computed=t5;constructor(){rt.on("resource:update",this.onResourceUpdated),rt.on("resource:error",this.onResourceError),rt.on("resource:fetch",this.onResourceFetch)}onResourceError=e=>{e.resource instanceof rN&&this.signInErrorSignal({error:e.error}),e.resource instanceof rL&&this.signUpErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof rN){if(ny(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof rL){if(ny(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}};onResourceFetch=e=>{e.resource instanceof rN&&this.signInFetchSignal({status:e.status}),e.resource instanceof rL&&this.signUpFetchSignal({status:e.status})}}function ny(e,t){return!t?.id&&e&&e.__internal_future?.hasBeenFinalized===!1}let nw="cannot_render_billing_disabled",nk="cannot_render_user_missing",nv="cannot_render_organizations_disabled",nx="cannot_render_organization_missing",nj="cannot_render_single_session_enabled",n_={polling:!0,standardBrowser:!0,touchSession:!0,isSatellite:!1,signInUrl:void 0,signUpUrl:void 0,afterSignOutUrl:void 0,signInFallbackRedirectUrl:void 0,signUpFallbackRedirectUrl:void 0,signInForceRedirectUrl:void 0,signUpForceRedirectUrl:void 0,newSubscriptionRedirectUrl:void 0};class nz{static version="6.0.0-snapshot.v20251211120550";static sdkMetadata={name:"@clerk/clerk-js",version:"6.0.0-snapshot.v20251211120550"};static _billing;static _apiKeys;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new nb;internal_last_error=null;environment;#ed;#eh="";#em;#ep;#ef;#eg;#eb;#ey=null;#ew;#ek;#ev;#ex="loading";#ej=[];#e_=[];#ez={};#eS=null;#eA=0;#eE=p();get __internal_queryClient(){return this.#ed||Promise.resolve().then(n.bind(n,3303)).then(e=>e.QueryClient).then(e=>{this.#ed||(this.#ed=new e,this.#eE.emit("queryClientStatus","ready"))}),this.#ed?{__tag:"clerk-rq-client",client:this.#ed}:void 0}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#eh}get version(){return nz.version}set sdkMetadata(e){nz.sdkMetadata=e}get sdkMetadata(){return nz.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#ex}get isSatellite(){return!!tb()&&e3(this.#ez.isSatellite,new URL(window.location.href),!1)}get domain(){if(tb()){let e=function(e=""){return(e||"").replace(/^.+:\/\//,"")}(e3(this.#em,new URL(window.location.href)));if("production"===this.#ev){let t;if(!e)return"";if(e.match(/^(clerk\.)+\w*$/))t=/(clerk\.)*(?=clerk\.)/;else{if(e.match(/\.clerk.accounts/))return e;t=/^(clerk\.)*/gi}return`clerk.${e.replace(t,"")}`}return e}return""}get proxyUrl(){if(tb()){let e=e3(this.#ep,new URL(window.location.href));return!e||eH(e)||eV(e)||tm.throwInvalidProxyUrl({url:e}),e?eV(e)?new URL(e,window.location.origin).toString():e:""}return""}get frontendApi(){let e=em(this.publishableKey);return e?e.frontendApi:tm.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#ev}get isStandardBrowser(){return this.#ez.standardBrowser||!1}get billing(){return nz._billing||(nz._billing=new an),nz._billing}get apiKeys(){return nz._apiKeys||(nz._apiKeys=new np),nz._apiKeys}__experimental_checkout(e){return this._checkout||(this._checkout=e=>(function(e,t){let a,r,n,i,{for:s,planId:o,planPeriod:l}=t;if(null===e.user)throw Error("Clerk: User is not authenticated");if("organization"===s&&null===e.organization)throw Error("Clerk: The current session does not have an active organization. Use `setActive` to set the organization");let c=function(e){let{userId:t,orgId:a,planId:r,planPeriod:n}=e;return`${t}-${a||"user"}-${r}-${n}`}({userId:e.user?.id||"",orgId:"organization"===s?e.organization?.id:void 0,planId:o,planPeriod:l}),u=nf.get(c);if(u)return u.signals.computedSignal();let d=(a=t3({resource:null}),r=t3({error:null}),n=t3({status:"idle"}),i=t5(()=>{let e=a().resource,t=r().error,i=n().status;return{errors:am(t,{}),fetchStatus:i,checkout:e}}),{resourceSignal:a,errorSignal:r,fetchSignal:n,computedSignal:i}),h=new ag(d,{..."organization"===s?{orgId:e.organization?.id}:{},planId:o,planPeriod:l});return nf.set(c,{resource:h,signals:d}),d.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#ez[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,t){if(!(e=(e||"").trim()))return tm.throwMissingPublishableKeyError();const a=em(e);if(!a)return tm.throwInvalidPublishableKeyError({key:e});this.#em=t?.domain,this.#ep=t?.proxyUrl,this.environment=rn.getInstance(),this.#ev=a.instanceType,this.#eh=e,this.#ek=function(e){let t=[],a=[];async function r(e){for await(let a of["undefined"!=typeof window&&window.__internal_onBeforeRequest,...t].filter(e=>e))if(await a(e)===!1)return!1;return!0}async function n(e,t){for await(let r of["undefined"!=typeof window&&window.__internal_onAfterResponse,...a].filter(e=>e))if(await r(e,t)===!1)return!1;return!0}function i({method:t,path:a,sessionId:r,search:n,rotatingTokenNonce:i}){let s=new URLSearchParams(n);return s.append("__clerk_api_version","2025-11-10"),s.append("_clerk_js_version","6.0.0-snapshot.v20251211120550"),i&&s.append("rotating_token_nonce",i),e.domain&&"development"===e.instanceType&&e.isSatellite&&s.append("__domain",e.domain),t&&"GET"!==t&&"POST"!==t&&s.append("_method",t),a&&!nm.some(e=>a.startsWith(e))&&r&&s.append("_clerk_session_id",r),ey([...s.entries()].reduce((e,[t,a])=>(e[t]=a.includes(",")?a.split(","):a,e),{}))}function s(t){let{path:a,pathPrefix:r="v1"}=t;if(e.proxyUrl){let n=new URL(e.proxyUrl),s=n.pathname.slice(1);return s.endsWith("/")&&(s=s.slice(0,-1)),e_({base:n.origin,pathname:`${s}/${r}${a}`,search:i(t)},{stringify:!1})}let n="production"===e.instanceType?e.domain:"";return e_({base:`https://${n||e.frontendApi}`,pathname:`${r}${a}`,search:i(t)},{stringify:!1})}async function o(t,a){let i,o={...t},{method:l="GET",body:u}=o;!u||"object"!=typeof u||u instanceof FormData||(o.body=function(e){if(!e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype)return e;let t={};for(let[a,r]of Object.entries(e))void 0!==r&&(t[a]=r);return t}(u)),o.url=s({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===l||u instanceof FormData||o.headers.has("content-type")||o.headers.set("content-type","application/x-www-form-urlencoded"),"application/x-www-form-urlencoded"===o.headers.get("content-type")&&(o.body=u?ey(u,{keyEncoder:et}):u);let d=await r(o),h="GET"===l?"GET":"POST",m=o.url,p={...o,method:h,credentials:o.credentials||"include"};try{if(d){let e=a?.fetchMaxTries??(c()?4:11);i=await ts(()=>fetch(m,p),{retryImmediately:!0,initialDelay:700,maxDelayBetweenRetries:5e3,shouldRetry:(t,a)=>"GET"===h&&a<e,onBeforeRetry:e=>{m.searchParams.set("_clerk_retry_attempt",e.toString())}})}else i=new Response("{}",o)}catch(t){let e=m.toString();ta.error("network error",{error:t,url:e,method:l},"fapiClient");throw Error(`${tz} Network error at "${e}" - ${t}. Please try again.`)}let f=204!==i.status?await i.json():null,g=Object.assign(i,{payload:f});return i.ok||ta.error("request failed",{method:l,path:o.path,status:i.status},"fapiClient"),await n(o,g),g}return{buildEmailAddress:function(t){return function({localPart:e,frontendApi:t}){return`${e}@${t?t.replace("clerk.",""):"clerk.com"}`}({localPart:t,frontendApi:e.frontendApi})},buildUrl:s,onAfterResponse:function(e){a.push(e)},onBeforeRequest:function(e){t.push(e)},request:o}}({domain:this.domain,frontendApi:this.frontendApi,instanceType:this.instanceType,isSatellite:this.isSatellite,getSessionId:()=>this.session?.id,proxyUrl:this.proxyUrl}),this.#eE.emit(f,"loading"),this.#eE.prioritizedOn(f,e=>this.#ex=e),tL.clerk=this,this.#eg=new ng}getFapiClient=()=>this.#ek;load=async e=>{if(ta.info("load() start",{},"clerk"),!this.loaded){if("development"===this.#ev&&Y("Clerk: Clerk has been loaded with development keys. Development instances have strict usage limits and should not be used when deploying your application to production. Learn more: https://clerk.com/docs/deployments/overview"),this.#ez=this.#eI(e),this.#ez.clerkUiCtor&&(this.#ew=Promise.resolve(this.#ez.clerkUiCtor).then(e=>new e(()=>this,()=>this.environment,this.#ez,new tl))),"development"===this.#ev&&(this.#ez.routerPush||this.#ez.routerReplace)&&(!this.#ez.routerPush||!this.#ez.routerReplace)){let e=this.#ez.routerPush?"routerReplace":"routerPush";Y(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}rt.on(re,()=>{this.#eC(this.session),this.#eP()}),this.#ez.sdkMetadata&&(nz.sdkMetadata=this.#ez.sdkMetadata),!1!==this.#ez.telemetry&&(this.telemetry=new eY({clerkVersion:nz.version,samplingRate:1,perEventSampling:!this.#ez.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#ez.telemetry}),this.#ez.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let t;if(!e||"object"!=typeof e)return{};let a=e.theme;if(!a)return{};if(Array.isArray(a))for(let e of a){let a=e9(e);if(a){t=a;break}}else t=e9(a);return{themeName:t}}(this.#ez.appearance)}));try{this.#ez.standardBrowser?await this.#eq():await this.#eO();let e=this.#ez.telemetry,t=!1!==e&&!e?.disabled,a=!!this.#ez.__internal_keyless_claimKeylessApplicationUrl,r=!!this.environment?.clientDebugMode,n=this.environment?.isProduction?.()??!1,i=r||a&&!n,s=a&&!r?"error":void 0;i&&function(e={}){if(e4)return;let{enabled:t=!1,...a}=e;t&&(e6=!0,e4=!0,tt(a))}({enabled:!0,...s?{logLevel:s}:{},...t&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#eg?.load(this.environment),ta.info("load() complete",{},"clerk")}catch(e){throw this.#eE.emit(f,"error"),ta.error("load() failed",{error:e},"clerk"),e}}};#eT(){let e;return!!(!this.#ez.signUpUrl&&this.#ez.signInUrl&&(e=this.#ez.signInUrl,!eb.test(e)))}signOut=async(e,t)=>{if(!this.client||0===this.client.sessions.length)return;let a="undefined"!=typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:e5,r="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e5,n=e&&"object"==typeof e?e:t||{},i=n?.redirectUrl||this.buildAfterSignOutUrl();ta.debug("signOut() start",{hasClient:!!this.client,multiSessionCount:this.client?.signedInSessions.length??0,redirectUrl:i,sessionTarget:n?.sessionId??null},"clerk");let s="function"==typeof e?e:void 0,o=async()=>{let e=tc(this.#ez.standardBrowser);rt.emit(a4,null),this.#eU(),await e.track(async()=>{s?await s():await this.navigate(i)}),e.isUnloading()||(this.#eC(),this.#eP(),await r())};if(await a(),!n.sessionId||1===this.client.signedInSessions.length){this.#ez.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),ta.info("signOut() complete",{redirectUrl:ez(i)},"clerk");return}let l=this.client.signedInSessions.find(e=>e.id===n.sessionId),c=l?.id&&this.session?.id===l.id;await l?.remove(),c&&(await o(),ta.info("signOut() complete",{redirectUrl:ez(i)},"clerk"))};openGoogleOneTap=e=>{this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openModal("googleOneTap",e||{})),this.telemetry?.record(e2("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(D(this,this.environment)){if("development"===this.#ev)throw new E(eF.cannotOpenSignInOrSignUp,{code:nj});return}this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openModal("signIn",e||{}));let t={withSignUp:e?.withSignUp??this.#eT()};this.telemetry?.record(e2("SignIn",e,t))};closeSignIn=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(F(this,this.environment)){if("development"===this.#ev)throw new E(eF.cannotRenderAnyBillingComponent("Checkout"),{code:nw});return}if(!this.user){if("development"===this.#ev)throw new E(eF.cannotOpenCheckout,{code:nk});return}this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(F(this,this.environment)){if("development"===this.#ev)throw new E(eF.cannotRenderAnyBillingComponent("PlanDetails"),{code:nw});return}this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openDrawer("planDetails",e||{})),this.telemetry?.record(e2("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#ev)throw new E(eF.cannotOpenUserProfile,{code:nk});return}this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openModal("userVerification",e||{})),this.telemetry?.record(e2("UserVerification",e))};__internal_closeReverification=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:t,caller:a}=e;if(this.user||"development"!==this.#ev||Y(`Clerk: "${a}" requires an active user session. Ensure a user is signed in before executing ${a}.`),"organizations"===t){let t;return(t=this.environment,t?.organizationSettings.enabled||this.session?.currentTask?.key==="choose-organization")?{isEnabled:!0}:("development"===this.#ev&&this.__internal_openEnableOrganizationsPrompt({caller:a,onSuccess:()=>window.location.reload(),onClose:e.onClose}),{isEnabled:!1})}throw Error(`Attempted to enable an unknown or unsupported setting "${t}".`)};__internal_openEnableOrganizationsPrompt=e=>{this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted({preloadHint:"EnableOrganizationsPrompt"})).then(t=>t.openModal("enableOrganizationsPrompt",e||{})),this.telemetry?.record(e0("EnableOrganizationsPrompt",e))};__internal_closeEnableOrganizationsPrompt=()=>{this.assertComponentsReady(this.#ew),this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt"))};__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(e=>e.closeModal("blankCaptcha")));__internal_loadStripeJs=async()=>{let{loadStripe:e}=await Promise.resolve().then(n.bind(n,5608));return e};openSignUp=e=>{if(D(this,this.environment)){if("development"===this.#ev)throw new E(eF.cannotOpenSignInOrSignUp,{code:nj});return}this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openModal("signUp",e||{})),this.telemetry?.record(e2("SignUp",e))};closeSignUp=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#ev)throw new E(eF.cannotOpenUserProfile,{code:nk});return}this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openModal("userProfile",e||{}));let t=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(e2("UserProfile",e,t))};closeUserProfile=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userProfile"))};openOrganizationProfile=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new E(eF.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:nv})}});if(t){if(!this.organization){if("development"===this.#ev)throw new E(eF.cannotRenderComponentWhenOrgDoesNotExist,{code:nx});return}this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openModal("organizationProfile",e||{})),this.telemetry?.record(e2("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeModal("organizationProfile"))};openCreateOrganization=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new E(eF.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:nv})}});t&&(this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openModal("createOrganization",e||{})),this.telemetry?.record(e2("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openModal("waitlist",e||{})),this.telemetry?.record(e2("Waitlist",e))};closeWaitlist=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,t)=>{this.assertComponentsReady(this.#ew);let a="SignIn";this.#ew.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"signIn",node:e,props:t}));let r={withSignUp:t?.withSignUp??this.#eT()};this.telemetry?.record(e0(a,t,r))};unmountSignIn=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserAvatar=(e,t)=>{this.assertComponentsReady(this.#ew);let a="UserAvatar";this.#ew.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"userAvatar",node:e,props:t})),this.telemetry?.record(e0(a,t))};unmountUserAvatar=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountSignUp=(e,t)=>{this.assertComponentsReady(this.#ew);let a="SignUp";this.#ew.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"signUp",node:e,props:t})),this.telemetry?.record(e0(a,t))};unmountSignUp=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserProfile=(e,t)=>{if(!this.user){if("development"===this.#ev)throw new E(eF.cannotRenderComponentWhenUserDoesNotExist,{code:nk});return}this.assertComponentsReady(this.#ew);let a="UserProfile";this.#ew.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"userProfile",node:e,props:t}));let r=(t?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(e0(a,t,r))};unmountUserProfile=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOrganizationProfile=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new E(eF.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:nv})}});if(!a)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#ev)throw new E(eF.cannotRenderComponentWhenOrgDoesNotExist,{code:nx});return}this.assertComponentsReady(this.#ew);let n="OrganizationProfile";this.#ew.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:n,appearanceKey:"userProfile",node:e,props:t})),this.telemetry?.record(e0(n,t))};unmountOrganizationProfile=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountCreateOrganization=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new E(eF.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:nv})}});if(!a)return;this.assertComponentsReady(this.#ew);let r="CreateOrganization";this.#ew.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:r,appearanceKey:"createOrganization",node:e,props:t})),this.telemetry?.record(e0(r,t))};unmountCreateOrganization=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOrganizationSwitcher=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationSwitcher",onClose:()=>{throw new E(eF.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:nv})}});if(!a)return;this.assertComponentsReady(this.#ew);let r="OrganizationSwitcher";this.#ew.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:r,appearanceKey:"organizationSwitcher",node:e,props:t})),this.telemetry?.record(e0(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(e=>e.prefetch("organizationSwitcher"))};mountOrganizationList=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationList",onClose:()=>{throw new E(eF.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:nv})}});if(!a)return;this.assertComponentsReady(this.#ew);let r="OrganizationList";this.#ew.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:r,appearanceKey:"organizationList",node:e,props:t})),this.telemetry?.record(e0(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserButton=(e,t)=>{this.assertComponentsReady(this.#ew);let a="UserButton";this.#ew.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"userButton",node:e,props:t}));let r={...t?.customMenuItems?.length||0?{customItems:!0}:void 0,...t?.__experimental_asStandalone?{standalone:!0}:void 0};this.telemetry?.record(e0(a,t,r))};unmountUserButton=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountWaitlist=(e,t)=>{this.assertComponentsReady(this.#ew);let a="Waitlist";this.#ew.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"waitlist",node:e,props:t})),this.telemetry?.record(e0(a,t))};unmountWaitlist=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountPricingTable=(e,t)=>{if(F(this,this.environment)){if("development"===this.#ev)throw new E(eF.cannotRenderAnyBillingComponent("PricingTable"),{code:nw});return}this.assertComponentsReady(this.#ew);let a="PricingTable";this.#ew.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"pricingTable",node:e,props:t})),this.telemetry?.record(e0(a,t))};unmountPricingTable=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,t)=>{this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:"OAuthConsent",appearanceKey:"__internal_oauthConsent",node:e,props:t}))};__internal_unmountOAuthConsent=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountAPIKeys=(e,t)=>{let a;if(Y("Clerk: <APIKeys /> component is in early access and not yet recommended for production use."),L(this,a=this.environment)&&W(this,a)){if("development"===this.#ev)throw new E(eF.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&W(this,this.environment)){if("development"===this.#ev)throw new E(eF.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if(L(this,this.environment)){if("development"===this.#ev)throw new E(eF.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#ew);let r="APIKeys";this.#ew.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:r,appearanceKey:"apiKeys",node:e,props:t})),this.telemetry?.record(e0(r,t))};unmountAPIKeys=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskChooseOrganization=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"TaskChooseOrganization",onClose:()=>{throw new E(eF.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:nv})}});if(!a)return;this.assertComponentsReady(this.#ew);let r="TaskChooseOrganization";this.#ew.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:r,appearanceKey:"taskChooseOrganization",node:e,props:t})),this.telemetry?.record(e0(r,t))};unmountTaskChooseOrganization=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskResetPassword=(e,t)=>{this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:"TaskResetPassword",appearanceKey:"taskResetPassword",node:e,props:t})),this.telemetry?.record(e0("TaskResetPassword",t))};unmountTaskResetPassword=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};setActive=async e=>{let{organization:t,redirectUrl:a,navigate:r}=e,{session:n}=e;this.__internal_setActiveInProgress=!0,ta.debug("setActive() start",{hasClient:!!this.client,sessionTarget:"string"==typeof n?n:n?.id??n??null,organizationTarget:"string"==typeof t?t:t?.id??t??null,redirectUrl:a??null},"clerk");try{var i;let s;if(!this.client)throw ta.warn("Clerk setActive called before client is loaded",{},"clerk"),Error("setActive is being called before the client is loaded. Wait for init.");if(void 0===n&&!this.session)throw ta.warn("Clerk setActive precondition not met: no target session and no active session",{},"clerk"),Error("setActive should either be called with a session param or there should be already an active session.");"string"==typeof n&&(n=this.client.sessions.find(e=>e.id===n)||null);let o="undefined"!=typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:e5,l="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e5,c=void 0===n?this.session:n;c?.status==="pending"&&(i={...this.#ez,...e},s=["taskUrls","navigate"],Object.keys(i).some(e=>s.includes(e))||Y('Clerk: Session has pending tasks but no handling is configured. To handle pending tasks, provide either "taskUrls" for navigation to custom URLs or "navigate" for programmatic navigation. Without these options, users may get stuck on incomplete flows.'));let d=void 0!==t;if(c&&d){let e="string"==typeof t?t:t?.id;if("string"==typeof e&&e.startsWith("org_"))c.lastActiveOrganizationId=e||null;else{let t=c.user.organizationMemberships.find(t=>t.organization.slug===e),a=t?.organization.id||null,r=null===a;if(this.environment?.organizationSettings?.forceOrganizationSelection&&r)return;c.lastActiveOrganizationId=a}}c?.status!=="pending"&&await o(null===c?"sign-out":void 0),(tb()&&globalThis.document.hasFocus()||!this.#ez.standardBrowser)&&(await this.#eM(c),c=this.#eR(c?.id)),await c?.getToken()||(u()||ta.warn("Token is null when setting active session (offline)",{sessionId:c?.id},"clerk"),rt.emit(a8,{token:null}));let h=tc(this.#ez.standardBrowser),m=c?.status==="pending"&&c?.currentTask&&this.#ez.taskUrls?.[c?.currentTask.key];if((a||m||r)&&await h.track(async()=>{if(this.client){if(c?.status!=="pending"&&this.#eU(),m){let e=a?e_({base:m,hashSearchParams:{redirectUrl:a}},{stringify:!0}):m;await this.navigate(e)}else if(r&&c)await r({session:c});else if(a){if(this.client.isEligibleForTouch()){let e=new URL(a,window.location.href),t=this.buildUrlWithAuth(this.client.buildTouchUrl({redirectUrl:e}));await this.navigate(t)}await this.navigate(a)}}}),h.isUnloading())return;this.#eC(c),this.#eP(),c?.status!=="pending"&&await l()}finally{this.__internal_setActiveInProgress=!1}};addListener=e=>{var t;let a;return t=e,e=e=>{var r;a||={...e},t(a={...{client:r2((r=a).client,e.client),session:r2(r.session,e.session),user:r2(r.user,e.user),organization:r2(r.organization,e.organization)}})},this.#ej.push(e),this.client&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#ej=this.#ej.filter(t=>t!==e)}};on=(...e)=>{this.#eE.on(...e)};off=(...e)=>{this.#eE.off(...e)};__internal_addNavigationListener=e=>(this.#e_.push(e),()=>{this.#e_=this.#e_.filter(t=>t!==e)});navigate=async(e,t)=>{if(!e||!tb())return;setTimeout(()=>{this.#eB()},0);let a=new URL(e,window.location.href);this.#eN.includes(a.protocol)||(console.warn(`Clerk: "${a.protocol}" is not a valid protocol. Redirecting to "/" instead. If you think this is a mistake, please open an issue.`),a=new URL("/",window.location.href));let r=t?.replace&&this.#ez.routerReplace?this.#ez.routerReplace:this.#ez.routerPush;if(ta.info(`Clerk is navigating to: ${a}`),this.#ez.routerDebug&&console.log(`Clerk is navigating to: ${a}`),"null"!==a.origin&&a.origin!==window.location.origin||!r)return void eK(a);let n={...t?.metadata?{__internal_metadata:t?.metadata}:{},windowNavigate:eK};return await r(ez(a),n)};buildUrlWithAuth(e){if("production"===this.#ev)return e;let t=new URL(e,window.location.origin);return t.origin!==window.location.origin&&this.#ef?this.#ef.decorateUrlWithDevBrowserToken(t).href:t.href}buildSignInUrl(e){return this.#eD("signInUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildSignUpUrl(e){return this.#eD("signUpUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildUserProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.userProfileUrl):""}buildHomeUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.homeUrl):""}buildAfterSignInUrl({params:e}={}){return this.buildUrlWithAuth(new eP(this.#ez,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eP(this.#ez,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#ez.afterSignOutUrl?this.buildUrlWithAuth(this.#ez.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#ez.newSubscriptionRedirectUrl?this.#ez.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?e_({base:this.#ez.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#ez.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#ez.afterMultiSessionSingleSignOutUrl):this.#ez.signInUrl?this.buildUrlWithAuth(e_({base:this.#ez.signInUrl,hashPath:"choose"},{stringify:!0})):this.buildUrlWithAuth(this.environment.displayConfig.afterSignOutOneUrl):""}buildCreateOrganizationUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.createOrganizationUrl):""}buildOrganizationProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.organizationProfileUrl):""}buildTasksUrl(e){let t=this.session?.currentTask;if(!t)return"";let a=this.#ez.taskUrls?.[t.key];return a||e_({base:this.buildSignInUrl(e),hashPath:eB(t)},{stringify:!0})}#eF=async()=>{if(!tb())return;let e=new URLSearchParams({[K]:"true"}),t=eT(V);t&&eH(t)||function(){throw Error(`${tz} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let a=e_({base:eT(V),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(a))};redirectWithAuth=async e=>{if(tb())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(tb())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(tb())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(tb())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(tb())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(tb())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(tb())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(tb())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(tb())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(tb())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(tb())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,t)=>{if(!this.client)return;let a=eT("__clerk_status");if("expired"===a)throw new z(A.Expired);if("client_mismatch"===a)throw new z(A.ClientMismatch);if("verified"!==a)throw new z(A.Failed);let r=eT("__clerk_created_session"),{signIn:n,signUp:i,sessions:s}=this.client,o=s.some(e=>e.id===r),l="needs_second_factor"===n.status||"missing_requirements"===i.status,c=e=>t&&"function"==typeof t?t(e):this.navigate(e),u=e.redirectUrl?()=>c(e.redirectUrl):e5;return o?this.setActive({session:r,redirectUrl:e.redirectUrlComplete}):l?u():("function"==typeof e.onVerifiedOnOtherDevice&&e.onVerifiedOnOtherDevice(),null)};handleGoogleOneTapCallback=async(e,t,a)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:r,signUp:n}=this.client,i="identifier"in(e||{})?e:r,s="missingFields"in(e||{})?e:n,o=e=>a&&"function"==typeof a?a(this.buildUrlWithAuth(e)):this.navigate(this.buildUrlWithAuth(e));return this._handleRedirectCallback(t,{signUp:s,signIn:i,navigate:o})};_handleRedirectCallback=async(e,{signIn:t,signUp:a,navigate:r})=>{if(!this.loaded||!this.environment||!this.client)return;if(!window.opener&&e.reloadResource)try{"signIn"===e.reloadResource?await t.reload():"signUp"===e.reloadResource&&await a.reload()}catch{}let{displayConfig:n}=this.environment,{firstFactorVerification:i}=t,{externalAccount:s}=a.verifications,o={status:a.status,missingFields:a.missingFields,externalAccountStatus:s.status,externalAccountErrorCode:s.error?.code,externalAccountSessionId:s.error?.meta?.sessionId,sessionId:a.createdSessionId},l={status:t.status,firstFactorVerificationStatus:i.status,firstFactorVerificationErrorCode:i.error?.code,firstFactorVerificationSessionId:i.error?.meta?.sessionId,sessionId:t.createdSessionId},c=e=>()=>r(e),u=c(e.signInUrl||n.signInUrl),d=c(e.signUpUrl||n.signUpUrl),h=c(e.firstFactorUrl||e_({base:n.signInUrl,hashPath:"/factor-one"},{stringify:!0})),m=c(e.secondFactorUrl||e_({base:n.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=c(e.resetPasswordUrl||e_({base:n.signInUrl,hashPath:"/reset-password"},{stringify:!0})),f=new eP(this.#ez,e),g=c(e.continueSignUpUrl||e_({base:n.signUpUrl,hashPath:"/continue"},{stringify:!0})),b=({missingFields:t})=>t.length?g():(({signUp:e,verifyEmailPath:t,verifyPhonePath:a,continuePath:r,navigate:n,handleComplete:i,redirectUrl:s="",redirectUrlComplete:o="",oidcPrompt:l})=>{if("complete"===e.status)return i&&i();if("missing_requirements"===e.status){if(e.missingFields.some(e=>"enterprise_sso"===e))return e.authenticateWithRedirect({strategy:"enterprise_sso",redirectUrl:s,redirectUrlComplete:o,continueSignUp:!0,oidcPrompt:l});let i=eM();if(e.unverifiedFields?.includes("email_address")&&t)return n(t,{searchParams:i});if(e.unverifiedFields?.includes("phone_number")&&a)return n(a,{searchParams:i});if(r)return n(r,{searchParams:i})}})({signUp:a,verifyEmailPath:e.verifyEmailAddressUrl||e_({base:n.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||e_({base:n.signUpUrl,hashPath:"/verify-phone-number"},{stringify:!0}),navigate:r}),y=e.signInUrl||n.signInUrl,w=e.signUpUrl||n.signUpUrl,k=async({session:e,baseUrl:t,redirectUrl:a})=>{e.currentTask?await eN(e,{baseUrl:t,navigate:this.navigate}):await this.navigate(a)};if("complete"===l.status)return this.setActive({session:l.sessionId,navigate:async({session:e})=>{await k({session:e,baseUrl:y,redirectUrl:f.getAfterSignInUrl()})}});if("transferable"===o.externalAccountStatus&&"external_account_exists"===o.externalAccountErrorCode){let e=await t.create({transfer:!0});switch(e.status){case"complete":return this.setActive({session:e.createdSessionId,navigate:async({session:e})=>{await k({session:e,baseUrl:w,redirectUrl:f.getAfterSignInUrl()})}});case"needs_first_factor":return h();case"needs_second_factor":return m();case"needs_new_password":return p();default:tA("sign in")}}let v="user_locked"===o.externalAccountErrorCode,x="user_locked"===l.firstFactorVerificationErrorCode;if(v)return d();if(x)return u();if("needs_first_factor"===l.status&&!t.supportedFirstFactors?.every(e=>"enterprise_sso"===e.strategy))return h();if("needs_new_password"===l.status)return p();if("transferable"===l.firstFactorVerificationStatus){if(!1===e.transferable)return u();let t=await a.create({transfer:!0});switch(t.status){case"complete":return this.setActive({session:t.createdSessionId,navigate:async({session:e})=>{await k({session:e,baseUrl:w,redirectUrl:f.getAfterSignUpUrl()})}});case"missing_requirements":return b({missingFields:t.missingFields});default:tA("sign in")}}if("complete"===o.status)return this.setActive({session:o.sessionId,navigate:async({session:e})=>{await k({session:e,baseUrl:w,redirectUrl:f.getAfterSignUpUrl()})}});if("needs_second_factor"===l.status)return m();let j=("failed"===o.externalAccountStatus||"unverified"===o.externalAccountStatus)&&"identifier_already_signed_in"===o.externalAccountErrorCode&&o.externalAccountSessionId,_="failed"===l.firstFactorVerificationStatus&&"identifier_already_signed_in"===l.firstFactorVerificationErrorCode&&l.firstFactorVerificationSessionId;if(j||_){let e=l.firstFactorVerificationSessionId||o.externalAccountSessionId;if(e)return this.setActive({session:e,navigate:async({session:e})=>{await k({session:e,baseUrl:j?w:y,redirectUrl:f.getAfterSignInUrl()})}})}return(e=>{let{externalAccount:t}=e.verifications;return!!t.error})(a)?d():"verified"===o.externalAccountStatus&&"missing_requirements"===o.status?b({missingFields:a.missingFields}):this.session?.currentTask?void await this.redirectToTasks({redirectUrl:this.buildAfterSignInUrl()}):u()};handleRedirectCallback=async(e={},t)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:a,signUp:r}=this.client,n=e=>t&&"function"==typeof t?t(e):this.navigate(e);return this._handleRedirectCallback(e,{signUp:r,signIn:a,navigate:n})};handleUnauthenticated=async(e={broadcast:!0})=>{if(this.client&&this.session)try{let t=await aM.getOrCreateInstance().fetch();if(this.updateClient(t),this.session)return;return e.broadcast&&rt.emit(a4,null),this.setActive({session:null})}catch(e){if(T(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};authenticateWithGoogleOneTap=async e=>this.client?.signIn.create({strategy:"google_one_tap",token:e.token}).catch(t=>{if(T(t)&&"external_account_not_found"===t.errors[0].code)return this.client?.signUp.create({strategy:"google_one_tap",token:e.token,legalAccepted:e.legalAccepted});throw t});authenticateWithMetamask=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_okx_wallet_signature"})};authenticateWithWeb3=async({redirectUrl:e,signUpContinueUrl:t,customNavigate:a,unsafeMetadata:r,strategy:n,legalAccepted:i,secondFactorUrl:s})=>{let o,l;if(!this.client||!this.environment)return;let{displayConfig:c}=this.environment,u=n.replace("web3_","").replace("_signature",""),d=await tk().getWeb3Identifier({provider:u});switch(u){case"metamask":o=tk().generateSignatureWithMetamask;break;case"base":o=tk().generateSignatureWithBase;break;case"coinbase_wallet":o=tk().generateSignatureWithCoinbaseWallet;break;default:o=tk().generateSignatureWithOKXWallet}let h=e=>()=>a&&"function"==typeof a?a(e):this.navigate(e),m=h(s||e_({base:c.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=h(t||e_({base:c.signUpUrl,hashPath:"/continue"},{stringify:!0}));try{l=await this.client.signIn.authenticateWithWeb3({identifier:d,generateSignature:o,strategy:n})}catch(e){if(th(e,"form_identifier_not_found"))l=await this.client.signUp.authenticateWithWeb3({identifier:d,generateSignature:o,unsafeMetadata:r,strategy:n,legalAccepted:i}),t&&"missing_requirements"===l.status&&"verified"===l.verifications.web3Wallet.status&&await p();else throw e}let f=async({session:e,redirectUrl:t})=>{e.currentTask?await eN(e,{baseUrl:c.signInUrl,navigate:this.navigate}):await this.navigate(t)};switch(l.status){case"needs_second_factor":await m();break;case"complete":l.createdSessionId&&await this.setActive({session:l.createdSessionId,navigate:async({session:t})=>{await f({session:t,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:t})=>rm.create({name:e,slug:t});getOrganization=async e=>rm.get(e);joinWaitlist=async({emailAddress:e})=>r1.join({emailAddress:e});updateEnvironment(e){this.environment=e}__internal_setCountry=e=>{this.__internal_country||(this.__internal_country=e)};__internal_getSessionCookie=()=>this.#ef?.getSessionCookie();get __internal_last_error(){let e=this.internal_last_error;return this.internal_last_error=null,e}set __internal_last_error(e){this.internal_last_error=e}updateClient=e=>{if(!this.client){let t=this.#ez.selectInitialSession?this.#ez.selectInitialSession(e):this.#eL(e);this.#eC(t)}if(this.client=e,this.session){let e=this.#eR(this.session.id);"active"===this.session.status&&e?.status==="pending"&&("undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e5)(),this.#eC(e),this.session?.lastActiveToken||u()||ta.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),rt.emit(a8,{token:this.session?.lastActiveToken})}this.#eP()};get __internal_environment(){return this.environment}__internal_setEnvironment=async e=>{this.environment=new rn(e)};__internal_onBeforeRequest=e=>{this.#ek.onBeforeRequest(e)};__internal_onAfterResponse=e=>{this.#ek.onAfterResponse(e)};__internal_updateProps=e=>{let t={...e,options:this.#eI({...this.#ez,...e.options})};return this.#ew?.then(e=>e.ensureMounted()).then(e=>e.updateProps(t))};__internal_navigateWithError(e,t){return this.__internal_last_error=t,this.navigate(e)}#eW=()=>{let e=new URLSearchParams({[V]:window.location.href});return e_({base:this.#ez.signInUrl,searchParams:e},{stringify:!0})};#eK=()=>{let e;if(this.proxyUrl){let t=new URL(this.proxyUrl);e=new URL(`${t.pathname}/v1/client/sync`,t.origin)}else this.domain&&(e=new URL("/v1/client/sync",`https://${this.domain}`));return e?.searchParams.append("redirect_url",window.location.href),e?.toString()||""};#eH=()=>"true"!==eT(K)&&!!this.isSatellite&&!!this.#ef?.isSignedOut();#eV=()=>"production"!==this.#ev&&!this.isSatellite&&!!eT(V);#eG=async()=>{"development"===this.instanceType?await this.navigate(this.#eW()):"production"===this.instanceType&&await this.navigate(this.#eK())};#eJ=(e,t)=>{let a;try{a=new URL(e)}catch{throw Error(`${tz} The signInUrl needs to have a absolute url format.`)}a.origin===t&&function(){throw Error(`${tz} The signInUrl needs to be on a different origin than your satellite application.`)}()};#eZ=()=>{this.isSatellite&&("development"!==this.#ev||this.#ez.signInUrl||function(){throw Error(`${tz} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${tz} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#ez.signInUrl&&this.#eJ(this.#ez.signInUrl,window.location.origin))};#eq=async()=>{if(this.#ef=await nd.create(this,this.#ek,this.#ev,this.#eE),this.#eZ(),this.#eH())return void await this.#eG();if(this.#eV())return void await this.#eF();this.#eS=(()=>{if(!s())return{onPageFocus:e5};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:t=>{e.push(t)}}})(),"undefined"!=typeof BroadcastChannel&&(this.#ey=new BroadcastChannel("clerk")),this.#e$();let e=function(e=window.location.hostname){if(!e)return!1;let t=ex.get(e);void 0===t&&(t=eo.some(t=>e.startsWith("accounts.")&&e.endsWith(t))||el.some(t=>e.endsWith(t)&&!e.endsWith(".clerk"+t)),ex.set(e,t));return t}(window?.location.hostname),t="development"===this.#ev&&!e,a=0,r=0;for(;r<2;){r++;try{var n;let e=rn.getInstance().fetch({touch:t}).then(e=>this.updateEnvironment(e)).catch(()=>{++a;let e=t_.getItem(tv,null);e&&this.updateEnvironment(new rn(e))}),r=async()=>aM.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(async e=>{if(q(e))throw e;++a;let t=this.#ef?.getSessionCookie(),r=function(e){let t;try{t=new rH({jwt:e||"",object:"token",id:void 0})}catch{t=null}if(aM.clearInstance(),!t?.jwt)return aM.getOrCreateInstance({object:"client",last_active_session_id:null,id:"client_init",sessions:[]});let{sessionId:a,userId:r,orgId:n,orgRole:i,orgPermissions:s,orgSlug:o,factorVerificationAge:l}=(e=>{let t,a,r,n,i=e.fva??null,s=e.sts??null;if(2===e.v){if(e.o){t=e.o?.id,r=e.o?.slg,e.o?.rol&&(a=`org:${e.o?.rol}`);let{org:i}=rE(e.fea),{permissions:s,featurePermissionMap:o}=(({per:e,fpm:t})=>{if(!e||!t)return{permissions:[],featurePermissionMap:[]};let a=e.split(",").map(e=>e.trim());return{permissions:a,featurePermissionMap:t.split(",").map(e=>Number.parseInt(e.trim(),10)).map(e=>e.toString(2).padStart(a.length,"0").split("").map(e=>Number.parseInt(e,10)).reverse()).filter(Boolean)}})({per:e.o?.per,fpm:e.o?.fpm});n=function({features:e,permissions:t,featurePermissionMap:a}){if(!e||!t||!a)return[];let r=[];for(let n=0;n<e.length;n++){let i=e[n];if(n>=a.length)continue;let s=a[n];if(s)for(let e=0;e<s.length;e++)1===s[e]&&r.push(`org:${i}:${t[e]}`)}return r}({features:i,featurePermissionMap:o,permissions:s})}}else t=e.org_id,a=e.org_role,r=e.org_slug,n=e.org_permissions;return{sessionClaims:e,sessionId:e.sid,sessionStatus:s,actor:e.act,userId:e.sub,orgId:t,orgRole:a,orgSlug:r,orgPermissions:n,factorVerificationAge:i}})(t.jwt.claims),c={object:"client",last_active_session_id:a,id:"client_init",sessions:[{object:"session",id:a,status:"active",last_active_organization_id:n||null,last_active_token:{id:void 0,object:"token",jwt:e},factor_verification_age:l||null,public_user_data:{user_id:r},user:{object:"user",id:r,organization_memberships:n&&o&&i?[{object:"organization_membership",id:n,role:i,permissions:s||[],organization:{object:"organization",id:n,name:o,slug:o,members_count:1,max_allowed_memberships:1}}]:[]}}]};return aM.getOrCreateInstance(c)}(t);return this.updateClient(r),this.#ef?.stopPollingForToken(),await this.session?.getToken({skipCache:!0}).catch(()=>null).finally(()=>{this.#ef?.startPollingForToken()}),null}),[,i]=await (n=[e,r()],Promise.all(Array.from(n).map(e=>e.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e})))));if("rejected"===i.status){let e=i.reason;if(th(e,"requires_captcha"))await r();else throw e}if(this.#ef?.setClientUatCookieForDevelopmentInstances(),await this.#eY())return;break}catch(e){if(th(e,"dev_browser_unauthenticated"))await this.#ef.handleUnauthenticatedDevBrowser();else if(!u())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${tz} Something went wrong initializing Clerk.`)}()}this.#eb=new nh(this),this.#eb.start(),this.#eQ(),this.#eX(),this.#e1(),this.#eE.emit(f,a>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#eO=async()=>{let e,t,a=this.shouldFallbackToCachedResources()?1:void 0,r=0;try{[e,t]=await Promise.all([rn.getInstance().fetch({touch:!1,fetchMaxTries:a}),aM.getOrCreateInstance().fetch({fetchMaxTries:a})])}catch(a){if(U(a)&&"network_error"===a.code&&this.shouldFallbackToCachedResources()){let a=await this.__internal_getCachedResources?.();e=new rn(a?.environment),aM.clearInstance(),t=aM.getOrCreateInstance(a?.client),++r}else throw a}this.updateClient(t),this.updateEnvironment(e),this.#eE.emit(f,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,t]=await Promise.all([rn.getInstance().fetch({touch:!1,fetchMaxTries:1}),aM.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(t),this.updateEnvironment(e),this.#eP()};#eL=e=>{if(e.lastActiveSessionId){let t=e.signedInSessions.find(t=>t.id===e.lastActiveSessionId);if(t)return t}return e.signedInSessions[0]||null};#e$=()=>{s()&&(this.#eS?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#eA>Date.now())&&(this.#eA=Date.now()+5e3,this.#ez.touchSession&&this.#eM(this.session))}),this.#ey?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),rt.on(a4,()=>{this.#ey?.postMessage({type:"signout"})}),rt.on(a7,()=>{t_.setItem(tv,this.environment?.__internal_toSnapshot(),864e5)}))};#eM=async e=>{if(!e)return Promise.resolve();await e.touch().catch(e=>{q(e)&&this.handleUnauthenticated()})};#eP=()=>{if(this.client)for(let e of this.#ej)e({client:this.client,session:this.session,user:this.user,organization:this.organization})};#eB=()=>{for(let e of this.#e_)e()};#eU=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#eP()};#e0=()=>(this.session?.user.organizationMemberships||[]).map(e=>e.organization).find(e=>e.id===this.session?.lastActiveOrganizationId)||null;#eC=e=>{this.session=e||null,this.organization=this.#e0(),this.user=this.session?this.session.user:null};#eR=e=>this.client?.signedInSessions.find(t=>t.id===e)||null;#eX=()=>{this.addListener(({session:e})=>{e?.actor&&this.#ew?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#e1=()=>{this.#ez.__internal_keyless_claimKeylessApplicationUrl&&this.#ew?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#ez.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#ez.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#ez.__internal_keyless_dismissPrompt}})})};#eD=(e,t,a)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#ez[e]||this.environment.displayConfig[e];this.#eT()&&(r=this.#ez.signInUrl);let n=new eP(this.#ez,t).toSearchParams(),i=new URLSearchParams(a||{}),s=e_({base:r,hashPath:this.#eT()&&"signUpUrl"===e?"/create":"",hashSearchParams:[i,n]},{stringify:!0});return this.buildUrlWithAuth(s)};assertComponentsReady(e){if(!e)throw Error("Clerk was not loaded with Ui components")}#eY=async()=>{var e;let t,a,r,n,i=new URLSearchParams(window.location.search).get("redirect_url"),s="production"===this.instanceType,o=null!==i&&(e=this.frontendApi,a=(t=new URL(i,ew)).pathname,r=eI.includes(a)||eC.includes(a),e===t.host&&r);if(s||!o)return!1;let l=this.session,c=this.#ez.signInUrl||this.environment?.displayConfig.signInUrl,u=c&&window.location.href.startsWith(c),d=this.#ez.signUpUrl||this.environment?.displayConfig.signUpUrl,h=d&&window.location.href.startsWith(d);return n=new URL(i,ew),(!eI.includes(n.pathname)||!!l||!u&&!h)&&(await this.navigate(this.buildUrlWithAuth(i)),!0)};#eI=e=>({...n_,...e,allowedRedirectOrigins:function(e,t,a){if(Array.isArray(e)&&e.length)return e;let r=[];return"undefined"!=typeof window&&window.location&&r.push(window.location.origin),r.push(`https://${ej(t)}`),r.push(`https://*.${ej(t)}`),"development"===a&&r.push(`https://${t}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)});#eQ=()=>{try{eU(K),eU(eq),eU(H),eU("__clerk_handshake"),eU("__clerk_handshake_nonce"),eU("__clerk_help")}catch{}};get #eN(){let e=eW;return this.#ez.allowedRedirectProtocols&&(e=e.concat(this.#ez.allowedRedirectProtocols)),e}}})();var s=exports;for(var o in i)s[o]=i[o];i.__esModule&&Object.defineProperty(s,"__esModule",{value:!0})})();
60
+ (This notice only appears in development)`,eD={cannotRenderComponentWhenSessionExists:"The <SignUp/> and <SignIn/> components cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the Home URL instead.",cannotRenderSignUpComponentWhenSessionExists:"The <SignUp/> component cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the value set in `afterSignUp` URL instead.",cannotRenderSignUpComponentWhenTaskExists:"The <SignUp/> component cannot render when a user has a pending task, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the task instead.",cannotRenderComponentWhenTaskDoesNotExist:"<TaskChooseOrganization/> cannot render unless a session task is pending. Clerk is redirecting to the value set in `redirectUrlComplete` instead.",cannotRenderSignInComponentWhenSessionExists:"The <SignIn/> component cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the `afterSignIn` URL instead.",cannotRenderSignInComponentWhenTaskExists:"The <SignIn/> component cannot render when a user has a pending task, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the task instead.",cannotRenderComponentWhenUserDoesNotExist:"<UserProfile/> cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotRenderComponentWhenOrgDoesNotExist:"<OrganizationProfile/> cannot render unless an organization is active. Since no organization is currently active, this is no-op.",cannotRenderAnyOrganizationComponent:e=>eN(`The <${e}/> cannot be rendered when the feature is turned off. Visit 'dashboard.clerk.com' to enable the feature. Since the feature is turned off, this is no-op.`),cannotRenderAnyBillingComponent:e=>eN(`The <${e}/> component cannot be rendered when billing is disabled. Visit 'https://dashboard.clerk.com/last-active?path=billing/settings' to follow the necessary steps to enable billing. Since billing is disabled, this is no-op.`),cannotOpenUserProfile:"The UserProfile modal cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotOpenCheckout:"The Checkout drawer cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotOpenSignInOrSignUp:"The SignIn or SignUp modals do not render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, this is no-op.",cannotRenderAPIKeysComponent:"The <APIKeys/> component cannot be rendered when API keys is disabled. Since API keys is disabled, this is no-op.",cannotRenderAPIKeysComponentForOrgWhenUnauthorized:"The <APIKeys/> component cannot be rendered for an organization unless a user has the required permissions. Since the user does not have the necessary permissions, this is no-op.",cannotRenderAPIKeysComponentForUserWhenDisabled:"The <APIKeys/> component cannot be rendered when user API keys are disabled. Since user API keys are disabled, this is no-op.",cannotRenderAPIKeysComponentForOrgWhenDisabled:"The <APIKeys/> component cannot be rendered when organization API keys are disabled. Since organization API keys are disabled, this is no-op."};for(let e of Object.keys(eD)){let t=eD[e];"function"!=typeof t&&(eD[e]=eN(t))}let eF="clerk:beforeunload",eL=["http:","https:","wails:","chrome-extension:"];function eW(e){let t=new URL(e,window.location.href);window.dispatchEvent(new CustomEvent(eF)),window.location.href=t.href}function eK(e){return/^http(s)?:\/\//.test(e||"")}function eH(e){return e.startsWith("/")}var eV=class{#c;#U=864e5;constructor(e){this.#c=e}isEventThrottled(e){let t=Date.now(),a=this.#M(e),r=this.#c.getItem(a);return!!r&&!(t-r>this.#U)||(this.#c.setItem(a,t),!1)}#M(e){let{sk:t,pk:a,payload:r,...n}=e,i={...r,...n};return JSON.stringify(Object.keys({...r,...n}).sort().map(e=>i[e]))}},eG=class{#R="clerk_telemetry_throttler";getItem(e){return this.#B()[e]}setItem(e,t){try{let a=this.#B();a[e]=t,localStorage.setItem(this.#R,JSON.stringify(a))}catch(e){e instanceof DOMException&&("QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)&&localStorage.length>0&&localStorage.removeItem(this.#R)}}removeItem(e){try{let t=this.#B();delete t[e],localStorage.setItem(this.#R,JSON.stringify(t))}catch{}}#B(){try{let e=localStorage.getItem(this.#R);if(!e)return{};return JSON.parse(e)}catch{return{}}}static isSupported(){return"undefined"!=typeof window&&!!window.localStorage}},eJ=class{#c=new Map;#N=1e4;getItem(e){return this.#c.size>this.#N?void this.#c.clear():this.#c.get(e)}setItem(e,t){this.#c.set(e,t)}removeItem(e){this.#c.delete(e)}};let eZ=new Set(["error","warn","info","debug","trace"]);var e$=class{#D;#F;#L={};#W=[];#K=null;constructor(e){this.#D={maxBufferSize:e.maxBufferSize??5,samplingRate:e.samplingRate??1,perEventSampling:e.perEventSampling??!0,disabled:e.disabled??!1,debug:e.debug??!1,endpoint:"https://clerk-telemetry.com"},e.clerkVersion||"undefined"!=typeof window?this.#L.clerkVersion=e.clerkVersion??"":this.#L.clerkVersion="",this.#L.sdk=e.sdk,this.#L.sdkVersion=e.sdkVersion,this.#L.publishableKey=e.publishableKey??"";const t=eh(e.publishableKey);t&&(this.#L.instanceType=t.instanceType),e.secretKey&&(this.#L.secretKey=e.secretKey.substring(0,16)),this.#F=new eV(eG.isSupported()?new eG:new eJ)}get isEnabled(){return!("development"!==this.#L.instanceType||this.#D.disabled||"undefined"!=typeof process&&process.env&&en(process.env.CLERK_TELEMETRY_DISABLED)||"undefined"!=typeof window&&window?.navigator?.webdriver)}get isDebug(){return this.#D.debug||"undefined"!=typeof process&&process.env&&en(process.env.CLERK_TELEMETRY_DEBUG)}record(e){try{let t=this.#H(e.event,e.payload);if(this.#V(t.event,t),!this.#G(t,e.eventSamplingRate))return;this.#W.push({kind:"event",value:t}),this.#J()}catch(e){console.error("[clerk/telemetry] Error recording telemetry event",e)}}recordLog(e){try{if(!this.#Z(e))return;let t="string"==typeof e?.level&&eZ.has(e.level),a="string"==typeof e?.message&&e.message.trim().length>0,r=null,n=e?.timestamp;if("number"==typeof n||"string"==typeof n){let e=new Date(n);Number.isNaN(e.getTime())||(r=e)}if(!t||!a||null===r){this.isDebug&&"undefined"!=typeof console&&console.warn("[clerk/telemetry] Dropping invalid telemetry log entry",{levelIsValid:t,messageIsValid:a,timestampIsValid:null!==r});return}let i=this.#$(),s={sdk:i.name,sdkv:i.version,cv:this.#L.clerkVersion??"",lvl:e.level,msg:e.message,ts:r.toISOString(),pk:this.#L.publishableKey||null,payload:this.#Y(e.context)};this.#W.push({kind:"log",value:s}),this.#J()}catch(e){console.error("[clerk/telemetry] Error recording telemetry log entry",e)}}#G(e,t){return this.isEnabled&&!this.isDebug&&this.#Q(e,t)}#Z(e){return!0}#Q(e,t){let a=Math.random();return!!(a<=this.#D.samplingRate&&(!1===this.#D.perEventSampling||void 0===t||a<=t))&&!this.#F.isEventThrottled(e)}#J(){if("undefined"==typeof window)return void this.#X();if(this.#W.length>=this.#D.maxBufferSize){this.#K&&("undefined"!=typeof cancelIdleCallback?cancelIdleCallback(Number(this.#K)):clearTimeout(Number(this.#K))),this.#X();return}this.#K||("requestIdleCallback"in window?this.#K=requestIdleCallback(()=>{this.#X(),this.#K=null}):this.#K=setTimeout(()=>{this.#X(),this.#K=null},0))}#X(){let e=[...this.#W];if(this.#W=[],this.#K=null,0===e.length)return;let t=e.filter(e=>"event"===e.kind).map(e=>e.value),a=e.filter(e=>"log"===e.kind).map(e=>e.value);t.length>0&&fetch(new URL("/v1/event",this.#D.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({events:t})}).catch(()=>void 0),a.length>0&&fetch(new URL("/v1/logs",this.#D.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({logs:a})}).catch(()=>void 0)}#V(e,t){this.isDebug&&(void 0!==console.groupCollapsed?(console.groupCollapsed("[clerk/telemetry]",e),console.log(t),console.groupEnd()):console.log("[clerk/telemetry]",e,t))}#$(){let e={name:this.#L.sdk,version:this.#L.sdkVersion};if("undefined"!=typeof window){let t=window;if(t.Clerk){let a=t.Clerk;if("object"==typeof a&&null!==a&&"constructor"in a&&"function"==typeof a.constructor&&a.constructor.sdkMetadata){let{name:t,version:r}=a.constructor.sdkMetadata;void 0!==t&&(e.name=t),void 0!==r&&(e.version=r)}}}return e}#H(e,t){let a=this.#$();return{event:e,cv:this.#L.clerkVersion??"",it:this.#L.instanceType??"",sdk:a.name,sdkv:a.version,...this.#L.publishableKey?{pk:this.#L.publishableKey}:{},...this.#L.secretKey?{sk:this.#L.secretKey}:{},payload:t}}#Y(e){if(null==e||"object"!=typeof e)return null;try{let t=JSON.parse(JSON.stringify(e));if(t&&"object"==typeof t&&!Array.isArray(t))return t;return null}catch{return null}}};let eY="COMPONENT_MOUNTED",eQ=new Set(["SignIn","SignUp"]);function eX(e){return function(t,a,r){return{event:e,eventSamplingRate:e===eY?eQ.has(t)?1:.1:.1,payload:{component:t,appearanceProp:!!a?.appearance,theme:!!a?.appearance?.theme,elements:!!a?.appearance?.elements,variables:!!a?.appearance?.variables,...r}}}}function e1(e,t,a){return eX(eY)(e,t,a)}function e0(e,t,a){return eX("COMPONENT_OPENED")(e,t,a)}function e2(e){return"string"==typeof e?e:"object"==typeof e&&null!==e&&"name"in e&&"string"==typeof e.name?e.name:void 0}function e9(e,t,a){return"function"==typeof e?e(t):void 0!==e?e:void 0!==a?a:void 0}let e3=(...e)=>{},e5=!1,e6=null,e8=!1,e4=[];function e7(e,t,a,r){e5&&(e4.push({level:e,message:t,context:a,source:r,ts:Date.now()}),e4.length>200&&e4.shift())}async function te(e){try{if(!e5||e6)return;let{getDebugLogger:t}=await Promise.resolve().then(n.bind(n,9854)),a=await t({logLevel:e?.logLevel,telemetryCollector:e?.telemetryCollector});if(a&&(e6=a)&&0!==e4.length){for(let e of e4){let t={...e.context||{},__preInit:!0,__preInitTs:e.ts};switch(e.level){case"error":e6.error(e.message,t,e.source);break;case"warn":e6.warn(e.message,t,e.source);break;case"info":e6.info(e.message,t,e.source);break;case"debug":e6.debug(e.message,t,e.source)}}e4.length=0}}catch(e){try{console.debug?.("Debug logger initialization failed",e)}catch{}return}}let tt={debug(e,t,a){e6?e6.debug(e,t,a):e7("debug",e,t,a)},error(e,t,a){e6?e6.error(e,t,a):e7("error",e,t,a)},info(e,t,a){e6?e6.info(e,t,a):e7("info",e,t,a)},warn(e,t,a){e6?e6.warn(e,t,a):e7("warn",e,t,a)}},ta={initialDelay:125,maxDelayBetweenRetries:0,factor:2,shouldRetry:(e,t)=>t<5,retryImmediately:!1,jitter:!0},tr=async e=>new Promise(t=>setTimeout(t,e)),tn=(e,t)=>t?e*(1+Math.random()):e,ti=async(e,t={})=>{var a;let r,n=0,{shouldRetry:i,initialDelay:s,maxDelayBetweenRetries:o,factor:l,retryImmediately:c,jitter:u,onBeforeRetry:d}={...ta,...t},h=(a={initialDelay:s,maxDelayBetweenRetries:o,factor:l,jitter:u},r=0,async()=>{let e;await tr((e=tn(e=a.initialDelay*Math.pow(a.factor,r),a.jitter),Math.min(a.maxDelayBetweenRetries||e,e))),r++});for(;;)try{return await e()}catch(e){if(!i(e,++n))throw e;d&&await d(n),c&&1===n?await tr(tn(100,u)):await h()}},ts=async e=>ti(e,{initialDelay:100,shouldRetry:(e,t)=>t<=3,retryImmediately:!0,factor:2});class to{#ee={"@zxcvbn-ts/core":()=>ts(()=>Promise.resolve().then(n.bind(n,7010))),"@zxcvbn-ts/language-common":()=>ts(()=>Promise.resolve().then(n.bind(n,655))),"@base-org/account":()=>ts(()=>Promise.resolve().then(n.bind(n,1965))),"@coinbase/wallet-sdk":()=>ts(()=>Promise.resolve().then(n.bind(n,2804))),"@stripe/stripe-js":()=>ts(()=>Promise.resolve().then(n.bind(n,5608)))};import(e){return this.#ee[e]?this.#ee[e]():Promise.resolve(void 0)}}let tl=(e=!1)=>{let t,a;if(!e)return{track:async e=>{await e()},isUnloading:()=>!1};let r=(t=!1,a=()=>t=!0,{startListening:()=>{window.addEventListener("beforeunload",a),window.addEventListener(eF,a)},stopListening:()=>{window.removeEventListener("beforeunload",a),window.removeEventListener(eF,a)},isUnloading:()=>t});return{track:async e=>{r.startListening(),await e(),r.stopListening()},isUnloading:r.isUnloading}},tc=e=>({amount:e.amount,amountFormatted:e.amount_formatted,currency:e.currency,currencySymbol:e.currency_symbol}),tu=e=>{let t={grandTotal:tc(e.grand_total),subtotal:tc(e.subtotal),taxTotal:tc(e.tax_total)};return"past_due"in e&&(t.pastDue=e.past_due?tc(e.past_due):null),"credit"in e&&(t.credit=e.credit?tc(e.credit):null),"total_due_now"in e&&(t.totalDueNow=tc(e.total_due_now)),"total_due_after_free_trial"in e&&(t.totalDueAfterFreeTrial=e.total_due_after_free_trial?tc(e.total_due_after_free_trial):null),t};function td(e,t=""){return e.errors&&!!e.errors.find(e=>e.code===t)}let th=function({packageName:e,customMessages:t}){let a=e;function r(e,t){if(!t)return`${a}: ${e}`;let r=e;for(let a of e.matchAll(/{{([a-zA-Z0-9-_]+)}}/g)){let e=(t[a[1]]||"").toString();r=r.replace(`{{${a[1]}}}`,e)}return`${a}: ${r}`}let n={...j,...t};return{setPackageName({packageName:e}){return"string"==typeof e&&(a=e),this},setMessages({customMessages:e}){return Object.assign(n,e||{}),this},throwInvalidPublishableKeyError(e){throw Error(r(n.InvalidPublishableKeyErrorMessage,e))},throwInvalidProxyUrl(e){throw Error(r(n.InvalidProxyUrlErrorMessage,e))},throwMissingPublishableKeyError(){throw Error(r(n.MissingPublishableKeyErrorMessage))},throwMissingSecretKeyError(){throw Error(r(n.MissingSecretKeyErrorMessage))},throwMissingClerkProviderError(e){throw Error(r(n.MissingClerkProvider,e))},throw(e){throw Error(r(e))}}}({packageName:"@clerk/clerk-js"});function tm(e){return decodeURIComponent(globalThis.atob(e.replace(/_/g,"/").replace(/-/g,"+")).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""))}function tp(e){let t=(e||"").split("."),[a,r,n]=t;if(3!==t.length||!a||!r||!n)throw Error("JWT could not be decoded");let i=JSON.parse(tm(r)),s={__raw:e};return Object.keys(i).forEach(e=>{s[e]=i[e]}),{encoded:{header:a,payload:r,signature:n},header:JSON.parse(tm(a)),claims:s}}function tf(){if(!s())return null;try{let e=navigator?.language;if(!e||"string"!=typeof e||""===e.trim())return null;return e}catch{return null}}function tg(){return void 0!==globalThis.document}function tb(){if(!function(){if(!tg())return!1;try{return window.self!==window.top}catch{return!0}}())return!1;try{return window.top?.location.href,!1}catch{return!0}}var ty=class e{#et=[];#ea={metamask:"MetaMask",okx_wallet:"OKX Wallet"};static #er=null;constructor(){if("undefined"==typeof window)return;window.addEventListener("eip6963:announceProvider",this.#en),window.dispatchEvent(new Event("eip6963:requestProvider"))}static getInstance(){return e.#er||(e.#er=new e),e.#er}get=e=>{let t=this.#et.find(t=>t.info.name===this.#ea[e])?.provider;return void 0!==t?t:window.ethereum};#en=e=>{this.#et.some(t=>t.info.uuid===e.detail.info.uuid)||this.#et.push(e.detail)}};let tw=()=>(function(e){async function t(e){let{provider:t}=e,a=await d(t);if(!a)return"";let r=await a.request({method:"eth_requestAccounts"});return r&&r[0]||""}async function a(e){let{identifier:t,nonce:a,provider:r}=e,n=await d(r);return n?await n.request({method:"personal_sign",params:[`0x${a.split("").map(e=>e.charCodeAt(0).toString(16).padStart(2,"0")).join("")}`,t]}):""}async function r(){return await t({provider:"metamask"})}async function n(){return await t({provider:"coinbase_wallet"})}async function i(){return await t({provider:"okx_wallet"})}async function s(){return await t({provider:"base"})}async function o(e){return await a({...e,provider:"metamask"})}async function l(e){return await a({...e,provider:"coinbase_wallet"})}async function c(e){return await a({...e,provider:"okx_wallet"})}async function u(e){return await a({...e,provider:"base"})}async function d(t){if("coinbase_wallet"===t){let t=await e.import("@coinbase/wallet-sdk");return t?t.createCoinbaseWalletSDK({preference:{options:"all"}}).getProvider():null}if("base"===t)try{let t=await e.import("@base-org/account");if(!t)return null;return t.createBaseAccountSDK({appName:"undefined"!=typeof window&&window.Clerk?.__internal_environment?.displayConfig?.applicationName||"undefined"!=typeof document&&document.title||"Web3 Application"}).getProvider()}catch{return null}return ty.getInstance().get(t)}return{getWeb3Identifier:t,generateWeb3Signature:a,getMetamaskIdentifier:r,getCoinbaseWalletIdentifier:n,getOKXWalletIdentifier:i,getBaseIdentifier:s,generateSignatureWithMetamask:o,generateSignatureWithCoinbaseWallet:l,generateSignatureWithOKXWallet:c,generateSignatureWithBase:u}})(new to),tk="environment",tv=JSON.stringify,tx=JSON.parse;class tj{static _key(e){return`__clerk_${e}`}static isExpired(e){return!!e.exp&&Date.now()>e.exp}static setItem(e,t,a){try{let r={value:t,...a&&{exp:Date.now()+a}};window.localStorage.setItem(this._key(e),tv(r))}catch{}}static getItem(e,t){try{let a=window.localStorage.getItem(this._key(e));if(!a)return t;let r=tx(a);if(!r)return t;if(this.isExpired(r))return this.removeItem(e),t;return r?.value??t}catch{return t}}static removeItem(e){try{window.localStorage.removeItem(this._key(e))}catch{}}}let t_="ClerkJS:";function tz(e=""){throw Error(`${t_} Something went wrong initializing Clerk in development mode.${e&&` ${e}`}`)}function tS(e){throw Error(`${t_} Something went wrong initializing Clerk during the ${e} flow. Please contact support.`)}function tA(e){throw Error(`${t_} You need to start a ${e} flow by calling ${e}.create() first.`)}function tE(e,t){throw Error(`${t_} Strategy "${t}" is not a valid strategy for ${e}.`)}function tI(e){throw Error(`${t_} You need to start a ${e} flow by calling ${e}.create({ identifier: 'your web3 wallet address' }) first`)}function tC(e=""){throw Error(`${t_} Missing '${e}' option`)}function tP(e,t){throw Error(`${t_} Response: ${e||0} not supported yet.
61
+ For more information contact us at ${t}`)}function tq(e){throw Error(`${t_} Missing publicKey. When calling 'navigator.credentials.${e}()' it is required to pass a publicKey object.`)}async function tO(e="",t){let{async:a,defer:r,beforeLoad:n,crossOrigin:i,nonce:s}=t||{};return ti(()=>new Promise((t,o)=>{e||o(Error("loadScript cannot be called without a src")),document&&document.body||o(Error("loadScript cannot be called when document does not exist"));let l=document.createElement("script");i&&l.setAttribute("crossorigin",i),l.async=a||!1,l.defer=r||!1,l.addEventListener("load",()=>{l.remove(),t(l)}),l.addEventListener("error",t=>{l.remove(),o(t.error??Error(`failed to load script: ${e}`))}),l.src=e,l.nonce=s,n?.(l),document.body.appendChild(l)}),{shouldRetry:(e,t)=>t<=5})}async function tT(e){return window.turnstile||await tU(e).catch(()=>{throw{captchaError:"captcha_script_failed_to_load"}}),window.turnstile}async function tU(e){try{return await tO("https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",{defer:!0,nonce:e})}catch(e){throw console.warn("Clerk: Failed to load the CAPTCHA script from Cloudflare. If you see a CSP error in your browser, please add the necessary CSP rules to your app. Visit https://clerk.com/docs/security/clerk-csp for more information."),e}}function tM(e){try{let t=e.getAttribute("data-cl-theme")||void 0,a=e.getAttribute("data-cl-language")||void 0,r=e.getAttribute("data-cl-size")||void 0;return{theme:t,language:a,size:r}}catch{return{theme:void 0,language:void 0,size:void 0}}}let tR=async e=>{let t,a,r,n,{siteKey:i,widgetType:s,invisibleSiteKey:o,nonce:l}=e,{modalContainerQuerySelector:c,modalWrapperQuerySelector:u,closeModal:d,openModal:h}=e,m=await tT(l),p=[],f="",g="",b=i,y=0,w=null,k="invisible";if(c&&u){w=s,n=c,k="modal";try{await h?.()}catch{throw{captchaError:"modal_component_not_ready"}}let e=await new Promise(e=>{if(document.querySelector(c))return e(document.querySelector(c));let t=new MutationObserver(()=>{document.querySelector(c)&&(t.disconnect(),e(document.querySelector(c)))});t.observe(document.body,{childList:!0,subtree:!0})});if(e){let{theme:n,language:i,size:s}=tM(e);t=n,r=i,a=s}}if(!n&&"smart"===s){let e=document.getElementById(V);if(e){k="smart",w="smart",n=`#${V}`,e.style.maxHeight="0";let{theme:i,language:s,size:o}=tM(e);t=i,r=s,a=o}else console.error("Cannot initialize Smart CAPTCHA widget because the `clerk-captcha` DOM element was not found; falling back to Invisible CAPTCHA widget. If you are using a custom flow, visit https://clerk.com/docs/guides/development/custom-flows/bot-sign-up-protection for instructions")}if(!n){k="invisible",b=o,w="invisible",n=`.${G}`;let e=document.createElement("div");e.classList.add(G),e.style.display="none",document.body.appendChild(e)}let v=async()=>new Promise((i,s)=>{try{let o=m.render(n,{sitekey:b,appearance:"interaction-only",theme:t||"auto",size:a||"normal",language:r||"auto",action:e.action,retry:"never","refresh-expired":"auto",callback:function(e){d?.(),i([e,o])},"before-interactive-callback":()=>{if(u){let e=document.querySelector(u);e?.style.setProperty("visibility","visible"),e?.style.setProperty("pointer-events","all")}else{let e=document.getElementById(V);e&&(e.style.maxHeight="unset",e.style.minHeight="compact"===a?"140px":"68px",e.style.marginBottom="1.5rem")}},"error-callback":function(e){var t;(p.push(e),y<2&&(t=e.toString(),["crashed","undefined_error","102","103","104","106","110600","300","600"].find(e=>t.startsWith(e))))?setTimeout(()=>{m.reset(o),y++},250):s([p.join(","),o])},"unsupported-callback":function(){return s(["This browser is not supported by the CAPTCHA.",o]),!0}})}catch(e){s([e,void 0])}});try{[f,g]=await v(),m.remove(g)}catch([e,t]){throw t&&m.remove(t),{captchaError:e}}finally{if("modal"===k&&d?.(),"invisible"===k){let e=document.querySelector(`.${G}`);e&&document.body.removeChild(e)}if("smart"===k){let e=document.getElementById(V);e&&(e.style.maxHeight="0",e.style.minHeight="unset",e.style.marginBottom="unset")}}return{captchaToken:f,captchaWidgetType:w}},tB=e=>{let t=e.__internal_environment,a=t?t.displayConfig.captchaProvider:"turnstile",r=e.__internal_getOption?.("nonce");return{captchaSiteKey:t?t.displayConfig.captchaPublicKey:null,captchaWidgetType:t?t.displayConfig.captchaWidgetType:null,captchaProvider:a,captchaPublicKeyInvisible:t?t.displayConfig.captchaPublicKeyInvisible:null,canUseCaptcha:t?t.userSettings.signUp.captcha_enabled&&e.isStandardBrowser:null,nonce:r||void 0}};class tN{clerk;constructor(e){this.clerk=e}async invisible(e){let{captchaSiteKey:t,canUseCaptcha:a,captchaPublicKeyInvisible:r,nonce:n}=tB(this.clerk);return a&&t&&r?{...await tR({action:e?.action,captchaProvider:"turnstile",invisibleSiteKey:r,nonce:e?.nonce||n||void 0,siteKey:r,widgetType:"invisible"}).catch(e=>e.captchaError?{captchaError:e.captchaError}:{captchaError:e?.message||e||"unexpected_captcha_error"}),captchaAction:e?.action}:{captchaError:"captcha_unavailable",captchaAction:e?.action}}async managedOrInvisible(e){let{captchaSiteKey:t,canUseCaptcha:a,captchaWidgetType:r,captchaProvider:n,captchaPublicKeyInvisible:i,nonce:s}=tB(this.clerk);if(a&&t&&i){let a=await tR({captchaProvider:n,invisibleSiteKey:i,nonce:s||void 0,siteKey:t,widgetType:r,...e}).catch(t=>t.captchaError?{captchaError:t.captchaError}:e?.action==="verify"?{captchaError:t?.message||t||"unexpected_captcha_error"}:void 0);return e?.action==="verify"?{...a,captchaAction:"verify"}:a}return e?.action==="verify"?{captchaError:"captcha_unavailable",captchaAction:e?.action}:{}}async managedInModal(e){return this.managedOrInvisible({modalWrapperQuerySelector:"#cl-modal-captcha-wrapper",modalContainerQuerySelector:"#cl-modal-captcha-container",openModal:()=>this.clerk.__internal_openBlankCaptchaModal(),closeModal:()=>this.clerk.__internal_closeBlankCaptchaModal(),action:e?.action})}}class tD{client;CaptchaChallengeImpl;static instance;inflightException=null;captchaRetryCount=0;MAX_RETRY_ATTEMPTS=3;static getInstance(){return tD.instance||(tD.instance=new tD(aU,tN)),tD.instance}constructor(e,t){this.client=e,this.CaptchaChallengeImpl=t}async execute(e,t){if(this.captchaAttemptsExceeded())throw new A("Security verification failed. Please try again by refreshing the page, clearing your browser cookies, or using a different web browser.",{code:"captcha_client_attempts_exceeded"});try{return this.inflightException&&await this.inflightException,await t()}catch(r){let a;if(!O(r)||T(r)&&"network_error"===r.code||r.errors[0]?.code!=="requires_captcha")throw r;if(this.inflightException)return await this.inflightException,await t();this.inflightException=new Promise(e=>a=e);try{let t=await this.managedChallenge(e);t?.captchaError!=="modal_component_not_ready"&&(await this.client.getOrCreateInstance().__internal_sendCaptchaToken(t),this.captchaRetryCount=0)}catch(e){throw this.captchaRetryCount++,e}finally{a(),this.inflightException=null}return await t()}}managedChallenge(e){return new this.CaptchaChallengeImpl(e).managedInModal({action:"verify"})}captchaAttemptsExceeded=()=>this.captchaRetryCount>=this.MAX_RETRY_ATTEMPTS}class tF{static clerk;id;pathRoot="";static get fapiClient(){return tF.clerk.getFapiClient()}async reload(e){let{rotatingTokenNonce:t}=e||{};return this._baseGet({forceUpdateClient:!0,rotatingTokenNonce:t})}isNew(){return!this.id}static async _fetch(e,t={}){return tD.getInstance().execute(this.clerk,()=>this._baseFetch(e,t))}static async _baseFetch(e,t={}){let a;tF.fapiClient||function(){throw Error(`${t_} Missing FAPI client in resources.`)}();let{fetchMaxTries:r}=t;try{a=await tF.fapiClient.request(e,{fetchMaxTries:r})}catch(t){if(this.shouldRethrowOfflineNetworkErrors())throw new A(t?.message||t,{code:"network_error"});if(!u())return tt.warn("Network request failed while offline, returning null",{method:e.method,path:e.path},"baseResource"),null;throw t}let{payload:n,status:i,statusText:s,headers:o}=a;if(o){let e=o.get("x-country");this.clerk.__internal_setCountry(e?e.toLowerCase():null)}if(("GET"!==e.method||t.forceUpdateClient)&&this._updateClient(n),i>=200&&i<=299)return n;if(i>=400){let e=n?.errors,t=e?.[0]?.long_message,a=e?.[0]?.code;401===i&&"requires_captcha"!==a&&await tF.clerk.handleUnauthenticated(),function(e,t){var a;if(!t||!t[0])return;let r=t[0],n=r.long_message;if("origin_invalid"===r.code&&((a=tF.clerk.publishableKey).startsWith("live_")||a.startsWith("pk_live_"))){let a=tF.clerk.frontendApi.replace("clerk.","");throw new v(`Clerk: Production Keys are only allowed for domain "${a}".
62
+ API Error: ${n}`,{data:t,status:e})}}(i,e);let r={data:e,status:i};if(429===i&&o){let e=o.get("retry-after");if(e){let t=parseInt(e,10);isNaN(t)||(r.retryAfter=t)}}throw new v(t||s,r)}return null}static _updateClient(e){if(!e)return;let t=e.client||e.meta?.client;t&&tF.clerk&&tF.clerk.updateClient(aU.getOrCreateInstance().fromJSON(t))}path(e){let t=this.pathRoot;if(this.isNew())return t;let a=t.replace(/[^/]$/,"$&/")+encodeURIComponent(this.id);return e?a.replace(/[^/]$/,"$&/")+encodeURIComponent(e):a}withDefault(e,t){return e??t}async _baseGet(e={}){let t=await tF._fetch({method:"GET",path:this.path(),rotatingTokenNonce:e.rotatingTokenNonce},e);return this.fromJSON(t?.response||t)}async _baseMutate(e){let{action:t,body:a,method:r,path:n}=e,i=await tF._fetch({method:r,path:n||this.path(t),body:a});return this.fromJSON(i?.response||i)}async _baseMutateBypass(e){let{action:t,body:a,method:r,path:n}=e,i=await tF._baseFetch({method:r,path:n||this.path(t),body:a});return this.fromJSON(i?.response||i)}async _basePost(e={}){return this._baseMutate({...e,method:"POST"})}async _basePostBypass(e={}){return this._baseMutateBypass({...e,method:"POST"})}async _basePut(e={}){return this._baseMutate({...e,method:"PUT"})}async _basePatch(e={}){return this._baseMutate({...e,method:"PATCH"})}async _baseDelete(e={}){await this._baseMutate({...e,method:"DELETE"})}static shouldRethrowOfflineNetworkErrors(){let e=tF.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}function tL(e){let t=new Date(e||new Date);return t instanceof Date&&!isNaN(t.getTime())?t:new Date}class tW extends tF{pathRoot="/api_keys";id;type;name;subject;scopes;claims;revoked;revocationReason;expired;expiration;createdBy;description;secret;lastUsedAt;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.type=e.type,this.name=e.name,this.subject=e.subject,this.scopes=e.scopes,this.claims=e.claims,this.revoked=e.revoked,this.revocationReason=e.revocation_reason,this.expired=e.expired,this.expiration=e.expiration?tL(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?tL(e.last_used_at):null,this.updatedAt=tL(e.updated_at),this.createdAt=tL(e.created_at)),this}__internal_toSnapshot(){return{object:"api_key",id:this.id,type:this.type,name:this.name,subject:this.subject,scopes:this.scopes,claims:this.claims,revoked:this.revoked,revocation_reason:this.revocationReason,expired:this.expired,expiration:this.expiration?this.expiration.getTime():null,created_by:this.createdBy,description:this.description,last_used_at:this.lastUsedAt?this.lastUsedAt.getTime():null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class tK extends tF{claimedAt=null;reverification=!1;singleSessionMode=!1;preferredChannels=null;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.claimedAt=this.withDefault(e.claimed_at?tL(e.claimed_at):null,this.claimedAt),this.reverification=this.withDefault(e.reverification,this.reverification),this.singleSessionMode=this.withDefault(e.single_session_mode,this.singleSessionMode),this.preferredChannels=this.withDefault(e.preferred_channels,this.preferredChannels)),this}__internal_toSnapshot(){return{claimed_at:this.claimedAt?this.claimedAt.getTime():null,id:this.id??"",object:"auth_config",reverification:this.reverification,single_session_mode:this.singleSessionMode}}}(b=y||(y={}))[b.None=0]="None",b[b.Mutable=1]="Mutable",b[b.Watching=2]="Watching",b[b.RecursedCheck=4]="RecursedCheck",b[b.Recursed=8]="Recursed",b[b.Dirty=16]="Dirty",b[b.Pending=32]="Pending";let tH=[],{link:tV,unlink:tG,propagate:tJ,checkDirty:tZ,endTracking:t$,startTracking:tY,shallowPropagate:tQ}=function({update:e,notify:t,unwatched:a}){let r=0;return{link:function(e,t){let a,n=t.depsTail;if(void 0!==n&&n.dep===e)return;if(4&t.flags&&void 0!==(a=void 0!==n?n.nextDep:t.deps)&&a.dep===e){a.version=r,t.depsTail=a;return}let i=e.subsTail;if(void 0!==i&&i.version===r&&i.sub===t)return;let s=t.depsTail=e.subsTail={version:r,dep:e,sub:t,prevDep:n,nextDep:a,prevSub:i,nextSub:void 0};void 0!==a&&(a.prevDep=s),void 0!==n?n.nextDep=s:t.deps=s,void 0!==i?i.nextSub=s:e.subs=s},unlink:n,propagate:function(e){let a,r=e.nextSub;t:for(;;){let n=e.sub,i=n.flags;if(3&i&&(60&i?12&i?4&i?!(48&i)&&function(e,t){let a=t.depsTail;if(void 0!==a){let r=t.deps;do{if(r===e)return!0;if(r===a)break;r=r.nextDep}while(void 0!==r)}return!1}(e,n)?(n.flags=40|i,i&=1):i=0:n.flags=-9&i|32:i=0:n.flags=32|i,2&i&&t(n),1&i)){let t=n.subs;if(void 0!==t){e=t,void 0!==t.nextSub&&(a={value:r,prev:a},r=e.nextSub);continue}}if(void 0!==(e=r)){r=e.nextSub;continue}for(;void 0!==a;)if(e=a.value,a=a.prev,void 0!==e){r=e.nextSub;continue t}break}},checkDirty:function(t,a){let r,n=0;t:for(;;){let s=t.dep,o=s.flags,l=!1;if(16&a.flags)l=!0;else if((17&o)==17){if(e(s)){let e=s.subs;void 0!==e.nextSub&&i(e),l=!0}}else if((33&o)==33){(void 0!==t.nextSub||void 0!==t.prevSub)&&(r={value:t,prev:r}),t=s.deps,a=s,++n;continue}if(!l&&void 0!==t.nextDep){t=t.nextDep;continue}for(;n;){--n;let s=a.subs,o=void 0!==s.nextSub;if(o?(t=r.value,r=r.prev):t=s,l){if(e(a)){o&&i(s),a=t.sub;continue}}else a.flags&=-33;if(a=t.sub,void 0!==t.nextDep){t=t.nextDep;continue t}l=!1}return l}},endTracking:function(e){let t=e.depsTail,a=void 0!==t?t.nextDep:e.deps;for(;void 0!==a;)a=n(a,e);e.flags&=-5},startTracking:function(e){++r,e.depsTail=void 0,e.flags=-57&e.flags|4},shallowPropagate:i};function n(e,t=e.sub){let r=e.dep,i=e.prevDep,s=e.nextDep,o=e.nextSub,l=e.prevSub;return void 0!==s?s.prevDep=i:t.depsTail=i,void 0!==i?i.nextDep=s:t.deps=s,void 0!==o?o.prevSub=l:r.subsTail=l,void 0!==l?l.nextSub=o:void 0===(r.subs=o)&&a(r),s}function i(e){do{let a=e.sub,r=e.nextSub,n=a.flags;(48&n)==32&&(a.flags=16|n,2&n&&t(a)),e=r}while(void 0!==e)}}({update:e=>"getter"in e?t6(e):t8(e,e.value),notify:function e(t){let a=t.flags;if(!(64&a)){t.flags=64|a;let r=t.subs;void 0!==r?e(r.sub):tH[t0++]=t}},unwatched(e){if("getter"in e){let t=e.deps;if(void 0!==t){e.flags=17;do t=tG(t,e);while(void 0!==t)}}else"previousValue"in e||at.call(e)}}),tX=0,t1=0,t0=0;function t2(t){let a=e;return e=t,a}function t9(e){return ae.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function t3(e){return t7.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function t5(a){let r={fn:a,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?tV(r,e):void 0!==t&&tV(r,t);let n=t2(r);try{r.fn()}finally{t2(n)}return at.bind(r)}function t6(e){let t=t2(e);tY(e);try{let t=e.value;return t!==(e.value=e.getter(t))}finally{t2(t),t$(e)}}function t8(e,t){return e.flags=1,e.previousValue!==(e.previousValue=t)}function t4(){for(;t1<t0;){let e=tH[t1];tH[t1++]=void 0,function e(t,a){if(16&a||32&a&&tZ(t.deps,t)){let e=t2(t);tY(t);try{t.fn()}finally{t2(e),t$(t)}return}32&a&&(t.flags=-33&a);let r=t.deps;for(;void 0!==r;){let t=r.dep,a=t.flags;64&a&&e(t,t.flags=-65&a),r=r.nextDep}}(e,e.flags&=-65)}t1=0,t0=0}function t7(){let a=this.flags;if(16&a||32&a&&tZ(this.deps,this)){if(t6(this)){let e=this.subs;void 0!==e&&tQ(e)}}else 32&a&&(this.flags=-33&a);return void 0!==e?tV(this,e):void 0!==t&&tV(this,t),this.value}function ae(...t){if(t.length){let e=t[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(tJ(e),tX||t4())}}else{let t=this.value;if(16&this.flags&&t8(this,t)){let e=this.subs;void 0!==e&&tQ(e)}return void 0!==e&&tV(this,e),t}}function at(){let e=this.deps;for(;void 0!==e;)e=tG(e,this);let t=this.subs;void 0!==t&&tG(t),this.flags=0}function aa(e){let{pageSize:t,initialPage:a,...r}=e||{},n=t??10;return new URLSearchParams({...Object.entries(r).reduce((e,[t,a])=>(void 0!==a&&(e[t]=a),e),{}),limit:n+"",offset:((a??1)-1)*n+""})}class ar{static #ei="/billing";static path(e,t){let{orgId:a}=t||{},r=a?`/organizations/${a}`:"/me";return`${r}${ar.#ei}${e}`}getPlans=async e=>{let{for:t,...a}=e||{},r={...a,payer_type:"organization"===t?"org":"user"};return await tF._fetch({path:`${ar.#ei}/plans`,method:"GET",search:aa(r)}).then(e=>{let{data:t,total_count:a}=e;return{total_count:a,data:t.map(e=>new aj(e))}})};getPlan=async e=>new aj(await tF._fetch({path:`${ar.#ei}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await tF._fetch({path:ar.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new aS(e?.response));getStatements=async e=>{let{orgId:t,...a}=e;return await tF._fetch({path:ar.path("/statements",{orgId:t}),method:"GET",search:aa(a)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new a_(e))}})};getStatement=async e=>new a_((await tF._fetch({path:ar.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:t,...a}=e;return await tF._fetch({path:ar.path("/payment_attempts",{orgId:t}),method:"GET",search:aa(a)}).then(e=>{let{data:t,total_count:a}=e;return{total_count:a,data:t.map(e=>new ag(e))}})};getPaymentAttempt=async e=>new ag(await tF._fetch({path:ar.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:t,...a}=e;return new ap((await tF._fetch({path:ar.path("/checkouts",{orgId:t}),method:"POST",body:a}))?.response)}}let an=t9({resource:null}),ai=t9({error:null}),as=t9({status:"idle"}),ao=t3(()=>{let e=an().resource,t=ai().error,a=as().status;return{errors:ah(t,{identifier:null,password:null,code:null}),fetchStatus:a,signIn:e?e.__internal_future:null}}),al=t9({resource:null}),ac=t9({error:null}),au=t9({status:"idle"}),ad=t3(()=>{let e=al().resource,t=ac().error,a=au().status;return{errors:ah(t,{firstName:null,lastName:null,emailAddress:null,phoneNumber:null,password:null,username:null,code:null,captcha:null,legalAccepted:null}),fetchStatus:a,signUp:e?e.__internal_future:null}});function ah(e,t){let a={fields:{...t},raw:null,global:null};if(!e)return a;if(!O(e))return a.raw=[e],a.global=[B(e)],a;function r(e){return"meta"in e&&e.meta&&"paramName"in e.meta&&void 0!==e.meta.paramName}return e.errors.some(r)?e.errors.forEach(e=>{if(a.raw?a.raw.push(e):a.raw=[e],r(e)){let t=X(e.meta.paramName);t in a.fields&&(a.fields[t]=e)}}):(a.raw=[e],a.global=[B(e)]),a}class am extends tF{id;createdAt;updatedAt;imageUrl;userId=null;email;firstName;lastName;organizationId=null;organizationName;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,e.created_at&&(this.createdAt=tL(e.created_at)),e.updated_at&&(this.updatedAt=tL(e.updated_at)),this.imageUrl=e.image_url,this.userId=e.user_id,this.email=e.email,this.firstName=e.first_name,this.lastName=e.last_name,this.organizationId=e.organization_id,this.organizationName=e.organization_name),this}}class ap extends tF{id;externalClientSecret;externalGatewayId;paymentMethod;plan;planPeriod;planPeriodStart;status;totals;isImmediatePlanChange;freeTrialEndsAt;payer;needsPaymentMethod;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.externalClientSecret=e.external_client_secret,this.externalGatewayId=e.external_gateway_id,this.paymentMethod=e.payment_method?new av(e.payment_method):void 0,this.plan=new aj(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=tu(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=tL(e.free_trial_ends_at)),this.payer=new am(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>ti(()=>this._basePatch({path:ar.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,t){if(!O(e)||t>=4)return!1;let a=e?.status,r=409===a&&e.errors?.[0]?.code==="checkout_already_in_progress";return a>=500||r}})}class af{resource=new ap(null);config;signals;pendingOperations=new Map;constructor(e,t){this.config=t,this.signals=e,this.signals.resourceSignal({resource:this})}get status(){return this.resource.status??"needs_initialization"}get externalClientSecret(){return this.resource.externalClientSecret}get externalGatewayId(){return this.resource.externalGatewayId}get plan(){return this.resource.plan}get planPeriod(){return this.resource.planPeriod}get totals(){return this.resource.totals}get isImmediatePlanChange(){return this.resource.isImmediatePlanChange}get freeTrialEndsAt(){return this.resource.freeTrialEndsAt}get payer(){return this.resource.payer}get paymentMethod(){return this.resource.paymentMethod??null}get planPeriodStart(){return this.resource.planPeriodStart}get needsPaymentMethod(){return this.resource.needsPaymentMethod}async start(){return this.runAsyncCheckoutTask("start",async()=>{let e=await ap.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new ap(null),this.signals.resourceSignal({resource:this})})}async confirm(e){if(!this.resource.id)throw Error("Clerk: `start()` must be called before `confirm()`");return this.runAsyncCheckoutTask("confirm",async()=>{await this.resource.confirm(e)})}async finalize(e){let{navigate:t}=e||{};return this.runAsyncCheckoutTask("finalize",async()=>{if("completed"!==this.resource.status)throw Error("Clerk: `confirm()` must be called before `finalize()`");await ap.clerk.setActive({session:ap.clerk.session?.id,navigate:t})})}runAsyncCheckoutTask(e,t,a){var r,n,i;return void 0===ap.clerk.user?(console.warn("Clerk: Checkout operations cannot be performed during transitive state"),{error:null}):(r=this,n=this.signals,i=this.pendingOperations,async(e,t,a)=>{if(i.get(e))return i.get(e);let s=(async()=>{++tX,n.errorSignal({error:null}),n.fetchSignal({status:"fetching"}),a?.(),--tX||t4(),++tX;try{return await t(),n.resourceSignal({resource:r}),{error:null}}catch(e){return n.errorSignal({error:e}),{error:e}}finally{i.delete(e),n.fetchSignal({status:"idle"}),--tX||t4()}})();return i.set(e,s),s})(e,t,a)}}class ag extends tF{id;amount;failedAt=null;paidAt=null;updatedAt;paymentMethod=null;subscriptionItem;chargeType;status;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.amount=tc(e.amount),this.paidAt=e.paid_at?tL(e.paid_at):null,this.failedAt=e.failed_at?tL(e.failed_at):null,this.updatedAt=tL(e.updated_at),this.paymentMethod=e.payment_method?new av(e.payment_method):null,this.subscriptionItem=new aA(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}let ab="/payment_methods",ay=async e=>{let{orgId:t,...a}=e;return new ax((await tF._fetch({path:ar.path(`${ab}/initialize`,{orgId:t}),method:"POST",body:a}))?.response)},aw=async e=>{let{orgId:t,...a}=e;return new av((await tF._fetch({path:ar.path(ab,{orgId:t}),method:"POST",body:a}))?.response)},ak=async e=>{let{orgId:t,...a}=e??{};return await tF._fetch({path:ar.path(ab,{orgId:t}),method:"GET",search:aa(a)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new av(e))}})};class av extends tF{id;last4=null;paymentType;cardType=null;isDefault;isRemovable;status;walletType;expiryYear;expiryMonth;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.last4=e.last4,this.paymentType=e.payment_type,this.cardType=e.card_type,this.isDefault=e.is_default,this.isRemovable=e.is_removable,this.status=e.status,this.walletType=e.wallet_type,this.expiryYear=e.expiry_year,this.expiryMonth=e.expiry_month,this.createdAt=null==e.created_at?e.created_at:tL(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:tL(e.updated_at)),this}async remove(e){let{orgId:t}=e??{};return new aR((await tF._fetch({path:ar.path(`/payment_methods/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:t}=e??{};return await tF._fetch({path:ar.path("/payers/default_payment_method",{orgId:t}),method:"PUT",body:{payment_method_id:this.id}}),null}}class ax extends tF{externalClientSecret;externalGatewayId;paymentMethodOrder;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.externalClientSecret=e.external_client_secret,this.externalGatewayId=e.external_gateway_id,this.paymentMethodOrder=e.payment_method_order??["card"]),this}}class aj extends tF{id;name;fee;annualFee=null;annualMonthlyFee=null;description=null;isDefault;isRecurring;hasBaseFee;forPayerType;publiclyVisible;slug;avatarUrl=null;features;freeTrialDays;freeTrialEnabled;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.fee=tc(e.fee),this.annualFee=e.annual_fee?tc(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?tc(e.annual_monthly_fee):null,this.description=e.description,this.isDefault=e.is_default,this.isRecurring=e.is_recurring,this.hasBaseFee=e.has_base_fee,this.forPayerType=e.for_payer_type,this.publiclyVisible=e.publicly_visible,this.slug=e.slug,this.avatarUrl=e.avatar_url,this.freeTrialDays=this.withDefault(e.free_trial_days,null),this.freeTrialEnabled=this.withDefault(e.free_trial_enabled,!1),this.features=(e.features||[]).map(e=>new ri(e))),this}}class a_ extends tF{id;status;timestamp;totals;groups;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.timestamp=tL(e.timestamp),this.totals=tu(e.totals),this.groups=e.groups.map(e=>new az(e))),this}}class az{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=tL(e.timestamp),this.items=e.items.map(e=>new ag(e))),this}}class aS extends tF{id;status;activeAt;createdAt;pastDueAt;updatedAt;nextPayment;subscriptionItems;eligibleForFreeTrial;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.createdAt=tL(e.created_at),this.updatedAt=e.updated_at?tL(e.updated_at):null,this.activeAt=tL(e.active_at),this.pastDueAt=e.past_due_at?tL(e.past_due_at):null,e.next_payment&&(this.nextPayment={amount:tc(e.next_payment.amount),date:tL(e.next_payment.date)}),this.subscriptionItems=(e.subscription_items||[]).map(e=>new aA(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1)),this}}class aA extends tF{id;plan;planPeriod;status;createdAt;periodStart;periodEnd;canceledAt;pastDueAt;amount;credit;isFreeTrial;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.plan=new aj(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.createdAt=tL(e.created_at),this.pastDueAt=e.past_due_at?tL(e.past_due_at):null,this.periodStart=tL(e.period_start),this.periodEnd=e.period_end?tL(e.period_end):null,this.canceledAt=e.canceled_at?tL(e.canceled_at):null,this.amount=e.amount?tc(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:tc(e.credit.amount)}:void 0,this.isFreeTrial=this.withDefault(e.is_free_trial,!1)),this}async cancel(e){let{orgId:t}=e;return new aR((await tF._fetch({path:ar.path(`/subscription_items/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}}let aE={build:(e,t,a)=>[e,t,a].filter(Boolean).join("-"),parse:(e,t,a)=>{let r=aE.extractTemplate(e,t,a);return{organizationId:a,sessionId:t,template:r}},extractTemplate:(e,t,a)=>{if(e===t||a&&e===`${t}-${a}`)return;let r=e.slice(t.length+1);return a&&r.endsWith(`-${a}`)&&(r=r.slice(0,-(a.length+1))),r||void 0}},aI="clerk",aC=10,aP={broadcast:!0},aq={broadcast:!1};class aO{prefix;data;static fromKey(e){let[t,a,r=""]=e.split("::");return new aO(t,{audience:r,tokenId:a})}constructor(e,t){this.prefix=e,this.data=t,this.prefix=e,this.data=t}toKey(){let{tokenId:e,audience:t}=this.data;return[this.prefix,e,t||""].join("::")}}let aT=((e=aI)=>{let t=new Map,a=Math.random().toString(36).slice(2),r=null,n=()=>r||("undefined"==typeof BroadcastChannel?null:((r=new BroadcastChannel("clerk:session_token")).addEventListener("message",e=>{s(e)}),r));n();let i=(a,r=aC)=>{n();let i=new aO(e,a),s=t.get(i.toKey());if(!s)return;let o=Math.floor(Date.now()/1e3)-s.createdAt;if(s.expiresIn-o<(r||1)+5){void 0!==s.timeoutId&&clearTimeout(s.timeoutId),t.delete(i.toKey());return}return s.entry},s=async({data:e})=>{let t,r=aE.build(e.sessionId,e.template,e.organizationId);if(e.tokenId!==r)return void tt.warn("Ignoring token broadcast with mismatched tokenId",{expectedTokenId:r,organizationId:e.organizationId,receivedTokenId:e.tokenId,tabId:a,template:e.template,traceId:e.traceId},"tokenCache");try{t=new rK({id:e.tokenId,jwt:e.tokenRaw,object:"token"})}catch(t){tt.warn("Failed to parse token from broadcast, skipping cache update",{error:t,tabId:a,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");return}let n=t.jwt?.claims?.iat,s=t.jwt?.claims?.exp;if(!n||!s)return void tt.warn("Token missing iat/exp claim, skipping cache update",{tabId:a,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");try{let t=i({tokenId:e.tokenId});if(t){let r=await t.tokenResolver,i=r.jwt?.claims?.iat;if(i&&i>=n)return void tt.debug("Ignoring older token broadcast",{existingIat:i,incomingIat:n,tabId:a,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}}catch(t){tt.warn("Existing entry compare failed; proceeding with broadcast update",{error:t,tabId:a,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}tt.info("Updating token cache from broadcast",{iat:n,organizationId:e.organizationId,tabId:a,template:e.template,tokenId:e.tokenId,traceId:e.traceId},"tokenCache"),o({createdAt:n,tokenId:e.tokenId,tokenResolver:Promise.resolve(t)},aq)},o=(n,i=aP)=>{let s=new aO(e,{audience:n.audience,tokenId:n.tokenId}).toKey(),o=Math.floor(Date.now()/1e3),l={createdAt:n.createdAt??o,entry:n,expiresIn:void 0},c=()=>{let e=t.get(s);e===l&&(void 0!==e.timeoutId&&clearTimeout(e.timeoutId),t.delete(s))};n.tokenResolver.then(e=>{let t=e.jwt?.claims;if(!t||"number"!=typeof t.exp||"number"!=typeof t.iat)return c();let s=t.exp-t.iat;l.expiresIn=s;let o=setTimeout(c,1e3*s);l.timeoutId=o,"function"==typeof o.unref&&o.unref();let u=r;if(u&&i.broadcast){let r=e.getRawString();if(r&&t.sid){let e=t.sid,i=t.org_id||t.o?.id,s=aE.extractTemplate(n.tokenId,e,i),o=aE.build(e,s,i);if(n.tokenId===o){let t=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;tt.info("Broadcasting token update to other tabs",{organizationId:i,sessionId:e,tabId:a,template:s,tokenId:n.tokenId,traceId:t},"tokenCache");let o={organizationId:i,sessionId:e,template:s,tokenId:n.tokenId,tokenRaw:r,traceId:t};u.postMessage(o)}}}}).catch(()=>{c()}),t.set(s,l)};return{clear:()=>{t.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId)}),t.clear()},close:()=>{r&&(r.close(),r=null)},get:i,set:e=>{n(),o(e,aP)},size:()=>t.size}})();class aU extends tF{static instance;pathRoot="/client";sessions=[];signUp=new rF;signIn=new rB;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return aU.instance||(aU.instance=new aU(e)),aU.instance}static clearInstance(){aU.instance=null}static isClientResource(e){return!!e&&e instanceof aU}constructor(e=null){super(),this.fromJSON(e)}get signUpAttempt(){return this.signUp}get signInAttempt(){return this.signIn}get signedInSessions(){return this.sessions.filter(e=>"active"===e.status||"pending"===e.status)}create(){return this._basePut()}fetch({fetchMaxTries:e}={}){return this._baseGet({fetchMaxTries:e})}async destroy(){return this._baseDelete({path:"/client"}).then(()=>{aT.clear(),this.id="",this.sessions=[],this.signUp=new rF(null),this.signIn=new rB(null),this.lastActiveSessionId=null,this.lastAuthenticationStrategy=null,this.cookieExpiresAt=null,this.createdAt=null,this.updatedAt=null})}removeSessions(){return this._baseDelete({path:this.path()+"/sessions"}).then(e=>(aT.clear(),e))}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return tF.fapiClient.buildUrl({method:"GET",path:"/client/touch",pathPrefix:"v1",search:{redirect_url:e.toString()}}).toString()}__internal_sendCaptchaToken(e){return this._basePostBypass({body:e,path:this.path()+"/verify"})}fromJSON(e){return e&&(this.id=e.id,this.sessions=(e.sessions||[]).map(e=>new rI(e)),this.signUp=new rF(e.sign_up),this.signIn=new rB(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?tL(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=tL(e.created_at||void 0),this.updatedAt=tL(e.updated_at||void 0)),this}__internal_toSnapshot(){return{object:"client",id:this.id||"",sessions:this.sessions.map(e=>e.__internal_toSnapshot()),sign_up:this.signUp.__internal_toSnapshot(),sign_in:this.signIn.__internal_toSnapshot(),last_active_session_id:this.lastActiveSessionId,captcha_bypass:this.captchaBypass,cookie_expires_at:this.cookieExpiresAt?this.cookieExpiresAt.getTime():null,last_authentication_strategy:this.lastAuthenticationStrategy??null,created_at:this.createdAt?.getTime()??null,updated_at:this.updatedAt?.getTime()??null}}path(){return this.pathRoot}}class aM extends tF{billing={stripePublishableKey:null,organization:{enabled:!1,hasPaidPlans:!1},user:{enabled:!1,hasPaidPlans:!1}};constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.billing.stripePublishableKey=e.billing.stripe_publishable_key,this.billing.organization.enabled=e.billing.organization.enabled,this.billing.organization.hasPaidPlans=e.billing.organization.has_paid_plans,this.billing.user.enabled=e.billing.user.enabled,this.billing.user.hasPaidPlans=e.billing.user.has_paid_plans),this}__internal_toSnapshot(){return{billing:{stripe_publishable_key:this.billing.stripePublishableKey,organization:{enabled:this.billing.organization.enabled,has_paid_plans:this.billing.organization.hasPaidPlans},user:{enabled:this.billing.user.enabled,has_paid_plans:this.billing.user.hasPaidPlans}}}}}class aR{object="";id;slug;deleted=!1;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.object=e.object,this.id=e.id,this.slug=e.slug,this.deleted=e.deleted),this}}class aB extends tF{afterCreateOrganizationUrl="";afterJoinWaitlistUrl="";afterLeaveOrganizationUrl="";afterSignInUrl="";afterSignOutAllUrl="";afterSignOutOneUrl="";afterSignOutUrl="";afterSignUpUrl="";afterSwitchSessionUrl="";applicationName="";backendHost="";branded=!1;captchaHeartbeat=!1;captchaHeartbeatIntervalMs;captchaOauthBypass=["oauth_google","oauth_microsoft","oauth_apple"];captchaProvider="turnstile";captchaPublicKey=null;captchaPublicKeyInvisible=null;captchaWidgetType=null;clerkJSVersion;createOrganizationUrl="";faviconImageUrl="";googleOneTapClientId;homeUrl="";id="";instanceEnvironmentType="";logoImageUrl="";organizationProfileUrl="";preferredSignInStrategy="password";privacyPolicyUrl="";showDevModeWarning=!1;signInUrl="";signUpUrl="";supportEmail="";termsUrl="";theme={};userProfileUrl="";waitlistUrl="";constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.afterCreateOrganizationUrl=this.withDefault(e.after_create_organization_url,this.afterCreateOrganizationUrl),this.afterJoinWaitlistUrl=this.withDefault(e.after_join_waitlist_url,this.afterJoinWaitlistUrl),this.afterLeaveOrganizationUrl=this.withDefault(e.after_leave_organization_url,this.afterLeaveOrganizationUrl),this.afterSignInUrl=this.withDefault(e.after_sign_in_url,this.afterSignInUrl),this.afterSignOutAllUrl=this.withDefault(e.after_sign_out_all_url,this.afterSignOutAllUrl),this.afterSignOutOneUrl=this.withDefault(e.after_sign_out_one_url,this.afterSignOutOneUrl),this.afterSignUpUrl=this.withDefault(e.after_sign_up_url,this.afterSignUpUrl),this.afterSwitchSessionUrl=this.withDefault(e.after_switch_session_url,this.afterSwitchSessionUrl),this.applicationName=this.withDefault(e.application_name,this.applicationName),this.branded=this.withDefault(e.branded,this.branded),this.captchaHeartbeat=this.withDefault(e.captcha_heartbeat,this.captchaHeartbeat),this.captchaHeartbeatIntervalMs=this.withDefault(e.captcha_heartbeat_interval_ms,this.captchaHeartbeatIntervalMs),this.captchaOauthBypass=this.withDefault(e.captcha_oauth_bypass,this.captchaOauthBypass),this.captchaProvider=this.withDefault(e.captcha_provider,this.captchaProvider),this.captchaPublicKey=this.withDefault(e.captcha_public_key,this.captchaPublicKey),this.captchaPublicKeyInvisible=this.withDefault(e.captcha_public_key_invisible,this.captchaPublicKeyInvisible),this.captchaWidgetType=this.withDefault(e.captcha_widget_type,this.captchaWidgetType),this.clerkJSVersion=this.withDefault(e.clerk_js_version,this.clerkJSVersion),this.createOrganizationUrl=this.withDefault(e.create_organization_url,this.createOrganizationUrl),this.faviconImageUrl=this.withDefault(e.favicon_image_url,this.faviconImageUrl),this.googleOneTapClientId=this.withDefault(e.google_one_tap_client_id,this.googleOneTapClientId),this.homeUrl=this.withDefault(e.home_url,this.homeUrl),this.id=this.withDefault(e.id,this.id),this.instanceEnvironmentType=this.withDefault(e.instance_environment_type,this.instanceEnvironmentType),this.logoImageUrl=this.withDefault(e.logo_image_url,this.logoImageUrl),this.organizationProfileUrl=this.withDefault(e.organization_profile_url,this.organizationProfileUrl),this.preferredSignInStrategy=this.withDefault(e.preferred_sign_in_strategy,this.preferredSignInStrategy),this.privacyPolicyUrl=this.withDefault(e.privacy_policy_url,this.privacyPolicyUrl),this.showDevModeWarning=this.withDefault(e.show_devmode_warning,this.showDevModeWarning),this.signInUrl=this.withDefault(e.sign_in_url,this.signInUrl),this.signUpUrl=this.withDefault(e.sign_up_url,this.signUpUrl),this.supportEmail=this.withDefault(e.support_email,this.supportEmail),this.termsUrl=this.withDefault(e.terms_url,this.termsUrl),this.theme=this.withDefault(e.theme,this.theme),this.userProfileUrl=this.withDefault(e.user_profile_url,this.userProfileUrl),this.waitlistUrl=this.withDefault(e.waitlist_url,this.waitlistUrl)),this}__internal_toSnapshot(){return{object:"display_config",after_create_organization_url:this.afterCreateOrganizationUrl,after_join_waitlist_url:this.afterJoinWaitlistUrl,after_leave_organization_url:this.afterLeaveOrganizationUrl,after_sign_in_url:this.afterSignInUrl,after_sign_out_all_url:this.afterSignOutAllUrl,after_sign_out_one_url:this.afterSignOutOneUrl,after_sign_up_url:this.afterSignUpUrl,after_switch_session_url:this.afterSwitchSessionUrl,application_name:this.applicationName,branded:this.branded,captcha_heartbeat_interval_ms:this.captchaHeartbeatIntervalMs,captcha_heartbeat:this.captchaHeartbeat,captcha_oauth_bypass:this.captchaOauthBypass,captcha_provider:this.captchaProvider,captcha_public_key_invisible:this.captchaPublicKeyInvisible,captcha_public_key:this.captchaPublicKey,captcha_widget_type:this.captchaWidgetType,clerk_js_version:this.clerkJSVersion,create_organization_url:this.createOrganizationUrl,favicon_image_url:this.faviconImageUrl,google_one_tap_client_id:this.googleOneTapClientId,home_url:this.homeUrl,id:this.id,instance_environment_type:this.instanceEnvironmentType,logo_image_url:this.logoImageUrl,organization_profile_url:this.organizationProfileUrl,preferred_sign_in_strategy:this.preferredSignInStrategy,privacy_policy_url:this.privacyPolicyUrl,show_devmode_warning:this.showDevModeWarning,sign_in_url:this.signInUrl,sign_up_url:this.signUpUrl,support_email:this.supportEmail,terms_url:this.termsUrl,theme:this.theme,user_profile_url:this.userProfileUrl,waitlist_url:this.waitlistUrl}}}var aN='const respond=r=>{self.postMessage(r)},workerToTabIds={};self.addEventListener("message",r=>{const e=r.data;switch(e.type){case"setTimeout":workerToTabIds[e.id]=setTimeout(()=>{respond({id:e.id}),delete workerToTabIds[e.id]},e.ms);break;case"clearTimeout":workerToTabIds[e.id]&&(clearTimeout(workerToTabIds[e.id]),delete workerToTabIds[e.id]);break;case"setInterval":workerToTabIds[e.id]=setInterval(()=>{respond({id:e.id})},e.ms);break;case"clearInterval":workerToTabIds[e.id]&&(clearInterval(workerToTabIds[e.id]),delete workerToTabIds[e.id]);break}});\n';let aD=(e,t={})=>{if("undefined"==typeof Worker)return null;try{let a=new Blob([e],{type:"application/javascript; charset=utf-8"}),r=globalThis.URL.createObjectURL(a);return new Worker(r,t)}catch{return console.warn("Clerk: Cannot create worker from blob. Consider adding worker-src blob:; to your CSP"),null}},aF=()=>{let e=0,t=()=>e++,a=new Map,r=(e,t)=>e?.postMessage(t),n=e=>{a.get(e.data.id)?.()},i=aD(aN,{name:"clerk-timers"});if(i?.addEventListener("message",n),!i)return{setTimeout:globalThis.setTimeout.bind(globalThis),setInterval:globalThis.setInterval.bind(globalThis),clearTimeout:globalThis.clearTimeout.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis),cleanup:e3};let s=()=>{i||(i=aD(aN,{name:"clerk-timers"}),i?.addEventListener("message",n))};return{setTimeout:(e,n)=>{s();let o=t();return a.set(o,()=>{e(),a.delete(o)}),r(i,{type:"setTimeout",id:o,ms:n}),o},setInterval:(e,n)=>{s();let o=t();return a.set(o,e),r(i,{type:"setInterval",id:o,ms:n}),o},clearTimeout:e=>{s(),a.delete(e),r(i,{type:"clearTimeout",id:e})},clearInterval:e=>{s(),a.delete(e),r(i,{type:"clearInterval",id:e})},cleanup:()=>{i&&(i.terminate(),i=null,a.clear())}}};function aL({delayInMs:e}={delayInMs:1e3}){let t,a=aF(),r=!1,n=()=>{t&&(a.clearTimeout(t),a.cleanup()),r=!0},i=async s=>{r=!1,await s(n),r||(t=a.setTimeout(()=>{i(s)},e))};return{run:i,stop:n}}class aW extends tF{id;emailAddress="";matchesSsoConnection=!1;linkedTo=[];verification;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}create(){return this._basePost({body:{email_address:this.emailAddress}})}prepareVerification=e=>this._basePost({action:"prepare_verification",body:{...e}});attemptVerification=e=>{let{code:t}=e||{};return this._basePost({action:"attempt_verification",body:{code:t}})};createEmailLinkFlow=()=>{let{run:e,stop:t}=aL();return{startEmailLinkFlow:async({redirectUrl:a})=>(await this.prepareVerification({strategy:"email_link",redirectUrl:a}),new Promise((a,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),a(e))}).catch(e=>{t(),r(e)}))})),cancelEmailLinkFlow:t}};createEnterpriseSSOLinkFlow=()=>{let{run:e,stop:t}=aL();return{startEnterpriseSSOLinkFlow:async({redirectUrl:a})=>{if(!(await this.prepareVerification({strategy:"enterprise_sso",redirectUrl:a})).verification.externalVerificationRedirectURL)throw Error("Unexpected: External verification redirect URL is missing");return new Promise((a,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),a(e))}).catch(e=>{t(),r(e)}))})},cancelEnterpriseSSOLinkFlow:t}};destroy=()=>this._baseDelete();toString=()=>this.emailAddress;fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.verification=new a1(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new rs(e))),this}__internal_toSnapshot(){return{object:"email_address",id:this.id,email_address:this.emailAddress,verification:this.verification.__internal_toSnapshot(),linked_to:this.linkedTo.map(e=>e.__internal_toSnapshot()),matches_sso_connection:this.matchesSsoConnection}}}var aK=class{static encode(e){return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}static decode(e){let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),a=t.length,r=new Uint8Array(a);for(let e=0;e<a;e++)r[e]=t.charCodeAt(e);return r.buffer}};async function aH(e){try{let t=await navigator.credentials.create({publicKey:e});if(!t)return{error:new I("Browser failed to create credential",{code:"passkey_registration_failed"}),publicKeyCredential:null};return{publicKeyCredential:t,error:null}}catch(e){var t;return{error:"InvalidStateError"===(t=e).name?new I(t.message,{code:"passkey_already_exists"}):"NotAllowedError"===t.name?new I(t.message,{code:"passkey_registration_cancelled"}):aJ(t),publicKeyCredential:null}}}let aV=new class{controller;__abort(){if(!this.controller)return;let e=Error();e.name="AbortError",this.controller.abort(e)}createAbortSignal(){this.__abort();let e=new AbortController;return this.controller=e,e.signal}abort(){this.__abort(),this.controller=void 0}};async function aG({publicKeyOptions:e,conditionalUI:t}){try{let a=await navigator.credentials.get({publicKey:e,mediation:t?"conditional":"optional",signal:aV.createAbortSignal()});if(!a)return{error:new I("Browser failed to get credential",{code:"passkey_retrieval_failed"}),publicKeyCredential:null};return{publicKeyCredential:a,error:null}}catch(e){var a;return{error:"NotAllowedError"===(a=e).name?new I(a.message,{code:"passkey_retrieval_cancelled"}):aJ(a),publicKeyCredential:null}}}function aJ(e){return"AbortError"===e.name?new I(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new I(e.message,{code:"passkey_invalid_rpID_or_domain"}):e}function aZ(e){let t=aX(e.challenge),a=(e.allowCredentials||[]).map(e=>({...e,id:aX(e.id)}));return{...e,allowCredentials:a,challenge:t}}function a$(e){return{type:e.type,id:e.id,rawId:aQ(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function aY(e){let t=e.response;return{...a$(e),response:{clientDataJSON:aQ(t.clientDataJSON),authenticatorData:aQ(t.authenticatorData),signature:aQ(t.signature),userHandle:t.userHandle?aQ(t.userHandle):null}}}let aQ=aK.encode.bind(aK),aX=aK.decode.bind(aK);class a1 extends tF{pathRoot="";status=null;strategy=null;nonce=null;message=null;externalVerificationRedirectURL=null;attempts=null;expireAt=null;error=null;verifiedAtClient=null;channel;constructor(e){super(),this.fromJSON(e)}verifiedFromTheSameClient=()=>this.verifiedAtClient===tF.clerk?.client?.id;fromJSON(e){return e&&(this.status=e.status,this.verifiedAtClient=e.verified_at_client,this.strategy=e.strategy,this.nonce=e.nonce||null,this.message=e.message||null,e.external_verification_redirect_url?this.externalVerificationRedirectURL=new URL(e.external_verification_redirect_url):this.externalVerificationRedirectURL=null,this.attempts=e.attempts,this.expireAt=tL(e.expire_at||void 0),this.error=e.error?new w(e.error):null,this.channel=e.channel||void 0),this}__internal_toSnapshot(){var e;return{object:"verification",id:this.id||"",status:this.status,strategy:this.strategy,nonce:this.nonce,message:this.message,external_verification_redirect_url:this.externalVerificationRedirectURL?.toString()||null,attempts:this.attempts,expire_at:this.expireAt?.getTime()||null,error:(e=this.error,{code:e?.code||"",message:e?.message||"",long_message:e?.longMessage,meta:{param_name:e?.meta?.paramName,session_id:e?.meta?.sessionId,email_addresses:e?.meta?.emailAddresses,identifiers:e?.meta?.identifiers,zxcvbn:e?.meta?.zxcvbn,plan:e?.meta?.plan,is_plan_upgrade_possible:e?.meta?.isPlanUpgradePossible}}),verified_at_client:this.verifiedAtClient}}}class a0 extends a1{publicKey=null;constructor(e){super(e),this.fromJSON(e)}fromJSON(e){var t;let a,r,n;return super.fromJSON(e),e?.nonce&&(this.publicKey=(a=aX((t=JSON.parse(e.nonce)).user.id),r=aX(t.challenge),n=(t.excludeCredentials||[]).map(e=>({...e,id:aX(e.id)})),{...t,excludeCredentials:n,challenge:r,user:{...t.user,id:a}})),this}}class a2{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new a9(e.email_address),this.phoneNumber=new a9(e.phone_number),this.web3Wallet=new a9(e.web3_wallet),this.externalAccount=new a1(e.external_account)):(this.emailAddress=new a9(null),this.phoneNumber=new a9(null),this.web3Wallet=new a9(null),this.externalAccount=new a1(null))}__internal_toSnapshot(){return{email_address:this.emailAddress.__internal_toSnapshot(),phone_number:this.phoneNumber.__internal_toSnapshot(),web3_wallet:this.web3Wallet.__internal_toSnapshot(),external_account:this.externalAccount.__internal_toSnapshot()}}}class a9 extends a1{nextAction;supportedStrategies;constructor(e){super(e),e?(this.nextAction=e.next_action,this.supportedStrategies=e.supported_strategies):(this.nextAction="",this.supportedStrategies=[])}__internal_toSnapshot(){return{...super.__internal_toSnapshot(),next_action:this.nextAction,supported_strategies:this.supportedStrategies}}}class a3 extends tF{id;protocol;provider;providerUserId=null;active;emailAddress="";firstName="";lastName="";publicMetadata={};verification=null;enterpriseConnection=null;lastAuthenticatedAt=null;enterpriseConnectionId=null;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.provider=e.provider,this.protocol=e.protocol,this.providerUserId=e.provider_user_id,this.active=e.active,this.emailAddress=e.email_address,this.firstName=e.first_name,this.lastName=e.last_name,this.publicMetadata=e.public_metadata,this.lastAuthenticatedAt=e.last_authenticated_at?tL(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new a1(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new a5(e.enterprise_connection))),this}__internal_toSnapshot(){return{object:"enterprise_account",id:this.id,provider:this.provider,protocol:this.protocol,provider_user_id:this.providerUserId,active:this.active,email_address:this.emailAddress,first_name:this.firstName,last_name:this.lastName,public_metadata:this.publicMetadata,verification:this.verification?.__internal_toSnapshot()||null,enterprise_connection:this.enterpriseConnection?.__internal_toSnapshot()||null,last_authenticated_at:this.lastAuthenticatedAt?this.lastAuthenticatedAt.getTime():null,enterprise_connection_id:this.enterpriseConnectionId}}}class a5 extends tF{id;active;allowIdpInitiated;allowSubdomains;disableAdditionalIdentifications;domain;logoPublicUrl="";name;protocol;provider;syncUserAttributes;createdAt;updatedAt;enterpriseConnectionId="";constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.domain=e.domain,this.active=e.active,this.provider=e.provider,this.logoPublicUrl=e.logo_public_url,this.syncUserAttributes=e.sync_user_attributes,this.allowSubdomains=e.allow_subdomains,this.allowIdpInitiated=e.allow_idp_initiated,this.disableAdditionalIdentifications=e.disable_additional_identifications,this.createdAt=tL(e.created_at),this.updatedAt=tL(e.updated_at),this.enterpriseConnectionId=e.enterprise_connection_id),this}__internal_toSnapshot(){return{object:"enterprise_account_connection",id:this.id,name:this.name,domain:this.domain,active:this.active,protocol:this.protocol,provider:this.provider,logo_public_url:this.logoPublicUrl,sync_user_attributes:this.syncUserAttributes,allow_subdomains:this.allowSubdomains,allow_idp_initiated:this.allowIdpInitiated,disable_additional_identifications:this.disableAdditionalIdentifications,enterprise_connection_id:this.enterpriseConnectionId,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}let a6="token:update",a8="user:signOut",a4="environment:update",a7="session:tokenResolved",re=p();class rt extends tF{user_api_keys_enabled=!1;orgs_api_keys_enabled=!1;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.user_api_keys_enabled=e.user_api_keys_enabled,this.orgs_api_keys_enabled=e.orgs_api_keys_enabled),this}__internal_toSnapshot(){return{user_api_keys_enabled:this.user_api_keys_enabled,orgs_api_keys_enabled:this.orgs_api_keys_enabled}}}class ra extends tF{actions={adminDelete:!1};domains={enabled:!1,enrollmentModes:[],defaultRole:null};slug={disabled:!1};enabled=!1;maxAllowedMemberships=1;forceOrganizationSelection;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(e.actions&&(this.actions.adminDelete=this.withDefault(e.actions.admin_delete,this.actions.adminDelete)),e.domains&&(this.domains.enabled=this.withDefault(e.domains.enabled,this.domains.enabled),this.domains.enrollmentModes=this.withDefault(e.domains.enrollment_modes,this.domains.enrollmentModes),this.domains.defaultRole=this.withDefault(e.domains.default_role,this.domains.defaultRole)),e.slug&&(this.slug.disabled=this.withDefault(e.slug.disabled,this.slug.disabled)),this.enabled=this.withDefault(e.enabled,this.enabled),this.maxAllowedMemberships=this.withDefault(e.max_allowed_memberships,this.maxAllowedMemberships),this.forceOrganizationSelection=this.withDefault(e.force_organization_selection,this.forceOrganizationSelection)),this}__internal_toSnapshot(){return{actions:{admin_delete:this.actions.adminDelete},domains:{enabled:this.domains.enabled,enrollment_modes:this.domains.enrollmentModes,default_role:this.domains.defaultRole},enabled:this.enabled,max_allowed_memberships:this.maxAllowedMemberships}}}class rr extends tF{static instance;authConfig=new tK;displayConfig=new aB;maintenanceMode=!1;clientDebugMode=!1;pathRoot="/environment";userSettings=new rY;organizationSettings=new ra;commerceSettings=new aM;apiKeysSettings=new rt;protectConfig=new rv;static getInstance(){return rr.instance||(rr.instance=new rr),rr.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new tK(e.auth_config),this.displayConfig=new aB(e.display_config),this.maintenanceMode=this.withDefault(e.maintenance_mode,this.maintenanceMode),this.clientDebugMode=this.withDefault(e.client_debug_mode,this.clientDebugMode),this.organizationSettings=new ra(e.organization_settings),this.userSettings=new rY(e.user_settings),this.commerceSettings=new aM(e.commerce_settings),this.apiKeysSettings=new rt(e.api_keys_settings),this.protectConfig=new rv(e.protect_config)),this}fetch({touch:e,fetchMaxTries:t}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:t})).then(e=>(re.emit(a4,null),e))}isDevelopmentOrStaging=()=>!this.isProduction();isProduction=()=>"production"===this.displayConfig.instanceEnvironmentType;isSingleSession=()=>this.authConfig.singleSessionMode;onWindowLocationHost=()=>this.displayConfig.backendHost===window.location.host;__internal_toSnapshot(){return{object:"environment",auth_config:this.authConfig.__internal_toSnapshot(),display_config:this.displayConfig.__internal_toSnapshot(),id:this.id??"",maintenance_mode:this.maintenanceMode,client_debug_mode:this.clientDebugMode,organization_settings:this.organizationSettings.__internal_toSnapshot(),user_settings:this.userSettings.__internal_toSnapshot(),commerce_settings:this.commerceSettings.__internal_toSnapshot(),api_keys_settings:this.apiKeysSettings.__internal_toSnapshot(),protect_config:this.protectConfig.__internal_toSnapshot()}}async __internal_enableEnvironmentSetting(e){await this._basePatch({path:"/dev_tools/enable_environment_setting",body:e})}}class rn extends tF{id;identificationId;provider;providerUserId="";emailAddress="";approvedScopes="";firstName="";lastName="";imageUrl="";username="";phoneNumber="";publicMetadata={};label="";verification=null;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}reauthorize=e=>{let{additionalScopes:t,redirectUrl:a}=e||{};return this._basePatch({action:"reauthorize",body:{additional_scope:t,redirect_url:a}})};destroy=()=>this._baseDelete();fromJSON(e){return e&&(this.id=e.id,this.identificationId=e.identification_id,this.providerUserId=e.provider_user_id,this.approvedScopes=e.approved_scopes,this.imageUrl=e.image_url,this.emailAddress=e.email_address,this.firstName=e.first_name,this.lastName=e.last_name,this.provider=(e.provider||"").replace("oauth_",""),this.username=e.username,this.phoneNumber=e.phone_number,this.publicMetadata=e.public_metadata,this.label=e.label,e.verification&&(this.verification=new a1(e.verification))),this}__internal_toSnapshot(){return{object:"external_account",id:this.id,identification_id:this.identificationId,provider:this.provider,provider_user_id:this.providerUserId,email_address:this.emailAddress,approved_scopes:this.approvedScopes,first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl,username:this.username,phone_number:this.phoneNumber,public_metadata:this.publicMetadata,label:this.label,verification:this.verification?.__internal_toSnapshot()||null}}providerSlug(){return this.provider}providerTitle(){let e;return[(e=this.providerSlug()||"").charAt(0).toUpperCase()+e.slice(1),"Account"].join(" ")}accountIdentifier(){return this.username||this.emailAddress||this.label}}class ri extends tF{id;name;description=null;slug;avatarUrl=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.description=e.description,this.slug=e.slug,this.avatarUrl=e.avatar_url),this}}class rs extends tF{id;type;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.type=e.type),this}__internal_toSnapshot(){return{object:"identification_link",id:this.id,type:this.type}}}class ro extends tF{id;name=null;publicUrl=null;static async create(e,t={}){let a,r=t;return"string"==typeof t.file?(r=t.file,a=new Headers({"Content-Type":"application/octet-stream"})):t.file&&(r=new FormData).append("file",t.file),new ro((await tF._fetch({path:e,method:"POST",body:r,headers:a}))?.response)}static async delete(e){return new ro((await tF._fetch({path:e,method:"DELETE"}))?.response)}constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.publicUrl=e.public_url),this}}class rl extends tF{id;name;organizationId;enrollmentMode;verification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:t}){return new rl((await tF._fetch({path:`/organizations/${e}/domains`,method:"POST",body:{name:t}}))?.response)}prepareAffiliationVerification=async e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/prepare_affiliation_verification`,method:"POST",body:e});attemptAffiliationVerification=async e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/attempt_affiliation_verification`,method:"POST",body:e});updateEnrollmentMode=e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/update_enrollment_mode`,body:e});delete=()=>this._baseDelete({path:`/organizations/${this.organizationId}/domains/${this.id}`});fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.organizationId=e.organization_id,this.enrollmentMode=e.enrollment_mode,this.affiliationEmailAddress=e.affiliation_email_address,this.totalPendingSuggestions=e.total_pending_suggestions,this.totalPendingInvitations=e.total_pending_invitations,e.verification?this.verification={status:e.verification.status,strategy:e.verification.strategy,attempts:e.verification.attempts,expiresAt:tL(e.verification.expires_at)}:this.verification=null),this}}class rc extends tF{id;organizationId;status;publicUserData;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}accept=async()=>await this._basePost({path:`/organizations/${this.organizationId}/membership_requests/${this.id}/accept`});reject=async()=>await this._basePost({path:`/organizations/${this.organizationId}/membership_requests/${this.id}/reject`});fromJSON(e){return e&&(this.id=e.id,this.organizationId=e.organization_id,this.status=e.status,this.createdAt=tL(e.created_at),this.updatedAt=tL(e.updated_at),e.public_user_data&&(this.publicUserData=new rx(e.public_user_data))),this}}class ru extends tF{id;key;name;description;type;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.key=e.key,this.name=e.name,this.description=e.description,this.type=e.type,this.createdAt=tL(e.created_at),this.updatedAt=tL(e.updated_at)),this}}class rd extends tF{id;key;name;description;permissions=[];createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.key=e.key,this.name=e.name,this.description=e.description,this.permissions=e.permissions.map(e=>new ru(e)),this.createdAt=tL(e.created_at),this.updatedAt=tL(e.updated_at)),this}}class rh extends tF{pathRoot="/organizations";id;name;slug;imageUrl;hasImage;publicMetadata={};adminDeleteEnabled;createdAt;updatedAt;membersCount=0;pendingInvitationsCount=0;maxAllowedMemberships;constructor(e){super(),this.fromJSON(e)}static async create(e){return new rh((await tF._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new rh((await tF._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await tF._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:aa(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rd(e))}});getDomains=async e=>await tF._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:aa(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rl(e))}});getDomain=async({domainId:e})=>new rl((await tF._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getMembershipRequests=async e=>await tF._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:aa(e)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rc(e))}});createDomain=async e=>rl.create(this.id,{name:e});getMemberships=async e=>await tF._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:aa({...e,paginated:!0})}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rp(e))}});getInvitations=async e=>await tF._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:aa(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rm(e))}});addMember=async({userId:e,role:t})=>await tF._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:t}}).then(e=>new rp(e?.response));inviteMember=async e=>rm.create(this.id,e);inviteMembers=async e=>rm.createBulk(this.id,e);updateMember=async({userId:e,role:t})=>await tF._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:t}}).then(e=>new rp(e?.response));removeMember=async e=>await tF._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new rp(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let t,a;return null===e?await tF._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new rh(e?.response)):("string"==typeof e?(t=e,a=new Headers({"Content-Type":"application/octet-stream"})):(t=new FormData).append("file",e),await tF._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:t,headers:a}).then(e=>new rh(e?.response)))};initializePaymentMethod=e=>ay({...e,orgId:this.id});addPaymentMethod=e=>aw({...e,orgId:this.id});getPaymentMethods=e=>ak({...e,orgId:this.id});fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.slug=e.slug,this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.publicMetadata=e.public_metadata||{},this.membersCount=e.members_count||0,this.pendingInvitationsCount=e.pending_invitations_count||0,this.maxAllowedMemberships=e.max_allowed_memberships||0,this.adminDeleteEnabled=e.admin_delete_enabled||!1,this.createdAt=tL(e.created_at),this.updatedAt=tL(e.updated_at)),this}__internal_toSnapshot(){return{object:"organization",id:this.id,name:this.name,slug:this.slug,image_url:this.imageUrl,has_image:this.hasImage,public_metadata:this.publicMetadata,members_count:this.membersCount,pending_invitations_count:this.pendingInvitationsCount,max_allowed_memberships:this.maxAllowedMemberships,admin_delete_enabled:this.adminDeleteEnabled,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async reload(e){let{rotatingTokenNonce:t}=e||{},a=(await tF._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:t},{forceUpdateClient:!0}))?.response;return this.fromJSON(a)}}class rm extends tF{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:t,role:a}){return new rm((await tF._fetch({path:`/organizations/${e}/invitations`,method:"POST",body:{email_address:t,role:a}}))?.response)}static async createBulk(e,t){let{emailAddresses:a,role:r}=t;return((await tF._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:a,role:r}}))?.response).map(e=>new rm(e))}constructor(e){super(),this.fromJSON(e)}revoke=async()=>await this._basePost({path:`/organizations/${this.organizationId}/invitations/${this.id}/revoke`});fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.organizationId=e.organization_id,this.publicMetadata=e.public_metadata,this.role=e.role,this.roleName=e.role_name,this.status=e.status,this.createdAt=tL(e.created_at),this.updatedAt=tL(e.updated_at)),this}}class rp extends tF{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await tF._fetch({path:"/me/organization_memberships",method:"GET",search:aa({...e,paginated:!0})}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rp(e))}});destroy=async()=>await this._baseDelete({path:`/organizations/${this.organization.id}/memberships/${this.publicUserData?.userId}`});update=async({role:e})=>await this._basePatch({path:`/organizations/${this.organization.id}/memberships/${this.publicUserData?.userId}`,body:{role:e}});fromJSON(e){return e&&(this.id=e.id,this.organization=new rh(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new rx(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=tL(e.created_at),this.updatedAt=tL(e.updated_at)),this}__internal_toSnapshot(){return{object:"organization_membership",id:this.id,organization:this.organization.__internal_toSnapshot(),public_metadata:this.publicMetadata,public_user_data:this.publicUserData?.__internal_toSnapshot(),permissions:this.permissions,role:this.role,role_name:this.roleName,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}reload(e){throw Error(`${t_} Calling OrganizationMembership.reload is not currently supported. Please contact support.`)}}class rf extends tF{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await tF._fetch({path:"/me/organization_suggestions",method:"GET",search:aa(e)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rf(e))}})}accept=async()=>await this._basePost({path:`/me/organization_suggestions/${this.id}/accept`});fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.publicOrganizationData={hasImage:e.public_organization_data.has_image,imageUrl:e.public_organization_data.image_url,name:e.public_organization_data.name,id:e.public_organization_data.id,slug:e.public_organization_data.slug},this.createdAt=tL(e.created_at),this.updatedAt=tL(e.updated_at)),this}}function rg(){return l()&&"function"==typeof window.PublicKeyCredential}async function rb(){try{return rg()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function ry(){try{return"undefined"!=typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class rw extends tF{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return tF._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new rw(e?.response))}static async attemptVerification(e,t){let a,r=(a=t.response,{...a$(t),response:{clientDataJSON:aQ(a.clientDataJSON),attestationObject:aQ(a.attestationObject),transports:a.getTransports()}});return tF._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new rw(e?.response))}static async registerPasskey(){let e=rw.clerk.__internal_isWebAuthnSupported||rg,t=rw.clerk.__internal_createPublicCredentials||aH,a=rw.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||ry;if(!e())throw new I("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let r=await this.create(),{verification:n}=r,i=n?.publicKey;if(i||tq("create"),i.authenticatorSelection?.authenticatorAttachment==="platform"&&!await a())throw new I("Registration requires a platform authenticator but the device does not support it.",{code:"passkey_pa_not_supported"});let{publicKeyCredential:s,error:o}=await t(i);if(!s)throw o;return this.attemptVerification(r.id,s)}update=e=>this._basePatch({body:e});delete=async()=>new aR((await tF._fetch({path:this.path(),method:"DELETE"}))?.response);fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.lastUsedAt=e.last_used_at?tL(e.last_used_at):null,this.createdAt=tL(e.created_at),this.updatedAt=tL(e.updated_at),e.verification&&(this.verification=new a0(e.verification))),this}__internal_toSnapshot(){return{object:"passkey",id:this.id,name:this.name,verification:this.verification?.__internal_toSnapshot()||null,last_used_at:this.lastUsedAt?.getTime()||null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class rk extends tF{id;phoneNumber="";reservedForSecondFactor=!1;defaultSecondFactor=!1;linkedTo=[];verification;backupCodes;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}create=()=>this._basePost({body:{phone_number:this.phoneNumber}});prepareVerification=()=>this._basePost({action:"prepare_verification",body:{strategy:"phone_code"}});attemptVerification=e=>{let{code:t}=e||{};return this._basePost({action:"attempt_verification",body:{code:t}})};setReservedForSecondFactor=e=>{let{reserved:t}=e||{};return this._basePatch({body:{reserved_for_second_factor:t}})};makeDefaultSecondFactor=()=>this._basePatch({body:{default_second_factor:!0}});destroy=()=>this._baseDelete();toString=()=>{let e=this.phoneNumber.match(/^(\d{3})(\d{3})(\d{4})$/);return e?"("+e[1]+") "+e[2]+"-"+e[3]:this.phoneNumber};fromJSON(e){return e&&(this.id=e.id,this.phoneNumber=e.phone_number,this.reservedForSecondFactor=e.reserved_for_second_factor,this.defaultSecondFactor=e.default_second_factor,this.verification=new a1(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new rs(e)),this.backupCodes=e.backup_codes),this}__internal_toSnapshot(){return{object:"phone_number",id:this.id||"",phone_number:this.phoneNumber,reserved_for_second_factor:this.reservedForSecondFactor,default_second_factor:this.defaultSecondFactor,verification:this.verification.__internal_toSnapshot(),linked_to:this.linkedTo.map(e=>e.__internal_toSnapshot()),backup_codes:this.backupCodes}}}class rv extends tF{id="";loaders;rollout;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=this.withDefault(e.id,this.id),this.loaders=this.withDefault(e.loaders,this.loaders)),this}__internal_toSnapshot(){return{object:"protect_config",id:this.id,loaders:this.loaders}}}class rx{firstName;lastName;imageUrl;hasImage;identifier;userId;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.firstName=e.first_name||null,this.lastName=e.last_name||null,this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.identifier=e.identifier||"",this.userId=e.user_id),this}__internal_toSnapshot(){return{first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl,has_image:this.hasImage,identifier:this.identifier,user_id:this.userId}}}let rj={strict_mfa:{afterMinutes:10,level:"multi_factor"},strict:{afterMinutes:10,level:"second_factor"},moderate:{afterMinutes:60,level:"second_factor"},lax:{afterMinutes:1440,level:"second_factor"}},r_=new Set(["first_factor","second_factor","multi_factor"]),rz=new Set(["strict_mfa","strict","moderate","lax"]),rS=(e,t)=>{let{org:a,user:r}=rA(e),[n,i]=t.split(":"),s=i||n;return"org"===n?a.includes(s):"user"===n?r.includes(s):[...a,...r].includes(s)},rA=e=>{let t=e?e.split(",").map(e=>e.trim()):[];return{org:t.filter(e=>e.split(":")[0].includes("o")).map(e=>e.split(":")[1]),user:t.filter(e=>e.split(":")[0].includes("u")).map(e=>e.split(":")[1])}};class rE extends tF{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new a1(null);secondFactorVerification=new a1(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new rI(e.session),this.level=e.level,this.supportedFirstFactors=er(e.supported_first_factors),this.supportedSecondFactors=er(e.supported_second_factors),this.firstFactorVerification=new a1(e.first_factor_verification),this.secondFactorVerification=new a1(e.second_factor_verification)),this}}class rI extends tF{pathRoot="/client/sessions";id;status;lastActiveAt;lastActiveToken;lastActiveOrganizationId;actor;user;publicUserData;factorVerificationAge=null;tasks=null;expireAt;abandonAt;createdAt;updatedAt;static isSessionResource(e){return!!e&&e instanceof rI}constructor(e){super(),this.fromJSON(e),this.#es(this.lastActiveToken)}end=()=>(aT.clear(),this._basePost({action:"end"}));remove=()=>(aT.clear(),this._basePost({action:"remove"}));touch=()=>this._basePost({action:"touch",body:{active_organization_id:this.lastActiveOrganizationId}}).then(e=>(e.lastActiveToken&&re.emit(a6,{token:e.lastActiveToken}),e));clearCache=()=>aT.clear();getToken=async e=>ti(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,t)=>!P(e)&&t<=8});checkAuthorization=e=>{let t,a=(this.user?.organizationMemberships||[]).find(e=>e.organization.id===this.lastActiveOrganizationId);return(t={userId:this.user?.id,factorVerificationAge:this.factorVerificationAge,orgId:a?.id,orgRole:a?.role,orgPermissions:a?.permissions,features:this.lastActiveToken?.jwt?.claims.fea||"",plans:this.lastActiveToken?.jwt?.claims.pla||""},e=>{if(!t.userId)return!1;let a=((e,t)=>{let{features:a,plans:r}=t;return e.feature&&a?rS(a,e.feature):e.plan&&r?rS(r,e.plan):null})(e,t),r=((e,t)=>{let{orgId:a,orgRole:r,orgPermissions:n}=t;return(e.role||e.permission)&&a&&r&&n?e.permission?n.includes(e.permission.replace(/^(org:)*/,"org:")):e.role?r.replace(/^(org:)*/,"org:")===e.role.replace(/^(org:)*/,"org:"):null:null})(e,t),n=((e,{factorVerificationAge:t})=>{if(!e.reverification||!t)return null;let a=(e=>{let t,a;if(!e)return!1;let r="string"==typeof e&&rz.has(e),n="object"==typeof e&&(t=e.level,r_.has(t))&&"number"==typeof(a=e.afterMinutes)&&a>0;return(!!r||!!n)&&(e=>"string"==typeof e?rj[e]:e).bind(null,e)})(e.reverification);if(!a)return null;let{level:r,afterMinutes:n}=a(),[i,s]=t,o=-1!==i?n>i:null,l=-1!==s?n>s:null;switch(r){case"first_factor":return o;case"second_factor":return -1!==s?l:o;case"multi_factor":return -1===s?o:o&&l}})(e,t);return[a||r,n].some(e=>null===e)?[a||r,n].some(e=>!0===e):[a||r,n].every(e=>!0===e)})(e)};#es=e=>{e&&aT.set({tokenId:this.#eo(),tokenResolver:Promise.resolve(e)})};#eo(e,t){let a=void 0===t?this.lastActiveOrganizationId:t;return aE.build(this.id,e,a)}startVerification=async({level:e})=>new rE((await tF._fetch({method:"POST",path:`/client/sessions/${this.id}/verify`,body:{level:e}}))?.response);prepareFirstFactorVerification=async e=>{let t;switch(e.strategy){case"email_code":t={emailAddressId:e.emailAddressId};break;case"phone_code":t={phoneNumberId:e.phoneNumberId,default:e.default};break;case"passkey":t={};break;case"enterprise_sso":t={emailAddressId:e.emailAddressId,enterpriseConnectionId:e.enterpriseConnectionId,redirectUrl:e.redirectUrl};break;default:tE("Session.prepareFirstFactorVerification",e.strategy)}return new rE((await tF._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_first_factor`,body:{...t,strategy:e.strategy}}))?.response)};attemptFirstFactorVerification=async e=>{let t;return t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(aY(e.publicKeyCredential))}:{...e},new rE((await tF._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_first_factor`,body:{...t,strategy:e.strategy}}))?.response)};verifyWithPasskey=async()=>{let{nonce:e=null}=(await this.prepareFirstFactorVerification({strategy:"passkey"})).firstFactorVerification,t=rI.clerk.__internal_isWebAuthnSupported||rg,a=rI.clerk.__internal_getPublicCredentials||aG;if(!t())throw new I("Passkeys are not supported",{code:"passkey_not_supported"});let r=e?aZ(JSON.parse(e)):null;r||tq("get");let{publicKeyCredential:n,error:i}=await a({publicKeyOptions:r,conditionalUI:!1});if(!n)throw i;return this.attemptFirstFactorVerification({strategy:"passkey",publicKeyCredential:n})};prepareSecondFactorVerification=async e=>new rE((await tF._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new rE((await tF._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_second_factor`,body:e}))?.response);fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.expireAt=tL(e.expire_at),this.abandonAt=tL(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=tL(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.createdAt=tL(e.created_at),this.updatedAt=tL(e.updated_at),this.user=new rG(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new rx(e.public_user_data)),this.lastActiveToken=e.last_active_token?new rK(e.last_active_token):null),this}__internal_toSnapshot(){return{object:"session",id:this.id,status:this.status,expire_at:this.expireAt.getTime(),abandon_at:this.abandonAt.getTime(),factor_verification_age:this.factorVerificationAge,last_active_at:this.lastActiveAt.getTime(),last_active_organization_id:this.lastActiveOrganizationId,actor:this.actor,tasks:this.tasks,user:this.user?.__internal_toSnapshot()||null,public_user_data:this.publicUserData.__internal_toSnapshot(),last_active_token:this.lastActiveToken?.__internal_toSnapshot()||null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async _getToken(e){if(!this.user)return null;let{leewayInSeconds:t,template:a,skipCache:r=!1}=e||{},n=void 0===e?.organizationId?this.lastActiveOrganizationId:e?.organizationId;if(!a&&Number(t)>=60)throw Error("Leeway can not exceed the token lifespan (60 seconds)");let i=this.#eo(a,n),s=r?void 0:aT.get({tokenId:i},t),o=!a&&n===this.lastActiveOrganizationId;if(s){tt.debug("Using cached token (no fetch needed)",{tokenId:i},"session");let e=await s.tokenResolver;return o&&re.emit(a6,{token:e}),e.getRawString()||null}tt.info("Fetching new token from API",{organizationId:n,template:a,tokenId:i},"session");let l=a?`${this.path()}/tokens/${a}`:`${this.path()}/tokens`,c=a?{}:{organizationId:n},u=rK.create(l,c,r);return aT.set({tokenId:i,tokenResolver:u}),u.then(e=>(o&&(re.emit(a6,{token:e}),e.jwt&&(this.lastActiveToken=e,re.emit(a7,null))),e.getRawString()||null))}get currentTask(){let[e]=this.tasks??[];return e}}class rC extends tF{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}static retrieve(){let e=tF.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new rC(e,"/me/sessions"))).catch(()=>[])}revoke(){return this._basePost({action:"revoke",body:{}})}fromJSON(e){let t;return e?(this.id=e.id,this.status=e.status,this.expireAt=tL(e.expire_at),this.abandonAt=tL(e.abandon_at),this.lastActiveAt=tL(e.last_active_at||void 0),this.latestActivity={id:(t=e.latest_activity??{}).id,deviceType:t.device_type,browserName:t.browser_name,browserVersion:t.browser_version,country:t.country,city:t.city,isMobile:t.is_mobile,ipAddress:t.ip_address},this.actor=e.actor,this):this}}let rP=(e,t,a)=>{let{onValidation:r=e3,onValidationComplexity:n=e3}=a||{},{show_zxcvbn:i,validatePassword:s}=t,o=e=>((e,t)=>{let{max_length:a,min_length:r,require_special_char:n,require_lowercase:i,require_numbers:s,require_uppercase:o}=t,l=(e=>{let t;if(e.allowed_special_characters){let a=e.allowed_special_characters.replace("[","\\[");a=a.replace("]","\\]"),t=RegExp(`[${a}]`)}else t=/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/;return(e,{minLength:a,maxLength:r})=>({max_length:e.length<r,min_length:e.length>=a,require_numbers:/\d/.test(e),require_lowercase:/[a-z]/.test(e),require_uppercase:/[A-Z]/.test(e),require_special_char:t.test(e)})})(t)(e,{maxLength:t.max_length,minLength:t.min_length}),c={max_length:a,min_length:r,require_special_char:n,require_lowercase:i,require_numbers:s,require_uppercase:o},u=new Map;for(let e in c)c[e]&&!l[e]&&u.set(e,!0);return Object.freeze(Object.fromEntries(u))})(e,t),l=(({min_zxcvbn_strength:e,onResult:t})=>a=>r=>{let n=a(r);return(t?.(n),n.score>=e&&n.score<3)?{state:"pass",keys:["unstable__errors.zxcvbn.couldBeStronger"],result:n}:n.score>=e?{state:"excellent",result:n}:{state:"fail",keys:["unstable__errors.zxcvbn.notEnough",...n.feedback.suggestions.map(e=>`unstable__errors.zxcvbn.suggestions.${e}`)],result:n}})(t),c={};return(t,a)=>{let{onValidation:u=r,onValidationComplexity:d=n}=a||{};if(!s)return;let h=o(t);d(0===Object.keys(h).length),c={...c,complexity:h},i&&e().then(e=>{let a=l(e)(t);u({...c={...c,strength:a},strength:a})}),c.complexity&&0===Object.keys(c.complexity).length&&i||u(c)}};function rq(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function rO(e,t,a,r,n){if(!e.client||!r.popup)return;let i=rq(e.frontendApi),{redirectUrl:s}=r,o=new URL(s);o.searchParams.set("sign_in_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("sign_up_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("intent",t);let l=e.buildUrlWithAuth(o.toString()),c=e.buildUrlWithAuth(`${i}/popup-callback`),u=e.buildUrlWithAuth(`${i}/popup-callback?return_url=${encodeURIComponent(l)}`),d=async t=>{if(t.origin!==i)return;let a=!1;if(t.data.session){if(!e.client?.sessions.find(e=>e.id===t.data.session))try{await e.client?.reload()}catch(e){console.error(e)}await e.setActive({session:t.data.session,redirectUrl:r.redirectUrlComplete}),a=!0}else t.data.return_url&&(e.navigate(t.data.return_url),a=!0);a&&window.removeEventListener("message",d)};window.addEventListener("message",d),await a({...r,redirectUrlComplete:c,redirectUrl:u},n)}function rT(e,{redirectCallbackUrl:t,redirectUrl:a}){let r=rq(e.frontendApi),n=new URL(t);n.searchParams.set("sign_in_force_redirect_url",a),n.searchParams.set("sign_up_force_redirect_url",a);let i=e.buildUrlWithAuth(n.toString()),s=e.buildUrlWithAuth(`${r}/popup-callback`);return{redirectCallbackUrl:e.buildUrlWithAuth(`${r}/popup-callback?return_url=${encodeURIComponent(i)}`),redirectUrl:s}}function rU(e,t){return new Promise((a,r)=>{if(!e.client||!t.popup)return void r();let n=async t=>{t.origin===rq(e.frontendApi)&&(t.data.session||t.data.return_url?(window.removeEventListener("message",n),a()):r())};window.addEventListener("message",n),t.popup.location.href=t.externalVerificationRedirectURL.toString()})}async function rM(e,t){re.emit("resource:error",{resource:e,error:null}),re.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await t(),error:null}}catch(t){return re.emit("resource:error",{resource:e,error:t}),{error:t}}finally{re.emit("resource:fetch",{resource:e,status:"idle"})}}let rR=()=>{var e;return(e=new to,{loadZxcvbn:()=>Promise.all([e.import("@zxcvbn-ts/core"),e.import("@zxcvbn-ts/language-common")]).then(([e,t])=>{if(!e||!t)throw Error("Failed to load zxcvbn modules");let{zxcvbnOptions:a,zxcvbn:r}=e,{dictionary:n,adjacencyGraphs:i}=t;return a.setOptions({dictionary:{...n},graphs:i}),r})}).loadZxcvbn};class rB extends tF{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new a1(null);secondFactorVerification=new a1(null);identifier=null;createdSessionId=null;userData=new rJ(null);clientTrustState;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&tt.debug("SignIn.status",{id:this.id,from:t,to:e})}__internal_future=new rN(this);__internal_basePost=this._basePost.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=e=>{tt.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let t=tf();return this._basePost({path:this.pathRoot,body:t?{locale:t,...e}:e})};resetPassword=e=>this._basePost({body:e,action:"reset_password"});prepareFirstFactor=e=>{let t;switch(tt.debug("SignIn.prepareFirstFactor",{id:this.id,strategy:e.strategy}),e.strategy){case"passkey":t={};break;case"email_link":t={emailAddressId:e.emailAddressId,redirectUrl:e.redirectUrl};break;case"email_code":case"reset_password_email_code":t={emailAddressId:e.emailAddressId};break;case"phone_code":t={phoneNumberId:e.phoneNumberId,default:e.default,channel:e.channel};break;case"web3_metamask_signature":case"web3_base_signature":case"web3_coinbase_wallet_signature":case"web3_okx_wallet_signature":t={web3WalletId:e.web3WalletId};break;case"reset_password_phone_code":t={phoneNumberId:e.phoneNumberId};break;case"enterprise_sso":t={redirectUrl:e.redirectUrl,actionCompleteRedirectUrl:e.actionCompleteRedirectUrl,oidcPrompt:e.oidcPrompt,enterpriseConnectionId:e.enterpriseConnectionId};break;default:tE("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...t,strategy:e.strategy},action:"prepare_first_factor"})};attemptFirstFactor=e=>{let t;return tt.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(aY(e.publicKeyCredential))}:{...e},this._basePost({body:{...t,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:t}=aL();return{startEmailLinkFlow:async({emailAddressId:a,redirectUrl:r})=>{this.id||tA("SignIn");let n={strategy:"email_link",emailAddressId:a,redirectUrl:r},i="needs_second_factor"===this.status||"needs_client_trust"===this.status,s=i?"secondFactorVerification":"firstFactorVerification";return i?await this.prepareSecondFactor(n):await this.prepareFirstFactor(n),new Promise((a,r)=>{e(()=>this.reload().then(e=>{let r=e[s].status;("verified"===r||"expired"===r)&&(t(),a(e))}).catch(e=>{t(),r(e)}))})},cancelEmailLinkFlow:t}};prepareSecondFactor=e=>(tt.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(tt.debug("SignIn.attemptSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_second_factor"}));authenticateWithRedirectOrPopup=async(e,t)=>{let{strategy:a,redirectUrlComplete:r,identifier:n,oidcPrompt:i,continueSignIn:s,enterpriseConnectionId:o}=e||{},l=rB.clerk.buildUrlWithAuth(e.redirectUrl);this.id&&s||await this.create({strategy:a,identifier:n,redirectUrl:l,actionCompleteRedirectUrl:r}),"enterprise_sso"===a&&await this.prepareFirstFactor({strategy:a,redirectUrl:l,actionCompleteRedirectUrl:r,oidcPrompt:i,enterpriseConnectionId:o});let{status:c,externalVerificationRedirectURL:u}=this.firstFactorVerification;"unverified"===c&&u?t(u):tP(c,rB.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eW);authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||tC("popup"),rO(rB.clerk,"signIn",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e.toString()})};authenticateWithWeb3=async e=>{let t,{identifier:a,generateSignature:r,strategy:n="web3_metamask_signature"}=e||{},i=n.replace("web3_","").replace("_signature","");"function"!=typeof r&&tC("generateSignature"),await this.create({identifier:a});let s=this.supportedFirstFactors?.find(e=>e.strategy===n);s||tI("SignIn"),await this.prepareFirstFactor(s);let{message:o}=this.firstFactorVerification;o||tI("SignIn");try{t=await r({identifier:a,nonce:o,provider:i})}catch(e){if("coinbase_wallet"===i&&4001===e.code)t=await r({identifier:a,nonce:o,provider:i});else throw e}return this.attemptFirstFactor({signature:t,strategy:n})};authenticateWithMetamask=async()=>{let e=await tw().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tw().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await tw().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tw().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await tw().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tw().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await tw().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tw().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithPasskey=async e=>{let{flow:t}=e||{},a=rB.clerk.__internal_isWebAuthnSupported||rg,r=rB.clerk.__internal_getPublicCredentials||aG,n=rB.clerk.__internal_isWebAuthnAutofillSupported||rb;if(!a())throw new I("Passkeys are not supported",{code:"passkey_not_supported"});if("autofill"===t||"discoverable"===t)await this.create({strategy:"passkey"});else{let e=this.supportedFirstFactors.find(e=>"passkey"===e.strategy);e||function(){throw Error(`${t_} You need to start a SignIn flow by calling SignIn.create({ strategy: 'passkey' }) first`)}(),await this.prepareFirstFactor(e)}let{nonce:i}=this.firstFactorVerification,s=i?aZ(JSON.parse(i)):null;s||tq("get");let o=!1;"autofill"===t&&(o=await n());let{publicKeyCredential:l,error:c}=await r({publicKeyOptions:s,conditionalUI:o});if(!l)throw c;return this.attemptFirstFactor({publicKeyCredential:l,strategy:"passkey"})};validatePassword=(e,t)=>{if(rB.clerk.__internal_environment?.userSettings.passwordSettings)return rP(rR(),{...rB.clerk.__internal_environment?.userSettings.passwordSettings,validatePassword:!0})(e,t)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.supportedIdentifiers=e.supported_identifiers,this.identifier=e.identifier,this.supportedFirstFactors=er(e.supported_first_factors),this.supportedSecondFactors=er(e.supported_second_factors),this.firstFactorVerification=new a1(e.first_factor_verification),this.secondFactorVerification=new a1(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new rJ(e.user_data),this.clientTrustState=e.client_trust_state??void 0),re.emit("resource:update",{resource:this}),this}__internal_toSnapshot(){return{object:"sign_in",id:this.id||"",status:this.status||null,supported_identifiers:this.supportedIdentifiers,supported_first_factors:ea(this.supportedFirstFactors),supported_second_factors:ea(this.supportedSecondFactors),first_factor_verification:this.firstFactorVerification.__internal_toSnapshot(),second_factor_verification:this.secondFactorVerification.__internal_toSnapshot(),identifier:this.identifier,created_session_id:this.createdSessionId,user_data:this.userData.__internal_toSnapshot()}}}class rN{emailCode={sendCode:this.sendEmailCode.bind(this),verifyCode:this.verifyEmailCode.bind(this)};emailLink={sendLink:this.sendEmailLink.bind(this),waitForVerification:this.waitForEmailLinkVerification.bind(this),get verification(){if(!s())return null;const e=eO("__clerk_status"),t=eO("__clerk_created_session");if(!e||!t)return null;const a="verified"===e&&void 0!==rB.clerk.client&&rB.clerk.client.sessions.some(e=>e.id===t);return{status:e,createdSessionId:t,verifiedFromTheSameClient:a}}};resetPasswordEmailCode={sendCode:this.sendResetPasswordEmailCode.bind(this),verifyCode:this.verifyResetPasswordEmailCode.bind(this),submitPassword:this.submitResetPassword.bind(this)};phoneCode={sendCode:this.sendPhoneCode.bind(this),verifyCode:this.verifyPhoneCode.bind(this)};mfa={sendPhoneCode:this.sendMFAPhoneCode.bind(this),verifyPhoneCode:this.verifyMFAPhoneCode.bind(this),verifyTOTP:this.verifyTOTP.bind(this),verifyBackupCode:this.verifyBackupCode.bind(this)};#el=!1;#ec;constructor(e){this.#ec=e}get id(){return this.#ec.id}get identifier(){return this.#ec.identifier}get createdSessionId(){return this.#ec.createdSessionId}get userData(){return this.#ec.userData}get status(){return this.#ec.status||"needs_identifier"}get supportedFirstFactors(){return this.#ec.supportedFirstFactors??[]}get supportedSecondFactors(){return this.#ec.supportedSecondFactors??[]}get isTransferable(){return"transferable"===this.#ec.firstFactorVerification.status}get existingSession(){if("failed"===this.#ec.firstFactorVerification.status&&this.#ec.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.#ec.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.#ec.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.#ec.firstFactorVerification}get secondFactorVerification(){return this.#ec.secondFactorVerification}get hasBeenFinalized(){return this.#el}async sendResetPasswordEmailCode(){if(!this.#ec.id)throw Error("Cannot reset password without a sign in.");return rM(this.#ec,async()=>{let e=this.#ec.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new A("Reset password email code factor not found",{code:"factor_not_found"});let{emailAddressId:t}=e;await this.#ec.__internal_basePost({body:{emailAddressId:t,strategy:"reset_password_email_code"},action:"prepare_first_factor"})})}async verifyResetPasswordEmailCode(e){let{code:t}=e;return rM(this.#ec,async()=>{await this.#ec.__internal_basePost({body:{code:t,strategy:"reset_password_email_code"},action:"attempt_first_factor"})})}async submitResetPassword(e){let{password:t,signOutOfOtherSessions:a=!0}=e;return rM(this.#ec,async()=>{await this.#ec.__internal_basePost({body:{password:t,signOutOfOtherSessions:a},action:"reset_password"})})}async _create(e){let t=tf();await this.#ec.__internal_basePost({path:this.#ec.pathRoot,body:t?{locale:t,...e}:e})}async create(e){return rM(this.#ec,async()=>{await this._create(e)})}async password(e){if([e.identifier,e.emailAddress,e.phoneNumber].filter(Boolean).length>1)throw Error("Only one of identifier, emailAddress, or phoneNumber can be provided");return rM(this.#ec,async()=>{let t=e.identifier||e.emailAddress||e.phoneNumber,a=this.#ec.identifier,r=tf();await this.#ec.__internal_basePost({path:this.#ec.pathRoot,body:{identifier:t||a,password:e.password,...r?{locale:r}:{}}})})}async sendEmailCode(e={}){let{emailAddress:t,emailAddressId:a}=e;if(!this.#ec.id&&a)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#ec.id&&!t)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return rM(this.#ec,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:a});if(!e)throw new A("Email code factor not found",{code:"factor_not_found"});await this.#ec.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor"})})}async verifyEmailCode(e){let{code:t}=e;return rM(this.#ec,async()=>{await this.#ec.__internal_basePost({body:{code:t,strategy:"email_code"},action:"attempt_first_factor"})})}async sendEmailLink(e){let{emailAddress:t,verificationUrl:a,emailAddressId:r}=e;if(!this.#ec.id&&r)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#ec.id&&!t)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return rM(this.#ec,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:r});if(!e)throw new A("Email link factor not found",{code:"factor_not_found"});let n=a;try{new URL(a)}catch{n=window.location.origin+a}await this.#ec.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:n,strategy:"email_link"},action:"prepare_first_factor"})})}async waitForEmailLinkVerification(){return rM(this.#ec,async()=>{let{run:e,stop:t}=aL();await new Promise((a,r)=>{e(async()=>{try{let e=await this.#ec.__internal_baseGet(),r=e.firstFactorVerification.status;("verified"===r||"expired"===r)&&(t(),a(e))}catch(e){t(),r(e)}})})})}async sendPhoneCode(e={}){let{phoneNumber:t,phoneNumberId:a,channel:r="sms"}=e;if(!this.#ec.id&&a)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.#ec.id&&!t)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return rM(this.#ec,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:a});if(!e)throw new A("Phone code factor not found",{code:"factor_not_found"});await this.#ec.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:r},action:"prepare_first_factor"})})}async verifyPhoneCode(e){let{code:t}=e;return rM(this.#ec,async()=>{await this.#ec.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_first_factor"})})}async sso(e){let{strategy:t,redirectUrl:a,redirectCallbackUrl:r,popup:n,oidcPrompt:i,enterpriseConnectionId:s,identifier:o}=e;return rM(this.#ec,async()=>{let e=a;try{new URL(a)}catch{e=window.location.origin+a}let l={redirectUrl:rB.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(n){let t=rT(rB.clerk,{redirectCallbackUrl:l.redirectUrl,redirectUrl:e});l.redirectUrl=t.redirectCallbackUrl,l.actionCompleteRedirectUrl=t.redirectUrl}await this._create({strategy:t,...l,identifier:o}),"enterprise_sso"===t&&await this.#ec.__internal_basePost({body:{...l,oidcPrompt:i,enterpriseConnectionId:s,strategy:"enterprise_sso"},action:"prepare_first_factor"});let{status:c,externalVerificationRedirectURL:u}=this.#ec.firstFactorVerification;"unverified"===c&&u&&(n?(await rU(rB.clerk,{popup:n,externalVerificationRedirectURL:u}),await this.#ec.reload()):eW(u))})}async web3(e){let{strategy:t}=e,a=t.replace("web3_","").replace("_signature","");return rM(this.#ec,async()=>{let e,r,n;switch(a){case"metamask":e=await tw().getMetamaskIdentifier(),r=tw().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await tw().getCoinbaseWalletIdentifier(),r=tw().generateSignatureWithCoinbaseWallet;break;case"base":e=await tw().getBaseIdentifier(),r=tw().generateSignatureWithBase;break;case"okx_wallet":e=await tw().getOKXWalletIdentifier(),r=tw().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${a}`)}await this._create({identifier:e});let i=this.#ec.supportedFirstFactors?.find(e=>e.strategy===t);if(!i)throw new A("Web3 first factor not found",{code:"factor_not_found"});await this.#ec.__internal_basePost({body:{web3WalletId:i.web3WalletId,strategy:t},action:"prepare_first_factor"});let{message:s}=this.firstFactorVerification;if(!s)throw new A("Web3 nonce not found",{code:"web3_nonce_not_found"});try{n=await r({identifier:e,nonce:s})}catch(t){if("coinbase_wallet"===a&&4001===t.code)n=await r({identifier:e,nonce:s});else throw t}await this.#ec.__internal_basePost({body:{signature:n,strategy:t},action:"attempt_first_factor"})})}async passkey(e){let{flow:t}=e||{},a=rB.clerk.__internal_isWebAuthnSupported||rg,r=rB.clerk.__internal_getPublicCredentials||aG,n=rB.clerk.__internal_isWebAuthnAutofillSupported||rb;if(!a())throw new I("Passkeys are not supported",{code:"passkey_not_supported"});return rM(this.#ec,async()=>{if("autofill"===t||"discoverable"===t)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new A("Passkey factor not found",{code:"factor_not_found"});await this.#ec.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor"})}let{nonce:e}=this.firstFactorVerification,a=e?aZ(JSON.parse(e)):null;if(!a)throw new A("Missing public key options",{code:"missing_public_key_options"});let i=!1;"autofill"===t&&(i=await n());let{publicKeyCredential:s,error:o}=await r({publicKeyOptions:a,conditionalUI:i});if(!s)throw new I(o.message,{code:"passkey_retrieval_failed"});await this.#ec.__internal_basePost({body:{publicKeyCredential:JSON.stringify(aY(s)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return rM(this.#ec,async()=>{let e=this.#ec.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new A("Phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:t}=e;await this.#ec.__internal_basePost({body:{phoneNumberId:t,strategy:"phone_code"},action:"prepare_second_factor"})})}async verifyMFAPhoneCode(e){let{code:t}=e;return rM(this.#ec,async()=>{await this.#ec.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:t}=e;return rM(this.#ec,async()=>{await this.#ec.__internal_basePost({body:{code:t,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:t}=e;return rM(this.#ec,async()=>{await this.#ec.__internal_basePost({body:{code:t,strategy:"backup_code"},action:"attempt_second_factor"})})}async ticket(e){let t=e?.ticket??eO("__clerk_ticket");return this.create({ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};if(!this.#ec.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return rM(this.#ec,async()=>{rB.clerk.client&&!rB.clerk.client.sessions.some(e=>e.id===this.#ec.createdSessionId)&&await rB.clerk.client.reload(),this.#el=!0,await rB.clerk.setActive({session:this.#ec.createdSessionId,navigate:t})})}selectFirstFactor({strategy:e,emailAddressId:t,phoneNumberId:a}){if(!this.#ec.supportedFirstFactors)return null;if(t){let a=this.#ec.supportedFirstFactors.find(a=>a.strategy===e&&a.emailAddressId===t);if(a)return a}if(a){let t=this.#ec.supportedFirstFactors.find(t=>t.strategy===e&&t.phoneNumberId===a);if(t)return t}let r=this.#ec.supportedFirstFactors.find(t=>t.strategy===e&&t.safeIdentifier===this.#ec.identifier);if(r)return r;let n=this.#ec.supportedFirstFactors.find(t=>t.strategy===e);return n||null}}function rD(e){let{unsafeMetadata:t}={...e},a=t?"object"==typeof t?JSON.stringify(t):t:"";return{...e,...t?{unsafeMetadata:a}:{}}}class rF extends tF{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new a2(null);username=null;firstName=null;lastName=null;emailAddress=null;phoneNumber=null;web3wallet=null;externalAccount;hasPassword=!1;unsafeMetadata={};createdSessionId=null;createdUserId=null;abandonAt=null;legalAcceptedAt=null;locale=null;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&tt.debug("SignUp.status",{id:this.id,from:t,to:e})}__internal_future=new rL(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{tt.debug("SignUp.create",{id:this.id,strategy:e.strategy});let t={...e};if(!t.locale){let e=tf();e&&(t.locale=e)}if(!this.clientBypass()&&!this.shouldBypassCaptchaForAttempt(e)){let e=new tN(rF.clerk),a=await e.managedOrInvisible({action:"signup"});if(!a)throw new A("",{code:"captcha_unavailable"});t={...t,...a}}if(t.transfer&&this.shouldBypassCaptchaForAttempt(t)){let e=rF.clerk.client?.signIn.firstFactorVerification.strategy;e&&(t={...t,strategy:e})}return this._basePost({path:this.pathRoot,body:rD(t)})};prepareVerification=e=>(tt.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(tt.debug("SignUp.attemptVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_verification"}));prepareEmailAddressVerification=e=>this.prepareVerification(e||{strategy:"email_code"});attemptEmailAddressVerification=e=>this.attemptVerification({...e,strategy:"email_code"});createEmailLinkFlow=()=>{let{run:e,stop:t}=aL();return{startEmailLinkFlow:async({redirectUrl:a})=>(this.id||tA("SignUp"),await this.prepareEmailAddressVerification({strategy:"email_link",redirectUrl:a}),new Promise((a,r)=>{e(()=>this.reload().then(e=>{let r=e.verifications.emailAddress.status;("verified"===r||"expired"===r)&&(t(),a(e))}).catch(e=>{t(),r(e)}))})),cancelEmailLinkFlow:t}};preparePhoneNumberVerification=e=>this.prepareVerification(e||{strategy:"phone_code"});attemptPhoneNumberVerification=e=>this.attemptVerification({...e,strategy:"phone_code"});prepareWeb3WalletVerification=e=>this.prepareVerification({strategy:"web3_metamask_signature",...e});attemptWeb3WalletVerification=async e=>{let{signature:t,strategy:a="web3_metamask_signature"}=e;return this.attemptVerification({signature:t,strategy:a})};authenticateWithWeb3=async e=>{let t,{generateSignature:a,identifier:r,unsafeMetadata:n,strategy:i="web3_metamask_signature",legalAccepted:s}=e||{},o=i.replace("web3_","").replace("_signature","");"function"!=typeof a&&tC("generateSignature");let l=r||this.web3wallet;await this.create({web3Wallet:l,unsafeMetadata:n,legalAccepted:s}),await this.prepareWeb3WalletVerification({strategy:i});let{message:c}=this.verifications.web3Wallet;c||tI("SignUp");try{t=await a({identifier:r,nonce:c,provider:o})}catch(e){if("coinbase_wallet"===o&&4001===e.code)t=await a({identifier:r,nonce:c,provider:o});else throw e}return this.attemptWeb3WalletVerification({signature:t,strategy:i})};authenticateWithMetamask=async e=>{let t=await tw().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tw().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let t=await tw().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tw().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let t=await tw().getBaseIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tw().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let t=await tw().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tw().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithRedirectOrPopup=async(e,t)=>{let{redirectUrl:a,redirectUrlComplete:r,strategy:n,continueSignUp:i=!1,unsafeMetadata:s,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:u}=e,d=rF.clerk.buildUrlWithAuth(a),h=()=>{let e={strategy:n,redirectUrl:d,actionCompleteRedirectUrl:r,unsafeMetadata:s,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:u};return i&&this.id?this.update(e):this.create(e)},{verifications:m}=await h().catch(async e=>{if(O(e)&&C(e))return await rF.clerk.__internal_environment.reload(),h();throw e}),{externalAccount:p}=m,{status:f,externalVerificationRedirectURL:g}=p;"unverified"===f&&g?t(g):tP(f,rF.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eW);authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||tC("popup"),rO(rF.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:rD(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,t)=>{if(rF.clerk.__internal_environment?.userSettings.passwordSettings)return rP(rR(),{...rF.clerk.__internal_environment?.userSettings.passwordSettings,validatePassword:!0})(e,t)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.requiredFields=e.required_fields,this.optionalFields=e.optional_fields,this.missingFields=e.missing_fields,this.unverifiedFields=e.unverified_fields,this.verifications=new a2(e.verifications),this.username=e.username,this.firstName=e.first_name,this.lastName=e.last_name,this.emailAddress=e.email_address,this.phoneNumber=e.phone_number,this.hasPassword=e.has_password,this.unsafeMetadata=e.unsafe_metadata,this.createdSessionId=e.created_session_id,this.createdUserId=e.created_user_id,this.abandonAt=e.abandon_at,this.web3wallet=e.web3_wallet,this.legalAcceptedAt=e.legal_accepted_at,this.locale=e.locale),re.emit("resource:update",{resource:this}),this}__internal_toSnapshot(){return{object:"sign_up",id:this.id||"",status:this.status||null,required_fields:this.requiredFields,optional_fields:this.optionalFields,missing_fields:this.missingFields,unverified_fields:this.unverifiedFields,verifications:this.verifications.__internal_toSnapshot(),username:this.username,first_name:this.firstName,last_name:this.lastName,email_address:this.emailAddress,phone_number:this.phoneNumber,has_password:this.hasPassword,unsafe_metadata:this.unsafeMetadata,created_session_id:this.createdSessionId,created_user_id:this.createdUserId,abandon_at:this.abandonAt,web3_wallet:this.web3wallet,legal_accepted_at:this.legalAcceptedAt,locale:this.locale,external_account:this.externalAccount,external_account_strategy:this.externalAccount?.strategy}}clientBypass(){return rF.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){if(!e.strategy)return!1;let t=rF.clerk.__internal_environment.displayConfig.captchaOauthBypass;return!!(t.some(t=>t===e.strategy)||e.transfer&&t.some(e=>e===rF.clerk.client.signIn.firstFactorVerification.strategy))}__experimental_getEnterpriseConnections=()=>tF._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new rW(e)))}class rL{verifications={sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)};#el=!1;#ec;constructor(e){this.#ec=e}get id(){return this.#ec.id}get requiredFields(){return this.#ec.requiredFields}get optionalFields(){return this.#ec.optionalFields}get missingFields(){return this.#ec.missingFields}get status(){return this.#ec.status||"missing_requirements"}get username(){return this.#ec.username}get firstName(){return this.#ec.firstName}get lastName(){return this.#ec.lastName}get emailAddress(){return this.#ec.emailAddress}get phoneNumber(){return this.#ec.phoneNumber}get web3Wallet(){return this.#ec.web3wallet}get hasPassword(){return this.#ec.hasPassword}get unsafeMetadata(){return this.#ec.unsafeMetadata}get createdSessionId(){return this.#ec.createdSessionId}get createdUserId(){return this.#ec.createdUserId}get abandonAt(){return this.#ec.abandonAt}get legalAcceptedAt(){return this.#ec.legalAcceptedAt}get locale(){return this.#ec.locale}get unverifiedFields(){return this.#ec.unverifiedFields}get isTransferable(){return"transferable"===this.#ec.verifications.externalAccount.status&&this.#ec.verifications.externalAccount.error?.code==="external_account_exists"}get existingSession(){if(("failed"===this.#ec.verifications.externalAccount.status||"unverified"===this.#ec.verifications.externalAccount.status)&&this.#ec.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.#ec.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.#ec.verifications.externalAccount.error?.meta?.sessionId}}get hasBeenFinalized(){return this.#el}async getCaptchaToken(){let e=new tN(rF.clerk),t=await e.managedOrInvisible({action:"signup"});if(!t)throw Error("Captcha challenge failed");let{captchaError:a,captchaToken:r,captchaWidgetType:n}=t;return{captchaToken:r,captchaWidgetType:n,captchaError:a}}async _create(e){let{captchaToken:t,captchaWidgetType:a,captchaError:r}=await this.getCaptchaToken(),n={transfer:e.transfer,captchaToken:t,captchaWidgetType:a,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rD(e.unsafeMetadata):void 0,locale:e.locale??tf()};await this.#ec.__internal_basePost({path:this.#ec.pathRoot,body:n})}async create(e){return rM(this.#ec,async()=>{await this._create(e)})}async update(e){return rM(this.#ec,async()=>{let t={...e,unsafeMetadata:e.unsafeMetadata?rD(e.unsafeMetadata):void 0};await this.#ec.__internal_basePatch({path:this.#ec.pathRoot,body:t})})}async password(e){return rM(this.#ec,async()=>{let{captchaToken:t,captchaWidgetType:a,captchaError:r}=await this.getCaptchaToken(),n={strategy:"password",captchaToken:t,captchaWidgetType:a,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rD(e.unsafeMetadata):void 0};await this.#ec.__internal_basePost({path:this.#ec.pathRoot,body:n})})}async sendEmailCode(){return rM(this.#ec,async()=>{await this.#ec.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:t}=e;return rM(this.#ec,async()=>{await this.#ec.__internal_basePost({body:{strategy:"email_code",code:t},action:"attempt_verification"})})}async sendPhoneCode(e){let{phoneNumber:t,channel:a="sms"}=e;return rM(this.#ec,async()=>{if(!this.#ec.id){let{captchaToken:e,captchaWidgetType:a,captchaError:r}=await this.getCaptchaToken();await this.#ec.__internal_basePost({path:this.#ec.pathRoot,body:{phoneNumber:t,captchaToken:e,captchaWidgetType:a,captchaError:r}})}await this.#ec.__internal_basePost({body:{strategy:"phone_code",channel:a},action:"prepare_verification"})})}async verifyPhoneCode(e){let{code:t}=e;return rM(this.#ec,async()=>{await this.#ec.__internal_basePost({body:{strategy:"phone_code",code:t},action:"attempt_verification"})})}async sso(e){let{strategy:t,redirectUrl:a,redirectCallbackUrl:r,unsafeMetadata:n,legalAccepted:i,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,popup:c}=e;return rM(this.#ec,async()=>{let{captchaToken:e,captchaWidgetType:u,captchaError:d}=await this.getCaptchaToken(),h=a;try{new URL(a)}catch{h=window.location.origin+a}let m={redirectUrl:rF.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:h};if(c){let e=rT(rF.clerk,{redirectCallbackUrl:m.redirectUrl,redirectUrl:h});m.redirectUrl=e.redirectCallbackUrl,m.actionCompleteRedirectUrl=e.redirectUrl}let p=()=>this.#ec.__internal_basePost({path:this.#ec.pathRoot,body:{strategy:t,...m,unsafeMetadata:n,legalAccepted:i,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,captchaToken:e,captchaWidgetType:u,captchaError:d}});await p().catch(async e=>{if(O(e)&&C(e))return await rF.clerk.__internal_environment.reload(),p();throw e});let{status:f,externalVerificationRedirectURL:g}=this.#ec.verifications.externalAccount;"unverified"===f&&g&&(c?(await rU(rF.clerk,{popup:c,externalVerificationRedirectURL:g}),await this.#ec.reload()):eW(g))})}async web3(e){let{strategy:t,unsafeMetadata:a,legalAccepted:r}=e,n=t.replace("web3_","").replace("_signature","");return rM(this.#ec,async()=>{let e,i,s;switch(n){case"metamask":e=await tw().getMetamaskIdentifier(),i=tw().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await tw().getCoinbaseWalletIdentifier(),i=tw().generateSignatureWithCoinbaseWallet;break;case"base":e=await tw().getBaseIdentifier(),i=tw().generateSignatureWithBase;break;case"okx_wallet":e=await tw().getOKXWalletIdentifier(),i=tw().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${n}`)}let o=e||this.#ec.web3wallet;await this._create({web3Wallet:o,unsafeMetadata:a,legalAccepted:r}),await this.#ec.__internal_basePost({body:{strategy:t},action:"prepare_verification"});let{message:l}=this.#ec.verifications.web3Wallet;l||tI("SignUp");try{s=await i({identifier:e,nonce:l})}catch(t){if("coinbase_wallet"===n&&4001===t.code)s=await i({identifier:e,nonce:l});else throw t}await this.#ec.__internal_basePost({body:{signature:s,strategy:t},action:"attempt_verification"})})}async ticket(e){let t=e?.ticket??eO("__clerk_ticket");return this.create({...e,ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};return rM(this.#ec,async()=>{if(!this.#ec.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#el=!0,await rF.clerk.setActive({session:this.#ec.createdSessionId,navigate:t})})}}class rW extends tF{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class rK extends tF{pathRoot="tokens";jwt;static async create(e,t={},a=!1){return new rK(await tF._fetch({body:t,method:"POST",path:e,search:a?"debug=skip_cache":void 0}),e)}constructor(e,t){super(),t&&(this.pathRoot=t),e?.jwt&&(this.jwt=tp(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=tp(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class rH extends tF{pathRoot="/me";id="";secret;uri;verified=!1;backupCodes;updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.secret=e.secret,this.uri=e.uri,this.verified=e.verified,this.backupCodes=e.backup_codes,this.updatedAt=tL(e.updated_at),this.createdAt=tL(e.created_at)),this}}class rV extends tF{pathRoot="/me";id;codes=[];updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.codes=e.codes,this.updatedAt=tL(e.updated_at),this.createdAt=tL(e.created_at)),this}}class rG extends tF{pathRoot="/me";id="";externalId=null;username=null;emailAddresses=[];phoneNumbers=[];web3Wallets=[];externalAccounts=[];enterpriseAccounts=[];passkeys=[];organizationMemberships=[];passwordEnabled=!1;firstName=null;lastName=null;fullName=null;primaryEmailAddressId=null;primaryEmailAddress=null;primaryPhoneNumberId=null;primaryPhoneNumber=null;primaryWeb3WalletId=null;primaryWeb3Wallet=null;imageUrl="";hasImage=!1;twoFactorEnabled=!1;totpEnabled=!1;backupCodeEnabled=!1;publicMetadata={};unsafeMetadata={};createOrganizationEnabled=!1;createOrganizationsLimit=null;deleteSelfEnabled=!1;lastSignInAt=null;legalAcceptedAt=null;updatedAt=null;createdAt=null;cachedSessionsWithActivities=null;static isUserResource(e){return!!e&&e instanceof rG}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case aW:return this.primaryEmailAddressId===e.id;case rk:return this.primaryPhoneNumberId===e.id;case rQ:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:t}=e||{};return new aW({email_address:t},this.path()+"/email_addresses/").create()};createPasskey=()=>rw.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:t}=e||{};return new rk({phone_number:t},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:t}=e||{};return new rQ({web3_wallet:t},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:t,redirectUrl:a,additionalScopes:r}=e||{};return new rn((await tF._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:t,redirect_url:a,additional_scope:r}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new rH((await tF._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new rH((await tF._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new aR((await tF._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new rV((await tF._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=e=>this._basePatch({body:rD(e)});updatePassword=e=>this._basePost({body:e,path:`${this.path()}/change_password`});removePassword=e=>this._basePost({body:e,path:`${this.path()}/remove_password`});delete=()=>this._baseDelete({path:"/me"}).then(e=>(re.emit(a8,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await rC.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:t}=e||{};return null===t?ro.delete(`${this.path()}/profile_image`):ro.create(`${this.path()}/profile_image`,{file:t})};getOrganizationInvitations=e=>rZ.retrieve(e);getOrganizationSuggestions=e=>rf.retrieve(e);getOrganizationMemberships=e=>rp.retrieve(e);leaveOrganization=async e=>new aR((await tF._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);initializePaymentMethod=e=>ay(e);addPaymentMethod=e=>aw(e);getPaymentMethods=e=>ak(e);get verifiedExternalAccounts(){return this.externalAccounts.filter(e=>e.verification?.status=="verified")}get unverifiedExternalAccounts(){return this.externalAccounts.filter(e=>e.verification?.status!="verified")}get verifiedWeb3Wallets(){return this.web3Wallets.filter(e=>e.verification?.status=="verified")}get hasVerifiedEmailAddress(){return this.emailAddresses.filter(e=>"verified"===e.verification.status).length>0}get hasVerifiedPhoneNumber(){return this.phoneNumbers.filter(e=>"verified"===e.verification.status).length>0}fromJSON(e){return e&&(this.id=e.id,this.externalId=e.external_id||null,this.firstName=e.first_name||null,this.lastName=e.last_name||null,(this.firstName||this.lastName)&&(this.fullName=(({firstName:e,lastName:t,name:a})=>a||[e,t].join(" ").trim()||"")({firstName:this.firstName,lastName:this.lastName})),this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.username=e.username||null,this.passwordEnabled=e.password_enabled||!1,this.emailAddresses=(e.email_addresses||[]).map(e=>new aW(e,this.path()+"/email_addresses")),this.primaryEmailAddressId=e.primary_email_address_id||null,this.primaryEmailAddress=this.emailAddresses.find(({id:e})=>e===this.primaryEmailAddressId)||null,this.phoneNumbers=(e.phone_numbers||[]).map(e=>new rk(e,this.path()+"/phone_numbers")),this.primaryPhoneNumberId=e.primary_phone_number_id||null,this.primaryPhoneNumber=this.phoneNumbers.find(({id:e})=>e===this.primaryPhoneNumberId)||null,this.web3Wallets=(e.web3_wallets||[]).map(e=>new rQ(e,this.path()+"/web3_wallets")),this.primaryWeb3WalletId=e.primary_web3_wallet_id||null,this.primaryWeb3Wallet=this.web3Wallets.find(({id:e})=>e===this.primaryWeb3WalletId)||null,this.externalAccounts=(e.external_accounts||[]).map(e=>new rn(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new rw(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new rp(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new a3(e,this.path()+"/enterprise_accounts")),this.publicMetadata=e.public_metadata||{},this.unsafeMetadata=e.unsafe_metadata||{},this.totpEnabled=e.totp_enabled||!1,this.backupCodeEnabled=e.backup_code_enabled||!1,this.twoFactorEnabled=e.two_factor_enabled||!1,this.createOrganizationEnabled=e.create_organization_enabled||!1,this.createOrganizationsLimit=e.create_organizations_limit||null,this.deleteSelfEnabled=e.delete_self_enabled||!1,e.last_sign_in_at&&(this.lastSignInAt=tL(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=tL(e.legal_accepted_at)),this.updatedAt=tL(e.updated_at||void 0),this.createdAt=tL(e.created_at||void 0)),this}__internal_toSnapshot(){return{object:"user",id:this.id,external_id:this.externalId,first_name:this.firstName,last_name:this.lastName,username:this.username,public_metadata:this.publicMetadata,unsafe_metadata:this.unsafeMetadata,image_url:this.imageUrl,has_image:this.hasImage,email_addresses:this.emailAddresses.map(e=>e.__internal_toSnapshot()),phone_numbers:this.phoneNumbers.map(e=>e.__internal_toSnapshot()),web3_wallets:this.web3Wallets.map(e=>e.__internal_toSnapshot()),external_accounts:this.externalAccounts.map(e=>e.__internal_toSnapshot()),passkeys:this.passkeys.map(e=>e.__internal_toSnapshot()),organization_memberships:this.organizationMemberships.map(e=>e.__internal_toSnapshot()),enterprise_accounts:this.enterpriseAccounts.map(e=>e.__internal_toSnapshot()),totp_enabled:this.totpEnabled,backup_code_enabled:this.backupCodeEnabled,two_factor_enabled:this.twoFactorEnabled,create_organization_enabled:this.createOrganizationEnabled,create_organizations_limit:this.createOrganizationsLimit,delete_self_enabled:this.deleteSelfEnabled,primary_email_address_id:this.primaryEmailAddressId,primary_phone_number_id:this.primaryPhoneNumberId,primary_web3_wallet_id:this.primaryWeb3WalletId,password_enabled:this.passwordEnabled,profile_image_id:this.imageUrl,last_sign_in_at:this.lastSignInAt?.getTime()||null,legal_accepted_at:this.legalAcceptedAt?.getTime()||null,updated_at:this.updatedAt?.getTime()||null,created_at:this.createdAt?.getTime()||null}}}class rJ{firstName;lastName;imageUrl;hasImage;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.firstName=e.first_name,this.lastName=e.last_name,this.imageUrl=e.image_url??void 0,this.hasImage=e.has_image??void 0),this}__internal_toSnapshot(){return{first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl||null,has_image:this.hasImage||null}}}class rZ extends tF{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await tF._fetch({path:"/me/organization_invitations",method:"GET",search:aa(e)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rZ(e))}})}constructor(e){super(),this.fromJSON(e)}accept=async()=>await this._basePost({path:`/me/organization_invitations/${this.id}/accept`});fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.publicOrganizationData={hasImage:e.public_organization_data.has_image,imageUrl:e.public_organization_data.image_url,name:e.public_organization_data.name,id:e.public_organization_data.id,slug:e.public_organization_data.slug},this.publicMetadata=e.public_metadata,this.role=e.role,this.status=e.status,this.createdAt=tL(e.created_at),this.updatedAt=tL(e.updated_at)),this}}let r$={enabled:!1,first_factors:[],name:"phone_number",required:!1,second_factors:[],used_for_first_factor:!1,used_for_second_factor:!1,verifications:[],verify_at_sign_up:!1};class rY extends tF{id=void 0;actions={create_organization:!1,delete_self:!1};attributes={email_address:{enabled:!0,first_factors:["email_code"],name:"email_address",required:!0,second_factors:[],used_for_first_factor:!0,used_for_second_factor:!1,verifications:["email_code"],verify_at_sign_up:!0},phone_number:{...r$,name:"phone_number"},username:{...r$,name:"username"},web3_wallet:{...r$,name:"web3_wallet"},first_name:{...r$,name:"first_name"},last_name:{...r$,name:"last_name"},password:{enabled:!0,first_factors:[],name:"password",required:!0,second_factors:[],used_for_first_factor:!1,used_for_second_factor:!1,verifications:[],verify_at_sign_up:!1},authenticator_app:{...r$,name:"authenticator_app"},backup_code:{...r$,name:"backup_code"},passkey:{...r$,name:"passkey"}};enterpriseSSO={enabled:!1};passkeySettings={allow_autofill:!1,show_sign_in_button:!1};passwordSettings={};signIn={second_factor:{required:!1,enabled:!1}};signUp={allowlist_only:!1,captcha_enabled:!1,legal_consent_enabled:!1,mode:"public",progressive:!0};social={};usernameSettings={};get authenticatableSocialStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled&&e.authenticatable).map(([,e])=>e.strategy).sort():[]}get enabledFirstFactorIdentifiers(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&!e.startsWith("web3")).map(([e])=>e):[]}get socialProviderStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled).map(([,e])=>e.strategy).sort():[]}get web3FirstFactors(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&e.startsWith("web3")).map(([,e])=>e.first_factors).flat():[]}get alternativePhoneCodeChannels(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&"phone_number"===e).map(([,e])=>e?.channels?.filter(e=>"sms"!==e)||[]).flat():[]}constructor(e=null){super(),this.fromJSON(e)}get instanceIsPasswordBased(){return!!(this.attributes?.password?.enabled&&this.attributes.password?.required)}get hasValidAuthFactor(){return!!(this.attributes?.email_address?.enabled||this.attributes?.phone_number?.enabled||this.attributes.password?.required&&this.attributes.username?.required)}fromJSON(e){return e&&(this.attributes=this.withDefault(e.attributes?Object.fromEntries(Object.entries(e.attributes).map(e=>[e[0],{...e[1],name:e[0]}])):null,this.attributes),this.actions=this.withDefault(e.actions,this.actions),this.enterpriseSSO=this.withDefault(e.enterprise_sso,this.enterpriseSSO),this.passkeySettings=this.withDefault(e.passkey_settings,this.passkeySettings),this.passwordSettings=e.password_settings?{...e.password_settings,min_length:Math.max(e.password_settings?.min_length??8,8),max_length:e.password_settings?.max_length===0?72:Math.min(e.password_settings?.max_length??72,72)}:this.passwordSettings,this.signIn=this.withDefault(e.sign_in,this.signIn),this.signUp=this.withDefault(e.sign_up,this.signUp),this.social=this.withDefault(e.social,this.social),this.usernameSettings=e.username_settings?{...e.username_settings,min_length:Math.max(e.username_settings?.min_length??4,4),max_length:Math.min(e.username_settings?.max_length??64,64)}:this.usernameSettings),this}__internal_toSnapshot(){return{actions:this.actions,attributes:this.attributes,passkey_settings:this.passkeySettings,password_settings:this.passwordSettings,sign_in:this.signIn,sign_up:this.signUp,social:this.social}}}class rQ extends tF{id;web3Wallet="";verification;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}create(){return this._basePost({body:{web3_wallet:this.web3Wallet}})}prepareVerification=e=>this._basePost({action:"prepare_verification",body:{...e}});attemptVerification=e=>{let{signature:t}=e;return this._basePost({action:"attempt_verification",body:{signature:t}})};destroy(){return this._baseDelete()}toString(){return this.web3Wallet}fromJSON(e){return e&&(this.id=e.id,this.web3Wallet=e.web3_wallet,this.verification=new a1(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}class rX extends tF{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=tL(e.updated_at),this.createdAt=tL(e.created_at)),this}static async join(e){return new rX((await tF._fetch({path:"/waitlist",method:"POST",body:e}))?.response)}}function r1(e,t){var a,r;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||(a=t,r=e,a.organizationMemberships.length!==r.organizationMemberships.length||a.organizationMemberships[0]?.updatedAt!==r.organizationMemberships[0]?.updatedAt)}function r0(e,t){return!function(e,t){if(!e&&t||e&&!t)return!0;if(!e&&e===t)return!1;if(!e||!t)return!0;try{if(aU.isClientResource(e))return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.sessions.length!==t.sessions.length;if(rI.isSessionResource(e)){var a,r;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.lastActiveToken?.jwt?.claims?.__raw!==t.lastActiveToken?.jwt?.claims?.__raw||function(e,t){if(e.lastActiveOrganizationId!==t.lastActiveOrganizationId)return!0;let a=e.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId),r=t.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId);return a?.permissions?.length!==r?.permissions?.length}(e,t)||(a=e,r=t,!!a.user!=!!r.user||!!a.user&&!!r.user&&r1(a.user,r.user))}if(rG.isUserResource(e))return r1(e,t)}catch{}return!0}(e,t)?e:t}let r2="__clerk_db_jwt";function r9(e,t){let a=new URL(e),r=a.searchParams.get(r2);a.searchParams.delete(r2);let n=r||t;return n&&a.searchParams.set(r2,n),a}let r3=e=>{let t=new URL(e);return t.searchParams.delete(r2),t},r5=e=>{let t=new URL(e);return t.searchParams.delete("__dev_session"),t.hash=decodeURI(t.hash).replace(/__clerk_db_jwt\[(.*)\]/,""),t.href.endsWith("#")&&(t.hash=""),t};function r6(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var r in a)e[r]=a[r]}return e}var r8=function e(t,a){function r(e,r,n){if("undefined"!=typeof document){"number"==typeof(n=r6({},a,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var s in n)n[s]&&(i+="; "+s,!0!==n[s]&&(i+="="+n[s].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+i}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var a=document.cookie?document.cookie.split("; "):[],r={},n=0;n<a.length;n++){var i=a[n].split("="),s=i.slice(1).join("=");try{var o=decodeURIComponent(i[0]);if(r[o]=t.read(s,o),e===o)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",r6({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,r6({},this.attributes,t))},withConverter:function(t){return e(r6({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(a)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});function r4(e){return{get:()=>r8.get(e),set(t,a={}){r8.set(e,t,a)},remove(t){r8.remove(e,t)}}}let r7=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function ne(e,t){let a=function(e){try{return new Date(e||new Date)}catch{return new Date}}(e);return a.setFullYear(a.getFullYear()+t),a}let nt=r4("__clerk_test_etld"),na="__client_uat",nr="__session",nn=()=>{let e=tb()?"None":"Lax",t=r7(e);return{sameSite:e,secure:t,partitioned:!1}};async function ni(e){let t;try{t=await ep(e)}catch(o){var a;a=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,Z.has(a)||(console.log(a),Z.add(a));let{default:r}=await Promise.resolve().then(n.t.bind(n,180,23)),{default:i}=await Promise.resolve().then(n.t.bind(n,3413,23)),s=r(e);t=i.stringify(s).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}return t}let ns=()=>{let e=tb()?"None":"Lax",t=r7(e);return{sameSite:e,secure:t}};var no=n(5945),nl=n.n(no);class nc{lock=(function(e){let t=new(nl());return window.addEventListener("beforeunload",async()=>{await t.releaseLock(e)}),{acquireLockAndRun:async a=>{if("locks"in navigator&&isSecureContext){let t=new AbortController,r=setTimeout(()=>t.abort(),4999);return await navigator.locks.request(e,{signal:t.signal},async()=>(clearTimeout(r),await a())).catch(()=>!1)}if(await t.acquireLock(e,5e3))try{return await a()}finally{await t.releaseLock(e)}}}})("clerk.lock.refreshSessionToken");workerTimers=aF();timerId=null;initiated=!1;startPollingForSessionToken(e){if(this.timerId||this.initiated)return;let t=async()=>{this.initiated=!0,await this.lock.acquireLockAndRun(e),this.timerId=this.workerTimers.setTimeout(t,5e3)};t()}stopPollingForSessionToken(){null!=this.timerId&&(this.workerTimers.clearTimeout(this.timerId),this.timerId=null),this.initiated=!1}}class nu{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,t,a,r){let n=await ni(e.publishableKey),i=new nu(e,t,n,a,r);return await i.setup(),i}constructor(e,t,r,n,i){this.clerk=e,this.instanceType=n,this.clerkEventBus=i,re.on(a6,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),re.on(a8,()=>this.handleSignOut()),this.refreshTokenOnFocus(),this.startPollingForToken(),this.clientUat=(e=>{let t=r4(na),r=r4(ef(na,e));return{set:e=>{let n=ne(Date.now(),1),i=tb()?"None":"Strict",s=r7(i),o=function(e=window.location.hostname,t=nt){if(a)return a;if(["localhost","127.0.0.1","0.0.0.0"].includes(e))return e;let r=e.split(".");if(1===r.length)return e;for(let e=r.length-2;e>=0;e--){let n=r.slice(e).join(".");if(t.set("1",{domain:n}),"1"===t.get())return t.remove({domain:n}),a=n,n;t.remove({domain:n})}}(),l="0";e&&e.updatedAt&&e.signedInSessions.length>0&&(l=Math.floor(e.updatedAt.getTime()/1e3).toString()),r.remove(),t.remove(),r.set(l,{domain:o,expires:n,partitioned:!1,sameSite:i,secure:s}),t.set(l,{domain:o,expires:n,partitioned:!1,sameSite:i,secure:s})},get:()=>parseInt(r.get()||t.get()||"0",10)}})(r),this.sessionCookie=(e=>{let t=r4(nr),a=r4(ef(nr,e)),r=()=>{let e=nn();t.remove(e),a.remove(e)};return{set:e=>{let n=ne(Date.now(),1),{sameSite:i,secure:s,partitioned:o}=nn();o&&r(),t.set(e,{expires:n,sameSite:i,secure:s,partitioned:o}),a.set(e,{expires:n,sameSite:i,secure:s,partitioned:o})},remove:r,get:()=>a.get()||t.get()}})(r),this.activeCookie=(()=>{let e=r4("clerk_active_context"),t={secure:r7("None")};return{set:a=>{e.set(a,t)},get:()=>e.get(),remove:()=>e.remove(t)}})(),this.devBrowser=function({cookieSuffix:e,frontendApi:t,fapiClient:a}){let r,n,i=(r=r4(r2),n=r4(ef(r2,e)),{get:()=>n.get()||r.get(),set:e=>{let t=ne(Date.now(),1),{sameSite:a,secure:i}=ns();n.set(e,{expires:t,sameSite:a,secure:i}),r.set(e,{expires:t,sameSite:a,secure:i})},remove:()=>{let e=ns();n.remove(e),r.remove(e)}});function s(){return i.get()}function o(e){i.set(e)}function l(){i.remove()}return{clear:function(){l()},setup:async function(){var e;let r;if(!ek(t))return;a.onBeforeRequest(e=>{let t=s();t&&e?.url&&(e.url=r9(e.url,t))}),a.onAfterResponse((e,t)=>{let a=t?.headers?.get("Clerk-Db-Jwt");a&&o(a)});let n=(r=(e=new URL(window.location.href)).searchParams.get(r2)||"",r3(r5(e)).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",r3(r5(e))),r);if(n)return void o(n);if(i.get())return;let l=a.buildUrl({path:"/dev_browser"}),c=await fetch(l.toString(),{method:"POST"});if(!c.ok){let e=function(e=[]){return e.length>0?e.map(e=>new w(e)):[]}((await c.json()).errors);e[0]?tz(e[0].longMessage):tz()}let u=await c.json();o(u?.id)},getDevBrowserJWT:s,setDevBrowserJWT:o,removeDevBrowserJWT:l}}({frontendApi:e.frontendApi,fapiClient:t,cookieSuffix:r})}async setup(){return"production"===this.instanceType?this.setupProduction():this.setupDevelopment()}isSignedOut(){return this.clerk.loaded?!!this.clerk.user:0>=this.clientUat.get()}async handleUnauthenticatedDevBrowser(){this.devBrowser.clear(),await this.devBrowser.setup()}decorateUrlWithDevBrowserToken(e){let t=this.devBrowser.getDevBrowserJWT();if(!t)throw Error(`${t_} Missing dev browser jwt. Please contact support.`);return r9(e,t)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new nc,this.poller.startPollingForSessionToken(()=>this.refreshSessionToken()))}stopPollingForToken(){this.poller&&(this.poller.stopPollingForSessionToken(),this.poller=null)}refreshTokenOnFocus(){window.addEventListener("focus",()=>{"visible"===document.visibilityState&&this.refreshSessionToken({updateCookieImmediately:!0})})}async refreshSessionToken({updateCookieImmediately:e=!1}={}){if(this.clerk.session)try{let t=await this.clerk.session.getToken();e&&this.updateSessionCookie(t)}catch(e){return this.handleGetTokenError(e)}}updateSessionCookie(e){if(document.hasFocus()||this.isCurrentContextActive())return e||u()||tt.warn("Removing session cookie (offline)",{sessionId:this.clerk.session?.id},"authCookieService"),this.setActiveContextInStorage(),e?this.sessionCookie.set(e):this.sessionCookie.remove()}setClientUatCookieForDevelopmentInstances(){"production"!==this.instanceType&&this.inCustomDevelopmentDomain()&&this.clientUat.set(this.clerk.client)}inCustomDevelopmentDomain(){let e=this.clerk.frontendApi.replace("clerk.","");return!window.location.host.endsWith(e)}handleGetTokenError(e){if(O(e)||T(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(P(e))return void this.clerk.handleUnauthenticated().catch(e3);this.clerkEventBus.emit(f,"degraded")}}handleSignOut(){this.activeCookie.remove(),this.sessionCookie.remove(),this.setClientUatCookieForDevelopmentInstances()}setActiveContextInStorage(){let e=this.clerk.session?.id||"",t=this.clerk.organization?.id||"",a=`${e}:${t}`;":"!==a?this.activeCookie.set(a):this.activeCookie.remove()}isCurrentContextActive(){let e=this.activeCookie.get();if(!e)return!0;let[t,a]=e.split(":"),r=this.clerk.session?.id||"",n=this.clerk.organization?.id||"";return t===r&&a===n}getSessionCookie(){return this.sessionCookie.get()}}class nd{clerk;captchaChallenge;timers;constructor(e,t=new tN(e),a=aF()){this.clerk=e,this.captchaChallenge=t,this.timers=a}async start(){this.isEnabled()&&(await this.challengeAndSend(),this.timers.setInterval(()=>{this.challengeAndSend()},this.intervalInMs()))}async challengeAndSend(){if(!(!this.clerk.client||this.clientBypass()))try{let e=await this.captchaChallenge.invisible({action:"heartbeat"});await this.clerk.client.__internal_sendCaptchaToken(e)}catch{}}isEnabled(){return!!this.clerk.__internal_environment?.displayConfig?.captchaHeartbeat}clientBypass(){return this.clerk.client?.captchaBypass}intervalInMs(){return this.clerk.__internal_environment?.displayConfig?.captchaHeartbeatIntervalMs??6e5}}let nh=["/client","/waitlist"];class nm{async getBaseFapiProxyOptions(){let e=await tF.clerk.session?.getToken();if(!e)throw new A("No valid session token available",{code:"no_session_token"});return{pathPrefix:"",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},credentials:"same-origin"}}async getAll(e){return tF._fetch({...await this.getBaseFapiProxyOptions(),method:"GET",path:"/api_keys",search:aa({...e,subject:e?.subject??tF.clerk.organization?.id??tF.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:t,total_count:a}=e;return{total_count:a,data:t.map(e=>new tW(e))}})}async create(e){return new tW(await tF._fetch({...await this.getBaseFapiProxyOptions(),path:"/api_keys",method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??tF.clerk.organization?.id??tF.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new tW(await tF._fetch({...await this.getBaseFapiProxyOptions(),method:"POST",path:`/api_keys/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let np=new Map;class nf{#eu=!1;load(e){let t=e?.protectConfig;if(t?.loaders&&Array.isArray(t.loaders)&&0!==t.loaders.length&&!this.#eu){if(s())for(let e of(this.#eu=!0,t.loaders))try{this.applyLoader(e)}catch(e){$(`[protect] failed to apply loader: ${e}`)}}}applyLoader(e){if(void 0!==e.rollout){let t=e.rollout;if("number"!=typeof t||t<0)return void $(`[protect] loader rollout value is invalid: ${t}`);if(0===t||Math.random()>t)return}let t=e.type||"script",a=e.target||"body",r=document.createElement(t);if(e.attributes)for(let[t,a]of Object.entries(e.attributes))switch(typeof a){case"string":case"number":case"boolean":r.setAttribute(t,String(a));break;default:$(`[protect] loader attribute is invalid type: ${t}=${a}`)}switch(e.textContent&&"string"==typeof e.textContent&&(r.textContent=e.textContent),a){case"head":document.head.appendChild(r);break;case"body":document.body.appendChild(r);break;default:if(a?.startsWith("#")){let e=document.getElementById(a.substring(1));if(!e)return void $(`[protect] loader target element not found: ${a}`);e.appendChild(r);return}$(`[protect] loader target is invalid: ${a}`)}}}class ng{signInResourceSignal=an;signInErrorSignal=ai;signInFetchSignal=as;signInSignal=ao;signUpResourceSignal=al;signUpErrorSignal=ac;signUpFetchSignal=au;signUpSignal=ad;__internal_effect=t5;__internal_computed=t3;constructor(){re.on("resource:update",this.onResourceUpdated),re.on("resource:error",this.onResourceError),re.on("resource:fetch",this.onResourceFetch)}onResourceError=e=>{e.resource instanceof rB&&this.signInErrorSignal({error:e.error}),e.resource instanceof rF&&this.signUpErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof rB){if(nb(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof rF){if(nb(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}};onResourceFetch=e=>{e.resource instanceof rB&&this.signInFetchSignal({status:e.status}),e.resource instanceof rF&&this.signUpFetchSignal({status:e.status})}}function nb(e,t){return!t?.id&&e&&e.__internal_future?.hasBeenFinalized===!1}let ny="cannot_render_billing_disabled",nw="cannot_render_user_missing",nk="cannot_render_organizations_disabled",nv="cannot_render_organization_missing",nx="cannot_render_single_session_enabled",nj={polling:!0,standardBrowser:!0,touchSession:!0,isSatellite:!1,signInUrl:void 0,signUpUrl:void 0,afterSignOutUrl:void 0,signInFallbackRedirectUrl:void 0,signUpFallbackRedirectUrl:void 0,signInForceRedirectUrl:void 0,signUpForceRedirectUrl:void 0,newSubscriptionRedirectUrl:void 0};class n_{static version="6.0.0-snapshot.v20251215203425";static sdkMetadata={name:"@clerk/clerk-js",version:"6.0.0-snapshot.v20251215203425"};static _billing;static _apiKeys;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new ng;internal_last_error=null;environment;#ed;#eh="";#em;#ep;#ef;#eg;#eb;#ey=null;#ew;#ek;#ev;#ex="loading";#ej=[];#e_=[];#ez={};#eS=null;#eA=0;#eE=p();get __internal_queryClient(){return this.#ed||Promise.resolve().then(n.bind(n,3303)).then(e=>e.QueryClient).then(e=>{this.#ed||(this.#ed=new e,this.#eE.emit("queryClientStatus","ready"))}),this.#ed?{__tag:"clerk-rq-client",client:this.#ed}:void 0}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#eh}get version(){return n_.version}set sdkMetadata(e){n_.sdkMetadata=e}get sdkMetadata(){return n_.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#ex}get isSatellite(){return!!tg()&&e9(this.#ez.isSatellite,new URL(window.location.href),!1)}get domain(){if(tg()){let e=function(e=""){return(e||"").replace(/^.+:\/\//,"")}(e9(this.#em,new URL(window.location.href)));if("production"===this.#ev){let t;if(!e)return"";if(e.match(/^(clerk\.)+\w*$/))t=/(clerk\.)*(?=clerk\.)/;else{if(e.match(/\.clerk.accounts/))return e;t=/^(clerk\.)*/gi}return`clerk.${e.replace(t,"")}`}return e}return""}get proxyUrl(){if(tg()){let e=e9(this.#ep,new URL(window.location.href));return!e||eK(e)||eH(e)||th.throwInvalidProxyUrl({url:e}),e?eH(e)?new URL(e,window.location.origin).toString():e:""}return""}get frontendApi(){let e=eh(this.publishableKey);return e?e.frontendApi:th.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#ev}get isStandardBrowser(){return this.#ez.standardBrowser||!1}get billing(){return n_._billing||(n_._billing=new ar),n_._billing}get apiKeys(){return n_._apiKeys||(n_._apiKeys=new nm),n_._apiKeys}__experimental_checkout(e){return this._checkout||(this._checkout=e=>(function(e,t){let a,r,n,i,{for:s,planId:o,planPeriod:l}=t;if(null===e.user)throw Error("Clerk: User is not authenticated");if("organization"===s&&null===e.organization)throw Error("Clerk: The current session does not have an active organization. Use `setActive` to set the organization");let c=function(e){let{userId:t,orgId:a,planId:r,planPeriod:n}=e;return`${t}-${a||"user"}-${r}-${n}`}({userId:e.user?.id||"",orgId:"organization"===s?e.organization?.id:void 0,planId:o,planPeriod:l}),u=np.get(c);if(u)return u.signals.computedSignal();let d=(a=t9({resource:null}),r=t9({error:null}),n=t9({status:"idle"}),i=t3(()=>{let e=a().resource,t=r().error,i=n().status;return{errors:ah(t,{}),fetchStatus:i,checkout:e}}),{resourceSignal:a,errorSignal:r,fetchSignal:n,computedSignal:i}),h=new af(d,{..."organization"===s?{orgId:e.organization?.id}:{},planId:o,planPeriod:l});return np.set(c,{resource:h,signals:d}),d.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#ez[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,t){if(!(e=(e||"").trim()))return th.throwMissingPublishableKeyError();const a=eh(e);if(!a)return th.throwInvalidPublishableKeyError({key:e});this.#em=t?.domain,this.#ep=t?.proxyUrl,this.environment=rr.getInstance(),this.#ev=a.instanceType,this.#eh=e,this.#ek=function(e){let t=[],a=[];async function r(e){for await(let a of["undefined"!=typeof window&&window.__internal_onBeforeRequest,...t].filter(e=>e))if(await a(e)===!1)return!1;return!0}async function n(e,t){for await(let r of["undefined"!=typeof window&&window.__internal_onAfterResponse,...a].filter(e=>e))if(await r(e,t)===!1)return!1;return!0}function i({method:t,path:a,sessionId:r,search:n,rotatingTokenNonce:i}){let s=new URLSearchParams(n);return s.append("__clerk_api_version","2025-11-10"),s.append("_clerk_js_version","6.0.0-snapshot.v20251215203425"),i&&s.append("rotating_token_nonce",i),e.domain&&"development"===e.instanceType&&e.isSatellite&&s.append("__domain",e.domain),t&&"GET"!==t&&"POST"!==t&&s.append("_method",t),a&&!nh.some(e=>a.startsWith(e))&&r&&s.append("_clerk_session_id",r),eb([...s.entries()].reduce((e,[t,a])=>(e[t]=a.includes(",")?a.split(","):a,e),{}))}function s(t){let{path:a,pathPrefix:r="v1"}=t;if(e.proxyUrl){let n=new URL(e.proxyUrl),s=n.pathname.slice(1);return s.endsWith("/")&&(s=s.slice(0,-1)),ej({base:n.origin,pathname:`${s}/${r}${a}`,search:i(t)},{stringify:!1})}let n="production"===e.instanceType?e.domain:"";return ej({base:`https://${n||e.frontendApi}`,pathname:`${r}${a}`,search:i(t)},{stringify:!1})}async function o(t,a){let i,o={...t},{method:l="GET",body:u}=o;!u||"object"!=typeof u||u instanceof FormData||(o.body=function(e){if(!e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype)return e;let t={};for(let[a,r]of Object.entries(e))void 0!==r&&(t[a]=r);return t}(u)),o.url=s({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===l||u instanceof FormData||o.headers.has("content-type")||o.headers.set("content-type","application/x-www-form-urlencoded"),"application/x-www-form-urlencoded"===o.headers.get("content-type")&&(o.body=u?eb(u,{keyEncoder:ee}):u);let d=await r(o),h="GET"===l?"GET":"POST",m=o.url,p={...o,method:h,credentials:o.credentials||"include"};try{if(d){let e=a?.fetchMaxTries??(c()?4:11);i=await ti(()=>fetch(m,p),{retryImmediately:!0,initialDelay:700,maxDelayBetweenRetries:5e3,shouldRetry:(t,a)=>"GET"===h&&a<e,onBeforeRetry:e=>{m.searchParams.set("_clerk_retry_attempt",e.toString())}})}else i=new Response("{}",o)}catch(t){let e=m.toString();tt.error("network error",{error:t,url:e,method:l},"fapiClient");throw Error(`${t_} Network error at "${e}" - ${t}. Please try again.`)}let f=204!==i.status?await i.json():null,g=Object.assign(i,{payload:f});return i.ok||tt.error("request failed",{method:l,path:o.path,status:i.status},"fapiClient"),await n(o,g),g}return{buildEmailAddress:function(t){return function({localPart:e,frontendApi:t}){return`${e}@${t?t.replace("clerk.",""):"clerk.com"}`}({localPart:t,frontendApi:e.frontendApi})},buildUrl:s,onAfterResponse:function(e){a.push(e)},onBeforeRequest:function(e){t.push(e)},request:o}}({domain:this.domain,frontendApi:this.frontendApi,instanceType:this.instanceType,isSatellite:this.isSatellite,getSessionId:()=>this.session?.id,proxyUrl:this.proxyUrl}),this.#eE.emit(f,"loading"),this.#eE.prioritizedOn(f,e=>this.#ex=e),tF.clerk=this,this.#eg=new nf}getFapiClient=()=>this.#ek;load=async e=>{if(tt.info("load() start",{},"clerk"),!this.loaded){if("development"===this.#ev&&$("Clerk: Clerk has been loaded with development keys. Development instances have strict usage limits and should not be used when deploying your application to production. Learn more: https://clerk.com/docs/deployments/overview"),this.#ez=this.#eI(e),this.#ez.clerkUiCtor&&(this.#ew=Promise.resolve(this.#ez.clerkUiCtor).then(e=>new e(()=>this,()=>this.environment,this.#ez,new to))),"development"===this.#ev&&(this.#ez.routerPush||this.#ez.routerReplace)&&(!this.#ez.routerPush||!this.#ez.routerReplace)){let e=this.#ez.routerPush?"routerReplace":"routerPush";$(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}re.on(a7,()=>{this.#eC(this.session),this.#eP()}),this.#ez.sdkMetadata&&(n_.sdkMetadata=this.#ez.sdkMetadata),!1!==this.#ez.telemetry&&(this.telemetry=new e$({clerkVersion:n_.version,samplingRate:1,perEventSampling:!this.#ez.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#ez.telemetry}),this.#ez.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let t;if(!e||"object"!=typeof e)return{};let a=e.theme;if(!a)return{};if(Array.isArray(a))for(let e of a){let a=e2(e);if(a){t=a;break}}else t=e2(a);return{themeName:t}}(this.#ez.appearance)}));try{this.#ez.standardBrowser?await this.#eq():await this.#eO();let e=this.#ez.telemetry,t=!1!==e&&!e?.disabled,a=!!this.#ez.__internal_keyless_claimKeylessApplicationUrl,r=!!this.environment?.clientDebugMode,n=this.environment?.isProduction?.()??!1,i=r||a&&!n,s=a&&!r?"error":void 0;i&&function(e={}){if(e8)return;let{enabled:t=!1,...a}=e;t&&(e5=!0,e8=!0,te(a))}({enabled:!0,...s?{logLevel:s}:{},...t&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#eg?.load(this.environment),tt.info("load() complete",{},"clerk")}catch(e){throw this.#eE.emit(f,"error"),tt.error("load() failed",{error:e},"clerk"),e}}};#eT(){let e;return!!(!this.#ez.signUpUrl&&this.#ez.signInUrl&&(e=this.#ez.signInUrl,!eg.test(e)))}signOut=async(e,t)=>{if(!this.client||0===this.client.sessions.length)return;let a="undefined"!=typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:e3,r="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e3,n=e&&"object"==typeof e?e:t||{},i=n?.redirectUrl||this.buildAfterSignOutUrl();tt.debug("signOut() start",{hasClient:!!this.client,multiSessionCount:this.client?.signedInSessions.length??0,redirectUrl:i,sessionTarget:n?.sessionId??null},"clerk");let s="function"==typeof e?e:void 0,o=async()=>{let e=tl(this.#ez.standardBrowser);re.emit(a8,null),this.#eU(),await e.track(async()=>{s?await s():await this.navigate(i)}),e.isUnloading()||(this.#eC(),this.#eP(),await r())};if(await a(),!n.sessionId||1===this.client.signedInSessions.length){this.#ez.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),tt.info("signOut() complete",{redirectUrl:e_(i)},"clerk");return}let l=this.client.signedInSessions.find(e=>e.id===n.sessionId),c=l?.id&&this.session?.id===l.id;await l?.remove(),c&&(await o(),tt.info("signOut() complete",{redirectUrl:e_(i)},"clerk"))};openGoogleOneTap=e=>{this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openModal("googleOneTap",e||{})),this.telemetry?.record(e0("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(N(this,this.environment)){if("development"===this.#ev)throw new A(eD.cannotOpenSignInOrSignUp,{code:nx});return}this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openModal("signIn",e||{}));let t={withSignUp:e?.withSignUp??this.#eT()};this.telemetry?.record(e0("SignIn",e,t))};closeSignIn=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(D(this,this.environment)){if("development"===this.#ev)throw new A(eD.cannotRenderAnyBillingComponent("Checkout"),{code:ny});return}if(!this.user){if("development"===this.#ev)throw new A(eD.cannotOpenCheckout,{code:nw});return}this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(D(this,this.environment)){if("development"===this.#ev)throw new A(eD.cannotRenderAnyBillingComponent("PlanDetails"),{code:ny});return}this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openDrawer("planDetails",e||{})),this.telemetry?.record(e0("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#ev)throw new A(eD.cannotOpenUserProfile,{code:nw});return}this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openModal("userVerification",e||{})),this.telemetry?.record(e0("UserVerification",e))};__internal_closeReverification=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:t,caller:a}=e;if(this.user||"development"!==this.#ev||$(`Clerk: "${a}" requires an active user session. Ensure a user is signed in before executing ${a}.`),"organizations"===t){let t;return(t=this.environment,t?.organizationSettings.enabled||this.session?.currentTask?.key==="choose-organization")?{isEnabled:!0}:("development"===this.#ev&&this.__internal_openEnableOrganizationsPrompt({caller:a,onSuccess:()=>window.location.reload(),onClose:e.onClose}),{isEnabled:!1})}throw Error(`Attempted to enable an unknown or unsupported setting "${t}".`)};__internal_openEnableOrganizationsPrompt=e=>{this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted({preloadHint:"EnableOrganizationsPrompt"})).then(t=>t.openModal("enableOrganizationsPrompt",e||{})),this.telemetry?.record(e1("EnableOrganizationsPrompt",e))};__internal_closeEnableOrganizationsPrompt=()=>{this.assertComponentsReady(this.#ew),this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt"))};__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(e=>e.closeModal("blankCaptcha")));__internal_loadStripeJs=async()=>{let{loadStripe:e}=await Promise.resolve().then(n.bind(n,5608));return e};openSignUp=e=>{if(N(this,this.environment)){if("development"===this.#ev)throw new A(eD.cannotOpenSignInOrSignUp,{code:nx});return}this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openModal("signUp",e||{})),this.telemetry?.record(e0("SignUp",e))};closeSignUp=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#ev)throw new A(eD.cannotOpenUserProfile,{code:nw});return}this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openModal("userProfile",e||{}));let t=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(e0("UserProfile",e,t))};closeUserProfile=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userProfile"))};openOrganizationProfile=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new A(eD.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:nk})}});if(t){if(!this.organization){if("development"===this.#ev)throw new A(eD.cannotRenderComponentWhenOrgDoesNotExist,{code:nv});return}this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openModal("organizationProfile",e||{})),this.telemetry?.record(e0("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeModal("organizationProfile"))};openCreateOrganization=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new A(eD.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:nk})}});t&&(this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openModal("createOrganization",e||{})),this.telemetry?.record(e0("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(t=>t.openModal("waitlist",e||{})),this.telemetry?.record(e0("Waitlist",e))};closeWaitlist=()=>{this.#ew?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,t)=>{this.assertComponentsReady(this.#ew);let a="SignIn";this.#ew.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"signIn",node:e,props:t}));let r={withSignUp:t?.withSignUp??this.#eT()};this.telemetry?.record(e1(a,t,r))};unmountSignIn=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserAvatar=(e,t)=>{this.assertComponentsReady(this.#ew);let a="UserAvatar";this.#ew.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"userAvatar",node:e,props:t})),this.telemetry?.record(e1(a,t))};unmountUserAvatar=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountSignUp=(e,t)=>{this.assertComponentsReady(this.#ew);let a="SignUp";this.#ew.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"signUp",node:e,props:t})),this.telemetry?.record(e1(a,t))};unmountSignUp=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserProfile=(e,t)=>{if(!this.user){if("development"===this.#ev)throw new A(eD.cannotRenderComponentWhenUserDoesNotExist,{code:nw});return}this.assertComponentsReady(this.#ew);let a="UserProfile";this.#ew.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"userProfile",node:e,props:t}));let r=(t?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(e1(a,t,r))};unmountUserProfile=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOrganizationProfile=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new A(eD.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:nk})}});if(!a)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#ev)throw new A(eD.cannotRenderComponentWhenOrgDoesNotExist,{code:nv});return}this.assertComponentsReady(this.#ew);let n="OrganizationProfile";this.#ew.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:n,appearanceKey:"userProfile",node:e,props:t})),this.telemetry?.record(e1(n,t))};unmountOrganizationProfile=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountCreateOrganization=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new A(eD.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:nk})}});if(!a)return;this.assertComponentsReady(this.#ew);let r="CreateOrganization";this.#ew.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:r,appearanceKey:"createOrganization",node:e,props:t})),this.telemetry?.record(e1(r,t))};unmountCreateOrganization=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOrganizationSwitcher=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationSwitcher",onClose:()=>{throw new A(eD.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:nk})}});if(!a)return;this.assertComponentsReady(this.#ew);let r="OrganizationSwitcher";this.#ew.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:r,appearanceKey:"organizationSwitcher",node:e,props:t})),this.telemetry?.record(e1(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(e=>e.prefetch("organizationSwitcher"))};mountOrganizationList=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationList",onClose:()=>{throw new A(eD.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:nk})}});if(!a)return;this.assertComponentsReady(this.#ew);let r="OrganizationList";this.#ew.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:r,appearanceKey:"organizationList",node:e,props:t})),this.telemetry?.record(e1(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserButton=(e,t)=>{this.assertComponentsReady(this.#ew);let a="UserButton";this.#ew.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"userButton",node:e,props:t}));let r={...t?.customMenuItems?.length||0?{customItems:!0}:void 0,...t?.__experimental_asStandalone?{standalone:!0}:void 0};this.telemetry?.record(e1(a,t,r))};unmountUserButton=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountWaitlist=(e,t)=>{this.assertComponentsReady(this.#ew);let a="Waitlist";this.#ew.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"waitlist",node:e,props:t})),this.telemetry?.record(e1(a,t))};unmountWaitlist=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountPricingTable=(e,t)=>{if(D(this,this.environment)){if("development"===this.#ev)throw new A(eD.cannotRenderAnyBillingComponent("PricingTable"),{code:ny});return}this.assertComponentsReady(this.#ew);let a="PricingTable";this.#ew.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"pricingTable",node:e,props:t})),this.telemetry?.record(e1(a,t))};unmountPricingTable=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,t)=>{this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:"OAuthConsent",appearanceKey:"__internal_oauthConsent",node:e,props:t}))};__internal_unmountOAuthConsent=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountAPIKeys=(e,t)=>{let a;if($("Clerk: <APIKeys /> component is in early access and not yet recommended for production use."),F(this,a=this.environment)&&L(this,a)){if("development"===this.#ev)throw new A(eD.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&L(this,this.environment)){if("development"===this.#ev)throw new A(eD.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if(F(this,this.environment)){if("development"===this.#ev)throw new A(eD.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#ew);let r="APIKeys";this.#ew.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:r,appearanceKey:"apiKeys",node:e,props:t})),this.telemetry?.record(e1(r,t))};unmountAPIKeys=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskChooseOrganization=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"TaskChooseOrganization",onClose:()=>{throw new A(eD.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:nk})}});if(!a)return;this.assertComponentsReady(this.#ew);let r="TaskChooseOrganization";this.#ew.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:r,appearanceKey:"taskChooseOrganization",node:e,props:t})),this.telemetry?.record(e1(r,t))};unmountTaskChooseOrganization=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskResetPassword=(e,t)=>{this.assertComponentsReady(this.#ew),this.#ew.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:"TaskResetPassword",appearanceKey:"taskResetPassword",node:e,props:t})),this.telemetry?.record(e1("TaskResetPassword",t))};unmountTaskResetPassword=e=>{this.#ew?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};setActive=async e=>{let{organization:t,redirectUrl:a,navigate:r}=e,{session:n}=e;this.__internal_setActiveInProgress=!0,tt.debug("setActive() start",{hasClient:!!this.client,sessionTarget:"string"==typeof n?n:n?.id??n??null,organizationTarget:"string"==typeof t?t:t?.id??t??null,redirectUrl:a??null},"clerk");try{var i;let s;if(!this.client)throw tt.warn("Clerk setActive called before client is loaded",{},"clerk"),Error("setActive is being called before the client is loaded. Wait for init.");if(void 0===n&&!this.session)throw tt.warn("Clerk setActive precondition not met: no target session and no active session",{},"clerk"),Error("setActive should either be called with a session param or there should be already an active session.");"string"==typeof n&&(n=this.client.sessions.find(e=>e.id===n)||null);let o="undefined"!=typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:e3,l="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e3,c=void 0===n?this.session:n;c?.status==="pending"&&(i={...this.#ez,...e},s=["taskUrls","navigate"],Object.keys(i).some(e=>s.includes(e))||$('Clerk: Session has pending tasks but no handling is configured. To handle pending tasks, provide either "taskUrls" for navigation to custom URLs or "navigate" for programmatic navigation. Without these options, users may get stuck on incomplete flows.'));let d=void 0!==t;if(c&&d){let e="string"==typeof t?t:t?.id;if("string"==typeof e&&e.startsWith("org_"))c.lastActiveOrganizationId=e||null;else{let t=c.user.organizationMemberships.find(t=>t.organization.slug===e),a=t?.organization.id||null,r=null===a;if(this.environment?.organizationSettings?.forceOrganizationSelection&&r)return;c.lastActiveOrganizationId=a}}c?.status!=="pending"&&await o(null===c?"sign-out":void 0),(tg()&&globalThis.document.hasFocus()||!this.#ez.standardBrowser)&&(await this.#eM(c),c=this.#eR(c?.id)),await c?.getToken()||(u()||tt.warn("Token is null when setting active session (offline)",{sessionId:c?.id},"clerk"),re.emit(a6,{token:null}));let h=tl(this.#ez.standardBrowser),m=c?.status==="pending"&&c?.currentTask&&this.#ez.taskUrls?.[c?.currentTask.key];if((a||m||r)&&await h.track(async()=>{if(this.client){if(c?.status!=="pending"&&this.#eU(),m){let e=a?ej({base:m,hashSearchParams:{redirectUrl:a}},{stringify:!0}):m;await this.navigate(e)}else if(r&&c)await r({session:c});else if(a){if(this.client.isEligibleForTouch()){let e=new URL(a,window.location.href),t=this.buildUrlWithAuth(this.client.buildTouchUrl({redirectUrl:e}));await this.navigate(t)}await this.navigate(a)}}}),h.isUnloading())return;this.#eC(c),this.#eP(),c?.status!=="pending"&&await l()}finally{this.__internal_setActiveInProgress=!1}};addListener=e=>{var t;let a;return t=e,e=e=>{var r;a||={...e},t(a={...{client:r0((r=a).client,e.client),session:r0(r.session,e.session),user:r0(r.user,e.user),organization:r0(r.organization,e.organization)}})},this.#ej.push(e),this.client&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#ej=this.#ej.filter(t=>t!==e)}};on=(...e)=>{this.#eE.on(...e)};off=(...e)=>{this.#eE.off(...e)};__internal_addNavigationListener=e=>(this.#e_.push(e),()=>{this.#e_=this.#e_.filter(t=>t!==e)});navigate=async(e,t)=>{if(!e||!tg())return;setTimeout(()=>{this.#eB()},0);let a=new URL(e,window.location.href);this.#eN.includes(a.protocol)||(console.warn(`Clerk: "${a.protocol}" is not a valid protocol. Redirecting to "/" instead. If you think this is a mistake, please open an issue.`),a=new URL("/",window.location.href));let r=t?.replace&&this.#ez.routerReplace?this.#ez.routerReplace:this.#ez.routerPush;if(tt.info(`Clerk is navigating to: ${a}`),this.#ez.routerDebug&&console.log(`Clerk is navigating to: ${a}`),"null"!==a.origin&&a.origin!==window.location.origin||!r)return void eW(a);let n={...t?.metadata?{__internal_metadata:t?.metadata}:{},windowNavigate:eW};return await r(e_(a),n)};buildUrlWithAuth(e){if("production"===this.#ev)return e;let t=new URL(e,window.location.origin);return t.origin!==window.location.origin&&this.#ef?this.#ef.decorateUrlWithDevBrowserToken(t).href:t.href}buildSignInUrl(e){return this.#eD("signInUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildSignUpUrl(e){return this.#eD("signUpUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildUserProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.userProfileUrl):""}buildHomeUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.homeUrl):""}buildAfterSignInUrl({params:e}={}){return this.buildUrlWithAuth(new eC(this.#ez,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eC(this.#ez,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#ez.afterSignOutUrl?this.buildUrlWithAuth(this.#ez.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#ez.newSubscriptionRedirectUrl?this.#ez.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?ej({base:this.#ez.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#ez.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#ez.afterMultiSessionSingleSignOutUrl):this.#ez.signInUrl?this.buildUrlWithAuth(ej({base:this.#ez.signInUrl,hashPath:"choose"},{stringify:!0})):this.buildUrlWithAuth(this.environment.displayConfig.afterSignOutOneUrl):""}buildCreateOrganizationUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.createOrganizationUrl):""}buildOrganizationProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.organizationProfileUrl):""}buildTasksUrl(e){let t=this.session?.currentTask;if(!t)return"";let a=this.#ez.taskUrls?.[t.key];return a||ej({base:this.buildSignInUrl(e),hashPath:eR(t)},{stringify:!0})}#eF=async()=>{if(!tg())return;let e=new URLSearchParams({[W]:"true"}),t=eO(H);t&&eK(t)||function(){throw Error(`${t_} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let a=ej({base:eO(H),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(a))};redirectWithAuth=async e=>{if(tg())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(tg())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(tg())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(tg())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(tg())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(tg())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(tg())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(tg())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(tg())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(tg())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(tg())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,t)=>{if(!this.client)return;let a=eO("__clerk_status");if("expired"===a)throw new _(S.Expired);if("client_mismatch"===a)throw new _(S.ClientMismatch);if("verified"!==a)throw new _(S.Failed);let r=eO("__clerk_created_session"),{signIn:n,signUp:i,sessions:s}=this.client,o=s.some(e=>e.id===r),l="needs_second_factor"===n.status||"missing_requirements"===i.status,c=e=>t&&"function"==typeof t?t(e):this.navigate(e),u=e.redirectUrl?()=>c(e.redirectUrl):e3;return o?this.setActive({session:r,redirectUrl:e.redirectUrlComplete}):l?u():("function"==typeof e.onVerifiedOnOtherDevice&&e.onVerifiedOnOtherDevice(),null)};handleGoogleOneTapCallback=async(e,t,a)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:r,signUp:n}=this.client,i="identifier"in(e||{})?e:r,s="missingFields"in(e||{})?e:n,o=e=>a&&"function"==typeof a?a(this.buildUrlWithAuth(e)):this.navigate(this.buildUrlWithAuth(e));return this._handleRedirectCallback(t,{signUp:s,signIn:i,navigate:o})};_handleRedirectCallback=async(e,{signIn:t,signUp:a,navigate:r})=>{if(!this.loaded||!this.environment||!this.client)return;if(!window.opener&&e.reloadResource)try{"signIn"===e.reloadResource?await t.reload():"signUp"===e.reloadResource&&await a.reload()}catch{}let{displayConfig:n}=this.environment,{firstFactorVerification:i}=t,{externalAccount:s}=a.verifications,o={status:a.status,missingFields:a.missingFields,externalAccountStatus:s.status,externalAccountErrorCode:s.error?.code,externalAccountSessionId:s.error?.meta?.sessionId,sessionId:a.createdSessionId},l={status:t.status,firstFactorVerificationStatus:i.status,firstFactorVerificationErrorCode:i.error?.code,firstFactorVerificationSessionId:i.error?.meta?.sessionId,sessionId:t.createdSessionId},c=e=>()=>r(e),u=c(e.signInUrl||n.signInUrl),d=c(e.signUpUrl||n.signUpUrl),h=c(e.firstFactorUrl||ej({base:n.signInUrl,hashPath:"/factor-one"},{stringify:!0})),m=c(e.secondFactorUrl||ej({base:n.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=c(e.resetPasswordUrl||ej({base:n.signInUrl,hashPath:"/reset-password"},{stringify:!0})),f=new eC(this.#ez,e),g=c(e.continueSignUpUrl||ej({base:n.signUpUrl,hashPath:"/continue"},{stringify:!0})),b=({missingFields:t})=>t.length?g():(({signUp:e,verifyEmailPath:t,verifyPhonePath:a,continuePath:r,navigate:n,handleComplete:i,redirectUrl:s="",redirectUrlComplete:o="",oidcPrompt:l})=>{if("complete"===e.status)return i&&i();if("missing_requirements"===e.status){if(e.missingFields.some(e=>"enterprise_sso"===e))return e.authenticateWithRedirect({strategy:"enterprise_sso",redirectUrl:s,redirectUrlComplete:o,continueSignUp:!0,oidcPrompt:l});let i=eU();if(e.unverifiedFields?.includes("email_address")&&t)return n(t,{searchParams:i});if(e.unverifiedFields?.includes("phone_number")&&a)return n(a,{searchParams:i});if(r)return n(r,{searchParams:i})}})({signUp:a,verifyEmailPath:e.verifyEmailAddressUrl||ej({base:n.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||ej({base:n.signUpUrl,hashPath:"/verify-phone-number"},{stringify:!0}),navigate:r}),y=e.signInUrl||n.signInUrl,w=e.signUpUrl||n.signUpUrl,k=async({session:e,baseUrl:t,redirectUrl:a})=>{e.currentTask?await eB(e,{baseUrl:t,navigate:this.navigate}):await this.navigate(a)};if("complete"===l.status)return this.setActive({session:l.sessionId,navigate:async({session:e})=>{await k({session:e,baseUrl:y,redirectUrl:f.getAfterSignInUrl()})}});if("transferable"===o.externalAccountStatus&&"external_account_exists"===o.externalAccountErrorCode){let e=await t.create({transfer:!0});switch(e.status){case"complete":return this.setActive({session:e.createdSessionId,navigate:async({session:e})=>{await k({session:e,baseUrl:w,redirectUrl:f.getAfterSignInUrl()})}});case"needs_first_factor":return h();case"needs_second_factor":return m();case"needs_new_password":return p();default:tS("sign in")}}let v="user_locked"===o.externalAccountErrorCode,x="user_locked"===l.firstFactorVerificationErrorCode;if(v)return d();if(x)return u();if("needs_first_factor"===l.status&&!t.supportedFirstFactors?.every(e=>"enterprise_sso"===e.strategy))return h();if("needs_new_password"===l.status)return p();if("transferable"===l.firstFactorVerificationStatus){if(!1===e.transferable)return u();let t=await a.create({transfer:!0});switch(t.status){case"complete":return this.setActive({session:t.createdSessionId,navigate:async({session:e})=>{await k({session:e,baseUrl:w,redirectUrl:f.getAfterSignUpUrl()})}});case"missing_requirements":return b({missingFields:t.missingFields});default:tS("sign in")}}if("complete"===o.status)return this.setActive({session:o.sessionId,navigate:async({session:e})=>{await k({session:e,baseUrl:w,redirectUrl:f.getAfterSignUpUrl()})}});if("needs_second_factor"===l.status)return m();let j=("failed"===o.externalAccountStatus||"unverified"===o.externalAccountStatus)&&"identifier_already_signed_in"===o.externalAccountErrorCode&&o.externalAccountSessionId,_="failed"===l.firstFactorVerificationStatus&&"identifier_already_signed_in"===l.firstFactorVerificationErrorCode&&l.firstFactorVerificationSessionId;if(j||_){let e=l.firstFactorVerificationSessionId||o.externalAccountSessionId;if(e)return this.setActive({session:e,navigate:async({session:e})=>{await k({session:e,baseUrl:j?w:y,redirectUrl:f.getAfterSignInUrl()})}})}return(e=>{let{externalAccount:t}=e.verifications;return!!t.error})(a)?d():"verified"===o.externalAccountStatus&&"missing_requirements"===o.status?b({missingFields:a.missingFields}):this.session?.currentTask?void await this.redirectToTasks({redirectUrl:this.buildAfterSignInUrl()}):u()};handleRedirectCallback=async(e={},t)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:a,signUp:r}=this.client,n=e=>t&&"function"==typeof t?t(e):this.navigate(e);return this._handleRedirectCallback(e,{signUp:r,signIn:a,navigate:n})};handleUnauthenticated=async(e={broadcast:!0})=>{if(this.client&&this.session)try{let t=await aU.getOrCreateInstance().fetch();if(this.updateClient(t),this.session)return;return e.broadcast&&re.emit(a8,null),this.setActive({session:null})}catch(e){if(O(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};authenticateWithGoogleOneTap=async e=>this.client?.signIn.create({strategy:"google_one_tap",token:e.token}).catch(t=>{if(O(t)&&"external_account_not_found"===t.errors[0].code)return this.client?.signUp.create({strategy:"google_one_tap",token:e.token,legalAccepted:e.legalAccepted});throw t});authenticateWithMetamask=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_okx_wallet_signature"})};authenticateWithWeb3=async({redirectUrl:e,signUpContinueUrl:t,customNavigate:a,unsafeMetadata:r,strategy:n,legalAccepted:i,secondFactorUrl:s})=>{let o,l;if(!this.client||!this.environment)return;let{displayConfig:c}=this.environment,u=n.replace("web3_","").replace("_signature",""),d=await tw().getWeb3Identifier({provider:u});switch(u){case"metamask":o=tw().generateSignatureWithMetamask;break;case"base":o=tw().generateSignatureWithBase;break;case"coinbase_wallet":o=tw().generateSignatureWithCoinbaseWallet;break;default:o=tw().generateSignatureWithOKXWallet}let h=e=>()=>a&&"function"==typeof a?a(e):this.navigate(e),m=h(s||ej({base:c.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=h(t||ej({base:c.signUpUrl,hashPath:"/continue"},{stringify:!0}));try{l=await this.client.signIn.authenticateWithWeb3({identifier:d,generateSignature:o,strategy:n})}catch(e){if(td(e,"form_identifier_not_found"))l=await this.client.signUp.authenticateWithWeb3({identifier:d,generateSignature:o,unsafeMetadata:r,strategy:n,legalAccepted:i}),t&&"missing_requirements"===l.status&&"verified"===l.verifications.web3Wallet.status&&await p();else throw e}let f=async({session:e,redirectUrl:t})=>{e.currentTask?await eB(e,{baseUrl:c.signInUrl,navigate:this.navigate}):await this.navigate(t)};switch(l.status){case"needs_second_factor":await m();break;case"complete":l.createdSessionId&&await this.setActive({session:l.createdSessionId,navigate:async({session:t})=>{await f({session:t,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:t})=>rh.create({name:e,slug:t});getOrganization=async e=>rh.get(e);joinWaitlist=async({emailAddress:e})=>rX.join({emailAddress:e});updateEnvironment(e){this.environment=e}__internal_setCountry=e=>{this.__internal_country||(this.__internal_country=e)};get __internal_last_error(){let e=this.internal_last_error;return this.internal_last_error=null,e}set __internal_last_error(e){this.internal_last_error=e}updateClient=e=>{if(!this.client){let t=this.#ez.selectInitialSession?this.#ez.selectInitialSession(e):this.#eL(e);this.#eC(t)}if(this.client=e,this.session){let e=this.#eR(this.session.id);"active"===this.session.status&&e?.status==="pending"&&("undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e3)(),this.#eC(e),this.session?.lastActiveToken||u()||tt.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),re.emit(a6,{token:this.session?.lastActiveToken})}this.#eP()};get __internal_environment(){return this.environment}__internal_setEnvironment=async e=>{this.environment=new rr(e)};__internal_onBeforeRequest=e=>{this.#ek.onBeforeRequest(e)};__internal_onAfterResponse=e=>{this.#ek.onAfterResponse(e)};__internal_updateProps=e=>{let t={...e,options:this.#eI({...this.#ez,...e.options})};return this.#ew?.then(e=>e.ensureMounted()).then(e=>e.updateProps(t))};__internal_navigateWithError(e,t){return this.__internal_last_error=t,this.navigate(e)}#eW=()=>{let e=new URLSearchParams({[H]:window.location.href});return ej({base:this.#ez.signInUrl,searchParams:e},{stringify:!0})};#eK=()=>{let e;if(this.proxyUrl){let t=new URL(this.proxyUrl);e=new URL(`${t.pathname}/v1/client/sync`,t.origin)}else this.domain&&(e=new URL("/v1/client/sync",`https://${this.domain}`));return e?.searchParams.append("redirect_url",window.location.href),e?.toString()||""};#eH=()=>"true"!==eO(W)&&!!this.isSatellite&&!!this.#ef?.isSignedOut();#eV=()=>"production"!==this.#ev&&!this.isSatellite&&!!eO(H);#eG=async()=>{"development"===this.instanceType?await this.navigate(this.#eW()):"production"===this.instanceType&&await this.navigate(this.#eK())};#eJ=(e,t)=>{let a;try{a=new URL(e)}catch{throw Error(`${t_} The signInUrl needs to have a absolute url format.`)}a.origin===t&&function(){throw Error(`${t_} The signInUrl needs to be on a different origin than your satellite application.`)}()};#eZ=()=>{this.isSatellite&&("development"!==this.#ev||this.#ez.signInUrl||function(){throw Error(`${t_} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${t_} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#ez.signInUrl&&this.#eJ(this.#ez.signInUrl,window.location.origin))};#eq=async()=>{if(this.#ef=await nu.create(this,this.#ek,this.#ev,this.#eE),this.#eZ(),this.#eH())return void await this.#eG();if(this.#eV())return void await this.#eF();this.#eS=(()=>{if(!s())return{onPageFocus:e3};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:t=>{e.push(t)}}})(),"undefined"!=typeof BroadcastChannel&&(this.#ey=new BroadcastChannel("clerk")),this.#e$();let e=function(e=window.location.hostname){if(!e)return!1;let t=ev.get(e);void 0===t&&(t=es.some(t=>e.startsWith("accounts.")&&e.endsWith(t))||eo.some(t=>e.endsWith(t)&&!e.endsWith(".clerk"+t)),ev.set(e,t));return t}(window?.location.hostname),t="development"===this.#ev&&!e,a=0,r=0;for(;r<2;){r++;try{var n;let e=rr.getInstance().fetch({touch:t}).then(e=>this.updateEnvironment(e)).catch(()=>{++a;let e=tj.getItem(tk,null);e&&this.updateEnvironment(new rr(e))}),r=async()=>aU.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(async e=>{if(P(e))throw e;++a;let t=this.#ef?.getSessionCookie(),r=function(e){let t;try{t=new rK({jwt:e||"",object:"token",id:void 0})}catch{t=null}if(aU.clearInstance(),!t?.jwt)return aU.getOrCreateInstance({object:"client",last_active_session_id:null,id:"client_init",sessions:[]});let{sessionId:a,userId:r,orgId:n,orgRole:i,orgPermissions:s,orgSlug:o,factorVerificationAge:l}=(e=>{let t,a,r,n,i=e.fva??null,s=e.sts??null;if(2===e.v){if(e.o){t=e.o?.id,r=e.o?.slg,e.o?.rol&&(a=`org:${e.o?.rol}`);let{org:i}=rA(e.fea),{permissions:s,featurePermissionMap:o}=(({per:e,fpm:t})=>{if(!e||!t)return{permissions:[],featurePermissionMap:[]};let a=e.split(",").map(e=>e.trim());return{permissions:a,featurePermissionMap:t.split(",").map(e=>Number.parseInt(e.trim(),10)).map(e=>e.toString(2).padStart(a.length,"0").split("").map(e=>Number.parseInt(e,10)).reverse()).filter(Boolean)}})({per:e.o?.per,fpm:e.o?.fpm});n=function({features:e,permissions:t,featurePermissionMap:a}){if(!e||!t||!a)return[];let r=[];for(let n=0;n<e.length;n++){let i=e[n];if(n>=a.length)continue;let s=a[n];if(s)for(let e=0;e<s.length;e++)1===s[e]&&r.push(`org:${i}:${t[e]}`)}return r}({features:i,featurePermissionMap:o,permissions:s})}}else t=e.org_id,a=e.org_role,r=e.org_slug,n=e.org_permissions;return{sessionClaims:e,sessionId:e.sid,sessionStatus:s,actor:e.act,userId:e.sub,orgId:t,orgRole:a,orgSlug:r,orgPermissions:n,factorVerificationAge:i}})(t.jwt.claims),c={object:"client",last_active_session_id:a,id:"client_init",sessions:[{object:"session",id:a,status:"active",last_active_organization_id:n||null,last_active_token:{id:void 0,object:"token",jwt:e},factor_verification_age:l||null,public_user_data:{user_id:r},user:{object:"user",id:r,organization_memberships:n&&o&&i?[{object:"organization_membership",id:n,role:i,permissions:s||[],organization:{object:"organization",id:n,name:o,slug:o,members_count:1,max_allowed_memberships:1}}]:[]}}]};return aU.getOrCreateInstance(c)}(t);return this.updateClient(r),this.#ef?.stopPollingForToken(),await this.session?.getToken({skipCache:!0}).catch(()=>null).finally(()=>{this.#ef?.startPollingForToken()}),null}),[,i]=await (n=[e,r()],Promise.all(Array.from(n).map(e=>e.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e})))));if("rejected"===i.status){let e=i.reason;if(td(e,"requires_captcha"))await r();else throw e}if(this.#ef?.setClientUatCookieForDevelopmentInstances(),await this.#eY())return;break}catch(e){if(td(e,"dev_browser_unauthenticated"))await this.#ef.handleUnauthenticatedDevBrowser();else if(!u())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${t_} Something went wrong initializing Clerk.`)}()}this.#eb=new nd(this),this.#eb.start(),this.#eQ(),this.#eX(),this.#e1(),this.#eE.emit(f,a>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#eO=async()=>{let e,t,a=this.shouldFallbackToCachedResources()?1:void 0,r=0;try{[e,t]=await Promise.all([rr.getInstance().fetch({touch:!1,fetchMaxTries:a}),aU.getOrCreateInstance().fetch({fetchMaxTries:a})])}catch(a){if(T(a)&&"network_error"===a.code&&this.shouldFallbackToCachedResources()){let a=await this.__internal_getCachedResources?.();e=new rr(a?.environment),aU.clearInstance(),t=aU.getOrCreateInstance(a?.client),++r}else throw a}this.updateClient(t),this.updateEnvironment(e),this.#eE.emit(f,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,t]=await Promise.all([rr.getInstance().fetch({touch:!1,fetchMaxTries:1}),aU.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(t),this.updateEnvironment(e),this.#eP()};#eL=e=>{if(e.lastActiveSessionId){let t=e.signedInSessions.find(t=>t.id===e.lastActiveSessionId);if(t)return t}return e.signedInSessions[0]||null};#e$=()=>{s()&&(this.#eS?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#eA>Date.now())&&(this.#eA=Date.now()+5e3,this.#ez.touchSession&&this.#eM(this.session))}),this.#ey?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),re.on(a8,()=>{this.#ey?.postMessage({type:"signout"})}),re.on(a4,()=>{tj.setItem(tk,this.environment?.__internal_toSnapshot(),864e5)}))};#eM=async e=>{if(!e)return Promise.resolve();await e.touch().catch(e=>{P(e)&&this.handleUnauthenticated()})};#eP=()=>{if(this.client)for(let e of this.#ej)e({client:this.client,session:this.session,user:this.user,organization:this.organization})};#eB=()=>{for(let e of this.#e_)e()};#eU=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#eP()};#e0=()=>(this.session?.user.organizationMemberships||[]).map(e=>e.organization).find(e=>e.id===this.session?.lastActiveOrganizationId)||null;#eC=e=>{this.session=e||null,this.organization=this.#e0(),this.user=this.session?this.session.user:null};#eR=e=>this.client?.signedInSessions.find(t=>t.id===e)||null;#eX=()=>{this.addListener(({session:e})=>{e?.actor&&this.#ew?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#e1=()=>{this.#ez.__internal_keyless_claimKeylessApplicationUrl&&this.#ew?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#ez.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#ez.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#ez.__internal_keyless_dismissPrompt}})})};#eD=(e,t,a)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#ez[e]||this.environment.displayConfig[e];this.#eT()&&(r=this.#ez.signInUrl);let n=new eC(this.#ez,t).toSearchParams(),i=new URLSearchParams(a||{}),s=ej({base:r,hashPath:this.#eT()&&"signUpUrl"===e?"/create":"",hashSearchParams:[i,n]},{stringify:!0});return this.buildUrlWithAuth(s)};assertComponentsReady(e){if(!e)throw Error("Clerk was not loaded with Ui components")}#eY=async()=>{var e;let t,a,r,n,i=new URLSearchParams(window.location.search).get("redirect_url"),s="production"===this.instanceType,o=null!==i&&(e=this.frontendApi,a=(t=new URL(i,ey)).pathname,r=eE.includes(a)||eI.includes(a),e===t.host&&r);if(s||!o)return!1;let l=this.session,c=this.#ez.signInUrl||this.environment?.displayConfig.signInUrl,u=c&&window.location.href.startsWith(c),d=this.#ez.signUpUrl||this.environment?.displayConfig.signUpUrl,h=d&&window.location.href.startsWith(d);return n=new URL(i,ey),(!eE.includes(n.pathname)||!!l||!u&&!h)&&(await this.navigate(this.buildUrlWithAuth(i)),!0)};#eI=e=>({...nj,...e,allowedRedirectOrigins:function(e,t,a){if(Array.isArray(e)&&e.length)return e;let r=[];return"undefined"!=typeof window&&window.location&&r.push(window.location.origin),r.push(`https://${ex(t)}`),r.push(`https://*.${ex(t)}`),"development"===a&&r.push(`https://${t}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)});#eQ=()=>{try{eT(W),eT(eP),eT(K),eT("__clerk_handshake"),eT("__clerk_handshake_nonce"),eT("__clerk_help")}catch{}};get #eN(){let e=eL;return this.#ez.allowedRedirectProtocols&&(e=e.concat(this.#ez.allowedRedirectProtocols)),e}}})();var s=exports;for(var o in i)s[o]=i[o];i.__esModule&&Object.defineProperty(s,"__esModule",{value:!0})})();