@buildbase/sdk 0.0.88 → 0.0.90

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 (58) hide show
  1. package/AGENTS.md +7 -3
  2. package/CHANGELOG.md +515 -0
  3. package/README.md +120 -3
  4. package/dist/cli.mjs +1 -1
  5. package/dist/css/styles.css +1 -1
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.ts +1351 -12
  8. package/dist/index.mjs +1 -1
  9. package/dist/mcp/index.cjs +1 -1
  10. package/dist/mcp/index.d.ts +120 -2
  11. package/dist/mcp/index.mjs +1 -1
  12. package/dist/react/chunks/SettingsDialog-BVyV5Zfm.mjs +2 -0
  13. package/dist/react/chunks/SettingsDialog-Ch8X6WXy.cjs +2 -0
  14. package/dist/react/chunks/{SubscriptionDialog-B8FTFRtp.cjs → SubscriptionDialog-CGIvMKpT.cjs} +1 -1
  15. package/dist/react/chunks/SubscriptionDialog-g0LwHhbe.mjs +2 -0
  16. package/dist/react/chunks/ar-3aqWucom.mjs +2 -0
  17. package/dist/react/chunks/ar-DQVB89r8.cjs +2 -0
  18. package/dist/react/chunks/de-DO10bhnU.cjs +2 -0
  19. package/dist/react/chunks/de-HXQk5D6k.mjs +2 -0
  20. package/dist/react/chunks/es-BZsmhBN3.mjs +2 -0
  21. package/dist/react/chunks/es-Cxg-qhUh.cjs +2 -0
  22. package/dist/react/chunks/fr-COCMy3vW.cjs +2 -0
  23. package/dist/react/chunks/fr-rdnNHzxy.mjs +2 -0
  24. package/dist/react/chunks/hi-BB0Z-Dgn.cjs +2 -0
  25. package/dist/react/chunks/hi-t3RH7ITu.mjs +2 -0
  26. package/dist/react/chunks/ja-CDyla2g0.mjs +2 -0
  27. package/dist/react/chunks/ja-D92JgUlk.cjs +2 -0
  28. package/dist/react/chunks/react-DTq7A_PT.mjs +2 -0
  29. package/dist/react/chunks/react-DeapSbq6.cjs +2 -0
  30. package/dist/react/chunks/zh-C5HABZZV.mjs +2 -0
  31. package/dist/react/chunks/zh-DK2yA5wB.cjs +2 -0
  32. package/dist/react/index.cjs +1 -1
  33. package/dist/react/index.d.ts +1517 -14
  34. package/dist/react/index.mjs +1 -1
  35. package/docs/ERROR_CODES.md +218 -0
  36. package/docs/THEMING.md +89 -21
  37. package/docs/UI-CONFIG.md +23 -4
  38. package/docs/USER-IMPORT.md +320 -0
  39. package/package.json +2 -1
  40. package/dist/react/chunks/SettingsDialog-CKVE1PpH.mjs +0 -2
  41. package/dist/react/chunks/SettingsDialog-DrDmxFEj.cjs +0 -2
  42. package/dist/react/chunks/SubscriptionDialog-UN7o9Hqb.mjs +0 -2
  43. package/dist/react/chunks/ar-B2l90OZJ.cjs +0 -2
  44. package/dist/react/chunks/ar-DVVNZhXD.mjs +0 -2
  45. package/dist/react/chunks/de-BspJtvAC.mjs +0 -2
  46. package/dist/react/chunks/de-dURUqbl0.cjs +0 -2
  47. package/dist/react/chunks/es-DArjREi5.cjs +0 -2
  48. package/dist/react/chunks/es-vu4BmI3g.mjs +0 -2
  49. package/dist/react/chunks/fr-DVm5WCvZ.mjs +0 -2
  50. package/dist/react/chunks/fr-DhYDaYrX.cjs +0 -2
  51. package/dist/react/chunks/hi-C_nv_c1T.cjs +0 -2
  52. package/dist/react/chunks/hi-VW8xCj_K.mjs +0 -2
  53. package/dist/react/chunks/ja-C-b88dvw.mjs +0 -2
  54. package/dist/react/chunks/ja-CqtDkLHr.cjs +0 -2
  55. package/dist/react/chunks/react-CHivaJhA.mjs +0 -2
  56. package/dist/react/chunks/react-Ch_Suxxy.cjs +0 -2
  57. package/dist/react/chunks/zh-D1yfhUf0.mjs +0 -2
  58. package/dist/react/chunks/zh-D_tMpsNt.cjs +0 -2
@@ -0,0 +1,2 @@
1
+ "use client";
2
+ import{jsxs as e,jsx as t,Fragment as n}from"react/jsx-runtime";import*as r from"react";import a,{Component as i,useMemo as s,useSyncExternalStore as o,createContext as c,useRef as l,useContext as d,useEffect as u,useCallback as p,useState as h,Suspense as m,lazy as g}from"react";import{clsx as f}from"clsx";import{twMerge as y}from"tailwind-merge";import{Loader2 as w,Eye as b,ChevronDown as v,Check as k,Copy as S,ExternalLink as I,Bot as C,Plus as x,Monitor as N,Smartphone as A,X as P,ShieldCheck as E,Bell as _,MonitorSmartphone as T,ChevronRight as U,MailOpen as R,BellOff as O,Mail as W,Archive as F,Building2 as L,RefreshCcw as D,Search as $,Users as M,Smile as j,Image as q}from"lucide-react";import B from"intl-messageformat";import{Slot as V}from"@radix-ui/react-slot";import{cva as z}from"class-variance-authority";import*as G from"@radix-ui/react-dialog";import{Cross2Icon as J,CheckIcon as H}from"@radix-ui/react-icons";import{zodResolver as Y}from"@hookform/resolvers/zod";import{Controller as K,FormProvider as Q,useFormContext as Z,useForm as X}from"react-hook-form";import*as ee from"@radix-ui/react-label";import{z as te}from"zod";import*as ne from"@radix-ui/react-avatar";import*as re from"@radix-ui/react-radio-group";import*as ae from"@radix-ui/react-scroll-area";import*as ie from"@radix-ui/react-separator";import*as se from"@radix-ui/react-accordion";import*as oe from"@radix-ui/react-alert-dialog";import*as ce from"@radix-ui/react-popover";function le(...e){return y(f(e))}let de=!0;function ue(e,...t){de&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(e,...t)}function pe(e,...t){console.error(e,...t)}function he(e,t){const n=AbortSignal.any;if("function"==typeof n)return n([e,t]);const r=new AbortController,a=e=>{r.signal.aborted||r.abort(e.reason)};for(const n of[e,t]){if(n.aborted){a(n);break}n.addEventListener("abort",()=>a(n),{once:!0})}return r.signal}function me(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}async function ge(e){const t=await e.text();if(!t)throw new Error("Empty response body");try{return JSON.parse(t)}catch(e){throw new Error(`Invalid JSON response: ${t.substring(0,100)}${t.length>100?"...":""}`)}}async function fe(e,t="Request failed"){if(!e.ok){let n,r=t;try{const t=await ge(e);r=t.message||t.error||r,"string"==typeof t.code&&(n=t.code)}catch{r=function(e,t){const n={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||t;return new Error(`${t} (${e.status}: ${n})`)}(e,t).message}throw Object.assign(new Error(r),{status:e.status,...n?{code:n}:{}})}try{return await ge(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class ye extends Error{constructor(e,t,n,r){super(e),this.code=t,this.context=n,this.originalError=r,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,ye)}}const we=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1},this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}configure(e){this.config={...this.config,...e},void 0!==e.enableConsoleLogging&&function(e){void 0!==e.enableLogging&&(de=e.enableLogging)}({enableLogging:e.enableConsoleLogging})}handleError(e,t={}){if(me(e))return;const n=e instanceof Error?e:new ye("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",t),r=n instanceof ye?n:new ye(n.message,"SDK_ERROR",t,n);if(this.config.enableConsoleLogging&&ue(`[SDK Error] ${t.component||"Unknown"}:`,{message:r.message,code:r.code,context:r.context,originalError:r.originalError,stack:r.stack}),this.config.onError)try{this.config.onError(r,t)}catch(e){pe("[SDK Error Handler] Error in custom error callback:",e)}for(const e of this.listeners)try{e(r,t)}catch(e){pe("[SDK Error Handler] Error in error listener:",e)}this.config.showUserNotifications&&this.notifyUser(r,t)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...n)=>e(...n).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...n)=>{try{return e(...n)}catch(e){throw this.handleError(e,t),e}}}};function be(e,t={}){we.handleError(e,t)}function ve(e,t={}){return!me(e)&&(we.handleError(e,t),!0)}function ke(e,t,n){return e instanceof Error?e.message:n(t)}function Se(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return be(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function Ie(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){be(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}function Ce(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){be(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}function xe(e,t){const n=Se(e);if(!n)return null;try{const r=JSON.parse(n);return t&&!t(r)?(be(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),Ce(e),null):r}catch(t){return be(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),Ce(e),null}}function Ne(e,t){try{Ie(e,JSON.stringify(t))}catch(t){be(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}const Ae="saas-session-id",Pe="saas-device-id",Ee="code",_e="state";function Te(e){Ie(Ae,e)}function Ue(){Ce(Ae)}function Re(){if("undefined"==typeof window)return null;try{return Se(Ae)}catch(e){return be(e,{component:"auth-utils",action:"getSessionId",metadata:{key:Ae}}),null}}function Oe(e){if("undefined"!=typeof window&&e)try{Ie(Pe,e)}catch(e){be(e,{component:"auth-utils",action:"setDeviceId",metadata:{key:Pe}})}}function We(){const e=Re(),t={};e&&(t["x-session-id"]=e);const n=function(){if("undefined"==typeof window)return null;try{return Se(Pe)??null}catch(e){return be(e,{component:"auth-utils",action:"getOrCreateDeviceId",metadata:{key:Pe}}),null}}();return n&&(t["x-device-id"]=n),t}function Fe(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get(Ee)}catch(e){return be(e,{component:"auth-utils",action:"getTokenFromUrl",metadata:{param:Ee}}),null}}function Le(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.delete(Ee),e.searchParams.delete(_e),window.history.replaceState({},"",e.toString())}catch(e){be(e,{component:"auth-utils",action:"removeTokenFromUrl",metadata:{param:Ee}})}}const De=Symbol.for("@buildbase/sdk/unreachable"),$e=/^(failed to fetch|networkerror when attempting to fetch resource\.?|load failed|fetch failed|network request failed)$/i;function Me(e){return Object.defineProperty(e,De,{value:!0}),e}function je(e){if(!e||"object"!=typeof e)return!1;if(!0===e[De])return!0;const{name:t,message:n}=e;return"TypeError"===t&&"string"==typeof n&&$e.test(n)}function qe(e,t,n="settings.common.error"){return je(e)?t("errors.unreachable"):e instanceof Error&&e.message?e.message:t(n)}const Be=new WeakSet,Ve=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),ze="SDK is not ready (missing serverUrl, version, or orgId)";class Ge{constructor(e){this.serverUrl=e.serverUrl,this.version=e.version,this.orgId=e.orgId,this.requireOrgId=e.requireOrgId??!1,this.basePath=e.basePath??"public",this._sessionId=e.sessionId,this._timeout=e.timeout??3e4,this._maxRetries=e.maxRetries??0,this._debug=e.debug??!1,this._customHeaders=e.headers??{},this._onError=e.onError,this._onUnauthorized=e.onUnauthorized,this._fetch=e.fetch??globalThis.fetch}ensureReady(){if(!this.serverUrl?.trim()||!this.version)throw new Error(ze);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(ze)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:We()}url(e){const t=e.startsWith("/")?e.slice(1):e;return`${this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}/${t}`}buildHeaders(e){const t={...this._customHeaders,...this.getAuthHeaders()};return e.headers&&Object.assign(t,e.headers),null==e.body||t["Content-Type"]||(t["Content-Type"]="application/json"),t}reportError(e,t){Be.has(e)||(Be.add(e),this._onError?.(e,t))}async executeFetch(e,t,n={}){return this.executeFetchUrl(this.url(e),t,e,n)}notifyUnauthorized(){this._onUnauthorized?.()}static delay(e,t){return new Promise((n,r)=>{const a=()=>{clearTimeout(i),r(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return a();const i=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e);t?.addEventListener("abort",a,{once:!0})})}async executeFetchUrl(e,t,n,r={}){const a=(t.method??"GET").toUpperCase(),i=n??e,s=this.buildHeaders(t),o={...t,headers:s},c=Ve.has(a);let l,d;if(this._timeout>0){d=new AbortController;const e=d;l=setTimeout(()=>e.abort(),this._timeout),o.signal=t.signal?he(t.signal,e.signal):e.signal}const u=e=>{if(d?.signal.aborted&&!t.signal?.aborted){const e=Me(new Error(`Request timeout after ${this._timeout}ms: ${a} ${i}`));return this.reportError(e,{method:a,path:i}),e}return e},p=async t=>{try{if("function"!=typeof this._fetch)throw new Error("No fetch implementation available. Global fetch requires Node 18+; on older runtimes pass a `fetch` in the SDK config (e.g. from `undici` or `node-fetch`).");const n=this._fetch.bind(globalThis),i=await n(e,o);if(this._debug&&console.log(`[BuildBase] ${a} ${e} → ${i.status}`),401===i.status&&this._onUnauthorized&&!r.deferUnauthorized&&this._onUnauthorized(),i.status>=500&&c&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await Ge.delay(e,o.signal),p(t+1)}return i}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw u(e);if(c&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`);try{await Ge.delay(e,o.signal)}catch(e){throw u(e)}return p(t+1)}throw e instanceof TypeError&&Me(e),e instanceof Error&&this.reportError(e,{method:a,path:i}),e}};try{return await p(0)}finally{void 0!==l&&clearTimeout(l)}}async fetchJson(e,t={},n="Request failed"){this.ensureReady();try{const r=await this.executeFetch(e,t);return await fe(r,n)}catch(n){throw n instanceof Error&&this.reportError(n,{method:(t.method??"GET").toUpperCase(),path:e}),n}}async fetchResponse(e,t={},n={}){return this.ensureReady(),this.executeFetch(e,t,n)}async fetchUnwrapped(e,t={},n="Request failed"){const r=await this.fetchResponse(e,t);return r.ok||await this.throwResponseError(r,n),this.unwrapResponse(r,n)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async fetchForeign(e,t={}){return this._fetch.call(globalThis,e,t)}async throwResponseError(e,t){let n=t,r=!1;try{n=(await e.json()).message||n}catch{n=`${t} (${e.status}: ${e.statusText})`,r=!0}const a=Object.assign(new Error(n),{status:e.status});throw r?Me(a):a}apiPath(e,...t){return e.reduce((e,n,r)=>e+n+(r<t.length?encodeURIComponent(String(t[r])):""),"")}async unwrapResponse(e,t){const n=await e.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||t);return void 0!==n.data?n.data:n}return n}}class Je extends Ge{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,n="Failed to initiate authentication",r=e=>this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});let a=await r(e);if(400===a.status&&(e.trackingConsent||e.trackingIdentity||e.trackingAttribution||e.invitationToken||e.locale)){const{trackingConsent:t,trackingIdentity:n,trackingAttribution:i,invitationToken:s,locale:o,...c}=e;a=await r(c)}return a.ok||await this.throwResponseError(a,n),this.unwrapResponse(a,n)}async getUsernamePolicy(e,t){const n=`${this.serverUrl}/api/${this.version}/auth/config?org=${encodeURIComponent(e)}`,r="Failed to fetch the sign-in settings",a=await this.fetchAbsoluteUrl(n,{signal:t});a.ok||await this.throwResponseError(a,r);const i=await this.unwrapResponse(a,r),s=i?.username??{},o=!0===s.enabled;return{enabled:o,required:o&&!0===s.required}}async getAccountDeletionGraceDays(e,t){const n=`${this.serverUrl}/api/${this.version}/auth/config?org=${encodeURIComponent(e)}`,r="Failed to fetch the sign-in settings",a=await this.fetchAbsoluteUrl(n,{signal:t});a.ok||await this.throwResponseError(a,r);const i=await this.unwrapResponse(a,r),s=Number((i?.security??{}).accountDeletionGraceDays);return Number.isFinite(s)?Math.min(30,Math.max(0,Math.floor(s))):7}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}async getDeviceToken(e,t){try{const n=await this.fetchUnwrapped("device-token",{headers:{"x-session-id":e},signal:t},"Failed to fetch device token");return n?.deviceToken??""}catch{return""}}async logout(e,t,n){await this.fetchJson("logout",{method:"POST",...e?{headers:{"x-session-id":e}}:{},...t?.all?{body:JSON.stringify({all:!0})}:{},signal:n},"Failed to sign out")}}class He extends Ge{constructor(e){super({...e,basePath:"beta",requireOrgId:!0})}getAuthHeaders(){return{}}async fetchConfig(){return this.fetchJson(`config?orgId=${encodeURIComponent(this.orgId)}`,{},"Failed to fetch beta form configuration")}async submitBetaUser(e){return this.fetchJson("submit",{method:"POST",body:JSON.stringify(e)},"Failed to submit beta user request")}}let Ye=class{constructor(e){this.api=new He(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const t=e?.context??{},n=t?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),r=t?.language??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[0]:void 0),a=t?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),i=t?.currency??("undefined"!=typeof Intl&&Intl.NumberFormat&&Intl.NumberFormat().resolvedOptions().currency?Intl.NumberFormat().resolvedOptions().currency:void 0);return this.api.submitBetaUser({orgId:this.orgId,formData:{...e,country:n,language:r,timezone:a,currency:i}})}};class Ke extends Ge{constructor(e){super(e)}async list(e){const t=await this.fetchJson("connected-agents",{signal:e},"Failed to load connected agents");return t?.agents??[]}async revoke(e){await this.fetchJson("connected-agents/revoke",{method:"POST",body:JSON.stringify({clientId:e})},"Failed to disconnect agent")}}class Qe extends Ge{constructor(e){super(e)}async list(e){const t=await this.fetchJson("devices",{signal:e},"Failed to load devices");return t?.devices??[]}async rename(e,t,n){await this.fetchJson(this.apiPath`devices/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:n},"Failed to rename device")}async signOut(e,t){return this.fetchJson(this.apiPath`devices/${e}`,{method:"DELETE",signal:t},"Failed to sign out device")}async forget(e,t){return this.fetchJson(`${this.apiPath`devices/${e}`}?forget=true`,{method:"DELETE",signal:t},"Failed to forget device")}}function Ze(e){const t=new URLSearchParams;for(const[n,r]of Object.entries(e))void 0!==r&&""!==r&&!1!==r&&t.set(n,String(r));const n=t.toString();return n?`?${n}`:""}const Xe=e=>JSON.stringify(e?{workspaceId:e}:{});class et extends Ge{constructor(e){super(e)}async list(e={},t){const n=await this.fetchJson(`notifications${Ze({workspaceId:e.workspaceId,unread:e.unread,archived:e.archived,page:e.page,limit:e.limit})}`,{signal:t},"Failed to load notifications");return{notifications:n?.notifications??[],page:n?.page??e.page??1,limit:n?.limit??e.limit??20,total:n?.total??0,hasNextPage:Boolean(n?.hasNextPage)}}async counts(e,t){const n=await this.fetchJson(`notifications/unread-count${Ze({workspaceId:e})}`,{signal:t},"Failed to load notification count");return{unread:n?.unread??0,unseen:n?.unseen??0}}markRead(e){return this.itemAction(this.apiPath`notifications/${e}/read`,"POST",!0)}markUnread(e){return this.itemAction(this.apiPath`notifications/${e}/unread`,"POST")}archive(e){return this.itemAction(this.apiPath`notifications/${e}/archive`,"POST")}unarchive(e){return this.itemAction(this.apiPath`notifications/${e}/archive`,"DELETE")}async markAllRead(e){await this.fetchJson("notifications/read-all",{method:"POST",body:Xe(e)},"Failed to mark notifications read")}async markSeen(e){await this.fetchJson("notifications/seen",{method:"POST",body:Xe(e)},"Failed to mark notifications seen")}async itemAction(e,t,n=!1){return this.fetchJson(e,n?{method:t,keepalive:n}:{method:t},"Failed to update notification")}}class tt extends Ge{constructor(e){super({...e,requireOrgId:!0})}async getVapidPublicKey(){return this.fetchJson("push/vapid-public-key")}async subscribe(e,t){await this.fetchJson("push/subscribe",{method:"POST",body:JSON.stringify({endpoint:e.endpoint,keys:e.keys,userAgent:t})})}async unsubscribe(e){await this.fetchJson("push/unsubscribe",{method:"DELETE",body:JSON.stringify({endpoint:e})})}}class nt extends Ge{constructor(e){super(e)}async list(e){const t=await this.fetchJson("sessions",{signal:e},"Failed to load sessions");return t?.sessions??[]}async revoke(e,t){await this.fetchJson(this.apiPath`sessions/${e}`,{method:"DELETE",signal:t},"Failed to sign out session")}}class rt extends Ge{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}const at="image/png,image/jpeg,image/gif,image/webp,image/svg+xml",it=5242880,st={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml"};function ot(e){if(e.type)return e.type;const t=(e.name??"").split(".").pop()?.toLowerCase()??"";return st[t]??""}function ct(e){const{status:t,code:n}=e??{};return"UPLOAD_TOO_LARGE"===n||413===t?"tooLarge":"INVALID_UPLOAD"===n?"invalid":"UPLOADS_DISABLED"===n?"disabled":"USER_UPLOAD_LIMIT"===n?"userLimit":"UPLOADS_UNAVAILABLE"===n||429===t||501===t||503===t?"unavailable":"failed"}function lt(e){const t=e?.uploads,n=Number(t?.maxFileBytes);return{enabled:!!t&&!1!==t.enabled,maxFileBytes:Number.isFinite(n)&&n>0?Math.min(n,it):it}}function dt(e,t){return t.enabled?e.size>t.maxFileBytes?"tooLarge":null:"disabled"}function ut(e,t){const n=1048576,[r,a]=e>=n?[e/n,"megabyte"]:[e/1024,"kilobyte"];try{return new Intl.NumberFormat(t,{style:"unit",unit:a,unitDisplay:"short",maximumFractionDigits:1}).format(r)}catch{return`${Math.round(10*r)/10} ${"megabyte"===a?"MB":"KB"}`}}class pt extends Ge{constructor(e){super(e)}async upload(e,t){const{purpose:n,signal:r}=t,a=await this.fetchJson("uploads",{method:"POST",body:JSON.stringify({purpose:n,name:e.name??"file",size:e.size,contentType:ot(e)}),signal:r},"Could not start the upload");let i;const s=new AbortController,o=setTimeout(()=>s.abort(),12e4);try{i=await this.fetchForeign(a.url,{method:"PUT",headers:a.headers,body:e,signal:r?he(r,s.signal):s.signal})}catch(e){if(r?.aborted)throw e;throw new Error("The upload to storage did not finish. Check the connection and try again.")}finally{clearTimeout(o)}if(!i.ok)throw Object.assign(new Error(`The upload to storage was refused (HTTP ${i.status}). Try again.`),{status:i.status});return this.fetchJson(this.apiPath`uploads/${a.uploadId}/complete`,{method:"POST",body:"{}",signal:r},"Could not finish the upload")}}class ht extends Ge{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user attributes");const n=await this.unwrapResponse(t,"Failed to fetch user attributes");return n&&"object"==typeof n&&!Array.isArray(n)?n:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(this.apiPath`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user features");const n=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof n&&null!==n?n:{}}}const mt={NOT_FOUND:"INVITATION_NOT_FOUND",EXPIRED:"INVITATION_EXPIRED",ALREADY_HANDLED:"INVITATION_ALREADY_HANDLED",EMAIL_MISMATCH:"INVITATION_EMAIL_MISMATCH",EMAIL_NOT_VERIFIED:"EMAIL_NOT_VERIFIED",INVITES_DISABLED:"WORKSPACE_INVITES_DISABLED",RATE_LIMITED:"INVITATION_RATE_LIMITED",EMAIL_FAILED:"INVITATION_EMAIL_FAILED",SEAT_LIMIT:"SEAT_LIMIT_REACHED",USER_BLOCKED:"USER_BLOCKED",NO_SENDER_CONFIGURED:"NO_SENDER_CONFIGURED"},gt={402:mt.SEAT_LIMIT,404:mt.NOT_FOUND,409:mt.ALREADY_HANDLED,410:mt.EXPIRED,429:mt.RATE_LIMITED,502:mt.EMAIL_FAILED,503:mt.NO_SENDER_CONFIGURED};function ft(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function yt(e){return"string"==typeof e&&e?e:void 0}async function wt(e,t){let n=null;try{n=await e.json()}catch{n=null}return function(e,t,n){const r=t&&"object"==typeof t?t:{},a=yt(r.message)??yt(r.error)??n,i={status:e,code:yt(r.code)??gt[e]??`HTTP_${e}`,currentUserCount:ft(r.currentUserCount),limit:ft(r.limit),retryAfterSeconds:ft(r.retryAfterSeconds),invitedEmail:yt(r.invitedEmail),invitationId:yt(r.invitationId),invitationStatus:yt(r.status)};return Object.assign(new Error(a),i)}(e.status,n,t)}function bt(e){return e instanceof Error&&"number"==typeof e.status}function vt(e){return"string"==typeof e&&e.length>0}function kt(e){return"number"==typeof e&&Number.isInteger(e)&&e>0}function St(e){return"number"==typeof e&&Number.isFinite(e)?Math.max(0,Math.ceil(e)):void 0}class It extends Ge{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(e){return this.fetchJson("workspaces",{signal:e},"Failed to fetch workspaces")}async createWorkspace(e,t){try{return await this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e),signal:t},"Failed to create workspace")}catch(n){const r=n?.status;if(400===r&&e.trackingAttribution){const{trackingAttribution:n,...r}=e;return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(r),signal:t},"Failed to create workspace")}throw n}}async updateWorkspace(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t),signal:n},"Failed to update workspace")}async deleteWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"DELETE",signal:t},"Failed to delete workspace")}async getWorkspaceUsers(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users`,{signal:t},"Failed to fetch workspace users")}async addUser(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to invite member")}async fetchInvitation(e,t={},n="Request failed"){const r=await this.fetchResponse(e,t);if(!r.ok)throw await wt(r,n);return fe(r,n)}async listInvitations(e,t){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations`,{signal:t},"Failed to fetch invitations")}async inviteMember(e,t,n){const r={email:t.email,role:t.role};return t.landingUrl&&(r.landingUrl=t.landingUrl),this.fetchInvitation(this.apiPath`workspaces/${e}/invitations`,{method:"POST",body:JSON.stringify(r),signal:n},"Failed to send invitation")}async resendInvitation(e,t,n){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations/${t}/resend`,{method:"POST",signal:n},"Failed to resend invitation")}async revokeInvitation(e,t,n){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations/${t}`,{method:"DELETE",signal:n},"Failed to revoke invitation")}async myInvitations(e){return this.fetchInvitation("invitations",{signal:e},"Failed to fetch your invitations")}async acceptInvitation(e,t,n){return this.fetchInvitation(this.apiPath`invitations/${e}/accept`,{method:"PATCH",signal:n,...t?.token?{body:JSON.stringify({token:t.token})}:{}},"Failed to accept invitation")}async declineInvitation(e,t){return this.fetchInvitation(this.apiPath`invitations/${e}/reject`,{method:"PATCH",signal:t},"Failed to decline invitation")}async previewInvitation(e,t){if(!this.orgId)throw new Error("orgId is required for previewInvitation");return this.fetchInvitation(this.apiPath`${this.orgId}/invitations/preview/${e}`,{signal:t},"Failed to load invitation")}async removeUser(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE",signal:n},"Failed to remove user")}async updateUser(e,t,n,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(n),signal:r},"Failed to update user")}async updateSettings(e,t){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t}),signal:n},"Failed to update workspace permissions")}async getMyPermissions(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/permissions/me`,{signal:t},"Failed to fetch workspace permissions")}async getFeatures(e){return this.fetchJson("workspaces/features",{signal:e},"Failed to fetch features")}async updateFeature(e,t,n,r){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:n}}),signal:r},"Failed to update feature")}async getWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{signal:t},"Failed to fetch workspace")}async getProfile(e){return this.fetchJson("profile",{signal:e},"Failed to fetch profile")}async updateUserProfile(e,t){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update user profile")}async changePassword(e,t,n){await this.fetchWithReason("profile/password",{method:"POST",body:JSON.stringify({currentPassword:e,newPassword:t}),signal:n},"Failed to change password")}async fetchWithReason(e,t,n,r=[]){const a=r.length>0,i=await this.fetchResponse(e,t,{deferUnauthorized:a});if(!i.ok){let e,t,s=n,o={},c=!1;try{const n=await i.json();"string"==typeof n?.message&&n.message&&(s=n.message),"string"==typeof n?.reason&&n.reason&&(e=n.reason),t=St(n?.retryAfter),o=function(e){if(!e||"object"!=typeof e)return{};const{maxAgeSeconds:t,factors:n,workspaces:r}=e,a={},i=St(t);if(void 0!==i&&(a.maxAgeSeconds=i),Array.isArray(n)){const e=n.filter(e=>"mfa"===e);e.length&&(a.factors=e)}return Array.isArray(r)&&(a.workspaces=r.filter(e=>!!e&&"object"==typeof e&&"string"==typeof e.id&&"string"==typeof e.name).map(({id:e,name:t})=>({id:e,name:t}))),a}(n)}catch{s=`${n} (${i.status}: ${i.statusText})`,c=!0}!a||401!==i.status||void 0!==e&&r.includes(e)||this.notifyUnauthorized();const l=Object.assign(new Error(s),{status:i.status,...e?{code:e}:{},...void 0!==t?{retryAfter:t}:{},...o});throw c?Me(l):l}return this.unwrapResponse(i,n)}static compactCode(e){return e.replace(/\s+/g,"")}async requestEmailChange(e,t){const n=await this.fetchWithReason("profile/email",{method:"POST",body:JSON.stringify({newEmail:e.trim()}),signal:t},"Failed to send the code");return{retryAfter:St(n?.retryAfter)??0}}async confirmEmailChange(e,t){return this.fetchWithReason("profile/email/confirm",{method:"POST",body:JSON.stringify({code:It.compactCode(e)}),signal:t},"Failed to change email",["code_expired"])}async addPhone(e,t,n){const r=await this.fetchWithReason("profile/phone",{method:"POST",body:JSON.stringify({phone:e.trim(),...t?{channel:t}:{}}),signal:n},"Failed to send the code");return{retryAfter:St(r?.retryAfter)??0}}async confirmPhone(e,t){const n=await this.fetchWithReason("profile/phone/confirm",{method:"POST",body:JSON.stringify({code:It.compactCode(e)}),signal:t},"Failed to verify the phone number");return{phone:"string"==typeof n?.phone?n.phone:"",phoneVerified:!0}}async removePhone(e){await this.fetchWithReason("profile/phone",{method:"DELETE",signal:e},"Failed to remove the phone number")}async getMfaStatus(e){return this.fetchWithReason("mfa",{signal:e},"Failed to fetch two-step sign-in status")}async startTotpEnrollment(e){return this.fetchWithReason("mfa/totp/enroll",{method:"POST",signal:e},"Failed to start authenticator app setup")}async confirmTotpEnrollment(e,t){return this.fetchWithReason("mfa/totp/confirm",{method:"POST",body:JSON.stringify({code:It.compactCode(e)}),signal:t},"Failed to confirm authenticator app")}async disableTotp(e,t){await this.fetchWithReason("mfa/totp/disable",{method:"POST",body:JSON.stringify({code:It.compactCode(e)}),signal:t},"Failed to turn off two-step sign-in")}async regenerateBackupCodes(e,t){return this.fetchWithReason("mfa/backup-codes/regenerate",{method:"POST",body:JSON.stringify({code:It.compactCode(e)}),signal:t},"Failed to make new backup codes")}async startSmsEnrollment(e){const t=await this.fetchWithReason("mfa/sms/enroll",{method:"POST",signal:e},"Failed to send the code");return{retryAfter:St(t?.retryAfter)??0,..."string"==typeof t?.phone&&t.phone?{phone:t.phone}:{}}}async confirmSmsEnrollment(e,t){const n=await this.fetchWithReason("mfa/sms/enroll/confirm",{method:"POST",body:JSON.stringify({code:It.compactCode(e)}),signal:t},"Failed to turn on text message codes"),r=n?.backupCodes;return Array.isArray(r)&&r.length>0&&r.every(e=>"string"==typeof e)?{backupCodes:r}:{}}async disableSms(e){await this.fetchWithReason("mfa/sms/disable",{method:"POST",signal:e},"Failed to turn off text message codes")}async getPasskeys(e){const t=await this.fetchJson("passkeys",{signal:e},"Failed to fetch passkeys");return t?.passkeys??[]}async renamePasskey(e,t,n){await this.fetchWithReason(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:n},"Failed to rename passkey")}async deletePasskey(e,t){await this.fetchWithReason(this.apiPath`passkeys/${e}`,{method:"DELETE",signal:t},"Failed to remove passkey")}async getConnectedAccounts(e){const t=await this.fetchWithReason("accounts",{signal:e},"Failed to fetch connected accounts"),n=Array.isArray(t?.accounts)?t.accounts:[],r=Array.isArray(t?.available)?t.available:[],a=function(e){if(!e||"object"!=typeof e)return;const{ethereumChainIds:t,solana:n}=e,r=Array.isArray(t)?t.filter(kt):[];return 0!==r.length||!0===n?{ethereumChainIds:r,solana:!0===n}:void 0}(t?.wallet);return{accounts:n.filter(e=>"string"==typeof e?._id&&!!e._id).map(({detail:e,...t})=>({...t,label:"string"==typeof t.label&&t.label?t.label:t.provider,..."string"==typeof e&&e?{detail:e}:{},canUnlink:!0===t.canUnlink})),available:r.filter(e=>"string"==typeof e?.methodId&&!!e.methodId).map(e=>({...e,label:"string"==typeof e.label&&e.label?e.label:e.provider})),...a?{wallet:a}:{},signInWays:"number"==typeof t?.signInWays&&Number.isFinite(t.signInWays)?t.signInWays:0,recentSignIn:!0===t?.recentSignIn}}async linkAccount(e,t,n){const r=await this.fetchWithReason("accounts",{method:"POST",body:JSON.stringify({methodId:e,redirect:t}),signal:n},"Failed to start connecting the account");if("string"!=typeof r?.url||!r.url)throw new Error("Failed to start connecting the account: the server sent no URL");return{url:r.url}}async unlinkAccount(e,t){await this.fetchWithReason(this.apiPath`accounts/${e}`,{method:"DELETE",signal:t},"Failed to remove the connected account")}async requestWalletNonce(e,t){const n=await this.fetchWithReason("accounts/wallet/nonce",{method:"POST",body:JSON.stringify({chain:e}),signal:t},"Failed to start connecting the wallet"),{nonce:r,domain:a,uri:i,issuedAt:s}=n??{};if(!(vt(r)&&vt(a)&&vt(i)&&vt(s)))throw new Error("Failed to start connecting the wallet: the server sent no nonce");const o=Array.isArray(n?.chainIds)?n.chainIds.filter(kt):void 0;return{nonce:r,domain:a,uri:i,issuedAt:s,...o?{chainIds:o}:{}}}async linkWallet(e,t){const{chain:n,message:r,signature:a}=e,i=await this.fetchWithReason("accounts/wallet",{method:"POST",body:JSON.stringify({chain:n,message:r,signature:a}),signal:t},"Failed to connect the wallet",["nonce_expired"]);if(!vt(i?._id))throw new Error("Failed to connect the wallet: the server sent no account");const s=vt(i.provider)?i.provider:n;return{_id:i._id,provider:s,label:vt(i.label)?i.label:s,...vt(i.icon)?{icon:i.icon}:{},...vt(i.detail)?{detail:i.detail}:{},canUnlink:!1}}async startReverification(e,t){const{returnUrl:n,factors:r}=e,a=await this.fetchWithReason("session/reverify",{method:"POST",body:JSON.stringify({returnUrl:n,...r?.length?{factors:r}:{}}),signal:t},"Failed to start confirming it is you");if(!vt(a?.url))throw new Error("Failed to start confirming it is you: the server sent no URL");return{url:a.url}}async requestAccountDeletion(e){const t=await this.fetchWithReason("account/delete",{method:"POST",signal:e},"Failed to delete the account");return{deleteAfter:vt(t?.deleteAfter)?t.deleteAfter:null,deleted:!0===t?.deleted||null===t?.deleteAfter}}async cancelAccountDeletion(e){const t=await this.fetchWithReason("account/delete/cancel",{method:"POST",signal:e},"Failed to cancel the deletion");return{cancelled:!0===t?.cancelled}}async setUsername(e,t){const n=e.trim(),r=await this.fetchWithReason("profile/username",{method:"PUT",body:JSON.stringify({username:n}),signal:t},"Failed to save the username");return{username:vt(r?.username)?r.username:n.toLowerCase()}}async removeUsername(e){await this.fetchWithReason("profile/username",{method:"DELETE",signal:e},"Failed to remove the username")}async requestGuestUpgrade(e,t){const n=e.name?.trim(),r=await this.fetchWithReason("guest/upgrade",{method:"POST",body:JSON.stringify({email:e.email.trim(),...n?{name:n}:{},...e.password?{password:e.password}:{}}),signal:t},"Failed to send the code");return{retryAfter:St(r?.retryAfter)??0}}async confirmGuestUpgrade(e,t){return this.fetchWithReason("guest/upgrade/confirm",{method:"POST",body:JSON.stringify({code:It.compactCode(e)}),signal:t},"Failed to create your account")}async getCurrentSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{signal:t},"Failed to fetch subscription")}async getPlanGroup(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`,{signal:t},"Failed to fetch plan group")}async getPlanGroupByVersion(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`,{signal:n},"Failed to fetch plan group version")}async getPlanGroupVersions(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group/versions`,{signal:t},"Failed to fetch plan group versions")}async getPublicPlans(e,t){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");return this.fetchUnwrapped(this.apiPath`${this.orgId}/plans/${encodeURIComponent(e)}`,{signal:t},"Failed to fetch plans")}async getPublicCreditPackages(e){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");return this.fetchUnwrapped(this.apiPath`${this.orgId}/credit-packages`,{signal:e},"Failed to fetch credit packages")}async getPlanGroupVersion(e,t){return this.fetchUnwrapped(this.apiPath`plan-group-versions/${e}`,{signal:t},"Failed to fetch plan group version")}async createCheckoutSession(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to create checkout session")}async selectFreePlan(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t}),signal:n},"Failed to select free plan")}async updateSubscription(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t),signal:n},"Failed to update subscription")}async createBillingPortalSession(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{}),signal:n})}async listInvoices(e,t=10,n,r){const a=new URLSearchParams;return a.append("limit",t.toString()),n&&a.append("starting_after",n),this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices`+`?${a.toString()}`,{signal:r},"Failed to fetch invoices")}async getInvoice(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices/${t}`,{signal:n},"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST",signal:t},"Failed to cancel subscription")}async resumeSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/resume`,{method:"POST",signal:t},"Failed to resume subscription")}async recordUsage(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to record usage")}async recordUsageBatch(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to record batch usage")}async getQuotaUsageStatus(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`,{signal:n},"Failed to fetch quota usage status")}async getAllQuotaUsage(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/all`,{signal:t},"Failed to fetch all quota usage")}async getUsageLogs(e,t,n){const r=new URLSearchParams;t?.quotaSlug&&r.append("quotaSlug",t.quotaSlug),t?.from&&r.append("from",t.from),t?.to&&r.append("to",t.to),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const a=r.toString(),i=this.apiPath`workspaces/${e}/subscription/usage/logs`+(a?`?${a}`:"");return this.fetchUnwrapped(i,{signal:n},"Failed to fetch usage logs")}async sendNotification(e,t,n,r,a){const i={event:t};return n&&(i.userId=n),r&&(i.data=r),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(i),signal:a},"Failed to send notification")}async getNotificationEvents(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/notification-events`,{signal:t},"Failed to fetch notification events")}async getNotificationPreferences(e,t){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{signal:t},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t,n){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:n},"Failed to update notification preferences")).notificationPreferences??{}}async getMyNotificationPreferences(e,t){const n=await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences/me`,{signal:t},"Failed to fetch your notification preferences");return{defaults:n?.defaults??{},mine:n?.mine??{}}}async updateMyNotificationPreferences(e,t,n){const r=await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences/me`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:n},"Failed to update your notification preferences");return{defaults:r?.defaults??{},mine:r?.mine??{}}}async getCreditBalance(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits`,{signal:t},"Failed to fetch credit balance")}async consumeCredits(e,t,n){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t),signal:n});if(!r.ok){if(402===r.status){const e=await r.json().catch(()=>({})),t=new Error(e.message||"Insufficient credits");throw t.available=e.available,t.requested=e.requested,t.code="INSUFFICIENT_CREDITS",t}await this.throwResponseError(r,"Failed to consume credits")}return this.unwrapResponse(r,"Failed to consume credits")}async purchaseCredits(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to create credit purchase checkout")}async getCreditPackages(e,t){const n=await this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/packages`,{signal:t},"Failed to fetch credit packages");return n.docs??n}async getCreditTransactions(e,t,n){const r=new URLSearchParams;t?.type&&r.append("type",t.type),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const a=r.toString(),i=this.apiPath`workspaces/${e}/credits/transactions`+(a?`?${a}`:"");return this.fetchUnwrapped(i,{signal:n},"Failed to fetch credit transactions")}async getCreditBuckets(e,t,n){const r=new URLSearchParams;t?.status&&r.append("status",t.status),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const a=r.toString(),i=this.apiPath`workspaces/${e}/credits/buckets`+(a?`?${a}`:"");return this.fetchUnwrapped(i,{signal:n},"Failed to fetch credit buckets")}async getExpiringCredits(e,t,n){const r=t?`?days=${t}`:"";return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/expiring`+r,{signal:n},"Failed to fetch expiring credits")}}var Ct;function xt(e){return Boolean(e?.serverUrl&&e?.version&&e?.orgId)}!function(e){e.V1="v1"}(Ct||(Ct={}));const Nt={UserCreated:"user:created",UserUpdated:"user:updated",WorkspaceChanged:"workspace:changed",WorkspaceUpdated:"workspace:updated",WorkspaceUserAdded:"workspace:user-added",WorkspaceUserRemoved:"workspace:user-removed",WorkspaceUserRoleChanged:"workspace:user-role-changed",WorkspaceCreated:"workspace:created",WorkspaceDeleted:"workspace:deleted",WorkspaceInvitationSent:"workspace:invitation-sent",WorkspaceInvitationAccepted:"workspace:invitation-accepted",WorkspaceInvitationDeclined:"workspace:invitation-declined",WorkspaceInvitationRevoked:"workspace:invitation-revoked"};class At{constructor(){this.callbacks=null,this.listeners=new Map}setCallbacks(e){this.callbacks=e}getCallbacks(){return this.callbacks}async emit(e,t){if(this.callbacks?.handleEvent)try{await this.callbacks.handleEvent(e,t)}catch(t){be(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}const n=this.listeners.get(e);if(n)for(const r of[...n])try{r(t)}catch(t){be(t,{component:"EventEmitter",action:"notifyListener",metadata:{eventType:e}})}}on(e,t){const n=this.listeners.get(e)??new Set;return n.add(t),this.listeners.set(e,n),()=>{this.listeners.get(e)?.delete(t)}}async emitUserCreated(e){await this.emit(Nt.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(Nt.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(Nt.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(Nt.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,n){await this.emit(Nt.WorkspaceUserAdded,{userId:e,workspace:t,role:n})}async emitWorkspaceInvitationSent(e,t){await this.emit(Nt.WorkspaceInvitationSent,{invitation:e,workspaceId:t})}async emitWorkspaceInvitationAccepted(e,t){await this.emit(Nt.WorkspaceInvitationAccepted,{invitation:e,workspace:t})}async emitWorkspaceInvitationDeclined(e){await this.emit(Nt.WorkspaceInvitationDeclined,{invitation:e})}async emitWorkspaceInvitationRevoked(e,t){await this.emit(Nt.WorkspaceInvitationRevoked,{invitationId:e,workspaceId:t})}async emitWorkspaceUserRemoved(e,t,n){await this.emit(Nt.WorkspaceUserRemoved,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRoleChanged(e,t,n,r){await this.emit(Nt.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:n,newRole:r})}async emitWorkspaceCreated(e){await this.emit(Nt.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(Nt.WorkspaceDeleted,{workspace:e})}}const Pt=new At,Et=globalThis;function _t(e){const t=Symbol.for(`@buildbase/sdk.invalidation.${e}`),n=Et[t]??(Et[t]=new Set);return{subscribe:e=>(n.add(e),()=>{n.delete(e)}),invalidate(){n.forEach(e=>e())},reset(){n.clear()}}}const Tt=_t("credit-balance"),Ut=Tt.subscribe,Rt=Tt.invalidate,Ot=_t("quota-usage"),Wt=Ot.subscribe,Ft=Ot.invalidate,Lt=_t("subscription"),Dt=Lt.subscribe,$t=Lt.invalidate,Mt="bb",jt={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",OpenConnectGuide:"openConnectGuide",Invite:"invite"},qt={Success:"success",Cancel:"cancel",Error:"error"},Bt={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",Security:"security",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function Vt(e,t){const n=t??("undefined"!=typeof window?window.location.href:"https://localhost");let r;try{r=new URL(n)}catch{throw new Error(`createBBUrl: invalid base URL: ${JSON.stringify(n)}`)}return r.search="",r.searchParams.set(Mt,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),r.toString()}function zt(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:Vt({action:jt.Checkout,status:qt.Success,ws:e,screen:Bt.Subscription},n),cancelUrl:Vt({action:jt.Checkout,status:qt.Cancel,ws:e,screen:Bt.Subscription},n)}}function Gt(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:Vt({action:jt.CreditPurchase,status:qt.Success,ws:e,screen:Bt.Credits},n),cancelUrl:Vt({action:jt.CreditPurchase,status:qt.Cancel,ws:e,screen:Bt.Credits},n)}}function Jt(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(Mt);if(!e)return null;const t=function(e){const t={};if(!e)return t;const n=e.split(",");for(const e of n){const n=e.indexOf(":");if(-1===n)continue;const r=decodeURIComponent(e.slice(0,n)),a=decodeURIComponent(e.slice(n+1));r&&(t[r]=a)}return t}(e);return Object.keys(t).length>0?t:null}catch{return null}}function Ht(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(Mt)&&(e.searchParams.delete(Mt),window.history.replaceState({},"",e.toString()))}catch{}}const Yt="__buildbaseBeforeLeave",Kt=globalThis,Qt=Kt[Yt]??(Kt[Yt]=new Set);function Zt(e,t={}){if(!e||"string"!=typeof e)return null;if(/^\/(?![/\\])/.test(e))return e;let n;try{n=new URL(e)}catch{return null}const r="https:"===n.protocol,a="http:"===n.protocol&&("localhost"===n.hostname||"127.0.0.1"===n.hostname||"[::1]"===n.hostname);if(!r&&!a)return null;const{sameOrigin:i,allowedOrigins:s}=t;return i||s?.length?i&&"undefined"!=typeof window&&window.location&&n.origin===window.location.origin||s?.some(e=>e.replace(/\/+$/,"")===n.origin)?e:null:e}function Xt(e,t="/",n={}){if("undefined"==typeof window||!window.location)return!1;const r=Zt(e,n)??Zt(t)??"/";return function(e){if("undefined"==typeof window||!window.location||0===Qt.size)return;let t;try{t=new URL(e,window.location.href).origin}catch{return}if(t!==window.location.origin)for(const e of Qt)try{e()}catch{}}(r),window.location.href=r,!0}const en="saas-auth-intent";function tn(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function nn(e){Zt(e,{sameOrigin:!0})&&Ne(en,{returnUrl:e,createdAt:Date.now()})}function rn(){const e=xe(en,tn);return Ce(en),e?Date.now()-e.createdAt>6e5?null:Zt(e.returnUrl,{sameOrigin:!0}):null}function an(){Ce(en)}const sn={usd:"$",eur:"€",gbp:"£",jpy:"¥",cad:"CA$",aud:"A$",chf:"CHF",cny:"¥",hkd:"HK$",sgd:"S$",inr:"₹",mxn:"MX$",brl:"R$",nzd:"NZ$",sek:"kr",nok:"kr",dkk:"kr",pln:"zł",thb:"฿"},on={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function cn(e){return e&&e.trim()?on[e.trim().toLowerCase()]??"":""}function ln(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return sn[t]??t.toUpperCase()}const dn=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],un=dn.map(e=>({value:e,label:`${e.toUpperCase()} (${ln(e)})`})),pn=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),hn=new Set(["bhd","jod","kwd","omr","tnd"]),mn=new Map;function gn(e){const t=(e??"").trim().toLowerCase();if(!t)return 2;if(pn.has(t))return 0;if(hn.has(t))return 3;if("isk"===t)return 2;let n=mn.get(t);if(void 0===n){try{n=new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).resolvedOptions().maximumFractionDigits??2}catch{n=2}mn.set(t,n)}return n}function fn(e){return""!==(e??"").trim()&&0===gn(e)}function yn(e,t){const n=gn(t);return 0===n?e.toLocaleString("en-US"):(e/10**n).toFixed(n)}function wn(e,t,n="en-US"){const r=(t??"").trim(),a=gn(r),i=e/10**a;if(!r)return i.toFixed(a);try{return new Intl.NumberFormat(n,{style:"currency",currency:r.toUpperCase(),minimumFractionDigits:a,maximumFractionDigits:a}).format(i)}catch{return ln(r)+(0===a?i.toLocaleString("en-US"):i.toFixed(a))}}function bn(e,t){return ln(t)+yn(e,t)}const vn={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included",hardLimit:"hard limit"};function kn(e,t,n,r,a){if(null==e||e<0)return null;const i={...vn,...r},s=null!=t&&t>=1?t:1,o=ln(n),c=yn(e,n);return 1===s?`${o}${c}/${i.unit}`:`${o}${c}/${s.toLocaleString(a)} ${i.units}`}function Sn(e,t,n,r,a,i,s){if(null==e||e<0)return null;const o={...vn,...i},c=null!=t&&t>=1?t:1,l=ln(r),d=yn(e,r);if(n){const e=a??(n.endsWith("s")?n:`${n}s`);return c>=2?`${l}${d}/${c.toLocaleString(s)} ${e}`:`${l}${d}/${n}`}return 1===c?`${l}${d}/${o.unit}`:`${l}${d}/${c.toLocaleString(s)} ${o.units}`}function In(e,t="unit"){const n=(e||"").trim().toLowerCase();if(!n)return t;const r=n.split(/\s+/)[0]??n;return new Set(["series","species","status","analysis","basis","bus","campus","corpus","axis"]).has(r)?r:r.endsWith("ies")&&r.length>3?r.slice(0,-3)+"y":r.endsWith("ses")||r.endsWith("xes")||r.endsWith("zes")||r.endsWith("ches")||r.endsWith("shes")?r.slice(0,-2):r.endsWith("s")&&!r.endsWith("ss")&&r.length>1?r.slice(0,-1):r||t}function Cn(e,t,n,r,a,i,s,o,c){const l={...vn,...s};if(!1===o)return null!=e?`${l.included}: ${e.toLocaleString(c)} (${l.hardLimit})`:s?.hardLimit??"Hard limit";const d=i??(n.endsWith("s")?n:`${n}s`),u=null!=a&&a>=2?`${a.toLocaleString(c)} ${d}`:n;return null!=e&&null!=t?`${l.included}: ${e.toLocaleString(c)}, ${l.afterThat} ${bn(t,r)}/${u}`:null!=e?`${l.included}: ${e.toLocaleString(c)}`:null!=t?`${l.afterIncluded}: ${bn(t,r)}/${u}`:"—"}function xn(e,t){if(null==e)return null;const n=e[t??"monthly"];return n?{included:n.included,...void 0!==n.overage&&{overage:n.overage},...void 0!==n.unitSize&&{unitSize:n.unitSize},allowOverage:!1!==e.allowOverage}:null}const Nn={included:"included",then:"then",hardLimit:"hard limit"};function An(e,t,n={}){const{overageInCents:r=!0,currency:a}=n,i={...Nn,...n.labels},s=n.currencySymbol??ln(a??"");if(null==e)return"—";const{included:o,overage:c}=e,l=`${o} ${i.included}`;if(!1===e.allowOverage)return`${l} (${i.hardLimit})`;if(null==c)return l;const d=gn(a),u=r&&d>0?c/10**d:c,p="number"==typeof u&&Number.isFinite(u)?0===d?u.toLocaleString("en-US"):u.toFixed(d):String(c),h=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${l}, ${i.then} ${s}${p}${h}`}function Pn(e,t,n={}){if(null==e)return null;const{overageInCents:r=!0,currency:a,locale:i="en"}=n,{included:s,overage:o}=e;if(!(!1!==e.allowOverage))return{included:s,hasOverage:!1,allowOverage:!1,price:"",unit:""};if(null==o)return{included:s,hasOverage:!1,allowOverage:!0,price:"",unit:""};const c=gn(a),l=r&&c>0?o/10**c:o,d=(a??"").trim().toUpperCase();let u;if(d&&"number"==typeof l&&Number.isFinite(l))try{u=new Intl.NumberFormat(i,{style:"currency",currency:d,minimumFractionDigits:c,maximumFractionDigits:c}).format(l)}catch{u=`${n.currencySymbol??ln(a??"")}${l.toFixed(c)}`}else{u=`${n.currencySymbol??ln(a??"")}${"number"==typeof l?l.toFixed(c):String(o)}`}return{included:s,hasOverage:!0,allowOverage:!0,price:u,unit:t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?`${e.unitSize.toLocaleString(i)} ${t}`:t||""}}const En={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},_n={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"},Tn={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},Un={Feature:"feature",Limit:"limit",Quota:"quota"},Rn={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},On={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},Wn={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},Fn={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"};function Ln(e,t){const n=e.pricingVariants;if(!n?.length)return null;const r=t.toLowerCase();return n.find(e=>e.currency?.toLowerCase()===r)??null}function Dn(e,t,n){const r=Ln(e,t);if(!r?.basePricing)return null;const a=r.basePricing[n];return null!=a?a:null}function $n(e,t,n){const r=Ln(e,t);if(!r?.stripePrices)return null;const a=n===En.Monthly?"monthlyPriceId":n===En.Yearly?"yearlyPriceId":"quarterlyPriceId",i=n===En.Monthly?"monthly":n===En.Yearly?"yearly":void 0;return r.stripePrices[a]??(i?r.stripePrices[i]:void 0)??null}function Mn(e,t,n,r){const a=Ln(e,t),i=a?.quotaOverages?.[n];if(i)return i[r]}function jn(e,t){const n=Ln(e,t);return n?n.currency:e.plan?.currency??""}function qn(e){const t=new Set;for(const n of e)n.pricingVariants?.forEach(e=>{e.currency&&t.add(e.currency.toLowerCase())});return Array.from(t).sort()}function Bn(e,t){for(const n of[...t,"usd"]){const t=n?.trim().toLowerCase();if(t&&e.includes(t))return t}return e[0]??""}function Vn(e,t,n,r){const a=e.quotas?.[n];if(null==a)return null;const i=a[r];if(!i)return null;const s=Mn(e,t,n,r);return{included:i.included,...void 0!==i.unitSize&&{unitSize:i.unitSize},...void 0!==s&&{overage:s},allowOverage:!1!==a.allowOverage}}function zn(e,t){if(!e)return null;for(const n of t){const t=n.pricingVariants;if(t?.length)for(const n of t){const t=n.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:n.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:n.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:n.currency}}}}return null}function Gn(e,t){const n=Ln(e,t);return n?.seatPricing?.enabled?n.seatPricing:null}function Jn(e,t,n){const r=Gn(e,t);return r?.perSeat?r.perSeat[n]??null:null}function Hn(e,t){return Math.max(0,e-(t||0))}function Yn(e,t,n,r){const a=Gn(e,t);if(!a)return null;return Hn(r,a.includedSeats)*(Jn(e,t,n)??0)}function Kn(e,t,n,r){const a=Dn(e,t,n);if(null===a)return null;if(void 0===r)return a;return a+(Yn(e,t,n,r)??0)}function Qn(e){const{planVersion:t,currency:n="usd",settingsMaxUsers:r}=e;if(t){const e=Gn(t,n);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=r&&r>0?{maxUsers:r,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}}function Zn(e){const{memberCount:t,maxUsersConfig:n,hasSubscription:r=!0,requireSubscription:a=!1}=e;if(a&&!r)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:i,source:s}=n;if(i<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(t>=i){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[s]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[s]??"users.memberLimitMessage",blockMessageValues:{maxUsers:i}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}}function Xn(e,t){return[En.Monthly,En.Quarterly,En.Yearly].filter(n=>n===En.Monthly||e.some(e=>null!=Dn(e,t,n)))}const er="saas-workspace-current",tr=e=>{e?Ie(er,e._id):Ce(er)},nr=()=>Se(er),rr=()=>{Ce(er)},ar=(e,t)=>!!e&&t.some(t=>t._id===e);function ir(e,t){if(!t)return!1;const n=(r=e.createdBy)?"string"==typeof r?r:"object"==typeof r&&"_id"in r&&"string"==typeof r._id?r._id:null:null;var r;return null!==n&&n===t}function sr(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const n=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return n&&"object"==typeof n&&"role"in n&&"string"==typeof n.role?n.role:null}const or={WORKSPACE_SETTINGS_VIEW:"workspace:settings:view",WORKSPACE_SETTINGS_EDIT:"workspace:settings:edit",WORKSPACE_DELETE:"workspace:delete",WORKSPACE_MEMBERS_VIEW:"workspace:members:view",WORKSPACE_MEMBERS_INVITE:"workspace:members:invite",WORKSPACE_MEMBERS_REMOVE:"workspace:members:remove",WORKSPACE_MEMBERS_ROLE_CHANGE:"workspace:members:role-change",WORKSPACE_FEATURES_VIEW:"workspace:features:view",WORKSPACE_FEATURES_EDIT:"workspace:features:edit",WORKSPACE_BILLING_VIEW:"workspace:billing:view",WORKSPACE_BILLING_MANAGE:"workspace:billing:manage",WORKSPACE_USAGE_VIEW:"workspace:usage:view",WORKSPACE_USAGE_RECORD:"workspace:usage:record"},cr=Object.values(or),lr={admin:cr.filter(e=>e!==or.WORKSPACE_DELETE),editor:[or.WORKSPACE_SETTINGS_VIEW,or.WORKSPACE_MEMBERS_VIEW,or.WORKSPACE_FEATURES_VIEW,or.WORKSPACE_BILLING_VIEW,or.WORKSPACE_USAGE_VIEW,or.WORKSPACE_USAGE_RECORD],viewer:[or.WORKSPACE_SETTINGS_VIEW,or.WORKSPACE_MEMBERS_VIEW]},dr="viewer";function ur(e,t){return t&&"admin"!==t&&e.includes(t)?t:e.includes(dr)?dr:e.find(e=>"admin"!==e)??""}function pr(e){const t=new Set;for(const n of Object.values(e))for(const e of n)t.add(e);return Array.from(t)}function hr(e){const{userId:t,workspace:n,settings:r,appPermissions:a}=e;if(!n||!t)return new Set;if(ir(n,t)){const e=new Set(cr);if(a)for(const t of pr(a))e.add(t);if(n.permissions)for(const t of pr(n.permissions))e.add(t);if(r?.workspace?.permissions)for(const t of pr(r.workspace.permissions))e.add(t);return e}const i=e.workspaceRole??sr(n,t);return i?mr(i,e):new Set}function mr(e,t,n={}){const{workspace:r,settings:a,appPermissions:i}=t;if(!r)return new Set;const s=r.permissions,o=a?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),l=e=>e.filter(e=>!e.startsWith("workspace:")),d=e=>!!s&&e in s,u=e=>!!o&&e in o,p=e=>d(e)||u(e)||e in lr;let h,m=e;if(!p(e)){const e=a?.workspace?.defaultRole;if(!e||"admin"===e||!p(e))return new Set;m=e}h=d(m)?c(s[m]):u(m)?c(o[m]):lr[m]??[];const g=new Set(h),f=new Set((a?.workspace?.customPermissions??[]).map(e=>e.key)),y=i?.[m]?l(i[m]).filter(e=>!f.has(e)):[];let w;w=d(m)?l(s[m]):u(m)?[...l(o[m]),...y]:i?.[m]?l(i[m]):[];for(const e of w)g.add(e);if("admin"===m){for(const e of lr.admin)g.add(e);for(const e of f)g.add(e);if(i)for(const e of l(pr(i)))g.add(e)}return!1!==n.applyRestrictions&&function(e,t,n){if(!n?.workspace)return;const{canInviteMembers:r}=n.workspace;(!1===r||"admin-only"===r&&"admin"!==t)&&e.delete(or.WORKSPACE_MEMBERS_INVITE)}(g,m,a),g}function gr(e,t){const n=hr(t);return Array.isArray(e)?e.every(e=>n.has(e)):n.has(e)}const fr="App";function yr(e,t){const n=e?.workspace?.customPermissions??[],r=new Map;for(const e of n)e?.key&&!e.key.startsWith("workspace:")&&r.set(e.key,{key:e.key,label:e.label||e.key,group:e.group||fr});for(const e of Object.values(t??{}))for(const t of e??[])t.startsWith("workspace:")||r.has(t)||r.set(t,{key:t,label:t,group:fr});return[...r.values()].sort((e,t)=>(e.group??"").localeCompare(t.group??"")||e.key.localeCompare(t.key))}const wr="\n// BuildBase Push Notification Service Worker\n// Place this file in your app's public directory (e.g. public/push-sw.js)\n\nself.addEventListener('push', function(event) {\n if (!event.data) return;\n\n let payload;\n try {\n payload = event.data.json();\n } catch (e) {\n console.error('[PushSW] Push payload is not JSON:', e);\n return;\n }\n if (!payload || typeof payload !== 'object') return;\n\n // i18n exception: service workers run outside the SDK's translation\n // provider, so this last-resort fallback stays English. The server should\n // always send a localized payload.title.\n const title = payload.title || 'Notification';\n // The tracked click URL (/api/push-track/link/...) wins over any url in\n // payload.data, so a click is always counted.\n const data = Object.assign({}, payload.data && typeof payload.data === 'object' ? payload.data : {});\n if (payload.url) data.url = payload.url;\n // A notification with the same tag replaces the earlier one instead of\n // stacking. No tag means every notification is shown on its own.\n const tag = payload.tag ? String(payload.tag) : undefined;\n const actions = Array.isArray(payload.actions)\n ? payload.actions.filter(function(a) {\n return a && typeof a.action === 'string' && typeof a.title === 'string';\n })\n : undefined;\n\n const options = {\n body: payload.body || '',\n icon: payload.icon || undefined,\n badge: payload.badge || payload.icon || undefined,\n image: payload.image || undefined,\n tag: tag,\n // The browser rejects renotify without a tag.\n renotify: tag ? !!payload.renotify : false,\n actions: actions && actions.length ? actions : undefined,\n silent: !!payload.silent,\n requireInteraction: !!payload.requireInteraction,\n timestamp: typeof payload.timestamp === 'number' ? payload.timestamp : undefined,\n dir: payload.dir === 'ltr' || payload.dir === 'rtl' ? payload.dir : 'auto',\n data: data,\n };\n\n event.waitUntil(\n Promise.resolve()\n .then(function() {\n return self.registration.showNotification(title, options);\n })\n .catch(function(e) {\n // A field this browser refuses must not cost the user the\n // notification: show it again with the basics only.\n console.error('[PushSW] Failed to show notification, retrying without rich options:', e);\n return self.registration.showNotification(title, {\n body: options.body,\n icon: options.icon,\n tag: tag,\n data: data,\n });\n })\n );\n});\n\nself.addEventListener('notificationclick', function(event) {\n event.notification.close();\n\n // A click on an action button (event.action is its id) opens the same\n // tracked URL as a click on the notification body.\n const url = event.notification.data && event.notification.data.url;\n if (url) {\n event.waitUntil(\n clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function(clientList) {\n for (let i = 0; i < clientList.length; i++) {\n const client = clientList[i];\n if (client.url === url && 'focus' in client) {\n return client.focus();\n }\n }\n if (clients.openWindow) {\n return clients.openWindow(url);\n }\n })\n );\n }\n});\n";var br;function vr(e){return{isAuthenticated:e===br.authenticated,isLoading:e===br.loading||e===br.redirecting||e===br.authenticating,isRedirecting:e===br.redirecting}}!function(e){e.loading="loading",e.redirecting="redirecting",e.authenticated="authenticated",e.unauthenticated="unauthenticated",e.authenticating="authenticating"}(br||(br={}));const kr="reverified",Sr="bb-reverified-at";function Ir(e){return e instanceof Error&&"reauth_required"===e.code}function Cr(e){return e instanceof Error&&"read_only_session"===e.code}function xr(e){return e instanceof Error&&"impersonation_sign_in_locked"===e.code}function Nr(e){let t;try{t=new URL(e)}catch{return null}return t.searchParams.has(kr)?(t.searchParams.delete(kr),t.toString()):null}async function Ar(e,t={}){const n=t.factors?.length?t.factors:void 0;if("number"==typeof t.maxAgeSeconds&&function(e,t,n=[],r=Date.now()){const a=e?.authTime?Date.parse(e.authTime):NaN;return!(!Number.isFinite(a)||a>r+6e4)&&!(r-a>=1e3*t)&&n.every(t=>e?.amr?.includes(t))}(e.session,t.maxAgeSeconds,n,e.now))return"recent";const r=t.returnUrl??Nr(e.currentHref)??e.currentHref;let a;try{a=await e.start({returnUrl:r,...n?{factors:n}:{}})}catch(t){const i=e.redirectUrl;if(!("invalid_return_url"===t?.code&&!!i&&i!==r))throw t;e.saveIntent(r);try{a=await e.start({returnUrl:i,...n?{factors:n}:{}})}catch(t){throw e.clearIntent(),t}}if(!Zt(a.url))throw e.clearIntent(),new Error("Failed to start confirming it is you: the server sent an unsafe URL");return e.redirect(a.url),"redirecting"}function Pr(e=Date.now()){try{const t=sessionStorage.getItem(Sr);if(null===t)return!1;sessionStorage.removeItem(Sr);const n=Number(t);return Number.isFinite(n)&&e-n>=0&&e-n<6e5}catch{return!1}}const Er=/^[a-z0-9](?:[a-z0-9_.-]{1,28})[a-z0-9]$/,_r=new Set(["admin","administrator","root","support","help","system","api","null","undefined","owner","staff","security","billing","moderator","buildbase"]);function Tr(e){if("string"!=typeof e)return null;const t=e.trim().toLowerCase();return Er.test(t)?t.includes("..")||_r.has(t)?null:t:null}function Ur(e){return null!==Tr(e)}const Rr=new Uint32Array([1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648]),Or=[0,1,62,28,27,36,44,6,55,20,3,10,43,25,39,41,45,15,21,8,18,2,61,56,14],Wr=136;function Fr(e,t,n){if(0===n)return[e,t];if(32===n)return[t,e];if(n<32)return[(e<<n|t>>>32-n)>>>0,(t<<n|e>>>32-n)>>>0];const r=n-32;return[(t<<r|e>>>32-r)>>>0,(e<<r|t>>>32-r)>>>0]}function Lr(e){const t=new Uint32Array(10),n=new Uint32Array(50);for(let r=0;r<24;r++){for(let n=0;n<5;n++){let r=0,a=0;for(let t=0;t<5;t++)r^=e[2*(n+5*t)],a^=e[2*(n+5*t)+1];t[2*n]=r,t[2*n+1]=a}for(let n=0;n<5;n++){const r=(n+4)%5,a=(n+1)%5,[i,s]=Fr(t[2*a],t[2*a+1],1),o=t[2*r]^i,c=t[2*r+1]^s;for(let t=0;t<5;t++)e[2*(n+5*t)]^=o,e[2*(n+5*t)+1]^=c}for(let t=0;t<5;t++)for(let r=0;r<5;r++){const a=t+5*r,i=r+(2*t+3*r)%5*5,[s,o]=Fr(e[2*a],e[2*a+1],Or[a]);n[2*i]=s,n[2*i+1]=o}for(let t=0;t<5;t++){const r=(t+1)%5,a=(t+2)%5;for(let i=0;i<5;i++){const s=t+5*i,o=r+5*i,c=a+5*i;e[2*s]=n[2*s]^~n[2*o]&n[2*c],e[2*s+1]=n[2*s+1]^~n[2*o+1]&n[2*c+1]}}e[0]^=Rr[2*r],e[1]^=Rr[2*r+1]}}function Dr(e,t){for(let n=0;n<34;n++)e[n]^=t[4*n]|t[4*n+1]<<8|t[4*n+2]<<16|t[4*n+3]<<24}const $r="0123456789abcdef";function Mr(e){let t="";for(const n of e)t+=$r[n>>4]+$r[15&n];return t}function jr(e){if("string"!=typeof(t=e)||!/^0x[0-9a-fA-F]{40}$/.test(t))return null;var t;const n=e.slice(2).toLowerCase(),r=Mr(function(e){const t=new Uint32Array(50);let n=0;for(;n+Wr<=e.length;n+=Wr)Dr(t,e.subarray(n,n+Wr)),Lr(t);const r=new Uint8Array(Wr);r.set(e.subarray(n)),r[e.length-n]^=1,r[135]^=128,Dr(t,r),Lr(t);const a=new Uint8Array(32);for(let e=0;e<8;e++){const n=t[e];a[4*e]=255&n,a[4*e+1]=n>>>8&255,a[4*e+2]=n>>>16&255,a[4*e+3]=n>>>24&255}return a}((new TextEncoder).encode(n)));let a="0x";for(let e=0;e<40;e++)a+=parseInt(r[e],16)>=8?n[e].toUpperCase():n[e];return a}const qr="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function Br(e){let t=0;for(;t<e.length&&0===e[t];)t++;const n=[];for(const t of e){let e=t;for(let t=n.length-1;t>=0;t--)e+=256*n[t],n[t]=e%58,e=Math.floor(e/58);for(;e>0;)n.unshift(e%58),e=Math.floor(e/58)}return"1".repeat(t)+n.map(e=>qr[e]).join("")}function Vr(e){return!("string"!=typeof e||e.length>64)&&32===function(e){if(!e)return null;let t=0;for(;t<e.length&&"1"===e[t];)t++;const n=[];for(const t of e){const e=qr.indexOf(t);if(e<0)return null;let r=e;for(let e=n.length-1;e>=0;e--)r+=58*n[e],n[e]=255&r,r>>=8;for(;r>0;)n.unshift(255&r),r>>=8}return Uint8Array.from([...new Array(t).fill(0),...n])}(e)?.length}const zr="Connect this wallet to your account.";function Gr(e){const t=e.statement??zr;if([e.domain,e.address,t,e.uri,String(e.chainId),e.nonce,e.issuedAt].some(e=>!e||/[\r\n]/.test(e)))throw new Error("A wallet message field is empty or spans lines");const n="ethereum"===e.chain?"Ethereum":"Solana";return[`${e.domain} wants you to sign in with your ${n} account:`,e.address,"",t,"",`URI: ${e.uri}`,"Version: 1",`Chain ID: ${e.chainId}`,`Nonce: ${e.nonce}`,`Issued At: ${e.issuedAt}`].join("\n")}class Jr extends Error{constructor(e,t){super(t),this.name="WalletFlowError",this.code=e}}function Hr(e,t){if(e instanceof Jr)return e;const n=e?.code,r=e instanceof Error&&e.message?e.message:"The wallet did not answer";return new Jr(4001===n?"rejected":-32002===n?"wallet_busy":t,r)}function Yr(e){return"number"==typeof e&&Number.isInteger(e)?e:"string"==typeof e&&/^0x[0-9a-fA-F]+$/.test(e)?parseInt(e,16):"string"==typeof e&&/^\d+$/.test(e)?Number(e):null}async function Kr(e){const t=void 0===e.ethereum?function(){if("undefined"==typeof window)return null;const e=window.ethereum;return e&&"function"==typeof e.request?e:null}():e.ethereum;if(!t)throw new Jr("no_wallet","No Ethereum wallet in this browser");let n;try{const e=await t.request({method:"eth_requestAccounts"});n=jr(Array.isArray(e)?e[0]:void 0)}catch(e){throw Hr(e,"wallet_failed")}if(!n)throw new Jr("no_account","The wallet gave no address");const r=await e.api.requestWalletNonce("ethereum"),a=r.chainIds?.length?r.chainIds:e.ethereumChainIds??[];let i;try{if(i=Yr(await t.request({method:"eth_chainId"})),null===i||!a.includes(i)){if(!a.length)throw new Jr("wrong_network","The app takes no Ethereum network");await t.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${a[0].toString(16)}`}]}),i=Yr(await t.request({method:"eth_chainId"}))}}catch(e){throw Hr(e,"wrong_network")}if(null===i||!a.includes(i))throw new Jr("wrong_network","The wallet is on a network the app does not take");const s=Gr({chain:"ethereum",domain:r.domain,address:n,statement:e.statement,uri:r.uri,chainId:i,nonce:r.nonce,issuedAt:r.issuedAt});let o;try{o=await t.request({method:"personal_sign",params:[(c=s,`0x${Mr((new TextEncoder).encode(c))}`),n]})}catch(e){throw Hr(e,"wallet_failed")}var c;if("string"!=typeof o||!/^0x[0-9a-fA-F]+$/.test(o))throw new Jr("wallet_failed","The wallet sent no signature");return e.api.linkWallet({chain:"ethereum",message:s,signature:o})}async function Qr(e){const t=void 0===e.solana?function(){if("undefined"==typeof window)return null;const e=window,t=e.phantom?.solana??e.solana;return t&&"function"==typeof t.connect&&"function"==typeof t.signMessage?t:null}():e.solana;if(!t)throw new Jr("no_wallet","No Solana wallet in this browser");let n;try{const e=await t.connect();n=(e&&e.publicKey?e.publicKey:t.publicKey)?.toString()}catch(e){throw Hr(e,"wallet_failed")}if(!Vr(n))throw new Jr("no_account","The wallet gave no address");const r=await e.api.requestWalletNonce("solana"),a=Gr({chain:"solana",domain:r.domain,address:n,statement:e.statement,uri:r.uri,chainId:"mainnet",nonce:r.nonce,issuedAt:r.issuedAt});let i;try{i=await t.signMessage((new TextEncoder).encode(a),"utf8")}catch(e){throw Hr(e,"wallet_failed")}const s=i instanceof Uint8Array?i:i?.signature;if(!(s instanceof Uint8Array)||64!==s.length)throw new Jr("wallet_failed","The wallet sent no signature");return e.api.linkWallet({chain:"solana",message:a,signature:Br(s)})}function Zr(e,t){return"ethereum"===e?Kr(t):Qr(t)}const Xr=["ethereum","solana"];function ea(e){return Xr.includes(e)}function ta(e){if(!e)return 0;const t=new Date(e).getTime();return Number.isNaN(t)?0:t}function na(e){const t=e=>"invited"===e.status?0:1;return[...e].sort((e,n)=>t(e)-t(n)||ta(n.invitedAt)-ta(e.invitedAt))}function ra(e,t=new Date){return"invited"===e.status&&(null===e.validTill||void 0===e.validTill||ta(e.validTill)>t.getTime())}function aa(e,t=new Date){return na(e.filter(e=>ra(e,t)))}function ia(e,t=new Date){return"expired"===e.status||"invited"===e.status&&!ra(e,t)}function sa(e){return"object"==typeof e.workspace&&e.workspace&&e.workspace.name||""}function oa(e){return"object"==typeof e.workspace&&e.workspace?e.workspace._id:e.workspace}function ca(e){const t=e.invitedBy;return t&&"string"!=typeof t&&(t.name||t.email)||null}function la(e,t=new Date){const n=ta(e.resendAvailableAt);return n?Math.max(0,Math.ceil((n-t.getTime())/1e3)):0}function da(e){return e.canView}const ua="saas-pending-invite",pa=/^[0-9a-f]{64}$/;function ha(e){return"object"==typeof e&&null!==e&&"string"==typeof e.token&&"string"==typeof e.orgId&&"number"==typeof e.createdAt}function ma(e,t){pa.test(e)&&t&&Ne(ua,{token:e,orgId:t,createdAt:Date.now()})}function ga(e,t=Date.now()){const n=xe(ua,ha);return n?t-n.createdAt>864e5?(Ce(ua),null):n.orgId!==e?null:pa.test(n.token)?n.token:(Ce(ua),null):null}function fa(){Ce(ua)}class ya extends i{constructor(e){super(e),this.resetError=()=>{this.setState({hasError:!1,error:null})},this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){if(be(e,{component:"ErrorBoundary",action:"componentDidCatch",metadata:{componentStack:t.componentStack,errorBoundary:this.constructor.name}}),this.props.onError)try{this.props.onError(e,t)}catch(e){pe("[SDK ErrorBoundary] Error in onError callback:",e)}}componentDidUpdate(e){this.state.hasError&&!1!==this.props.resetOnPropsChange&&e.children!==this.props.children&&this.resetError()}render(){return this.state.hasError&&this.state.error?this.props.fallback?"function"==typeof this.props.fallback?this.props.fallback(this.state.error,this.resetError):this.props.fallback:e("div",{className:"saas-os-ui",style:{padding:"1rem",border:"1px solid hsl(var(--destructive, 0 72% 45%))",borderRadius:"0.5rem",backgroundColor:"hsl(var(--destructive, 0 72% 45%) / 0.08)",color:"hsl(var(--destructive-text, 0 72% 36%))"},children:[t("h3",{style:{margin:"0 0 0.5rem 0",fontSize:"1rem",fontWeight:600},children:this.props.errorTitle??"Something went wrong"}),t("p",{style:{margin:"0 0 1rem 0",fontSize:"0.875rem"},children:this.state.error.message||"An unexpected error occurred"}),t("button",{onClick:this.resetError,style:{padding:"0.5rem 1rem",backgroundColor:"hsl(var(--destructive, 0 72% 45%))",color:"hsl(var(--destructive-foreground, 210 40% 98%))",border:"none",borderRadius:"0.25rem",cursor:"pointer",fontSize:"0.875rem"},children:this.props.retryLabel??"Try again"})]}):this.props.children}}const wa={authenticationStarted:()=>({type:"AUTHENTICATION_STARTED"}),authenticationProcessing:()=>({type:"AUTHENTICATION_PROCESSING"}),authenticationFailed:()=>({type:"AUTHENTICATION_FAILED"}),setSession:e=>({type:"SET_SESSION",payload:e}),removeSession:()=>({type:"REMOVE_SESSION"})};function ba(e,t,n,r){const a=s(()=>{const t=n??(e=>e);let a,i,s=!1;return()=>{const n=e();if(!s)return s=!0,a=n,i=t(n),i;if(Object.is(a,n))return i;const o=t(n);a=n;return(r?r(i,o):Object.is(i,o))||(i=o),i}},[e,n,r]);return o(t,a,a)}function va({name:e,initialState:n,reducer:r,initializer:i}){const o=c(null);o.displayName=`${e}StoreContext`;const d=a.memo(({children:e})=>{const a=l(null);return null===a.current&&(a.current=function(e,t,n){let r=n?n(e):e;const a=new Set;return{getState:()=>r,dispatch:e=>{const n=t(r,e);Object.is(n,r)||(r=n,a.forEach(e=>e()))},subscribe:e=>(a.add(e),()=>{a.delete(e)})}}(n,r,i)),t(o.Provider,{value:a.current,children:e})});d.displayName=`${e}Provider`;const u=(t="Store")=>{const n=a.useContext(o);if(!n)throw(t=>new Error(`use${e}${t} must be used within a ${e}Provider. Make sure SaaSOSProvider is wrapping your application.`))(t);return n};return{Provider:d,useContext:()=>{const e=u("Context"),t=ba(e.getState,e.subscribe);return s(()=>({state:t,dispatch:e.dispatch}),[t,e])},useState:()=>{const e=u("State");return ba(e.getState,e.subscribe)},useDispatch:()=>u("Dispatch").dispatch,useSelector:(e,t)=>{const n=u("Selector");return ba(n.getState,n.subscribe,e,t)},useStore:u}}function ka(e,t,n){return{...e,[t]:n}}function Sa(e,t){return{...e,...t}}const{Provider:Ia,useDispatch:Ca,useSelector:xa,useStore:Na}=va({name:"Auth",initialState:{session:null,status:br.loading},reducer:(e,t)=>{switch(t.type){case"AUTHENTICATION_STARTED":return ka(e,"status",br.redirecting);case"AUTHENTICATION_PROCESSING":return ka(e,"status",br.authenticating);case"AUTHENTICATION_FAILED":case"REMOVE_SESSION":return Sa(e,{session:null,status:br.unauthenticated});case"SET_SESSION":return Sa(e,{session:t.payload,status:br.authenticated});default:return e}}}),Aa=Ia,Pa=Ca,Ea=xa,_a=Na,Ta=e=>({type:"SET_SAAS_OS_CONFIG",payload:e}),Ua=e=>({type:"SET_SETTINGS",payload:e}),Ra=(e,t)=>({type:"SET_SETTINGS_STATUS",payload:{status:e,error:t}}),Oa=()=>({serverUrl:"",version:Ct.V1,orgId:"",settings:null,settingsStatus:"idle",settingsError:null}),{Provider:Wa,useDispatch:Fa,useStore:La}=va({name:"OS",initialState:Oa(),reducer:(e,t)=>{switch(t.type){case"SET_SAAS_OS_CONFIG":return Sa(e,t.payload);case"REMOVE_SAAS_OS_CONFIG":return Oa();case"SET_SETTINGS":return Sa(e,{settings:t.payload,settingsStatus:"loaded",settingsError:null});case"SET_SETTINGS_STATUS":return Sa(e,{settingsStatus:t.payload.status,settingsError:t.payload.error??null});default:return e}}}),Da=Wa,$a=Fa,Ma=La,ja=e=>({type:"SET_WORKSPACES",payload:e}),qa=e=>({type:"ADD_WORKSPACE",payload:e}),Ba=e=>({type:"UPDATE_WORKSPACE",payload:e}),Va=e=>({type:"REMOVE_WORKSPACE",payload:e}),za=e=>({type:"SET_ALL_FEATURES",payload:e}),Ga=e=>({type:"SET_CURRENT_WORKSPACE",payload:e}),Ja=()=>({type:"RESET_CURRENT_WORKSPACE"}),Ha=e=>({type:"SET_IS_INITIALIZED",payload:e}),Ya=e=>({type:"SET_LOADING",payload:e}),Ka=e=>({type:"SET_ERROR",payload:e}),Qa=e=>({type:"SET_REFRESHING",payload:e}),Za=e=>({type:"SET_SWITCHING_TO_ID",payload:e}),{Provider:Xa,useDispatch:ei,useStore:ti}=va({name:"Workspace",initialState:{workspaces:[],loading:!1,error:null,currentWorkspace:null,refreshing:!1,switchingToId:null,isInitialized:!1,allFeatures:[]},reducer:(e,t)=>{switch(t.type){case"SET_WORKSPACES":return ka(e,"workspaces",t.payload);case"ADD_WORKSPACE":return ka(e,"workspaces",[...e.workspaces,t.payload]);case"UPDATE_WORKSPACE":return ka(e,"workspaces",e.workspaces.map(e=>e._id===t.payload._id?t.payload:e));case"REMOVE_WORKSPACE":return ka(e,"workspaces",e.workspaces.filter(e=>e._id!==t.payload));case"SET_ALL_FEATURES":return ka(e,"allFeatures",t.payload);case"SET_CURRENT_WORKSPACE":return ka(e,"currentWorkspace",t.payload);case"RESET_CURRENT_WORKSPACE":return ka(e,"currentWorkspace",null);case"SET_IS_INITIALIZED":return ka(e,"isInitialized",t.payload);case"SET_LOADING":return ka(e,"loading",t.payload);case"SET_ERROR":return ka(e,"error",t.payload);case"SET_REFRESHING":return ka(e,"refreshing",t.payload);case"SET_SWITCHING_TO_ID":return ka(e,"switchingToId",t.payload);default:return e}}}),ni=Xa,ri=ei,ai=ti,ii=a.memo(({children:e})=>t(Da,{children:t(Aa,{children:t(ni,{children:e})})}));ii.displayName="SDKContextProvider";const si=c({});si.displayName="CheckoutConfigContext";const oi=a.memo(({getCheckoutStripeParams:e,children:n})=>{const r=a.useMemo(()=>({getCheckoutStripeParams:e}),[e]);return t(si.Provider,{value:r,children:n})});oi.displayName="CheckoutConfigProvider";const ci={settings:{titles:{profile:"Account",security:"Security",devices:"Devices & sessions",general:"Workspace Settings",users:"Workspace Members",subscription:"Plan & Billing",usage:"Usage",credits:"Credits",features:"Workspace Features",notifications:"Notifications",permissions:"Permissions",danger:"Danger Zone"},sidebar:{account:"Account",workspace:"Workspace",profile:"Account",security:"Security",devices:"Devices",general:"Settings",users:"Members",subscription:"Plan & Billing",usage:"Usage",credits:"Credits",features:"Features",notifications:"Notifications",permissions:"Permissions",danger:"Danger Zone"},common:{refresh:"Refresh",refreshing:"Refreshing...",retry:"Retry",retrying:"Retrying...",save:"Save",saving:"Saving...",cancel:"Cancel",delete:"Delete",dismiss:"Dismiss",loading:"Loading...",success:"Done",error:"Something went wrong",refreshAction:"{loading, select, true {Refreshing...} other {Refresh}}",retryAction:"{loading, select, true {Retrying...} other {Retry}}",noPermissionTitle:"Access Restricted",noPermissionDescription:"You don't have permission to access this section. Contact a workspace admin if you need access.",billingManageOnly:"Only users with billing management permissions can perform this action.",openSettings:"Open settings",back:"Back",close:"Close"}},subscription:{managePlan:"Manage your plan and billing",changePlan:"Change Plan",viewPricingPlans:"View Pricing Plans",viewPlans:"View Plans",upgradePlan:"Upgrade Now",subscribe:"Subscribe",startFree:"Start free",currentPlan:"Current Plan",noSubscription:"You don't have an active subscription",choosePlan:"Choose Your Plan",choosePlanDescription:"Compare plans and select the one that fits your needs",forWorkspace:"for {name}",planUpdateAvailable:"Plan update available",updateSuccess:"Subscription updated successfully!",updateSuccessTrial:"Plan changed. Your trial continues on the new plan until {date}.",paymentRequiredTitle:"Complete payment to finish the upgrade",paymentRequiredMessage:"Your new plan starts once this payment goes through. Until then you stay on your current plan, and the change is dropped if it is not paid in time.",completePayment:"Complete payment",updateFailed:"Update failed",cancelTitle:"Cancel Subscription",cancelConfirm:"Are you sure you want to cancel your subscription?",cancelKeep:"Keep Subscription",cancelButton:"Yes, Cancel Subscription",canceling:"Canceling...",cancelSuccess:"Subscription will be canceled at the end of the billing period.",cancelNotCharged:"You won't be charged again after cancellation",cancelResumeAnytime:"You can resume your subscription anytime before it ends",cancelTrialTitle:"Cancel Trial",cancelTrialConfirm:"Are you sure you want to cancel your trial?",cancelTrialAccess:"Your trial will continue until",cancelTrialNoCharge:"You won't be charged, and your trial will simply expire",cancelTrialResume:"You can resume your trial anytime before it ends",cancelTrialKeep:"Keep Trial",cancelTrialButton:"Yes, Cancel Trial",resumeTitle:"Resume Subscription",resumeTrial:"Resume Trial",resumeConfirm:"Are you sure you want to resume your subscription?",resumeKeep:"Keep Canceled",resumeButton:"Yes, Resume Subscription",resuming:"Resuming...",resumeSuccess:"Subscription has been resumed.",managePayment:"Manage Payment",openingPortal:"Opening...",viewAllPlans:"View All Plans",scheduledCancellation:"Subscription scheduled for cancellation",scheduledTrialCancellation:"Trial scheduled for cancellation",paymentPastDue:"Payment past due",paymentPastDueDescription:"Please update your payment method to avoid service interruption.",subscriptionPaused:"Subscription paused",subscriptionPausedDescription:"Your subscription is currently paused. Resume to restore full access.",errorLoading:"Error loading subscription data",errorLoadingDescription:"Please check your connection and try again.",errorProcessing:"Failed to process subscription",errorCanceling:"Failed to cancel subscription",errorResuming:"Failed to resume subscription",invalidWorkspace:"Invalid workspace ID",billingInterval:{monthly:"Monthly",quarterly:"Quarterly",yearly:"Yearly",perMonth:"/month",perQuarter:"/quarter",perYear:"/year"},seats:{title:"Seats",members:"Members",included:"Included",billable:"Billable",perExtraSeat:"Per extra seat",limit:"Limit",includedSeats:"Included seats",maxSeats:"Max seats",freeWithBase:"Free with base price",allIncluded:"All included",extra:"extra",unlimited:"Unlimited"},items:{unlimited:"Unlimited",features:"Features",limits:"Limits",quotas:"Usage Quotas",credits:"AI Credits",creditsPerMonth:"Credits per month",creditsOneTime:"Credits (given once)",creditRenewal:"Credit renewal",creditModeReset:"Fresh every month",creditModeTopup:"Adds up every month",creditModeLifetime:"Given once",creditsPerPeriod:"Credits per month",creditRollover:"Credit renewal"},checkout:{upgrade:"Upgrade",downgrade:"Downgrade",switchTo:"Switch to",select:"Select"},status:{active:"Active",canceling:"Canceling",trial:"Trial",canceled:"Canceled",pastDue:"Past Due",paused:"Paused",deprecated:"Deprecated",unknown:"Unknown"},plan:"Plan",invoicesTab:"Invoices",tabsLabel:"Subscription tabs",endsOn:"(ends {date})",versionLabel:"Version {version}",changePlanButton:"Change Plan",noPlanAssigned:"No plan assigned",free:"Free",perSeatDisplay:"+ {price}/seat{interval}",estTotalDisplay:"Est. total: {total}{interval} ({count, plural, one {# extra seat} other {# extra seats}})",nextBillingDisplay:"Next billing: {date}",membersInWorkspace:"{count, plural, one {# member} other {# members}} in workspace",billingInCurrency:"Billing in {currency}",savingsPercent:"Save {percent, number}%",switchToInterval:"Switch to {interval}",seatPriceDisplay:"+ {price}/seat{interval} ({included} {includedLabel})",trialEnded:"Your trial has ended.",trialEndsIn:"Your trial ends in {days, plural, one {# day} other {# days}}.",onTrial:"You are on a trial.",upgradeToKeepAccess:"Upgrade to keep access.",trialKeepAccess:"Your access continues after the trial once a payment method is on file.",viewInvoices:"View Invoices",cancelTrial:"Cancel Trial",dunningFinal:"Final warning: Subscription will be suspended",dunningSuspended:"Subscription suspended",dunningRecovery:"Payment recovery in progress",dunningSuspendedDescription:"Your subscription has been suspended due to repeated payment failures. Update your payment method to restore access.",dunningRecoveryDescription:"We were unable to process your payment. Please update your payment method to avoid losing access.",cancelEndDescription:"Your subscription will end on",trialEndDescription:"Your trial will end on",cancelEndFallback:"Your subscription will be canceled at the end of the current billing period. You won't be charged again.",resumeChargeDate:"You will be charged again on",resumeChargeFallback:"the next billing date",resumeContinue:"Your subscription will continue automatically and you'll be billed according to your plan",resumeCancelAnytime:"You can cancel anytime before the next billing date if you change your mind",retainAccess:"You'll retain full access to this plan until",retainAccessFallback:"the end of your current billing period",noPlansAvailable:"No plan groups are available for this workspace. Please contact support if you believe this is an error.",noPlansAvailableHint:"No plan groups are available for this workspace.",startTrialDescription:"Try the full plan with no commitment. You can upgrade or cancel anytime.",noSubscriptionDescription:"Choose a plan to get started with your workspace",startFreeTrial:"Start Free Trial",startTrialDays:"Start {days}-day Free Trial",trialBadge:"{days}-day trial"},users:{emailPlaceholder:"example@example.com",title:"Workspace Members",adminOnly:"Only workspace admin can manage users and roles.",inviteByEmail:"Invite member by email",inviteButton:"Invite",inviting:"Inviting...",inviteSuccess:"User invited successfully",emailRequired:"Email is required",invalidEmail:"Invalid email address format",inviteFailed:"Failed to invite member",seatLimitReached:"Seat limit reached",memberLimitReached:"Member limit reached",role:"Role",you:"You",owner:"Owner",noMembers:"No members found in this workspace.",extraSeatCost:"Each additional member adds {price}/{interval, select, yearly {yr} quarterly {qtr} other {mo}} to your subscription",unknownUser:"Unknown User",seats:"Seats",members:"Members",included:"included",perExtraSeat:"/extra seat",maxMembers:"max members",available:"available",noMemberLimit:"No member limit",seatHeading:"{hasSeatPricing, select, true {Seats} other {Members}}",limitReached:"{reason, select, seat_limit_reached {Seat limit reached} other {Member limit reached}}",memberCount:"{count, plural, one {# member} other {# members}}",subscriptionRequired:"A subscription is required to invite members.",seatLimitMessage:"Your plan allows up to {maxUsers, number} members. Upgrade for more seats.",settingsLimitMessage:"This workspace allows up to {maxUsers, number} members.",memberLimitMessage:"Member limit of {maxUsers, number} reached.",selectRole:"Select a role",inviteAs:"Invite as {role}",invitations:{title:"Pending invitations",pendingCount:"{count, plural, =0 {none pending} one {# pending} other {# pending}}",sent:"Invitation sent to {email}",resend:"Resend",resendIn:"Resend in {minutes, plural, one {# minute} other {# minutes}}",revoke:"Revoke",revokeTitle:"Revoke invitation?",revokeConfirm:"Withdraw the invitation to {email}? They will be told it is no longer valid.",sentAt:"Sent {date}",expiresAt:"Expires {date}",seatNote:"{count, plural, one {# pending invitation is billed as a seat} other {# pending invitations are billed as seats}} until accepted, declined, revoked or expired.",formerMember:"a former member",loadFailed:"Could not load invitations",resendFailed:"Could not resend the invitation",revokeFailed:"Could not revoke the invitation",status:{invited:"Pending",accepted:"Accepted",rejected:"Declined",expired:"Expired"}}},invitations:{title:"You have been invited",description:"{inviter} invited you to join {workspace} as {role}.",listDescription:"Workspaces waiting for your answer.",titleJoined:"Welcome to {workspace}",titleUnavailable:"Invitation unavailable",sentTo:"Sent to {email}",invitedAs:"{inviter} invited you as {role}",accept:"Accept",decline:"Decline",accepted:"You joined {workspace}.",declined:"Invitation declined.",expired:"This invitation has expired. Ask {inviter} to send a new one.",revoked:"This invitation is no longer valid.",alreadyAccepted:"You already accepted this invitation.",wrongAccount:"This invitation was sent to {email}. Sign out and sign in with that address.",verifyFirst:"Verify your email address to accept this invitation.",workspaceFull:"This workspace has reached its member limit. Ask an admin to make room.",disabled:"This workspace no longer accepts invitations.",empty:"No invitations waiting for you",signInToAccept:"Sign in to accept",dismiss:"Close",signOut:"Sign out",loadFailed:"Could not load the invitation",acceptFailed:"Could not accept the invitation",declineFailed:"Could not decline the invitation"},invoices:{title:"Billing History",description:"View and download your invoices",pay:"Pay",view:"View",viewDetails:"View Details",download:"PDF",errorLoading:"Error loading invoices",noInvoices:"No invoices yet. Subscribe to a plan to receive invoices.",noInvoicesWithSub:"No invoices with download option found",paidAmount:"Paid: {amount}",na:"N/A",status:{draft:"Draft",open:"Open",paid:"Paid",uncollectible:"Uncollectible",void:"Void"}},usage:{title:"Usage",description:"Monitor your resource consumption and quotas",totalResources:"Total Resources",overallUsage:"Overall Usage",inOverage:"In Overage",estOverageCost:"Est. Overage Cost",overageDetected:"Overage Detected",overageDescription:"Additional usage will be billed as overage on your next invoice.",overageUnits:"Overage units",rate:"Rate",billableBlocks:"Billable blocks",estimatedCharge:"Estimated charge",noData:"No quota usage data available for this workspace.",noDataHint:"Quotas will appear here once your plan includes metered resources.",used:"used",remaining:"remaining",overLimit:"over limit",percentUsed:"{percent, number}% used",availableRemaining:"{count} remaining",overLimitCount:"{count} over limit",overageWarning:"{count, plural, one {# resource has exceeded the included quota.} other {# resources have exceeded the included quota.}} Additional usage will be billed as overage on your next invoice.",fullyUsed:"Fully used",renewingSoon:"renewing soon",almostFull:"Almost full",overage:"Overage",errorLoading:"Failed to load usage data",perUnit:"/ unit",perUnits:"/ units",rateDisplay:"{rate} {unitSize, plural, =1 {/ unit} other {/ {unitSize, number} units}}",resourcesExceeded:"{count, plural, one {# resource has exceeded the included quota.} other {# resources have exceeded the included quota.}}",estOverageCharges:"Estimated overage charges this period: {amount}",overageRateDisplay:"Overage rate: {rate}",resetDateDisplay:"Usage resets on {date}",daysRemainingDisplay:"{count, plural, one {# day remaining} other {# days remaining}}"},profile:{email:"Email",name:"Name",language:"Language",country:"Country",currency:"Currency",timezone:"Timezone",profileImage:"Profile Image",changePicture:"Upload picture",removePicture:"Remove picture",success:"Profile saved successfully",nameMinLength:"Name must be at least 2 characters.",save:"Save",reset:"Reset",changeEmail:"Change",changeEmailNewLabel:"New email address",changeEmailNewHint:"We'll email a code to the new address. Your email changes only once you enter it.",changeEmailInvalid:"Enter a valid email address.",changeEmailSame:"That is already your email address.",changeEmailSend:"Send code",changeEmailSentTo:"We sent a code to {email}.",changeEmailCodeLabel:"6-digit code from the email",changeEmailCodeInvalid:"Enter the 6-digit code from the email.",changeEmailConfirm:"Change email",changeEmailResend:"Resend code",changeEmailResendIn:"Resend in {seconds, plural, one {# second} other {# seconds}}",changeEmailResent:"We sent a new code to {email}.",changeEmailChanged:"Your email is now {email}. We let your old address know.",changeEmailBlockedSocial:"You sign in with Google or another provider, which finds your account by this address, so it cannot be changed here. Changing it would leave you with a second account.",username:"Username",usernameHint:"You can sign in with it instead of your email address.",usernameInvalid:"Use 3 to 30 characters: letters a to z, digits, dots, dashes or underscores. Start and end with a letter or digit.",usernameSave:"Save username",usernameRemove:"Remove",usernameSaved:"Your username is now {username}.",usernameRemoved:"Your username was removed.",usernameRequiredNote:"This app requires a username, so you can change it but not remove it.",loadFailed:"Your profile couldn't be loaded. Please try again."},general:{ownerOnly:"Only the workspace owner can change the workspace settings.",name:"Name",namePlaceholder:"My Awesome Workspace",nameMinLength:"Workspace name must be at least 2 characters.",billingCurrency:"Billing currency",icon:"Icon",iconDescription:"Choose an emoji or upload a custom image for your workspace.",imageUrl:"Image URL",imageUrlPlaceholder:"https://example.com/image.png",imageUrlDescription:"Enter a valid URL for your workspace image. Supports PNG, JPG, and SVG formats.",previewLabel:"Preview:",previewImageAlt:"Workspace preview",success:"Workspace settings saved successfully",chooseEmoji:"Choose Emoji",customImageUrl:"Custom Image URL",uploadImage:"Upload Image",chooseImage:"Choose an image",updateWorkspace:"Update Workspace"},uploads:{description:"PNG, JPG, GIF, WebP or SVG, up to {max}.",uploading:"Uploading...",errorTooLarge:"This image is too large. Choose one up to {max}.",errorInvalid:"This file type is not supported. Use PNG, JPG, GIF, WebP or SVG.",errorDisabled:"Image uploads are turned off for this app.",errorUserLimit:"You have reached your upload limit for this app.",errorUnavailable:"Uploads are not available right now. Try again later.",errorFailed:"The image could not be uploaded. Check your connection and try again."},features:{title:"Workspace Features",ownerOnly:"Only the workspace owner can change the features.",noFeatures:"Workspace has no features to manage.",enabled:"enabled",disabled:"disabled",enabling:"Enabling",disabling:"Disabling",featureSuccess:"successfully",updateSuccess:"{feature} {enabled, select, true {enabled} other {disabled}} successfully",actionStatus:"{action, select, enabling {Enabling} disabling {Disabling} other {}}",fallbackName:"Feature"},danger:{title:"Delete Workspace",adminOnly:"Only workspace admins can delete workspaces.",deleteWorkspace:"Delete Workspace",deleteConfirm:"Are you absolutely sure?",deleteWarning:"This action cannot be undone. This will permanently delete the workspace and all associated data.",deleting:"Deleting...",deleteDescription:"Once you delete a workspace, there is no going back. This will permanently delete the workspace and all of its data, including members, settings, and features.",deleteConfirmDescription:"This action cannot be undone. This will permanently delete the workspace and all of its data.",failedToDelete:"Failed to delete workspace"},notifications:{inbox:{title:"Notifications",description:"Everything this app has sent you.",bellLabel:"Notifications",bellUnread:"{count, plural, one {# unread notification} other {# unread notifications}}",filterAll:"All",filterUnread:"Unread",markAllRead:"Mark all as read",markRead:"Mark as read",markUnread:"Mark as unread",archive:"Archive",loadMore:"Load more",empty:"You're all caught up.",emptyUnread:"No unread notifications.",loadFailed:"Could not load notifications",updateFailed:"Could not update the notification",channelEmail:"Email",channelPush:"Push",opened:"Opened",clicked:"Clicked",notDelivered:"Not delivered"},title:"Notification Preferences",permissionDenied:"Notification permission denied",notSupported:"Push notifications are not supported in this browser.",manageDescription:"Manage how you receive notifications from this workspace.",blocked:"Notifications Blocked",blockedDescription:"You previously blocked notifications for this site. To enable them, update your browser settings:",pushTitle:"Push Notifications",pushEnabledDescription:"You will receive browser notifications for important updates.",pushDisabledDescription:"Get notified about payment issues, trial expiry, and other important updates.",enabling:"Enabling...",disabling:"Disabling...",enable:"Enable",disable:"Disable",toggleAction:"{loading, select, true {{subscribed, select, true {Disabling...} other {Enabling...}}} other {{subscribed, select, true {Disable} other {Enable}}}}",pushDescription:"{subscribed, select, true {You will receive browser notifications for important updates.} other {Get notified about payment issues, trial expiry, and other important updates.}}",deviceNote:"Notifications are sent to this device. Enable on other devices separately.",prefsSaved:"Notification preferences saved.",prefsSaveFailed:"Could not save your notification settings",yourTitle:"Your notifications",yourDescription:"How you hear about each event in this workspace. Everything still appears in your inbox.",defaultsTitle:"Workspace defaults",defaultsDescription:"What members get unless they choose otherwise. A required event can't be changed by members.",requiredLabel:"Required",requiredHint:"Required by this workspace",loadingPrefs:"Loading preferences...",categories:{workspace:"Workspace",billing:"Billing & Payments"},events:{workspace_invite:"Member Invited",workspace_invite_desc:"When a new member is added to the workspace",workspace_removed:"Member Removed",workspace_removed_desc:"When a member is removed from the workspace",workspace_role_changed:"Role Changed",workspace_role_changed_desc:"When a member's role is updated",subscription_created:"Subscription Created",subscription_created_desc:"When a new subscription is activated",subscription_upgraded:"Plan Upgraded",subscription_upgraded_desc:"When the subscription plan is upgraded",subscription_canceled:"Subscription Canceled",subscription_canceled_desc:"When the subscription is canceled",subscription_suspended:"Access Suspended",subscription_suspended_desc:"When access is suspended due to payment failures",trial_ending:"Trial Ending",trial_ending_desc:"A few days before the trial expires",trial_expired:"Trial Expired",trial_expired_desc:"When the trial period has ended",payment_failed:"Payment Failed",payment_failed_desc:"When a payment could not be processed",payment_action_required:"Payment Action Required",payment_action_required_desc:"When a payment requires additional verification",payment_succeeded:"Payment Received",payment_succeeded_desc:"When a payment is successfully processed"},unblock:{firefox:{step1:"Click the lock icon (or shield icon) in the address bar",step2:'Find "Notifications" in the permissions list',step3:'Change from "Blocked" to "Allow"',step4:"Reload this page"},safari:{step1:"Open Safari → Settings → Websites → Notifications",step2:"Find this website in the list",step3:'Change from "Deny" to "Allow"',step4:"Reload this page"},edge:{step1:"Click the lock icon in the address bar",step2:'Click "Permissions for this site"',step3:'Set "Notifications" to "Allow"',step4:"Reload this page"},chrome:{step1:"Click the lock icon (or tune icon) in the address bar",step2:'Click "Site settings"',step3:'Set "Notifications" to "Allow"',step4:"Reload this page"}}},quota:{includedOnly:"{count, number}/mo",includedWithOverage:"{count, number}/mo, then {price} / {unit}",includedHardLimit:"{count, number}/mo (hard limit)",unitFallback:"unit"},pricing:{title:"Choose Your Plan",description:"Compare plans and select the one that fits your needs",currency:"Currency",billingIn:"Billing in",noPlansCurrency:"No plans available for your billing currency.",noPlansCurrencyHint:"Something went wrong. Please contact support.",noPlans:"No plans available",free:"Free",included:"included",save:"Save",current:"Current",processing:"Processing...",unavailable:"Unavailable",selectCurrency:"Select billing currency",billingInterval:"Billing interval"},beta:{logoAlt:"Logo",nameLabel:"Name",emailLabel:"Email",submitText:"Submit",submittingText:"Submitting...",errorMessage:"An error occurred",tryAgain:"Try Again",privacyConsent:"By submitting this form, you consent to our",privacyPolicy:"Privacy Policy",and:"and",termsOfService:"Terms of Service"},workspace:{switchTitle:"Switch Workspace",switchDescription:"Select a workspace to switch to or create a new one.",notLoggedIn:"It looks like you are not signed in. Please sign in to continue.",availableWorkspaces:"Available Workspaces ({count, number})",loadingWorkspaces:"Loading workspaces...",searchPlaceholder:"Search workspaces...",noWorkspacesFound:"No workspaces found",noWorkspacesAvailable:"No workspaces available",switchTo:"Switch to",membersCount:"{count, plural, one {# member} other {# members}}",createNew:"Create New Workspace",createTitle:"Create New Workspace",createDescription:"Create a new workspace to get started.",workspaceName:"Workspace Name",workspaceNamePlaceholder:"My Awesome Workspace",workspaceNameMinLength:"Workspace name must be at least 2 characters.",workspaceIcon:"Workspace Icon",iconDescription:"Choose an emoji or upload a custom image for your workspace.",chooseEmoji:"Choose Emoji",customImageUrl:"Custom Image URL",imageUrl:"Image URL",imageUrlPlaceholder:"https://example.com/image.png",imageUrlDescription:"Enter a valid URL for your workspace image. Supports PNG, JPG, and SVG formats.",invalidUrl:"Please enter a valid URL",creating:"Creating...",createWorkspace:"Create Workspace"},dropdowns:{search:"Search...",chooseOption:"Choose option",chooseCountry:"Choose country",searchCountry:"Choose country...",chooseLanguage:"Choose language",searchLanguage:"Choose language...",chooseCurrency:"Choose currency",searchCurrency:"Choose currency...",chooseTimezone:"Choose timezone",searchTimezone:"Choose timezone...",noResults:"No results found"},push:{failedToSubscribe:"Failed to subscribe to push notifications",failedToUnsubscribe:"Failed to unsubscribe from push notifications"},permissions:{title:"Permissions",description:"Permissions assigned to each role in this workspace.",ownerOnly:"Only the workspace owner can manage permissions.",save:"Save Permissions",saving:"Saving...",saveSuccess:"Permissions saved successfully"},credits:{title:"Credits",description:"Credits can be used for premium actions like AI generation.",balance:"Credit Balance",available:"Available",totalGranted:"Total Granted",totalConsumed:"Total Consumed",totalExpired:"Total Expired",noCredits:"No credits yet",noCreditsHint:"Credits will appear here when granted by your plan or purchased.",buyCredits:"Buy Credits",buyAmount:"Buy {count} Credits",purchasing:"Redirecting...",packages:"Credit Packages",noPackages:"No credit packages available.",creditsAmount:"{count} credits",validityDays:"Valid for {count} days",validityUnlimited:"No expiry",transactions:"Recent Transactions",noTransactions:"No transactions yet.",loadMore:"Load More",viewAll:"View All",expiringSoon:"Expiring Soon",expiringInDays:"{count} credits expiring within {days} days",noExpiring:"No credits expiring soon.",type:{plan_grant:"Plan Grant",pack_purchased:"Purchased",consumed:"Consumed",expired:"Expired",admin_grant:"Granted",admin_revoke:"Revoked",refund:"Refund"},dialogTitle:"Buy Credit Packages",dialogDescription:"Choose a credit package to purchase.",dialogDescriptionWorkspace:"Purchase credits for {workspace}.",perCredit:"{price} per credit",purchaseSuccess:"Credits purchased successfully! Your balance has been updated.",purchaseCanceled:"Credit purchase was canceled. No charges were made.",purchaseFailed:"Credit purchase failed. Please try again or contact support.",errorLoading:"Failed to load credit data",insufficientCredits:"Not enough credits",insufficientDetail:"Insufficient credits. Available: {available}, requested: {requested}"},guest:{title:"Create your account",description:"You are using the app as a guest. Add your email address to keep what you have done here and sign in again later.",emailLabel:"Email",nameLabel:"Name (optional)",passwordLabel:"Password (optional)",passwordHint:"At least 8 characters. Leave it empty to sign in another way the app offers.",emailInvalid:"Enter a valid email address.",passwordMinLength:"Use at least 8 characters.",send:"Send code",sentTo:"We sent a code to {email}.",codeLabel:"Code from the email",codeInvalid:"Enter the 6-digit code from the email.",resend:"Resend code",resendIn:"Resend in {seconds, plural, one {# second} other {# seconds}}",resent:"We sent a new code to {email}.",confirm:"Create account",done:"Your account is ready. You can sign in with {email} from now on."},loading:{restoringSession:"Restoring your session...",redirecting:"Redirecting...",signingIn:"Signing you in...",verifyingAccount:"Verifying your account...",almostThere:"Almost there..."},errors:{networkError:"Network error: Please check your internet connection",unreachable:"The server could not be reached. Check your connection and try again.",unauthorized:"Your session has ended. Sign in again.",notFound:"Resource not found",generic:"An error occurred",fetchPlans:"Failed to fetch plans",fetchPlanGroup:"Failed to fetch plan group",fetchPlanGroupVersion:"Failed to fetch plan group version",fetchPlanGroupVersions:"Failed to fetch plan group versions",fetchSubscription:"Failed to fetch subscription",createCheckout:"Failed to create checkout session",updateSubscription:"Failed to update subscription",fetchInvoices:"Failed to fetch invoices",fetchInvoice:"Failed to fetch invoice",openBillingPortal:"Failed to open billing portal",cancelSubscription:"Failed to cancel subscription",resumeSubscription:"Failed to resume subscription",recordUsage:"Failed to record usage",fetchQuotaUsage:"Failed to fetch quota usage status",fetchAllQuotaUsage:"Failed to fetch all quota usage",fetchUsageLogs:"Failed to fetch usage logs",fetchCreditBalance:"Failed to fetch credit balance",consumeCredits:"Failed to consume credits",purchaseCredits:"Failed to purchase credits",fetchCreditPackages:"Failed to fetch credit packages",fetchCreditTransactions:"Failed to fetch credit transactions",fetchExpiringCredits:"Failed to fetch expiring credits",fetchWorkspaces:"Failed to fetch workspaces"},security:{connectedAgentsTitle:"Connected agents",connectedAgentsDescription:"AI agents you've authorized to access your account. Disconnect any you no longer use. Disconnecting revokes access immediately.",connectedAgentsDisconnect:"Disconnect",connectedAgentsEmpty:"No connected agents.",connectedAgentsAccess:"Access",connectedAgentsGranted:"Granted",connectedAgentsLoadFailed:"Failed to load connected agents",connectedAgentsRevokeFailed:"Failed to disconnect",connectedAgentsConfirmTitle:"Disconnect {name}?",connectedAgentsConfirmBody:"It loses access to your account at once. You can connect it again at any time.",connectedAgentsCancel:"Cancel",connectedAgentsDisconnected:"{name} was disconnected.",mcpConnectAction:"Connect an agent",mcpGuideTitle:"Connect an AI agent",mcpGuideDescription:"Let an AI assistant securely work in your account. Choose your app below and follow the steps. It only takes a minute.",mcpServerUrlLabel:"Server address",mcpServerUrlHint:"Some apps just ask you to paste this address.",mcpPromptLabel:"Or paste this into your AI",mcpPromptHint:"Works with chat assistants that can add tools. Paste it into the chat and send.",mcpPromptTemplate:"Please connect to my {{name}} account using the MCP server at {{url}}, then use its tools to help me.",mcpClientsLabel:"Step-by-step for popular apps",mcpAddToConfigFile:"Open the file {path} and add this:",mcpClientChatgptInstructions:"In ChatGPT, go to Settings → Connectors, choose “Add custom connector”, and paste the server address above.",mcpClientClaudeInstructions:"In Claude, go to Settings → Connectors, choose “Add custom connector”, and paste the server address above.",mcpClientClineInstructions:"In Cline, open the MCP Servers panel, choose “Add remote server”, and paste the server address above.",mcpCopy:"Copy",mcpCopied:"Copied",mcpLearnMore:"Learn more",inactive:"Inactive",inactiveHint:"Registered on a previous sign-in domain and can no longer be used. You can remove it.",passkeysTitle:"Passkeys",passkeysDescription:"Passkeys let you sign in with your fingerprint, face, or device PIN.",noPasskeys:"No passkeys registered",addHint:"After you sign in, the sign-in page offers to add a passkey on that device, but only while your account has none.",rename:"Rename",remove:"Remove",removeTitle:"Remove passkey",removeDescription:"You will no longer be able to sign in with this passkey.",renamePlaceholder:"Passkey name",lastUsed:"Last used",added:"Added",passwordTitle:"Password",passwordDescription:"Change the password you sign in with. Every other session is signed out.",currentPassword:"Current password",newPassword:"New password",passwordRequired:"Enter your current password.",passwordMinLength:"Use at least 8 characters.",changePassword:"Change password",passwordChanged:"Password changed. You were signed out on every other device.",passwordSocialHint:'If you signed up with Google or another provider, or with a code or link, you have no password yet. To set one, sign out and use "Forgot password?" on the sign-in page.',passwordNone:"You sign in without a password.",passwordNoneHint:'To set one, sign out and use "Forgot password?" on the sign-in page.',twoStepTitle:"Two-step sign-in",twoStepDescription:"Ask for a code from an authenticator app when you sign in, so a stolen password alone is not enough.",twoStepSetUp:"Set up",twoStepRequiredSetup:"This app requires two-step sign-in. Set it up now, or you will be asked to at your next sign-in.",twoStepScan:"Scan this QR code with your authenticator app.",twoStepQrAlt:"QR code for your authenticator app",twoStepManualKey:"Can't scan it? Type this key into the app instead.",twoStepCodeLabel:"6-digit code from the app",twoStepCodeInvalid:"Enter the 6-digit code the app shows.",twoStepTurnOn:"Turn on",twoStepEnabled:"Two-step sign-in is on.",twoStepBackupTitle:"Save your backup codes",twoStepBackupDescription:"Each code signs you in once if you lose your phone. Keep them somewhere safe. They will not be shown again.",twoStepCopy:"Copy",twoStepCopied:"Copied",twoStepDone:"Done",twoStepAppName:"Authenticator app",twoStepBackupLeft:"{count, plural, =0 {No backup codes left} one {# backup code left} other {# backup codes left}}",twoStepNewCodes:"New backup codes",twoStepTurnOff:"Turn off",twoStepRequiredNote:"This app requires two-step sign-in, so it cannot be turned off.",twoStepCurrentCodeLabel:"Code from your authenticator app, or a backup code",twoStepCurrentCodeRequired:"Enter a code to continue.",twoStepTurnOffHint:"Enter a current code to turn off two-step sign-in.",twoStepNewCodesHint:"Enter a current code to make new backup codes. The old ones stop working.",twoStepDisabled:"Two-step sign-in is off.",twoStepCodesRegenerated:"New backup codes made. The old ones no longer work.",twoStepOffDescription:"This app has two-step sign-in turned off, so signing in does not ask for a code. You can still remove what you set up before.",twoStepRemoveHint:"Enter a current code to remove the authenticator app.",twoStepRemoved:"The authenticator app was removed.",connectedAccountsTitle:"Connected accounts",connectedAccountsDescription:"Sign in with any of these accounts. Connect another, or remove one you no longer use.",connectedAccountsEmpty:"No accounts connected yet.",connectedAccountsAvailable:"Connect another account",connectedAccountsConnect:"Connect {provider}",connectedAccountsLastWay:"This is the only way you can sign in. Add another sign-in method before removing it.",connectedAccountsRemoveTitle:"Remove {provider}?",connectedAccountsRemoveDescription:"You will no longer be able to sign in with this {provider} account. You can connect it again later.",connectedAccountsRemoved:"{provider} was removed from your account.",connectedAccountsLinked:"{provider} is connected. You can sign in with it from now on.",connectedAccountsLinkedGeneric:"The account is connected. You can sign in with it from now on.",connectedAccountsReauth:"For your security, confirm it's you before removing a connected account.",connectedAccountsSignInAgain:"Sign in again",connectedAccountsLinkConflict:"That account is already connected to a different account here, so it was not connected to this one.",connectedAccountsProviderError:"The provider did not allow the connection, or it was cancelled. Nothing was changed.",connectedAccountsProviderFailed:"The account could not be connected. Please try again.",connectedAccountsSessionEnded:"Your session ended before the account was connected. Sign in and try again.",connectedAccountsNoVerifiedEmail:"That account has no verified email address. Verify an email address with the provider, then try again.",connectedAccountsEmailUnverified:"That account has no verified email address to create your account with. Nothing was changed.",connectedAccountsEmailUnavailable:"The email address of that account cannot be used here. Connect another account, or if that address already has an account here, sign in to that account instead.",connectedAccountsDisposableEmail:"That account uses a disposable email address. Connect an account with a permanent address.",connectedAccountsSignupClosed:"Sign-up is not enabled for this app, so your account cannot be created.",connectedAccountsSignupRestricted:"Sign-up isn't available for the email address of that account.",connectedAccountsWaitlistRequired:"This app signs people up from its waitlist. Join it with that address, and you can create your account once you're approved.",connectedAccountsNotAGuest:"Your account already has an email address.",twoStepGuest:"Create your account before setting up two-step sign-in.",phoneTitle:"Phone number",phoneDescription:"Add a phone number to get sign-in codes by text message.",phoneEmpty:"No phone number added yet.",phoneAdd:"Add phone number",phoneChange:"Change",phoneCountryLabel:"Country",phoneNumberHint:"We will text a code to this number to check it is yours. Message rates may apply.",phoneNumberInvalid:"Enter a phone number with its area code.",phoneSendCode:"Send code",phoneSentTo:"We sent a code to {phone}.",phoneCodeLabel:"Code from the text message",phoneCodeInvalid:"Enter the code from the text message.",phoneResend:"Resend code",phoneResendIn:"Resend in {seconds, plural, one {# second} other {# seconds}}",phoneWait:"A code was sent moments ago. You can send another in {seconds, plural, one {# second} other {# seconds}}.",phoneResent:"We sent a new code to {phone}.",phoneVerify:"Verify",phoneVerified:"Verified",phoneNotVerified:"Not verified",phoneSaved:"{phone} is verified and on your account.",phoneRemoveTitle:"Remove your phone number?",phoneRemoveDescription:"Codes will no longer be sent to {phone}. You can add a number again later.",phoneRemoved:"Your phone number was removed.",phoneReauth:"For your security, confirm it's you before removing your phone number.",phoneLastWay:"This is the only way you can sign in. Add another sign-in method before removing your phone number.",phoneUsedForTwoStep:"Two-step sign-in sends codes to this number. Turn off text message codes before removing it.",phoneSmsUnavailable:"Text messages cannot be sent right now. Try again later.",phoneCheckUnavailable:"The code cannot be checked right now. Try again later.",phoneTextUnavailable:"This app does not send codes by text message, so a phone number cannot be added here.",twoStepSmsName:"Text message",twoStepSmsWeaker:"Less secure than an authenticator app, because a phone number can be moved to someone else's SIM card.",twoStepSmsTo:"Codes go to {phone}.",twoStepSmsNeedsPhone:"Add and verify a phone number first, then turn on text message codes.",twoStepSmsGoToPhone:"Go to phone number",twoStepSmsSentGeneric:"We sent a code to your phone.",twoStepSmsEnabled:"Text message codes are on.",twoStepSmsDisabled:"Text message codes are off.",twoStepSmsTurnOffTitle:"Turn off text message codes?",twoStepSmsTurnOffDescription:"Sign-in will no longer send a code to your phone.",twoStepSmsReauth:"For your security, confirm it's you before turning off text message codes.",reauthConfirm:"Confirm it's you",reauthConfirmed:"Thanks, that's confirmed. You can go ahead now.",reauthImpersonating:"You are signed in as this person from the console, so you can't confirm it's them here. Only they can make this change.",deleteAccountTitle:"Delete account",deleteAccountDescription:"Delete your account and the personal data in it. Workspaces only you use are deleted with it.",deleteAccountWarning:"Your other sessions end now. Depending on the app, the account is deleted straight away or after up to 30 days in which you can change your mind. After that, the account and its personal data are gone for good.",deleteAccountWarningNow:"Your account and its personal data are deleted straight away, and you are signed out. This cannot be undone.",deleteAccountWarningDays:"Your other sessions end now. You have {days, plural, one {# day} other {# days}} to change your mind; after that, the account and its personal data are gone for good.",deleteAccountTypeLabel:"Type {word} to confirm",deleteAccountWord:"DELETE",deleteAccountConfirm:"Delete my account",deleteAccountScheduled:"Your account will be deleted on {date}. You can cancel until then.",deleteAccountNotice:"Your account will be deleted on {date}.",deleteAccountCancel:"Cancel deletion",deleteAccountCancelled:"Your account will not be deleted.",deleteAccountReauth:"For your security, confirm it's you before deleting your account.",deleteAccountOwnsWorkspaces:"{count, plural, one {This workspace has other members or a subscription, so it cannot be deleted with your account. Remove the other members and cancel the subscription, or delete the workspace, then try again:} other {These workspaces have other members or a subscription, so they cannot be deleted with your account. Remove the other members and cancel the subscriptions, or delete those workspaces, then try again:}}",impersonationReadOnly:"You are viewing as {name}. {actor} signed in as this person, read-only until {time}.",impersonationFull:"You are viewing as {name}. {actor} signed in as this person until {time}. Changes are saved to their account.",impersonationSignInLocked:"How they sign in can't be changed.",impersonationExit:"Exit",impersonationRegion:"Viewing as another person",walletConnectEthereum:"Connect an Ethereum wallet",walletConnectSolana:"Connect a Solana wallet",walletNotFound:"No {chain} wallet was found in this browser. Install a wallet extension and try again.",walletRejected:"The request was cancelled in your wallet.",walletBusy:"Your wallet is already waiting for you. Open it to continue.",walletWrongNetwork:"Switch your wallet to a network this app accepts, then try again.",walletNoAccount:"Your wallet did not share an address. Unlock it and try again.",walletFailed:"Your wallet could not sign the request. Please try again.",walletHint:"Connecting asks your wallet to sign a message. It is free and sends no transaction.",devicesTitle:"Your devices",devicesDescription:"Phones and computers you've used to sign in. Sign out or remove any you don't recognize.",devicesEmpty:"You haven't signed in from any devices yet.",devicesLoadFailed:"Couldn't load your devices. Please try again.",deviceCurrent:"This device",deviceTrusted:"Trusted",deviceActiveSessions:"{count, plural, one {# active session} other {# active sessions}}",devicePushEnabled:"Notifications on",deviceLastActive:"Last used: {date}",deviceRename:"Rename",deviceRenamePlaceholder:"Device name",deviceRenameFailed:"Couldn't rename the device. Please try again.",deviceSave:"Save",deviceCancel:"Cancel",deviceSignOut:"Sign out",deviceSignOutFailed:"Couldn't sign out the device. Please try again.",deviceForget:"Remove",deviceForgetFailed:"Couldn't remove the device. Please try again.",deviceForgetConfirmTitle:"Remove this device?",deviceForgetConfirmBody:"This signs the device out and removes it from your list. If you sign in from it again, it'll show up here.",sessionsTitle:"Where you're signed in",sessionsDescription:"You're currently signed in on these. Sign out any you don't recognize.",sessionsEmpty:"You're not signed in anywhere else.",sessionsLoadFailed:"Couldn't load your sessions. Please try again.",sessionCurrent:"This one",sessionExpires:"Signs out: {date}",sessionLastActive:"Last used: {date}",sessionSignOut:"Sign out",sessionSignOutFailed:"Couldn't sign out that session. Please try again."},help:{button:"Help: {label}",linkNewTab:"{link} (opens in a new tab)",twoStep:"When you sign in, you also enter a short code that only you can get. Someone who learns your password still cannot get in.",twoStepApp:"An authenticator app shows a new 6-digit code every 30 seconds, even without signal. For example Google Authenticator, Microsoft Authenticator, 1Password or Authy. You scan the QR code with it once.",twoStepSms:"With text message codes, the code comes by text to your verified phone number. They are more convenient, but less safe than an app.",twoStepLostPhone:"Lost your phone? Sign in with one of your backup codes, then turn the app off here and set it up on your new phone. If you have no backup codes left, or cannot turn it off, ask this app's support team to reset your two-step sign-in.",twoStepKeyPrivate:"Keep this key private, like a password. Anyone who has it can make your sign-in codes.",backupCodesLabel:"Backup codes",backupCodes:"Backup codes let you sign in when you cannot use your authenticator app, for example after losing your phone. Each code works only once.",backupCodesKeep:"Keep them somewhere safe and private, such as a password manager or a printed copy at home. Anyone who has them and your password can sign in as you.",backupCodesNew:"Making new backup codes replaces all the old ones: they stop working at once, used or not.",passkeys:"A passkey lets you sign in with your fingerprint, your face or your screen lock (the PIN or pattern that unlocks your device), instead of a password.",passkeysWhere:"It stays on your device or in your password manager, such as iCloud Keychain or Google Password Manager. This app never receives the passkey itself.",passkeysRemove:"Removing a passkey here means it can no longer sign you in. Your device or password manager may still list it, and you can delete it there too.",devicesThis:"{label}: the phone or computer you are using now.",devicesTrusted:"{label}: you chose to remember this device when you signed in, so it may skip the two-step code for a while.",devicesSignOut:"{label}: ends every sign-in on that device, so whoever uses it next has to sign in again. On this device, it signs you out here too.",devicesRemove:"{label}: signs the device out and takes it off this list. It comes back if you sign in on it again.",sessionsWhat:"Each one is a place where you are signed in, such as a browser or an app.",sessionsThis:"{label}: where you are signed in right now.",sessionsSignOut:"{label}: ends that sign-in straight away.",sessionsEverywhere:"Changing your password signs you out everywhere except here. Do it if you see a sign-in you do not recognize.",connectedAccounts:"Connecting another account lets you sign in here with it, without a password. You confirm on its own sign-in page, then come back here.",connectedAccountsRemove:"Removing one only means it can no longer sign you in here. The account itself does not change.",connectedAccountsLastWay:"You always need at least one way to sign in, so the last one cannot be removed. A way to sign in can be a connected account, a passkey, a password, or a code sent to your verified email or phone, where this app offers them.",phone:"Your phone number can get codes by text message: to sign in, if this app offers that, and for two-step sign-in, if you turn text message codes on.",phoneCheck:"We text a code to the number first, to check it is yours. Sign-in codes only go to a verified number.",reauth:"Some changes, such as removing a way to sign in or deleting your account, need a sign-in from the last 10 minutes. That stops someone else making them on a device you left signed in.",reauthHow:"You confirm on the sign-in page, then come straight back here. Then make the change again.",email:"Your email address is how this app knows you, and where it sends messages about your account.",emailChange:"To change it, enter the new address, then the 6-digit code we email there. We let your old address know, and you stay signed in.",password:"You enter your current password first, so nobody else can change it on a device you left open. The new one needs at least 8 characters. A few unrelated words together are hard to guess, and you will remember them.",passwordLeaks:"Passwords found in known data leaks are refused. After the change, you stay signed in here and are signed out everywhere else.",passwordForgot:'Forgot your current password? Sign out, then choose "Forgot password?" on the sign-in page.',deleteAccountDays:"Your account is deleted {days, plural, one {# day} other {# days}} after you confirm. Until then it keeps working: you can still sign in, and {cancel}, here or at the top of the settings, keeps your account.",deleteAccountNow:"This app deletes accounts as soon as you confirm. There is no waiting time, and it cannot be undone.",deleteAccountRange:"Depending on the app, your account is deleted as soon as you confirm, or after a waiting time of up to 30 days. During that time it keeps working: you can still sign in, and {cancel} keeps your account."}},li={en:async()=>ci,es:async()=>(await import("./es-BZsmhBN3.mjs")).es,fr:async()=>(await import("./fr-rdnNHzxy.mjs")).fr,de:async()=>(await import("./de-HXQk5D6k.mjs")).de,ja:async()=>(await import("./ja-CDyla2g0.mjs")).ja,zh:async()=>(await import("./zh-C5HABZZV.mjs")).zh,hi:async()=>(await import("./hi-t3RH7ITu.mjs")).hi,ar:async()=>(await import("./ar-3aqWucom.mjs")).ar},di=["en","es","fr","de","ja","zh","hi","ar"];function ui(e){if("string"!=typeof e||!e)return;const t=e.toLowerCase().replace("_","-");if(di.includes(t))return t;const n=t.split("-")[0];return di.includes(n)?n:void 0}const pi={hi:"hi-u-nu-deva",ar:"ar-u-nu-arab"};function hi(e,t){const n={...e};for(const r of Object.keys(t)){const a=t[r],i=e[r];"string"==typeof a?n[r]=a:a&&"object"==typeof a&&i&&"object"==typeof i&&(n[r]=hi(i,a))}return n}const mi=c({messages:ci,locale:"en",formattingLocale:"en"});function gi({locale:e,messageOverrides:t,children:n}){const r=ui(e??"en")??"en";const[i,o]=a.useState(ci);a.useEffect(()=>{if("en"===r)return void o(ci);let e=!1;const t=li[r];return t&&t().then(t=>{e||o(t)}),()=>{e=!0}},[r]);const c=s(()=>t?hi(i,t):i,[i,t]),l=function(e){return pi[e]??e}(r),d=s(()=>({messages:c,locale:r,formattingLocale:l,requestedLocale:e}),[c,r,l,e]);return a.createElement(mi.Provider,{value:d},n)}const fi=new Map,yi=new Map,wi=new Map;function bi(e,t){return t?`${e}:${JSON.stringify(t)}`:e}const vi={getNumberFormat(e,t){const n=bi(e,t);let r=fi.get(n);return r||(r=new Intl.NumberFormat(e,t),fi.set(n,r)),r},getDateTimeFormat(e,t){const n=bi(e,t);let r=yi.get(n);return r||(r=new Intl.DateTimeFormat(e,t),yi.set(n,r)),r},getPluralRules(e,t){const n=bi(e,t);let r=wi.get(n);return r||(r=new Intl.PluralRules(e,t),wi.set(n,r)),r}},ki=new Map;function Si(){const{messages:e,locale:t,formattingLocale:n}=d(mi),r=s(()=>{const t=(e,t)=>{let n=e;for(const e of t.split(".")){if(!n||"object"!=typeof n||!(e in n))return;n=n[e]}return"string"==typeof n?n:void 0};return(r,a)=>{const i=t(e,r)??t(ci,r)??r;if(!a)return i;try{const e=function(e,t){const n=`${t}:${e}`;let r=ki.get(n);return r||(r=new B(e,t,void 0,{formatters:vi}),ki.set(n,r)),r}(i,n),t=e.format(a);return"string"==typeof t?t:String(t)}catch{return i.replace(/\{(\w+)\}/g,(e,t)=>String(a[t]??`{${t}}`))}}},[e,n]),a="ar"===t?"rtl":"ltr",i=s(()=>e=>e.toLocaleString(n),[n]),o=s(()=>(e,t)=>wn(e,t,n),[n]);return{t:r,locale:t,formattingLocale:n,dir:a,fmtNum:i,fmtCents:o,messages:e}}const Ii=new Map;function Ci(e,t){const n=Ii.get(e);if(n)return n;const r=t().finally(()=>{Ii.get(e)===r&&Ii.delete(e)});return Ii.set(e,r),r}function xi(){const e=l(null);u(()=>()=>e.current?.abort(),[]);return{begin:p(()=>{e.current?.abort();const t=new AbortController;return e.current=t,t},[]),settle:p(t=>e.current===t&&(e.current=null,!t.signal.aborted),[])}}const Ni="bb_attr",Ai=["gclid","gbraid","wbraid","dclid","fbclid","msclkid","li_fat_id","twclid","ttclid","rdt_cid","epik","irclickid","utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id"],Pi=/^[\w.~-]{1,200}$/;function Ei(){return"undefined"==typeof window?null:window}function _i(e,t){if(!e||!e.includes("."))return"";if(/^\d{1,3}(\.\d{1,3}){3}$/.test(e))return"";const n=t??Ei()?.document;if(!n)return"";const r=e.split(".");for(let e=r.length-2;e>=0;e--){const t="."+r.slice(e).join("."),a=`__bb_probe_${Date.now()}`;n.cookie=`${a}=1; domain=${t}; path=/; SameSite=Lax`;const i=n.cookie.includes(`${a}=1`);if(n.cookie=`${a}=; domain=${t}; path=/; max-age=0; SameSite=Lax`,i)return t}return""}const Ti="$t",Ui="$l";function Ri(e){const t=e.cookie.split("; ").find(e=>e.startsWith(`${Ni}=`));if(!t)return{params:{}};try{const e=JSON.parse(decodeURIComponent(t.slice(8)));if("object"!=typeof e||!e)return{params:{}};const{[Ti]:n,[Ui]:r,...a}=e;return{params:a,..."number"==typeof n&&n>0?{capturedAt:n}:{},..."string"==typeof r&&r?{landingUrl:r}:{}}}catch{return{params:{}}}}function Oi(e){try{const{origin:t,pathname:n}=e.location;return t&&"null"!==t?`${t}${n}`.slice(0,300):void 0}catch{return}}const Wi=Ai.filter(e=>!e.startsWith("utm_")),Fi=e=>Wi.some(t=>!!e[t]);function Li(){const e=Ei();if(!e)return{};const t=e.document,n=function(e){return Ri(e).params}(t),r=function(e){const t=new URLSearchParams(e),n={};for(const e of Ai){const r=t.get(e);r&&(r.length>200||Pi.test(r)&&(n[e]=r))}return n}(e.location.search),a=Object.keys(r).length>0&&(Fi(r)||!Fi(n)),i=a?r:n;return 0===Object.keys(i).length?{}:(a&&!function(e,t){const n=new Set([...Object.keys(e),...Object.keys(t)]);for(const r of n)if(e[r]!==t[r])return!1;return!0}(r,n)&&function(e,t,n,r){const a=encodeURIComponent(JSON.stringify({...t,[Ti]:r.capturedAt,...r.landingUrl?{[Ui]:r.landingUrl}:{}}));e.cookie=`${Ni}=${a}; path=/; max-age=7776000; SameSite=Lax`+(n?`; domain=${n}`:"")}(t,i,_i(e.location.hostname,t),{capturedAt:Date.now(),landingUrl:Oi(e)}),i)}function Di(){const e=Ei();return e?Ri(e.document):{params:{}}}function $i(){const e=Di(),t={};for(const[n,r]of Object.entries(e.params))"string"==typeof r&&r&&/^[a-z_]{2,32}$/.test(n)&&(t[n]=r);if(Object.keys(t).length)return{params:t,...e.capturedAt?{capturedAt:e.capturedAt}:{},...e.landingUrl?{landingUrl:e.landingUrl}:{}}}function Mi(e){try{const t=new URLSearchParams(e);return t.has("code")&&t.has("state")}catch{return!1}}const ji="bb_pending_checkout",qi=216e5;function Bi(){try{return"undefined"==typeof window?null:window.sessionStorage}catch{return null}}function Vi(e){try{Bi()?.setItem(ji,JSON.stringify(e))}catch{}!function(e){if(!e.sessionId)return;const t=Gi();if(!t)return;try{const n=_i(window.location?.hostname??"",t);t.cookie=`${zi}=${encodeURIComponent(JSON.stringify(e))}; path=/; max-age=21600; SameSite=Lax`+(n?`; domain=${n}`:"")}catch{}}(e)}const zi="bb_co";function Gi(){try{return"undefined"==typeof window?null:window.document??null}catch{return null}}function Ji(){const e=Gi();if(e)try{const t=_i(window.location?.hostname??"",e);e.cookie=`${zi}=; path=/; max-age=0; SameSite=Lax`+(t?`; domain=${t}`:"")}catch{}}function Hi(e,t){if(!e)return null;try{const n=JSON.parse(e);return n&&"string"==typeof n.eventId&&n.eventId?"number"!=typeof n.startedAt||t-n.startedAt>qi?null:n:null}catch{return null}}function Yi(e=Date.now()){const t=Bi();if(!t)return null;let n=null;try{n=t.getItem(ji),t.removeItem(ji)}catch{return null}const r=Hi(n,e);return r&&Ji(),r}function Ki(e){try{return Hi(Bi()?.getItem(ji)??null,e)}catch{return null}}function Qi(e,t=Date.now()){let n=null;try{n=new URLSearchParams(e).get("session_id")}catch{return null}if(!n)return null;const r=Ki(t);if(r?.sessionId===n)return Yi(t);const a=function(e){const t=Gi();if(!t||"string"!=typeof t.cookie)return null;const n=t.cookie.split("; ").find(e=>e.startsWith(`${zi}=`));return n?Hi(decodeURIComponent(n.slice(zi.length+1)),e):null}(t);return a?.sessionId!==n?null:(Ji(),a)}function Zi(e,t=Date.now()){return function(e){let t=null;try{t=new URLSearchParams(e).get("bb")}catch{return!1}if(!t)return!1;const n={};for(const e of t.split(",")){const t=e.indexOf(":");if(-1!==t)try{n[decodeURIComponent(e.slice(0,t))]=decodeURIComponent(e.slice(t+1))}catch{}}return"checkout"===n.action&&"cancel"===n.status}(e)&&Ki(t)?Yi(t):null}const Xi=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),es=new Set(["bhd","jod","kwd","omr","tnd"]);function ts(e,t){if("number"!=typeof e||!Number.isFinite(e))return;const n=(t??"").toLowerCase();return Xi.has(n)?e:e/(es.has(n)?1e3:100)}const ns=["AT","BE","BG","HR","CY","CZ","DK","EE","FI","FR","DE","GR","HU","IE","IT","LV","LT","LU","MT","NL","PL","PT","RO","SK","SI","ES","SE","IS","LI","NO"],rs=/^[A-Z]{2}(-[A-Z0-9]{1,3})?$/;function as(e){const t=new Set;for(const n of e??[]){const e=String(n).trim().toUpperCase();if("EEA"===e)for(const e of ns)t.add(e);else rs.test(e)&&t.add(e)}return[...t]}function is(e,t,n){return e.includes(t)}function ss(e,t,n){const r=(t??"").trim().toUpperCase();if(!/^[A-Z]{2}$/.test(r)||"XX"===r||"T1"===r)return"denied";const a=(n??"").trim().toUpperCase()||void 0,i=as(e.regions?.denied),s=as(e.regions?.granted);if(a){if(i.includes(`${r}-${a}`))return"denied";if(s.includes(`${r}-${a}`))return"granted"}return is(i,r)?"denied":is(s,r)||"granted"===e.default?"granted":"denied"}function os(){return"undefined"==typeof window?null:window}const cs=["ad_storage","ad_user_data","ad_personalization","analytics_storage"];function ls(e){const t={};for(const n of cs)t[n]=e;return t}function ds(e){const t=os();if(!t)return;const n=t.gtag;n?.("consent","update",{ad_storage:e.marketing?"granted":"denied",ad_user_data:e.marketing?"granted":"denied",ad_personalization:e.marketing?"granted":"denied",analytics_storage:e.analytics?"granted":"denied"}),n?.("set","ads_data_redaction",!e.marketing);const r=t.fbq;r?.("consent",e.marketing?"grant":"revoke")}const us="bb_cid";function ps(){if("undefined"!=typeof document&&"undefined"!=typeof window)try{const e=document.cookie.split("; ").find(e=>e.startsWith(`${us}=`)),t=e?.slice(7);if(t&&/^[\w-]{16,64}$/.test(t))return t;const n=function(){const e=globalThis.crypto;if(e&&"function"==typeof e.randomUUID)return e.randomUUID();const t=new Uint8Array(16);if(e&&"function"==typeof e.getRandomValues)e.getRandomValues(t);else for(let e=0;e<t.length;e++)t[e]=Math.floor(256*Math.random());return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}(),r=_i(window.location.hostname,document);return document.cookie=`${us}=${n}; path=/; max-age=34128000; SameSite=Lax`+(r?`; domain=${r}`:""),n}catch{return}}const hs="bb_consent_recorded";function ms(e){if("function"!=typeof fetch||!e.serverUrl||!e.orgId||!e.clientId)return;const t=JSON.stringify([e.orgId,e.clientId,!!e.state.analytics,!!e.state.marketing,e.manifestVersion??"",e.consentString??"",e.headers?.["x-session-id"]?"account":"anonymous"]);if(!e.source&&function(e){try{return window.localStorage.getItem(hs)===e}catch{return!1}}(t))return;!function(e){try{window.localStorage.setItem(hs,e)}catch{}}(t);const n=ps();if(!n)return;const r=`${e.serverUrl.replace(/\/$/,"")}/api/v1/public/${e.orgId}/consent`;try{fetch(r,{method:"POST",keepalive:!0,headers:{"content-type":"application/json",...e.headers??{}},body:JSON.stringify({clientId:e.clientId,visitorId:n,choices:{analytics:!!e.state.analytics,marketing:!!e.state.marketing},...e.manifestVersion?{manifestVersion:e.manifestVersion}:{},...e.source?{source:e.source.slice(0,40)}:{},...e.consentString?{consentString:e.consentString.slice(0,2e3)}:{}})}).catch(()=>{})}catch{}}const gs=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),fs=(e,t)=>e>>>t|e<<32-t;function ys(e){return function(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}(function(e){let t=1779033703,n=3144134277,r=1013904242,a=2773480762,i=1359893119,s=2600822924,o=528734635,c=1541459225;const l=e.length,d=l+1,u=d+(56-d%64+64)%64+8,p=new Uint8Array(u);p.set(e,0),p[l]=128;const h=8*l,m=Math.floor(h/4294967296),g=h>>>0;p[u-8]=m>>>24&255,p[u-7]=m>>>16&255,p[u-6]=m>>>8&255,p[u-5]=255&m,p[u-4]=g>>>24&255,p[u-3]=g>>>16&255,p[u-2]=g>>>8&255,p[u-1]=255&g;const f=new Uint32Array(64);for(let e=0;e<u;e+=64){for(let t=0;t<16;t++){const n=e+4*t;f[t]=p[n]<<24|p[n+1]<<16|p[n+2]<<8|p[n+3]}for(let e=16;e<64;e++){const t=fs(f[e-15],7)^fs(f[e-15],18)^f[e-15]>>>3,n=fs(f[e-2],17)^fs(f[e-2],19)^f[e-2]>>>10;f[e]=f[e-16]+t+f[e-7]+n>>>0}let l=t,d=n,u=r,h=a,m=i,g=s,y=o,w=c;for(let e=0;e<64;e++){const t=w+(fs(m,6)^fs(m,11)^fs(m,25))+(m&g^~m&y)+gs[e]+f[e]>>>0,n=l&d^l&u^d&u;w=y,y=g,g=m,m=h+t>>>0,h=u,u=d,d=l,l=t+((fs(l,2)^fs(l,13)^fs(l,22))+n>>>0)>>>0}t=t+l>>>0,n=n+d>>>0,r=r+u>>>0,a=a+h>>>0,i=i+m>>>0,s=s+g>>>0,o=o+y>>>0,c=c+w>>>0}const y=new Uint8Array(32),w=[t,n,r,a,i,s,o,c];for(let e=0;e<8;e++)y[4*e]=w[e]>>>24&255,y[4*e+1]=w[e]>>>16&255,y[4*e+2]=w[e]>>>8&255,y[4*e+3]=255&w[e];return y}(e))}async function ws(e){const t=globalThis.crypto?.subtle;if(t&&"function"==typeof t.digest)try{const n=await t.digest("SHA-256",(new TextEncoder).encode(e));return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")}catch{}return ys((n=e,(new TextEncoder).encode(n)));var n}async function bs(e){const t=function(e){const t=String(e??"").trim().toLowerCase(),n=t.lastIndexOf("@");if(n<1||n===t.length-1)return"";let r=t.slice(0,n);const a=t.slice(n+1);return"gmail.com"!==a&&"googlemail.com"!==a||(r=r.replace(/\./g,"")),`${r}@${a}`}(e.email),n=function(e){const t=String(e??"").trim();if(!t.startsWith("+"))return"";const n=t.replace(/[^\d]/g,"");return n.length>=8&&n.length<=15?`+${n}`:""}(e.phone),r={};return t&&(r.emailHash=await ws(t)),n&&(r.phoneHash=await ws(n)),r}function vs(e,t){if("undefined"==typeof window)return;if(!t.emailHash&&!t.phoneHash)return;const n=window;e.some(e=>"google_ads"===e.provider||"ga4"===e.provider||"gtm"===e.provider)&&n.gtag?.("set","user_data",{...t.emailHash?{sha256_email_address:t.emailHash}:{},...t.phoneHash?{sha256_phone_number:t.phoneHash}:{}});for(const r of e)"meta_pixel"===r.provider&&r.providerId&&n.fbq?.("init",r.providerId,{...t.emailHash?{em:t.emailHash}:{},...t.phoneHash?{ph:t.phoneHash}:{}})}function ks(){const e={};try{if("undefined"==typeof document||"string"!=typeof document.cookie)return e;for(const t of document.cookie.split("; ")){const n=t.indexOf("=");n>0&&(e[t.slice(0,n)]=t.slice(n+1))}}catch{}return e}function Ss(e){if(!e)return;const t=e.split(".");if(t.length<4)return;const n=t.slice(-2).join(".");return/^\d+\.\d+$/.test(n)?n:void 0}function Is(e){if(!e)return;const t=/^GS2\.\d+\.(?:.*?\$)?s(\d+)/.exec(e)??/^GS2\.\d+\.s(\d+)/.exec(e);if(t)return t[1];const n=/^GS1\.\d+\.(\d+)\./.exec(e);return n?n[1]:void 0}function Cs(e){const t={},n=(e,n)=>{n&&(t[`bb_${e}`]=n.slice(0,400))};if("undefined"==typeof window||"undefined"==typeof document)return t;const r=ks();n("fbp",r._fbp),n("fbc",r._fbc),n("ga_cid",Ss(r._ga));const a=Object.keys(r).find(e=>e.startsWith("_ga_"));n("ga_sid",a?Is(r[a]):void 0);try{"undefined"!=typeof navigator&&n("ua",navigator.userAgent),"undefined"!=typeof window&&window.location?.origin&&n("url",window.location.origin+window.location.pathname)}catch{}n("consent",function(e){if(!e)return;const t=[e.analytics&&"analytics",e.marketing&&"marketing"].filter(Boolean);return t.length?t.join(","):"none"}(e));try{const e=window.__buildbase?.tracking;n("client",e?.clientId)}catch{}return t}function xs(){const e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}const Ns=new Set(["workspace_id","workspace_role","workspace_owner","workspace_member_count","workspace_plan","subscription_status"]);function As(e){const t={};if(!e)return t;for(const[n,r]of Object.entries(e)){if(Object.keys(t).length>=10)break;if(null==r)continue;if(Ns.has(n))continue;const e=typeof r;"string"!==e&&"number"!==e&&"boolean"!==e||/^[a-z][a-z0-9_]{0,39}$/.test(n)&&(t[`bbp_${n}`]=String(r).slice(0,200))}return t}function Ps(...e){const t=Math.max(0,...e.map(e=>e?Object.keys(e).length:0));return Math.max(0,Math.min(30,40-t))}function Es(e,t,n,r=30){const a={bb_event_id:e,...Cs(t),...As(n)},i=Di();for(const[e,t]of Object.entries(i.params)){if(Object.keys(a).length>=30)break;"string"==typeof t&&t&&(a[`bb_${e}`]=t)}i.capturedAt&&Object.keys(i.params).length&&Object.keys(a).length<30&&(a.bb_attr_ts=String(i.capturedAt));const s=Math.max(0,Math.min(r,30));return Object.fromEntries(Object.entries(a).slice(0,s))}const _s={gtm:{title:"Google Tag Manager",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Container ID",idPattern:"^GTM-[A-Z0-9]{4,10}$",idExample:"GTM-ABC1234",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"analytics",supportsConsentMode:!0,needsConversionIds:!1},ga4:{title:"Google Analytics 4",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Measurement ID",idPattern:"^G-[A-Z0-9]{8,12}$",idExample:"G-ABCD123456",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"analytics",supportsConsentMode:!0,needsConversionIds:!1},google_ads:{title:"Google Ads",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Conversion ID",idPattern:"^AW-[0-9]{9,12}$",idExample:"AW-123456789",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"marketing",supportsConsentMode:!0,needsConversionIds:!0},meta_pixel:{title:"Meta Pixel",vendor:"Meta Platforms Ireland Limited",privacyUrl:"https://www.facebook.com/privacy/policy",idLabel:"Pixel ID",idPattern:"^[0-9]{15,16}$",idExample:"123456789012345",scriptOrigin:"https://connect.facebook.net",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},x_pixel:{title:"X (Twitter) Pixel",vendor:"X Corp.",privacyUrl:"https://x.com/en/privacy",idLabel:"Pixel ID",idPattern:"^o[a-z0-9]{4,6}$",idExample:"o1a2b3",scriptOrigin:"https://static.ads-twitter.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!0,multiInstance:!0},linkedin:{title:"LinkedIn Insight Tag",vendor:"LinkedIn Ireland Unlimited Company",privacyUrl:"https://www.linkedin.com/legal/privacy-policy",idLabel:"Partner ID",idPattern:"^[0-9]{6,9}$",idExample:"1234567",scriptOrigin:"https://snap.licdn.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!0,multiInstance:!0},tiktok:{title:"TikTok Pixel",vendor:"TikTok Information Technologies UK Limited",privacyUrl:"https://www.tiktok.com/legal/privacy-policy",idLabel:"Pixel ID",idPattern:"^[A-Z0-9]{20}$",idExample:"C4A1B2C3D4E5F6G7H8I9",scriptOrigin:"https://analytics.tiktok.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},reddit:{title:"Reddit Pixel",vendor:"Reddit, Inc.",privacyUrl:"https://www.reddit.com/policies/privacy-policy",idLabel:"Advertiser ID",idPattern:"^t2_[a-z0-9]{4,12}$",idExample:"t2_abc123",scriptOrigin:"https://www.redditstatic.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},bing_uet:{title:"Microsoft Advertising (UET)",vendor:"Microsoft Corporation",privacyUrl:"https://privacy.microsoft.com/en-us/privacystatement",idLabel:"Tag ID",idPattern:"^[0-9]{7,9}$",idExample:"12345678",scriptOrigin:"https://bat.bing.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},clarity:{title:"Microsoft Clarity",vendor:"Microsoft Corporation",privacyUrl:"https://privacy.microsoft.com/en-us/privacystatement",idLabel:"Project ID",idPattern:"^[a-z0-9]{10}$",idExample:"ab12cd34ef",scriptOrigin:"https://www.clarity.ms",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},hotjar:{title:"Hotjar",vendor:"Hotjar Limited",privacyUrl:"https://www.hotjar.com/legal/policies/privacy/",idLabel:"Site ID",idPattern:"^[0-9]{6,9}$",idExample:"1234567",scriptOrigin:"https://static.hotjar.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},posthog:{title:"PostHog",vendor:"PostHog, Inc.",privacyUrl:"https://posthog.com/privacy",idLabel:"Project API key",idPattern:"^phc_[A-Za-z0-9]{32,48}$",idExample:"phc_abcdefghijklmnopqrstuvwxyz012345",scriptOrigin:"https://us-assets.i.posthog.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1,hosts:["us.i.posthog.com","eu.i.posthog.com"]},plausible:{title:"Plausible Analytics",vendor:"Plausible Insights OÜ",privacyUrl:"https://plausible.io/privacy",idLabel:"Domain",idPattern:"^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$",idExample:"example.com",scriptOrigin:"https://plausible.io",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},ahrefs:{title:"Ahrefs Analytics",vendor:"Ahrefs Pte. Ltd.",privacyUrl:"https://ahrefs.com/privacy",idLabel:"Analytics key",idPattern:"^[A-Za-z0-9+/=]{20,64}$",idExample:"AbCdEfGhIjKlMnOpQrStUv==",scriptOrigin:"https://analytics.ahrefs.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1}},Ts=Object.keys(_s);function Us(e){return"string"==typeof e&&Object.prototype.hasOwnProperty.call(_s,e)}function Rs(e,t){return!!Us(e)&&("string"==typeof t&&0!==t.length&&new RegExp(_s[e].idPattern).test(t))}const Os=/^[a-z][a-z0-9-]{0,40}$/,Ws=/^[\w.:/@+=-]{1,200}$/;function Fs(e){return function(e){if("string"!=typeof e)return!1;if(0===e.length||e.length>300)return!1;let t;try{t=new URL(e)}catch{return!1}return!("https:"!==t.protocol||!t.hostname||!t.hostname.includes(".")||e.includes("?")||e.includes("#")||t.username||t.password)}(e.src)&&function(e){if(null==e)return!0;if("object"!=typeof e||Array.isArray(e))return!1;const t=Object.entries(e);return!(t.length>12)&&t.every(([e,t])=>Os.test(e)&&"string"==typeof t&&Ws.test(t))}(e.dataAttributes)}Array.from(new Set(Ts.map(e=>_s[e].scriptOrigin))).sort();const Ls={sign_up:{ga4:"sign_up",meta:"CompleteRegistration",tiktok:"CompleteRegistration",reddit:"SignUp"},login:{ga4:"login",meta:null,tiktok:null,reddit:null},trial_started:{ga4:"begin_checkout",meta:"StartTrial",tiktok:"StartTrial",reddit:"Lead"},checkout_started:{ga4:"begin_checkout",meta:"InitiateCheckout",tiktok:"InitiateCheckout",reddit:"AddToCart"},purchase:{ga4:"purchase",meta:"Purchase",tiktok:"CompletePayment",reddit:"Purchase"},subscription_created:{ga4:"purchase",meta:"Subscribe",tiktok:"Subscribe",reddit:"Purchase"},subscription_upgraded:{ga4:"subscription_upgraded",meta:null,tiktok:null,reddit:null},lead:{ga4:"generate_lead",meta:"Lead",tiktok:"SubmitForm",reddit:"Lead"},workspace_created:{ga4:"workspace_created",meta:null,tiktok:null,reddit:null}},Ds=Object.keys(Ls);function $s(e){return Ds.includes(e)}function Ms(){return"undefined"==typeof window?null:window}const js={gtm:"dataLayer",ga4:"gtag",google_ads:"gtag",meta_pixel:"fbq",x_pixel:"twq",linkedin:"lintrk",tiktok:"ttq",reddit:"rdt",bing_uet:"uetq",clarity:"clarity",hotjar:"hj",posthog:"posthog",plausible:"plausible",ahrefs:"__ahrefs_loaded"};function qs(){return"undefined"==typeof window?null:window}function Bs(e,t={}){const n=qs();if(!n)return null;const r=n.document.createElement("script");r.async=!0,r.src=e;for(const[e,n]of Object.entries(t))r.setAttribute(e,n);return n.document.head.appendChild(r),r}function Vs(e){const t=qs();if(!t)return;const n=t.document.createElement("script");n.text=e,t.document.head.appendChild(n)}function zs(e){const t=qs();t&&(Array.isArray(t[e])||(t[e]=[]),"function"!=typeof t.gtag&&(t.gtag=function(){t[e].push(arguments)}))}const Gs=new Set;function Js(e){for(const t of Gs)if(t.slice(0,t.indexOf(":"))===e)return!0;return!1}function Hs(e,t){const n=qs();if(!n)return!1;if("gtm"===e||"ga4"===e||"google_ads"===e){const e=n.google_tag_manager;return!(!e||"object"!=typeof e)&&Object.prototype.hasOwnProperty.call(e,t)}const r=js[e];if(!r)return!1;if(void 0===n[r])return!1;if(Gs.has(`${e}:${t}`))return!0;return!_s[e].multiInstance||!Js(e)}const Ys={meta_pixel:e=>`fbq('init','${e}');fbq('track','PageView');`,x_pixel:e=>`twq('config','${e}');`,tiktok:e=>`ttq.load('${e}');ttq.page();`,reddit:e=>`rdt('init','${e}');rdt('track','PageVisit');`,bing_uet:e=>`window.uetq=window.uetq||[];window.uetq.push({ti:'${e}',enableAutoSpaTracking:false});`,linkedin:e=>`window._linkedin_data_partner_ids=window._linkedin_data_partner_ids||[];window._linkedin_data_partner_ids.push('${e}');`};function Ks(e,t,n){const r=function(e,t,n){const r=qs();if(!r)return!1;if("external"===e.provider){if(!e.src)return!1;const t={};for(const[n,r]of Object.entries(e.dataAttributes??{}))t[`data-${n}`]=r;return Bs(e.src,t),!0}const a=e.provider,i=_s[a];if(!i)return!1;const s=e.providerId;if(!s)return!1;const o=Ys[a];if(o&&Js(a))return Vs(o(s)),!0;switch(a){case"gtm":{zs(t),r[t].push({"gtm.start":Date.now(),event:"gtm.js"});const e="dataLayer"===t?"":`&l=${t}`;return Bs(`${i.scriptOrigin}/gtm.js?id=${s}${e}`),!0}case"ga4":case"google_ads":{zs(t),Bs(`${i.scriptOrigin}/gtag/js?id=${s}`);const e=r.gtag;e("js",new Date);const o="ga4"===a&&n?.gaClientId?{client_id:n.gaClientId}:void 0;return o?e("config",s,o):e("config",s),!0}case"meta_pixel":return Vs(`!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','${i.scriptOrigin}/en_US/fbevents.js');fbq('init','${s}');fbq('track','PageView');`),!0;case"x_pixel":return Vs(`!function(e,t,n,s,u,a){e.twq||(s=e.twq=function(){s.exe?s.exe.apply(s,arguments):s.queue.push(arguments)},s.version='1.1',s.queue=[],u=t.createElement(n),u.async=!0,u.src='${i.scriptOrigin}/uwt.js',a=t.getElementsByTagName(n)[0],a.parentNode.insertBefore(u,a))}(window,document,'script');twq('config','${s}');`),!0;case"linkedin":return Vs(`window._linkedin_partner_id='${s}';window._linkedin_data_partner_ids=window._linkedin_data_partner_ids||[];window._linkedin_data_partner_ids.push('${s}');window.lintrk=window.lintrk||function(a,b){(window.lintrk.q=window.lintrk.q||[]).push([a,b])};window.lintrk.q=window.lintrk.q||[];`),Bs(`${i.scriptOrigin}/li.lms-analytics/insight.min.js`),!0;case"tiktok":return Vs(`!function(w,d,t){w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=['page','track','identify','instances','debug','on','off','once','ready','alias','group','enableCookie','disableCookie'];ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.load=function(e,n){var r='${i.scriptOrigin}/i18n/pixel/events.js';ttq._i=ttq._i||{};ttq._i[e]=[];ttq._i[e]._u=r;ttq._t=ttq._t||{};ttq._t[e]=+new Date;ttq._o=ttq._o||{};ttq._o[e]=n||{};var o=d.createElement('script');o.type='text/javascript';o.async=!0;o.src=r+'?sdkid='+e+'&lib='+t;var a=d.getElementsByTagName('script')[0];a.parentNode.insertBefore(o,a)};ttq.load('${s}');ttq.page()}(window,document,'ttq');`),!0;case"reddit":return Vs(`!function(w,d){if(!w.rdt){var p=w.rdt=function(){p.sendEvent?p.sendEvent.apply(p,arguments):p.callQueue.push(arguments)};p.callQueue=[];var t=d.createElement('script');t.src='${i.scriptOrigin}/ads/pixel.js';t.async=!0;var s=d.getElementsByTagName('script')[0];s.parentNode.insertBefore(t,s)}}(window,document);rdt('init','${s}');rdt('track','PageVisit');`),!0;case"bing_uet":return Vs(`(function(w,d,t,r,u){w[u]=w[u]||[];w[u].push({ti:'${s}',enableAutoSpaTracking:false});var o=d.createElement(t);o.src='${i.scriptOrigin}/bat.js';o.async=1;var i=d.getElementsByTagName(t)[0];i.parentNode.insertBefore(o,i)})(window,document,'script',0,'uetq');`),!0;case"clarity":return Vs(`(function(c,l,a,r,i,t,y){c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};t=l.createElement(r);t.async=1;t.src='${i.scriptOrigin}/tag/'+i;y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y)})(window,document,'clarity','script','${s}');`),!0;case"hotjar":return Vs(`(function(h,o,t,j,a,r){h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};h._hjSettings={hjid:${s},hjsv:6};a=o.getElementsByTagName('head')[0];r=o.createElement('script');r.async=1;r.src='${i.scriptOrigin}/hotjar-'+h._hjSettings.hjid+'.js?sv='+h._hjSettings.hjsv;a.appendChild(r)})(window,document);`),!0;case"posthog":{const t=i.hosts,n=t?.includes(e.host??"")?e.host:t?.[0]??"us.i.posthog.com";return Vs(`!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split('.');2==o.length&&(t=t[o[0]],e=o[1]);t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement('script')).type='text/javascript',p.async=!0,p.src='${i.scriptOrigin}/static/array.js',(r=t.getElementsByTagName('script')[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a='posthog',u.people=u.people||[],u.toString=function(t){var e='posthog';return'posthog'!==a&&(e+='.'+a),t||(e+=' (stub)'),e},u.people.toString=function(){return u.toString(1)+'.people (stub)'},o='init capture register register_once identify alias people.set people.set_once set_config get_distinct_id getFeatureFlag isFeatureEnabled onFeatureFlags reloadFeatureFlags group reset'.split(' '),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);posthog.init('${s}',{api_host:'https://${n}'});`),!0}case"plausible":return Vs("window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)};"),Bs(`${i.scriptOrigin}/js/script.js`,{"data-domain":s,defer:"true"}),!0;case"ahrefs":return Bs(`${i.scriptOrigin}/analytics.js`,{"data-key":s}),r.__ahrefs_loaded=!0,!0;default:return!1}}(e,t,n);return r&&"external"!==e.provider&&e.providerId&&Gs.add(`${e.provider}:${e.providerId}`),r}const Qs=Symbol.for("@buildbase/sdk.tracking.context"),Zs=globalThis,Xs=Zs[Qs]??(Zs[Qs]=c(null)),eo={consent:{manifest:[],state:null,effective:null,default:null,country:null,set:()=>{}},track:()=>{},setUser:()=>{},setIdentity:()=>{},setConsentRecordHeaders:()=>{},setProperties:()=>{},getProperties:()=>({}),completeCheckout:async()=>{},installed:{},ready:!0,attribution:{}};function to(){return d(Xs)??eo}function no(){return null!==d(Xs)}const ro=({serverUrl:e,orgId:n,clientId:r,enabled:a=!0,consent:i="auto",autoPageview:o=!0,events:c,onEvent:d,properties:m,enrich:g,identity:f,debug:y=!1,children:w})=>{const b=l(f);b.current=f;const[v,k]=h(null),[S,I]=h(!1),[C,x]=h(!1),N="object"==typeof i?JSON.stringify(i):"",A=s(()=>N?function(e){if(!e||"object"!=typeof e)return null;const t=e;if("granted"!==t.default&&"denied"!==t.default)return null;const n=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):void 0;return{default:t.default,regions:{...n(t.regions?.denied)?{denied:n(t.regions?.denied)}:{},...n(t.regions?.granted)?{granted:n(t.regions?.granted)}:{}}}}(JSON.parse(N)):null,[N]),P="string"==typeof i?i:"auto",E="granted"===P?{analytics:!0,marketing:!0}:"denied"===P?{analytics:!1,marketing:!1}:null,[_,T]=h(E),U=l(null),R=l(d);R.current=d;const O=l(g);O.current=g;const W=l({});W.current=m??{};const F=l({}),L=p(()=>({...W.current,...F.current}),[]),D=p(e=>{const t={...F.current,...e};for(const[e,n]of Object.entries(t))void 0===n&&delete t[e];F.current=t},[]),[$,M]=h({}),j=l({}),[q,B]=h(0),V=l(null),[z,G]=h(0),J=l({}),H=l(null);H.current=v;const Y=v?.dataLayerName??"dataLayer",K=p((...e)=>{y&&console.info("[buildbase:tracking]",...e)},[y]);u(()=>{return e=()=>{0!==Object.keys(j.current).length&&window.dispatchEvent("function"==typeof PageTransitionEvent?new PageTransitionEvent("pagehide",{persisted:!1}):new Event("pagehide"))},Qt.add(e),()=>{Qt.delete(e)};var e},[]),u(()=>{if(!(a&&e&&n&&r))return void I(!0);let t=!1;const i=`${e.replace(/\/$/,"")}/api/v1/public/${n}/tracking?clientId=${encodeURIComponent(r)}`;return fetch(i).then(e=>e.ok?e.json():null).then(e=>{if(t||!e)return;const n=e.data??e;n&&Array.isArray(n.scripts)&&k(n)}).catch(()=>{K("config fetch failed; nothing installed")}).finally(()=>{t||I(!0)}),()=>{t=!0}},[a,e,n,r,K]),u(()=>{a&&M(Li())},[a]);const Q="auto"===P?A??v?.consent?.defaults??null:null,Z=s(()=>v?"auto"!==P?P:A?ss(A,v.country,v.region):v.consent?.defaults?v.resolvedConsentDefault??ss(v.consent.defaults,v.country,v.region):"denied":null,[v,P,A]),X=_??("granted"===Z?{analytics:!0,marketing:!0}:null),ee=!!v?.enhancedConversions&&!!X?.marketing,te=!!v?.scripts?.some(e=>"ga4"===e.provider||"google_ads"===e.provider||"gtm"===e.provider),ne=Q?JSON.stringify(Q):"";u(()=>{a&&v?.enabled&&(zs(Y),function(e,t,n={}){const r=os();if(!r)return;Array.isArray(r[e])||(r[e]=[]),"function"!=typeof r.gtag&&(r.gtag=function(){r[e].push(arguments)});const a=r.gtag,i="auto"===t?n.regional:null;let s="granted"===t?"granted":"denied";if(i){const e=as(i.regions?.denied),t=as(i.regions?.granted).filter(t=>!e.includes(t));e.length&&a("consent","default",{...ls("denied"),region:e,wait_for_update:500}),t.length&&a("consent","default",{...ls("granted"),region:t}),s=i.default}a("consent","default",{...ls(s),..."denied"===s?{wait_for_update:500}:{}}),n.google&&(a("set","url_passthrough",!0),a("set","ads_data_redaction","granted"!==(n.resolved??s)))}(Y,P,{regional:ne?JSON.parse(ne):null,resolved:Z,google:te}),U.current&&ds(U.current))},[a,v?.enabled,Y,P,ne,te]);const re=s(()=>v?.enabled?v.scripts.filter(e=>{const t=Us(e.provider)&&_s[e.provider].supportsConsentMode;return function(e,t,n,r){return"denied"!==r&&("granted"===r||!!t||!!n&&("marketing"===e?n.marketing:n.analytics))}(e.consentCategory,t,X,P)}):[],[v,_,Z,P]),[ae,ie]=h(()=>"undefined"==typeof window||!Mi(window.location.search));u(()=>{if(ae)return;const e=setInterval(()=>{Mi(window.location.search)||ie(!0)},50),t=setTimeout(()=>ie(!0),5e3);return()=>{clearInterval(e),clearTimeout(t)}},[ae]),u(()=>{if(!ae)return;if(!a||!v?.enabled)return void(S&&x(!0));let e=0;for(const t of re)if(!j.current[t.key]){if("external"===t.provider){if(!Fs({src:t.src,dataAttributes:t.dataAttributes})){K("rejected external script",t.key);continue}}else{if(!Us(t.provider)){K("rejected unknown provider",t.provider);continue}if(!Rs(t.provider,t.providerId)){K("rejected id for",t.provider);continue}if(Hs(t.provider,t.providerId??"")){K(`${t.provider} ${t.providerId} is already on the page; skipping. Configure each tag in exactly one place.`);continue}}Ks(t,Y,b.current)&&(j.current[t.key]=t.providerId??t.src??"",e+=1,K("installed",t.key))}e&&B(e=>e+1);const t=window;t.__buildbase=t.__buildbase??{},t.__buildbase.tracking={installed:{...j.current},dataLayerName:Y,clientId:r};const n=Object.keys(j.current).length>0,i=null!==X||0===v.scripts.length;(n||i)&&x(!0)},[a,v,re,S,_,Z,Y,K,ae,r]),u(()=>{if(!a||!o||!v?.enabled)return;if("undefined"==typeof window)return;if(!ae)return;let e=null;const t=()=>{e&&clearTimeout(e),e=setTimeout(()=>function(e,t){const n=Ms();if(!n)return;const r=n[t];Array.isArray(r)&&r.push({event:"page_view",page_path:n.location.pathname,page_location:n.location.href,page_title:n.document.title});for(const t of e)switch(t.provider){case"ga4":n.gtag?.("event","page_view",{send_to:t.providerId,page_path:n.location.pathname,page_location:n.location.href,page_title:n.document.title});break;case"meta_pixel":n.fbq?.("track","PageView");break;case"tiktok":{const e=n.ttq;e?.page?.();break}case"reddit":n.rdt?.("track","PageVisit")}}(re,Y),50)},n=window.history,r=n.pushState,i=n.replaceState;return n.pushState=function(...e){const n=r.apply(this,e);return t(),n},n.replaceState=function(...e){const n=i.apply(this,e);return t(),n},window.addEventListener("popstate",t),()=>{n.pushState=r,n.replaceState=i,window.removeEventListener("popstate",t),e&&clearTimeout(e)}},[a,o,v?.enabled,re,Y,ae]),u(()=>{if(!a)return;const e=function(e,t){const n=e?.mode??"auto",r=e?.overrides??{};if(("manual"===n||Object.values(r).some(e=>"manual"===e))&&!t)return'[buildbase:tracking] events are set to "manual" but no onEvent handler was provided, so those events would never fire anywhere. Pass onEvent, or use mode "auto".';for(const e of Object.keys(r))if(!$s(e))return`[buildbase:tracking] unknown event "${e}" in events.overrides. Overrides only apply to the events the SDK fires itself.`;return null}(c,!!d);if(e)throw new Error(e)},[a,c,d]);const se=p((e,t={},n)=>{if(!a)return;const r=n?.eventId||xs(),i=c?.mode??"auto",s=($s(e)?c?.overrides?.[e]:void 0)??i,o={...W.current,...F.current,...$,...t},l=O.current?.({name:e,params:o})??{},d={...o,...l},u=R.current?.({name:e,params:d,eventId:r,handledBy:s});"manual"!==s&&!0!==u?(ee&&V.current&&vs(re,V.current),function(e,t,n,r,a){const i=Ms();if(!i)return;const s=i[a];Array.isArray(s)&&s.push({event:e,...t,event_id:n});const o=$s(e)?Ls[e]:{ga4:e,meta:null,tiktok:null,reddit:null};for(const a of r){const r=a.provider,s=_s[r];if(s){if(s.needsConversionIds){const s=a.conversionIds?.[e];if(!s)continue;"google_ads"===r?i.gtag?.("event","conversion",{send_to:`${a.providerId}/${s}`,transaction_id:n,...t}):"x_pixel"===r?i.twq?.("event",s,{...t,conversion_id:n}):"linkedin"===r&&i.lintrk?.("track",{conversion_id:s});continue}switch(r){case"ga4":o.ga4&&i.gtag?.("event",o.ga4,{...t,send_to:a.providerId,event_id:n});break;case"meta_pixel":o.meta&&i.fbq?.("track",o.meta,t,{eventID:n});break;case"tiktok":if(o.tiktok){const e=i.ttq;e?.track?.(o.tiktok,{...t,event_id:n})}break;case"reddit":o.reddit&&i.rdt?.("track",o.reddit,{...t,conversionId:n});break;case"bing_uet":{const r=i.uetq;r?.push?.("event",o.ga4??e,{...t,event_id:n});break}case"clarity":i.clarity?.("event",e);break;case"hotjar":{const t=i.hj;t?.("event",e);break}case"posthog":{const r=i.posthog;r?.capture?.(e,{...t,event_id:n});break}case"plausible":i.plausible?.(e,{props:t})}}}}(e,d,r,re,Y),K("event fired:",e,r)):K("event handled by app:",e)},[a,c,re,Y,$,K,ee]),oe=p(async(t,r={})=>{const a=function(e){return{name:"trial_started"===e.kind?"trial_started":"purchase",params:{...e.workspaceId?{workspace_id:e.workspaceId}:{},...e.planVersionId?{plan_version_id:e.planVersionId}:{},...e.creditPackageId?{credit_package_id:e.creditPackageId}:{},...e.billingInterval?{billing_interval:e.billingInterval}:{},...e.currency?{currency:e.currency.toUpperCase()}:{},..."number"==typeof e.value?{value:e.value}:{},...e.sessionId?{transaction_id:e.sessionId}:{}}}}(t);let i=a.params;if(t.sessionId&&e&&n){const r=await async function(e,t){try{const n=e.serverUrl.replace(/\/$/,""),r=await fetch(`${n}/api/v1/public/${encodeURIComponent(e.orgId)}/checkout/${encodeURIComponent(t)}`,{credentials:"omit",..."undefined"!=typeof AbortSignal&&AbortSignal.timeout?{signal:AbortSignal.timeout(2e3)}:{}});if(!r.ok)return null;const a=await r.json(),i=a?.data??a;return"number"!=typeof i?.amount?null:{value:ts(i.amount,i.currency),currency:"string"==typeof i.currency?i.currency:void 0,...Array.isArray(i.items)&&i.items.length?{items:i.items}:{}}}catch{return null}}({serverUrl:e,orgId:n},t.sessionId);r&&"number"==typeof r.value&&(i={...i,value:r.value,...r.currency?{currency:r.currency.toUpperCase()}:{},...r.items?.length?{items:r.items}:{}})}if(se(a.name,{...i,...r},{eventId:t.eventId}),"purchase"===a.name&&t.sessionId&&e&&n){const r=(v?.scripts??[]).find(e=>"ga4"===e.provider&&e.providerId);r&&Hs("ga4",r.providerId??"")&&function(e,t,n){try{const r=e.serverUrl.replace(/\/$/,"");fetch(`${r}/api/v1/public/${encodeURIComponent(e.orgId)}/checkout/${encodeURIComponent(t)}/reported`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:n}),keepalive:!0,credentials:"omit"}).catch(()=>{})}catch{}}({serverUrl:e,orgId:n},t.sessionId,"ga4")}},[e,n,se,v]),[ce]=h(()=>"undefined"==typeof window?"":window.location.search);u(()=>{if(!a||!C)return;if("undefined"==typeof window)return;const e=Qi(window.location.search);if(e)return void oe(e);const t=Zi(ce);t&&se("checkout_abandoned",{...t.workspaceId?{workspace_id:t.workspaceId}:{},...t.planVersionId?{plan_version_id:t.planVersionId}:{},...t.creditPackageId?{credit_package_id:t.creditPackageId}:{},...t.billingInterval?{billing_interval:t.billingInterval}:{},...t.currency?{currency:t.currency.toUpperCase()}:{},..."number"==typeof t.value?{value:t.value}:{},seconds_at_checkout:Math.max(0,Math.round((Date.now()-t.startedAt)/1e3))})},[a,C,oe,ce,se]);const le=p((t,i)=>{U.current=t,T(t),ds(t),a&&ms({serverUrl:e,orgId:n,clientId:r,state:t,manifestVersion:H.current?.consent?.manifestVersion,source:i?.source,consentString:i?.consentString,headers:J.current})},[a,e,n,r]),de=p(e=>{J.current={...e}},[]),ue=p(e=>{if(!e)return V.current=null,void G(e=>e+1);bs(e).then(e=>{V.current=e.emailHash||e.phoneHash?e:null,G(e=>e+1)})},[]),pe=p((e,t)=>{const n=function(e){if(!e)return{traits:e,identity:null};const{email:t,phone:n,...r}=e,a={};return"string"==typeof t&&t&&(a.email=t),"string"==typeof n&&n&&(a.phone=n),{traits:r,identity:a.email||a.phone?a:null}}(t);n.identity&&ue(n.identity),function(e,t,n){const r=Ms();if(!r)return;const a=!!n&&Object.keys(n).length>0;for(const i of t)switch(i.provider){case"ga4":case"google_ads":r.gtag?.("set",{user_id:e}),a&&r.gtag?.("set",{user_properties:n});break;case"meta_pixel":i.providerId&&r.fbq?.("init",i.providerId,{external_id:e});break;case"posthog":r.posthog?.identify?.(e,a?n:void 0);break;case"clarity":if(r.clarity?.("identify",e),a)for(const[e,t]of Object.entries(n))r.clarity?.("set",e,String(t));break;case"hotjar":r.hj?.("identify",e,{});break;case"tiktok":{const t=r.ttq;t?.identify?.({external_id:e});break}}}(e,re,n.traits)},[re,ue]);u(()=>{ee&&V.current&&0!==Object.keys(j.current).length&&vs(re,V.current)},[ee,re,z,q]);const he=s(()=>({consent:{manifest:v?.consent?.manifest??[],state:_,effective:X,default:Z,country:v?.country??null,set:le},track:se,setUser:pe,setIdentity:ue,setConsentRecordHeaders:de,setProperties:D,getProperties:L,completeCheckout:oe,installed:{...j.current},ready:C,attribution:$}),[v,_,Z,le,se,pe,ue,de,D,L,oe,C,q,$]);return t(Xs.Provider,{value:he,children:w})};function ao(){const e=Pa(),t=$a(),n=ri();return s(()=>({auth:e,os:t,workspaces:n}),[e,t,n])}function io(e,t){const n=Ma(),r=_a(),a=ai(),i=p(e=>{const t=[n.subscribe(e),r.subscribe(e),a.subscribe(e)];return()=>t.forEach(e=>e())},[n,r,a]);return ba(s(()=>{let e=null;return()=>(null!==e&&e.os===n.getState()&&e.auth===r.getState()&&e.workspaces===a.getState()||(e={os:n.getState(),auth:r.getState(),workspaces:a.getState()}),e)},[n,r,a]),i,e,t)}function so(e,t,n){u(()=>{const t=new AbortController;return e(t.signal).catch(e=>{me(e)||(n?.onError?n.onError(e):be(e,{component:"useAsyncEffect",action:"effect",metadata:{note:"Unhandled rejection - consider passing onError"}}))}),()=>t.abort()},t)}function oo(){return io(e=>e.os)}ro.displayName="BuildBaseTracking";const co=new Map;let lo=null;function uo(){const e=ao(),t=oo(),{serverUrl:n,version:r,orgId:a,settings:i,settingsStatus:o,settingsError:c}=t,l=s(()=>xt(t)?new rt({serverUrl:n,version:r,orgId:a}):null,[n,r,a]),d=p(async t=>{if(!l)return null;const i=((e,t,n)=>`${e}|${t}|${n}`)(n,r,a);lo=i;const s=co.get(i);if(s)return s;const o=(async()=>{e.os(Ra("loading"));try{const t=await l.getSettings();return lo===i&&e.os(Ua(t)),t}catch(t){return lo===i&&e.os(Ra("error",t instanceof Error?t.message:"Failed to load settings")),ve(t,{component:"useSaaSSettings",action:"getSettings",metadata:{serverUrl:n,version:r,orgId:a}}),null}finally{co.delete(i)}})();return co.set(i,o),o},[l,e,n,r,a]);so(async()=>{i||xt(t)&&await d()},[n,r,a],{onError:e=>ve(e,{component:"useSaaSSettings",action:"fetchSettings",metadata:{serverUrl:n,version:r,orgId:a}})});const u="loading"===o||("idle"===o||void 0===o)&&xt(t);return s(()=>({settings:i,loading:u,error:c??null,refetch:d,getSettings:d}),[i,u,c,d])}function po(){const e=oo(),t=ao(),n=p(()=>{Ue(),t.auth(wa.removeSession()),e.auth?.callbacks?.onSessionExpired?.("expired")},[t,e.auth?.callbacks?.onSessionExpired]),r=function(e,t){return s(()=>new It({...e,onUnauthorized:t}),[e.serverUrl,e.version,e.orgId,t])}(e,n);return s(()=>({os:e,api:r}),[e,r])}const ho=e=>{const{t:t}=Si(),{os:n,api:r}=po(),a=xt(n),[i,s]=h(null),[o,c]=h(!1),[l,d]=h(null),[m,g]=h(null),{begin:f,settle:y}=xi(),w=p(async()=>{if(!e||!a)return f(),s(null),g(null),void c(!1);const n=f();c(!0),d(null);try{const t=await r.getPublicPlans(e);if(n.signal.aborted)return;s(t),g(e)}catch(r){if(n.signal.aborted)return;g(e);const a=ke(r,"errors.fetchPlans",t);d(a),be(r,{component:"usePublicPlans",action:"fetchPlans",metadata:{slug:e}})}finally{y(n)&&c(!1)}},[r,e,a,f,y]);u(()=>{w()},[w]);const b=!(!e||a&&m===e),v=b||o;return{items:b?[]:i?.items??[],plans:b?[]:i?.plans??[],notes:b?void 0:i?.notes,loading:v,error:l,refetch:w}},mo=e=>{const{t:t}=Si(),{api:n}=po(),[r,a]=h(null),[i,s]=h(!1),[o,c]=h(null),{begin:l,settle:d}=xi(),m=p(async()=>{if(!e)return l(),a(null),void s(!1);const r=l();s(!0),c(null);try{const t=await n.getPlanGroupVersion(e);if(r.signal.aborted)return;a(t)}catch(n){if(r.signal.aborted)return;const a=ke(n,"errors.fetchPlanGroupVersion",t);c(a),be(n,{component:"usePublicPlanGroupVersion",action:"fetchVersion",metadata:{groupVersionId:e}})}finally{d(r)&&s(!1)}},[n,e,l,d]);return u(()=>{m()},[m]),{planGroupVersion:r,loading:i,error:o,refetch:m}},go=e=>{const{t:t}=Si(),{os:n,api:r}=po(),[a,i]=h(null),[s,o]=h(!1),[c,l]=h(null),[d,m]=h(null),{begin:g,settle:f}=xi(),y=p(async()=>{if(!e)return g(),i(null),m(null),void o(!1);const a=g();o(!0),l(null);try{const t=await Ci(`subscription:${n.serverUrl}:${n.orgId}:${e}`,()=>r.getCurrentSubscription(e));if(a.signal.aborted)return;i(t),m(e)}catch(n){if(a.signal.aborted)return;m(e);const r=ke(n,"errors.fetchSubscription",t);l(r),be(n,{component:"useSubscription",action:"fetchSubscription",metadata:{workspaceId:e}})}finally{f(a)&&o(!1)}},[r,n.serverUrl,n.orgId,e,g,f]);u(()=>{y()},[y]),u(()=>Dt(y),[y]);const w=!!e&&d!==e;return{subscription:w?null:a,loading:s||w,error:c,refetch:y}},fo=(e,t)=>{const{t:n}=Si(),{api:r}=po(),[a,i]=h(null),[s,o]=h(!1),[c,l]=h(null),{begin:d,settle:m}=xi(),g=p(async()=>{if(!e)return d(),i(null),void o(!1);const a=d();o(!0),l(null);try{const n=t?await r.getPlanGroupByVersion(e,t):await r.getPlanGroup(e);if(a.signal.aborted)return;i(n)}catch(r){if(a.signal.aborted)return;const i=ke(r,"errors.fetchPlanGroup",n);l(i),be(r,{component:"usePlanGroup",action:"fetchPlanGroup",metadata:{workspaceId:e,groupVersionId:t}})}finally{m(a)&&o(!1)}},[r,e,t,d,m]);return u(()=>{g()},[g]),{planGroup:a,loading:s,error:c,refetch:g}},yo=e=>{const{t:t}=Si(),{api:n}=po(),[r,a]=h(null),[i,s]=h(!1),[o,c]=h(null),{begin:l,settle:d}=xi(),m=p(async()=>{if(!e)return l(),a(null),void s(!1);const r=l();s(!0),c(null);try{const t=await n.getPlanGroupVersions(e);if(r.signal.aborted)return;a(t)}catch(n){if(r.signal.aborted)return;const a=ke(n,"errors.fetchPlanGroupVersions",t);c(a),be(n,{component:"usePlanGroupVersions",action:"fetchVersions",metadata:{workspaceId:e}})}finally{d(r)&&s(!1)}},[n,e,l,d]);return u(()=>{m()},[m]),{versions:r,loading:i,error:o,refetch:m}},wo=e=>{const{t:t}=Si(),{api:n}=po(),{getCheckoutStripeParams:r}=d(si),{track:a,consent:i,getProperties:s}=to(),o=no(),[c,l]=h(!1),[u,m]=h(null);return{createCheckoutSession:p(async c=>{if(!e)throw new Error("Workspace ID is required");l(!0),m(null);const d=xs();try{const t=r?await r(c):void 0,l=o?Es(d,i.effective,s(),Ps({...c.stripeOptions?.metadata,...t?.metadata},{...c.stripeOptions?.subscriptionMetadata,...t?.subscriptionMetadata})):{},u=Object.keys(l).length>0||t?{...c,stripeOptions:{...c.stripeOptions,...t,metadata:{...l,...c.stripeOptions?.metadata,...t?.metadata},subscriptionMetadata:{...l,...c.stripeOptions?.subscriptionMetadata,...t?.subscriptionMetadata}}}:c,p=await n.createCheckoutSession(e,u),h="checkout"!==p.type&&p.type?void 0:p,m=h?.currency??c.currency,g=ts(h?.amountTotal,m);return h&&o&&Vi({eventId:d,workspaceId:e,planVersionId:c.planVersionId,billingInterval:c.billingInterval,currency:m,sessionId:h.sessionId,value:g,kind:h.trial?"trial_started":"purchase",startedAt:Date.now()}),a("trial_started"===p.type?"trial_started":"checkout_started",{plan_version_id:c.planVersionId,...c.billingInterval?{billing_interval:c.billingInterval}:{},...m?{currency:m.toUpperCase()}:{},..."number"==typeof g?{value:g}:{}},{eventId:d}),"trial_started"===p.type&&($t(),Ft()),p}catch(n){const r=ke(n,"errors.createCheckout",t);throw m(r),be(n,{component:"useCreateCheckoutSession",action:"createCheckoutSession",metadata:{workspaceId:e,request:c}}),n}finally{l(!1)}},[n,e,r,a,t,i.effective,o]),loading:c,error:u}},bo=e=>{const{t:t}=Si(),{api:n}=po(),{track:r}=to(),a=no(),[i,s]=h(!1),[o,c]=h(null);return{updateSubscription:p(async(i,o)=>{if(!e)throw new Error("Workspace ID is required");s(!0),c(null);try{const t={planVersionId:i,...o?.billingInterval&&{billingInterval:o.billingInterval},...o?.successUrl&&{successUrl:o.successUrl},...o?.cancelUrl&&{cancelUrl:o.cancelUrl}},s=xs(),c=await n.updateSubscription(e,t),l="checkoutUrl"in c&&c.checkoutUrl?c:null;if(l){const t=l.currency,n=ts(l.amountTotal,t);a&&Vi({eventId:s,workspaceId:e,planVersionId:i,billingInterval:o?.billingInterval,currency:t,sessionId:l.sessionId,value:n,kind:l.trial?"trial_started":"purchase",startedAt:Date.now()}),r("checkout_started",{plan_version_id:i,...o?.billingInterval?{billing_interval:o.billingInterval}:{},...t?{currency:t.toUpperCase()}:{},..."number"==typeof n?{value:n}:{}},{eventId:s})}else if(!c.paymentRequired){const e=c,t=e.invoice?.amount_due;r("subscription_upgraded",{plan_version_id:i,...o?.billingInterval?{billing_interval:o.billingInterval}:{},..."number"==typeof t&&t>0?{value:ts(t,void 0)}:{}},{eventId:s})}return $t(),c}catch(n){const r=ke(n,"errors.updateSubscription",t);throw c(r),be(n,{component:"useUpdateSubscription",action:"updateSubscription",metadata:{workspaceId:e,planVersionId:i,options:o}}),n}finally{s(!1)}},[n,e,r,a]),loading:i,error:o}},vo=(e,t)=>{const n=go(e),r=fo(e,t),a=bo(e),i=p(async()=>{await Promise.all([n.refetch(),r.refetch()])},[n.refetch,r.refetch]);return{subscription:n.subscription,planGroup:r.planGroup,loading:n.loading||r.loading||a.loading,error:n.error||r.error||a.error,updateSubscription:a.updateSubscription,refetch:i}},ko=(e,t=10,n)=>{const{t:r}=Si(),{api:a}=po(),[i,s]=h([]),[o,c]=h(!1),[l,d]=h(!1),[m,g]=h(null),{begin:f,settle:y}=xi(),w=p(async()=>{if(!e)return f(),s([]),c(!1),void d(!1);const i=f();d(!0),g(null);try{const r=await a.listInvoices(e,t,n);if(i.signal.aborted)return;s(r.invoices||[]),c(r.has_more||!1)}catch(a){if(i.signal.aborted)return;const s=ke(a,"errors.fetchInvoices",r);g(s),be(a,{component:"useInvoices",action:"fetchInvoices",metadata:{workspaceId:e,limit:t,startingAfter:n}})}finally{y(i)&&d(!1)}},[a,e,t,n,f,y]);return u(()=>{w()},[w]),{invoices:i,hasMore:o,loading:l,error:m,refetch:w}},So=e=>{const{t:t}=Si(),{api:n}=po(),[r,a]=h(!1),[i,s]=h(null);return{openBillingPortal:p(async r=>{if(!e)throw new Error("Workspace ID is required");a(!0),s(null);try{const t=r||window.location.href,a=await n.createBillingPortalSession(e,t);return a.url&&window.open(a.url,"_blank","noopener,noreferrer"),a}catch(n){const r=ke(n,"errors.openBillingPortal",t);throw s(r),be(n,{component:"useBillingPortal",action:"openBillingPortal",metadata:{workspaceId:e}}),n}finally{a(!1)}},[e,n]),loading:r,error:i}},Io=(e,t)=>{const{t:n}=Si(),{api:r}=po(),[a,i]=h(null),[s,o]=h(!1),[c,l]=h(null),{begin:d,settle:m}=xi(),g=p(async()=>{if(!e||!t)return d(),i(null),void o(!1);const a=d();o(!0),l(null);try{const n=await r.getInvoice(e,t);if(a.signal.aborted)return;i(n.invoice)}catch(r){if(a.signal.aborted)return;const i=ke(r,"errors.fetchInvoice",n);l(i),be(r,{component:"useInvoice",action:"fetchInvoice",metadata:{workspaceId:e,invoiceId:t}})}finally{m(a)&&o(!1)}},[r,e,t,d,m]);return u(()=>{g()},[g]),{invoice:a,loading:s,error:c,refetch:g}},Co=e=>{const{t:t}=Si(),{api:n}=po(),[r,a]=h(!1),[i,s]=h(null);return{cancelSubscription:p(async()=>{if(!e)throw new Error("Workspace ID is required");a(!0),s(null);try{const t=await n.cancelSubscriptionAtPeriodEnd(e);return $t(),t}catch(n){const r=ke(n,"errors.cancelSubscription",t);throw s(r),be(n,{component:"useCancelSubscription",action:"cancelSubscription",metadata:{workspaceId:e}}),n}finally{a(!1)}},[n,e]),loading:r,error:i}},xo=e=>{const{t:t}=Si(),{api:n}=po(),[r,a]=h(!1),[i,s]=h(null);return{resumeSubscription:p(async()=>{if(!e)throw new Error("Workspace ID is required");a(!0),s(null);try{const t=await n.resumeSubscription(e);return $t(),t}catch(n){const r=ke(n,"errors.resumeSubscription",t);throw s(r),be(n,{component:"useResumeSubscription",action:"resumeSubscription",metadata:{workspaceId:e}}),n}finally{a(!1)}},[n,e]),loading:r,error:i}},No=e=>{const{t:t}=Si(),{api:n}=po(),[r,a]=h(!1),[i,s]=h(null);return{recordUsage:p(async r=>{if(!e)throw new Error("Workspace ID is required");a(!0),s(null);try{const t=await n.recordUsage(e,r);return Ft(),t}catch(n){const a=ke(n,"errors.recordUsage",t);throw s(a),be(n,{component:"useRecordUsage",action:"recordUsage",metadata:{workspaceId:e,request:r}}),n}finally{a(!1)}},[n,e]),loading:r,error:i}},Ao=(e,t)=>{const{t:n}=Si(),{api:r}=po(),[a,i]=h(null),[s,o]=h(!1),[c,l]=h(null),{begin:d,settle:m}=xi(),g=p(async()=>{if(!e||!t)return d(),i(null),void o(!1);const a=d();o(!0),l(null);try{const n=await r.getQuotaUsageStatus(e,t);if(a.signal.aborted)return;i(n)}catch(r){if(a.signal.aborted)return;const i=ke(r,"errors.fetchQuotaUsage",n);l(i),be(r,{component:"useQuotaUsageStatus",action:"fetchStatus",metadata:{workspaceId:e,quotaSlug:t}})}finally{m(a)&&o(!1)}},[r,e,t,d,m]);return u(()=>{g()},[g]),{status:a,loading:s,error:c,refetch:g}},Po=e=>{const{t:t}=Si(),{os:n,api:r}=po(),[a,i]=h(null),[s,o]=h(!1),[c,l]=h(null),[d,m]=h(null),{begin:g,settle:f}=xi(),y=p(async()=>{if(!e)return g(),i(null),m(null),void o(!1);const a=g();o(!0),l(null);try{const t=await Ci(`quota-usage:${n.serverUrl}:${n.orgId}:${e}`,()=>r.getAllQuotaUsage(e));if(a.signal.aborted)return;i(t.quotas),m(e)}catch(n){if(a.signal.aborted)return;m(e);const r=ke(n,"errors.fetchAllQuotaUsage",t);l(r),be(n,{component:"useAllQuotaUsage",action:"fetchAllUsage",metadata:{workspaceId:e}})}finally{f(a)&&o(!1)}},[r,n.serverUrl,n.orgId,e,g,f]);u(()=>{y()},[y]),u(()=>Wt(y),[y]);const w=!!e&&d!==e;return{quotas:w?null:a,loading:s||w,error:c,refetch:y}},Eo=(e,t,n)=>{const{t:r}=Si(),{api:a}=po(),[i,s]=h([]),[o,c]=h(0),[l,d]=h(0),[m,g]=h(1),[f,y]=h(!1),[w,b]=h(!1),[v,k]=h(!1),[S,I]=h(null),{begin:C,settle:x}=xi(),N=n?.from,A=n?.to,P=n?.source,E=n?.page,_=n?.limit,T=p(async()=>{if(!e)return C(),s([]),c(0),d(0),g(1),y(!1),b(!1),void k(!1);const n=C();k(!0),I(null);try{const r={...t&&{quotaSlug:t},...N&&{from:N},...A&&{to:A},...P&&{source:P},...E&&{page:E},..._&&{limit:_}},i=await a.getUsageLogs(e,r);if(n.signal.aborted)return;s(i.docs||[]),c(i.totalDocs||0),d(i.totalPages||0),g(i.page||1),y(i.hasNextPage||!1),b(i.hasPrevPage||!1)}catch(a){if(n.signal.aborted)return;const i=ke(a,"errors.fetchUsageLogs",r);I(i),be(a,{component:"useUsageLogs",action:"fetchLogs",metadata:{workspaceId:e,quotaSlug:t}})}finally{x(n)&&k(!1)}},[a,e,t,N,A,P,E,_,C,x]);return u(()=>{T()},[T]),{logs:i,totalDocs:o,totalPages:l,page:m,hasNextPage:f,hasPrevPage:w,loading:v,error:S,refetch:T}},_o=c(null);_o.displayName="SubscriptionContext";const To=a.memo(function({children:e}){const n=io(e=>e.workspaces.currentWorkspace),{subscription:r,loading:a,error:i,refetch:o}=go(n?._id),c=s(()=>({response:r,loading:a,error:i,refetch:o}),[r,a,i,o]);return t(_o.Provider,{value:c,children:e})});function Uo(){const e=d(_o);if(null===e)throw new Error("useSubscriptionContext must be used within SubscriptionContextProvider. Make sure SubscriptionContextProvider is wrapping your application (or the tree that uses subscription gates).");return e}To.displayName="SubscriptionContextProvider";const Ro=({message:r})=>e(n,{children:[t("div",{className:"bb-fs-loader-spinner",style:{width:40,height:40,border:"3px solid hsl(var(--muted, 210 40% 96%))",borderTopColor:"hsl(var(--muted-foreground, 215.4 16.3% 46.9%))",borderRadius:"50%",animation:"bb-fs-loader-spin 0.6s linear infinite"}}),t("p",{"aria-hidden":"true",style:{marginTop:16,color:"hsl(var(--muted-foreground, 215.4 16.3% 46.9%))",fontSize:14},children:r}),t("style",{children:"\n @keyframes bb-fs-loader-spin { to { transform: rotate(360deg) } }\n @media (prefers-reduced-motion: reduce) {\n .bb-fs-loader-spinner { animation: none !important; }\n }\n @media (prefers-color-scheme: dark) {\n .bb-fs-loader-spinner {\n border-color: hsl(var(--muted, 217.2 32.6% 17.5%)) !important;\n border-top-color: hsl(var(--muted-foreground, 215 20.2% 65.1%)) !important;\n }\n }\n "})]}),Oo=({children:n,message:r,backgroundColor:a})=>{const{t:i}=Si(),s=r??i("settings.common.loading");return e("div",{role:"status","aria-live":"polite","aria-busy":"true",className:"bb-fs-loader",style:{position:"fixed",inset:0,zIndex:2147483647,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",backgroundColor:a??void 0},children:[t("span",{style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0,0,0,0)",whiteSpace:"nowrap",border:0},children:s}),n??t(Ro,{message:s}),t("style",{children:"\n .bb-fs-loader {\n background-color: hsl(var(--background, 0 0% 100%));\n }\n @media (prefers-color-scheme: dark) {\n .bb-fs-loader {\n background-color: hsl(var(--background, 222.2 84% 4.9%));\n }\n .bb-fs-loader p {\n color: hsl(var(--muted-foreground, 215 20.2% 65.1%)) !important;\n }\n }\n "})]})};Oo.displayName="FullScreenLoader";const Wo=c(null),Fo=({children:n,loadingComponent:r})=>{const[a,i]=h({visible:!1,message:""}),o=l(null),c=p(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),d=p(()=>{c(),i({visible:!1,message:""})},[c]),m=p(e=>{c(),i({visible:!0,message:e}),o.current=setTimeout(()=>{be(new Error("FullScreenLoader timed out — auto-hiding after 60s"),{component:"FullScreenLoaderProvider",action:"timeout"}),i({visible:!1,message:""})},6e4)},[c]);u(()=>()=>c(),[c]);const g=s(()=>({show:m,hide:d,visible:a.visible,message:a.message}),[m,d,a.visible,a.message]),f="function"==typeof r?r({message:a.message}):r;return e(Wo.Provider,{value:g,children:[n,a.visible&&t(Oo,{message:a.message,children:f})]})};function Lo(){const e=d(Wo);if(!e)throw new Error("useFullScreenLoader must be used within FullScreenLoaderProvider");return e}Fo.displayName="FullScreenLoaderProvider";const Do="saas-oauth-state";function $o(){Ce(Do)}function Mo(e={}){const t={};for(const[n,r]of Object.entries(e))null!=r&&""!==r&&("string"==typeof r?t[n]=r.slice(0,100):("number"==typeof r?Number.isFinite(r):"boolean"==typeof r)&&(t[n]=r));return t}const jo=new Set;function qo(e){return!jo.has(e)&&(jo.add(e),!0)}function Bo(e,t,n,r){const{emitOnce:a}=Vo(),i=l(r);i.current=r,u(()=>{e&&a(t,n,i.current)},[e,t,n,a])}function Vo(){const{track:e,ready:t}=to(),n=p((t,n)=>{try{e(t,Mo(n))}catch{}},[e]),r=p((e,r,a)=>{t&&qo(`${r}|${e}`)&&n(r,a)},[n,t]);return{emit:n,emitOnce:r,ready:t}}const zo=c({});function Go({ui:e,children:n}){const r=s(()=>e??{},[e]);return t(zo.Provider,{value:r,children:n})}function Jo(){return d(zo)}function Ho(e,t){return t?Yo(e,t):e}function Yo(e,t){if(!e||!t||"object"!=typeof e||"object"!=typeof t||Array.isArray(e)||Array.isArray(t))return t;const n={...e};for(const[e,r]of Object.entries(t))n[e]=e in n?Yo(n[e],r):r;return n}const Ko={rows:[],loading:!1,error:null,fetchedAt:0};class Qo{constructor(){this.snapshot=Ko,this.listeners=new Set,this.inFlight=null,this.generation=0,this.getSnapshot=()=>this.snapshot,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e))}set(e){this.snapshot={...this.snapshot,...e};for(const e of this.listeners)e()}load(e,t){if(this.inFlight)return this.inFlight;const n=t.maxAgeMs??0;if(n>0&&this.snapshot.fetchedAt&&Date.now()-this.snapshot.fetchedAt<n)return Promise.resolve();const r=this.generation;return this.set({loading:!0,error:null}),this.inFlight=e().then(e=>{r===this.generation&&this.set({rows:aa(e),fetchedAt:Date.now()})}).catch(e=>{r===this.generation&&this.set({error:t.onError(e)})}).finally(()=>{this.inFlight=null,r===this.generation&&this.set({loading:!1})}),this.inFlight}remove(e){this.set({rows:this.snapshot.rows.filter(t=>t._id!==e)})}setError(e){this.set({error:e})}reset(){this.generation++,this.inFlight=null,this.snapshot=Ko;for(const e of this.listeners)e()}}const Zo=new Map;function Xo(e){const t=e||"unscoped";let n=Zo.get(t);return n||(n=new Qo,Zo.set(t,n)),n}const ec={Profile:"profile",Security:"security",Devices:"devices",ConnectedAgents:"connected-agents",General:"general",Users:"users",Subscription:"subscription",Usage:"usage",Credits:"credits",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"},tc=new Set(Object.values(ec));const nc=new class{constructor(){this.listeners=new Set,this.currentState={open:!1,section:ec.Profile}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getState(){return this.currentState}openWorkspaceSettings(e,t){this.currentState={open:!0,section:e||ec.Profile,params:t},this.notifyListeners()}closeSettings(){this.currentState={...this.currentState,open:!1,params:void 0},this.notifyListeners()}setSection(e){this.currentState={...this.currentState,section:e},this.notifyListeners()}clearParams(){void 0!==this.currentState.params&&(this.currentState={...this.currentState,params:void 0},this.notifyListeners())}notifyListeners(){this.listeners.forEach(e=>{e(this.currentState)})}},rc=c(null);rc.displayName="WorkspaceActionsContext";const ac=({children:e})=>{const n=ao(),{os:r,api:i}=po(),{settings:o}=uo(),{t:c}=Si(),l=a.useRef(c);u(()=>{l.current=c},[c]);const d=io(e=>e.workspaces),h=io(e=>e.auth.session?.user),m=a.useRef(!1),g=a.useRef(!1),f=a.useRef(0),y=p((e,t)=>{if((!(e._id===d.currentWorkspace?._id)||t?.forceEmit)&&e){const t=d.currentWorkspace;tr(e),n.workspaces(Ga(e)),Pt.emitWorkspaceChanged(e,t).catch(t=>{be(t,{component:"WorkspaceProvider",action:"emitWorkspaceChanged",metadata:{workspaceId:e._id}})})}},[d.currentWorkspace,n]),w=p(async(e,t)=>{const a=++f.current;n.workspaces(Za(e._id));try{const n=r.auth?.callbacks?.onWorkspaceChange;if(n){const t=sr(e,h?.id);try{await n({workspace:e,user:h??null,role:t})}catch(t){throw be(t,{component:"WorkspaceProvider",action:"onWorkspaceChange",metadata:{workspaceId:e._id}}),t}if(a!==f.current)return}y(e,t)}finally{a===f.current&&n.workspaces(Za(null))}},[n,r.auth?.callbacks?.onWorkspaceChange,y,h]),b=a.useRef(w);b.current=w,u(()=>{if(!d.isInitialized){const e=nr();if(n.workspaces(Ha(!0)),e){const t=d.workspaces.find(t=>t._id===e);t&&b.current(t,{forceEmit:!0}).catch(t=>{be(t,{component:"WorkspaceProvider",action:"initWorkspaceSwitch",metadata:{savedWorkspaceId:e}})})}}},[d.isInitialized,d.workspaces,n]);const v=p(()=>{rr(),n.workspaces(Ja())},[n]),k=p(async()=>{if(!d.loading&&!m.current){m.current=!0,n.workspaces(Ya(!0)),n.workspaces(Ka(null));try{const e=await i.getWorkspaces();if(n.workspaces(ja(e)),e.length>0){const t=nr();if(t&&ar(t,e)){const n=e.find(e=>e._id===t);if(n)try{await w(n,{forceEmit:!0})}catch{}}else{const t=e[0];try{await w(t,{forceEmit:!0})}catch{}}}}catch(e){n.workspaces(Ka(ke(e,"errors.fetchWorkspaces",l.current)))}finally{n.workspaces(Ya(!1)),m.current=!1}}},[i,d.loading,n,w]),S=p(async()=>{if(!d.refreshing&&!m.current){m.current=!0,n.workspaces(Qa(!0));try{const e=await i.getWorkspaces();n.workspaces(ja(e))}catch(e){}finally{n.workspaces(Qa(!1)),m.current=!1}}},[i,d.refreshing,n]),I=a.useRef(null),C=Jo(),x=!1!==C.behavior?.autoOpenPlanDialog&&!1!==C.settings?.sections?.subscription,N=a.useRef(x);N.current=x,u(()=>()=>{I.current&&clearTimeout(I.current)},[]);const A=p(async(e,t)=>{const r=$i(),a=await i.createWorkspace({name:e,...t?{image:t}:{},...r?{trackingAttribution:r}:{}});n.workspaces(qa(a)),await w(a),Pt.emitWorkspaceCreated(a).catch(e=>{be(e,{component:"WorkspaceProvider",action:"emitWorkspaceCreated",metadata:{workspaceId:a._id}})}),I.current&&clearTimeout(I.current),I.current=null,N.current&&(I.current=setTimeout(()=>{I.current=null,nc.openWorkspaceSettings(ec.Subscription)},300))},[i,n,w]),P=p(async(e,t)=>{const r=await i.updateWorkspace(e._id,t);n.workspaces(Ba(r)),Pt.emitWorkspaceUpdated(r).catch(e=>{be(e,{component:"WorkspaceProvider",action:"emitWorkspaceUpdated",metadata:{workspaceId:r._id}})})},[i,n]),E=p(async()=>{if(g.current)return d.allFeatures.length>0?d.allFeatures:null;if(d.allFeatures.length>0)return d.allFeatures;g.current=!0;try{const e=await i.getFeatures();return n.workspaces(za(e)),e}catch(e){return be(e,{component:"WorkspaceProvider",action:"getFeatures"}),null}finally{g.current=!1}},[i,n,d.allFeatures]),_=p(async(e,t,n)=>await i.updateFeature(e,t,n),[i]),T=p(async e=>i.updateSettings(e),[i]),U=p(async(e,t)=>{const n=await i.updateWorkspacePermissions(e,t);return await S(),n},[i,S]);u(()=>{if(!d.currentWorkspace?._id||0===d.workspaces.length)return;const e=d.currentWorkspace._id,t=d.workspaces.find(t=>t._id===e);if(t)t!==d.currentWorkspace&&(tr(t),n.workspaces(Ga(t)));else if(d.workspaces.length>0){const t=d.workspaces[0];t._id!==e&&w(t).catch(e=>{be(e,{component:"WorkspaceProvider",action:"fallbackWorkspaceSwitch",metadata:{workspaceId:t._id}})})}},[d.workspaces,d.currentWorkspace,n,w]);const R=p(async e=>await i.getWorkspaceUsers(e),[i]),O=p(async(e,t,n)=>{const r=d.workspaces.find(t=>t._id===e);if(r){const e=Qn({settingsMaxUsers:o?.workspace?.maxWorkspaceUsers}),t=Zn({memberCount:r.users?.length??0,maxUsersConfig:e});if(!t.canInvite)throw new Error(t.blockMessageKey||"users.memberLimitReached")}const a=await i.addUser(e,{email:t,role:n});return r&&Pt.emitWorkspaceUserAdded(a.userId,r,n).catch(t=>{be(t,{component:"WorkspaceProvider",action:"emitWorkspaceUserAdded",metadata:{workspaceId:e,userId:a.userId,role:n}})}),S().catch(e=>{be(e,{component:"WorkspaceProvider",action:"refreshAfterAddUser"})}),$t(),a},[i,d.workspaces,S,o]),W=p(async(e,t)=>{const n=d.workspaces.find(t=>t._id===e);if(n&&ir(n,t))throw new Error("Cannot remove the workspace owner");const r=(await i.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===t),a=await i.removeUser(e,t);if(n&&r){const t=r.role;Pt.emitWorkspaceUserRemoved(a.userId,n,t).catch(n=>{be(n,{component:"WorkspaceProvider",action:"emitWorkspaceUserRemoved",metadata:{workspaceId:e,userId:a.userId,role:t}})})}return S().catch(e=>{be(e,{component:"WorkspaceProvider",action:"refreshAfterRemoveUser"})}),$t(),a},[i,d.workspaces,S]),F=p(async(e,t,n)=>{if(n.role){const n=d.workspaces.find(t=>t._id===e);if(n&&ir(n,t))throw new Error("Cannot change the role of the workspace owner")}let r;if(n.role){const n=(await i.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===t);r=n?.role}const a=await i.updateUser(e,t,n);return n.role&&r&&r!==n.role&&Pt.emitWorkspaceUserRoleChanged(a.userId,a.workspace,r,n.role).catch(a=>{be(a,{component:"WorkspaceProvider",action:"emitWorkspaceUserRoleChanged",metadata:{workspaceId:e,userId:t,previousRole:r,newRole:n.role}})}),a},[i,d.workspaces]),L=p(async e=>{const t=await i.getProfile().catch(()=>null),n=await i.updateUserProfile(e);return Pt.emitUserUpdated(n,t||void 0).catch(e=>{be(e,{component:"WorkspaceProvider",action:"emitUserUpdated",metadata:{userId:n._id}})}),n},[i]),D=p(async()=>await i.getProfile(),[i]),$=p(async e=>await i.getWorkspace(e),[i]),M=p(async e=>{if(!h)throw new Error("User must be authenticated to delete a workspace");const t=d.workspaces.find(t=>t._id===e);if(!t)throw new Error("Workspace not found");if(!ir(t,h.id))throw new Error("Only the workspace creator can delete the workspace");const r=await i.deleteWorkspace(e);return n.workspaces(Va(e)),d.currentWorkspace?._id===e&&(rr(),n.workspaces(Ja())),t&&Pt.emitWorkspaceDeleted(t).catch(t=>{be(t,{component:"WorkspaceProvider",action:"emitWorkspaceDeleted",metadata:{workspaceId:e}})}),r},[i,d.workspaces,d.currentWorkspace,n,h]),j=p(e=>i.listInvitations(e),[i]),q=p(async(e,t,n,r)=>{const a=await i.inviteMember(e,{email:t,role:n,landingUrl:r?.landingUrl});return Pt.emitWorkspaceInvitationSent(a,e).catch(t=>{be(t,{component:"WorkspaceProvider",action:"emitWorkspaceInvitationSent",metadata:{workspaceId:e,invitationId:a._id}})}),$t(),a},[i]),B=p(async(e,t)=>{const n=await i.resendInvitation(e,t);return $t(),n},[i]),V=p(async(e,t)=>{await i.revokeInvitation(e,t),Pt.emitWorkspaceInvitationRevoked(t,e).catch(n=>{be(n,{component:"WorkspaceProvider",action:"emitWorkspaceInvitationRevoked",metadata:{workspaceId:e,invitationId:t}})}),$t()},[i]),z=p(()=>i.myInvitations(),[i]),G=p(async(e,t)=>{const a=await i.acceptInvitation(e,t),s=a.workspace;s&&!d.workspaces.some(e=>e._id===s._id)&&n.workspaces(qa(s)),S().catch(e=>{be(e,{component:"WorkspaceProvider",action:"refreshAfterAccept"})}),a.workspace&&Pt.emitWorkspaceInvitationAccepted(a.invitation,a.workspace).catch(t=>{be(t,{component:"WorkspaceProvider",action:"emitWorkspaceInvitationAccepted",metadata:{invitationId:e}})});const o=a.workspace;return h?.id&&o&&Pt.emitWorkspaceUserAdded(h.id,o,a.invitation.role).catch(t=>{be(t,{component:"WorkspaceProvider",action:"emitWorkspaceUserAdded",metadata:{workspaceId:o._id,invitationId:e}})}),$t(),Xo(r.orgId??"").remove(e),{invitation:a.invitation,workspace:a.workspace}},[i,S,h?.id,r.orgId,d.workspaces,n]),J=p(async e=>{const{invitation:t}=await i.declineInvitation(e);return Pt.emitWorkspaceInvitationDeclined(t).catch(t=>{be(t,{component:"WorkspaceProvider",action:"emitWorkspaceInvitationDeclined",metadata:{invitationId:e}})}),Xo(r.orgId??"").remove(e),t},[i,r.orgId]),H=p(e=>i.previewInvitation(e),[i]),Y=s(()=>({fetchWorkspaces:k,refreshWorkspaces:S,setCurrentWorkspace:y,switchToWorkspace:w,resetCurrentWorkspace:v,createWorkspace:A,updateWorkspace:P,deleteWorkspace:M,getWorkspace:$,getUsers:R,addUser:O,removeUser:W,updateUser:F,getProfile:D,updateUserProfile:L,getFeatures:E,updateFeature:_,updateWorkspaceSettings:T,updateWorkspacePermissions:U,listInvitations:j,inviteMember:q,resendInvitation:B,revokeInvitation:V,myInvitations:z,acceptInvitation:G,declineInvitation:J,previewInvitation:H}),[k,S,y,w,v,A,P,M,$,R,O,W,F,D,L,E,_,T,U,j,q,B,V,z,G,J,H]);return t(rc.Provider,{value:Y,children:e})};ac.displayName="WorkspaceProviderInner";const ic=({children:e})=>{const r=a.useContext(rc);return t(r?n:ac,{children:e})};ic.displayName="WorkspaceProvider";const sc=()=>{const e=a.useContext(rc);if(!e)throw new Error("useSaaSWorkspaces must be used within a WorkspaceProvider. Make sure SaaSOSProvider is wrapping your application.");const t=io(e=>e.workspaces);return s(()=>({workspaces:t.workspaces,loading:t.loading,error:t.error,refreshing:t.refreshing,currentWorkspace:t.currentWorkspace,allFeatures:t.allFeatures,switching:null!==t.switchingToId,switchingToId:t.switchingToId,...e}),[t,e])},oc=/^\+[1-9]\d{6,14}$/;function cc(e){return"string"==typeof e&&oc.test(e)}function lc(e){return!0===e.isAnonymous||"string"==typeof e.email&&e.email.endsWith("@anonymous.invalid")}function dc(e){return"string"==typeof e&&e&&Number.isFinite(Date.parse(e))?e:void 0}function uc(e){const t=dc(e.authTime),n=Array.isArray(e.amr)?e.amr.filter(e=>"string"==typeof e&&e.length>0):void 0,r=e.impersonation,a=dc(r?.expiresAt),i=r&&"object"==typeof r&&a?{actorName:"string"==typeof r.actorName?r.actorName:"",readOnly:!1!==r.readOnly,expiresAt:a}:void 0;return{...t?{authTime:t}:{},...n?{amr:n}:{},...i?{impersonation:i}:{}}}function pc(e){return!0===e.canChangeEmail?{canChangeEmail:!0}:"linked_social_account"===e.changeEmailBlockedBy?{canChangeEmail:!1,changeEmailBlockedBy:"linked_social_account"}:{canChangeEmail:!1}}function hc(e){return cc(e.phone)?{phone:e.phone,phoneVerified:!0===e.phoneVerified}:{}}function mc(e,t,n){const r=e._id||e.id;if(!r||"string"!=typeof r)throw new Error("User data missing required ID field");if(!e.email||"string"!=typeof e.email)throw new Error("User data missing required email field");const a=lc(e),i="string"==typeof e.username?e.username:"",s=dc(e.deleteAfter);return{id:r,name:e.name||"",org:t,email:a?"":e.email,emailVerified:!a&&!1!==e.emailVerified,clientId:n,role:e.role||"",image:e.image,createdAt:"string"==typeof e.createdAt?e.createdAt:void 0,firstAuthAt:"string"==typeof e.firstAuthAt?e.firstAuthAt:void 0,mfaEnabled:!0===e.mfaEnabled,...pc(e),..."string"==typeof e.externalId&&e.externalId?{externalId:e.externalId}:{},...hc(e),...i?{username:i}:{},claims:(o=e.claims,o&&"object"==typeof o&&!Array.isArray(o)?o:{}),isAnonymous:a,...s?{deleteAfter:s}:{}};var o}function gc(e,t,n={}){return{user:e,sessionId:t,expires:new Date(Date.now()+864e5).toISOString(),...n}}function fc(){return io(e=>e.auth)}function yc(){const{t:e}=Si(),t=ao(),n=fc(),r=oo(),{serverUrl:a,orgId:i,auth:o}=r,{resetCurrentWorkspace:c,currentWorkspace:l}=sc(),u=Lo(),{consent:h}=to(),{emit:m}=Vo(),g=d(mi).requestedLocale,f=s(()=>new Je({serverUrl:a,version:r.version}),[a,r.version]),{api:y}=po(),w=p(async n=>{nn(n||window.location.href),m("sign_in_started",{from_path:window.location.pathname}),t.auth(wa.authenticationStarted()),u.show(e("loading.redirecting"));try{const e=function(){const e=new Uint8Array(32);crypto.getRandomValues(e);const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return Ie(Do,t),t}(),{redirectUrl:t}=await f.requestAuth({orgId:i,clientId:o?.clientId??"",redirect:{success:o?.redirectUrl||window.location.href,error:o?.redirectUrl||window.location.href},state:e,...h.state?{trackingConsent:{analytics:!!h.state.analytics,marketing:!!h.state.marketing}}:{},...(()=>{const e=function(){const e=ks(),t=Object.keys(e).find(e=>e.startsWith("_ga_")),n={},r=Ss(e._ga);r&&(n.gaClientId=r);const a=t?Is(e[t]):void 0;return a&&(n.gaSessionId=a),n}();return Object.keys(e).length?{trackingIdentity:e}:{}})(),...(()=>{const e=$i();return e?{trackingAttribution:e}:{}})(),...(()=>{const e=ga(i);return e?{invitationToken:e}:{}})(),...(()=>{const e=ui(o?.locale)??ui(g);return e?{locale:e}:{}})()});Xt(t)}catch(e){throw u.hide(),t.auth(wa.authenticationFailed()),be(e,{component:"useSaaSAuth",action:"signIn"}),e}},[f,i,o,t,u,e,h.state,m,g]),b=p(e=>async function(e,t){const n=function(e){if(e&&"object"==typeof e)return"everywhere"in e?e:void 0}(t);try{if("function"==typeof e.onSignOut)try{await e.onSignOut()}catch(t){e.onError(t)}try{await e.revoke(n?.everywhere?{all:!0}:void 0)}catch(t){e.onError(t)}}finally{e.clearLocal()}}({onSignOut:o?.callbacks?.onSignOut,revoke:e=>f.logout(Re()??void 0,e),clearLocal:()=>{Ue(),t.auth(wa.removeSession()),c()},onError:e=>be(e,{component:"useSaaSAuth",action:"signOut"})},e),[f,t,c,o?.callbacks?.onSignOut]),v=n.session,k=p(t=>Ar({currentHref:window.location.href,redirectUrl:o?.redirectUrl||void 0,session:v,start:e=>y.startReverification(e),saveIntent:nn,clearIntent:an,redirect:t=>{u.show(e("loading.redirecting")),Xt(t)}},t).catch(e=>{throw u.hide(),be(e,{component:"useSaaSAuth",action:"requireReverification"}),e}),[y,o?.redirectUrl,v,u,e]),S=p(e=>{l?nc.openWorkspaceSettings(e):be(new Error("Cannot open settings: No current workspace"),{component:"useSaaSAuth",action:"openWorkspaceSettings"})},[l]),I=p(()=>{l?nc.openWorkspaceSettings(ec.Credits,{action:jt.OpenCreditStore}):be(new Error("Cannot open credit store: No current workspace"),{component:"useSaaSAuth",action:"openCreditStore"})},[l]),C=p(()=>{l?nc.openWorkspaceSettings(ec.Subscription,{action:jt.SelectPlan}):be(new Error("Cannot open plan picker: No current workspace"),{component:"useSaaSAuth",action:"openPlanPicker"})},[l]),x=s(()=>vr(n.status),[n.status]);return s(()=>({user:n.session?.user,session:n.session,status:n.status,...x,signIn:w,signOut:b,requireReverification:k,openWorkspaceSettings:S,openCreditStore:I,openPlanPicker:C}),[n.session,n.status,x,w,b,k,S,I,C])}const wc=z("inline-flex items-center justify-center rounded-full font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:opacity-50 disabled:pointer-events-none ring-offset-background",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"underline-offset-4 hover:underline text-primary"},withIcon:{true:"flex"},fullWidth:{true:"w-full"},size:{default:"h-10 sm:h-9 py-2 px-4 text-sm",sm:"h-9 sm:h-8 px-3 text-xs",lg:"h-11 sm:h-10 px-6 text-base",icon:"h-10 w-10 sm:h-9 sm:w-9"}},compoundVariants:[{size:"lg",withIcon:!0,className:"gap-x-1.5"},{size:"default",withIcon:!0,className:"gap-x-1"},{size:"sm",withIcon:!0,className:"gap-x-0.5"}],defaultVariants:{variant:"default",size:"default"}}),bc=r.forwardRef(({className:n,variant:a,progress:i,size:s,startIcon:o,endIcon:c,asChild:l=!1,...d},u)=>{const p=l?V:"button",h=function(e){switch(e){case"lg":return 20;case"sm":return 14;default:return 16}}(s);return e(p,{disabled:i||d.disabled,className:le(wc({variant:a,size:s,withIcon:null!=i||null!=o||null!=c,className:n})),ref:u,...d,children:[i&&t(w,{size:h,className:"animate-spin"}),o&&r.cloneElement(o,{size:h}),d.children,c&&r.cloneElement(c,{size:h})]})});function vc({className:r,fixed:a=!0}){const{t:i,formattingLocale:s}=Si(),o=fc().session,{signOut:c}=yc(),[l,d]=h(!1),u=o?.impersonation;if(!o||!u)return null;let p="";try{p=new Intl.DateTimeFormat(s,{timeStyle:"short"}).format(new Date(u.expiresAt))}catch{p=u.expiresAt}const m={name:o.user.name||o.user.email,actor:u.actorName,time:p};return t("div",{className:"saas-os-ui",style:{backgroundColor:"transparent"},children:e("div",{role:"region","aria-label":i("security.impersonationRegion"),className:le("flex flex-col gap-2 border-t border-warning/40 bg-background px-4 py-3 text-sm shadow-lg sm:flex-row sm:items-center sm:justify-between",a&&"fixed inset-x-0 bottom-0 z-[2147483000]",r),children:[e("p",{className:"flex min-w-0 items-start gap-2 text-warning",children:[t(b,{className:"mt-0.5 h-4 w-4 shrink-0","aria-hidden":"true"}),t("span",{className:"min-w-0 break-words",children:u.readOnly?i("security.impersonationReadOnly",m):e(n,{children:[i("security.impersonationFull",m),t("span",{className:"block",children:i("security.impersonationSignInLocked")})]})})]}),t(bc,{size:"sm",variant:"outline",className:"shrink-0 self-end sm:self-auto",progress:l,disabled:l,onClick:async()=>{d(!0),await c(),d(!1)},children:i("security.impersonationExit")})]})})}bc.displayName="Button";const kc=e=>{const{t:t}=Si(),{os:n,api:r}=po(),[a,i]=h(null),[s,o]=h(!1),[c,l]=h(null),{begin:d,settle:m}=xi(),g=p(async()=>{if(!e)return d(),i(null),void o(!1);const a=d();o(!0),l(null);try{const t=await Ci(`credit-balance:${n.serverUrl}:${n.orgId}:${e}`,()=>r.getCreditBalance(e));if(a.signal.aborted)return;i(t)}catch(n){if(a.signal.aborted)return;const r=ke(n,"errors.fetchCreditBalance",t);l(r),be(n,{component:"useCreditBalance",action:"fetchBalance",metadata:{workspaceId:e}})}finally{m(a)&&o(!1)}},[r,n.serverUrl,n.orgId,e,d,m]);return u(()=>{g()},[g]),u(()=>Ut(g),[g]),{balance:a,loading:s,error:c,refetch:g}},Sc=e=>{const{t:t}=Si(),{api:n}=po(),[r,a]=h(!1),[i,s]=h(null);return{consumeCredits:p(async r=>{if(!e)throw new Error("Workspace ID is required");a(!0),s(null);try{const t=await n.consumeCredits(e,r);return Rt(),t}catch(n){const a="INSUFFICIENT_CREDITS"===n.code?t("credits.insufficientDetail",{available:n.available,requested:n.requested}):ke(n,"errors.consumeCredits",t);throw s(a),be(n,{component:"useConsumeCredits",action:"consumeCredits",metadata:{workspaceId:e,request:r}}),n}finally{a(!1)}},[n,e]),loading:r,error:i}},Ic=e=>{const{t:t}=Si(),{api:n}=po(),{track:r,consent:a,getProperties:i}=to(),s=no(),[o,c]=h(!1),[l,d]=h(null);return{purchaseCredits:p(async o=>{if(!e)throw new Error("Workspace ID is required");c(!0),d(null);const l=xs(),u=s?Es(l,a.effective,i(),Math.min(Ps(o.metadata),20-Object.keys(o.metadata??{}).length)):{},p=Object.keys(u).length>0?{...o,metadata:{...u,...o.metadata}}:o;try{let t;try{t=await n.purchaseCredits(e,p)}catch(r){const a=r?.status;if(p===o||o.metadata||400!==a)throw r;t=await n.purchaseCredits(e,o)}const a=t.currency??o.currency,i=ts(t.amountTotal,a);return s&&Vi({eventId:l,workspaceId:e,creditPackageId:o.creditPackageId,currency:a,sessionId:t.sessionId,value:i,kind:"purchase",startedAt:Date.now()}),r("checkout_started",{credit_package_id:o.creditPackageId,...a?{currency:a.toUpperCase()}:{},..."number"==typeof i?{value:i}:{}},{eventId:l}),t}catch(n){const r=ke(n,"errors.purchaseCredits",t);throw d(r),be(n,{component:"usePurchaseCredits",action:"purchaseCredits",metadata:{workspaceId:e,request:o}}),n}finally{c(!1)}},[n,e,r,a.effective,s]),loading:o,error:l}},Cc=e=>{const{t:t}=Si(),{api:n}=po(),[r,a]=h([]),[i,s]=h(!1),[o,c]=h(null),{begin:l,settle:d}=xi(),m=p(async()=>{if(!e)return l(),a([]),void s(!1);const r=l();s(!0),c(null);try{const t=await n.getCreditPackages(e);if(r.signal.aborted)return;a(t)}catch(n){if(r.signal.aborted)return;const a=ke(n,"errors.fetchCreditPackages",t);c(a),be(n,{component:"useCreditPackages",action:"fetchPackages",metadata:{workspaceId:e}})}finally{d(r)&&s(!1)}},[n,e,l,d]);return u(()=>{m()},[m]),{packages:r,loading:i,error:o,refetch:m}},xc=(e,t)=>{const{t:n}=Si(),{api:r}=po(),[a,i]=h([]),[s,o]=h(0),[c,l]=h(0),[d,m]=h(1),[g,f]=h(!1),[y,w]=h(!1),[b,v]=h(!1),[k,S]=h(null),{begin:I,settle:C}=xi(),x=t?.type,N=t?.page,A=t?.limit,P=p(async()=>{if(!e)return I(),i([]),o(0),l(0),m(1),f(!1),w(!1),void v(!1);const t=I();v(!0),S(null);try{const n=await r.getCreditTransactions(e,{type:x,page:N,limit:A});if(t.signal.aborted)return;i(n.docs||[]),o(n.totalDocs||0),l(n.totalPages||0),m(n.page||1),f(n.hasNextPage||!1),w(n.hasPrevPage||!1)}catch(r){if(t.signal.aborted)return;const a=ke(r,"errors.fetchCreditTransactions",n);S(a),be(r,{component:"useCreditTransactions",action:"fetchTransactions",metadata:{workspaceId:e}})}finally{C(t)&&v(!1)}},[r,e,x,N,A,I,C]);return u(()=>{P()},[P]),{transactions:a,totalDocs:s,totalPages:c,page:d,hasNextPage:g,hasPrevPage:y,loading:b,error:k,refetch:P}},Nc=(e,t)=>{const{t:n}=Si(),{api:r}=po(),[a,i]=h(null),[s,o]=h(!1),[c,l]=h(null),{begin:d,settle:m}=xi(),g=p(async()=>{if(!e)return d(),i(null),void o(!1);const a=d();o(!0),l(null);try{const n=await r.getExpiringCredits(e,t);if(a.signal.aborted)return;i(n)}catch(r){if(a.signal.aborted)return;const i=ke(r,"errors.fetchExpiringCredits",n);l(i),be(r,{component:"useExpiringCredits",action:"fetchExpiring",metadata:{workspaceId:e,days:t}})}finally{m(a)&&o(!1)}},[r,e,t,d,m]);return u(()=>{g()},[g]),{expiringCredits:a?.expiringCredits??0,buckets:a?.buckets??[],days:a?.days??t??7,loading:s,error:c,refetch:g}},Ac=()=>{const{t:e}=Si(),{os:t,api:n}=po(),r=xt(t),[a,i]=h([]),[s,o]=h(),[c,l]=h(!1),[d,m]=h(null),{begin:g,settle:f}=xi(),y=p(async()=>{if(!r)return g(),i([]),void l(!1);const t=g();l(!0),m(null);try{const e=await n.getPublicCreditPackages();if(t.signal.aborted)return;i(e.packages||[]),o(e.notes)}catch(n){if(t.signal.aborted)return;const r=ke(n,"errors.fetchCreditPackages",e);m(r),be(n,{component:"usePublicCreditPackages",action:"fetchPackages"})}finally{f(t)&&l(!1)}},[n,r,g,f]);u(()=>{y()},[y]);return{packages:a,notes:s,loading:!r||c,error:d,refetch:y}},Pc=c(null);Pc.displayName="CreditBalanceContext";const Ec=a.memo(function({children:e}){const n=io(e=>e.workspaces.currentWorkspace),{balance:r,loading:a,error:i,refetch:o}=kc(n?._id),c=s(()=>({balance:r,loading:a,error:i,refetch:o}),[r,a,i,o]);return t(Pc.Provider,{value:c,children:e})});function _c(){const e=d(Pc);if(null===e)throw new Error("useCreditBalanceContext must be used within CreditBalanceContextProvider. Make sure CreditBalanceContextProvider is wrapping your application (included in SaaSOSProvider by default).");return e}Ec.displayName="CreditBalanceContextProvider";const Tc=c(null);function Uc(e,t){return e?e.replace(/\{\{(\w+)\}\}/g,(e,n)=>n in t?t[n]:e):e}function Rc(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"app"}function Oc({mcp:e,children:n}){const r=s(()=>e?.url?{...e,url:e.url.replace(/\/+$/,"")}:null,[e]);return t(Tc.Provider,{value:r,children:n})}function Wc(){return d(Tc)}const Fc=c({appPermissions:void 0});function Lc({appPermissions:e,children:n}){const r=s(()=>({appPermissions:e}),[e]);return t(Fc.Provider,{value:r,children:n})}function Dc(){return d(Fc)}const $c=c(null);$c.displayName="QuotaUsageContext";const Mc=a.memo(function({children:e}){const n=io(e=>e.workspaces.currentWorkspace),{quotas:r,loading:a,error:i,refetch:o}=Po(n?._id),c=s(()=>({quotas:r,loading:a,error:i,refetch:o}),[r,a,i,o]);return t($c.Provider,{value:c,children:e})});function jc(){const e=d($c);if(null===e)throw new Error("useQuotaUsageContext must be used within QuotaUsageContextProvider. Make sure QuotaUsageContextProvider is wrapping your application (or the tree that uses quota gates).");return e}Mc.displayName="QuotaUsageContextProvider";let qc=!1;function Bc(){qc=!0}const Vc=a.memo(({children:e,callbacks:r})=>{const{t:i}=Si(),s=ao(),o=fc(),c=oo(),l=vr(o.status).isAuthenticated,d=Lo(),h=a.useRef(!1),m=a.useRef(null),g=a.useRef(!1),f=a.useRef(null),y=p(async e=>{try{if(r?.handleAuthentication){d.show(i("loading.signingIn"));const{sessionId:t}=await r.handleAuthentication(e);if(!t||"string"!=typeof t||""===t.trim())throw new Error("Invalid sessionId received from authentication callback");const n=c;if(!xt(n))throw new Error("OS configuration is not available");const{serverUrl:a,version:o,orgId:l}=n;d.show(i("loading.verifyingAccount"));const u=new Je({serverUrl:a,version:o}),p=await u.getProfile(t),h=gc(mc(p,l,n.auth?.clientId||""),t,uc(p));d.show(i("loading.almostThere")),Te(h.sessionId),u.getDeviceToken(h.sessionId).then(e=>e&&Oe(e)).catch(()=>{}),Le();const m=rn(),g=!!m&&m!==window.location.href;g&&Bc(),s.auth(wa.setSession(h)),g&&Xt(m),d.hide()}}catch(t){throw d.hide(),rn(),be(t,{component:"AuthProviderWrapper",action:"handleAuthRedirect",metadata:{hasCode:!!e}}),s.auth(wa.authenticationFailed()),t}},[s,r,c,d,i]);return a.useEffect(()=>{if("undefined"==typeof window)return;const e=Nr(window.location.href);e&&(window.history.replaceState(window.history.state,"",e),function(e=Date.now()){try{sessionStorage.setItem(Sr,String(e))}catch{}}())},[]),a.useEffect(()=>{if("undefined"==typeof window)return;if(l)return;if(g.current)return;if(f.current)return;if(!xt(c))return;if(Fe())return;if(!r?.getSession)return g.current=!0,void s.auth(wa.authenticationFailed());const e=r.getSession,{serverUrl:t,version:n,orgId:a}=c,o=c.auth?.clientId||"";f.current=(async()=>{d.show(i("loading.restoringSession"));let c=null;try{c=await e()}catch(e){be(e,{component:"AuthProviderWrapper",action:"getSession"})}if(!c)return Ue(),g.current=!0,s.auth(wa.authenticationFailed()),d.hide(),"undefined"!=typeof window&&nn(window.location.href),void r?.onSessionExpired?.("missing");try{d.show(i("loading.verifyingAccount"));const e=new Je({serverUrl:t,version:n}),r=await e.getProfile(c),l=gc(mc(r,a,o),c,uc(r));Te(l.sessionId),e.getDeviceToken(l.sessionId).then(e=>e&&Oe(e)).catch(()=>{}),g.current=!0;const u=rn(),p=!!u&&u!==window.location.href;p&&Bc(),s.auth(wa.setSession(l)),d.hide(),p&&Xt(u)}catch(e){be(e,{component:"AuthProviderWrapper",action:"fetchUserProfile"}),Ue(),g.current=!0,s.auth(wa.authenticationFailed()),d.hide(),"undefined"!=typeof window&&nn(window.location.href),r?.onSessionExpired?.("expired")}finally{f.current=null}})()},[l,s,c,r]),u(()=>{const e=Fe();if(!e)return;if(h.current||m.current===e)return;if(!xt(c))return;const t=function(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get(_e)}catch(e){return be(e,{component:"auth-utils",action:"getStateFromUrl",metadata:{param:_e}}),null}}();if(t&&!function(e){if(!e)return!1;const t=Se(Do);if(Ce(Do),!t)return!1;if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return 0===n}(t))return $o(),Le(),be(new Error("OAuth state mismatch — possible CSRF attack"),{component:"AuthProviderWrapper",action:"validateOAuthState"}),void s.auth(wa.authenticationFailed());$o(),h.current=!0,m.current=e;let n=!1;return s.auth(wa.authenticationProcessing()),y(e).then(()=>{n||(m.current=null)}).catch(e=>{n||(be(e,{component:"AuthProviderWrapper",action:"handleAuthRedirectEffect",metadata:{hasCode:!0}}),Le(),m.current=null)}).finally(()=>{h.current=!1}),()=>{n=!0}},[y,c.serverUrl,c.version,c.orgId]),t(n,{children:e})});Vc.displayName="AuthProviderWrapper";const zc=a.memo(({config:e,auth:r,children:i})=>{const s=ao();oo();const o=a.useRef(r?.callbacks);o.current=r?.callbacks;const c=Object.keys(r?.callbacks??{}).sort().join(","),l=a.useMemo(()=>{if(!c)return;const e={};for(const t of c.split(","))e[t]=(...e)=>{const n=o.current;return n?.[t]?.(...e)};return e},[c]),d=a.useMemo(()=>({clientId:r?.clientId||"",redirectUrl:r?.redirectUrl||"",callbacks:l}),[r?.clientId,r?.redirectUrl,l]);return u(()=>{s.os(Ta({...e,auth:d}))},[e,d,s]),t(n,{children:i})});zc.displayName="ContextConfigProvider";const Gc=c({container:null,setContainer:()=>{}}),Jc=a.memo(({children:n})=>{const[r,i]=a.useState(null),s=a.useMemo(()=>({container:r,setContainer:i}),[r]);return e(Gc.Provider,{value:s,children:[n,t("div",{ref:i,id:"saas-os-portal",className:"saas-os-ui",style:{width:"100%",height:"100%"}})]})});Jc.displayName="PortalProvider";const Hc=c(null);function Yc(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}const Kc=a.memo(function({children:e,serviceWorkerPath:n="/push-sw.js",autoSubscribe:r=!1}){const{t:a}=Si(),i=oo(),{isAuthenticated:o}=yc(),c=s(()=>"undefined"!=typeof window&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window,[]),l=s(()=>new tt({serverUrl:i.serverUrl,version:i.version,orgId:i.orgId}),[i.serverUrl,i.version,i.orgId]),[d,m]=h({permission:c?Notification.permission:"default",isSubscribed:!1,isSupported:c,loading:!1,error:null});u(()=>{if(!o||!c)return;let e=!1;return(async()=>{try{const t=await navigator.serviceWorker.getRegistration(n);if(e)return;if(!t)return void m(e=>({...e,isSubscribed:!1}));const r=await t.pushManager.getSubscription();if(e)return;m(e=>({...e,isSubscribed:!!r,permission:Notification.permission}))}catch{e||m(e=>({...e,isSubscribed:!1}))}})(),()=>{e=!0}},[o,c,n]);const g=p(async()=>{if(!c)return!1;const e=await Notification.requestPermission();return m(t=>({...t,permission:e})),"granted"===e},[c]),f=p(async()=>{if(c&&o){m(e=>({...e,loading:!0,error:null}));try{if(!await g())return void m(e=>({...e,loading:!1,error:a("notifications.permissionDenied")}));const{publicKey:e}=await l.getVapidPublicKey(),t=await navigator.serviceWorker.register(n);await navigator.serviceWorker.ready;const r=(await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Yc(e)})).toJSON();await l.subscribe({endpoint:r.endpoint,keys:{p256dh:r.keys.p256dh,auth:r.keys.auth}},navigator.userAgent),m(e=>({...e,isSubscribed:!0,loading:!1}))}catch(e){const t=e instanceof Error?e.message:a("push.failedToSubscribe");m(e=>({...e,loading:!1,error:t})),be(e,{component:"PushNotificationProvider",action:"subscribe"})}}},[c,o,l,n,g]),y=p(async()=>{if(c){m(e=>({...e,loading:!0,error:null}));try{const e=await navigator.serviceWorker.getRegistration(n);if(e){const t=await e.pushManager.getSubscription();if(t){const e=t.endpoint;await t.unsubscribe(),await l.unsubscribe(e)}}m(e=>({...e,isSubscribed:!1,loading:!1}))}catch(e){const t=e instanceof Error?e.message:a("push.failedToUnsubscribe");m(e=>({...e,loading:!1,error:t})),be(e,{component:"PushNotificationProvider",action:"unsubscribe"})}}},[c,l,n]),w=s(()=>({...d,requestPermission:g,subscribe:f,unsubscribe:y}),[d,g,f,y]);return t(Hc.Provider,{value:w,children:e})});function Qc(){const e=d(Hc);if(!e)throw new Error("usePushNotifications must be used within PushNotificationProvider");return e}const Zc="bb_seen_users",Xc=12e4;function el(){try{const e=window.localStorage.getItem(Zc),t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function tl(e,t,n=Date.now()){if(!e)return"login";if("undefined"==typeof window)return"login";if(el().includes(e))return"login";if(function(e){try{const t=[e,...el().filter(t=>t!==e)].slice(0,20);window.localStorage.setItem(Zc,JSON.stringify(t))}catch{}}(e),!t)return"login";const r=Date.parse(t);return Number.isNaN(r)||r>n||n-r>Xc||function(e){try{const t=window.document?.cookie;return"string"==typeof t&&t.split("; ").includes(`${nl}=${e}`)}catch{return!1}}(e)?"login":(function(e){try{const t=window.document;if(!t||!rl.test(e))return;const n=_i(window.location?.hostname??"",t);t.cookie=`${nl}=${e}; path=/; max-age=120; SameSite=Lax`+(n?`; domain=${n}`:"")}catch{}}(e),"sign_up")}const nl="bb_su",rl=/^[\w-]{1,64}$/;const al="bb_announced_session";const il={[Nt.UserCreated]:"user_created",[Nt.UserUpdated]:"user_updated",[Nt.WorkspaceCreated]:"workspace_created",[Nt.WorkspaceUpdated]:"workspace_updated",[Nt.WorkspaceChanged]:"workspace_switched",[Nt.WorkspaceDeleted]:"workspace_deleted",[Nt.WorkspaceUserAdded]:"workspace_member_added",[Nt.WorkspaceUserRemoved]:"workspace_member_removed",[Nt.WorkspaceUserRoleChanged]:"workspace_member_role_changed",[Nt.WorkspaceInvitationSent]:"workspace_invitation_sent",[Nt.WorkspaceInvitationAccepted]:"workspace_invitation_accepted",[Nt.WorkspaceInvitationDeclined]:"workspace_invitation_declined",[Nt.WorkspaceInvitationRevoked]:"workspace_invitation_revoked"};const sl=Object.keys(il),ol="undefined"==typeof window?a.useEffect:a.useLayoutEffect;function cl({children:e}){const{track:r,setUser:i,setProperties:s,ready:o,setIdentity:c,setConsentRecordHeaders:l}=to(),d=fc().session,u=d?.user?.id,p=d?.sessionId,h=d?.user?.email;a.useEffect(()=>{l(p?{"x-session-id":p}:{})},[p,l]),a.useEffect(()=>{c(h?{email:h}:null)},[h,c]);const{currentWorkspace:m}=sc(),{response:g,loading:f}=Uo(),y=a.useMemo(()=>function(e){const{workspace:t,userId:n,subscription:r,subscriptionLoading:a}=e,i={workspace_id:void 0,workspace_role:void 0,workspace_owner:void 0,workspace_member_count:void 0,workspace_plan:void 0,subscription_status:void 0};if(!t?._id)return i;const s=Array.isArray(t.users)?t.users.length:void 0,o=a?void 0:r?.subscription?r.plan?.slug??void 0:"none";return{workspace_id:String(t._id),workspace_role:sr(t,n)??void 0,workspace_owner:n?ir(t,n):void 0,workspace_member_count:s,workspace_plan:o,subscription_status:a?void 0:r?.subscription?.subscriptionStatus??"none"}}({workspace:u?m:null,userId:u,subscription:g,subscriptionLoading:f}),[m,u,g,f]),w=JSON.stringify(y),b=a.useRef(null);ol(()=>{b.current!==w&&(b.current=w,s(y))},[w,s]);const v=function(e){const t={};return void 0!==e.workspace_plan&&(t.workspace_plan=e.workspace_plan),void 0!==e.workspace_role&&(t.workspace_role=e.workspace_role),void 0!==e.subscription_status&&(t.subscription_status=e.subscription_status),t}(y),k=JSON.stringify(v),S=a.useRef(null);a.useEffect(()=>{if(!o||!u||0===Object.keys(v).length)return;const e=`${u}|${k}`;S.current!==e&&(S.current=e,i(u,v))},[o,u,k,i]),a.useEffect(()=>{o&&u&&p&&(qc||function(e){if(!e)return!1;if("undefined"==typeof window)return!1;try{return window.localStorage.getItem(al)!==e&&(window.localStorage.setItem(al,e),!0)}catch{return!0}}(p)&&(i(u),r(tl(u,d?.user?.firstAuthAt),{method:"buildbase"})))},[o,u,p,d?.user?.firstAuthAt,r,i]),a.useEffect(()=>{const e=sl.map(e=>Pt.on(e,t=>{(function(e,t){if(e!==Nt.WorkspaceChanged)return!0;const n=t,r=n.workspace?._id,a=n.previousWorkspace?._id;return!!r&&!!a&&r!==a})(e,t)&&r(il[e],function(e,t){const n=t,r={},a=n.workspace;a?._id&&(r.workspace_id=a._id);const i=n.previousWorkspace;i?._id&&(r.previous_workspace_id=i._id);const s=n.user;(s?._id||s?.id)&&(r.user_id=s._id??s.id),"string"==typeof n.userId&&(r.member_id=n.userId),"string"==typeof n.workspaceId&&(r.workspace_id=n.workspaceId);const o=n.invitation;o?._id&&(r.invitation_id=o._id),"string"==typeof o?.role&&(r.role=o.role);const c=o?.workspace;return"string"==typeof c?r.workspace_id=c:c?._id&&(r.workspace_id=c._id),"string"==typeof n.invitationId&&(r.invitation_id=n.invitationId),"string"==typeof n.role&&(r.role=n.role),"string"==typeof n.previousRole&&(r.previous_role=n.previousRole),"string"==typeof n.newRole&&(r.new_role=n.newRole),r}(0,t))}));return()=>e.forEach(e=>e())},[r]);const I=a.useRef(o);I.current=o;const C=a.useRef([]);return a.useEffect(()=>we.subscribe((e,t)=>{if(!qo(`sdk_error|${`${t.component??"unknown"}|${t.action??"unknown"}`}`))return;const n=Mo({component:t.component,action:t.action,code:e.code});I.current?r("sdk_error",n):C.current.length<20&&C.current.push(n)}),[r]),a.useEffect(()=>{if(!o||0===C.current.length)return;const e=C.current;C.current=[],e.forEach(e=>r("sdk_error",e))},[o,r]),t(n,{children:e})}cl.displayName="TrackingBridge";const ll=a.createContext(void 0),dl=a.memo(({children:e})=>{const{t:n}=Si(),r=oo(),i=function(){const e=oo();return s(()=>new ht(e),[e.serverUrl,e.version])}(),{isAuthenticated:o}=yc(),{serverUrl:c,version:l}=r,[d,u]=h({}),[m,g]=h({}),[f,y]=h(!1),[w,b]=h(!1),[v,k]=h(null),[S,I]=h(null),C=p(async e=>{if(c&&l&&o){k(null);try{const t=await i.getAttributes(e);u(t)}catch(e){if(me(e))return;const t=e instanceof Error?e:new Error(n("errors.generic"));k(t),be(e,{component:"UserProvider",action:"fetchAttributes"})}}else u({})},[i,c,l,o,n]),x=p(async()=>{if(c&&l&&o){y(!0);try{await C()}finally{y(!1)}}},[c,l,o,C]),N=p(async e=>{y(!0),k(null);try{const t=await i.updateAttributes(e);return await C(),t}catch(t){const r=t instanceof Error?t:new Error(n("errors.generic"));throw k(r),be(t,{component:"UserProvider",action:"updateAttributes",metadata:{updates:e}}),t}finally{y(!1)}},[i,C,n]),A=p(async(e,t)=>{y(!0),k(null);try{const n=await i.updateAttribute(e,t);return await C(),n}catch(r){const a=r instanceof Error?r:new Error(n("errors.generic"));throw k(a),be(r,{component:"UserProvider",action:"updateAttribute",metadata:{attributeKey:e,value:t}}),r}finally{y(!1)}},[i,C,n]),P=p(async e=>{if(c&&l&&o){I(null);try{const t=await i.getFeatures(e);g(t)}catch(e){if(me(e))return;const t=e instanceof Error?e:new Error(n("errors.generic"));I(t),be(e,{component:"UserProvider",action:"fetchFeatures"})}}else g({})},[i,c,l,o,n]),E=p(async()=>{if(c&&l&&o){b(!0);try{await P()}finally{b(!1)}}},[c,l,o,P]);so(async e=>{if(!o||!c||!l)return u({}),void g({});y(!0),b(!0),await Promise.all([C(e).finally(()=>y(!1)),P(e).finally(()=>b(!1))])},[o,c,l,C,P],{onError:e=>be(e,{component:"UserProvider",action:"initialFetch",metadata:{step:"fetchAttributesAndFeatures"}})});const _=a.useMemo(()=>({attributes:d,features:m,isLoading:f||w,error:v??S,attributesLoading:f,featuresLoading:w,attributesError:v,featuresError:S,updateAttributes:N,updateAttribute:A,refreshAttributes:x,refreshFeatures:E}),[d,m,f,w,v,S,N,A,x,E]);return t(ll.Provider,{value:_,children:e})});dl.displayName="UserProvider";const ul=G.Root,pl=G.Trigger,hl=G.Portal,ml=r.forwardRef(({className:e,...n},r)=>t(G.Overlay,{ref:r,className:le("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...n}));ml.displayName=G.Overlay.displayName;const gl=r.forwardRef(({className:n,children:a,...i},s)=>{const{container:o}=r.useContext(Gc),{t:c}=Si();return e(hl,{container:o,children:[t(ml,{}),e(G.Content,{ref:s,className:le("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg md:w-full",n),...i,children:[a,e(G.Close,{className:"absolute right-2 rtl:right-auto rtl:left-2 top-2 z-20 p-2 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[t(J,{className:"h-4 w-4"}),t("span",{className:"sr-only",children:c("settings.common.close")})]})]})]})});gl.displayName=G.Content.displayName;const fl=({className:e,...n})=>t("div",{className:le("flex flex-col space-y-1.5 text-center sm:text-start",e),...n});fl.displayName="DialogHeader";const yl=({className:e,...n})=>t("div",{className:le("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...n});yl.displayName="DialogFooter";const wl=r.forwardRef(({className:e,...n},r)=>t(G.Title,{ref:r,className:le("text-lg font-semibold leading-none tracking-tight",e),...n}));wl.displayName=G.Title.displayName;const bl=r.forwardRef(({className:e,...n},r)=>t(G.Description,{ref:r,className:le("text-sm text-muted-foreground",e),...n}));bl.displayName=G.Description.displayName;const vl={error:{box:"bg-destructive/10 border-destructive/20 text-destructive",sub:"text-destructive/80",button:"border-destructive/20 text-destructive hover:bg-destructive/10"},success:{box:"bg-success/10 border-success/20 text-success",sub:"text-success/80",button:"border-success/20 text-success hover:bg-success/10"},warning:{box:"bg-warning/10 border-warning/20 text-warning",sub:"text-warning/80",button:"border-warning/20 text-warning hover:bg-warning/10"},info:{box:"bg-info/10 border-info/20 text-info",sub:"text-info/80",button:"border-info/20 text-info hover:bg-info/10"}};function kl({variant:n,title:r,message:a,description:i,icon:s,actionLabel:o,onAction:c,actionDisabled:l,actionProgress:d,className:u}){const p=vl[n];return e("div",{role:"error"===n?"alert":"status","aria-live":"error"===n?"assertive":"polite","aria-atomic":"true",className:le("border px-4 py-3 rounded-lg flex items-start justify-between gap-2 sm:gap-4",p.box,u),children:[e("div",{className:"flex items-start gap-2 min-w-0",children:[s,e("div",{className:"min-w-0",children:[r&&t("p",{className:"text-sm font-medium",children:r}),a&&t("p",{className:le("text-sm",r&&"mt-1"),children:a}),i&&t("p",{className:le("text-xs mt-2",p.sub),children:i})]})]}),o&&t(bc,{variant:"outline",size:"sm",onClick:c,progress:d,disabled:l||d,className:le("flex-shrink-0",p.button),children:o})]})}const Sl=new Set(["alreadyAccepted","expired","revoked","accepted","declined","disabled"]),Il=new Set(["expired","revoked","disabled"]),Cl=new Set(["accepted"]),xl=new Set(["alreadyAccepted","expired","revoked","declined"]);function Nl(){const{t:r}=Si(),a=oo(),{isAuthenticated:i,isLoading:s,signIn:o,signOut:c}=yc(),{previewInvitation:d,acceptInvitation:m,declineInvitation:g,switchToWorkspace:f}=sc(),y=a.orgId??"",[w,b]=h(null),[v,k]=h(null),[S,I]=h({kind:"none"}),[C,x]=h(!1),N=l(!1),A=Sl.has(S.kind),P="accepted"===S.kind?r("invitations.titleJoined",{workspace:S.workspace}):Il.has(S.kind)?r("invitations.titleUnavailable"):r("invitations.title"),E="wrongAccount"===S.kind,_=p(e=>{I(e),Sl.has(e.kind)&&fa()},[]);u(()=>{if(N.current||!y)return;N.current=!0;const e=Jt();e?.action===jt.Invite&&e.token&&(ma(e.token,y),Ht(),b(e.token))},[y]),u(()=>{if(!y||w||s)return;const e=ga(y);e&&b(e)},[y,w,s,i]),u(()=>{if(!w)return;let e=!1;return k(null),I({kind:"none"}),d(w).then(t=>{e||(k(t),"accepted"===t.status?_({kind:"alreadyAccepted"}):"expired"===t.status?_({kind:"expired",inviter:t.inviterName}):"rejected"===t.status?_({kind:"revoked"}):!1===t.joinable&&_({kind:"disabled"}))}).catch(t=>{e||(be(t,{component:"InvitationLanding",action:"preview"}),bt(t)&&404===t.status?_({kind:"revoked"}):I({kind:"loadFailed"}))}),()=>{e=!0}},[w,d,_]);const T=p(()=>{fa(),b(null),k(null),I({kind:"none"})},[]);if(!w)return null;const U=function(e,t){switch(e.kind){case"none":return null;case"alreadyAccepted":return t("invitations.alreadyAccepted");case"expired":return t("invitations.expired",{inviter:e.inviter});case"revoked":return t("invitations.revoked");case"loadFailed":return t("invitations.loadFailed");case"accepted":return t("invitations.accepted",{workspace:e.workspace});case"declined":return t("invitations.declined");case"verifyFirst":return t("invitations.verifyFirst");case"wrongAccount":return t("invitations.wrongAccount",{email:e.email});case"workspaceFull":return t("invitations.workspaceFull");case"disabled":return t("invitations.disabled");case"acceptFailed":return t("invitations.acceptFailed");case"declineFailed":return t("invitations.declineFailed");case"raw":return e.message}}(S,r),R=Cl.has(S.kind)?"success":xl.has(S.kind)?"info":"error";return t(ul,{open:!0,onOpenChange:e=>!e&&T(),children:e(gl,{className:"sm:max-w-md",children:[e(fl,{children:[t(wl,{children:P}),v&&t(bl,{children:r("invitations.description",{inviter:v.inviterName,workspace:v.workspaceName,role:v.role})})]}),v&&t("p",{className:"text-sm text-muted-foreground",children:r("invitations.sentTo",{email:v.email})}),U&&t(kl,{variant:R,message:U}),t(yl,{className:"gap-2 sm:gap-2",children:A?t(bc,{onClick:T,children:r("invitations.dismiss")}):E?e(n,{children:[t(bc,{variant:"outline",onClick:T,children:r("invitations.dismiss")}),t(bc,{onClick:()=>{c().then(()=>I({kind:"none"})).catch(e=>be(e,{component:"InvitationLanding",action:"signOut"}))},children:r("invitations.signOut")})]}):v?s?null:e(n,i?{children:[t(bc,{variant:"outline",disabled:C,onClick:async()=>{if(v){x(!0),I({kind:"none"});try{await g(v.id),_({kind:"declined"})}catch(e){be(e,{component:"InvitationLanding",action:"decline"}),bt(e)&&e.code===mt.EMAIL_MISMATCH?I({kind:"wrongAccount",email:e.invitedEmail??v.email}):bt(e)&&e.code===mt.ALREADY_HANDLED?_("accepted"===e.invitationStatus?{kind:"alreadyAccepted"}:{kind:"revoked"}):I({kind:"declineFailed"})}finally{x(!1)}}},children:r("invitations.decline")}),t(bc,{progress:C,onClick:async()=>{if(v){x(!0),I({kind:"none"});try{const{workspace:e}=await m(v.id,{token:w??void 0});_({kind:"accepted",workspace:v.workspaceName}),e&&await f(e)}catch(e){if(be(e,{component:"InvitationLanding",action:"accept"}),bt(e))switch(e.code){case mt.EMAIL_NOT_VERIFIED:I({kind:"verifyFirst"});break;case mt.EMAIL_MISMATCH:I({kind:"wrongAccount",email:e.invitedEmail??v.email});break;case mt.SEAT_LIMIT:I({kind:"workspaceFull"});break;case mt.INVITES_DISABLED:_({kind:"disabled"});break;case mt.EXPIRED:_({kind:"expired",inviter:v.inviterName});break;case mt.ALREADY_HANDLED:case mt.NOT_FOUND:_("accepted"===e.invitationStatus?{kind:"alreadyAccepted"}:{kind:"revoked"});break;default:I({kind:"raw",message:e.message})}else I({kind:"acceptFailed"})}finally{x(!1)}}},children:r("invitations.accept")})]}:{children:[t(bc,{variant:"outline",onClick:T,children:r("invitations.dismiss")}),t(bc,{onClick:()=>{o(window.location.href).catch(e=>be(e,{component:"InvitationLanding",action:"signIn"}))},children:r("invitations.signInToAccept")})]}):t(bc,{variant:"outline",onClick:T,disabled:!U,children:r("invitations.dismiss")})})]})})}function Al(e){const{user:t}=yc(),{currentWorkspace:n}=sc(),{settings:r}=uo(),{appPermissions:a}=Dc(),i=e??n??null,o=t?.id??null,c=s(()=>i?sr(i,o):null,[i,o]),l=s(()=>!!i&&ir(i,o),[i,o]),d=s(()=>hr({userId:o,workspaceRole:c,workspace:i,settings:r,appPermissions:a}),[o,c,i,r,a]),u=p(e=>Array.isArray(e)?e.every(e=>d.has(e)):d.has(e),[d]),h=s(()=>yr(r,a),[r,a]);return{can:u,permissions:d,isOwner:l,role:c,appPermissionDefinitions:h}}function Pl(){const e=Jo(),{can:t}=Al();return{visible:p((n,r)=>!1!==n(e)&&(void 0===r||t(r)),[e,t]),ui:e}}function El(e,t="en-US",n){try{const r=new Date(e);return isNaN(r.getTime())?"":new Intl.DateTimeFormat(t,n??{month:"short",day:"numeric",year:"numeric"}).format(r)}catch{return""}}function _l(e,t="en-US"){return El(e,t,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})}function Tl(e,t="en-US"){return e?new Date(1e3*e).toLocaleDateString(t,{year:"numeric",month:"short",day:"numeric"}):""}const Ul=[["second",60],["minute",60],["hour",24],["day",7],["week",4.34524],["month",12],["year",Number.POSITIVE_INFINITY]];function Rl(e,t="en-US",n=Date.now()){try{const r=new Date(e).getTime();if(isNaN(r))return"";const a=new Intl.RelativeTimeFormat(t,{numeric:"auto"});let i=(r-n)/1e3;if(Math.abs(i)<60)return a.format(0,"second");for(const[e,t]of Ul){if(Math.abs(i)<t)return a.format(Math.round(i),e);i/=t}return""}catch{return""}}function Ol(){const e=l(null);return u(()=>()=>{e.current&&clearTimeout(e.current)},[]),p((t,n=5e3)=>{e.current&&clearTimeout(e.current),e.current=setTimeout(()=>{e.current=null,t()},n)},[])}function Wl(){const e=oo();return s(()=>new Ke(e),[e.serverUrl,e.version])}function Fl(){const e=Wl(),{t:t}=Si(),[n,r]=h([]),[a,i]=h(!0),[o,c]=h(null),[d,m]=h(null),g=l(null),f=l(t);u(()=>{f.current=t},[t]);const y=p(async()=>{g.current?.abort();const t=new AbortController;g.current=t,i(!0),c(null);try{const n=await e.list(t.signal);t.signal.aborted||r(n)}catch(e){if(t.signal.aborted)return;ve(e,{component:"useConnectedAgents",action:"list"}),c(ke(e,"security.connectedAgentsLoadFailed",f.current))}finally{g.current===t&&(g.current=null,i(!1))}},[e]);u(()=>(y(),()=>g.current?.abort()),[y]);const w=p(async t=>{m(t),c(null);try{return await e.revoke(t),r(e=>e.filter(e=>e.clientId!==t)),!0}catch(e){return ve(e,{component:"useConnectedAgents",action:"revoke"}),c(ke(e,"security.connectedAgentsRevokeFailed",f.current)),!1}finally{m(null)}},[e]);return s(()=>({agents:n,loading:a,error:o,revoking:d,refresh:y,revoke:w}),[n,a,o,d,y,w])}const Ll=oe.Root,Dl=oe.Trigger,$l=oe.Portal,Ml=r.forwardRef(({className:e,...n},r)=>t(oe.Overlay,{className:le("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...n,ref:r}));Ml.displayName=oe.Overlay.displayName;const jl=r.forwardRef(({className:n,...a},i)=>{const{container:s}=r.useContext(Gc);return e($l,{container:s,children:[t(Ml,{}),t(oe.Content,{ref:i,className:le("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg md:w-full",n),...a})]})});jl.displayName=oe.Content.displayName;const ql=({className:e,...n})=>t("div",{className:le("flex flex-col space-y-2 text-center sm:text-start",e),...n});ql.displayName="AlertDialogHeader";const Bl=({className:e,...n})=>t("div",{className:le("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...n});Bl.displayName="AlertDialogFooter";const Vl=r.forwardRef(({className:e,...n},r)=>t(oe.Title,{ref:r,className:le("text-lg font-semibold",e),...n}));Vl.displayName=oe.Title.displayName;const zl=r.forwardRef(({className:e,...n},r)=>t(oe.Description,{ref:r,className:le("text-sm text-muted-foreground",e),...n}));zl.displayName=oe.Description.displayName;const Gl=r.forwardRef(({className:e,...n},r)=>t(oe.Action,{ref:r,className:le(wc(),e),...n}));Gl.displayName=oe.Action.displayName;const Jl=r.forwardRef(({className:e,...n},r)=>t(oe.Cancel,{ref:r,className:le(wc({variant:"outline"}),"mt-2 sm:mt-0",e),...n}));function Hl({icon:n,title:r,description:a,action:i,className:s}){return e("div",{className:le("flex flex-col items-center gap-2 rounded-md border border-dashed p-6 text-center",s),children:[n&&t("span",{"aria-hidden":"true",children:n}),r&&t("p",{className:"text-sm font-medium",children:r}),a&&t("p",{className:"text-sm text-muted-foreground",children:a}),i]})}function Yl({title:n,description:r,actions:a,help:i,className:s,titleClassName:o}){if(!n&&!r&&!a)return null;const c=n&&t("h3",{className:le("text-sm font-medium",o),children:n}),l=r&&t("p",{className:"text-sm text-muted-foreground",children:r});return e("div",{className:le(s),children:[(n||a)&&e("div",{className:le("flex items-center gap-2",n?"justify-between":"justify-end"),children:[c&&i?e("div",{className:"flex min-w-0 items-center gap-1",children:[c,i]}):c,a]}),l&&i&&!n?e("div",{className:"flex items-start gap-1",children:[l,i]}):l]})}function Kl({className:e,...n}){return t("div",{className:le("animate-pulse rounded-md bg-primary/10",e),...n})}Jl.displayName=oe.Cancel.displayName;const Ql=se.Root,Zl=r.forwardRef(({className:e,...n},r)=>t(se.Item,{ref:r,className:le("border-b last:border-b-0",e),...n}));Zl.displayName="AccordionItem";const Xl=r.forwardRef(({className:n,children:r,...a},i)=>t(se.Header,{className:"flex",children:e(se.Trigger,{ref:i,className:le("flex flex-1 items-center gap-2 py-3 text-start text-sm font-medium transition-all hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-sm [&[data-state=open]>svg]:rotate-180",n),...a,children:[t(v,{className:"h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200","aria-hidden":"true"}),t("span",{className:"min-w-0 flex-1",children:r})]})}));Xl.displayName="AccordionTrigger";const ed=r.forwardRef(({className:e,children:n,...r},a)=>t(se.Content,{ref:a,className:"overflow-hidden text-sm data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...r,children:t("div",{className:le("pb-3 pt-0",e),children:n})}));function td({value:n,displayValue:a,copyLabel:i,copiedLabel:s,variant:o="inline",className:c}){const l=a??n,[d,u]=r.useState(!1),p=r.useRef(null);r.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const h=async()=>{await async function(e){try{if("undefined"!=typeof navigator&&navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),!0}catch{}if("undefined"==typeof document)return!1;try{const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.position="absolute",t.style.left="-9999px",document.body.appendChild(t),t.select();const n=document.execCommand("copy");return document.body.removeChild(t),n}catch{return!1}}(n)&&(u(!0),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>u(!1),2e3))},m=n=>e(bc,{type:"button",variant:"ghost",size:"sm",onClick:h,"aria-label":d?s:i,className:"h-7 shrink-0 gap-1.5 px-2",children:[t(d?k:S,{className:"h-3.5 w-3.5","aria-hidden":"true"}),t("span",{className:le("text-xs",n&&"hidden sm:inline"),children:d?s:i})]});return e("div","inline"===o?{dir:"ltr",className:le("flex items-center gap-2 rounded-md border bg-muted/40 py-1 ps-3 pe-1",c),children:[t("code",{className:"min-w-0 flex-1 truncate text-xs",title:n,children:l}),m(!0)]}:{dir:"code"===o?"ltr":void 0,className:le("overflow-hidden rounded-md border bg-muted/40",c),children:[t("div",{className:"flex justify-end border-b bg-muted/30 px-1.5 py-1",children:m(!1)}),"code"===o?t("pre",{className:"overflow-x-auto p-3 text-start text-xs leading-relaxed",children:t("code",{children:l})}):t("p",{className:"p-3 text-sm leading-relaxed",children:l})]})}function nd({config:n,title:r,description:a,className:i}){const{t:s}=Si(),o=Wc(),c=n??o;if(!c?.url)return null;const l=c.name?.trim()||"app",d={url:c.url,name:l,key:Rc(l)},u=(e,t,n,r)=>({id:e,name:t,instructions:s("security.mcpAddToConfigFile",{path:`⁦${n}⁩`}),snippet:r}),p=[{id:"chatgpt",name:"ChatGPT",instructions:s("security.mcpClientChatgptInstructions")},{id:"claude",name:"Claude",instructions:s("security.mcpClientClaudeInstructions")},u("cursor","Cursor","~/.cursor/mcp.json",'{\n "mcpServers": {\n "{{key}}": {\n "url": "{{url}}"\n }\n }\n}'),u("vscode","VS Code",".vscode/mcp.json",'{\n "servers": {\n "{{key}}": {\n "type": "http",\n "url": "{{url}}"\n }\n }\n}'),u("windsurf","Windsurf","~/.codeium/windsurf/mcp_config.json",'{\n "mcpServers": {\n "{{key}}": {\n "serverUrl": "{{url}}"\n }\n }\n}'),{id:"cline",name:"Cline",instructions:s("security.mcpClientClineInstructions")}],h=c.clients??p,m=void 0===r?s("security.mcpGuideTitle"):r,g=void 0===a?s("security.mcpGuideDescription"):a,f=s("security.mcpCopy"),y=s("security.mcpCopied"),w=!1===c.prompt?null:c.prompt??s("security.mcpPromptTemplate"),b=Uc(w??void 0,d),v=Uc(w??void 0,{...d,url:`⁦${d.url}⁩`,name:`⁨${d.name}⁩`});return e("div",{className:le("space-y-5",i),children:[t(Yl,{title:m,description:g}),e("div",{className:"space-y-1.5",children:[t("p",{className:"text-sm font-medium",children:s("security.mcpServerUrlLabel")}),t("p",{className:"text-xs text-muted-foreground",children:s("security.mcpServerUrlHint")}),t(td,{value:c.url,copyLabel:f,copiedLabel:y})]}),b&&e("div",{className:"space-y-1.5",children:[t("p",{className:"text-sm font-medium",children:s("security.mcpPromptLabel")}),t("p",{className:"text-xs text-muted-foreground",children:s("security.mcpPromptHint")}),t(td,{value:b,displayValue:v,copyLabel:f,copiedLabel:y,variant:"text"})]}),h.length>0&&e("div",{className:"space-y-1.5",children:[t("p",{className:"text-sm font-medium",children:s("security.mcpClientsLabel")}),t(Ql,{type:"single",collapsible:!0,defaultValue:h[0]?.id,className:"rounded-md border px-3",children:h.map(n=>{const r=Uc(n.instructions,d),a=Uc(n.snippet,d);return e(Zl,{value:n.id,children:[t(Xl,{children:n.name}),t(ed,{children:e("div",{className:"space-y-2",children:[r&&t("p",{className:"text-sm text-muted-foreground",children:r}),a&&t(td,{value:a,copyLabel:f,copiedLabel:y,variant:"code"}),n.actionUrl&&e("a",{href:n.actionUrl,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary hover:underline",children:[n.actionLabel??n.actionUrl,t(I,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})})]},n.id)})})]}),c.docsUrl&&e("a",{href:c.docsUrl,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary hover:underline",children:[s("security.mcpLearnMore"),t(I,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})}function rd({className:n,title:r,description:a,disconnectLabel:i,emptyLabel:s,showConnectGuide:o=!0}){const{t:c,formattingLocale:d}=Si(),{formats:p}=Jo(),{agents:m,loading:g,error:f,revoking:y,revoke:w}=Fl(),b=Wc(),v=o&&Boolean(b?.url),[k,S]=h(!1),[I,N]=h(null),[A,P]=h(null),E=Ol(),_=l(!1);u(()=>{if(_.current||!v)return;const e=nc.getState().params;e?.action===jt.OpenConnectGuide&&(_.current=!0,nc.clearParams(),S(!0))},[v]);const T=void 0===r?c("security.connectedAgentsTitle"):r,U=void 0===a?c("security.connectedAgentsDescription"):a,R=i??c("security.connectedAgentsDisconnect"),O=s??c("security.connectedAgentsEmpty"),W=c("security.mcpConnectAction"),F=e=>El(e,d,p?.date??{dateStyle:"medium"}),L=n=>v?e(bc,{size:"sm",onClick:()=>S(!0),"aria-label":W,className:"shrink-0 gap-1.5",children:[t(x,{className:"h-4 w-4","aria-hidden":"true"}),t("span",{className:n?"hidden sm:inline":void 0,children:W})]}):null;return e("div",{className:le("space-y-4",n),children:[t(Yl,{title:T,description:U,actions:!g&&m.length>0?L(!0):void 0}),g&&t("div",{className:"space-y-3",children:[0,1].map(e=>t(Kl,{className:"h-20 rounded-md"},e))}),f&&!g&&t("p",{role:"alert",className:"text-destructive text-sm",children:f}),A&&t(kl,{variant:"success",message:c("security.connectedAgentsDisconnected",{name:A})}),!g&&!f&&0===m.length&&t(Hl,{icon:t(C,{className:"h-5 w-5 text-muted-foreground"}),description:O,action:L(!1)??void 0}),!g&&m.length>0&&t("ul",{className:"space-y-3",children:m.map(n=>e("li",{className:"flex items-start justify-between gap-x-4 rounded-md border p-3",children:[e("div",{className:"flex min-w-0 flex-col gap-y-1",children:[t("span",{className:"text-sm font-medium break-words",children:n.title}),n.scope.length>0&&e("span",{className:"text-muted-foreground text-xs break-words",children:[c("security.connectedAgentsAccess"),": ",n.scope.join(", ")]}),n.lastGrantedAt&&e("span",{className:"text-muted-foreground text-xs",children:[c("security.connectedAgentsGranted"),": ",F(n.lastGrantedAt)]})]}),t(bc,{variant:"outline",size:"sm",progress:y===n.clientId,disabled:null!==y,onClick:()=>N(n),className:"shrink-0",children:R})]},n.clientId))}),t(Ll,{open:null!==I,onOpenChange:e=>{e||N(null)},children:e(jl,{children:[e(ql,{children:[t(Vl,{children:c("security.connectedAgentsConfirmTitle",{name:I?.title??""})}),t(zl,{children:c("security.connectedAgentsConfirmBody")})]}),e(Bl,{children:[t(Jl,{children:c("security.connectedAgentsCancel")}),t(Gl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:async()=>{if(!I)return;const{clientId:e,title:t}=I;N(null),P(null),await w(e)&&(P(t),E(()=>P(null)))},children:R})]})]})}),v&&t(ul,{open:k,onOpenChange:S,children:e(gl,{className:"h-dvh max-h-dvh min-w-full gap-4 overflow-y-auto p-4 sm:h-auto sm:max-h-[90vh] sm:w-full sm:min-w-0 sm:max-w-lg sm:p-6",children:[e(fl,{className:"pe-8",children:[t(wl,{children:c("security.mcpGuideTitle")}),t(bl,{children:c("security.mcpGuideDescription")})]}),t(nd,{title:null,description:null})]})})]})}function ad({label:n,className:r}){const{t:a}=Si();return e("div",{role:"status","aria-live":"polite",className:le("flex items-center gap-2 rounded-lg border bg-muted/50 px-4 py-3 text-sm text-muted-foreground",r),children:[t(w,{className:"h-4 w-4 animate-spin flex-shrink-0"}),t("span",{children:n??a("settings.common.loading")})]})}function id(){const e=oo();return s(()=>new Qe(e),[e.serverUrl,e.version])}function sd(){const e=id(),{t:t}=Si(),[n,r]=h([]),[a,i]=h(!0),[o,c]=h(null),[d,m]=h(null),g=l(null),f=l(t);u(()=>{f.current=t},[t]);const y=p(async()=>{g.current?.abort();const t=new AbortController;g.current=t,i(!0),c(null);try{const n=await e.list(t.signal);t.signal.aborted||r(n)}catch(e){if(t.signal.aborted)return;ve(e,{component:"useDevices",action:"list"}),c(ke(e,"security.devicesLoadFailed",f.current))}finally{g.current===t&&(g.current=null,i(!1))}},[e]);u(()=>(y(),()=>g.current?.abort()),[y]);const w=p(async(t,n)=>{m(t),c(null);try{await e.rename(t,n),r(e=>e.map(e=>e.deviceId===t?{...e,name:n}:e))}catch(e){ve(e,{component:"useDevices",action:"rename"}),c(ke(e,"security.deviceRenameFailed",f.current))}finally{m(null)}},[e]),b=p(async t=>{m(t),c(null);try{await e.signOut(t),r(e=>e.map(e=>e.deviceId===t?{...e,activeSessions:0}:e))}catch(e){ve(e,{component:"useDevices",action:"signOut"}),c(ke(e,"security.deviceSignOutFailed",f.current))}finally{m(null)}},[e]),v=p(async t=>{m(t),c(null);try{await e.forget(t),r(e=>e.filter(e=>e.deviceId!==t))}catch(e){ve(e,{component:"useDevices",action:"forget"}),c(ke(e,"security.deviceForgetFailed",f.current))}finally{m(null)}},[e]);return s(()=>({devices:n,loading:a,error:o,busyId:d,refresh:y,rename:w,signOut:b,forget:v}),[n,a,o,d,y,w,b,v])}function od(e){return!!e&&/Mobi|Android|iPhone|iPad|iPod|Windows Phone/i.test(e)}function cd(e){return/Windows NT/.test(e)?"Windows":/iPhone/.test(e)?"iPhone":/iPad/.test(e)?"iPad":/Android/.test(e)?"Android":/Mac OS X|Macintosh/.test(e)?"macOS":/CrOS/.test(e)?"ChromeOS":/Linux/.test(e)?"Linux":""}function ld(e){return e?[(t=e,/Edg\//.test(t)?"Edge":/OPR\/|Opera/.test(t)?"Opera":/Firefox\//.test(t)?"Firefox":/Chrome\//.test(t)?"Chrome":/Safari\//.test(t)&&/Version\//.test(t)?"Safari":""),cd(e)].filter(Boolean).join(" · "):"";var t}ed.displayName="AccordionContent";const dd=r.forwardRef(({className:e,type:n,...r},a)=>t("input",{type:n,className:le("flex h-10 sm:h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base sm:text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:a,...r}));function ud({className:r,title:a,description:i,showRename:s,showSignOut:o,showRemove:c,renameLabel:l,signOutLabel:d,removeLabel:u,emptyLabel:p}){const{t:m,formattingLocale:g}=Si(),{formats:f}=Jo(),{visible:y}=Pl(),{devices:w,loading:b,error:v,busyId:S,rename:I,signOut:C,forget:x}=sd(),[T,U]=h(null),[R,O]=h(""),[W,F]=h(null),L=s??y(e=>e.settings?.devices?.rename),D=o??y(e=>e.settings?.devices?.signOut),$=c??y(e=>e.settings?.devices?.forget),M=L||D||$,j=void 0===a?m("security.devicesTitle"):a,q=void 0===i?m("security.devicesDescription"):i,B=l??m("security.deviceRename"),V=d??m("security.deviceSignOut"),z=u??m("security.deviceForget"),G=p??m("security.devicesEmpty"),J=e=>El(e,g,f?.date??{dateStyle:"medium"}),H=async e=>{const t=R.trim();t&&await I(e,t),U(null)};return e("div",{className:le("space-y-4",r),children:[t(Yl,{title:j,description:q}),b&&t("div",{className:"space-y-3",children:[0,1].map(e=>t(Kl,{className:"h-24 rounded-md"},e))}),v&&!b&&t("p",{className:"text-destructive text-sm",children:v}),!b&&!v&&0===w.length&&t(Hl,{icon:t(N,{className:"h-5 w-5 text-muted-foreground"}),description:G}),!b&&w.length>0&&t("ul",{className:"space-y-3",children:w.map(r=>{const a=T===r.deviceId,i=S===r.deviceId,s=ld(r.userAgent),o=function(e){return[[e.ipInfo?.city,e.ipInfo?.country].filter(Boolean).join(", "),e.ip].filter(Boolean).join(" · ")}(r),c=od(r.userAgent)?A:N;return e("li",{className:"flex items-start justify-between gap-x-4 rounded-md border p-3",children:[e("div",{className:"flex min-w-0 gap-x-3",children:[t(c,{className:"text-muted-foreground mt-0.5 h-5 w-5 shrink-0","aria-hidden":"true"}),e("div",{className:"flex min-w-0 flex-col gap-y-1",children:[e("div",a?{className:"flex items-center gap-x-2",children:[t(dd,{value:R,onChange:e=>O(e.target.value),placeholder:m("security.deviceRenamePlaceholder"),className:"h-8 w-48",autoFocus:!0,onKeyDown:e=>{"Enter"===e.key&&H(r.deviceId),"Escape"===e.key&&U(null)}}),t(bc,{size:"sm",variant:"ghost","aria-label":m("security.deviceSave"),progress:i,onClick:()=>H(r.deviceId),children:t(k,{className:"h-4 w-4","aria-hidden":"true"})}),t(bc,{size:"sm",variant:"ghost","aria-label":m("security.deviceCancel"),onClick:()=>U(null),children:t(P,{className:"h-4 w-4","aria-hidden":"true"})})]}:{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[t("span",{className:"text-sm font-medium break-words",children:r.name}),r.current&&t("span",{className:"bg-primary/10 text-primary rounded px-1.5 py-0.5 text-xs font-medium",children:m("security.deviceCurrent")}),r.trusted&&e("span",{className:"text-primary inline-flex items-center gap-x-1 text-xs",children:[t(E,{className:"h-3.5 w-3.5","aria-hidden":"true"}),m("security.deviceTrusted")]}),r.pushEnabled&&t("span",{className:"text-muted-foreground inline-flex","aria-label":m("security.devicePushEnabled"),title:m("security.devicePushEnabled"),children:t(_,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]}),s&&t("span",{className:"text-muted-foreground text-xs break-words",children:s}),o&&t("span",{className:"text-muted-foreground text-xs break-words",children:o}),e("span",{className:"text-muted-foreground text-xs",children:[r.lastActiveAt&&m("security.deviceLastActive",{date:J(r.lastActiveAt)}),r.activeSessions>0&&e(n,{children:[r.lastActiveAt&&" · ",m("security.deviceActiveSessions",{count:r.activeSessions})]})]})]})]}),!a&&M&&e("div",{className:"flex shrink-0 flex-col items-end gap-y-1.5",children:[(L||D)&&e("div",{className:"flex items-center gap-x-1.5",children:[L&&t(bc,{variant:"ghost",size:"sm",disabled:i,onClick:()=>(e=>{U(e.deviceId),O(e.name)})(r),children:B}),D&&r.activeSessions>0&&t(bc,{variant:"outline",size:"sm",progress:i,onClick:()=>C(r.deviceId),children:V})]}),$&&t(bc,{variant:"ghost",size:"sm",className:"text-destructive hover:bg-destructive/10 hover:text-destructive",disabled:i,onClick:()=>F(r),children:z})]})]},r.deviceId)})}),t(Ll,{open:null!==W,onOpenChange:e=>{e||F(null)},children:e(jl,{children:[e(ql,{children:[t(Vl,{children:m("security.deviceForgetConfirmTitle")}),t(zl,{children:m("security.deviceForgetConfirmBody")})]}),e(Bl,{children:[t(Jl,{children:m("security.deviceCancel")}),t(Gl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:async()=>{if(!W)return;const{deviceId:e}=W;F(null),await x(e)},children:z})]})]})})]})}function pd(){const e=oo();return s(()=>new nt(e),[e.serverUrl,e.version])}function hd(){const e=pd(),{t:t}=Si(),[n,r]=h([]),[a,i]=h(!0),[o,c]=h(null),[d,m]=h(null),g=l(null),f=l(t);u(()=>{f.current=t},[t]);const y=p(async()=>{g.current?.abort();const t=new AbortController;g.current=t,i(!0),c(null);try{const n=await e.list(t.signal);t.signal.aborted||r(n)}catch(e){if(t.signal.aborted)return;ve(e,{component:"useSessions",action:"list"}),c(ke(e,"security.sessionsLoadFailed",f.current))}finally{g.current===t&&(g.current=null,i(!1))}},[e]);u(()=>(y(),()=>g.current?.abort()),[y]);const w=p(async t=>{m(t),c(null);try{await e.revoke(t),r(e=>e.filter(e=>e.id!==t))}catch(e){ve(e,{component:"useSessions",action:"revoke"}),c(ke(e,"security.sessionSignOutFailed",f.current))}finally{m(null)}},[e]);return s(()=>({sessions:n,loading:a,error:o,revoking:d,refresh:y,revoke:w}),[n,a,o,d,y,w])}function md({className:r,title:a,description:i,showSignOut:s,signOutLabel:o,emptyLabel:c}){const{t:l,formattingLocale:d}=Si(),{formats:u}=Jo(),{visible:p}=Pl(),{sessions:h,loading:m,error:g,revoking:f,revoke:y}=hd(),w=s??p(e=>e.settings?.devices?.sessionSignOut),b=void 0===a?l("security.sessionsTitle"):a,v=void 0===i?l("security.sessionsDescription"):i,k=o??l("security.sessionSignOut"),S=c??l("security.sessionsEmpty"),I=e=>El(e,d,u?.date??{dateStyle:"medium"});return e("div",{className:le("space-y-4",r),children:[t(Yl,{title:b,description:v}),m&&t("div",{className:"space-y-3",children:[0,1].map(e=>t(Kl,{className:"h-20 rounded-md"},e))}),g&&!m&&t("p",{className:"text-destructive text-sm",children:g}),!m&&!g&&0===h.length&&t(Hl,{icon:t(T,{className:"h-5 w-5 text-muted-foreground"}),description:S}),!m&&h.length>0&&t("ul",{className:"space-y-3",children:h.map(r=>{const a=ld(r.userAgent),i=function(e){return[[e.ipInfo?.city,e.ipInfo?.country].filter(Boolean).join(", "),e.ip].filter(Boolean).join(" · ")}(r),s=r.device?.name||a||l("security.sessionsTitle"),o=od(r.userAgent)?A:N;return e("li",{className:"flex items-start justify-between gap-x-4 rounded-md border p-3",children:[e("div",{className:"flex min-w-0 gap-x-3",children:[t(o,{className:"text-muted-foreground mt-0.5 h-5 w-5 shrink-0","aria-hidden":"true"}),e("div",{className:"flex min-w-0 flex-col gap-y-1",children:[e("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[t("span",{className:"text-sm font-medium break-words",children:s}),r.current&&t("span",{className:"bg-primary/10 text-primary rounded px-1.5 py-0.5 text-xs font-medium",children:l("security.sessionCurrent")})]}),a&&s!==a&&t("span",{className:"text-muted-foreground text-xs break-words",children:a}),i&&t("span",{className:"text-muted-foreground text-xs break-words",children:i}),e("span",{className:"text-muted-foreground text-xs",children:[r.lastActiveAt&&e(n,{children:[l("security.sessionLastActive",{date:I(r.lastActiveAt)}),r.expiresAt&&" · "]}),r.expiresAt&&l("security.sessionExpires",{date:I(r.expiresAt)})]})]})]}),!r.current&&w&&t(bc,{variant:"ghost",size:"sm",progress:f===r.id,onClick:()=>y(r.id),className:"text-destructive hover:bg-destructive/10 hover:text-destructive shrink-0",children:k})]},r.id)})})]})}dd.displayName="Input";const gd=ce.Root,fd=ce.Trigger,yd=r.forwardRef(({className:e,align:n="center",sideOffset:a=4,...i},s)=>{const{container:o}=r.useContext(Gc);return t(ce.Portal,{container:o,children:t(ce.Content,{ref:s,align:n,sideOffset:a,className:le("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...i})})});yd.displayName=ce.Content.displayName;const wd=z("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),bd=r.forwardRef(({className:e,...n},r)=>t(ee.Root,{ref:r,className:le(wd(),e),...n}));bd.displayName=ee.Root.displayName;const vd=Q,kd=r.createContext({}),Sd=({...e})=>t(kd.Provider,{value:{name:e.name},children:t(K,{...e})}),Id=()=>{const e=r.useContext(kd),t=r.useContext(Cd),{getFieldState:n,formState:a}=Z(),i=n(e.name,a);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:s}=t;return{id:s,name:e.name,formItemId:`${s}-form-item`,formDescriptionId:`${s}-form-item-description`,formMessageId:`${s}-form-item-message`,...i}},Cd=r.createContext({}),xd=r.forwardRef(({className:e,...n},a)=>{const i=r.useId();return t(Cd.Provider,{value:{id:i},children:t("div",{ref:a,className:le("space-y-2",e),...n})})});xd.displayName="FormItem";const Nd=r.forwardRef(({className:e,...n},r)=>{const{error:a,formItemId:i}=Id();return t(bd,{ref:r,className:le(a&&"text-destructive",e),htmlFor:i,...n})});Nd.displayName="FormLabel";const Ad=r.forwardRef(({...e},n)=>{const{error:r,formItemId:a,formDescriptionId:i,formMessageId:s}=Id();return t(V,{ref:n,id:a,"aria-describedby":r?`${i} ${s}`:`${i}`,"aria-invalid":!!r,...e})});Ad.displayName="FormControl";const Pd=r.forwardRef(({className:e,...n},r)=>{const{formDescriptionId:a}=Id();return t("p",{ref:r,id:a,className:le("text-sm text-muted-foreground",e),...n})});Pd.displayName="FormDescription";const Ed=r.forwardRef(({className:e,children:n,...r},a)=>{const{error:i,formMessageId:s}=Id(),o=i?String(i?.message):n;return o?t("p",{ref:a,id:s,className:le("text-sm font-medium text-destructive",e),...r,children:o}):null});Ed.displayName="FormMessage";const _d=r.forwardRef(({className:e,...n},r)=>t(re.Root,{className:le("grid gap-2",e),...n,ref:r}));_d.displayName=re.Root.displayName;const Td=r.forwardRef(({className:e,...n},r)=>t(re.Item,{ref:r,className:le("aspect-square h-4 w-4 rounded-full border border-primary text-primary shadow focus:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),...n,children:t(re.Indicator,{className:"flex items-center justify-center",children:t(H,{className:"h-3.5 w-3.5 fill-primary"})})}));Td.displayName=re.Item.displayName;const Ud=r.forwardRef(({className:n,children:r,...a},i)=>e(ae.Root,{ref:i,className:le("relative overflow-hidden",n),...a,children:[t(ae.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),t(Rd,{}),t(ae.Corner,{})]}));Ud.displayName=ae.Root.displayName;const Rd=r.forwardRef(({className:e,orientation:n="vertical",...r},a)=>t(ae.ScrollAreaScrollbar,{ref:a,orientation:n,className:le("flex touch-none select-none transition-colors","vertical"===n&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===n&&"h-2.5 border-t border-t-transparent p-[1px]",e),...r,children:t(ae.ScrollAreaThumb,{className:le("relative rounded-full bg-border","vertical"===n&&"flex-1")})}));function Od(){const e=oo();return s(()=>new pt(e),[e.serverUrl,e.version])}Rd.displayName=ae.ScrollAreaScrollbar.displayName;const Wd={tooLarge:"uploads.errorTooLarge",invalid:"uploads.errorInvalid",disabled:"uploads.errorDisabled",userLimit:"uploads.errorUserLimit",unavailable:"uploads.errorUnavailable",failed:"uploads.errorFailed"};function Fd(e){const t=Od(),{settings:n}=uo(),{t:r,formattingLocale:a}=Si(),[i,o]=h(!1),[c,d]=h(null),m=l(null),g=l(!0),f=s(()=>lt(n),[n]),y=s(()=>ut(f.maxFileBytes,a),[f.maxFileBytes,a]);u(()=>(g.current=!0,()=>{g.current=!1,m.current?.abort()}),[]);const w=p(()=>m.current?.abort(),[]),b=p(async n=>{m.current?.abort();const r=dt(n,f);if(r)throw d(r),Object.assign(new Error(`The upload was refused: ${r}.`),{code:"disabled"===r?"UPLOADS_DISABLED":"UPLOAD_TOO_LARGE",status:"disabled"===r?403:413});const a=new AbortController;m.current=a,o(!0),d(null);try{return await t.upload(n,{purpose:e,signal:a.signal})}catch(e){throw!me(e)&&g.current&&d(ct(e)),ve(e,{component:"useUpload",action:"upload"}),e}finally{m.current===a&&(m.current=null,g.current&&o(!1))}},[t,e,f]),v=c?r(Wd[c],{max:y}):null;return s(()=>({upload:b,cancel:w,loading:i,error:v,failure:c,enabled:f.enabled,maxBytes:f.maxFileBytes,maxLabel:y}),[b,w,i,v,c,f,y])}function Ld(e){return`data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><text x="50%" y="50%" dominant-baseline="middle" alignment-baseline="middle" text-anchor="middle" font-size="50" font-family="sans-serif">${e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}</text></svg>`}const Dd=["🏢","🏬","🏣","🏤","🏦","🏛️","🏠","🏡","🏭","🏗️","🏪","🏨","🏫","🏥","💼","📊","📈","📉","📋","📁","📂","🗂️","🗃️","🗄️","📅","🗓️","📝","🖋️","✏️","🖊️","🖌️","🖍️","📇","📌","📍","📎","🖇️","💻","🖥️","🖨️","🖱️","⌨️","📱","📲","📡","🌐","🔗","🔒","🔓","⚙️","🔧","🛠️","🧑‍💻","👨‍💻","👩‍💻","🕹️","💾","📟","🖥️","🖲️","🚀","💡","🎨","🖼️","🧪","🔬","🧬","🎯","⚡","🎲","🎮","🧩","📷","🎥","✉️","📨","📩","📧","📞","☎️","📠","🗣️","💬","🗨️","📢","📣","🔔","🛎️","💰","💸","💳","🏦","📈","📉","⚖️","🧾","🪙","🏛️","⚗️","🧪","🔭","🔬","🩺","🧬","🩻","🏥","🌱","🌍","🌏","🌎","🌡️","👨‍💼","👩‍💼","👨‍🏫","👩‍🏫","👨‍🔬","👩‍🔬","👨‍🎨","👩‍🎨","👨‍🔧","👩‍🔧","👨‍🚀","👩‍🚀","👨‍⚖️","👩‍⚖️","🏅","🎖️","🥇","🥈","🥉","🏆","🎗️","🔑","🗝️","🧭","🛡️","🚩","🏳️‍🌈","🎟️","🎫"],$d={step:"details",request:null,profile:null,error:null,retryAfter:0,resent:!1};function Md(e){if(je(e))return{message:"",unreachable:!0};const{status:t,code:n}=e??{};return{message:e instanceof Error&&e.message?e.message:"",..."number"==typeof t?{status:t}:{},..."string"==typeof n?{code:n}:{}}}function jd(e){const t=e?.retryAfter;return"number"==typeof t&&t>0?t:0}async function qd(e,t,n){const r=n??t.request;if(!r)return t;try{const{retryAfter:a}=await e.requestGuestUpgrade(r);return{...t,step:"code",request:r,error:null,retryAfter:a,resent:!n}}catch(e){return{...t,error:Md(e),retryAfter:jd(e),resent:!1}}}function Bd(){const[e,t]=h(0),[n,r]=h(()=>Date.now());u(()=>{if(e<=Date.now())return;r(Date.now());const t=setInterval(()=>{const n=Date.now();r(n),n>=e&&clearInterval(t)},1e3);return()=>clearInterval(t)},[e]);const a=p(e=>{const n=Date.now();r(n),t(n+1e3*e)},[]),i=p(()=>t(0),[]);return{waitSeconds:Math.max(0,Math.ceil((e-n)/1e3)),wait:a,clear:i}}function Vd(){const{api:e}=po(),{t:t}=Si(),n=_a(),r=!0===fc().session?.user.isAnonymous,{waitSeconds:a,wait:i,clear:o}=Bd(),[c,d]=h($d),[u,m]=h(null),g=l(c);g.current=c;const f=p((e,n)=>{const r=e.error&&!e.error.message?{...e,error:{...e.error,message:t(e.error.unreachable?"errors.unreachable":"settings.common.error")}}:e;return d(r),r.retryAfter>0&&i(r.retryAfter),r.error&&be(Object.assign(new Error(r.error.message),r.error),{component:"useGuestUpgrade",action:n}),!r.error},[i,t]),y=p(async t=>{m("send");try{const n=await qd(e,{...g.current,error:null},t);return f(n,"requestGuestUpgrade")}finally{m(null)}},[e,f]),w=p(async()=>{m("resend");try{const t=await qd(e,{...g.current,error:null});return f(t,"requestGuestUpgrade")}finally{m(null)}},[e,f]),b=p(async t=>{m("confirm");try{const r=await async function(e,t,n){try{const r=await e.confirmGuestUpgrade(n);return{...t,step:"done",profile:r,error:null,retryAfter:0,resent:!1}}catch(e){return{...t,error:Md(e),resent:!1}}}(e,{...g.current,error:null},t);if("done"===r.step){o();const e=n.getState().session;e&&n.dispatch(wa.setSession(function(e,t,n){if(t)try{const n=mc({...t,isAnonymous:!1},e.user.org,e.user.clientId);return{...e,user:n}}catch{}const r=n?.name?.trim();return{...e,user:{...e.user,isAnonymous:!1,...n?{email:n.email.trim(),emailVerified:!0}:{},...r?{name:r}:{}}}}(e,r.profile,r.request)))}return f(r,"confirmGuestUpgrade")}finally{m(null)}},[e,f,o,n]),v=p(()=>{o(),d($d)},[o]);return s(()=>({isGuest:r,step:c.step,email:c.request?.email.trim()??null,profile:c.profile,pending:u,error:c.error,waitSeconds:a,resent:c.resent,start:y,resend:w,confirm:b,reset:v}),[r,c,u,a,y,w,b,v])}const zd=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,Gd=({busy:n,waitSeconds:r,onSubmit:a})=>{const{t:i}=Si(),s=te.object({email:te.string().trim().refine(e=>zd.test(e),{message:i("guest.emailInvalid")}),name:te.string().max(200),password:te.string().refine(e=>""===e||e.length>=8,{message:i("guest.passwordMinLength")})}),o=X({resolver:Y(s),defaultValues:{email:"",name:"",password:""}});return t(vd,{...o,children:e("form",{noValidate:!0,onSubmit:o.handleSubmit(e=>a({email:e.email,...e.name.trim()?{name:e.name.trim()}:{},...e.password?{password:e.password}:{}})),className:"space-y-3 rounded-md border p-4",children:[t(Sd,{disabled:n,control:o.control,name:"email",render:({field:n})=>e(xd,{children:[t(Nd,{children:i("guest.emailLabel")}),t(Ad,{children:t(dd,{type:"email",dir:"ltr",autoComplete:"email",autoCapitalize:"off",spellCheck:!1,...n})}),t(Ed,{})]})}),t(Sd,{disabled:n,control:o.control,name:"name",render:({field:n})=>e(xd,{children:[t(Nd,{children:i("guest.nameLabel")}),t(Ad,{children:t(dd,{autoComplete:"name",maxLength:200,...n})}),t(Ed,{})]})}),t(Sd,{disabled:n,control:o.control,name:"password",render:({field:n})=>e(xd,{children:[t(Nd,{children:i("guest.passwordLabel")}),t(Ad,{children:t(dd,{type:"password",autoComplete:"new-password",maxLength:256,...n})}),t("p",{className:"text-xs text-muted-foreground",children:i("guest.passwordHint")}),t(Ed,{})]})}),t("div",{className:"flex justify-end",children:t(bc,{type:"submit",progress:n,disabled:n||r>0,children:r>0?i("guest.resendIn",{seconds:r}):i("guest.send")})})]})})},Jd=({email:n,confirming:r,resending:a,waitSeconds:i,onSubmit:s,onResend:o,onCancel:c})=>{const{t:l}=Si(),d=r||a,u=te.object({code:te.string().refine(e=>/^\d{6}$/.test((e=>e.replace(/\s+/g,""))(e)),{message:l("guest.codeInvalid")})}),p=X({resolver:Y(u),defaultValues:{code:""}});return t(vd,{...p,children:e("form",{onSubmit:p.handleSubmit(e=>s(e.code)),className:"space-y-3 rounded-md border p-4",children:[t("p",{className:"break-words text-sm",children:l("guest.sentTo",{email:n})}),t(Sd,{disabled:d,control:p.control,name:"code",render:({field:n})=>e(xd,{children:[t(Nd,{children:l("guest.codeLabel")}),t(Ad,{children:t(dd,{dir:"ltr",autoFocus:!0,autoComplete:"one-time-code",autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,inputMode:"numeric",maxLength:7,className:"font-mono sm:max-w-xs",...n})}),t(Ed,{})]})}),e("div",{className:"flex flex-col-reverse gap-2 sm:flex-row sm:items-center sm:justify-between",children:[t(bc,{type:"button",variant:"outline",progress:a,disabled:d||i>0,onClick:o,children:i>0?l("guest.resendIn",{seconds:i}):l("guest.resend")}),e("div",{className:"flex flex-wrap justify-end gap-2",children:[t(bc,{type:"button",variant:"ghost",disabled:d,onClick:c,children:l("settings.common.cancel")}),t(bc,{type:"submit",progress:r,disabled:d,children:l("guest.confirm")})]})]})]})})};function Hd({className:n,title:r,description:a,onUpgraded:i}){const{t:s}=Si(),o=Vd(),c=l(!1);if(u(()=>{"done"!==o.step||c.current||(c.current=!0,i?.({profile:o.profile,email:o.profile?.email||o.email||""}))},[o.step,o.profile,o.email,i]),!o.isGuest&&"done"!==o.step)return null;const d=void 0===r?s("guest.title"):r,p=void 0===a?s("guest.description"):a;return t("div",{className:"saas-os-ui",style:{backgroundColor:"transparent"},children:e("div",{className:le("space-y-4",n),children:[(d||p)&&t(Yl,{title:d??void 0,description:p??void 0}),o.error&&t(kl,{variant:"error",title:s("settings.common.error"),message:o.error.message}),"code"===o.step&&o.resent&&!o.error&&o.email&&t(kl,{variant:"success",message:s("guest.resent",{email:o.email})}),"done"===o.step?t(kl,{variant:"success",title:s("settings.common.success"),message:s("guest.done",{email:o.email??""})}):"code"===o.step&&o.email?t(Jd,{email:o.email,confirming:"confirm"===o.pending,resending:"resend"===o.pending,waitSeconds:o.waitSeconds,onSubmit:e=>{o.confirm(e)},onResend:()=>{o.resend()},onCancel:o.reset}):t(Gd,{busy:"send"===o.pending,waitSeconds:o.waitSeconds,onSubmit:e=>{o.start(e)}})]})})}const Yd=r.forwardRef(({className:e,...n},r)=>t(ne.Root,{ref:r,className:le("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...n}));Yd.displayName=ne.Root.displayName;const Kd=r.forwardRef(({className:e,...n},r)=>t(ne.Image,{ref:r,className:le("aspect-square h-full w-full",e),...n}));Kd.displayName=ne.Image.displayName;const Qd=r.forwardRef(({className:e,...n},r)=>t(ne.Fallback,{ref:r,className:le("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...n}));function Zd(e,t){const{response:n}=Uo(),{settings:r}=uo(),a=t?.settingsMaxUsers??r?.workspace?.maxWorkspaceUsers;return s(()=>{if(!e)return{hasSeatPricing:!1,memberCount:0,includedSeats:0,maxUsers:0,maxSeats:0,limitSource:"none",billableSeats:0,availableSeats:1/0,isAtMax:!1,isNearMax:!1,perSeatPriceCents:null,currency:"",canInvite:!0,inviteBlockReason:null,inviteBlockMessageKey:null,inviteBlockMessageValues:null};const r=(e.users?.length??0)+(t?.pendingInvitations??0),i=n?.planVersion,s=n?.subscription,o=e.billingCurrency||"usd",c=Qn({planVersion:i,currency:o,settingsMaxUsers:a}),{maxUsers:l,hasSeatPricing:d,includedSeats:u}=c,p=d?Math.max(0,r-u):0,h=l>0?Math.max(0,l-r):1/0,m=l>0&&r>=l,g=l>0&&r>=.8*l&&!m,f=d&&i?Jn(i,o,s?.billingInterval??"monthly"):null,y=Zn({memberCount:r,maxUsersConfig:c});return{hasSeatPricing:d,memberCount:r,includedSeats:u,maxUsers:l,maxSeats:l,limitSource:c.source,billableSeats:p,availableSeats:h,isAtMax:m,isNearMax:g,perSeatPriceCents:f,currency:o,canInvite:y.canInvite,inviteBlockReason:y.blockReason,inviteBlockMessageKey:y.blockMessageKey,inviteBlockMessageValues:y.blockMessageValues}},[n,e,a,t?.pendingInvitations])}function Xd(e){const{listInvitations:t,resendInvitation:n,revokeInvitation:r}=sc(),{t:a}=Si(),{begin:i,settle:o}=xi(),[c,d]=h([]),[m,g]=h(Boolean(e)),[f,y]=h(null),[w,b]=h(null),v=l(a);u(()=>{v.current=a},[a]);const k=p(async()=>{if(!e)return d([]),void g(!1);const n=i();g(!0),y(null);try{const r=await t(e);if(n.signal.aborted)return;d(na(r))}catch(e){if(n.signal.aborted)return;ve(e,{component:"useWorkspaceInvitations",action:"list"}),y(ke(e,"users.invitations.loadFailed",v.current))}finally{o(n)&&g(!1)}},[e,t,i,o]);u(()=>{k()},[k]);const S=p(async t=>{if(!e)throw new Error("No workspace");b(t),y(null);try{const r=await n(e,t);return d(e=>na(e.map(e=>e._id===t?{...e,...r}:e))),r}catch(e){throw ve(e,{component:"useWorkspaceInvitations",action:"resend"}),y(ke(e,"users.invitations.resendFailed",v.current)),e}finally{b(null)}},[e,n]),I=p(async t=>{if(!e)throw new Error("No workspace");b(t),y(null);try{await r(e,t),d(e=>e.filter(e=>e._id!==t))}catch(e){throw ve(e,{component:"useWorkspaceInvitations",action:"revoke"}),y(ke(e,"users.invitations.revokeFailed",v.current)),e}finally{b(null)}},[e,r]),C=s(()=>c.filter(e=>ra(e)).length,[c]);return s(()=>({invitations:c,pendingCount:C,loading:m,error:f,busy:w,refresh:k,resend:S,revoke:I}),[c,C,m,f,w,k,S,I])}function eu(e){return e?.workspace}function tu(e){return!1!==eu(e)?.canInviteMembers}function nu(e){return 1!==eu(e)?.maxWorkspacesPerUser}Qd.displayName=ne.Fallback.displayName;const ru="text-foreground/70";function au({title:n,children:r,className:a}){return e("div",{className:le("px-2 flex flex-col gap-1",a),children:[t("div",{className:le("text-xs font-bold uppercase tracking-wide px-2 pb-1 shrink-0 whitespace-nowrap",ru),children:n}),r]})}function iu({icon:n,label:r,active:a=!1,onClick:i,className:s}){return e("button",{className:le("flex w-full text-start px-2 py-2.5 sm:py-1 rounded text-sm items-center gap-x-2 sm:gap-x-1 whitespace-nowrap shrink-0",a?"bg-primary/10 text-primary font-medium":"hover:bg-muted hover:text-foreground",s),onClick:i,"aria-current":a?"true":void 0,children:[n,t("span",{className:"min-w-0 truncate",children:r}),t(U,{"aria-hidden":"true",className:"h-4 w-4 ms-auto opacity-40 sm:hidden rtl:rotate-180"})]})}const su=g(()=>import("./SettingsDialog-BVyV5Zfm.mjs").then(function(e){return e.e}).then(e=>({default:e.default})));const ou=({children:r})=>{const{currentWorkspace:a,switchToWorkspace:i,workspaces:s}=sc(),[o,c]=h(!1),[d,p]=h(ec.Profile),g=l(!1);return u(()=>{const e=nc.getState();c(e.open),p(e.section);return nc.subscribe(e=>{c(e.open),p(e.section)})},[]),u(()=>{if(g.current)return;if(!a)return;const e=Jt();if(!e)return;const t=function(e){if(e.screen&&tc.has(e.screen))return e.screen;switch(e.action){case jt.Checkout:case jt.Billing:case jt.SelectPlan:return ec.Subscription;case jt.CreditPurchase:return ec.Credits;case jt.OpenConnectGuide:return ec.ConnectedAgents;default:return null}}(e);if(!t)return g.current=!0,void Ht();const n=e.ws;if(n&&n!==a._id){const e=s.find(e=>e._id===n);return e?void i(e).catch(e=>{be(e,{component:"WorkspaceSettingsProvider",action:"switchWorkspaceFromUrl",metadata:{targetWs:n}}),g.current=!0,Ht()}):(g.current=!0,void Ht())}g.current=!0,nc.openWorkspaceSettings(t,e),Ht()},[a,s,i]),e(n,{children:[r,t(Nl,{}),a&&o&&t(ya,{fallback:null,children:t(m,{fallback:null,children:t(su,{workspace:a,open:o,onOpenChange:e=>{e||nc.closeSettings()},section:d,onSectionChange:e=>{nc.setSection(e)},showTrigger:!1})})})]})},cu=(e,t,n)=>{if(t!==Ct.V1)throw new Error(`Invalid version: "${t}". Only "${Ct.V1}" is currently supported.`);if(!e||"string"!=typeof e)throw new Error("serverUrl is required and must be a string");if(!(e=>{try{return new URL(e),!0}catch{return!1}})(e))throw new Error(`Invalid serverUrl: "${e}". Must be a valid URL.`);if(!n||"string"!=typeof n)throw new Error("orgId is required and must be a string");if(!/^[0-9a-fA-F]{24}$/.test(n))throw new Error(`Invalid orgId: "${n}". Must be a valid MongoDB ObjectId (24 hexadecimal characters).`)};function lu(){const{impersonationBanner:e}=Jo();return!1===e?null:t(vc,{})}const du=a.memo(({serverUrl:n,version:r,orgId:i,region:s,auth:o,locale:c,defaultPermissions:l,getCheckoutStripeParams:d,loadingComponent:p,ui:h,mcp:m,tracking:g,children:f})=>{cu(n,r,i);const y=a.useMemo(()=>({serverUrl:n,version:r,orgId:i,...void 0!==s&&{region:s}}),[n,r,i,s]),w=a.useMemo(()=>o?.callbacks,[o?.callbacks?.handleAuthentication,o?.callbacks?.onSignOut,o?.callbacks?.getSession,o?.callbacks?.onSessionExpired,o?.callbacks?.handleEvent,o?.callbacks?.onWorkspaceChange]),b=o?.callbacks?.handleEvent;return u(()=>(Pt.setCallbacks(b?{handleEvent:b}:null),()=>{Pt.setCallbacks(null)}),[b]),t(gi,{locale:c,messageOverrides:h?.messages,children:t(ii,{children:t(Fo,{loadingComponent:p,children:t(Vc,{callbacks:w,children:t(Jc,{children:t(zc,{config:y,auth:o,children:t(Go,{ui:h,children:t(oi,{getCheckoutStripeParams:d,children:t(Lc,{appPermissions:l,children:t(ic,{children:e(Oc,{mcp:m,children:[t(lu,{}),t(dl,{children:t(To,{children:t(Mc,{children:t(Ec,{children:t(Kc,{children:g&&o?.clientId?t(ro,{serverUrl:n,orgId:i,clientId:o.clientId,...g,children:t(ou,{children:t(cl,{children:f})})}):t(ou,{children:f})})})})})})]})})})})})})})})})})})});du.displayName="SaaSOSProviderInner";const uu=({children:e,...n})=>t(ya,{errorTitle:n.ui?.errorBoundary?.title,retryLabel:n.ui?.errorBoundary?.retryLabel,children:t(du,{...n,children:e})});uu.displayName="SaaSOSProvider";const pu=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{status:a}=yc();return vr(a).isLoading?n??null:a!==br.authenticated?r??null:t},hu=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{status:a}=yc();return vr(a).isLoading?n??null:a!==br.unauthenticated?r??null:t};pu.displayName="WhenAuthenticated",hu.displayName="WhenUnauthenticated";function mu(){const{isAuthenticated:e}=yc(),{orgId:t}=oo(),{settings:n}=uo(),r=tu(n),{myInvitations:a,acceptInvitation:i,declineInvitation:c}=sc(),{t:d}=Si(),m=s(()=>Xo(t??""),[t]),g=o(m.subscribe,m.getSnapshot,m.getSnapshot),[f,y]=h(null),w=l(d);u(()=>{w.current=d},[d]);const b=p(e=>m.load(a,{maxAgeMs:e,onError:e=>(ve(e,{component:"useMyInvitations",action:"list"}),ke(e,"invitations.loadFailed",w.current))}),[m,a]),v=p(()=>b(0),[b]);u(()=>{e&&r?b(15e3).catch(()=>{}):m.reset()},[e,r,m,b]);const k=p(async(e,t)=>{y(e),m.setError(null);try{const{workspace:n}=await i(e,t);return m.remove(e),n}catch(e){throw ve(e,{component:"useMyInvitations",action:"accept"}),m.setError(ke(e,"invitations.acceptFailed",w.current)),e}finally{y(null)}},[m,i]),S=p(async e=>{y(e),m.setError(null);try{await c(e),m.remove(e)}catch(e){throw ve(e,{component:"useMyInvitations",action:"decline"}),m.setError(ke(e,"invitations.declineFailed",w.current)),e}finally{y(null)}},[m,c]);return s(()=>({invitations:g.rows,loading:g.loading,error:g.error,busy:f,refresh:v,accept:k,decline:S}),[g,f,v,k,S])}function gu({className:r,title:a,description:i,emptyLabel:s,hideWhenEmpty:o=!1,switchOnAccept:c=!0,onAccepted:l}){const{t:d,formattingLocale:u}=Si(),{formats:p}=Jo(),{invitations:h,loading:m,error:g,busy:f,accept:y,decline:w}=mu(),{switchToWorkspace:b}=sc(),v=void 0===a?d("invitations.title"):a,k=void 0===i?d("invitations.listDescription"):i,S=s??d("invitations.empty");return m||0!==h.length||!o||g?t("div",{className:"saas-os-ui",style:{backgroundColor:"transparent"},children:e("div",{className:le("space-y-4",r),children:[t(Yl,{title:v,description:k}),g&&t(kl,{variant:"error",message:g}),m?e("div",{className:"space-y-2",children:[t(Kl,{className:"h-16 w-full"}),t(Kl,{className:"h-16 w-full"})]}):0===h.length?t(Hl,{icon:t(R,{className:"h-5 w-5 text-muted-foreground"}),description:S}):t("ul",{className:"space-y-2",children:h.map(r=>{const a=ca(r),i=f===r._id;return t("li",{className:"rounded-md border bg-card p-3 text-card-foreground",children:e("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e("div",{className:"min-w-0",children:[t("div",{className:"truncate text-sm font-medium",children:sa(r)}),e("div",{className:"text-xs text-muted-foreground",children:[d("invitations.invitedAs",{inviter:a??d("users.invitations.formerMember"),role:r.role}),r.validTill&&e(n,{children:[" · ",d("users.invitations.expiresAt",{date:(s=r.validTill,s?El(s,u,p?.date??{dateStyle:"medium"}):"")})]})]})]}),e("div",{className:"flex shrink-0 items-center gap-2",children:[t(bc,{variant:"outline",size:"sm",disabled:i,onClick:()=>w(r._id).catch(()=>{}),children:d("invitations.decline")}),t(bc,{size:"sm",progress:i,onClick:()=>(async e=>{let t;try{t=await y(e)}catch{return}t&&(l?.(t),c&&await b(t))})(r._id),children:d("invitations.accept")})]})]})},r._id);var s})})]})}):null}const fu=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{invitations:a,loading:i}=mu();return i?n??null:0===a.length?r??null:t},yu="https://www.buildbase.app",wu={"built-with":{sm:{width:120,height:40},md:{width:144,height:48},lg:{width:168,height:56}},"powered-by":{sm:{width:150,height:30},md:{width:180,height:36},lg:{width:210,height:42}},mark:{sm:{width:88,height:24},md:{width:110,height:30},lg:{width:132,height:36}}},bu={"built-with":"Built with BuildBase","powered-by":"Powered by BuildBase",mark:"BuildBase"};function vu(e,t){return`${yu}/badge/v1/${e}.svg?theme=${t}`}function ku(e){const t=(e??"").trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64).replace(/-+$/g,"");return t.length>0?t:void 0}function Su(e,{refCode:t,params:n}={}){const r=new URLSearchParams({utm_source:"badge",utm_medium:e}),a=ku(t);a&&r.set("ref",a);for(const[e,t]of Object.entries(n??{}))e&&null!=t&&r.set(e,String(t));return`${yu}/?${r.toString()}`}const Iu=({variant:e="built-with",theme:n="auto",size:r="md",alt:a,className:i,link:s=!0,refCode:o,params:c})=>{const l=wu[e][r],d=t("img",{src:vu(e,n),alt:a??bu[e],width:l.width,height:l.height,loading:"lazy",decoding:"async"});return s?t("a",{href:Su(e,{refCode:o,params:c}),target:"_blank",rel:"noopener",className:le("inline-block",i),children:d}):t("span",{className:i,children:d})},Cu=e=>{const{children:t,fallback:n,roles:r}=e,{user:a}=yc();return r.includes(a?.role??"")?t:n||null},xu=e=>{const{children:t,fallback:n,roles:r}=e,{user:a}=yc(),{currentWorkspace:i}=sc(),s=i?.users.find(e=>e._id===a?.id);return s&&r.includes(s?.role??"")?t:n||null};Cu.displayName="WhenRoles",xu.displayName="WhenWorkspaceRoles";const Nu=e=>{const{children:t,fallback:n,permission:r}=e,{can:a}=Al();return a(r)?t:n??null};function Au(){const e=oo();return s(()=>new et(e),[e.serverUrl,e.version])}Nu.displayName="WhenPermission";const Pu=async(e,t)=>{const{io:n}=await import("socket.io-client");return n(e,t)};let Eu=null;function _u(e){e.timer&&clearTimeout(e.timer),e.timer=setTimeout(()=>{e.timer=null;for(const t of e.listeners)try{t()}catch{}},500)}function Tu(e){e.closed=!0,e.timer&&clearTimeout(e.timer),e.socket?.disconnect(),e.socket=null}function Uu(e,t,n,r=Pu){const a=`${e}|${t}`;if(Eu&&Eu.key!==a&&(Tu(Eu),Eu=null),!Eu){const n={key:a,listeners:new Set,socket:null,closed:!1,timer:null};Eu=n,Promise.resolve(r(`${e.replace(/\/$/,"")}/inbox`,{auth:{sessionId:t},transports:["websocket"],reconnectionDelay:2e3,reconnectionDelayMax:6e4})).then(e=>{n.closed?e.disconnect():(n.socket=e,e.on("notifications:changed",()=>_u(n)),e.on("connect",()=>_u(n)))}).catch(()=>{})}const i=Eu;i.listeners.add(n);let s=!1;return()=>{s||(s=!0,i.listeners.delete(n),0===i.listeners.size&&(Tu(i),Eu===i&&(Eu=null)))}}const Ru={items:[],counts:{unread:0,unseen:0},loading:!1,loadingMore:!1,error:null,hasNextPage:!1,page:0,fetchedAt:0},Ou=e=>!e.readAt,Wu=e=>!e.readAt&&!e.seenAt;function Fu(e,t){const n=new Map(e.map(e=>[e.id,e]));for(const e of t)n.set(e.id,e);return[...n.values()].sort((e,t)=>new Date(t.createdAt??0).getTime()-new Date(e.createdAt??0).getTime())}class Lu{constructor(){this.snapshot=Ru,this.listeners=new Set,this.inFlight=null,this.moreInFlight=null,this.generation=0,this.pollers=0,this.pollTimer=null,this.pollTick=null,this.getSnapshot=()=>this.snapshot,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e))}set(e){this.snapshot={...this.snapshot,...e};for(const e of this.listeners)e()}load(e,t,n){if(this.inFlight)return this.inFlight;const r=n.maxAgeMs??0;if(r>0&&this.snapshot.fetchedAt&&Date.now()-this.snapshot.fetchedAt<r)return Promise.resolve();const a=this.generation;return this.set({loading:0===this.snapshot.fetchedAt,error:null}),this.inFlight=Promise.all([e(1),t()]).then(([e,t])=>{if(a!==this.generation)return;const n=this.snapshot.page<=1;this.set({items:n?e.notifications:Fu(this.snapshot.items,e.notifications),counts:t,hasNextPage:n?e.hasNextPage:this.snapshot.hasNextPage,page:Math.max(this.snapshot.page,1),fetchedAt:Date.now()})}).catch(e=>{a===this.generation&&this.set({error:n.onError(e)})}).finally(()=>{this.inFlight=null,a===this.generation&&this.set({loading:!1})}),this.inFlight}loadMore(e,t){if(this.moreInFlight)return this.moreInFlight;if(!this.snapshot.hasNextPage)return Promise.resolve();const n=this.generation,r=this.snapshot.page+1;return this.set({loadingMore:!0,error:null}),this.moreInFlight=e(r).then(e=>{n===this.generation&&this.set({items:Fu(this.snapshot.items,e.notifications),hasNextPage:e.hasNextPage,page:r})}).catch(e=>{n===this.generation&&this.set({error:t.onError(e)})}).finally(()=>{this.moreInFlight=null,n===this.generation&&this.set({loadingMore:!1})}),this.moreInFlight}async poll(e,t,n){if(this.inFlight)return;const r=this.generation;try{const a=await t();if(r!==this.generation)return;const i=this.snapshot.counts;if(a.unread===i.unread&&a.unseen===i.unseen)return;this.set({counts:a}),await this.load(e,t,{onError:n})}catch{}}retainPoll(e,t){this.pollers++,this.pollTick=t,!this.pollTimer&&e>0&&(this.pollTimer=setInterval(()=>this.pollTick?.(),e));let n=!1;return()=>{n||(n=!0,this.pollers--,this.pollers<=0&&this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null,this.pollTick=null))}}replace(e){const t=this.snapshot.items.find(t=>t.id===e.id);this.set({items:this.snapshot.items.map(t=>t.id===e.id?e:t),counts:t?this.adjustCounts(t,e):this.snapshot.counts})}optimistic(e,t){const n=this.snapshot.items.find(t=>t.id===e);if(!n)return()=>{};const r=this.snapshot.counts;return this.replace({...n,...t}),()=>{this.set({items:this.snapshot.items.map(t=>t.id===e?n:t),counts:r})}}remove(e){const t=this.snapshot.items.findIndex(t=>t.id===e);if(-1===t)return()=>{};const n=this.snapshot.items[t],r=this.snapshot.counts;return this.set({items:this.snapshot.items.filter(t=>t.id!==e),counts:{unread:Math.max(0,r.unread-(Ou(n)?1:0)),unseen:Math.max(0,r.unseen-(Wu(n)?1:0))}}),()=>{const e=[...this.snapshot.items];e.splice(Math.min(t,e.length),0,n),this.set({items:e,counts:r})}}markAll(e,t=(new Date).toISOString()){const{items:n,counts:r}=this.snapshot;return this.set({items:n.map(n=>"readAt"===e?n.readAt?n:{...n,readAt:t,readVia:"inbox",seenAt:n.seenAt??t}:n.seenAt?n:{...n,seenAt:t}),counts:"readAt"===e?{unread:0,unseen:0}:{...r,unseen:0}}),()=>this.set({items:n,counts:r})}setError(e){this.set({error:e})}reset(){this.generation++,this.inFlight=null,this.moreInFlight=null,this.snapshot=Ru;for(const e of this.listeners)e()}adjustCounts(e,t){const{unread:n,unseen:r}=this.snapshot.counts;return{unread:Math.max(0,n+(Ou(t)?1:0)-(Ou(e)?1:0)),unseen:Math.max(0,r+(Wu(t)?1:0)-(Wu(e)?1:0))}}}const Du=new Map;const $u=()=>"undefined"==typeof document||"hidden"!==document.visibilityState;function Mu(e={}){const{isAuthenticated:t}=yc(),{orgId:n,serverUrl:r}=oo(),{currentWorkspace:a}=sc(),i=Au(),{t:c}=Si(),d="current"===e.workspaceId?a?._id:e.workspaceId,h="current"===e.workspaceId&&!a?._id,m=Math.max(1,Math.min(e.pageSize??20,100)),g=e.pollIntervalMs??6e4,f=e.live??!0,y=h?"__waiting_for_workspace__":d,w=s(()=>function(e,t){const n=`${e||"unscoped"}|${t??"*"}`;let r=Du.get(n);return r||(r=new Lu,Du.set(n,r)),r}(n??"",y),[n,y]),b=o(w.subscribe,w.getSnapshot,w.getSnapshot),v=l(c);u(()=>{v.current=c},[c]);const k=p(e=>t=>(ve(t,{component:"useNotifications",action:e}),ke(t,"notifications.inbox.loadFailed",v.current)),[]),S=p(e=>i.list({workspaceId:d,page:e,limit:m}),[i,d,m]),I=p(()=>i.counts(d),[i,d]),C=p(e=>w.load(S,I,{maxAgeMs:e,onError:k("list")}),[w,S,I,k]),x=p(()=>C(0),[C]);u(()=>{t?h||C(15e3).catch(()=>{}):w.reset()},[t,h,w,C]),u(()=>{if(!t||h||g<=0)return;const e=()=>{$u()&&w.poll(S,I,k("poll"))},n=w.retainPoll(g,e),r=()=>{$u()&&e()};return"undefined"!=typeof document&&document.addEventListener("visibilitychange",r),()=>{n(),"undefined"!=typeof document&&document.removeEventListener("visibilitychange",r)}},[t,h,g,w,S,I,k]),u(()=>{if(!t||h||!f||!r)return;const e=Re();return e?Uu(r,e,()=>{C(0).catch(()=>{})}):void 0},[t,h,f,r,C]);const N=p(async(e,t,n)=>{const r=t();w.setError(null);try{const e=await n();e&&"object"==typeof e&&"id"in e&&w.replace(e)}catch(t){throw r(),ve(t,{component:"useNotifications",action:e}),w.setError(ke(t,"notifications.inbox.updateFailed",v.current)),t}},[w]),A=p(async e=>{const t=w.getSnapshot().items.find(t=>t.id===e);if(t?.readAt)return;const n=(new Date).toISOString();await N("read",()=>w.optimistic(e,{readAt:n,readVia:"inbox",seenAt:t?.seenAt??n}),()=>i.markRead(e))},[N,i,w]),P=p(e=>N("unread",()=>w.optimistic(e,{readAt:null,readVia:null}),()=>i.markUnread(e)),[N,i,w]),E=p(e=>N("archive",()=>w.remove(e),async()=>{await i.archive(e)}),[N,i,w]),_=p(()=>N("read-all",()=>w.markAll("readAt"),()=>i.markAllRead(d)),[N,i,w,d]),T=p(async()=>{0!==w.getSnapshot().counts.unseen&&await N("seen",()=>w.markAll("seenAt"),()=>i.markSeen(d)).catch(()=>{})},[N,i,w,d]),U=p(()=>w.loadMore(S,{onError:k("load-more")}),[w,S,k]),R=s(()=>b.items.filter(e=>!e.readAt),[b.items]);return s(()=>({notifications:b.items,unread:R,counts:b.counts,loading:b.loading||t&&h,loadingMore:b.loadingMore,hasMore:b.hasNextPage,error:b.error,refresh:x,loadMore:U,markRead:A,markUnread:P,archive:E,markAllRead:_,markSeen:T}),[b,t,h,R,x,U,A,P,E,_,T])}function ju({className:n,title:r,description:a,showFilter:i=!0,onSelect:s,emptyLabel:o,markSeenOnView:c=!0,compact:l=!1,...d}){const{t:p,formattingLocale:m}=Si(),{notifications:g,unread:f,counts:y,loading:w,loadingMore:b,hasMore:v,error:S,loadMore:I,markRead:C,markUnread:x,archive:N,markAllRead:P,markSeen:E}=Mu(d),[_,T]=h("all");u(()=>{c&&!w&&y.unseen>0&&E()},[c,w,y.unseen,E]);const U=void 0===r?p("notifications.inbox.title"):r,L=void 0===a?p("notifications.inbox.description"):a,D="unread"===_?f:g,$=o??p("unread"===_?"notifications.inbox.emptyUnread":"notifications.inbox.empty"),M=e=>{C(e.id).catch(()=>{}),s?s(e):function(e){if(e.link&&"undefined"!=typeof window)try{const t=new URL(e.link,window.location.href);"http:"!==t.protocol&&"https:"!==t.protocol||window.location.assign(t.href)}catch{}}(e)};return t("div",{className:"saas-os-ui",style:{backgroundColor:"transparent"},children:e("div",{className:le(l?"space-y-3":"space-y-4",n),children:[t(Yl,{title:U,description:L}),e("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[i?t("div",{role:"group",className:"inline-flex rounded-md border p-0.5 text-xs",children:["all","unread"].map(t=>e("button",{type:"button","aria-pressed":_===t,onClick:()=>T(t),className:le("rounded px-2.5 py-1 font-medium transition-colors",_===t?"bg-secondary text-secondary-foreground":"text-muted-foreground hover:text-foreground"),children:[p("all"===t?"notifications.inbox.filterAll":"notifications.inbox.filterUnread"),"unread"===t&&y.unread>0&&e("span",{className:"ms-1 tabular-nums",children:["(",y.unread,")"]})]},t))}):t("span",{}),t(bc,{variant:"ghost",size:"sm",disabled:0===y.unread,startIcon:t(k,{}),onClick:()=>P().catch(()=>{}),children:p("notifications.inbox.markAllRead")})]}),S&&t(kl,{variant:"error",message:S}),w?e("div",{className:"space-y-2",children:[t(Kl,{className:"h-14 w-full"}),t(Kl,{className:"h-14 w-full"}),t(Kl,{className:"h-14 w-full"})]}):0===D.length?t(Hl,{icon:t(O,{className:"h-5 w-5 text-muted-foreground"}),description:$}):t("ul",{className:"divide-y rounded-md border bg-card text-card-foreground",children:D.map(n=>{const r=!n.readAt,a=function(e,t){const n=[],{email:r,push:a}=e.channels;if("none"!==r.status&&"skipped"!==r.status){const e="failed"===r.status?t("notifications.inbox.notDelivered"):r.clickedAt?t("notifications.inbox.clicked"):r.openedAt?t("notifications.inbox.opened"):null;n.push({key:"email",icon:"email",text:[t("notifications.inbox.channelEmail"),e].filter(Boolean).join(" · ")})}if("none"!==a.status&&"skipped"!==a.status){const e="failed"===a.status?t("notifications.inbox.notDelivered"):a.clickedAt?t("notifications.inbox.clicked"):null;n.push({key:"push",icon:"push",text:[t("notifications.inbox.channelPush"),e].filter(Boolean).join(" · ")})}return n}(n,p);return e("li",{className:"group relative flex gap-3 p-3",children:[t("span",{"aria-hidden":"true",className:le("mt-1.5 h-2 w-2 shrink-0 rounded-full",r?"bg-primary":"bg-transparent")}),e("button",{type:"button",onClick:()=>M(n),className:"min-w-0 flex-1 text-start outline-none focus-visible:underline",children:[e("div",{className:"flex items-baseline justify-between gap-2",children:[t("span",{className:le("truncate text-sm",r?"font-semibold":"font-medium text-muted-foreground"),children:n.title}),n.createdAt&&t("time",{dateTime:n.createdAt,className:"shrink-0 text-xs text-muted-foreground tabular-nums",children:Rl(n.createdAt,m)})]}),n.body&&t("p",{className:le("mt-0.5 text-sm text-muted-foreground",l?"line-clamp-2":"line-clamp-3"),children:n.body}),a.length>0&&t("div",{className:"mt-1.5 flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground",children:a.map(n=>e("span",{className:"inline-flex items-center gap-1",children:["email"===n.icon?t(W,{className:"h-3 w-3","aria-hidden":"true"}):t(A,{className:"h-3 w-3","aria-hidden":"true"}),n.text]},n.key))})]}),e("div",{className:"flex shrink-0 items-start gap-0.5 opacity-100 sm:opacity-0 sm:transition-opacity sm:group-focus-within:opacity-100 sm:group-hover:opacity-100",children:[t(bc,{variant:"ghost",size:"icon",className:"h-7 w-7 sm:h-7 sm:w-7",title:p(r?"notifications.inbox.markRead":"notifications.inbox.markUnread"),"aria-label":p(r?"notifications.inbox.markRead":"notifications.inbox.markUnread"),onClick:()=>(r?C(n.id):x(n.id)).catch(()=>{}),children:t(r?R:W,{className:"h-4 w-4"})}),t(bc,{variant:"ghost",size:"icon",className:"h-7 w-7 sm:h-7 sm:w-7",title:p("notifications.inbox.archive"),"aria-label":p("notifications.inbox.archive"),onClick:()=>N(n.id).catch(()=>{}),children:t(F,{className:"h-4 w-4"})})]})]},n.id)})}),v&&!w&&t(bc,{variant:"outline",size:"sm",fullWidth:!0,progress:b,onClick:()=>I().catch(()=>{}),children:p("notifications.inbox.loadMore")})]})})}function qu({className:n,align:r="end",inboxProps:a,maxCount:i=99,...s}){const{t:o}=Si(),{counts:c}=Mu(s),[l,d]=h(!1),u=c.unread,p=u>i?`${i}+`:String(u),m=u>0?o("notifications.inbox.bellUnread",{count:u}):o("notifications.inbox.bellLabel");return t("div",{className:"saas-os-ui",style:{backgroundColor:"transparent",display:"inline-flex"},children:e(gd,{open:l,onOpenChange:d,children:[t(fd,{asChild:!0,children:e(bc,{variant:"ghost",size:"icon","aria-label":m,title:m,className:le("relative",n),children:[t(_,{className:"h-5 w-5"}),u>0&&t("span",{"aria-hidden":"true",className:le("absolute -end-0.5 -top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[10px] font-semibold leading-none tabular-nums",c.unseen>0?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"),children:p})]})}),t(yd,{align:r,className:"w-[min(24rem,calc(100vw-2rem))] max-h-[min(32rem,calc(100vh-6rem))] overflow-y-auto p-3",children:l&&t(ju,{description:null,...a,...s,compact:!0})})]})})}function Bu(){const e=d(ll);if(void 0===e)throw new Error("useUserAttributes must be used within a UserProvider");return s(()=>({attributes:e.attributes,loading:e.attributesLoading,error:e.attributesError,refetch:e.refreshAttributes,updateAttributes:e.updateAttributes,updateAttribute:e.updateAttribute,isLoading:e.isLoading,refreshAttributes:e.refreshAttributes}),[e])}function Vu(){const e=d(ll);if(void 0===e)throw new Error("useUserFeatures must be used within a UserProvider");return s(()=>({features:e.features,loading:e.featuresLoading,error:e.featuresError,refetch:e.refreshFeatures,isFeatureEnabled:t=>Boolean(e.features[t]),isLoading:e.featuresLoading,refreshFeatures:e.refreshFeatures}),[e])}const zu=e=>{const{children:t,slug:n}=e,{currentWorkspace:r}=sc(),a=r?.features?.[n];return a?t:null},Gu=e=>{const{children:t,slug:n}=e,{currentWorkspace:r}=sc(),a=r?.features?.[n];return Bo(!!r&&!a,`workspace:${n}`,"feature_gate_shown",{feature:n,scope:"workspace"}),a?null:t},Ju=e=>{const{children:t,slug:n}=e,{isFeatureEnabled:r}=Vu();return r(n)?t:null},Hu=e=>{const{children:t,slug:n}=e,{isFeatureEnabled:r,loading:a}=Vu(),i=r(n);return Bo(!a&&!i,`user:${n}`,"feature_gate_shown",{feature:n,scope:"user"}),i?null:t};zu.displayName="WhenWorkspaceFeatureEnabled",Gu.displayName="WhenWorkspaceFeatureDisabled",Ju.displayName="WhenUserFeatureEnabled",Hu.displayName="WhenUserFeatureDisabled";const Yu=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{response:a,loading:i}=Uo();return i?n??null:a?.subscription?t:r??null},Ku=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{response:a,loading:i}=Uo();return i?n??null:a?.subscription?r??null:t},Qu=e=>{const{children:t,plans:n,loadingComponent:r,fallbackComponent:a}=e,{response:i,loading:s}=Uo(),o=i?.subscription?i.plan??i.subscription?.plan:void 0,c=n.map(e=>e.trim().toLowerCase()),l=(o?.slug??"").toLowerCase(),d=!!o&&c.includes(l),{currentWorkspace:u}=sc();return Bo(!!u&&!s&&!d&&null!=a,c.join(","),"plan_gate_shown",{required_plans:c.join(","),current_plan:l||"none"}),s?r??null:d?t:a??null},Zu=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{response:a,loading:i}=Uo();return i?n??null:"trialing"!==a?.subscription?.subscriptionStatus?r??null:t},Xu=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{response:a,loading:i}=Uo();return i?n??null:a?.subscription?.subscriptionStatus===_n.Trialing?r??null:t},ep=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{behavior:a}=Jo(),i=e.daysThreshold??a?.trialEndingDays??3,{response:s,loading:o}=Uo();if(o)return n??null;const c=s?.subscription;if(!c||"trialing"!==c.subscriptionStatus)return r??null;const l=c.trialEnd||c.stripeCurrentPeriodEnd;if(!l)return r??null;const d=new Date(l);if(isNaN(d.getTime()))return r??null;return Math.max(0,Math.ceil((d.getTime()-Date.now())/864e5))>i?r??null:t};Yu.displayName="WhenSubscription",Ku.displayName="WhenNoSubscription",Qu.displayName="WhenSubscriptionToPlans",Zu.displayName="WhenTrialing",Xu.displayName="WhenNotTrialing",ep.displayName="WhenTrialEnding";const tp=e=>{const{slug:t,children:n,loadingComponent:r,fallbackComponent:a}=e,{quotas:i,loading:s}=jc(),o=s?void 0:i?.[t];return Bo(!!o&&o.available<=0&&null!=a,t,"quota_limit_reached",{quota:t,included:o?.included,consumed:o?.consumed}),s?r??null:o?o.available<=0?a??null:n:a??null},np=e=>{const{slug:t,children:n,loadingComponent:r,fallbackComponent:a}=e,{quotas:i,loading:s}=jc(),o=s?void 0:i?.[t];return Bo(!!o&&o.available<=0,t,"quota_limit_reached",{quota:t,included:o?.included,consumed:o?.consumed}),s?r??null:o?o.available>0?a??null:n:a??null},rp=e=>{const{slug:t,children:n,loadingComponent:r,fallbackComponent:a}=e,{quotas:i,loading:s}=jc();if(s)return r??null;const o=i?.[t];return o&&o.hasOverage&&!1!==o.allowOverage?n:a??null},ap=e=>{const{slug:t,threshold:n,children:r,loadingComponent:a,fallbackComponent:i}=e,{quotas:s,loading:o}=jc(),c=o?void 0:s?.[t],l=c?c.included>0?c.consumed/c.included*100:c.consumed>0?100:0:0;return Bo(!!c&&l>=n,`${t}@${n}`,"quota_threshold_reached",{quota:t,threshold:n,percent_used:Math.round(l)}),o?a??null:c?l<n?i??null:r:i??null};tp.displayName="WhenQuotaAvailable",np.displayName="WhenQuotaExhausted",rp.displayName="WhenQuotaOverage",ap.displayName="WhenQuotaThreshold";const ip=({children:e})=>{const{currentWorkspace:t}=sc(),n=t?._id,{balance:r,loading:a,error:i,refetch:s}=_c(),{packages:o,loading:c}=Cc(n),{consumeCredits:l,loading:d,error:u}=Sc(n),{purchaseCredits:p,loading:h,error:m}=Ic(n);return e({balance:r,loading:a,packages:o,packagesLoading:c,consume:l,consuming:d,purchase:async e=>{if(!n)throw new Error("No workspace selected");const{successUrl:t,cancelUrl:r}=Gt(n),a=await p({creditPackageId:e._id,successUrl:t,cancelUrl:r});a.url&&Xt(a.url)},purchasing:h,refetch:s,error:u||m||i})};ip.displayName="CreditActionsProvider";const sp=({children:e})=>{const{balance:t,loading:n,error:r,refetch:a}=_c();return e({balance:t,loading:n,error:r,refetch:a})};function op({children:r,loadingFallback:a,errorFallback:i,redirectBaseUrl:s}){const{packages:o,notes:c,loading:l,error:d,refetch:u}=Ac(),{isAuthenticated:h,signIn:m}=yc(),g=p(e=>{if(h)nc.openWorkspaceSettings(ec.Credits,{action:jt.CreditPurchase,packageId:e});else if(s){const t=Vt({action:jt.CreditPurchase,screen:"credits",packageId:e},s);m(t)}else m()},[h,m,s]);return l?void 0!==a?t(n,{children:a}):e("div",{className:"space-y-4",children:[t(Kl,{className:"h-8 w-48"}),t("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(e=>t(Kl,{className:"h-48 rounded-lg"},e))})]}):d?i?t(n,{children:i(d)}):t("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive",children:d}):t(n,{children:r({loading:l,error:d,packages:o,notes:c,refetch:u,selectPackage:g})})}sp.displayName="CreditBalance";const cp=e=>{const{min:t=1,children:n,loadingComponent:r,fallbackComponent:a}=e,{balance:i,loading:s}=_c();return s?r??null:i?i.available<t?a??null:n:a??null},lp=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{balance:a,loading:i}=_c();return i?n??null:a?a.available>0?r??null:t:r??null},dp=e=>{const{threshold:t,children:n,loadingComponent:r,fallbackComponent:a}=e,{balance:i,loading:s}=_c();return s?r??null:i?i.available>t?a??null:n:a??null};function up(e){if(!e)return null;const t=new Date(e);return isNaN(t.getTime())?null:t}function pp(){const{response:e}=Uo();return s(()=>{const t=e?.subscription;if(!t||"trialing"!==t.subscriptionStatus)return{isTrialing:!1,daysRemaining:0,trialEndsAt:null,trialStartedAt:null,isTrialEnding:!1};const n=up(t.trialEnd)??up(t.stripeCurrentPeriodEnd),r=up(t.trialStart),a=n?Math.max(0,Math.ceil((n.getTime()-Date.now())/864e5)):0;return{isTrialing:!0,daysRemaining:a,trialEndsAt:n,trialStartedAt:r,isTrialEnding:a<=3}},[e])}cp.displayName="WhenCreditsAvailable",lp.displayName="WhenCreditsExhausted",dp.displayName="WhenCreditsLow";const hp=te.object({name:te.string().min(1,"Please enter your name").max(50,"Name must be less than 50 characters").regex(/^[\p{L}\p{M}\s'-]*$/u,"Name can only contain letters and spaces"),email:te.string().min(1,"Please enter your email address").email("Please enter a valid email address").max(100,"Email must be less than 100 characters").regex(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,"Please enter a valid email format (e.g., name@domain.com)")}),mp=({onSuccess:r,onError:a,className:i="w-full",fieldClassName:s="flex flex-col gap-1.5 w-full",autoFocus:o=!0,showSuccessMessage:c=!0,hideLogo:l=!1,hideTitles:d=!1})=>{const{t:m}=Si(),[g,f]=h(!1),[y,w]=h(!1),{submitBetaForm:b,isLoading:v,isSubmitting:k,error:S,config:I,success:C,message:x}=(()=>{const{t:e}=Si(),t=oo(),[n,r]=h(null),[a,i]=h(!0),[s,o]=h(!1),[c,l]=h(null),[d,m]=h(!1),[g,f]=h(null);return u(()=>{let n=!1;return(async()=>{i(!0),l(null);try{const e=new Ye(t),a=await e.fetchConfig();n||r(a)}catch(t){n||l(t instanceof Error?t.message:e("beta.errorMessage"))}finally{n||i(!1)}})(),()=>{n=!0}},[t]),{isLoading:a,isSubmitting:s,config:n,error:c,success:d,message:g,submitBetaForm:p(async n=>{if(!t){const t=e("errors.generic");return l(t),{success:!1,message:t}}try{o(!0),l(null),m(!1),f(null);const e=new Ye(t),r=await e.submitBetaUser({name:n.name||"",email:n.email}),a="success"===r.status;return m(a),f(r.message),{success:a,message:r.message}}catch(t){const n=t instanceof Error?t.message:e("beta.errorMessage");return l(n),m(!1),f(n),{success:!1,message:n}}finally{o(!1)}},[t])}})();u(()=>{C&&c&&(f(!0),w(!0)),S&&w(!0)},[C,c,S]);const N=X({resolver:Y(hp),defaultValues:{email:"",name:""},mode:"onChange",reValidateMode:"onChange"});u(()=>{o&&N.setFocus("name")},[o,N]);const A=N.formState.isValid&&!k;return t("div",{className:"saas-os-ui",style:{width:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},children:e("div",v?{className:le("flex flex-col items-center justify-center w-full px-2.5 sm:px-6 py-2.5 sm:py-6 gap-y-2.5 sm:gap-y-4",i),children:[t(Kl,{className:"h-24 w-24 rounded-lg"}),t(Kl,{className:"h-6 w-32"}),e("div",{className:"w-full space-y-4",children:[e("div",{className:"space-y-2",children:[t(Kl,{className:"h-4 w-16"}),t(Kl,{className:"h-10 w-full"})]}),e("div",{className:"space-y-2",children:[t(Kl,{className:"h-4 w-16"}),t(Kl,{className:"h-10 w-full"})]}),t(Kl,{className:"h-10 w-full"})]})]}:{className:"flex flex-col items-center justify-center w-full px-2.5 sm:px-6 py-2.5 sm:py-6 gap-y-2.5 sm:gap-y-4",children:[!l&&e("div",{className:"flex flex-col items-center justify-center w-full",children:[I?.logo&&t(fp,{logo:I?.logo}),I?.name&&t("div",{children:I?.name})]}),t(Q,{...N,children:e("form",{onSubmit:N.handleSubmit(async e=>{try{const t=await b(e);t.success?(r?.(),N.reset(),c&&f(!0),w(!0)):(a?.(t.message),w(!0))}catch(e){a?.(e instanceof Error?e.message:m("beta.errorMessage")),w(!0)}}),className:i,noValidate:!0,"aria-busy":k,children:[!y&&e(n,{children:[!d&&I?.screen?.register&&t(gp,{screen:I?.screen?.register}),t(Sd,{control:N.control,name:"name",render:({field:n})=>e(xd,{className:s,children:[t(Nd,{children:m("beta.nameLabel")}),t(Ad,{children:t(dd,{...n})}),t(Pd,{}),t(Ed,{})]})}),t(Sd,{control:N.control,name:"email",render:({field:n})=>e(xd,{className:s,children:[t(Nd,{children:m("beta.emailLabel")}),t(Ad,{children:t(dd,{...n})}),t(Pd,{}),t(Ed,{})]})}),t(bc,{type:"submit",disabled:!A,className:s,children:m(k?"beta.submittingText":"beta.submitText")})]}),y&&S&&e("div",{className:"flex flex-col items-center justify-center w-full",children:[e("div",{className:"border-destructive/30 text-destructive",role:"alert","aria-live":"assertive","aria-atomic":!0,children:[t("span",{className:"text-4xl mb-2",role:"img","aria-label":m("settings.common.error"),children:"❗"}),S]}),t("div",{className:"mt-4 flex justify-center",children:t(bc,{type:"button",onClick:()=>{w(!1),N.reset()},className:s,children:m("beta.tryAgain")})})]}),y&&g&&x&&t("div",{className:"flex flex-col items-center justify-center w-full text-success border-success/30 text-center",children:I?.screen?.thankYou&&t(gp,{screen:I?.screen?.thankYou})})]})}),!y&&t("div",{children:e("div",{children:[m("beta.privacyConsent")," ",t("a",{href:I?.privacyPolicy,target:"_blank",rel:"noopener noreferrer",className:"text-info hover:text-info",children:m("beta.privacyPolicy")})," ",m("beta.and")," ",t("a",{href:I?.termsOfService,target:"_blank",rel:"noopener noreferrer",className:"text-info hover:text-info",children:m("beta.termsOfService")}),"."]})})]})})};function gp({screen:n}){return e("div",{className:"flex flex-col items-center justify-center w-full",children:[t("p",{className:"text-2xl font-bold",children:n?.title}),t("p",{className:"text-sm text-muted-foreground",children:n?.description})]})}function fp({logo:e}){const{t:n}=Si();return t("img","string"==typeof e?{src:e,alt:n("beta.logoAlt"),className:"max-h-24"}:{src:e.bucket?.url,alt:n("beta.logoAlt"),className:"max-h-24"})}function yp({slug:r,children:a,loadingFallback:i,errorFallback:s,redirectBaseUrl:o}){const{items:c,plans:l,notes:d,loading:u,error:h,refetch:m}=ho(r),{isAuthenticated:g,signIn:f}=yc(),{currentWorkspace:y,fetchWorkspaces:w}=sc(),{emit:b}=Vo();Bo(!u&&!h&&l.length>0,r,"pricing_viewed",{pricing_slug:r,plan_count:l.length,authenticated:g});const v=p((e,t,n)=>o?Vt({action:"selectPlan",plan:e,interval:t,currency:n},o):null,[o]),k=p((e,t,n)=>{if(b("pricing_plan_selected",{pricing_slug:r,plan_version_id:e,billing_interval:t,currency:n?n.toUpperCase():void 0,authenticated:g}),g)return nc.openWorkspaceSettings(ec.Subscription,{action:"selectPlan",plan:e,interval:t,currency:n}),void(y||w());const a=v(e,t,n);f(a??void 0)},[g,f,v,b,r,y,w]);return u?void 0!==i?t(n,{children:i}):e("div",{className:"space-y-4",children:[t(Kl,{className:"h-8 w-48"}),t("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(e=>t(Kl,{className:"h-64 rounded-lg"},e))})]}):h?s?t(n,{children:s(h)}):t("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive",children:h}):t(n,{children:a({loading:u,error:h,items:c,plans:l,notes:d,refetch:m,selectPlan:k})})}const wp=r.forwardRef(({className:e,orientation:n="horizontal",decorative:r=!0,...a},i)=>t(ie.Root,{ref:i,decorative:r,orientation:n,className:le("shrink-0 bg-border","horizontal"===n?"h-[1px] w-full":"h-full w-[1px]",e),...a}));wp.displayName=ie.Root.displayName;const bp=g(()=>import("./SettingsDialog-BVyV5Zfm.mjs").then(function(e){return e.e}).then(e=>({default:e.default})));function vp({message:r}){return e(n,{children:[t(L,{className:"mx-auto h-12 w-12 text-muted-foreground"}),t("p",{className:"mt-2 text-sm text-muted-foreground",children:r})]})}function kp(r){const{t:a,dir:i}=Si(),{isAuthenticated:s,user:o}=yc(),c=xt(oo()),{workspaces:l,currentWorkspace:d,loading:p,refreshing:g,switchingToId:f,fetchWorkspaces:y,getFeatures:b,refreshWorkspaces:v,setCurrentWorkspace:k,switchToWorkspace:S}=sc(),{settings:I,loading:C}=uo(),{visible:x}=Pl(),[N,A]=h(!1),[P,E]=h(0),[_,T]=h(""),U=p||g;u(()=>{s&&c&&(0===l.length?(y(),b()):b())},[s,c]),u(()=>{s&&c&&P>0&&v()},[P,s,c]);const R=l,O=R.filter(e=>e._id!==d?._id).filter(e=>e.name.toLowerCase().includes(_.toLowerCase())),W=(I?.workspace?.canCreateWorkspace??!0)&&x(e=>e.workspaceSwitcher?.createButton),F=(I?.workspace?.showSwitcher??!0)&&x(e=>e.workspaceSwitcher?.show),M=I?.workspace?.maxWorkspacesPerUser??0,j=R?.filter(e=>("object"==typeof e.createdBy?e.createdBy._id?.toString():e.createdBy?.toString())===o?.id?.toString()).length??0,q=!1!==W&&(0===M||j<M);u(()=>{!F&&l.length>0&&!d&&S(l[0]).catch(e=>{be(e,{component:"WorkspaceProvider",action:"autoSelectWorkspace"})})},[F,l,d]);const{emit:B}=Vo();return u(()=>{N&&F&&B("workspace_switcher_opened",{workspace_count:l.length})},[N]),C&&!I?t(n,{children:r.trigger?.(!0,d)}):!F&&d?e(n,{children:[t("div",{role:"button",tabIndex:0,"aria-label":a("settings.common.openSettings"),className:"cursor-pointer",onClick:()=>A(!0),onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),A(!0))},children:r.trigger?.(U,d)}),t(m,{fallback:null,children:t(bp,{workspace:d,open:N,onOpenChange:A,showTrigger:!1})})]}):e(ul,{open:N,onOpenChange:A,children:[t(pl,{children:r.trigger?.(U,d)}),e(gl,{dir:i,className:"max-w-2xl min-w-full md:min-w-[800px]",children:[e(fl,{dir:i,children:[e(wl,{className:"flex items-center gap-2",children:[t(L,{className:"h-5 w-5"}),a("workspace.switchTitle")]}),t(bl,{children:a("workspace.switchDescription")})]}),!o&&t("div",{className:"flex flex-col items-center justify-center h-full py-4 sm:py-8",children:t("div",{className:"text-sm font-medium text-muted-foreground",children:a("workspace.notLoggedIn")})}),o&&e("div",{dir:i,className:"flex flex-col gap-4",children:[d&&t(Sp,{workspace:d,isCurrentWorkspace:!0,switchToWorkspace:S,switchingToId:f,setCurrentWorkspace:k,setOpen:A,workspacesToUse:R}),t(wp,{}),e("div",{children:[e("div",{className:"flex items-center justify-between",children:[t("div",{className:"text-sm font-medium text-muted-foreground",children:a("workspace.availableWorkspaces",{count:O.length})}),t("div",{children:t(bc,{progress:g,disabled:g,variant:"ghost",onClick:function(){s&&c&&E(e=>e+1)},startIcon:t(D,{}),children:a("settings.common.refreshAction",{loading:String(g)})})})]}),e("div",{className:"relative",children:[t($,{className:"absolute start-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"}),t(dd,{placeholder:a("workspace.searchPlaceholder"),value:_,onChange:e=>T(e.target.value),className:"ps-10"})]}),p?e("div",{className:"flex items-center justify-center py-8",children:[t(w,{className:"h-6 w-6 animate-spin text-muted-foreground"}),t("span",{className:"ms-2 text-sm text-muted-foreground",children:a("workspace.loadingWorkspaces")})]}):0===O.length?t("div",{className:"text-center py-8",children:_?t(vp,{message:a("workspace.noWorkspacesFound")}):t(fu,{fallbackComponent:t(vp,{message:a("workspace.noWorkspacesAvailable")}),children:t(gu,{title:null,description:null,className:"text-start"})})}):t(Ud,{className:"h-64",dir:i,children:t("div",{dir:i,className:"flex flex-col gap-2 my-2.5",children:O.map(e=>{const n=e._id===d?._id;return t(Sp,{workspace:e,isCurrentWorkspace:n,switchToWorkspace:S,switchingToId:f,setCurrentWorkspace:k,setOpen:A,workspacesToUse:R},e._id)})})})]}),q&&e(n,{children:[t(wp,{}),t(Ip,{onCreated:()=>{y()}})]})]})]})]})}function Sp(n){const{t:r}=Si(),{visible:a}=Pl(),i=a(e=>e.workspaceSwitcher?.memberCount),s=a(e=>e.workspaceSwitcher?.planBadge),{workspace:o,setCurrentWorkspace:c,setOpen:l,workspacesToUse:d,switchingToId:u}=n,p=n.isCurrentWorkspace??!1,h=u===o._id,g=o.subscription??null,f=null!=g&&"object"==typeof g?g.plan??null:null,y=f?.name??"";return e("div",{className:le("flex items-center gap-3 rounded-lg border-2 p-3 border-border",{"bg-muted text-muted-foreground":p}),children:[e(Yd,{className:"h-8 w-8 flex items-center justify-center",children:[t("div",{children:t(Kd,{src:o.image&&o.image.trim()?o.image:void 0})}),t(Qd,{children:(w=o.name,w.split(" ").map(e=>e[0]).join("").toUpperCase().slice(0,2))})]}),e("div",{className:"flex-1 min-w-0 max-w-full",children:[t("div",{className:"flex items-center gap-2",children:t("span",{className:"font-medium line-clamp-1 text-ellipsis overflow-hidden max-w-full",children:o.name})}),i&&e("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[t(M,{className:"h-3 w-3"}),t("span",{children:r("workspace.membersCount",{count:o.users?.length||0})})]}),s&&y&&t("div",{className:"max-w-fit",children:t("div",{className:"flex items-center gap-1 text-sm bg-success text-success-foreground rounded-full px-2 py-0.5",children:t("span",{className:"text-xs",children:y})})})]}),e("div",{className:"flex items-center gap-2",children:[p?null:t(bc,{size:"sm",disabled:null!==u||h,progress:h,onClick:()=>{n.switchToWorkspace(o).then(()=>l(!1)).catch(e=>{be(e,{component:"WorkspaceItem",action:"switchToWorkspace",metadata:{workspaceId:o._id}})})},children:r("workspace.switchTo")}),t(m,{fallback:null,children:t(bp,{workspace:o,onClose:()=>{if(p){const e=d.findIndex(e=>e._id?.toString()===o._id?.toString());-1!==e&&c(d[e])}}})})]})]});var w}function Ip(r){const{t:a,dir:i}=Si(),{switching:s}=sc(),[o,c]=h(!1),[l,d]=h("emoji"),[u,p]=h("🏢"),[m,g]=h(!1),{createWorkspace:f}=sc(),y=te.object({name:te.string().min(2,{message:a("workspace.workspaceNameMinLength")}),image:te.string().optional()}),b=X({resolver:Y(y),defaultValues:{name:"",image:""}});return e(ul,{open:o,onOpenChange:c,children:[t(pl,{asChild:!0,children:e(bc,{className:"w-full rounded-none",disabled:s,children:[t(x,{className:"h-4 w-4 me-2"}),a("workspace.createNew")]})}),e(gl,{dir:i,className:"max-w-xl min-w-full sm:min-w-[600px]",children:[e(fl,{children:[t(wl,{children:a("workspace.createTitle")}),t(bl,{children:a("workspace.createDescription")})]}),t(vd,{...b,children:e("form",{onSubmit:b.handleSubmit(async function(e){let t="";if("emoji"===l)t=Ld(u);else if("url"===l&&e.image)try{new URL(e.image),t=e.image}catch{return void b.setError("image",{message:a("workspace.invalidUrl")})}g(!0);try{await f(e.name,t),c(!1),b.reset(),p("🏢"),d("emoji"),r?.onCreated?.()}catch(t){be(t,{component:"WorkspaceProvider",action:"createWorkspace",metadata:{name:e.name}})}finally{g(!1)}}),children:[t(Sd,{control:b.control,name:"name",render:({field:n})=>e(xd,{children:[t(Nd,{children:a("workspace.workspaceName")}),t(Ad,{children:t(dd,{placeholder:a("workspace.workspaceNamePlaceholder"),...n})}),t(Ed,{})]})}),e("div",{className:"flex flex-col gap-y-2 my-2",children:[e("div",{children:[t(bd,{className:"text-sm font-medium",children:a("workspace.workspaceIcon")}),t(Pd,{children:a("workspace.iconDescription")})]}),e(_d,{value:l,onValueChange:e=>d(e),className:"flex flex-col gap-y-2",children:[e("div",{className:"flex items-center gap-x-2 my-1",children:[t(Td,{value:"emoji",id:"emoji"}),e(bd,{htmlFor:"emoji",className:"flex items-center gap-2",children:[t(j,{className:"h-4 w-4"}),a("workspace.chooseEmoji")]})]}),e("div",{className:"flex items-center gap-x-2 my-1",children:[t(Td,{value:"url",id:"url"}),e(bd,{htmlFor:"url",className:"flex items-center gap-2",children:[t(q,{className:"h-4 w-4"}),a("workspace.customImageUrl")]})]})]}),"emoji"===l&&e("div",{className:"flex flex-col gap-y-2",children:[e("div",{className:"flex items-center gap-3",children:[t("span",{className:"text-sm font-medium",children:a("general.previewLabel")}),t("div",{className:"w-12 h-12 rounded-lg border-2 border-border flex items-center justify-center text-2xl bg-muted",children:u})]}),t(Ud,{className:"h-32 w-full rounded-md border",children:t("div",{className:"p-4 grid grid-cols-8 gap-2",children:Dd.map((e,n)=>t("button",{type:"button",onClick:()=>(e=>{p(e),b.setValue("image",Ld(e))})(e),"aria-label":e,"aria-pressed":u===e,className:"w-10 h-10 sm:w-8 sm:h-8 rounded flex items-center justify-center text-lg hover:bg-muted transition-colors "+(u===e?"bg-primary text-primary-foreground":""),children:e},n))})})]}),"url"===l&&e("div",{className:"flex flex-col gap-y-2",children:[t(Sd,{control:b.control,name:"image",render:({field:n})=>e(xd,{children:[t(Nd,{children:a("workspace.imageUrl")}),t(Ad,{children:t(dd,{placeholder:a("workspace.imageUrlPlaceholder"),...n})}),t(Pd,{children:a("workspace.imageUrlDescription")}),t(Ed,{})]})}),b.watch("image")&&b.watch("image")?.trim()&&e("div",{className:"flex items-center gap-3",children:[t("span",{className:"text-sm font-medium",children:a("general.previewLabel")}),t("div",{className:"w-12 h-12 rounded-lg border-2 border-border overflow-hidden bg-muted",children:t("img",{src:b.watch("image")||void 0,alt:a("general.previewImageAlt"),className:"w-full h-full object-cover",onError:e=>{e.currentTarget.style.display="none"}})})]})]})]}),e("div",{className:"flex justify-end gap-3 pt-4",children:[t(bc,{type:"button",variant:"outline",onClick:()=>{c(!1),b.reset(),p("🏢"),d("emoji")},disabled:m,children:a("settings.common.cancel")}),t(bc,{type:"submit",disabled:m,children:m?e(n,{children:[t(w,{className:"me-2 h-4 w-4 animate-spin"}),a("workspace.creating")]}):a("workspace.createWorkspace")})]})]})})]})]})}export{gd as $,nc as A,bc as B,rd as C,ul as D,jt as E,qt as F,Rt as G,Yl as H,Hl as I,_l as J,Gt as K,ad as L,Xt as M,Fn as N,sc as O,or as P,uo as Q,Ll as R,kl as S,Dl as T,jl as U,ql as V,Vl as W,zl as X,Bl as Y,Jl as Z,Gl as _,_a as a,zn as a$,fd as a0,yd as a1,ud as a2,md as a3,Fd as a4,vd as a5,Sd as a6,xd as a7,Nd as a8,Ad as a9,Bt as aA,yc as aB,ea as aC,Zr as aD,Jr as aE,Zt as aF,Bd as aG,hc as aH,Pr as aI,td as aJ,ko as aK,Tl as aL,Tn as aM,Pn as aN,En as aO,Un as aP,Vn as aQ,xn as aR,_n as aS,Bo as aT,vo as aU,wo as aV,Co as aW,xo as aX,So as aY,yo as aZ,Vo as a_,dd as aa,Ed as ab,bd as ac,cn as ad,Pd as ae,_d as af,Td as ag,at as ah,Ud as ai,Dd as aj,Ld as ak,Qc as al,Dc as am,yr as an,mr as ao,lc as ap,Yd as aq,Kd as ar,Qd as as,Hd as at,oo as au,Je as av,pc as aw,Tr as ax,cc as ay,Mt as az,wa as b,yp as b$,Dn as b0,Gn as b1,Jn as b2,Rn as b3,$n as b4,zt as b5,$t as b6,jc as b7,Uo as b8,Mn as b9,mp as bA,Iu as bB,uu as bC,sn as bD,on as bE,nd as bF,Ke as bG,ip as bH,sp as bI,Ec as bJ,On as bK,Wn as bL,op as bM,lr as bN,Qe as bO,At as bP,dr as bQ,Oo as bR,mt as bS,vc as bT,qu as bU,ju as bV,et as bW,dn as bX,un as bY,wr as bZ,gu as b_,Gc as ba,tu as bb,Xd as bc,da as bd,Zd as be,ur as bf,la as bg,ia as bh,ir as bi,nu as bj,ec as bk,ru as bl,au as bm,iu as bn,Ho as bo,Go as bp,pl as bq,tc as br,Ln as bs,qn as bt,Xn as bu,ts as bv,fr as bw,Ct as bx,br as by,Ge as bz,Si as c,bt as c$,tt as c0,Kc as c1,Mc as c2,Nt as c3,di as c4,nt as c5,rt as c6,To as c7,it as c8,pt as c9,kp as cA,aa as cB,Gr as cC,Hn as cD,Yn as cE,Kn as cF,Ht as cG,an as cH,fa as cI,ku as cJ,rn as cK,Vt as cL,Pt as cM,Uc as cN,bn as cO,kn as cP,Sn as cQ,Cn as cR,An as cS,ut as cT,jn as cU,In as cV,gr as cW,Ft as cX,ca as cY,xr as cZ,ra as c_,ht as ca,zr as cb,pu as cc,cp as cd,lp as ce,dp as cf,Ku as cg,Xu as ch,fu as ci,Nu as cj,tp as ck,np as cl,rp as cm,ap as cn,Cu as co,Yu as cp,Qu as cq,ep as cr,Zu as cs,hu as ct,Hu as cu,Ju as cv,Gu as cw,zu as cx,xu as cy,It as cz,Jo as d,Cr as d0,Ir as d1,Ur as d2,fn as d3,Rc as d4,yn as d5,ma as d6,dt as d7,Jt as d8,ga as d9,Ao as dA,No as dB,hd as dC,pd as dD,go as dE,pp as dF,bo as dG,Od as dH,Eo as dI,Bu as dJ,Vu as dK,Zn as dL,oa as dM,sa as dN,Qn as da,hr as db,nn as dc,na as dd,jr as de,ct as df,lt as dg,Po as dh,Fl as di,Wl as dj,Sc as dk,kc as dl,sd as dm,id as dn,Lo as dp,Vd as dq,Io as dr,Wc as ds,mu as dt,Mu as du,Au as dv,fo as dw,Ac as dx,mo as dy,ho as dz,po as e,Ol as f,El as g,le as h,be as i,qe as j,gl as k,wl as l,bl as m,ln as n,wn as o,Bn as p,gn as q,Kl as r,Al as s,Pl as t,Ea as u,_c as v,Cc as w,Nc as x,xc as y,Ic as z};