@buildbase/sdk 0.0.56 → 0.0.58

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 (35) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +7 -9
  3. package/dist/css/styles.css +1 -1
  4. package/dist/index.cjs +1 -1
  5. package/dist/index.d.ts +7 -0
  6. package/dist/index.mjs +1 -1
  7. package/dist/mcp/index.cjs +1 -1
  8. package/dist/mcp/index.mjs +1 -1
  9. package/dist/react/chunks/{SettingsDialog-VaOW2jtS.mjs → SettingsDialog-B_7I4e7D.mjs} +1 -1
  10. package/dist/react/chunks/{SettingsDialog-CvoDs5eM.cjs → SettingsDialog-Y6Y8MzPi.cjs} +1 -1
  11. package/dist/react/chunks/{SubscriptionDialog-8CagFA_V.cjs → SubscriptionDialog-CwDxl0IL.cjs} +1 -1
  12. package/dist/react/chunks/{SubscriptionDialog-C5EgpXE0.mjs → SubscriptionDialog-D2tAmz-0.mjs} +1 -1
  13. package/dist/react/chunks/react-2_QlCyzs.cjs +2 -0
  14. package/dist/react/chunks/react-DS9JF2Lc.mjs +2 -0
  15. package/dist/react/index.cjs +1 -1
  16. package/dist/react/index.d.ts +79 -17
  17. package/dist/react/index.mjs +1 -1
  18. package/docs/MCP-AND-AGENT-READINESS.md +1 -3
  19. package/package.json +1 -1
  20. package/dist/react/chunks/react-BBY-Vuzr.cjs +0 -2
  21. package/dist/react/chunks/react-CvU8uS25.mjs +0 -2
  22. /package/dist/react/chunks/{ar-CGbuXEeR.cjs → ar-D7uaSur2.cjs} +0 -0
  23. /package/dist/react/chunks/{ar-DnShbYvQ.mjs → ar-DHxjPtfZ.mjs} +0 -0
  24. /package/dist/react/chunks/{de-a1mX2rR4.cjs → de-CBzx6NJq.cjs} +0 -0
  25. /package/dist/react/chunks/{de-C3iuiLAz.mjs → de-D_xfGk1N.mjs} +0 -0
  26. /package/dist/react/chunks/{es-u9vKMeaX.mjs → es-D4-Dv2t5.mjs} +0 -0
  27. /package/dist/react/chunks/{es-D4T7YE7x.cjs → es-WVRwuj-e.cjs} +0 -0
  28. /package/dist/react/chunks/{fr-Bnnz2yJZ.cjs → fr-CEpK52jT.cjs} +0 -0
  29. /package/dist/react/chunks/{fr-DjgpP202.mjs → fr-DurP7qkZ.mjs} +0 -0
  30. /package/dist/react/chunks/{hi-Cu_9iCjb.mjs → hi-7roM83DB.mjs} +0 -0
  31. /package/dist/react/chunks/{hi-B8Mjr8rU.cjs → hi-CVqVRSoy.cjs} +0 -0
  32. /package/dist/react/chunks/{ja-B0eCVKdZ.cjs → ja-BrDXec_v.cjs} +0 -0
  33. /package/dist/react/chunks/{ja-DfJ5WUrG.mjs → ja-DT8x4SW1.mjs} +0 -0
  34. /package/dist/react/chunks/{zh-JjoMmHmK.mjs → zh-CH1Z55Je.mjs} +0 -0
  35. /package/dist/react/chunks/{zh-BnPZ0j4w.cjs → zh-CdCzcD53.cjs} +0 -0
@@ -0,0 +1,2 @@
1
+ "use client";
2
+ "use strict";var e=require("react/jsx-runtime"),t=require("react"),r=require("clsx"),s=require("tailwind-merge"),n=require("intl-messageformat"),a=require("@hookform/resolvers/zod"),i=require("react-hook-form"),o=require("@radix-ui/react-slot"),c=require("class-variance-authority"),l=require("lucide-react"),u=require("@radix-ui/react-label"),d=require("zod"),p=require("@radix-ui/react-avatar"),m=require("@radix-ui/react-dialog"),h=require("@radix-ui/react-icons"),g=require("@radix-ui/react-radio-group"),f=require("@radix-ui/react-scroll-area"),y=require("@radix-ui/react-separator"),b=require("@radix-ui/react-accordion"),x=require("@radix-ui/react-alert-dialog");function w(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,Object.freeze(t)}var v=w(t),k=w(u),S=w(p),C=w(m),N=w(g),P=w(f),E=w(y),j=w(b),I=w(x);function A(...e){return s.twMerge(r.clsx(e))}let U=!0;function W(e,...t){U&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(e,...t)}function R(e,...t){console.error(e,...t)}function T(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}async function F(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 O(e,t="Request failed"){if(!e.ok){let r=t;try{const t=await F(e);r=t.message||t.error||r}catch{r=function(e,t){const r={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}: ${r})`)}(e,t).message}throw new Error(r)}try{return await F(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class _ extends Error{constructor(e,t,r,s){super(e),this.code=t,this.context=r,this.originalError=s,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,_)}}const D=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1}}configure(e){this.config={...this.config,...e},void 0!==e.enableConsoleLogging&&function(e){void 0!==e.enableLogging&&(U=e.enableLogging)}({enableLogging:e.enableConsoleLogging})}handleError(e,t={}){if(T(e))return;const r=e instanceof Error?e:new _("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",t),s=r instanceof _?r:new _(r.message,"SDK_ERROR",t,r);if(this.config.enableConsoleLogging&&W(`[SDK Error] ${t.component||"Unknown"}:`,{message:s.message,code:s.code,context:s.context,originalError:s.originalError,stack:s.stack}),this.config.onError)try{this.config.onError(s,t)}catch(e){R("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(s,t)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...r)=>e(...r).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...r)=>{try{return e(...r)}catch(e){throw this.handleError(e,t),e}}}};function L(e,t={}){D.handleError(e,t)}function M(e,t={}){return!T(e)&&(D.handleError(e,t),!0)}function $(e,t,r){return e instanceof Error?e.message:r(t)}function B(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return L(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function q(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){L(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}function z(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){L(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}const V="saas-session-id",G="saas-device-id",J="code",K="state";function H(e){q(V,e)}function Y(){z(V)}function Q(){return function(){if("undefined"==typeof window)return null;try{return B(V)}catch(e){return L(e,{component:"auth-utils",action:"getSessionId",metadata:{key:V}}),null}}()}function Z(e){if("undefined"!=typeof window&&e)try{q(G,e)}catch(e){L(e,{component:"auth-utils",action:"setDeviceId",metadata:{key:G}})}}function X(){const e=Q(),t={};e&&(t["x-session-id"]=e);const r=function(){if("undefined"==typeof window)return null;try{return B(G)??null}catch(e){return L(e,{component:"auth-utils",action:"getOrCreateDeviceId",metadata:{key:G}}),null}}();return r&&(t["x-device-id"]=r),t}function ee(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get(J)}catch(e){return L(e,{component:"auth-utils",action:"getTokenFromUrl",metadata:{param:J}}),null}}function te(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.delete(J),e.searchParams.delete(K),window.history.replaceState({},"",e.toString())}catch(e){L(e,{component:"auth-utils",action:"removeTokenFromUrl",metadata:{param:J}})}}const re=new WeakSet,se=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),ne="SDK is not ready (missing serverUrl, version, or orgId)";class ae{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(ne);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(ne)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:X()}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){re.has(e)||(re.add(e),this._onError?.(e,t))}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}static delay(e,t){return new Promise((r,s)=>{const n=()=>{clearTimeout(a),s(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return n();const a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}async executeFetchUrl(e,t,r){const s=(t.method??"GET").toUpperCase(),n=r??e,a=this.buildHeaders(t),i={...t,headers:a},o=se.has(s);let c,l;if(this._timeout>0){l=new AbortController;const e=l;c=setTimeout(()=>e.abort(),this._timeout),i.signal=t.signal?function(e,t){const r=AbortSignal.any;if("function"==typeof r)return r([e,t]);const s=new AbortController,n=e=>{s.signal.aborted||s.abort(e.reason)};for(const r of[e,t]){if(r.aborted){n(r);break}r.addEventListener("abort",()=>n(r),{once:!0})}return s.signal}(t.signal,e.signal):e.signal}const u=e=>{if(l?.signal.aborted&&!t.signal?.aborted){const e=new Error(`Request timeout after ${this._timeout}ms: ${s} ${n}`);return this.reportError(e,{method:s,path:n}),e}return e},d=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 r=this._fetch.bind(globalThis),n=await r(e,i);if(this._debug&&console.log(`[BuildBase] ${s} ${e} → ${n.status}`),401===n.status&&this._onUnauthorized&&this._onUnauthorized(),n.status>=500&&o&&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 ae.delay(e,i.signal),d(t+1)}return n}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw u(e);if(o&&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 ae.delay(e,i.signal)}catch(e){throw u(e)}return d(t+1)}throw e instanceof Error&&this.reportError(e,{method:s,path:n}),e}};try{return await d(0)}finally{void 0!==c&&clearTimeout(c)}}async fetchJson(e,t={},r="Request failed"){this.ensureReady();try{const s=await this.executeFetch(e,t);return await O(s,r)}catch(r){throw r instanceof Error&&this.reportError(r,{method:(t.method??"GET").toUpperCase(),path:e}),r}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchUnwrapped(e,t={},r="Request failed"){const s=await this.fetchResponse(e,t);return s.ok||await this.throwResponseError(s,r),this.unwrapResponse(s,r)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async throwResponseError(e,t){let r=t;try{r=(await e.json()).message||r}catch{r=`${t} (${e.status}: ${e.statusText})`}throw new Error(r)}apiPath(e,...t){return e.reduce((e,r,s)=>e+r+(s<t.length?encodeURIComponent(String(t[s])):""),"")}async unwrapResponse(e,t){const r=await e.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||t);return void 0!==r.data?r.data:r}return r}}class ie extends ae{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,r="Failed to initiate authentication",s=await this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});return s.ok||await this.throwResponseError(s,r),this.unwrapResponse(s,r)}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 r=await this.fetchUnwrapped("device-token",{headers:{"x-session-id":e},signal:t},"Failed to fetch device token");return r?.deviceToken??""}catch{return""}}}class oe extends ae{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 ce=class{constructor(e){this.api=new oe(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const t=e?.context??{},r=t?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),s=t?.language??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[0]:void 0),n=t?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),a=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:r,language:s,timezone:n,currency:a}})}};class le extends ae{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 ue extends ae{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,r){await this.fetchJson(this.apiPath`devices/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:r},"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")}}class de extends ae{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 pe extends ae{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 me extends ae{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class he extends ae{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 r=await this.unwrapResponse(t,"Failed to fetch user attributes");return r&&"object"==typeof r&&!Array.isArray(r)?r:{}}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 r=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof r&&null!==r?r:{}}}class ge extends ae{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(e){return this.fetchJson("workspaces",{signal:e},"Failed to fetch workspaces")}async createWorkspace(e,t){return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e),signal:t},"Failed to create workspace")}async updateWorkspace(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t),signal:r},"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,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to invite member")}async removeUser(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE",signal:r},"Failed to remove user")}async updateUser(e,t,r,s){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(r),signal:s},"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,r){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t}),signal:r},"Failed to update workspace permissions")}async getFeatures(e){return this.fetchJson("workspaces/features",{signal:e},"Failed to fetch features")}async updateFeature(e,t,r,s){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:r}}),signal:s},"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 getPasskeys(e){const t=await this.fetchJson("passkeys",{signal:e},"Failed to fetch passkeys");return t?.passkeys??[]}async renamePasskey(e,t,r){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:r},"Failed to rename passkey")}async deletePasskey(e,t){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"DELETE",signal:t},"Failed to remove passkey")}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,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`,{signal:r},"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,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to create checkout session")}async selectFreePlan(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t}),signal:r},"Failed to select free plan")}async updateSubscription(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t),signal:r},"Failed to update subscription")}async createBillingPortalSession(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{}),signal:r})}async listInvoices(e,t=10,r,s){const n=new URLSearchParams;return n.append("limit",t.toString()),r&&n.append("starting_after",r),this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices`+`?${n.toString()}`,{signal:s},"Failed to fetch invoices")}async getInvoice(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices/${t}`,{signal:r},"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,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to record usage")}async recordUsageBatch(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to record batch usage")}async getQuotaUsageStatus(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`,{signal:r},"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,r){const s=new URLSearchParams;t?.quotaSlug&&s.append("quotaSlug",t.quotaSlug),t?.from&&s.append("from",t.from),t?.to&&s.append("to",t.to),t?.source&&s.append("source",t.source),t?.page&&s.append("page",t.page.toString()),t?.limit&&s.append("limit",t.limit.toString());const n=s.toString(),a=this.apiPath`workspaces/${e}/subscription/usage/logs`+(n?`?${n}`:"");return this.fetchUnwrapped(a,{signal:r},"Failed to fetch usage logs")}async sendNotification(e,t,r,s,n){const a={event:t};return r&&(a.userId=r),s&&(a.data=s),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(a),signal:n},"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,r){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:r},"Failed to update notification preferences")).notificationPreferences??{}}async getCreditBalance(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits`,{signal:t},"Failed to fetch credit balance")}async consumeCredits(e,t,r){const s=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t),signal:r});if(!s.ok){if(402===s.status){const e=await s.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(s,"Failed to consume credits")}return this.unwrapResponse(s,"Failed to consume credits")}async purchaseCredits(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to create credit purchase checkout")}async getCreditPackages(e,t){const r=await this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/packages`,{signal:t},"Failed to fetch credit packages");return r.docs??r}async getCreditTransactions(e,t,r){const s=new URLSearchParams;t?.type&&s.append("type",t.type),t?.page&&s.append("page",t.page.toString()),t?.limit&&s.append("limit",t.limit.toString());const n=s.toString(),a=this.apiPath`workspaces/${e}/credits/transactions`+(n?`?${n}`:"");return this.fetchUnwrapped(a,{signal:r},"Failed to fetch credit transactions")}async getCreditBuckets(e,t,r){const s=new URLSearchParams;t?.status&&s.append("status",t.status),t?.source&&s.append("source",t.source),t?.page&&s.append("page",t.page.toString()),t?.limit&&s.append("limit",t.limit.toString());const n=s.toString(),a=this.apiPath`workspaces/${e}/credits/buckets`+(n?`?${n}`:"");return this.fetchUnwrapped(a,{signal:r},"Failed to fetch credit buckets")}async getExpiringCredits(e,t,r){const s=t?`?days=${t}`:"";return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/expiring`+s,{signal:r},"Failed to fetch expiring credits")}}function fe(e){return Boolean(e?.serverUrl&&e?.version&&e?.orgId)}exports.ApiVersion=void 0,(exports.ApiVersion||(exports.ApiVersion={})).V1="v1";const ye={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"};class be{constructor(){this.callbacks=null}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){L(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}}async emitUserCreated(e){await this.emit(ye.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(ye.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(ye.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(ye.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,r){await this.emit(ye.WorkspaceUserAdded,{userId:e,workspace:t,role:r})}async emitWorkspaceUserRemoved(e,t,r){await this.emit(ye.WorkspaceUserRemoved,{userId:e,workspace:t,role:r})}async emitWorkspaceUserRoleChanged(e,t,r,s){await this.emit(ye.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:r,newRole:s})}async emitWorkspaceCreated(e){await this.emit(ye.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(ye.WorkspaceDeleted,{workspace:e})}}const xe=new be;function we(){const e=new Set;return{subscribe:t=>(e.add(t),()=>{e.delete(t)}),invalidate(){e.forEach(e=>e())},reset(){e.clear()}}}const ve=we(),ke=ve.subscribe,Se=ve.invalidate,Ce=we(),Ne=Ce.subscribe,Pe=Ce.invalidate,Ee=we(),je=Ee.subscribe,Ie=Ee.invalidate,Ae="bb",Ue={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",OpenConnectGuide:"openConnectGuide",Invite:"invite"},We={Success:"success",Cancel:"cancel",Error:"error"},Re={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function Te(e,t){const r=t??("undefined"!=typeof window?window.location.href:"https://localhost");let s;try{s=new URL(r)}catch{throw new Error(`createBBUrl: invalid base URL: ${JSON.stringify(r)}`)}return s.search="",s.searchParams.set(Ae,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),s.toString()}function Fe(e,t){const r=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:Te({action:Ue.CreditPurchase,status:We.Success,ws:e,screen:Re.Credits},r),cancelUrl:Te({action:Ue.CreditPurchase,status:We.Cancel,ws:e,screen:Re.Credits},r)}}function Oe(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(Ae);if(!e)return null;const t=function(e){const t={};if(!e)return t;const r=e.split(",");for(const e of r){const r=e.indexOf(":");if(-1===r)continue;const s=decodeURIComponent(e.slice(0,r)),n=decodeURIComponent(e.slice(r+1));s&&(t[s]=n)}return t}(e);return Object.keys(t).length>0?t:null}catch{return null}}function _e(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(Ae)&&(e.searchParams.delete(Ae),window.history.replaceState({},"",e.toString()))}catch{}}function De(e,t={}){if(!e||"string"!=typeof e)return null;if(/^\/(?![/\\])/.test(e))return e;let r;try{r=new URL(e)}catch{return null}const s="https:"===r.protocol,n="http:"===r.protocol&&("localhost"===r.hostname||"127.0.0.1"===r.hostname||"[::1]"===r.hostname);if(!s&&!n)return null;const{sameOrigin:a,allowedOrigins:i}=t;return a||i?.length?a&&"undefined"!=typeof window&&window.location&&r.origin===window.location.origin||i?.some(e=>e.replace(/\/+$/,"")===r.origin)?e:null:e}function Le(e,t="/",r={}){if("undefined"==typeof window||!window.location)return!1;const s=De(e,r);return window.location.href=s??De(t)??"/",!0}const Me="saas-auth-intent";function $e(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function Be(e){De(e,{sameOrigin:!0})&&function(e,t){try{q(e,JSON.stringify(t))}catch(t){L(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}(Me,{returnUrl:e,createdAt:Date.now()})}function qe(){const e=function(e,t){const r=B(e);if(!r)return null;try{const s=JSON.parse(r);return t&&!t(s)?(L(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),z(e),null):s}catch(t){return L(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),z(e),null}}(Me,$e);return z(Me),e?Date.now()-e.createdAt>6e5?null:De(e.returnUrl,{sameOrigin:!0}):null}const ze={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:"฿"},Ve={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function Ge(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return ze[t]??t.toUpperCase()}const Je=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],Ke=Je.map(e=>({value:e,label:`${e.toUpperCase()} (${Ge(e)})`})),He=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),Ye=new Set(["bhd","jod","kwd","omr","tnd"]),Qe=new Map;function Ze(e){const t=(e??"").trim().toLowerCase();if(!t)return 2;if(He.has(t))return 0;if(Ye.has(t))return 3;if("isk"===t)return 2;let r=Qe.get(t);if(void 0===r){try{r=new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).resolvedOptions().maximumFractionDigits??2}catch{r=2}Qe.set(t,r)}return r}function Xe(e,t){const r=Ze(t);return 0===r?e.toLocaleString("en-US"):(e/10**r).toFixed(r)}function et(e,t,r="en-US"){const s=(t??"").trim(),n=Ze(s),a=e/10**n;if(!s)return a.toFixed(n);try{return new Intl.NumberFormat(r,{style:"currency",currency:s.toUpperCase(),minimumFractionDigits:n,maximumFractionDigits:n}).format(a)}catch{return Ge(s)+(0===n?a.toLocaleString("en-US"):a.toFixed(n))}}function tt(e,t){return Ge(t)+Xe(e,t)}const rt={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included",hardLimit:"hard limit"};const st={included:"included",then:"then",hardLimit:"hard limit"};const nt={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},at={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"};function it(e,t){const r=e.pricingVariants;if(!r?.length)return null;const s=t.toLowerCase();return r.find(e=>e.currency?.toLowerCase()===s)??null}function ot(e,t,r){const s=it(e,t);if(!s?.basePricing)return null;const n=s.basePricing[r];return null!=n?n:null}function ct(e,t,r,s){const n=it(e,t),a=n?.quotaOverages?.[r];if(a)return a[s]}function lt(e,t){const r=it(e,t);return r?.seatPricing?.enabled?r.seatPricing:null}function ut(e,t,r){const s=lt(e,t);return s?.perSeat?s.perSeat[r]??null:null}function dt(e,t){return Math.max(0,e-(t||0))}function pt(e,t,r,s){const n=lt(e,t);if(!n)return null;return dt(s,n.includedSeats)*(ut(e,t,r)??0)}function mt(e){const{planVersion:t,currency:r="usd",settingsMaxUsers:s}=e;if(t){const e=lt(t,r);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=s&&s>0?{maxUsers:s,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}}function ht(e){const{memberCount:t,maxUsersConfig:r,hasSubscription:s=!0,requireSubscription:n=!1}=e;if(n&&!s)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:a,source:i}=r;if(a<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(t>=a){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[i]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[i]??"users.memberLimitMessage",blockMessageValues:{maxUsers:a}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}}const gt="saas-workspace-current",ft=e=>{e?q(gt,e._id):z(gt)},yt=()=>B(gt),bt=()=>{z(gt)},xt=(e,t)=>!!e&&t.some(t=>t._id===e);function wt(e,t){if(!t)return!1;const r=(s=e.createdBy)?"string"==typeof s?s:"object"==typeof s&&"_id"in s&&"string"==typeof s._id?s._id:null:null;var s;return null!==r&&r===t}function vt(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const r=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return r&&"object"==typeof r&&"role"in r&&"string"==typeof r.role?r.role:null}const kt={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"},St=Object.values(kt),Ct={admin:St.filter(e=>e!==kt.WORKSPACE_DELETE),member:[kt.WORKSPACE_SETTINGS_VIEW,kt.WORKSPACE_MEMBERS_VIEW,kt.WORKSPACE_FEATURES_VIEW,kt.WORKSPACE_BILLING_VIEW,kt.WORKSPACE_USAGE_VIEW],viewer:[kt.WORKSPACE_SETTINGS_VIEW,kt.WORKSPACE_MEMBERS_VIEW]};function Nt(e){const t=new Set;for(const r of Object.values(e))for(const e of r)t.add(e);return Array.from(t)}function Pt(e){const{userId:t,workspace:r,settings:s,appPermissions:n}=e;if(!r||!t)return new Set;if(wt(r,t)){const e=new Set(St);if(n)for(const t of Nt(n))e.add(t);if(r.permissions)for(const t of Nt(r.permissions))e.add(t);if(s?.workspace?.permissions)for(const t of Nt(s.workspace.permissions))e.add(t);return e}const a=e.workspaceRole??vt(r,t);if(!a)return new Set;const i=r.permissions,o=s?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),l=e=>e.filter(e=>!e.startsWith("workspace:")),u=!!i&&a in i,d=!!o&&a in o,p=a in Ct;let m;if(u)m=c(i[a]);else if(d)m=c(o[a]);else if(p)m=Ct[a];else{const e=s?.workspace?.defaultRole;m=e&&e in Ct?Ct[e]:[]}const h=new Set(m),g=u?l(i[a]):[],f=n?.[a]?l(n[a]):[],y=u?g:f;for(const e of y)h.add(e);return function(e,t,r){if(!r?.workspace)return;const{canInviteMembers:s}=r.workspace;(!1===s||"admin-only"===s&&"admin"!==t)&&e.delete(kt.WORKSPACE_MEMBERS_INVITE)}(h,a,s),h}var Et;function jt(e){return{isAuthenticated:e===exports.AuthStatus.authenticated,isLoading:e===exports.AuthStatus.loading||e===exports.AuthStatus.redirecting||e===exports.AuthStatus.authenticating,isRedirecting:e===exports.AuthStatus.redirecting}}exports.AuthStatus=void 0,(Et=exports.AuthStatus||(exports.AuthStatus={})).loading="loading",Et.redirecting="redirecting",Et.authenticated="authenticated",Et.unauthenticated="unauthenticated",Et.authenticating="authenticating";class It extends t.Component{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(L(e,{component:"ErrorBoundary",action:"componentDidCatch",metadata:{componentStack:t.componentStack,errorBoundary:this.constructor.name}}),this.props.onError)try{this.props.onError(e,t)}catch(e){R("[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.jsxs("div",{style:{padding:"1rem",border:"1px solid hsl(var(--destructive, 0 84.2% 60.2%))",borderRadius:"0.5rem",backgroundColor:"hsl(var(--destructive, 0 84.2% 60.2%) / 0.08)",color:"hsl(var(--destructive, 0 70% 35%))"},children:[e.jsx("h3",{style:{margin:"0 0 0.5rem 0",fontSize:"1rem",fontWeight:600},children:this.props.errorTitle??"Something went wrong"}),e.jsx("p",{style:{margin:"0 0 1rem 0",fontSize:"0.875rem"},children:this.state.error.message||"An unexpected error occurred"}),e.jsx("button",{onClick:this.resetError,style:{padding:"0.5rem 1rem",backgroundColor:"hsl(var(--destructive, 0 84.2% 60.2%))",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 At=()=>({type:"AUTHENTICATION_STARTED"}),Ut=()=>({type:"AUTHENTICATION_PROCESSING"}),Wt=()=>({type:"AUTHENTICATION_FAILED"}),Rt=e=>({type:"SET_SESSION",payload:e}),Tt=()=>({type:"REMOVE_SESSION"});function Ft(e,r,s,n){const a=t.useMemo(()=>{const t=s??(e=>e);let r,a,i=!1;return()=>{const s=e();if(!i)return i=!0,r=s,a=t(s),a;if(Object.is(r,s))return a;const o=t(s);r=s;return(n?n(a,o):Object.is(a,o))||(a=o),a}},[e,s,n]);return t.useSyncExternalStore(r,a,a)}function Ot({name:r,initialState:s,reducer:n,initializer:a}){const i=t.createContext(null);i.displayName=`${r}StoreContext`;const o=t.memo(({children:r})=>{const o=t.useRef(null);return null===o.current&&(o.current=function(e,t,r){let s=r?r(e):e;const n=new Set;return{getState:()=>s,dispatch:e=>{const r=t(s,e);Object.is(r,s)||(s=r,n.forEach(e=>e()))},subscribe:e=>(n.add(e),()=>{n.delete(e)})}}(s,n,a)),e.jsx(i.Provider,{value:o.current,children:r})});o.displayName=`${r}Provider`;const c=(e="Store")=>{const s=t.useContext(i);if(!s)throw(e=>new Error(`use${r}${e} must be used within a ${r}Provider. Make sure SaaSOSProvider is wrapping your application.`))(e);return s};return{Provider:o,useContext:()=>{const e=c("Context"),r=Ft(e.getState,e.subscribe);return t.useMemo(()=>({state:r,dispatch:e.dispatch}),[r,e])},useState:()=>{const e=c("State");return Ft(e.getState,e.subscribe)},useDispatch:()=>c("Dispatch").dispatch,useSelector:(e,t)=>{const r=c("Selector");return Ft(r.getState,r.subscribe,e,t)},useStore:c}}function _t(e,t,r){return{...e,[t]:r}}function Dt(e,t){return{...e,...t}}const{Provider:Lt,useDispatch:Mt,useStore:$t}=Ot({name:"Auth",initialState:{session:null,status:exports.AuthStatus.loading},reducer:(e,t)=>{switch(t.type){case"AUTHENTICATION_STARTED":return _t(e,"status",exports.AuthStatus.redirecting);case"AUTHENTICATION_PROCESSING":return _t(e,"status",exports.AuthStatus.authenticating);case"AUTHENTICATION_FAILED":case"REMOVE_SESSION":return Dt(e,{session:null,status:exports.AuthStatus.unauthenticated});case"SET_SESSION":return Dt(e,{session:t.payload,status:exports.AuthStatus.authenticated});default:return e}}}),Bt=Lt,qt=Mt,zt=$t,Vt=e=>({type:"SET_SAAS_OS_CONFIG",payload:e}),Gt=e=>({type:"SET_SETTINGS",payload:e}),Jt=(e,t)=>({type:"SET_SETTINGS_STATUS",payload:{status:e,error:t}}),Kt=()=>({serverUrl:"",version:exports.ApiVersion.V1,orgId:"",settings:null,settingsStatus:"idle",settingsError:null}),{Provider:Ht,useDispatch:Yt,useStore:Qt}=Ot({name:"OS",initialState:Kt(),reducer:(e,t)=>{switch(t.type){case"SET_SAAS_OS_CONFIG":return Dt(e,t.payload);case"REMOVE_SAAS_OS_CONFIG":return Kt();case"SET_SETTINGS":return Dt(e,{settings:t.payload,settingsStatus:"loaded",settingsError:null});case"SET_SETTINGS_STATUS":return Dt(e,{settingsStatus:t.payload.status,settingsError:t.payload.error??null});default:return e}}}),Zt=Ht,Xt=Yt,er=Qt,tr=e=>({type:"SET_WORKSPACES",payload:e}),rr=e=>({type:"ADD_WORKSPACE",payload:e}),sr=e=>({type:"UPDATE_WORKSPACE",payload:e}),nr=e=>({type:"REMOVE_WORKSPACE",payload:e}),ar=e=>({type:"SET_ALL_FEATURES",payload:e}),ir=e=>({type:"SET_CURRENT_WORKSPACE",payload:e}),or=()=>({type:"RESET_CURRENT_WORKSPACE"}),cr=e=>({type:"SET_IS_INITIALIZED",payload:e}),lr=e=>({type:"SET_LOADING",payload:e}),ur=e=>({type:"SET_ERROR",payload:e}),dr=e=>({type:"SET_REFRESHING",payload:e}),pr=e=>({type:"SET_SWITCHING_TO_ID",payload:e}),{Provider:mr,useDispatch:hr,useStore:gr}=Ot({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 _t(e,"workspaces",t.payload);case"ADD_WORKSPACE":return _t(e,"workspaces",[...e.workspaces,t.payload]);case"UPDATE_WORKSPACE":return _t(e,"workspaces",e.workspaces.map(e=>e._id===t.payload._id?t.payload:e));case"REMOVE_WORKSPACE":return _t(e,"workspaces",e.workspaces.filter(e=>e._id!==t.payload));case"SET_ALL_FEATURES":return _t(e,"allFeatures",t.payload);case"SET_CURRENT_WORKSPACE":return _t(e,"currentWorkspace",t.payload);case"RESET_CURRENT_WORKSPACE":return _t(e,"currentWorkspace",null);case"SET_IS_INITIALIZED":return _t(e,"isInitialized",t.payload);case"SET_LOADING":return _t(e,"loading",t.payload);case"SET_ERROR":return _t(e,"error",t.payload);case"SET_REFRESHING":return _t(e,"refreshing",t.payload);case"SET_SWITCHING_TO_ID":return _t(e,"switchingToId",t.payload);default:return e}}}),fr=mr,yr=hr,br=gr,xr=t.memo(({children:t})=>e.jsx(Zt,{children:e.jsx(Bt,{children:e.jsx(fr,{children:t})})}));xr.displayName="SDKContextProvider";const wr=t.createContext({});wr.displayName="CheckoutConfigContext";const vr=t.memo(({getCheckoutStripeParams:r,children:s})=>{const n=t.useMemo(()=>({getCheckoutStripeParams:r}),[r]);return e.jsx(wr.Provider,{value:n,children:s})});vr.displayName="CheckoutConfigProvider";const kr={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:"Success!",error:"Error",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",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!",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 — 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:{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.",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}"},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",success:"Profile saved successfully",nameMinLength:"Name must be at least 2 characters.",save:"Save",reset:"Reset"},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",updateWorkspace:"Update Workspace"},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:{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.",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:"Looks like you are not logged in. Please login 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}"},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",unauthorized:"Unauthorized - Please check your session",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 — it revokes access immediately.",connectedAgentsDisconnect:"Disconnect",connectedAgentsEmpty:"No connected agents.",connectedAgentsAccess:"Access",connectedAgentsGranted:"Granted",connectedAgentsLoadFailed:"Failed to load connected agents",connectedAgentsRevokeFailed:"Failed to disconnect",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:'To add a passkey, choose "Add a passkey" the next time you sign in on the device you want to use.',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",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."}},Sr={en:async()=>kr,es:async()=>(await Promise.resolve().then(function(){return require("./es-WVRwuj-e.cjs")})).es,fr:async()=>(await Promise.resolve().then(function(){return require("./fr-CEpK52jT.cjs")})).fr,de:async()=>(await Promise.resolve().then(function(){return require("./de-CBzx6NJq.cjs")})).de,ja:async()=>(await Promise.resolve().then(function(){return require("./ja-BrDXec_v.cjs")})).ja,zh:async()=>(await Promise.resolve().then(function(){return require("./zh-CdCzcD53.cjs")})).zh,hi:async()=>(await Promise.resolve().then(function(){return require("./hi-CVqVRSoy.cjs")})).hi,ar:async()=>(await Promise.resolve().then(function(){return require("./ar-D7uaSur2.cjs")})).ar},Cr=["en","es","fr","de","ja","zh","hi","ar"];const Nr={hi:"hi-u-nu-deva",ar:"ar-u-nu-arab"};function Pr(e,t){const r={...e};for(const s of Object.keys(t)){const n=t[s],a=e[s];"string"==typeof n?r[s]=n:n&&"object"==typeof n&&a&&"object"==typeof a&&(r[s]=Pr(a,n))}return r}const Er=t.createContext({messages:kr,locale:"en",formattingLocale:"en"});function jr({locale:e="en",messageOverrides:r,children:s}){const n=function(e){const t=e.toLowerCase().replace("_","-");if(Cr.includes(t))return t;const r=t.split("-")[0];return Cr.includes(r)?r:"en"}(e),[a,i]=t.useState(kr);t.useEffect(()=>{if("en"===n)return void i(kr);let e=!1;const t=Sr[n];return t&&t().then(t=>{e||i(t)}),()=>{e=!0}},[n]);const o=t.useMemo(()=>r?Pr(a,r):a,[a,r]),c=function(e){return Nr[e]??e}(n),l=t.useMemo(()=>({messages:o,locale:n,formattingLocale:c}),[o,n,c]);return t.createElement(Er.Provider,{value:l},s)}const Ir=new Map,Ar=new Map,Ur=new Map;function Wr(e,t){return t?`${e}:${JSON.stringify(t)}`:e}const Rr={getNumberFormat(e,t){const r=Wr(e,t);let s=Ir.get(r);return s||(s=new Intl.NumberFormat(e,t),Ir.set(r,s)),s},getDateTimeFormat(e,t){const r=Wr(e,t);let s=Ar.get(r);return s||(s=new Intl.DateTimeFormat(e,t),Ar.set(r,s)),s},getPluralRules(e,t){const r=Wr(e,t);let s=Ur.get(r);return s||(s=new Intl.PluralRules(e,t),Ur.set(r,s)),s}},Tr=new Map;function Fr(){const{messages:e,locale:r,formattingLocale:s}=t.useContext(Er),a=t.useMemo(()=>{const t=(e,t)=>{let r=e;for(const e of t.split(".")){if(!r||"object"!=typeof r||!(e in r))return;r=r[e]}return"string"==typeof r?r:void 0};return(r,a)=>{const i=t(e,r)??t(kr,r)??r;if(!a)return i;try{const e=function(e,t){const r=`${t}:${e}`;let s=Tr.get(r);return s||(s=new n(e,t,void 0,{formatters:Rr}),Tr.set(r,s)),s}(i,s),t=e.format(a);return"string"==typeof t?t:String(t)}catch{return i.replace(/\{(\w+)\}/g,(e,t)=>String(a[t]??`{${t}}`))}}},[e,s]),i="ar"===r?"rtl":"ltr",o=t.useMemo(()=>e=>e.toLocaleString(s),[s]),c=t.useMemo(()=>(e,t)=>et(e,t,s),[s]);return{t:a,locale:r,formattingLocale:s,dir:i,fmtNum:o,fmtCents:c,messages:e}}function Or(){const e=t.useRef(null);t.useEffect(()=>()=>e.current?.abort(),[]);return{begin:t.useCallback(()=>{e.current?.abort();const t=new AbortController;return e.current=t,t},[]),settle:t.useCallback(t=>e.current===t&&(e.current=null,!t.signal.aborted),[])}}function _r(){const e=qt(),r=Xt(),s=yr();return t.useMemo(()=>({auth:e,os:r,workspaces:s}),[e,r,s])}function Dr(e,r){const s=er(),n=zt(),a=br(),i=t.useCallback(e=>{const t=[s.subscribe(e),n.subscribe(e),a.subscribe(e)];return()=>t.forEach(e=>e())},[s,n,a]);return Ft(t.useMemo(()=>{let e=null;return()=>(null!==e&&e.os===s.getState()&&e.auth===n.getState()&&e.workspaces===a.getState()||(e={os:s.getState(),auth:n.getState(),workspaces:a.getState()}),e)},[s,n,a]),i,e,r)}function Lr(e,r,s){t.useEffect(()=>{const t=new AbortController;return e(t.signal).catch(e=>{T(e)||(s?.onError?s.onError(e):L(e,{component:"useAsyncEffect",action:"effect",metadata:{note:"Unhandled rejection - consider passing onError"}}))}),()=>t.abort()},r)}function Mr(){return Dr(e=>e.os)}const $r=new Map;let Br=null;function qr(){const e=_r(),r=Mr(),{serverUrl:s,version:n,orgId:a,settings:i,settingsStatus:o,settingsError:c}=r,l=t.useMemo(()=>fe(r)?new me({serverUrl:s,version:n,orgId:a}):null,[s,n,a]),u=t.useCallback(async t=>{if(!l)return null;const r=((e,t,r)=>`${e}|${t}|${r}`)(s,n,a);Br=r;const i=$r.get(r);if(i)return i;const o=(async()=>{e.os(Jt("loading"));try{const t=await l.getSettings();return Br===r&&e.os(Gt(t)),t}catch(t){return Br===r&&e.os(Jt("error",t instanceof Error?t.message:"Failed to load settings")),M(t,{component:"useSaaSSettings",action:"getSettings",metadata:{serverUrl:s,version:n,orgId:a}}),null}finally{$r.delete(r)}})();return $r.set(r,o),o},[l,e,s,n,a]);Lr(async()=>{i||fe(r)&&await u()},[s,n,a],{onError:e=>M(e,{component:"useSaaSSettings",action:"fetchSettings",metadata:{serverUrl:s,version:n,orgId:a}})});const d="loading"===o||("idle"===o||void 0===o)&&fe(r);return t.useMemo(()=>({settings:i,loading:d,error:c??null,refetch:u,getSettings:u}),[i,d,c,u])}function zr(){const e=Mr(),r=_r(),s=t.useCallback(()=>{Y(),r.auth(Tt()),e.auth?.callbacks?.onSessionExpired?.("expired")},[r,e.auth?.callbacks?.onSessionExpired]),n=function(e,r){return t.useMemo(()=>new ge({...e,onUnauthorized:r}),[e.serverUrl,e.version,e.orgId,r])}(e,s);return t.useMemo(()=>({os:e,api:n}),[e,n])}const Vr=e=>{const{t:r}=Fr(),{os:s,api:n}=zr(),a=fe(s),[i,o]=t.useState(null),[c,l]=t.useState(!1),[u,d]=t.useState(null),{begin:p,settle:m}=Or(),h=t.useCallback(async()=>{if(!e||!a)return p(),o(null),void l(!1);const t=p();l(!0),d(null);try{const r=await n.getPublicPlans(e);if(t.signal.aborted)return;o(r)}catch(s){if(t.signal.aborted)return;const n=$(s,"errors.fetchPlans",r);d(n),L(s,{component:"usePublicPlans",action:"fetchPlans",metadata:{slug:e}})}finally{m(t)&&l(!1)}},[n,e,a,p,m]);t.useEffect(()=>{h()},[h]);const g=e&&!a||c;return{items:i?.items??[],plans:i?.plans??[],notes:i?.notes,loading:g,error:u,refetch:h}},Gr=e=>{const{t:r}=Fr(),{api:s}=zr(),[n,a]=t.useState(null),[i,o]=t.useState(!1),[c,l]=t.useState(null),{begin:u,settle:d}=Or(),p=t.useCallback(async()=>{if(!e)return u(),a(null),void o(!1);const t=u();o(!0),l(null);try{const r=await s.getCurrentSubscription(e);if(t.signal.aborted)return;a(r)}catch(s){if(t.signal.aborted)return;const n=$(s,"errors.fetchSubscription",r);l(n),L(s,{component:"useSubscription",action:"fetchSubscription",metadata:{workspaceId:e}})}finally{d(t)&&o(!1)}},[s,e,u,d]);return t.useEffect(()=>{p()},[p]),{subscription:n,loading:i,error:c,refetch:p}},Jr=(e,r)=>{const{t:s}=Fr(),{api:n}=zr(),[a,i]=t.useState(null),[o,c]=t.useState(!1),[l,u]=t.useState(null),{begin:d,settle:p}=Or(),m=t.useCallback(async()=>{if(!e)return d(),i(null),void c(!1);const t=d();c(!0),u(null);try{const s=r?await n.getPlanGroupByVersion(e,r):await n.getPlanGroup(e);if(t.signal.aborted)return;i(s)}catch(n){if(t.signal.aborted)return;const a=$(n,"errors.fetchPlanGroup",s);u(a),L(n,{component:"usePlanGroup",action:"fetchPlanGroup",metadata:{workspaceId:e,groupVersionId:r}})}finally{p(t)&&c(!1)}},[n,e,r,d,p]);return t.useEffect(()=>{m()},[m]),{planGroup:a,loading:o,error:l,refetch:m}},Kr=e=>{const{t:r}=Fr(),{api:s}=zr(),[n,a]=t.useState(!1),[i,o]=t.useState(null);return{updateSubscription:t.useCallback(async(t,n)=>{if(!e)throw new Error("Workspace ID is required");a(!0),o(null);try{const r={planVersionId:t,...n?.billingInterval&&{billingInterval:n.billingInterval},...n?.successUrl&&{successUrl:n.successUrl},...n?.cancelUrl&&{cancelUrl:n.cancelUrl}},a=await s.updateSubscription(e,r);return Ie(),a}catch(s){const a=$(s,"errors.updateSubscription",r);throw o(a),L(s,{component:"useUpdateSubscription",action:"updateSubscription",metadata:{workspaceId:e,planVersionId:t,options:n}}),s}finally{a(!1)}},[s,e]),loading:n,error:i}},Hr=e=>{const{t:r}=Fr(),{api:s}=zr(),[n,a]=t.useState(null),[i,o]=t.useState(!1),[c,l]=t.useState(null),{begin:u,settle:d}=Or(),p=t.useCallback(async()=>{if(!e)return u(),a(null),void o(!1);const t=u();o(!0),l(null);try{const r=await s.getAllQuotaUsage(e);if(t.signal.aborted)return;a(r.quotas)}catch(s){if(t.signal.aborted)return;const n=$(s,"errors.fetchAllQuotaUsage",r);l(n),L(s,{component:"useAllQuotaUsage",action:"fetchAllUsage",metadata:{workspaceId:e}})}finally{d(t)&&o(!1)}},[s,e,u,d]);return t.useEffect(()=>{p()},[p]),{quotas:n,loading:i,error:c,refetch:p}},Yr=t.createContext(null);Yr.displayName="SubscriptionContext";const Qr=t.memo(function({children:r}){const s=Dr(e=>e.workspaces.currentWorkspace),{subscription:n,loading:a,error:i,refetch:o}=Gr(s?._id);t.useEffect(()=>je(o),[o]);const c=t.useMemo(()=>({response:n,loading:a,error:i,refetch:o}),[n,a,i,o]);return e.jsx(Yr.Provider,{value:c,children:r})});function Zr(){const e=t.useContext(Yr);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}Qr.displayName="SubscriptionContextProvider";const Xr=e=>{const{t:r}=Fr(),{api:s}=zr(),[n,a]=t.useState(null),[i,o]=t.useState(!1),[c,l]=t.useState(null),{begin:u,settle:d}=Or(),p=t.useCallback(async()=>{if(!e)return u(),a(null),void o(!1);const t=u();o(!0),l(null);try{const r=await s.getCreditBalance(e);if(t.signal.aborted)return;a(r)}catch(s){if(t.signal.aborted)return;const n=$(s,"errors.fetchCreditBalance",r);l(n),L(s,{component:"useCreditBalance",action:"fetchBalance",metadata:{workspaceId:e}})}finally{d(t)&&o(!1)}},[s,e,u,d]);return t.useEffect(()=>{p()},[p]),{balance:n,loading:i,error:c,refetch:p}},es=e=>{const{t:r}=Fr(),{api:s}=zr(),[n,a]=t.useState(!1),[i,o]=t.useState(null);return{consumeCredits:t.useCallback(async t=>{if(!e)throw new Error("Workspace ID is required");a(!0),o(null);try{const r=await s.consumeCredits(e,t);return Se(),r}catch(s){const n="INSUFFICIENT_CREDITS"===s.code?r("credits.insufficientDetail",{available:s.available,requested:s.requested}):$(s,"errors.consumeCredits",r);throw o(n),L(s,{component:"useConsumeCredits",action:"consumeCredits",metadata:{workspaceId:e,request:t}}),s}finally{a(!1)}},[s,e]),loading:n,error:i}},ts=e=>{const{t:r}=Fr(),{api:s}=zr(),[n,a]=t.useState(!1),[i,o]=t.useState(null);return{purchaseCredits:t.useCallback(async t=>{if(!e)throw new Error("Workspace ID is required");a(!0),o(null);try{return await s.purchaseCredits(e,t)}catch(s){const n=$(s,"errors.purchaseCredits",r);throw o(n),L(s,{component:"usePurchaseCredits",action:"purchaseCredits",metadata:{workspaceId:e,request:t}}),s}finally{a(!1)}},[s,e]),loading:n,error:i}},rs=e=>{const{t:r}=Fr(),{api:s}=zr(),[n,a]=t.useState([]),[i,o]=t.useState(!1),[c,l]=t.useState(null),{begin:u,settle:d}=Or(),p=t.useCallback(async()=>{if(!e)return u(),a([]),void o(!1);const t=u();o(!0),l(null);try{const r=await s.getCreditPackages(e);if(t.signal.aborted)return;a(r)}catch(s){if(t.signal.aborted)return;const n=$(s,"errors.fetchCreditPackages",r);l(n),L(s,{component:"useCreditPackages",action:"fetchPackages",metadata:{workspaceId:e}})}finally{d(t)&&o(!1)}},[s,e,u,d]);return t.useEffect(()=>{p()},[p]),{packages:n,loading:i,error:c,refetch:p}},ss=()=>{const{t:e}=Fr(),{os:r,api:s}=zr(),n=fe(r),[a,i]=t.useState([]),[o,c]=t.useState(),[l,u]=t.useState(!1),[d,p]=t.useState(null),{begin:m,settle:h}=Or(),g=t.useCallback(async()=>{if(!n)return m(),i([]),void u(!1);const t=m();u(!0),p(null);try{const e=await s.getPublicCreditPackages();if(t.signal.aborted)return;i(e.packages||[]),c(e.notes)}catch(r){if(t.signal.aborted)return;const s=$(r,"errors.fetchCreditPackages",e);p(s),L(r,{component:"usePublicCreditPackages",action:"fetchPackages"})}finally{h(t)&&u(!1)}},[s,n,m,h]);t.useEffect(()=>{g()},[g]);return{packages:a,notes:o,loading:!n||l,error:d,refetch:g}},ns=t.createContext(null);ns.displayName="CreditBalanceContext";const as=t.memo(function({children:r}){const s=Dr(e=>e.workspaces.currentWorkspace),{balance:n,loading:a,error:i,refetch:o}=Xr(s?._id);t.useEffect(()=>ke(o),[o]);const c=t.useMemo(()=>({balance:n,loading:a,error:i,refetch:o}),[n,a,i,o]);return e.jsx(ns.Provider,{value:c,children:r})});function is(){const e=t.useContext(ns);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}as.displayName="CreditBalanceContextProvider";const os=({message:t})=>e.jsxs(e.Fragment,{children:[e.jsx("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"}}),e.jsx("p",{"aria-hidden":"true",style:{marginTop:16,color:"hsl(var(--muted-foreground, 215.4 16.3% 46.9%))",fontSize:14},children:t}),e.jsx("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 "})]}),cs=({children:t,message:r,backgroundColor:s})=>{const{t:n}=Fr(),a=r??n("settings.common.loading");return e.jsxs("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:s??void 0},children:[e.jsx("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:a}),t??e.jsx(os,{message:a}),e.jsx("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 "})]})};cs.displayName="FullScreenLoader";const ls=t.createContext(null),us=({children:r,loadingComponent:s})=>{const[n,a]=t.useState({visible:!1,message:""}),i=t.useRef(null),o=t.useCallback(()=>{i.current&&(clearTimeout(i.current),i.current=null)},[]),c=t.useCallback(()=>{o(),a({visible:!1,message:""})},[o]),l=t.useCallback(e=>{o(),a({visible:!0,message:e}),i.current=setTimeout(()=>{L(new Error("FullScreenLoader timed out — auto-hiding after 60s"),{component:"FullScreenLoaderProvider",action:"timeout"}),a({visible:!1,message:""})},6e4)},[o]);t.useEffect(()=>()=>o(),[o]);const u=t.useMemo(()=>({show:l,hide:c,visible:n.visible,message:n.message}),[l,c,n.visible,n.message]),d="function"==typeof s?s({message:n.message}):s;return e.jsxs(ls.Provider,{value:u,children:[r,n.visible&&e.jsx(cs,{message:n.message,children:d})]})};function ds(){const e=t.useContext(ls);if(!e)throw new Error("useFullScreenLoader must be used within FullScreenLoaderProvider");return e}us.displayName="FullScreenLoaderProvider";const ps=t.createContext(null);function ms(e,t){return e?e.replace(/\{\{(\w+)\}\}/g,(e,r)=>r in t?t[r]:e):e}function hs(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"app"}function gs({mcp:r,children:s}){const n=t.useMemo(()=>r?.url?{...r,url:r.url.replace(/\/+$/,"")}:null,[r]);return e.jsx(ps.Provider,{value:n,children:s})}function fs(){return t.useContext(ps)}const ys=t.createContext({appPermissions:void 0});function bs({appPermissions:r,children:s}){const n=t.useMemo(()=>({appPermissions:r}),[r]);return e.jsx(ys.Provider,{value:n,children:s})}function xs(){return t.useContext(ys)}const ws=t.createContext(null);ws.displayName="QuotaUsageContext";const vs=t.memo(function({children:r}){const s=Dr(e=>e.workspaces.currentWorkspace),{quotas:n,loading:a,error:i,refetch:o}=Hr(s?._id);t.useEffect(()=>Ne(o),[o]);const c=t.useMemo(()=>({quotas:n,loading:a,error:i,refetch:o}),[n,a,i,o]);return e.jsx(ws.Provider,{value:c,children:r})});function ks(){const e=t.useContext(ws);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}vs.displayName="QuotaUsageContextProvider";const Ss=t.createContext({});function Cs({ui:r,children:s}){const n=t.useMemo(()=>r??{},[r]);return e.jsx(Ss.Provider,{value:n,children:s})}function Ns(){return t.useContext(Ss)}function Ps(e,t){if(!e||!t||"object"!=typeof e||"object"!=typeof t||Array.isArray(e)||Array.isArray(t))return t;const r={...e};for(const[e,s]of Object.entries(t))r[e]=e in r?Ps(r[e],s):s;return r}const Es="saas-oauth-state";function js(){z(Es)}const Is={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"},As=new Set(Object.values(Is));const Us=new class{constructor(){this.listeners=new Set,this.currentState={open:!1,section:Is.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||Is.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)})}},Ws=t.createContext(null);Ws.displayName="WorkspaceActionsContext";const Rs=({children:r})=>{const s=_r(),{os:n,api:a}=zr(),{settings:i}=qr(),{t:o}=Fr(),c=t.useRef(o);t.useEffect(()=>{c.current=o},[o]);const l=Dr(e=>e.workspaces),u=Dr(e=>e.auth.session?.user),d=t.useRef(!1),p=t.useRef(!1),m=t.useRef(0),h=t.useCallback((e,t)=>{if((!(e._id===l.currentWorkspace?._id)||t?.forceEmit)&&e){const t=l.currentWorkspace;ft(e),s.workspaces(ir(e)),xe.emitWorkspaceChanged(e,t).catch(t=>{L(t,{component:"WorkspaceProvider",action:"emitWorkspaceChanged",metadata:{workspaceId:e._id}})})}},[l.currentWorkspace,s]),g=t.useCallback(async(e,t)=>{const r=++m.current;s.workspaces(pr(e._id));try{const s=n.auth?.callbacks?.onWorkspaceChange;if(s){const t=vt(e,u?.id);try{await s({workspace:e,user:u??null,role:t})}catch(t){throw L(t,{component:"WorkspaceProvider",action:"onWorkspaceChange",metadata:{workspaceId:e._id}}),t}if(r!==m.current)return}h(e,t)}finally{r===m.current&&s.workspaces(pr(null))}},[s,n.auth?.callbacks?.onWorkspaceChange,h,u]),f=t.useRef(g);f.current=g,t.useEffect(()=>{if(!l.isInitialized){const e=yt();if(s.workspaces(cr(!0)),e){const t=l.workspaces.find(t=>t._id===e);t&&f.current(t,{forceEmit:!0}).catch(t=>{L(t,{component:"WorkspaceProvider",action:"initWorkspaceSwitch",metadata:{savedWorkspaceId:e}})})}}},[l.isInitialized,l.workspaces,s]);const y=t.useCallback(()=>{bt(),s.workspaces(or())},[s]),b=t.useCallback(async()=>{if(!l.loading&&!d.current){d.current=!0,s.workspaces(lr(!0)),s.workspaces(ur(null));try{const e=await a.getWorkspaces();if(s.workspaces(tr(e)),e.length>0){const t=yt();if(t&&xt(t,e)){const r=e.find(e=>e._id===t);if(r)try{await g(r,{forceEmit:!0})}catch{}}else{const t=e[0];try{await g(t,{forceEmit:!0})}catch{}}}}catch(e){s.workspaces(ur($(e,"errors.fetchWorkspaces",c.current)))}finally{s.workspaces(lr(!1)),d.current=!1}}},[a,l.loading,s,g]),x=t.useCallback(async()=>{if(!l.refreshing&&!d.current){d.current=!0,s.workspaces(dr(!0));try{const e=await a.getWorkspaces();s.workspaces(tr(e))}catch(e){}finally{s.workspaces(dr(!1)),d.current=!1}}},[a,l.refreshing,s]),w=t.useRef(null);t.useEffect(()=>()=>{w.current&&clearTimeout(w.current)},[]);const v=t.useCallback(async(e,t)=>{const r=await a.createWorkspace({name:e,image:t});s.workspaces(rr(r)),await g(r),xe.emitWorkspaceCreated(r).catch(e=>{L(e,{component:"WorkspaceProvider",action:"emitWorkspaceCreated",metadata:{workspaceId:r._id}})}),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{w.current=null,Us.openWorkspaceSettings(Is.Subscription)},300)},[a,s,g]),k=t.useCallback(async(e,t)=>{const r=await a.updateWorkspace(e._id,t);s.workspaces(sr(r)),xe.emitWorkspaceUpdated(r).catch(e=>{L(e,{component:"WorkspaceProvider",action:"emitWorkspaceUpdated",metadata:{workspaceId:r._id}})})},[a,s]),S=t.useCallback(async()=>{if(p.current)return l.allFeatures.length>0?l.allFeatures:null;if(l.allFeatures.length>0)return l.allFeatures;p.current=!0;try{const e=await a.getFeatures();return s.workspaces(ar(e)),e}catch(e){return L(e,{component:"WorkspaceProvider",action:"getFeatures"}),null}finally{p.current=!1}},[a,s,l.allFeatures]),C=t.useCallback(async(e,t,r)=>await a.updateFeature(e,t,r),[a]),N=t.useCallback(async e=>a.updateSettings(e),[a]),P=t.useCallback(async(e,t)=>{const r=await a.updateWorkspacePermissions(e,t);return await x(),r},[a,x]);t.useEffect(()=>{if(!l.currentWorkspace?._id||0===l.workspaces.length)return;const e=l.currentWorkspace._id,t=l.workspaces.find(t=>t._id===e);if(t)t!==l.currentWorkspace&&(ft(t),s.workspaces(ir(t)));else if(l.workspaces.length>0){const t=l.workspaces[0];t._id!==e&&g(t).catch(e=>{L(e,{component:"WorkspaceProvider",action:"fallbackWorkspaceSwitch",metadata:{workspaceId:t._id}})})}},[l.workspaces,l.currentWorkspace,s,g]);const E=t.useCallback(async e=>await a.getWorkspaceUsers(e),[a]),j=t.useCallback(async(e,t,r)=>{const s=l.workspaces.find(t=>t._id===e);if(s){const e=mt({settingsMaxUsers:i?.workspace?.maxWorkspaceUsers}),t=ht({memberCount:s.users?.length??0,maxUsersConfig:e});if(!t.canInvite)throw new Error(t.blockMessageKey||"users.memberLimitReached")}const n=await a.addUser(e,{email:t,role:r});return s&&xe.emitWorkspaceUserAdded(n.userId,s,r).catch(t=>{L(t,{component:"WorkspaceProvider",action:"emitWorkspaceUserAdded",metadata:{workspaceId:e,userId:n.userId,role:r}})}),x().catch(e=>{L(e,{component:"WorkspaceProvider",action:"refreshAfterAddUser"})}),Ie(),n},[a,l.workspaces,x,i]),I=t.useCallback(async(e,t)=>{const r=l.workspaces.find(t=>t._id===e);if(r&&wt(r,t))throw new Error("Cannot remove the workspace owner");const s=(await a.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===t),n=await a.removeUser(e,t);if(r&&s){const t=s.role;xe.emitWorkspaceUserRemoved(n.userId,r,t).catch(r=>{L(r,{component:"WorkspaceProvider",action:"emitWorkspaceUserRemoved",metadata:{workspaceId:e,userId:n.userId,role:t}})})}return x().catch(e=>{L(e,{component:"WorkspaceProvider",action:"refreshAfterRemoveUser"})}),Ie(),n},[a,l.workspaces,x]),A=t.useCallback(async(e,t,r)=>{if(r.role){const r=l.workspaces.find(t=>t._id===e);if(r&&wt(r,t))throw new Error("Cannot change the role of the workspace owner")}let s;if(r.role){const r=(await a.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===t);s=r?.role}const n=await a.updateUser(e,t,r);return r.role&&s&&s!==r.role&&xe.emitWorkspaceUserRoleChanged(n.userId,n.workspace,s,r.role).catch(n=>{L(n,{component:"WorkspaceProvider",action:"emitWorkspaceUserRoleChanged",metadata:{workspaceId:e,userId:t,previousRole:s,newRole:r.role}})}),n},[a,l.workspaces]),U=t.useCallback(async e=>{const t=await a.getProfile().catch(()=>null),r=await a.updateUserProfile(e);return xe.emitUserUpdated(r,t||void 0).catch(e=>{L(e,{component:"WorkspaceProvider",action:"emitUserUpdated",metadata:{userId:r._id}})}),r},[a]),W=t.useCallback(async()=>await a.getProfile(),[a]),R=t.useCallback(async e=>await a.getWorkspace(e),[a]),T=t.useCallback(async e=>{if(!u)throw new Error("User must be authenticated to delete a workspace");const t=l.workspaces.find(t=>t._id===e);if(!t)throw new Error("Workspace not found");if(!wt(t,u.id))throw new Error("Only the workspace creator can delete the workspace");const r=await a.deleteWorkspace(e);return s.workspaces(nr(e)),l.currentWorkspace?._id===e&&(bt(),s.workspaces(or())),t&&xe.emitWorkspaceDeleted(t).catch(t=>{L(t,{component:"WorkspaceProvider",action:"emitWorkspaceDeleted",metadata:{workspaceId:e}})}),r},[a,l.workspaces,l.currentWorkspace,s,u]),F=t.useMemo(()=>({fetchWorkspaces:b,refreshWorkspaces:x,setCurrentWorkspace:h,switchToWorkspace:g,resetCurrentWorkspace:y,createWorkspace:v,updateWorkspace:k,deleteWorkspace:T,getWorkspace:R,getUsers:E,addUser:j,removeUser:I,updateUser:A,getProfile:W,updateUserProfile:U,getFeatures:S,updateFeature:C,updateWorkspaceSettings:N,updateWorkspacePermissions:P}),[b,x,h,g,y,v,k,T,R,E,j,I,A,W,U,S,C,N,P]);return e.jsx(Ws.Provider,{value:F,children:r})};Rs.displayName="WorkspaceProviderInner";const Ts=({children:r})=>t.useContext(Ws)?e.jsx(e.Fragment,{children:r}):e.jsx(Rs,{children:r});Ts.displayName="WorkspaceProvider";const Fs=()=>{const e=t.useContext(Ws);if(!e)throw new Error("useSaaSWorkspaces must be used within a WorkspaceProvider. Make sure SaaSOSProvider is wrapping your application.");const r=Dr(e=>e.workspaces);return t.useMemo(()=>({workspaces:r.workspaces,loading:r.loading,error:r.error,refreshing:r.refreshing,currentWorkspace:r.currentWorkspace,allFeatures:r.allFeatures,switching:null!==r.switchingToId,switchingToId:r.switchingToId,...e}),[r,e])};function Os(e,t,r){const s=e._id||e.id;if(!s||"string"!=typeof s)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");return{id:s,name:e.name||"",org:t,email:e.email,emailVerified:!1!==e.emailVerified,clientId:r,role:e.role||"",image:e.image}}function _s(e,t){return{user:e,sessionId:t,expires:new Date(Date.now()+864e5).toISOString()}}function Ds(){return Dr(e=>e.auth)}function Ls(){const{t:e}=Fr(),r=_r(),s=Ds(),n=Mr(),{serverUrl:a,orgId:i,auth:o}=n,{resetCurrentWorkspace:c,currentWorkspace:l}=Fs(),u=ds(),d=t.useMemo(()=>new ie({serverUrl:a,version:n.version}),[a,n.version]),p=t.useCallback(async t=>{Be(t||window.location.href),r.auth(At()),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 q(Es,t),t}(),{redirectUrl:t}=await d.requestAuth({orgId:i,clientId:o?.clientId??"",redirect:{success:o?.redirectUrl||window.location.href,error:o?.redirectUrl||window.location.href},state:e});Le(t)}catch(e){throw u.hide(),r.auth(Wt()),L(e,{component:"useSaaSAuth",action:"signIn"}),e}},[d,i,o,r,u,e]),m=t.useCallback(async()=>{try{o?.callbacks?.onSignOut&&"function"==typeof o.callbacks.onSignOut&&await o.callbacks.onSignOut()}catch(e){L(e,{component:"useSaaSAuth",action:"signOut"})}finally{Y(),r.auth(Tt()),c()}},[r,c,o?.callbacks?.onSignOut]),h=t.useCallback(e=>{l?Us.openWorkspaceSettings(e):L(new Error("Cannot open settings: No current workspace"),{component:"useSaaSAuth",action:"openWorkspaceSettings"})},[l]),g=t.useCallback(()=>{l?Us.openWorkspaceSettings(Is.Credits,{action:Ue.OpenCreditStore}):L(new Error("Cannot open credit store: No current workspace"),{component:"useSaaSAuth",action:"openCreditStore"})},[l]),f=t.useCallback(()=>{l?Us.openWorkspaceSettings(Is.Subscription,{action:Ue.SelectPlan}):L(new Error("Cannot open plan picker: No current workspace"),{component:"useSaaSAuth",action:"openPlanPicker"})},[l]),y=t.useMemo(()=>jt(s.status),[s.status]);return t.useMemo(()=>({user:s.session?.user,session:s.session,status:s.status,...y,signIn:p,signOut:m,openWorkspaceSettings:h,openCreditStore:g,openPlanPicker:f}),[s.session,s.status,y,p,m,h,g,f])}const Ms=t.memo(({children:r,callbacks:s})=>{const{t:n}=Fr(),a=_r(),i=Ds(),o=Mr(),c=jt(i.status).isAuthenticated,l=ds(),u=t.useRef(!1),d=t.useRef(null),p=t.useRef(!1),m=t.useRef(null),h=t.useCallback(async e=>{try{if(s?.handleAuthentication){l.show(n("loading.signingIn"));const{sessionId:t}=await s.handleAuthentication(e);if(!t||"string"!=typeof t||""===t.trim())throw new Error("Invalid sessionId received from authentication callback");const r=o;if(!fe(r))throw new Error("OS configuration is not available");const{serverUrl:i,version:c,orgId:u}=r;l.show(n("loading.verifyingAccount"));const d=new ie({serverUrl:i,version:c}),p=await d.getProfile(t),m=_s(Os(p,u,r.auth?.clientId||""),t);l.show(n("loading.almostThere")),H(m.sessionId),d.getDeviceToken(m.sessionId).then(e=>e&&Z(e)).catch(()=>{}),a.auth(Rt(m)),te();const h=qe();h&&h!==window.location.href&&Le(h),l.hide()}}catch(t){throw l.hide(),qe(),L(t,{component:"AuthProviderWrapper",action:"handleAuthRedirect",metadata:{hasCode:!!e}}),a.auth(Wt()),t}},[a,s,o,l,n]);return t.useEffect(()=>{if("undefined"==typeof window)return;if(c)return;if(p.current)return;if(m.current)return;if(!fe(o))return;if(ee())return;if(!s?.getSession)return p.current=!0,void a.auth(Wt());const e=s.getSession,{serverUrl:t,version:r,orgId:i}=o,u=o.auth?.clientId||"";m.current=(async()=>{l.show(n("loading.restoringSession"));let o=null;try{o=await e()}catch(e){L(e,{component:"AuthProviderWrapper",action:"getSession"})}if(!o)return p.current=!0,a.auth(Wt()),l.hide(),"undefined"!=typeof window&&Be(window.location.href),void s?.onSessionExpired?.("missing");try{l.show(n("loading.verifyingAccount"));const e=new ie({serverUrl:t,version:r}),s=await e.getProfile(o),c=_s(Os(s,i,u),o);H(c.sessionId),e.getDeviceToken(c.sessionId).then(e=>e&&Z(e)).catch(()=>{}),p.current=!0,a.auth(Rt(c)),l.hide();const d=qe();d&&d!==window.location.href&&Le(d)}catch(e){L(e,{component:"AuthProviderWrapper",action:"fetchUserProfile"}),p.current=!0,a.auth(Wt()),l.hide(),"undefined"!=typeof window&&Be(window.location.href),s?.onSessionExpired?.("expired")}finally{m.current=null}})()},[c,a,o,s]),t.useEffect(()=>{const e=ee();if(!e)return;if(u.current||d.current===e)return;if(!fe(o))return;const t=function(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get(K)}catch(e){return L(e,{component:"auth-utils",action:"getStateFromUrl",metadata:{param:K}}),null}}();if(t&&!function(e){if(!e)return!1;const t=B(Es);if(z(Es),!t)return!1;if(t.length!==e.length)return!1;let r=0;for(let s=0;s<t.length;s++)r|=t.charCodeAt(s)^e.charCodeAt(s);return 0===r}(t))return js(),te(),L(new Error("OAuth state mismatch — possible CSRF attack"),{component:"AuthProviderWrapper",action:"validateOAuthState"}),void a.auth(Wt());js(),u.current=!0,d.current=e;let r=!1;return a.auth(Ut()),h(e).then(()=>{r||(d.current=null)}).catch(e=>{r||(L(e,{component:"AuthProviderWrapper",action:"handleAuthRedirectEffect",metadata:{hasCode:!0}}),te(),d.current=null)}).finally(()=>{u.current=!1}),()=>{r=!0}},[h,o.serverUrl,o.version,o.orgId]),e.jsx(e.Fragment,{children:r})});Ms.displayName="AuthProviderWrapper";const $s=t.memo(({config:r,auth:s,children:n})=>{const a=_r();Mr();const i=t.useMemo(()=>({clientId:s?.clientId||"",redirectUrl:s?.redirectUrl||"",callbacks:s?.callbacks}),[s?.clientId,s?.redirectUrl,s?.callbacks]);return t.useEffect(()=>{a.os(Vt({...r,auth:i}))},[r,i,a]),e.jsx(e.Fragment,{children:n})});$s.displayName="ContextConfigProvider";const Bs=t.createContext({container:null,setContainer:()=>{}}),qs=t.memo(({children:r})=>{const[s,n]=t.useState(null),a=t.useMemo(()=>({container:s,setContainer:n}),[s]);return e.jsxs(Bs.Provider,{value:a,children:[r,e.jsx("div",{ref:n,id:"saas-os-portal",className:"saas-os-ui",style:{width:"100%",height:"100%"}})]})});qs.displayName="PortalProvider";const zs=t.createContext(null);function Vs(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),s=new Uint8Array(r.length);for(let e=0;e<r.length;e++)s[e]=r.charCodeAt(e);return s}const Gs=t.memo(function({children:r,serviceWorkerPath:s="/push-sw.js",autoSubscribe:n=!1}){const{t:a}=Fr(),i=Mr(),{isAuthenticated:o}=Ls(),c=t.useMemo(()=>"undefined"!=typeof window&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window,[]),l=t.useMemo(()=>new de({serverUrl:i.serverUrl,version:i.version,orgId:i.orgId}),[i.serverUrl,i.version,i.orgId]),[u,d]=t.useState({permission:c?Notification.permission:"default",isSubscribed:!1,isSupported:c,loading:!1,error:null});t.useEffect(()=>{if(!o||!c)return;let e=!1;return(async()=>{try{const t=await navigator.serviceWorker.getRegistration(s);if(e)return;if(!t)return void d(e=>({...e,isSubscribed:!1}));const r=await t.pushManager.getSubscription();if(e)return;d(e=>({...e,isSubscribed:!!r,permission:Notification.permission}))}catch{e||d(e=>({...e,isSubscribed:!1}))}})(),()=>{e=!0}},[o,c,s]);const p=t.useCallback(async()=>{if(!c)return!1;const e=await Notification.requestPermission();return d(t=>({...t,permission:e})),"granted"===e},[c]),m=t.useCallback(async()=>{if(c&&o){d(e=>({...e,loading:!0,error:null}));try{if(!await p())return void d(e=>({...e,loading:!1,error:a("notifications.permissionDenied")}));const{publicKey:e}=await l.getVapidPublicKey(),t=await navigator.serviceWorker.register(s);await navigator.serviceWorker.ready;const r=(await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Vs(e)})).toJSON();await l.subscribe({endpoint:r.endpoint,keys:{p256dh:r.keys.p256dh,auth:r.keys.auth}},navigator.userAgent),d(e=>({...e,isSubscribed:!0,loading:!1}))}catch(e){const t=e instanceof Error?e.message:a("push.failedToSubscribe");d(e=>({...e,loading:!1,error:t})),L(e,{component:"PushNotificationProvider",action:"subscribe"})}}},[c,o,l,s,p]),h=t.useCallback(async()=>{if(c){d(e=>({...e,loading:!0,error:null}));try{const e=await navigator.serviceWorker.getRegistration(s);if(e){const t=await e.pushManager.getSubscription();if(t){const e=t.endpoint;await t.unsubscribe(),await l.unsubscribe(e)}}d(e=>({...e,isSubscribed:!1,loading:!1}))}catch(e){const t=e instanceof Error?e.message:a("push.failedToUnsubscribe");d(e=>({...e,loading:!1,error:t})),L(e,{component:"PushNotificationProvider",action:"unsubscribe"})}}},[c,l,s]),g=t.useMemo(()=>({...u,requestPermission:p,subscribe:m,unsubscribe:h}),[u,p,m,h]);return e.jsx(zs.Provider,{value:g,children:r})});const Js=t.createContext(void 0),Ks=t.memo(({children:r})=>{const{t:s}=Fr(),n=Mr(),a=function(){const e=Mr();return t.useMemo(()=>new he(e),[e.serverUrl,e.version])}(),{isAuthenticated:i}=Ls(),{serverUrl:o,version:c}=n,[l,u]=t.useState({}),[d,p]=t.useState({}),[m,h]=t.useState(!1),[g,f]=t.useState(!1),[y,b]=t.useState(null),[x,w]=t.useState(null),v=t.useCallback(async e=>{if(o&&c&&i){b(null);try{const t=await a.getAttributes(e);u(t)}catch(e){if(T(e))return;const t=e instanceof Error?e:new Error(s("errors.generic"));b(t),L(e,{component:"UserProvider",action:"fetchAttributes"})}}else u({})},[a,o,c,i,s]),k=t.useCallback(async()=>{if(o&&c&&i){h(!0);try{await v()}finally{h(!1)}}},[o,c,i,v]),S=t.useCallback(async e=>{h(!0),b(null);try{const t=await a.updateAttributes(e);return await v(),t}catch(t){const r=t instanceof Error?t:new Error(s("errors.generic"));throw b(r),L(t,{component:"UserProvider",action:"updateAttributes",metadata:{updates:e}}),t}finally{h(!1)}},[a,v,s]),C=t.useCallback(async(e,t)=>{h(!0),b(null);try{const r=await a.updateAttribute(e,t);return await v(),r}catch(r){const n=r instanceof Error?r:new Error(s("errors.generic"));throw b(n),L(r,{component:"UserProvider",action:"updateAttribute",metadata:{attributeKey:e,value:t}}),r}finally{h(!1)}},[a,v,s]),N=t.useCallback(async e=>{if(o&&c&&i){w(null);try{const t=await a.getFeatures(e);p(t)}catch(e){if(T(e))return;const t=e instanceof Error?e:new Error(s("errors.generic"));w(t),L(e,{component:"UserProvider",action:"fetchFeatures"})}}else p({})},[a,o,c,i,s]),P=t.useCallback(async()=>{if(o&&c&&i){f(!0);try{await N()}finally{f(!1)}}},[o,c,i,N]);Lr(async e=>{if(!i||!o||!c)return u({}),void p({});h(!0),f(!0),await Promise.all([v(e).finally(()=>h(!1)),N(e).finally(()=>f(!1))])},[i,o,c,v,N],{onError:e=>L(e,{component:"UserProvider",action:"initialFetch",metadata:{step:"fetchAttributesAndFeatures"}})});const E=t.useMemo(()=>({attributes:l,features:d,isLoading:m||g,error:y??x,attributesLoading:m,featuresLoading:g,attributesError:y,featuresError:x,updateAttributes:S,updateAttribute:C,refreshAttributes:k,refreshFeatures:P}),[l,d,m,g,y,x,S,C,k,P]);return e.jsx(Js.Provider,{value:E,children:r})});Ks.displayName="UserProvider";const Hs=c.cva("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"}}),Ys=v.forwardRef(({className:t,variant:r,progress:s,size:n,startIcon:a,endIcon:i,asChild:c=!1,...u},d)=>{const p=c?o.Slot:"button",m=function(e){switch(e){case"lg":return 20;case"sm":return 14;default:return 16}}(n);return e.jsxs(p,{disabled:s||u.disabled,className:A(Hs({variant:r,size:n,withIcon:null!=s||null!=a||null!=i,className:t})),ref:d,...u,children:[s&&e.jsx(l.Loader2,{size:m,className:"animate-spin"}),a&&v.cloneElement(a,{size:m}),u.children,i&&v.cloneElement(i,{size:m})]})});Ys.displayName="Button";const Qs=C.Root,Zs=C.Trigger,Xs=C.Portal,en=v.forwardRef(({className:t,...r},s)=>e.jsx(C.Overlay,{ref:s,className:A("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",t),...r}));en.displayName=C.Overlay.displayName;const tn=v.forwardRef(({className:t,children:r,...s},n)=>{const{container:a}=v.useContext(Bs),{t:i}=Fr();return e.jsxs(Xs,{container:a,children:[e.jsx(en,{}),e.jsxs(C.Content,{ref:n,className:A("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",t),...s,children:[r,e.jsxs(C.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:[e.jsx(h.Cross2Icon,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:i("settings.common.close")})]})]})]})});tn.displayName=C.Content.displayName;const rn=({className:t,...r})=>e.jsx("div",{className:A("flex flex-col space-y-1.5 text-center sm:text-start",t),...r});rn.displayName="DialogHeader";const sn=v.forwardRef(({className:t,...r},s)=>e.jsx(C.Title,{ref:s,className:A("text-lg font-semibold leading-none tracking-tight",t),...r}));sn.displayName=C.Title.displayName;const nn=v.forwardRef(({className:t,...r},s)=>e.jsx(C.Description,{ref:s,className:A("text-sm text-muted-foreground",t),...r}));function an(e){const{user:r}=Ls(),{currentWorkspace:s}=Fs(),{settings:n}=qr(),{appPermissions:a}=xs(),i=e??s??null,o=r?.id??null,c=t.useMemo(()=>i?vt(i,o):null,[i,o]),l=t.useMemo(()=>!!i&&wt(i,o),[i,o]),u=t.useMemo(()=>Pt({userId:o,workspaceRole:c,workspace:i,settings:n,appPermissions:a}),[o,c,i,n,a]);return{can:t.useCallback(e=>Array.isArray(e)?e.every(e=>u.has(e)):u.has(e),[u]),permissions:u,isOwner:l,role:c}}function on(){const e=Ns(),{can:r}=an();return{visible:t.useCallback((t,s)=>!1!==t(e)&&(void 0===s||r(s)),[e,r]),ui:e}}function cn(){const e=Mr();return t.useMemo(()=>new le(e),[e.serverUrl,e.version])}function ln(){const e=cn(),{t:r}=Fr(),[s,n]=t.useState([]),[a,i]=t.useState(!0),[o,c]=t.useState(null),[l,u]=t.useState(null),d=t.useRef(null),p=t.useRef(r);t.useEffect(()=>{p.current=r},[r]);const m=t.useCallback(async()=>{d.current?.abort();const t=new AbortController;d.current=t,i(!0),c(null);try{const r=await e.list(t.signal);t.signal.aborted||n(r)}catch(e){if(t.signal.aborted)return;M(e,{component:"useConnectedAgents",action:"list"}),c($(e,"security.connectedAgentsLoadFailed",p.current))}finally{d.current===t&&(d.current=null,i(!1))}},[e]);t.useEffect(()=>(m(),()=>d.current?.abort()),[m]);const h=t.useCallback(async t=>{u(t),c(null);try{await e.revoke(t),n(e=>e.filter(e=>e.clientId!==t))}catch(e){M(e,{component:"useConnectedAgents",action:"revoke"}),c($(e,"security.connectedAgentsRevokeFailed",p.current))}finally{u(null)}},[e]);return t.useMemo(()=>({agents:s,loading:a,error:o,revoking:l,refresh:m,revoke:h}),[s,a,o,l,m,h])}function un(e,t="en-US",r){try{const s=new Date(e);return isNaN(s.getTime())?"":new Intl.DateTimeFormat(t,r??{month:"short",day:"numeric",year:"numeric"}).format(s)}catch{return""}}function dn({icon:t,title:r,description:s,action:n,className:a}){return e.jsxs("div",{className:A("flex flex-col items-center gap-2 rounded-md border border-dashed p-6 text-center",a),children:[t&&e.jsx("span",{"aria-hidden":"true",children:t}),r&&e.jsx("p",{className:"text-sm font-medium",children:r}),s&&e.jsx("p",{className:"text-sm text-muted-foreground",children:s}),n]})}function pn({title:t,description:r,actions:s,className:n,titleClassName:a}){return t||r||s?e.jsxs("div",{className:A(n),children:[(t||s)&&e.jsxs("div",{className:A("flex items-center gap-2",t?"justify-between":"justify-end"),children:[t&&e.jsx("h3",{className:A("text-sm font-medium",a),children:t}),s]}),r&&e.jsx("p",{className:"text-sm text-muted-foreground",children:r})]}):null}function mn({className:t,...r}){return e.jsx("div",{className:A("animate-pulse rounded-md bg-primary/10",t),...r})}nn.displayName=C.Description.displayName;const hn=j.Root,gn=v.forwardRef(({className:t,...r},s)=>e.jsx(j.Item,{ref:s,className:A("border-b last:border-b-0",t),...r}));gn.displayName="AccordionItem";const fn=v.forwardRef(({className:t,children:r,...s},n)=>e.jsx(j.Header,{className:"flex",children:e.jsxs(j.Trigger,{ref:n,className:A("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",t),...s,children:[e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200","aria-hidden":"true"}),e.jsx("span",{className:"min-w-0 flex-1",children:r})]})}));fn.displayName="AccordionTrigger";const yn=v.forwardRef(({className:t,children:r,...s},n)=>e.jsx(j.Content,{ref:n,className:"overflow-hidden text-sm data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...s,children:e.jsx("div",{className:A("pb-3 pt-0",t),children:r})}));function bn({value:t,displayValue:r,copyLabel:s,copiedLabel:n,variant:a="inline",className:i}){const o=r??t,[c,u]=v.useState(!1),d=v.useRef(null);v.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const p=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 r=document.execCommand("copy");return document.body.removeChild(t),r}catch{return!1}}(t)&&(u(!0),d.current&&clearTimeout(d.current),d.current=setTimeout(()=>u(!1),2e3))},m=t=>e.jsxs(Ys,{type:"button",variant:"ghost",size:"sm",onClick:p,"aria-label":c?n:s,className:"h-7 shrink-0 gap-1.5 px-2",children:[c?e.jsx(l.Check,{className:"h-3.5 w-3.5","aria-hidden":"true"}):e.jsx(l.Copy,{className:"h-3.5 w-3.5","aria-hidden":"true"}),e.jsx("span",{className:A("text-xs",t&&"hidden sm:inline"),children:c?n:s})]});return"inline"===a?e.jsxs("div",{dir:"ltr",className:A("flex items-center gap-2 rounded-md border bg-muted/40 py-1 ps-3 pe-1",i),children:[e.jsx("code",{className:"min-w-0 flex-1 truncate text-xs",title:t,children:o}),m(!0)]}):e.jsxs("div",{dir:"code"===a?"ltr":void 0,className:A("overflow-hidden rounded-md border bg-muted/40",i),children:[e.jsx("div",{className:"flex justify-end border-b bg-muted/30 px-1.5 py-1",children:m(!1)}),"code"===a?e.jsx("pre",{className:"overflow-x-auto p-3 text-start text-xs leading-relaxed",children:e.jsx("code",{children:o})}):e.jsx("p",{className:"p-3 text-sm leading-relaxed",children:o})]})}function xn({config:t,title:r,description:s,className:n}){const{t:a}=Fr(),i=fs(),o=t??i;if(!o?.url)return null;const c=o.name?.trim()||"app",u={url:o.url,name:c,key:hs(c)},d=(e,t,r,s)=>({id:e,name:t,instructions:a("security.mcpAddToConfigFile",{path:`⁦${r}⁩`}),snippet:s}),p=[{id:"chatgpt",name:"ChatGPT",instructions:a("security.mcpClientChatgptInstructions")},{id:"claude",name:"Claude",instructions:a("security.mcpClientClaudeInstructions")},d("cursor","Cursor","~/.cursor/mcp.json",'{\n "mcpServers": {\n "{{key}}": {\n "url": "{{url}}"\n }\n }\n}'),d("vscode","VS Code",".vscode/mcp.json",'{\n "servers": {\n "{{key}}": {\n "type": "http",\n "url": "{{url}}"\n }\n }\n}'),d("windsurf","Windsurf","~/.codeium/windsurf/mcp_config.json",'{\n "mcpServers": {\n "{{key}}": {\n "serverUrl": "{{url}}"\n }\n }\n}'),{id:"cline",name:"Cline",instructions:a("security.mcpClientClineInstructions")}],m=o.clients??p,h=void 0===r?a("security.mcpGuideTitle"):r,g=void 0===s?a("security.mcpGuideDescription"):s,f=a("security.mcpCopy"),y=a("security.mcpCopied"),b=!1===o.prompt?null:o.prompt??a("security.mcpPromptTemplate"),x=ms(b??void 0,u),w=ms(b??void 0,{...u,url:`⁦${u.url}⁩`,name:`⁨${u.name}⁩`});return e.jsxs("div",{className:A("space-y-5",n),children:[e.jsx(pn,{title:h,description:g}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-sm font-medium",children:a("security.mcpServerUrlLabel")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:a("security.mcpServerUrlHint")}),e.jsx(bn,{value:o.url,copyLabel:f,copiedLabel:y})]}),x&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-sm font-medium",children:a("security.mcpPromptLabel")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:a("security.mcpPromptHint")}),e.jsx(bn,{value:x,displayValue:w,copyLabel:f,copiedLabel:y,variant:"text"})]}),m.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-sm font-medium",children:a("security.mcpClientsLabel")}),e.jsx(hn,{type:"single",collapsible:!0,defaultValue:m[0]?.id,className:"rounded-md border px-3",children:m.map(t=>{const r=ms(t.instructions,u),s=ms(t.snippet,u);return e.jsxs(gn,{value:t.id,children:[e.jsx(fn,{children:t.name}),e.jsx(yn,{children:e.jsxs("div",{className:"space-y-2",children:[r&&e.jsx("p",{className:"text-sm text-muted-foreground",children:r}),s&&e.jsx(bn,{value:s,copyLabel:f,copiedLabel:y,variant:"code"}),t.actionUrl&&e.jsxs("a",{href:t.actionUrl,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary hover:underline",children:[t.actionLabel??t.actionUrl,e.jsx(l.ExternalLink,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})})]},t.id)})})]}),o.docsUrl&&e.jsxs("a",{href:o.docsUrl,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary hover:underline",children:[a("security.mcpLearnMore"),e.jsx(l.ExternalLink,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})}yn.displayName="AccordionContent";const wn={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"}};const vn=I.Root,kn=I.Trigger,Sn=I.Portal,Cn=v.forwardRef(({className:t,...r},s)=>e.jsx(I.Overlay,{className:A("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",t),...r,ref:s}));Cn.displayName=I.Overlay.displayName;const Nn=v.forwardRef(({className:t,...r},s)=>{const{container:n}=v.useContext(Bs);return e.jsxs(Sn,{container:n,children:[e.jsx(Cn,{}),e.jsx(I.Content,{ref:s,className:A("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",t),...r})]})});Nn.displayName=I.Content.displayName;const Pn=({className:t,...r})=>e.jsx("div",{className:A("flex flex-col space-y-2 text-center sm:text-start",t),...r});Pn.displayName="AlertDialogHeader";const En=({className:t,...r})=>e.jsx("div",{className:A("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...r});En.displayName="AlertDialogFooter";const jn=v.forwardRef(({className:t,...r},s)=>e.jsx(I.Title,{ref:s,className:A("text-lg font-semibold",t),...r}));jn.displayName=I.Title.displayName;const In=v.forwardRef(({className:t,...r},s)=>e.jsx(I.Description,{ref:s,className:A("text-sm text-muted-foreground",t),...r}));In.displayName=I.Description.displayName;const An=v.forwardRef(({className:t,...r},s)=>e.jsx(I.Action,{ref:s,className:A(Hs(),t),...r}));An.displayName=I.Action.displayName;const Un=v.forwardRef(({className:t,...r},s)=>e.jsx(I.Cancel,{ref:s,className:A(Hs({variant:"outline"}),"mt-2 sm:mt-0",t),...r}));function Wn(){const e=Mr();return t.useMemo(()=>new ue(e),[e.serverUrl,e.version])}function Rn(){const e=Wn(),{t:r}=Fr(),[s,n]=t.useState([]),[a,i]=t.useState(!0),[o,c]=t.useState(null),[l,u]=t.useState(null),d=t.useRef(null),p=t.useRef(r);t.useEffect(()=>{p.current=r},[r]);const m=t.useCallback(async()=>{d.current?.abort();const t=new AbortController;d.current=t,i(!0),c(null);try{const r=await e.list(t.signal);t.signal.aborted||n(r)}catch(e){if(t.signal.aborted)return;M(e,{component:"useDevices",action:"list"}),c($(e,"security.devicesLoadFailed",p.current))}finally{d.current===t&&(d.current=null,i(!1))}},[e]);t.useEffect(()=>(m(),()=>d.current?.abort()),[m]);const h=t.useCallback(async(t,r)=>{u(t),c(null);try{await e.rename(t,r),n(e=>e.map(e=>e.deviceId===t?{...e,name:r}:e))}catch(e){M(e,{component:"useDevices",action:"rename"}),c($(e,"security.deviceRenameFailed",p.current))}finally{u(null)}},[e]),g=t.useCallback(async t=>{u(t),c(null);try{await e.signOut(t),n(e=>e.map(e=>e.deviceId===t?{...e,activeSessions:0}:e))}catch(e){M(e,{component:"useDevices",action:"signOut"}),c($(e,"security.deviceSignOutFailed",p.current))}finally{u(null)}},[e]),f=t.useCallback(async t=>{u(t),c(null);try{await e.forget(t),n(e=>e.filter(e=>e.deviceId!==t))}catch(e){M(e,{component:"useDevices",action:"forget"}),c($(e,"security.deviceForgetFailed",p.current))}finally{u(null)}},[e]);return t.useMemo(()=>({devices:s,loading:a,error:o,busyId:l,refresh:m,rename:h,signOut:g,forget:f}),[s,a,o,l,m,h,g,f])}function Tn(e){return!!e&&/Mobi|Android|iPhone|iPad|iPod|Windows Phone/i.test(e)}function Fn(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 On(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":""),Fn(e)].filter(Boolean).join(" · "):"";var t}Un.displayName=I.Cancel.displayName;const _n=v.forwardRef(({className:t,type:r,...s},n)=>e.jsx("input",{type:r,className:A("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",t),ref:n,...s}));function Dn(){const e=Mr();return t.useMemo(()=>new pe(e),[e.serverUrl,e.version])}function Ln(){const e=Dn(),{t:r}=Fr(),[s,n]=t.useState([]),[a,i]=t.useState(!0),[o,c]=t.useState(null),[l,u]=t.useState(null),d=t.useRef(null),p=t.useRef(r);t.useEffect(()=>{p.current=r},[r]);const m=t.useCallback(async()=>{d.current?.abort();const t=new AbortController;d.current=t,i(!0),c(null);try{const r=await e.list(t.signal);t.signal.aborted||n(r)}catch(e){if(t.signal.aborted)return;M(e,{component:"useSessions",action:"list"}),c($(e,"security.sessionsLoadFailed",p.current))}finally{d.current===t&&(d.current=null,i(!1))}},[e]);t.useEffect(()=>(m(),()=>d.current?.abort()),[m]);const h=t.useCallback(async t=>{u(t),c(null);try{await e.revoke(t),n(e=>e.filter(e=>e.id!==t))}catch(e){M(e,{component:"useSessions",action:"revoke"}),c($(e,"security.sessionSignOutFailed",p.current))}finally{u(null)}},[e]);return t.useMemo(()=>({sessions:s,loading:a,error:o,revoking:l,refresh:m,revoke:h}),[s,a,o,l,m,h])}_n.displayName="Input";const Mn=c.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),$n=v.forwardRef(({className:t,...r},s)=>e.jsx(k.Root,{ref:s,className:A(Mn(),t),...r}));$n.displayName=k.Root.displayName;const Bn=i.FormProvider,qn=v.createContext({}),zn=({...t})=>e.jsx(qn.Provider,{value:{name:t.name},children:e.jsx(i.Controller,{...t})}),Vn=()=>{const e=v.useContext(qn),t=v.useContext(Gn),{getFieldState:r,formState:s}=i.useFormContext(),n=r(e.name,s);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:a}=t;return{id:a,name:e.name,formItemId:`${a}-form-item`,formDescriptionId:`${a}-form-item-description`,formMessageId:`${a}-form-item-message`,...n}},Gn=v.createContext({}),Jn=v.forwardRef(({className:t,...r},s)=>{const n=v.useId();return e.jsx(Gn.Provider,{value:{id:n},children:e.jsx("div",{ref:s,className:A("space-y-2",t),...r})})});Jn.displayName="FormItem";const Kn=v.forwardRef(({className:t,...r},s)=>{const{error:n,formItemId:a}=Vn();return e.jsx($n,{ref:s,className:A(n&&"text-destructive",t),htmlFor:a,...r})});Kn.displayName="FormLabel";const Hn=v.forwardRef(({...t},r)=>{const{error:s,formItemId:n,formDescriptionId:a,formMessageId:i}=Vn();return e.jsx(o.Slot,{ref:r,id:n,"aria-describedby":s?`${a} ${i}`:`${a}`,"aria-invalid":!!s,...t})});Hn.displayName="FormControl";const Yn=v.forwardRef(({className:t,...r},s)=>{const{formDescriptionId:n}=Vn();return e.jsx("p",{ref:s,id:n,className:A("text-sm text-muted-foreground",t),...r})});Yn.displayName="FormDescription";const Qn=v.forwardRef(({className:t,children:r,...s},n)=>{const{error:a,formMessageId:i}=Vn(),o=a?String(a?.message):r;return o?e.jsx("p",{ref:n,id:i,className:A("text-sm font-medium text-destructive",t),...s,children:o}):null});Qn.displayName="FormMessage";const Zn=v.forwardRef(({className:t,...r},s)=>e.jsx(N.Root,{className:A("grid gap-2",t),...r,ref:s}));Zn.displayName=N.Root.displayName;const Xn=v.forwardRef(({className:t,...r},s)=>e.jsx(N.Item,{ref:s,className:A("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",t),...r,children:e.jsx(N.Indicator,{className:"flex items-center justify-center",children:e.jsx(h.CheckIcon,{className:"h-3.5 w-3.5 fill-primary"})})}));Xn.displayName=N.Item.displayName;const ea=v.forwardRef(({className:t,children:r,...s},n)=>e.jsxs(P.Root,{ref:n,className:A("relative overflow-hidden",t),...s,children:[e.jsx(P.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),e.jsx(ta,{}),e.jsx(P.Corner,{})]}));ea.displayName=P.Root.displayName;const ta=v.forwardRef(({className:t,orientation:r="vertical",...s},n)=>e.jsx(P.ScrollAreaScrollbar,{ref:n,orientation:r,className:A("flex touch-none select-none transition-colors","vertical"===r&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===r&&"h-2.5 border-t border-t-transparent p-[1px]",t),...s,children:e.jsx(P.ScrollAreaThumb,{className:A("relative rounded-full bg-border","vertical"===r&&"flex-1")})}));function ra(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>`}ta.displayName=P.ScrollAreaScrollbar.displayName;const sa=["🏢","🏬","🏣","🏤","🏦","🏛️","🏠","🏡","🏭","🏗️","🏪","🏨","🏫","🏥","💼","📊","📈","📉","📋","📁","📂","🗂️","🗃️","🗄️","📅","🗓️","📝","🖋️","✏️","🖊️","🖌️","🖍️","📇","📌","📍","📎","🖇️","💻","🖥️","🖨️","🖱️","⌨️","📱","📲","📡","🌐","🔗","🔒","🔓","⚙️","🔧","🛠️","🧑‍💻","👨‍💻","👩‍💻","🕹️","💾","📟","🖥️","🖲️","🚀","💡","🎨","🖼️","🧪","🔬","🧬","🎯","⚡","🎲","🎮","🧩","📷","🎥","✉️","📨","📩","📧","📞","☎️","📠","🗣️","💬","🗨️","📢","📣","🔔","🛎️","💰","💸","💳","🏦","📈","📉","⚖️","🧾","🪙","🏛️","⚗️","🧪","🔭","🔬","🩺","🧬","🩻","🏥","🌱","🌍","🌏","🌎","🌡️","👨‍💼","👩‍💼","👨‍🏫","👩‍🏫","👨‍🔬","👩‍🔬","👨‍🎨","👩‍🎨","👨‍🔧","👩‍🔧","👨‍🚀","👩‍🚀","👨‍⚖️","👩‍⚖️","🏅","🎖️","🥇","🥈","🥉","🏆","🎗️","🔑","🗝️","🧭","🛡️","🚩","🏳️‍🌈","🎟️","🎫"];const na=t.lazy(()=>Promise.resolve().then(function(){return require("./SettingsDialog-Y6Y8MzPi.cjs")}).then(function(e){return e.SettingsDialog}).then(e=>({default:e.default})));const aa=({children:r})=>{const{currentWorkspace:s,switchToWorkspace:n,workspaces:a}=Fs(),[i,o]=t.useState(!1),[c,l]=t.useState(Is.Profile),u=t.useRef(!1);return t.useEffect(()=>{const e=Us.getState();o(e.open),l(e.section);return Us.subscribe(e=>{o(e.open),l(e.section)})},[]),t.useEffect(()=>{if(u.current)return;if(!s)return;const e=Oe();if(!e)return;const t=function(e){if(e.screen&&As.has(e.screen))return e.screen;switch(e.action){case Ue.Checkout:case Ue.Billing:case Ue.SelectPlan:return Is.Subscription;case Ue.CreditPurchase:return Is.Credits;case Ue.OpenConnectGuide:return Is.ConnectedAgents;default:return null}}(e);if(!t)return u.current=!0,void _e();const r=e.ws;if(r&&r!==s._id){const e=a.find(e=>e._id===r);return e?void n(e).catch(e=>{L(e,{component:"WorkspaceSettingsProvider",action:"switchWorkspaceFromUrl",metadata:{targetWs:r}}),u.current=!0,_e()}):(u.current=!0,void _e())}u.current=!0,Us.openWorkspaceSettings(t,e),_e()},[s,a,n]),e.jsxs(e.Fragment,{children:[r,s&&i&&e.jsx(It,{fallback:null,children:e.jsx(t.Suspense,{fallback:null,children:e.jsx(na,{workspace:s,open:i,onOpenChange:e=>{e||Us.closeSettings()},section:c,onSectionChange:e=>{Us.setSection(e)},showTrigger:!1})})})]})},ia=(e,t,r)=>{if(t!==exports.ApiVersion.V1)throw new Error(`Invalid version: "${t}". Only "${exports.ApiVersion.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(!r||"string"!=typeof r)throw new Error("orgId is required and must be a string");if(!/^[0-9a-fA-F]{24}$/.test(r))throw new Error(`Invalid orgId: "${r}". Must be a valid MongoDB ObjectId (24 hexadecimal characters).`)},oa=t.memo(({serverUrl:r,version:s,orgId:n,auth:a,locale:i,defaultPermissions:o,getCheckoutStripeParams:c,loadingComponent:l,ui:u,mcp:d,children:p})=>{ia(r,s,n);const m=t.useMemo(()=>({serverUrl:r,version:s,orgId:n}),[r,s,n]),h=t.useMemo(()=>a?.callbacks,[a?.callbacks?.handleAuthentication,a?.callbacks?.onSignOut,a?.callbacks?.getSession,a?.callbacks?.onSessionExpired,a?.callbacks?.handleEvent,a?.callbacks?.onWorkspaceChange]),g=a?.callbacks?.handleEvent;return t.useEffect(()=>(xe.setCallbacks(g?{handleEvent:g}:null),()=>{xe.setCallbacks(null)}),[g]),e.jsx(jr,{locale:i,messageOverrides:u?.messages,children:e.jsx(xr,{children:e.jsx(us,{loadingComponent:l,children:e.jsx(Ms,{callbacks:h,children:e.jsx(qs,{children:e.jsx($s,{config:m,auth:a,children:e.jsx(Ts,{children:e.jsx(vr,{getCheckoutStripeParams:c,children:e.jsx(bs,{appPermissions:o,children:e.jsx(Cs,{ui:u,children:e.jsx(gs,{mcp:d,children:e.jsx(Ks,{children:e.jsx(Qr,{children:e.jsx(vs,{children:e.jsx(as,{children:e.jsx(Gs,{children:e.jsx(aa,{children:p})})})})})})})})})})})})})})})})})});oa.displayName="SaaSOSProviderInner";const ca=({children:t,...r})=>e.jsx(It,{errorTitle:r.ui?.errorBoundary?.title,retryLabel:r.ui?.errorBoundary?.retryLabel,children:e.jsx(oa,{...r,children:t})});ca.displayName="SaaSOSProvider";const la=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{status:n}=Ls();return jt(n).isLoading?r??null:n!==exports.AuthStatus.authenticated?s??null:t},ua=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{status:n}=Ls();return jt(n).isLoading?r??null:n!==exports.AuthStatus.unauthenticated?s??null:t};la.displayName="WhenAuthenticated",ua.displayName="WhenUnauthenticated";const da="https://www.buildbase.app",pa={"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}}},ma={"built-with":"Built with BuildBase","powered-by":"Powered by BuildBase",mark:"BuildBase"};function ha(e,t){return`${da}/badge/v1/${e}.svg?theme=${t}`}function ga(e){return`${da}/?utm_source=badge&utm_medium=${e}`}const fa=e=>{const{children:t,fallback:r,roles:s}=e,{user:n}=Ls();return s.includes(n?.role??"")?t:r||null},ya=e=>{const{children:t,fallback:r,roles:s}=e,{user:n}=Ls(),{currentWorkspace:a}=Fs(),i=a?.users.find(e=>e._id===n?.id);return i&&s.includes(i?.role??"")?t:r||null};fa.displayName="WhenRoles",ya.displayName="WhenWorkspaceRoles";const ba=e=>{const{children:t,fallback:r,permission:s}=e,{can:n}=an();return n(s)?t:r??null};function xa(){const e=t.useContext(Js);if(void 0===e)throw new Error("useUserFeatures must be used within a UserProvider");return t.useMemo(()=>({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])}ba.displayName="WhenPermission";const wa=e=>{const{children:t,slug:r}=e,{currentWorkspace:s}=Fs(),n=s?.features?.[r];return n?t:null},va=e=>{const{children:t,slug:r}=e,{currentWorkspace:s}=Fs(),n=s?.features?.[r];return n?null:t},ka=e=>{const{children:t,slug:r}=e,{isFeatureEnabled:s}=xa();return s(r)?t:null},Sa=e=>{const{children:t,slug:r}=e,{isFeatureEnabled:s}=xa();return s(r)?null:t};wa.displayName="WhenWorkspaceFeatureEnabled",va.displayName="WhenWorkspaceFeatureDisabled",ka.displayName="WhenUserFeatureEnabled",Sa.displayName="WhenUserFeatureDisabled";const Ca=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{response:n,loading:a}=Zr();return a?r??null:n?.subscription?t:s??null},Na=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{response:n,loading:a}=Zr();return a?r??null:n?.subscription?s??null:t},Pa=e=>{const{children:t,plans:r,loadingComponent:s,fallbackComponent:n}=e,{response:a,loading:i}=Zr();if(i)return s??null;if(!a?.subscription)return n??null;const o=a.plan??a.subscription?.plan;if(!o)return n??null;const c=r.map(e=>e.trim().toLowerCase()),l=(o.slug??"").toLowerCase();return c.includes(l)?t:n??null},Ea=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{response:n,loading:a}=Zr();return a?r??null:"trialing"!==n?.subscription?.subscriptionStatus?s??null:t},ja=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{response:n,loading:a}=Zr();return a?r??null:n?.subscription?.subscriptionStatus===at.Trialing?s??null:t},Ia=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{behavior:n}=Ns(),a=e.daysThreshold??n?.trialEndingDays??3,{response:i,loading:o}=Zr();if(o)return r??null;const c=i?.subscription;if(!c||"trialing"!==c.subscriptionStatus)return s??null;const l=c.trialEnd||c.stripeCurrentPeriodEnd;if(!l)return s??null;const u=new Date(l);if(isNaN(u.getTime()))return s??null;return Math.max(0,Math.ceil((u.getTime()-Date.now())/864e5))>a?s??null:t};Ca.displayName="WhenSubscription",Na.displayName="WhenNoSubscription",Pa.displayName="WhenSubscriptionToPlans",Ea.displayName="WhenTrialing",ja.displayName="WhenNotTrialing",Ia.displayName="WhenTrialEnding";const Aa=e=>{const{slug:t,children:r,loadingComponent:s,fallbackComponent:n}=e,{quotas:a,loading:i}=ks();if(i)return s??null;const o=a?.[t];return o?o.available<=0?n??null:r:n??null},Ua=e=>{const{slug:t,children:r,loadingComponent:s,fallbackComponent:n}=e,{quotas:a,loading:i}=ks();if(i)return s??null;const o=a?.[t];return o?o.available>0?n??null:r:n??null},Wa=e=>{const{slug:t,children:r,loadingComponent:s,fallbackComponent:n}=e,{quotas:a,loading:i}=ks();if(i)return s??null;const o=a?.[t];return o&&o.hasOverage&&!1!==o.allowOverage?r:n??null},Ra=e=>{const{slug:t,threshold:r,children:s,loadingComponent:n,fallbackComponent:a}=e,{quotas:i,loading:o}=ks();if(o)return n??null;const c=i?.[t];if(!c)return a??null;return(c.included>0?c.consumed/c.included*100:c.consumed>0?100:0)<r?a??null:s};Aa.displayName="WhenQuotaAvailable",Ua.displayName="WhenQuotaExhausted",Wa.displayName="WhenQuotaOverage",Ra.displayName="WhenQuotaThreshold";const Ta=({children:e})=>{const{currentWorkspace:t}=Fs(),r=t?._id,{balance:s,loading:n,error:a,refetch:i}=is(),{packages:o,loading:c}=rs(r),{consumeCredits:l,loading:u,error:d}=es(r),{purchaseCredits:p,loading:m,error:h}=ts(r);return e({balance:s,loading:n,packages:o,packagesLoading:c,consume:l,consuming:u,purchase:async e=>{if(!r)throw new Error("No workspace selected");const{successUrl:t,cancelUrl:s}=Fe(r),n=await p({creditPackageId:e._id,successUrl:t,cancelUrl:s});n.url&&Le(n.url)},purchasing:m,refetch:i,error:d||h||a})};Ta.displayName="CreditActionsProvider";const Fa=({children:e})=>{const{balance:t,loading:r,error:s,refetch:n}=is();return e({balance:t,loading:r,error:s,refetch:n})};Fa.displayName="CreditBalance";const Oa=e=>{const{min:t=1,children:r,loadingComponent:s,fallbackComponent:n}=e,{balance:a,loading:i}=is();return i?s??null:a?a.available<t?n??null:r:n??null},_a=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{balance:n,loading:a}=is();return a?r??null:n?n.available>0?s??null:t:s??null},Da=e=>{const{threshold:t,children:r,loadingComponent:s,fallbackComponent:n}=e,{balance:a,loading:i}=is();return i?s??null:a?a.available>t?n??null:r:n??null};function La(e){if(!e)return null;const t=new Date(e);return isNaN(t.getTime())?null:t}Oa.displayName="WhenCreditsAvailable",_a.displayName="WhenCreditsExhausted",Da.displayName="WhenCreditsLow";const Ma=d.z.object({name:d.z.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:d.z.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)")});function $a({screen:t}){return e.jsxs("div",{className:"flex flex-col items-center justify-center w-full",children:[e.jsx("p",{className:"text-2xl font-bold",children:t?.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t?.description})]})}function Ba({logo:t}){const{t:r}=Fr();return"string"==typeof t?e.jsx("img",{src:t,alt:r("beta.logoAlt"),className:"max-h-24"}):e.jsx("img",{src:t.bucket?.url,alt:r("beta.logoAlt"),className:"max-h-24"})}const qa=v.forwardRef(({className:t,...r},s)=>e.jsx(S.Root,{ref:s,className:A("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",t),...r}));qa.displayName=S.Root.displayName;const za=v.forwardRef(({className:t,...r},s)=>e.jsx(S.Image,{ref:s,className:A("aspect-square h-full w-full",t),...r}));za.displayName=S.Image.displayName;const Va=v.forwardRef(({className:t,...r},s)=>e.jsx(S.Fallback,{ref:s,className:A("flex h-full w-full items-center justify-center rounded-full bg-muted",t),...r}));Va.displayName=S.Fallback.displayName;const Ga=v.forwardRef(({className:t,orientation:r="horizontal",decorative:s=!0,...n},a)=>e.jsx(E.Root,{ref:a,decorative:s,orientation:r,className:A("shrink-0 bg-border","horizontal"===r?"h-[1px] w-full":"h-full w-[1px]",t),...n}));Ga.displayName=E.Root.displayName;const Ja=t.lazy(()=>Promise.resolve().then(function(){return require("./SettingsDialog-Y6Y8MzPi.cjs")}).then(function(e){return e.SettingsDialog}).then(e=>({default:e.default})));function Ka(r){const{t:s}=Fr(),{visible:n}=on(),a=n(e=>e.workspaceSwitcher?.memberCount),i=n(e=>e.workspaceSwitcher?.planBadge),{workspace:o,setCurrentWorkspace:c,setOpen:u,workspacesToUse:d,switchingToId:p}=r,m=r.isCurrentWorkspace??!1,h=p===o._id,g=o.subscription??null,f=null!=g&&"object"==typeof g?g.plan??null:null,y=f?.name??"";return e.jsxs("div",{className:A("flex items-center gap-3 rounded-lg border-2 p-3 border-border",{"bg-muted text-muted-foreground":m}),children:[e.jsxs(qa,{className:"h-8 w-8 flex items-center justify-center",children:[e.jsx("div",{children:e.jsx(za,{src:o.image&&o.image.trim()?o.image:void 0})}),e.jsx(Va,{children:(b=o.name,b.split(" ").map(e=>e[0]).join("").toUpperCase().slice(0,2))})]}),e.jsxs("div",{className:"flex-1 min-w-0 max-w-full",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"font-medium line-clamp-1 text-ellipsis overflow-hidden max-w-full",children:o.name})}),a&&e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(l.Users,{className:"h-3 w-3"}),e.jsx("span",{children:s("workspace.membersCount",{count:o.users?.length||0})})]}),i&&y&&e.jsx("div",{className:"max-w-fit",children:e.jsx("div",{className:"flex items-center gap-1 text-sm bg-success text-success-foreground rounded-full px-2 py-0.5",children:e.jsx("span",{className:"text-xs",children:y})})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[m?null:e.jsx(Ys,{size:"sm",disabled:null!==p||h,progress:h,onClick:()=>{r.switchToWorkspace(o).then(()=>u(!1)).catch(e=>{L(e,{component:"WorkspaceItem",action:"switchToWorkspace",metadata:{workspaceId:o._id}})})},children:s("workspace.switchTo")}),e.jsx(t.Suspense,{fallback:null,children:e.jsx(Ja,{workspace:o,onClose:()=>{if(m){const e=d.findIndex(e=>e._id?.toString()===o._id?.toString());-1!==e&&c(d[e])}}})})]})]});var b}function Ha(r){const{t:s,dir:n}=Fr(),{switching:o}=Fs(),[c,u]=t.useState(!1),[p,m]=t.useState("emoji"),[h,g]=t.useState("🏢"),[f,y]=t.useState(!1),{createWorkspace:b}=Fs(),x=d.z.object({name:d.z.string().min(2,{message:s("workspace.workspaceNameMinLength")}),image:d.z.string().optional()}),w=i.useForm({resolver:a.zodResolver(x),defaultValues:{name:"",image:""}});return e.jsxs(Qs,{open:c,onOpenChange:u,children:[e.jsx(Zs,{asChild:!0,children:e.jsxs(Ys,{className:"w-full rounded-none",disabled:o,children:[e.jsx(l.Plus,{className:"h-4 w-4 me-2"}),s("workspace.createNew")]})}),e.jsxs(tn,{dir:n,className:"max-w-xl min-w-full sm:min-w-[600px]",children:[e.jsxs(rn,{children:[e.jsx(sn,{children:s("workspace.createTitle")}),e.jsx(nn,{children:s("workspace.createDescription")})]}),e.jsx(Bn,{...w,children:e.jsxs("form",{onSubmit:w.handleSubmit(async function(e){let t="";if("emoji"===p)t=ra(h);else if("url"===p&&e.image)try{new URL(e.image),t=e.image}catch{return void w.setError("image",{message:s("workspace.invalidUrl")})}y(!0);try{await b(e.name,t),u(!1),w.reset(),g("🏢"),m("emoji"),r?.onCreated?.()}catch(t){L(t,{component:"WorkspaceProvider",action:"createWorkspace",metadata:{name:e.name}})}finally{y(!1)}}),children:[e.jsx(zn,{control:w.control,name:"name",render:({field:t})=>e.jsxs(Jn,{children:[e.jsx(Kn,{children:s("workspace.workspaceName")}),e.jsx(Hn,{children:e.jsx(_n,{placeholder:s("workspace.workspaceNamePlaceholder"),...t})}),e.jsx(Qn,{})]})}),e.jsxs("div",{className:"flex flex-col gap-y-2 my-2",children:[e.jsxs("div",{children:[e.jsx($n,{className:"text-sm font-medium",children:s("workspace.workspaceIcon")}),e.jsx(Yn,{children:s("workspace.iconDescription")})]}),e.jsxs(Zn,{value:p,onValueChange:e=>m(e),className:"flex flex-col gap-y-2",children:[e.jsxs("div",{className:"flex items-center gap-x-2 my-1",children:[e.jsx(Xn,{value:"emoji",id:"emoji"}),e.jsxs($n,{htmlFor:"emoji",className:"flex items-center gap-2",children:[e.jsx(l.Smile,{className:"h-4 w-4"}),s("workspace.chooseEmoji")]})]}),e.jsxs("div",{className:"flex items-center gap-x-2 my-1",children:[e.jsx(Xn,{value:"url",id:"url"}),e.jsxs($n,{htmlFor:"url",className:"flex items-center gap-2",children:[e.jsx(l.Image,{className:"h-4 w-4"}),s("workspace.customImageUrl")]})]})]}),"emoji"===p&&e.jsxs("div",{className:"flex flex-col gap-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm font-medium",children:s("general.previewLabel")}),e.jsx("div",{className:"w-12 h-12 rounded-lg border-2 border-border flex items-center justify-center text-2xl bg-muted",children:h})]}),e.jsx(ea,{className:"h-32 w-full rounded-md border",children:e.jsx("div",{className:"p-4 grid grid-cols-8 gap-2",children:sa.map((t,r)=>e.jsx("button",{type:"button",onClick:()=>(e=>{g(e),w.setValue("image",ra(e))})(t),"aria-label":t,"aria-pressed":h===t,className:"w-10 h-10 sm:w-8 sm:h-8 rounded flex items-center justify-center text-lg hover:bg-muted transition-colors "+(h===t?"bg-primary text-primary-foreground":""),children:t},r))})})]}),"url"===p&&e.jsxs("div",{className:"flex flex-col gap-y-2",children:[e.jsx(zn,{control:w.control,name:"image",render:({field:t})=>e.jsxs(Jn,{children:[e.jsx(Kn,{children:s("workspace.imageUrl")}),e.jsx(Hn,{children:e.jsx(_n,{placeholder:s("workspace.imageUrlPlaceholder"),...t})}),e.jsx(Yn,{children:s("workspace.imageUrlDescription")}),e.jsx(Qn,{})]})}),w.watch("image")&&w.watch("image")?.trim()&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm font-medium",children:s("general.previewLabel")}),e.jsx("div",{className:"w-12 h-12 rounded-lg border-2 border-border overflow-hidden bg-muted",children:e.jsx("img",{src:w.watch("image")||void 0,alt:s("general.previewImageAlt"),className:"w-full h-full object-cover",onError:e=>{e.currentTarget.style.display="none"}})})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[e.jsx(Ys,{type:"button",variant:"outline",onClick:()=>{u(!1),w.reset(),g("🏢"),m("emoji")},disabled:f,children:s("settings.common.cancel")}),e.jsx(Ys,{type:"submit",disabled:f,children:f?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"me-2 h-4 w-4 animate-spin"}),s("workspace.creating")]}):s("workspace.createWorkspace")})]})]})})]})]})}exports.AlertDialog=vn,exports.AlertDialogAction=An,exports.AlertDialogCancel=Un,exports.AlertDialogContent=Nn,exports.AlertDialogDescription=In,exports.AlertDialogFooter=En,exports.AlertDialogHeader=Pn,exports.AlertDialogTitle=jn,exports.AlertDialogTrigger=kn,exports.AuthApi=ie,exports.BBAction=Ue,exports.BBScreen=Re,exports.BBStatus=We,exports.BB_PARAM=Ae,exports.BaseApi=ae,exports.BetaForm=({onSuccess:r,onError:s,className:n="w-full",fieldClassName:o="flex flex-col gap-1.5 w-full",autoFocus:c=!0,showSuccessMessage:l=!0,hideLogo:u=!1,hideTitles:d=!1})=>{const{t:p}=Fr(),[m,h]=t.useState(!1),[g,f]=t.useState(!1),{submitBetaForm:y,isLoading:b,isSubmitting:x,error:w,config:v,success:k,message:S}=(()=>{const{t:e}=Fr(),r=Mr(),[s,n]=t.useState(null),[a,i]=t.useState(!0),[o,c]=t.useState(!1),[l,u]=t.useState(null),[d,p]=t.useState(!1),[m,h]=t.useState(null);return t.useEffect(()=>{let t=!1;return(async()=>{i(!0),u(null);try{const e=new ce(r),s=await e.fetchConfig();t||n(s)}catch(r){t||u(r instanceof Error?r.message:e("beta.errorMessage"))}finally{t||i(!1)}})(),()=>{t=!0}},[r]),{isLoading:a,isSubmitting:o,config:s,error:l,success:d,message:m,submitBetaForm:t.useCallback(async t=>{if(!r){const t=e("errors.generic");return u(t),{success:!1,message:t}}try{c(!0),u(null),p(!1),h(null);const e=new ce(r),s=await e.submitBetaUser({name:t.name||"",email:t.email}),n="success"===s.status;return p(n),h(s.message),{success:n,message:s.message}}catch(t){const r=t instanceof Error?t.message:e("beta.errorMessage");return u(r),p(!1),h(r),{success:!1,message:r}}finally{c(!1)}},[r])}})();t.useEffect(()=>{k&&l&&(h(!0),f(!0)),w&&f(!0)},[k,l,w]);const C=i.useForm({resolver:a.zodResolver(Ma),defaultValues:{email:"",name:""},mode:"onChange",reValidateMode:"onChange"});t.useEffect(()=>{c&&C.setFocus("name")},[c,C]);const N=C.formState.isValid&&!x;return e.jsx("div",{className:"saas-os-ui",style:{width:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},children:b?e.jsxs("div",{className:A("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",n),children:[e.jsx(mn,{className:"h-24 w-24 rounded-lg"}),e.jsx(mn,{className:"h-6 w-32"}),e.jsxs("div",{className:"w-full space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(mn,{className:"h-4 w-16"}),e.jsx(mn,{className:"h-10 w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(mn,{className:"h-4 w-16"}),e.jsx(mn,{className:"h-10 w-full"})]}),e.jsx(mn,{className:"h-10 w-full"})]})]}):e.jsxs("div",{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:[!u&&e.jsxs("div",{className:"flex flex-col items-center justify-center w-full",children:[v?.logo&&e.jsx(Ba,{logo:v?.logo}),v?.name&&e.jsx("div",{children:v?.name})]}),e.jsx(i.FormProvider,{...C,children:e.jsxs("form",{onSubmit:C.handleSubmit(async e=>{try{const t=await y(e);t.success?(r?.(),C.reset(),l&&h(!0),f(!0)):(s?.(t.message),f(!0))}catch(e){s?.(e instanceof Error?e.message:p("beta.errorMessage")),f(!0)}}),className:n,noValidate:!0,"aria-busy":x,children:[!g&&e.jsxs(e.Fragment,{children:[!d&&v?.screen?.register&&e.jsx($a,{screen:v?.screen?.register}),e.jsx(zn,{control:C.control,name:"name",render:({field:t})=>e.jsxs(Jn,{className:o,children:[e.jsx(Kn,{children:p("beta.nameLabel")}),e.jsx(Hn,{children:e.jsx(_n,{...t})}),e.jsx(Yn,{}),e.jsx(Qn,{})]})}),e.jsx(zn,{control:C.control,name:"email",render:({field:t})=>e.jsxs(Jn,{className:o,children:[e.jsx(Kn,{children:p("beta.emailLabel")}),e.jsx(Hn,{children:e.jsx(_n,{...t})}),e.jsx(Yn,{}),e.jsx(Qn,{})]})}),e.jsx(Ys,{type:"submit",disabled:!N,className:o,children:p(x?"beta.submittingText":"beta.submitText")})]}),g&&w&&e.jsxs("div",{className:"flex flex-col items-center justify-center w-full",children:[e.jsxs("div",{className:"border-destructive/30 text-destructive",role:"alert","aria-live":"assertive","aria-atomic":!0,children:[e.jsx("span",{className:"text-4xl mb-2",role:"img","aria-label":p("settings.common.error"),children:"❗"}),w]}),e.jsx("div",{className:"mt-4 flex justify-center",children:e.jsx(Ys,{type:"button",onClick:()=>{f(!1),C.reset()},className:o,children:p("beta.tryAgain")})})]}),g&&m&&S&&e.jsx("div",{className:"flex flex-col items-center justify-center w-full text-success border-success/30 text-center",children:v?.screen?.thankYou&&e.jsx($a,{screen:v?.screen?.thankYou})})]})}),!g&&e.jsx("div",{children:e.jsxs("div",{children:[p("beta.privacyConsent")," ",e.jsx("a",{href:v?.privacyPolicy,target:"_blank",rel:"noopener noreferrer",className:"text-info hover:text-info",children:p("beta.privacyPolicy")})," ",p("beta.and")," ",e.jsx("a",{href:v?.termsOfService,target:"_blank",rel:"noopener noreferrer",className:"text-info hover:text-info",children:p("beta.termsOfService")}),"."]})})]})})},exports.BillingIntervals=nt,exports.BuildBaseBadge=({variant:t="built-with",theme:r="auto",size:s="md",alt:n,className:a,link:i=!0})=>{const o=pa[t][s],c=e.jsx("img",{src:ha(t,r),alt:n??ma[t],width:o.width,height:o.height,loading:"lazy",decoding:"async"});return i?e.jsx("a",{href:ga(t),target:"_blank",rel:"noopener noreferrer",className:A("inline-block",a),children:c}):e.jsx("span",{className:a,children:c})},exports.Button=Ys,exports.CURRENCY_DISPLAY=ze,exports.CURRENCY_FLAG=Ve,exports.ConnectMcpGuide=xn,exports.ConnectedAgents=function({className:r,title:s,description:n,disconnectLabel:a,emptyLabel:i,showConnectGuide:o=!0}){const{t:c,formattingLocale:u}=Fr(),{formats:d}=Ns(),{agents:p,loading:m,error:h,revoking:g,revoke:f}=ln(),y=fs(),b=o&&Boolean(y?.url),[x,w]=t.useState(!1),v=t.useRef(!1);t.useEffect(()=>{if(v.current||!b)return;const e=Us.getState().params;e?.action===Ue.OpenConnectGuide&&(v.current=!0,Us.clearParams(),w(!0))},[b]);const k=void 0===s?c("security.connectedAgentsTitle"):s,S=void 0===n?c("security.connectedAgentsDescription"):n,C=a??c("security.connectedAgentsDisconnect"),N=i??c("security.connectedAgentsEmpty"),P=c("security.mcpConnectAction"),E=t=>b?e.jsxs(Ys,{size:"sm",onClick:()=>w(!0),"aria-label":P,className:"shrink-0 gap-1.5",children:[e.jsx(l.Plus,{className:"h-4 w-4","aria-hidden":"true"}),e.jsx("span",{className:t?"hidden sm:inline":void 0,children:P})]}):null;return e.jsxs("div",{className:A("space-y-4",r),children:[e.jsx(pn,{title:k,description:S,actions:!m&&p.length>0?E(!0):void 0}),m&&e.jsx("div",{className:"space-y-3",children:[0,1].map(t=>e.jsx(mn,{className:"h-20 rounded-md"},t))}),h&&!m&&e.jsx("p",{className:"text-destructive text-sm",children:h}),!m&&!h&&0===p.length&&e.jsx(dn,{icon:e.jsx(l.Bot,{className:"h-5 w-5 text-muted-foreground"}),description:N,action:E(!1)??void 0}),!m&&p.length>0&&e.jsx("ul",{className:"space-y-3",children:p.map(t=>{return e.jsxs("li",{className:"flex items-start justify-between gap-x-4 rounded-md border p-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-col gap-y-1",children:[e.jsx("span",{className:"text-sm font-medium break-words",children:t.title}),t.scope.length>0&&e.jsxs("span",{className:"text-muted-foreground text-xs break-words",children:[c("security.connectedAgentsAccess"),": ",t.scope.join(", ")]}),t.lastGrantedAt&&e.jsxs("span",{className:"text-muted-foreground text-xs",children:[c("security.connectedAgentsGranted"),": ",(r=t.lastGrantedAt,un(r,u,d?.date??{dateStyle:"medium"}))]})]}),e.jsx(Ys,{variant:"outline",size:"sm",progress:g===t.clientId,onClick:()=>f(t.clientId),className:"shrink-0",children:C})]},t.clientId);var r})}),b&&e.jsx(Qs,{open:x,onOpenChange:w,children:e.jsxs(tn,{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.jsxs(rn,{className:"pe-8",children:[e.jsx(sn,{children:c("security.mcpGuideTitle")}),e.jsx(nn,{children:c("security.mcpGuideDescription")})]}),e.jsx(xn,{title:null,description:null})]})})]})},exports.ConnectedAgentsApi=le,exports.CreditActionsProvider=Ta,exports.CreditBalance=Fa,exports.CreditBalanceContextProvider=as,exports.CreditBucketSource={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},exports.CreditBucketStatus={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},exports.CreditStorePage=function({children:r,loadingFallback:s,errorFallback:n,redirectBaseUrl:a}){const{packages:i,notes:o,loading:c,error:l,refetch:u}=ss(),{isAuthenticated:d,signIn:p}=Ls(),m=t.useCallback(e=>{if(d)Us.openWorkspaceSettings(Is.Credits,{action:Ue.CreditPurchase,packageId:e});else if(a){const t=Te({action:Ue.CreditPurchase,screen:"credits",packageId:e},a);p(t)}else p()},[d,p,a]);return c?void 0!==s?e.jsx(e.Fragment,{children:s}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(mn,{className:"h-8 w-48"}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(t=>e.jsx(mn,{className:"h-48 rounded-lg"},t))})]}):l?n?e.jsx(e.Fragment,{children:n(l)}):e.jsx("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive",children:l}):e.jsx(e.Fragment,{children:r({loading:c,error:l,packages:i,notes:o,refetch:u,selectPackage:m})})},exports.CreditTransactionType={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"},exports.DEFAULT_ROLE_PERMISSIONS=Ct,exports.Devices=function({className:r,title:s,description:n,showRename:a,showSignOut:i,showRemove:o,renameLabel:c,signOutLabel:u,removeLabel:d,emptyLabel:p}){const{t:m,formattingLocale:h}=Fr(),{formats:g}=Ns(),{visible:f}=on(),{devices:y,loading:b,error:x,busyId:w,rename:v,signOut:k,forget:S}=Rn(),[C,N]=t.useState(null),[P,E]=t.useState(""),[j,I]=t.useState(null),U=a??f(e=>e.settings?.devices?.rename),W=i??f(e=>e.settings?.devices?.signOut),R=o??f(e=>e.settings?.devices?.forget),T=U||W||R,F=void 0===s?m("security.devicesTitle"):s,O=void 0===n?m("security.devicesDescription"):n,_=c??m("security.deviceRename"),D=u??m("security.deviceSignOut"),L=d??m("security.deviceForget"),M=p??m("security.devicesEmpty"),$=async e=>{const t=P.trim();t&&await v(e,t),N(null)};return e.jsxs("div",{className:A("space-y-4",r),children:[e.jsx(pn,{title:F,description:O}),b&&e.jsx("div",{className:"space-y-3",children:[0,1].map(t=>e.jsx(mn,{className:"h-24 rounded-md"},t))}),x&&!b&&e.jsx("p",{className:"text-destructive text-sm",children:x}),!b&&!x&&0===y.length&&e.jsx(dn,{icon:e.jsx(l.Monitor,{className:"h-5 w-5 text-muted-foreground"}),description:M}),!b&&y.length>0&&e.jsx("ul",{className:"space-y-3",children:y.map(t=>{const r=C===t.deviceId,s=w===t.deviceId,n=On(t.userAgent),a=function(e){return[[e.ipInfo?.city,e.ipInfo?.country].filter(Boolean).join(", "),e.ip].filter(Boolean).join(" · ")}(t),i=Tn(t.userAgent)?l.Smartphone:l.Monitor;return e.jsxs("li",{className:"flex items-start justify-between gap-x-4 rounded-md border p-3",children:[e.jsxs("div",{className:"flex min-w-0 gap-x-3",children:[e.jsx(i,{className:"text-muted-foreground mt-0.5 h-5 w-5 shrink-0","aria-hidden":"true"}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-y-1",children:[r?e.jsxs("div",{className:"flex items-center gap-x-2",children:[e.jsx(_n,{value:P,onChange:e=>E(e.target.value),placeholder:m("security.deviceRenamePlaceholder"),className:"h-8 w-48",autoFocus:!0,onKeyDown:e=>{"Enter"===e.key&&$(t.deviceId),"Escape"===e.key&&N(null)}}),e.jsx(Ys,{size:"sm",variant:"ghost","aria-label":m("security.deviceSave"),progress:s,onClick:()=>$(t.deviceId),children:e.jsx(l.Check,{className:"h-4 w-4","aria-hidden":"true"})}),e.jsx(Ys,{size:"sm",variant:"ghost","aria-label":m("security.deviceCancel"),onClick:()=>N(null),children:e.jsx(l.X,{className:"h-4 w-4","aria-hidden":"true"})})]}):e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[e.jsx("span",{className:"text-sm font-medium break-words",children:t.name}),t.current&&e.jsx("span",{className:"bg-primary/10 text-primary rounded px-1.5 py-0.5 text-xs font-medium",children:m("security.deviceCurrent")}),t.trusted&&e.jsxs("span",{className:"text-primary inline-flex items-center gap-x-1 text-xs",children:[e.jsx(l.ShieldCheck,{className:"h-3.5 w-3.5","aria-hidden":"true"}),m("security.deviceTrusted")]}),t.pushEnabled&&e.jsx("span",{className:"text-muted-foreground inline-flex","aria-label":m("security.devicePushEnabled"),title:m("security.devicePushEnabled"),children:e.jsx(l.Bell,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]}),n&&e.jsx("span",{className:"text-muted-foreground text-xs break-words",children:n}),a&&e.jsx("span",{className:"text-muted-foreground text-xs break-words",children:a}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:[t.lastActiveAt&&m("security.deviceLastActive",{date:(o=t.lastActiveAt,un(o,h,g?.date??{dateStyle:"medium"}))}),t.activeSessions>0&&e.jsxs(e.Fragment,{children:[t.lastActiveAt&&" · ",m("security.deviceActiveSessions",{count:t.activeSessions})]})]})]})]}),!r&&T&&e.jsxs("div",{className:"flex shrink-0 flex-col items-end gap-y-1.5",children:[(U||W)&&e.jsxs("div",{className:"flex items-center gap-x-1.5",children:[U&&e.jsx(Ys,{variant:"ghost",size:"sm",disabled:s,onClick:()=>(e=>{N(e.deviceId),E(e.name)})(t),children:_}),W&&t.activeSessions>0&&e.jsx(Ys,{variant:"outline",size:"sm",progress:s,onClick:()=>k(t.deviceId),children:D})]}),R&&e.jsx(Ys,{variant:"ghost",size:"sm",className:"text-destructive hover:bg-destructive/10 hover:text-destructive",disabled:s,onClick:()=>I(t),children:L})]})]},t.deviceId);var o})}),e.jsx(vn,{open:null!==j,onOpenChange:e=>{e||I(null)},children:e.jsxs(Nn,{children:[e.jsxs(Pn,{children:[e.jsx(jn,{children:m("security.deviceForgetConfirmTitle")}),e.jsx(In,{children:m("security.deviceForgetConfirmBody")})]}),e.jsxs(En,{children:[e.jsx(Un,{children:m("security.deviceCancel")}),e.jsx(An,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:async()=>{if(!j)return;const{deviceId:e}=j;I(null),await S(e)},children:L})]})]})})]})},exports.DevicesApi=ue,exports.Dialog=Qs,exports.DialogContent=tn,exports.DialogDescription=nn,exports.DialogTitle=sn,exports.DialogTrigger=Zs,exports.DunningState={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},exports.EmptyState=dn,exports.EventEmitter=be,exports.Form=Bn,exports.FormControl=Hn,exports.FormDescription=Yn,exports.FormField=zn,exports.FormItem=Jn,exports.FormLabel=Kn,exports.FormMessage=Qn,exports.FullScreenLoader=cs,exports.Input=_n,exports.InvoiceStatuses={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},exports.Label=$n,exports.LoadingState=function({label:t,className:r}){const{t:s}=Fr();return e.jsxs("div",{role:"status","aria-live":"polite",className:A("flex items-center gap-2 rounded-lg border bg-muted/50 px-4 py-3 text-sm text-muted-foreground",r),children:[e.jsx(l.Loader2,{className:"h-4 w-4 animate-spin flex-shrink-0"}),e.jsx("span",{children:t??s("settings.common.loading")})]})},exports.PLAN_CURRENCY_CODES=Je,exports.PLAN_CURRENCY_OPTIONS=Ke,exports.PUSH_SERVICE_WORKER_SCRIPT="\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 try {\n const payload = event.data.json();\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 const options = {\n body: payload.body || '',\n icon: payload.icon || undefined,\n badge: payload.icon || undefined,\n data: { url: payload.url, ...(payload.data || {}) },\n tag: 'buildbase-push-' + Date.now(),\n };\n\n event.waitUntil(\n self.registration.showNotification(title, options)\n );\n } catch (e) {\n console.error('[PushSW] Failed to show notification:', e);\n }\n});\n\nself.addEventListener('notificationclick', function(event) {\n event.notification.close();\n\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",exports.Permission=kt,exports.PortalContext=Bs,exports.PricingPage=function({slug:r,children:s,loadingFallback:n,errorFallback:a,redirectBaseUrl:i}){const{items:o,plans:c,notes:l,loading:u,error:d,refetch:p}=Vr(r),{isAuthenticated:m,signIn:h}=Ls(),g=t.useCallback((e,t,r)=>i?Te({action:"selectPlan",plan:e,interval:t,currency:r},i):null,[i]),f=t.useCallback((e,t,r)=>{if(m)return void Us.openWorkspaceSettings(Is.Subscription,{action:"selectPlan",plan:e,interval:t,currency:r});const s=g(e,t,r);h(s??void 0)},[m,h,g]);return u?void 0!==n?e.jsx(e.Fragment,{children:n}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(mn,{className:"h-8 w-48"}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(t=>e.jsx(mn,{className:"h-64 rounded-lg"},t))})]}):d?a?e.jsx(e.Fragment,{children:a(d)}):e.jsx("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive",children:d}):e.jsx(e.Fragment,{children:s({loading:u,error:d,items:o,plans:c,notes:l,refetch:p,selectPlan:f})})},exports.PushApi=de,exports.PushNotificationProvider=Gs,exports.QuotaUsageContextProvider=vs,exports.RadioGroup=Zn,exports.RadioGroupItem=Xn,exports.SDKEvent=ye,exports.SETTINGS_SCREENS=As,exports.SUPPORTED_LOCALES=Cr,exports.SaaSOSProvider=ca,exports.ScrollArea=ea,exports.SectionHeader=pn,exports.Sessions=function({className:t,title:r,description:s,showSignOut:n,signOutLabel:a,emptyLabel:i}){const{t:o,formattingLocale:c}=Fr(),{formats:u}=Ns(),{visible:d}=on(),{sessions:p,loading:m,error:h,revoking:g,revoke:f}=Ln(),y=n??d(e=>e.settings?.devices?.sessionSignOut),b=void 0===r?o("security.sessionsTitle"):r,x=void 0===s?o("security.sessionsDescription"):s,w=a??o("security.sessionSignOut"),v=i??o("security.sessionsEmpty"),k=e=>un(e,c,u?.date??{dateStyle:"medium"});return e.jsxs("div",{className:A("space-y-4",t),children:[e.jsx(pn,{title:b,description:x}),m&&e.jsx("div",{className:"space-y-3",children:[0,1].map(t=>e.jsx(mn,{className:"h-20 rounded-md"},t))}),h&&!m&&e.jsx("p",{className:"text-destructive text-sm",children:h}),!m&&!h&&0===p.length&&e.jsx(dn,{icon:e.jsx(l.MonitorSmartphone,{className:"h-5 w-5 text-muted-foreground"}),description:v}),!m&&p.length>0&&e.jsx("ul",{className:"space-y-3",children:p.map(t=>{const r=On(t.userAgent),s=function(e){return[[e.ipInfo?.city,e.ipInfo?.country].filter(Boolean).join(", "),e.ip].filter(Boolean).join(" · ")}(t),n=t.device?.name||r||o("security.sessionsTitle"),a=Tn(t.userAgent)?l.Smartphone:l.Monitor;return e.jsxs("li",{className:"flex items-start justify-between gap-x-4 rounded-md border p-3",children:[e.jsxs("div",{className:"flex min-w-0 gap-x-3",children:[e.jsx(a,{className:"text-muted-foreground mt-0.5 h-5 w-5 shrink-0","aria-hidden":"true"}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-y-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[e.jsx("span",{className:"text-sm font-medium break-words",children:n}),t.current&&e.jsx("span",{className:"bg-primary/10 text-primary rounded px-1.5 py-0.5 text-xs font-medium",children:o("security.sessionCurrent")})]}),r&&n!==r&&e.jsx("span",{className:"text-muted-foreground text-xs break-words",children:r}),s&&e.jsx("span",{className:"text-muted-foreground text-xs break-words",children:s}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:[t.lastActiveAt&&e.jsxs(e.Fragment,{children:[o("security.sessionLastActive",{date:k(t.lastActiveAt)}),t.expiresAt&&" · "]}),t.expiresAt&&o("security.sessionExpires",{date:k(t.expiresAt)})]})]})]}),!t.current&&y&&e.jsx(Ys,{variant:"ghost",size:"sm",progress:g===t.id,onClick:()=>f(t.id),className:"text-destructive hover:bg-destructive/10 hover:text-destructive shrink-0",children:w})]},t.id)})})]})},exports.SessionsApi=pe,exports.SettingsApi=me,exports.SettingsScreen=Is,exports.SidebarNavItem=function({icon:t,label:r,active:s=!1,onClick:n,className:a}){return e.jsxs("button",{className:A("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",s?"bg-primary/10 text-primary font-medium":"hover:bg-muted hover:text-foreground",a),onClick:n,"aria-current":s?"true":void 0,children:[t,e.jsx("span",{className:"min-w-0 truncate",children:r}),e.jsx(l.ChevronRight,{"aria-hidden":"true",className:"h-4 w-4 ms-auto opacity-40 sm:hidden rtl:rotate-180"})]})},exports.SidebarNavSection=function({title:t,children:r,className:s}){return e.jsxs("div",{className:A("px-2 flex flex-col gap-1",s),children:[e.jsx("div",{className:"text-xs font-bold text-muted-foreground uppercase tracking-wide px-2 pb-1 shrink-0 whitespace-nowrap",children:t}),r]})},exports.Skeleton=mn,exports.StatusBanner=function({variant:t,title:r,message:s,description:n,icon:a,actionLabel:i,onAction:o,actionDisabled:c,className:l}){const u=wn[t];return e.jsxs("div",{role:"error"===t?"alert":"status","aria-live":"error"===t?"assertive":"polite","aria-atomic":"true",className:A("border px-4 py-3 rounded-lg flex items-start justify-between gap-2 sm:gap-4",u.box,l),children:[e.jsxs("div",{className:"flex items-start gap-2 min-w-0",children:[a,e.jsxs("div",{className:"min-w-0",children:[r&&e.jsx("p",{className:"text-sm font-medium",children:r}),s&&e.jsx("p",{className:A("text-sm",r&&"mt-1"),children:s}),n&&e.jsx("p",{className:A("text-xs mt-2",u.sub),children:n})]})]}),i&&e.jsx(Ys,{variant:"outline",size:"sm",onClick:o,disabled:c,className:A("flex-shrink-0",u.button),children:i})]})},exports.SubscriptionContextProvider=Qr,exports.SubscriptionItemType={Feature:"feature",Limit:"limit",Quota:"quota"},exports.SubscriptionStatus=at,exports.UIConfigProvider=Cs,exports.UserApi=he,exports.WhenAuthenticated=la,exports.WhenCreditsAvailable=Oa,exports.WhenCreditsExhausted=_a,exports.WhenCreditsLow=Da,exports.WhenNoSubscription=Na,exports.WhenNotTrialing=ja,exports.WhenPermission=ba,exports.WhenQuotaAvailable=Aa,exports.WhenQuotaExhausted=Ua,exports.WhenQuotaOverage=Wa,exports.WhenQuotaThreshold=Ra,exports.WhenRoles=fa,exports.WhenSubscription=Ca,exports.WhenSubscriptionToPlans=Pa,exports.WhenTrialEnding=Ia,exports.WhenTrialing=Ea,exports.WhenUnauthenticated=ua,exports.WhenUserFeatureDisabled=Sa,exports.WhenUserFeatureEnabled=ka,exports.WhenWorkspaceFeatureDisabled=va,exports.WhenWorkspaceFeatureEnabled=wa,exports.WhenWorkspaceRoles=ya,exports.WorkspaceApi=ge,exports.WorkspaceSwitcher=function(r){const{t:s,dir:n}=Fr(),{isAuthenticated:a,user:i}=Ls(),o=fe(Mr()),{workspaces:c,currentWorkspace:u,loading:d,refreshing:p,switchingToId:m,fetchWorkspaces:h,getFeatures:g,refreshWorkspaces:f,setCurrentWorkspace:y,switchToWorkspace:b}=Fs(),{settings:x,loading:w}=qr(),{visible:v}=on(),[k,S]=t.useState(!1),[C,N]=t.useState(0),[P,E]=t.useState(""),j=d||p;t.useEffect(()=>{a&&o&&(0===c.length?(h(),g()):g())},[a,o]),t.useEffect(()=>{a&&o&&C>0&&f()},[C,a,o]);const I=c,A=I.filter(e=>e._id!==u?._id).filter(e=>e.name.toLowerCase().includes(P.toLowerCase())),U=(x?.workspace?.canCreateWorkspace??!0)&&v(e=>e.workspaceSwitcher?.createButton),W=(x?.workspace?.showSwitcher??!0)&&v(e=>e.workspaceSwitcher?.show),R=x?.workspace?.maxWorkspacesPerUser??0,T=I?.filter(e=>("object"==typeof e.createdBy?e.createdBy._id?.toString():e.createdBy?.toString())===i?.id?.toString()).length??0,F=!1!==U&&(0===R||T<R);return t.useEffect(()=>{!W&&c.length>0&&!u&&b(c[0]).catch(e=>{L(e,{component:"WorkspaceProvider",action:"autoSelectWorkspace"})})},[W,c,u]),w&&!x?e.jsx(e.Fragment,{children:r.trigger?.(!0,u)}):!W&&u?e.jsxs(e.Fragment,{children:[e.jsx("div",{role:"button",tabIndex:0,"aria-label":s("settings.common.openSettings"),className:"cursor-pointer",onClick:()=>S(!0),onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),S(!0))},children:r.trigger?.(j,u)}),e.jsx(t.Suspense,{fallback:null,children:e.jsx(Ja,{workspace:u,open:k,onOpenChange:S,showTrigger:!1})})]}):e.jsxs(Qs,{open:k,onOpenChange:S,children:[e.jsx(Zs,{children:r.trigger?.(j,u)}),e.jsxs(tn,{dir:n,className:"max-w-2xl min-w-full md:min-w-[800px]",children:[e.jsxs(rn,{dir:n,children:[e.jsxs(sn,{className:"flex items-center gap-2",children:[e.jsx(l.Building2,{className:"h-5 w-5"}),s("workspace.switchTitle")]}),e.jsx(nn,{children:s("workspace.switchDescription")})]}),!i&&e.jsx("div",{className:"flex flex-col items-center justify-center h-full py-4 sm:py-8",children:e.jsx("div",{className:"text-sm font-medium text-muted-foreground",children:s("workspace.notLoggedIn")})}),i&&e.jsxs("div",{dir:n,className:"flex flex-col gap-4",children:[u&&e.jsx(Ka,{workspace:u,isCurrentWorkspace:!0,switchToWorkspace:b,switchingToId:m,setCurrentWorkspace:y,setOpen:S,workspacesToUse:I}),e.jsx(Ga,{}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-sm font-medium text-muted-foreground",children:s("workspace.availableWorkspaces",{count:A.length})}),e.jsx("div",{children:e.jsx(Ys,{progress:p,disabled:p,variant:"ghost",onClick:function(){a&&o&&N(e=>e+1)},startIcon:e.jsx(l.RefreshCcw,{}),children:s("settings.common.refreshAction",{loading:String(p)})})})]}),e.jsxs("div",{className:"relative",children:[e.jsx(l.Search,{className:"absolute start-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"}),e.jsx(_n,{placeholder:s("workspace.searchPlaceholder"),value:P,onChange:e=>E(e.target.value),className:"ps-10"})]}),d?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(l.Loader2,{className:"h-6 w-6 animate-spin text-muted-foreground"}),e.jsx("span",{className:"ms-2 text-sm text-muted-foreground",children:s("workspace.loadingWorkspaces")})]}):0===A.length?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(l.Building2,{className:"mx-auto h-12 w-12 text-muted-foreground"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:s(P?"workspace.noWorkspacesFound":"workspace.noWorkspacesAvailable")})]}):e.jsx(ea,{className:"h-64",dir:n,children:e.jsx("div",{dir:n,className:"flex flex-col gap-2 my-2.5",children:A.map(t=>{const r=t._id===u?._id;return e.jsx(Ka,{workspace:t,isCurrentWorkspace:r,switchToWorkspace:b,switchingToId:m,setCurrentWorkspace:y,setOpen:S,workspacesToUse:I},t._id)})})})]}),F&&e.jsxs(e.Fragment,{children:[e.jsx(Ga,{}),e.jsx(Ha,{onCreated:()=>{h()}})]})]})]})]})},exports.calculateBillableSeats=dt,exports.calculateSeatOverageCents=pt,exports.calculateTotalSubscriptionCents=function(e,t,r,s){const n=ot(e,t,r);return null===n?null:void 0===s?n:n+(pt(e,t,r,s)??0)},exports.cleanBBParams=_e,exports.clearAuthIntent=function(){z(Me)},exports.cn=A,exports.consumeAuthIntent=qe,exports.createBBUrl=Te,exports.createCheckoutRedirectUrls=function(e,t){const r=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:Te({action:Ue.Checkout,status:We.Success,ws:e,screen:Re.Subscription},r),cancelUrl:Te({action:Ue.Checkout,status:We.Cancel,ws:e,screen:Re.Subscription},r)}},exports.createCreditPurchaseRedirectUrls=Fe,exports.eventEmitter=xe,exports.fillMcpTemplate=ms,exports.formatCents=tt,exports.formatDate=un,exports.formatDateTime=function(e,t="en-US"){return un(e,t,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})},exports.formatMinorAmountIntl=et,exports.formatOverageRate=function(e,t,r,s,n){if(null==e||e<0)return null;const a={...rt,...s},i=null!=t&&t>=1?t:1,o=Ge(r),c=Xe(e,r);return 1===i?`${o}${c}/${a.unit}`:`${o}${c}/${i.toLocaleString(n)} ${a.units}`},exports.formatOverageRateWithLabel=function(e,t,r,s,n,a,i){if(null==e||e<0)return null;const o={...rt,...a},c=null!=t&&t>=1?t:1,l=Ge(s),u=Xe(e,s);if(r){const e=n??(r.endsWith("s")?r:`${r}s`);return c>=2?`${l}${u}/${c.toLocaleString(i)} ${e}`:`${l}${u}/${r}`}return 1===c?`${l}${u}/${o.unit}`:`${l}${u}/${c.toLocaleString(i)} ${o.units}`},exports.formatQuotaIncludedOverage=function(e,t,r,s,n,a,i,o,c){const l={...rt,...i};if(!1===o)return null!=e?`${l.included}: ${e.toLocaleString(c)} (${l.hardLimit})`:i?.hardLimit??"Hard limit";const u=a??(r.endsWith("s")?r:`${r}s`),d=null!=n&&n>=2?`${n.toLocaleString(c)} ${u}`:r;return null!=e&&null!=t?`${l.included}: ${e.toLocaleString(c)}, ${l.afterThat} ${tt(t,s)}/${d}`:null!=e?`${l.included}: ${e.toLocaleString(c)}`:null!=t?`${l.afterIncluded}: ${tt(t,s)}/${d}`:"—"},exports.formatQuotaWithPrice=function(e,t,r={}){const{overageInCents:s=!0,currency:n}=r,a={...st,...r.labels},i=r.currencySymbol??Ge(n??"");if(null==e)return"—";const{included:o,overage:c}=e,l=`${o} ${a.included}`;if(!1===e.allowOverage)return`${l} (${a.hardLimit})`;if(null==c)return l;const u=Ze(n),d=s&&u>0?c/10**u:c,p="number"==typeof d&&Number.isFinite(d)?0===u?d.toLocaleString("en-US"):d.toFixed(u):String(c),m=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${l}, ${a.then} ${i}${p}${m}`},exports.formatUnixDate=function(e,t="en-US"){return e?new Date(1e3*e).toLocaleDateString(t,{year:"numeric",month:"short",day:"numeric"}):""},exports.getAvailableCurrenciesFromPlans=function(e){const t=new Set;for(const r of e)r.pricingVariants?.forEach(e=>{e.currency&&t.add(e.currency.toLowerCase())});return Array.from(t).sort()},exports.getBasePriceCents=ot,exports.getBillingIntervalAndCurrencyFromPriceId=function(e,t){if(!e)return null;for(const r of t){const t=r.pricingVariants;if(t?.length)for(const r of t){const t=r.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:r.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:r.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:r.currency}}}}return null},exports.getCurrencyDecimals=Ze,exports.getCurrencyFlag=function(e){return e&&e.trim()?Ve[e.trim().toLowerCase()]??"":""},exports.getCurrencySymbol=Ge,exports.getDisplayCurrency=function(e,t){const r=it(e,t);return r?r.currency:e.plan?.currency??""},exports.getPerSeatPriceCents=ut,exports.getPricingVariant=it,exports.getQuotaDisplayParts=function(e,t,r={}){if(null==e)return null;const{overageInCents:s=!0,currency:n,locale:a="en"}=r,{included:i,overage:o}=e;if(!(!1!==e.allowOverage))return{included:i,hasOverage:!1,allowOverage:!1,price:"",unit:""};if(null==o)return{included:i,hasOverage:!1,allowOverage:!0,price:"",unit:""};const c=Ze(n),l=s&&c>0?o/10**c:o,u=(n??"").trim().toUpperCase();let d;if(u&&"number"==typeof l&&Number.isFinite(l))try{d=new Intl.NumberFormat(a,{style:"currency",currency:u,minimumFractionDigits:c,maximumFractionDigits:c}).format(l)}catch{d=`${r.currencySymbol??Ge(n??"")}${l.toFixed(c)}`}else{d=`${r.currencySymbol??Ge(n??"")}${"number"==typeof l?l.toFixed(c):String(o)}`}return{included:i,hasOverage:!0,allowOverage:!0,price:d,unit:t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?`${e.unitSize.toLocaleString(a)} ${t}`:t||""}},exports.getQuotaDisplayValue=function(e,t){if(null==e)return null;const r=e[t??"monthly"];return r?{included:r.included,...void 0!==r.overage&&{overage:r.overage},...void 0!==r.unitSize&&{unitSize:r.unitSize},allowOverage:!1!==e.allowOverage}:null},exports.getQuotaDisplayWithVariant=function(e,t,r,s){const n=e.quotas?.[r];if(null==n)return null;const a=n[s];if(!a)return null;const i=ct(e,t,r,s);return{included:a.included,...void 0!==a.unitSize&&{unitSize:a.unitSize},...void 0!==i&&{overage:i},allowOverage:!1!==n.allowOverage}},exports.getQuotaOverageCents=ct,exports.getQuotaUnitLabelFromName=function(e,t="unit"){const r=(e||"").trim().toLowerCase();if(!r)return t;const s=r.split(/\s+/)[0]??r;return new Set(["series","species","status","analysis","basis","bus","campus","corpus","axis"]).has(s)?s:s.endsWith("ies")&&s.length>3?s.slice(0,-3)+"y":s.endsWith("ses")||s.endsWith("xes")||s.endsWith("zes")||s.endsWith("ches")||s.endsWith("shes")?s.slice(0,-2):s.endsWith("s")&&!s.endsWith("ss")&&s.length>1?s.slice(0,-1):s||t},exports.getSeatPricing=lt,exports.getStripePriceIdForInterval=function(e,t,r){const s=it(e,t);if(!s?.stripePrices)return null;const n=r===nt.Monthly?"monthlyPriceId":r===nt.Yearly?"yearlyPriceId":"quarterlyPriceId",a=r===nt.Monthly?"monthly":r===nt.Yearly?"yearly":void 0;return s.stripePrices[n]??(a?s.stripePrices[a]:void 0)??null},exports.getSvgImage=ra,exports.handleError=L,exports.hasPermission=function(e,t){const r=Pt(t);return Array.isArray(e)?e.every(e=>r.has(e)):r.has(e)},exports.invalidateCreditBalance=Se,exports.invalidateQuotaUsage=Pe,exports.invalidateSubscription=Ie,exports.isWorkspaceOwner=wt,exports.isZeroDecimalCurrency=function(e){return""!==(e??"").trim()&&0===Ze(e)},exports.mcpServerKey=hs,exports.mergeUIConfig=function(e,t){return t?Ps(e,t):e},exports.minorAmountToDisplay=Xe,exports.readBBParams=Oe,exports.resolveMaxUsers=mt,exports.resolvePermissions=Pt,exports.safeRedirect=Le,exports.saveAuthIntent=Be,exports.useAllQuotaUsage=Hr,exports.useBillingPortal=e=>{const{t:r}=Fr(),{api:s}=zr(),[n,a]=t.useState(!1),[i,o]=t.useState(null);return{openBillingPortal:t.useCallback(async t=>{if(!e)throw new Error("Workspace ID is required");a(!0),o(null);try{const r=t||window.location.href,n=await s.createBillingPortalSession(e,r);return n.url&&window.open(n.url,"_blank","noopener,noreferrer"),n}catch(t){const s=$(t,"errors.openBillingPortal",r);throw o(s),L(t,{component:"useBillingPortal",action:"openBillingPortal",metadata:{workspaceId:e}}),t}finally{a(!1)}},[e,s]),loading:n,error:i}},exports.useCancelSubscription=e=>{const{t:r}=Fr(),{api:s}=zr(),[n,a]=t.useState(!1),[i,o]=t.useState(null);return{cancelSubscription:t.useCallback(async()=>{if(!e)throw new Error("Workspace ID is required");a(!0),o(null);try{const t=await s.cancelSubscriptionAtPeriodEnd(e);return Ie(),t}catch(t){const s=$(t,"errors.cancelSubscription",r);throw o(s),L(t,{component:"useCancelSubscription",action:"cancelSubscription",metadata:{workspaceId:e}}),t}finally{a(!1)}},[s,e]),loading:n,error:i}},exports.useConnectedAgents=ln,exports.useConnectedAgentsApi=cn,exports.useConsumeCredits=es,exports.useCreateCheckoutSession=e=>{const{t:r}=Fr(),{api:s}=zr(),{getCheckoutStripeParams:n}=t.useContext(wr),[a,i]=t.useState(!1),[o,c]=t.useState(null);return{createCheckoutSession:t.useCallback(async t=>{if(!e)throw new Error("Workspace ID is required");i(!0),c(null);try{let r=t;if(n){const e=await n(t);e&&(r={...t,stripeOptions:{...t.stripeOptions,...e,metadata:{...t.stripeOptions?.metadata,...e.metadata},subscriptionMetadata:{...t.stripeOptions?.subscriptionMetadata,...e.subscriptionMetadata}}})}const a=await s.createCheckoutSession(e,r);return"trial_started"===a.type&&(Ie(),Pe()),a}catch(s){const n=$(s,"errors.createCheckout",r);throw c(n),L(s,{component:"useCreateCheckoutSession",action:"createCheckoutSession",metadata:{workspaceId:e,request:t}}),s}finally{i(!1)}},[s,e,n]),loading:a,error:o}},exports.useCreditBalance=Xr,exports.useCreditBalanceContext=is,exports.useCreditPackages=rs,exports.useCreditTransactions=(e,r)=>{const{t:s}=Fr(),{api:n}=zr(),[a,i]=t.useState([]),[o,c]=t.useState(0),[l,u]=t.useState(0),[d,p]=t.useState(1),[m,h]=t.useState(!1),[g,f]=t.useState(!1),[y,b]=t.useState(!1),[x,w]=t.useState(null),{begin:v,settle:k}=Or(),S=r?.type,C=r?.page,N=r?.limit,P=t.useCallback(async()=>{if(!e)return v(),i([]),c(0),u(0),p(1),h(!1),f(!1),void b(!1);const t=v();b(!0),w(null);try{const r=await n.getCreditTransactions(e,{type:S,page:C,limit:N});if(t.signal.aborted)return;i(r.docs||[]),c(r.totalDocs||0),u(r.totalPages||0),p(r.page||1),h(r.hasNextPage||!1),f(r.hasPrevPage||!1)}catch(r){if(t.signal.aborted)return;const n=$(r,"errors.fetchCreditTransactions",s);w(n),L(r,{component:"useCreditTransactions",action:"fetchTransactions",metadata:{workspaceId:e}})}finally{k(t)&&b(!1)}},[n,e,S,C,N,v,k]);return t.useEffect(()=>{P()},[P]),{transactions:a,totalDocs:o,totalPages:l,page:d,hasNextPage:m,hasPrevPage:g,loading:y,error:x,refetch:P}},exports.useDevices=Rn,exports.useDevicesApi=Wn,exports.useExpiringCredits=(e,r)=>{const{t:s}=Fr(),{api:n}=zr(),[a,i]=t.useState(null),[o,c]=t.useState(!1),[l,u]=t.useState(null),{begin:d,settle:p}=Or(),m=t.useCallback(async()=>{if(!e)return d(),i(null),void c(!1);const t=d();c(!0),u(null);try{const s=await n.getExpiringCredits(e,r);if(t.signal.aborted)return;i(s)}catch(n){if(t.signal.aborted)return;const a=$(n,"errors.fetchExpiringCredits",s);u(a),L(n,{component:"useExpiringCredits",action:"fetchExpiring",metadata:{workspaceId:e,days:r}})}finally{p(t)&&c(!1)}},[n,e,r,d,p]);return t.useEffect(()=>{m()},[m]),{expiringCredits:a?.expiringCredits??0,buckets:a?.buckets??[],days:a?.days??r??7,loading:o,error:l,refetch:m}},exports.useFullScreenLoader=ds,exports.useInvoice=(e,r)=>{const{t:s}=Fr(),{api:n}=zr(),[a,i]=t.useState(null),[o,c]=t.useState(!1),[l,u]=t.useState(null),{begin:d,settle:p}=Or(),m=t.useCallback(async()=>{if(!e||!r)return d(),i(null),void c(!1);const t=d();c(!0),u(null);try{const s=await n.getInvoice(e,r);if(t.signal.aborted)return;i(s.invoice)}catch(n){if(t.signal.aborted)return;const a=$(n,"errors.fetchInvoice",s);u(a),L(n,{component:"useInvoice",action:"fetchInvoice",metadata:{workspaceId:e,invoiceId:r}})}finally{p(t)&&c(!1)}},[n,e,r,d,p]);return t.useEffect(()=>{m()},[m]),{invoice:a,loading:o,error:l,refetch:m}},exports.useInvoices=(e,r=10,s)=>{const{t:n}=Fr(),{api:a}=zr(),[i,o]=t.useState([]),[c,l]=t.useState(!1),[u,d]=t.useState(!1),[p,m]=t.useState(null),{begin:h,settle:g}=Or(),f=t.useCallback(async()=>{if(!e)return h(),o([]),l(!1),void d(!1);const t=h();d(!0),m(null);try{const n=await a.listInvoices(e,r,s);if(t.signal.aborted)return;o(n.invoices||[]),l(n.has_more||!1)}catch(a){if(t.signal.aborted)return;const i=$(a,"errors.fetchInvoices",n);m(i),L(a,{component:"useInvoices",action:"fetchInvoices",metadata:{workspaceId:e,limit:r,startingAfter:s}})}finally{g(t)&&d(!1)}},[a,e,r,s,h,g]);return t.useEffect(()=>{f()},[f]),{invoices:i,hasMore:c,loading:u,error:p,refetch:f}},exports.useMcpConnection=fs,exports.usePermissionConfig=xs,exports.usePermissions=an,exports.usePlanGroup=Jr,exports.usePlanGroupVersions=e=>{const{t:r}=Fr(),{api:s}=zr(),[n,a]=t.useState(null),[i,o]=t.useState(!1),[c,l]=t.useState(null),{begin:u,settle:d}=Or(),p=t.useCallback(async()=>{if(!e)return u(),a(null),void o(!1);const t=u();o(!0),l(null);try{const r=await s.getPlanGroupVersions(e);if(t.signal.aborted)return;a(r)}catch(s){if(t.signal.aborted)return;const n=$(s,"errors.fetchPlanGroupVersions",r);l(n),L(s,{component:"usePlanGroupVersions",action:"fetchVersions",metadata:{workspaceId:e}})}finally{d(t)&&o(!1)}},[s,e,u,d]);return t.useEffect(()=>{p()},[p]),{versions:n,loading:i,error:c,refetch:p}},exports.usePublicCreditPackages=ss,exports.usePublicPlanGroupVersion=e=>{const{t:r}=Fr(),{api:s}=zr(),[n,a]=t.useState(null),[i,o]=t.useState(!1),[c,l]=t.useState(null),{begin:u,settle:d}=Or(),p=t.useCallback(async()=>{if(!e)return u(),a(null),void o(!1);const t=u();o(!0),l(null);try{const r=await s.getPlanGroupVersion(e);if(t.signal.aborted)return;a(r)}catch(s){if(t.signal.aborted)return;const n=$(s,"errors.fetchPlanGroupVersion",r);l(n),L(s,{component:"usePublicPlanGroupVersion",action:"fetchVersion",metadata:{groupVersionId:e}})}finally{d(t)&&o(!1)}},[s,e,u,d]);return t.useEffect(()=>{p()},[p]),{planGroupVersion:n,loading:i,error:c,refetch:p}},exports.usePublicPlans=Vr,exports.usePurchaseCredits=ts,exports.usePushNotifications=function(){const e=t.useContext(zs);if(!e)throw new Error("usePushNotifications must be used within PushNotificationProvider");return e},exports.useQuotaUsageContext=ks,exports.useQuotaUsageStatus=(e,r)=>{const{t:s}=Fr(),{api:n}=zr(),[a,i]=t.useState(null),[o,c]=t.useState(!1),[l,u]=t.useState(null),{begin:d,settle:p}=Or(),m=t.useCallback(async()=>{if(!e||!r)return d(),i(null),void c(!1);const t=d();c(!0),u(null);try{const s=await n.getQuotaUsageStatus(e,r);if(t.signal.aborted)return;i(s)}catch(n){if(t.signal.aborted)return;const a=$(n,"errors.fetchQuotaUsage",s);u(a),L(n,{component:"useQuotaUsageStatus",action:"fetchStatus",metadata:{workspaceId:e,quotaSlug:r}})}finally{p(t)&&c(!1)}},[n,e,r,d,p]);return t.useEffect(()=>{m()},[m]),{status:a,loading:o,error:l,refetch:m}},exports.useRecordUsage=e=>{const{t:r}=Fr(),{api:s}=zr(),[n,a]=t.useState(!1),[i,o]=t.useState(null);return{recordUsage:t.useCallback(async t=>{if(!e)throw new Error("Workspace ID is required");a(!0),o(null);try{const r=await s.recordUsage(e,t);return Pe(),r}catch(s){const n=$(s,"errors.recordUsage",r);throw o(n),L(s,{component:"useRecordUsage",action:"recordUsage",metadata:{workspaceId:e,request:t}}),s}finally{a(!1)}},[s,e]),loading:n,error:i}},exports.useResumeSubscription=e=>{const{t:r}=Fr(),{api:s}=zr(),[n,a]=t.useState(!1),[i,o]=t.useState(null);return{resumeSubscription:t.useCallback(async()=>{if(!e)throw new Error("Workspace ID is required");a(!0),o(null);try{const t=await s.resumeSubscription(e);return Ie(),t}catch(t){const s=$(t,"errors.resumeSubscription",r);throw o(s),L(t,{component:"useResumeSubscription",action:"resumeSubscription",metadata:{workspaceId:e}}),t}finally{a(!1)}},[s,e]),loading:n,error:i}},exports.useSaaSAuth=Ls,exports.useSaaSOs=Mr,exports.useSaaSSettings=qr,exports.useSaaSWorkspaces=Fs,exports.useSeatStatus=function(e,r){const{response:s}=Zr();return t.useMemo(()=>{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 t=e.users?.length??0,n=s?.planVersion,a=s?.subscription,i=e.billingCurrency||"usd",o=mt({planVersion:n,currency:i,settingsMaxUsers:r?.settingsMaxUsers}),{maxUsers:c,hasSeatPricing:l,includedSeats:u}=o,d=l?Math.max(0,t-u):0,p=c>0?Math.max(0,c-t):1/0,m=c>0&&t>=c,h=c>0&&t>=.8*c&&!m,g=l&&n?ut(n,i,a?.billingInterval??"monthly"):null,f=ht({memberCount:t,maxUsersConfig:o});return{hasSeatPricing:l,memberCount:t,includedSeats:u,maxUsers:c,maxSeats:c,limitSource:o.source,billableSeats:d,availableSeats:p,isAtMax:m,isNearMax:h,perSeatPriceCents:g,currency:i,canInvite:f.canInvite,inviteBlockReason:f.blockReason,inviteBlockMessageKey:f.blockMessageKey,inviteBlockMessageValues:f.blockMessageValues}},[s,e,r?.settingsMaxUsers])},exports.useSessions=Ln,exports.useSessionsApi=Dn,exports.useSubscription=Gr,exports.useSubscriptionContext=Zr,exports.useSubscriptionManagement=(e,r)=>{const s=Gr(e),n=Jr(e,r),a=Kr(e),i=t.useCallback(async()=>{await Promise.all([s.refetch(),n.refetch()])},[s.refetch,n.refetch]);return{subscription:s.subscription,planGroup:n.planGroup,loading:s.loading||n.loading||a.loading,error:s.error||n.error||a.error,updateSubscription:a.updateSubscription,refetch:i}},exports.useTranslation=Fr,exports.useTrialStatus=function(){const{response:e}=Zr();return t.useMemo(()=>{const t=e?.subscription;if(!t||"trialing"!==t.subscriptionStatus)return{isTrialing:!1,daysRemaining:0,trialEndsAt:null,trialStartedAt:null,isTrialEnding:!1};const r=La(t.trialEnd)??La(t.stripeCurrentPeriodEnd),s=La(t.trialStart),n=r?Math.max(0,Math.ceil((r.getTime()-Date.now())/864e5)):0;return{isTrialing:!0,daysRemaining:n,trialEndsAt:r,trialStartedAt:s,isTrialEnding:n<=3}},[e])},exports.useUIConfig=Ns,exports.useUIVisibility=on,exports.useUpdateSubscription=Kr,exports.useUsageLogs=(e,r,s)=>{const{t:n}=Fr(),{api:a}=zr(),[i,o]=t.useState([]),[c,l]=t.useState(0),[u,d]=t.useState(0),[p,m]=t.useState(1),[h,g]=t.useState(!1),[f,y]=t.useState(!1),[b,x]=t.useState(!1),[w,v]=t.useState(null),{begin:k,settle:S}=Or(),C=s?.from,N=s?.to,P=s?.source,E=s?.page,j=s?.limit,I=t.useCallback(async()=>{if(!e)return k(),o([]),l(0),d(0),m(1),g(!1),y(!1),void x(!1);const t=k();x(!0),v(null);try{const s={...r&&{quotaSlug:r},...C&&{from:C},...N&&{to:N},...P&&{source:P},...E&&{page:E},...j&&{limit:j}},n=await a.getUsageLogs(e,s);if(t.signal.aborted)return;o(n.docs||[]),l(n.totalDocs||0),d(n.totalPages||0),m(n.page||1),g(n.hasNextPage||!1),y(n.hasPrevPage||!1)}catch(s){if(t.signal.aborted)return;const a=$(s,"errors.fetchUsageLogs",n);v(a),L(s,{component:"useUsageLogs",action:"fetchLogs",metadata:{workspaceId:e,quotaSlug:r}})}finally{S(t)&&x(!1)}},[a,e,r,C,N,P,E,j,k,S]);return t.useEffect(()=>{I()},[I]),{logs:i,totalDocs:c,totalPages:u,page:p,hasNextPage:h,hasPrevPage:f,loading:b,error:w,refetch:I}},exports.useUserAttributes=function(){const e=t.useContext(Js);if(void 0===e)throw new Error("useUserAttributes must be used within a UserProvider");return t.useMemo(()=>({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])},exports.useUserFeatures=xa,exports.useWorkspaceApiWithOs=zr,exports.validateInvite=ht,exports.validateRedirectUrl=De,exports.workspaceEmojis=sa,exports.workspaceSettingsManager=Us;