@buildbase/sdk 0.0.51 → 0.0.54
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.
- package/AGENTS.md +24 -8
- package/CHANGELOG.md +102 -0
- package/README.md +283 -33
- package/dist/css/styles.css +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1248 -76
- package/dist/index.mjs +1 -1
- package/dist/mcp/index.cjs +1 -0
- package/dist/mcp/index.d.ts +1956 -0
- package/dist/mcp/index.mjs +1 -0
- package/dist/react/chunks/{SettingsDialog-DitAiAqr.cjs → SettingsDialog-B28WJsAr.cjs} +1 -1
- package/dist/react/chunks/{SettingsDialog-uVKFxlal.mjs → SettingsDialog-blhppbNm.mjs} +1 -1
- package/dist/react/chunks/{SubscriptionDialog-P0GlXEyn.mjs → SubscriptionDialog-BTWVX3cH.mjs} +1 -1
- package/dist/react/chunks/{SubscriptionDialog-Cg-qYVKr.cjs → SubscriptionDialog-QKmwvJU1.cjs} +1 -1
- package/dist/react/chunks/ar-1Z1MOGAP.mjs +2 -0
- package/dist/react/chunks/ar-VGzBv3AZ.cjs +2 -0
- package/dist/react/chunks/de-BjdDg60Y.cjs +2 -0
- package/dist/react/chunks/de-CXUItplO.mjs +2 -0
- package/dist/react/chunks/es-BBPsSZUp.cjs +2 -0
- package/dist/react/chunks/es-BTbzVutz.mjs +2 -0
- package/dist/react/chunks/fr-Cax48X_S.cjs +2 -0
- package/dist/react/chunks/fr-DPMeOQu3.mjs +2 -0
- package/dist/react/chunks/hi-BJqvpG6d.cjs +2 -0
- package/dist/react/chunks/hi-JfJx-LV7.mjs +2 -0
- package/dist/react/chunks/ja-CDGtLzTk.mjs +2 -0
- package/dist/react/chunks/ja-DvVyj5xX.cjs +2 -0
- package/dist/react/chunks/react-6QJCOE-D.cjs +2 -0
- package/dist/react/chunks/react-CC6T7Zky.mjs +2 -0
- package/dist/react/chunks/zh-BAcqxkxk.cjs +2 -0
- package/dist/react/chunks/zh-BNZ2Ooe8.mjs +2 -0
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.d.ts +98 -43
- package/dist/react/index.mjs +1 -1
- package/package.json +20 -5
- package/dist/react/chunks/ar-SrPOJXdL.mjs +0 -2
- package/dist/react/chunks/ar-a3aRbPCs.cjs +0 -2
- package/dist/react/chunks/de-DE3_z7r0.cjs +0 -2
- package/dist/react/chunks/de-xnPl61SS.mjs +0 -2
- package/dist/react/chunks/es-C_xcyGtp.cjs +0 -2
- package/dist/react/chunks/es-CyuBtosP.mjs +0 -2
- package/dist/react/chunks/fr-BMu7Bk4k.cjs +0 -2
- package/dist/react/chunks/fr-CxuDLZ27.mjs +0 -2
- package/dist/react/chunks/hi-CQ215yc9.cjs +0 -2
- package/dist/react/chunks/hi-CpuvyorS.mjs +0 -2
- package/dist/react/chunks/ja-DIJ_xCIi.mjs +0 -2
- package/dist/react/chunks/ja-DK6Buuws.cjs +0 -2
- package/dist/react/chunks/react-C2ikFWBG.cjs +0 -2
- package/dist/react/chunks/react-CCukNQ4q.mjs +0 -2
- package/dist/react/chunks/zh-CYQwZiBL.mjs +0 -2
- package/dist/react/chunks/zh-Dt-apS2s.cjs +0 -2
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use client";
|
|
2
|
-
import{jsxs as e,jsx as t,Fragment as r}from"react/jsx-runtime";import*as s from"react";import n,{Component as a,useRef as i,useMemo as o,createContext as c,useReducer as l,useContext as u,useEffect as d,useCallback as p,useState as h,Suspense as m,lazy as g}from"react";import{clsx as f}from"clsx";import{twMerge as w}from"tailwind-merge";import y from"intl-messageformat";import{zodResolver as b}from"@hookform/resolvers/zod";import{Controller as k,FormProvider as v,useFormContext as S,useForm as C}from"react-hook-form";import{Slot as P}from"@radix-ui/react-slot";import{cva as N}from"class-variance-authority";import{Loader2 as x,Bot as E,ChevronRight as I,Building2 as R,RefreshCcw as U,Search as W,Users as A,Plus as T,Smile as F,Image as _}from"lucide-react";import*as O from"@radix-ui/react-label";import{z as D}from"zod";import*as $ from"@radix-ui/react-avatar";import*as L from"@radix-ui/react-dialog";import{Cross2Icon as M,CheckIcon as B}from"@radix-ui/react-icons";import*as j from"@radix-ui/react-radio-group";import*as q from"@radix-ui/react-scroll-area";import*as V from"@radix-ui/react-separator";function z(...e){return w(f(e))}let G=!0;function J(e,...t){G&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(e,...t)}function K(e,...t){console.error(e,...t)}function H(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}async function Y(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 Q(e,t="Request failed"){if(!e.ok){let r=t;try{const t=await Y(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 Y(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class Z 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,Z)}}const X=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&&(G=e.enableLogging)}({enableLogging:e.enableConsoleLogging})}handleError(e,t={}){if(H(e))return;const r=e instanceof Error?e:new Z("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",t),s=r instanceof Z?r:new Z(r.message,"SDK_ERROR",t,r);if(this.config.enableConsoleLogging&&J(`[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){K("[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 ee(e,t={}){X.handleError(e,t)}function te(e,t={}){return!H(e)&&(X.handleError(e,t),!0)}function re(e,t,r){return e instanceof Error?e.message:r(t)}function se(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return ee(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function ne(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){ee(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}function ae(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){ee(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}const ie="saas-session-id",oe="code",ce="state";function le(e){ne(ie,e)}function ue(){return function(){if("undefined"==typeof window)return null;try{return se(ie)}catch(e){return ee(e,{component:"auth-utils",action:"getSessionId",metadata:{key:ie}}),null}}()}function de(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get(oe)}catch(e){return ee(e,{component:"auth-utils",action:"getTokenFromUrl",metadata:{param:oe}}),null}}function pe(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.delete(oe),e.searchParams.delete(ce),window.history.replaceState({},"",e.toString())}catch(e){ee(e,{component:"auth-utils",action:"removeTokenFromUrl",metadata:{param:oe}})}}const he=new WeakSet,me="SDK is not ready (missing serverUrl, version, or orgId)";class ge{constructor(e){this.serverUrl=e.serverUrl,this.version=e.version,this.orgId=e.orgId,this.requireOrgId=e.requireOrgId??!1,this.basePath=e.basePath??"public",this._sessionId=e.sessionId,this._timeout=e.timeout??3e4,this._maxRetries=e.maxRetries??0,this._debug=e.debug??!1,this._customHeaders=e.headers??{},this._onError=e.onError,this._onUnauthorized=e.onUnauthorized,this._fetch=e.fetch??globalThis.fetch}ensureReady(){if(!this.serverUrl?.trim()||!this.version)throw new Error(me);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(me)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:function(){const e=ue(),t={};return e&&(t["x-session-id"]=e),t}()}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){he.has(e)||(he.add(e),this._onError?.(e,t))}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}async executeFetchUrl(e,t,r){const s=(t.method??"GET").toUpperCase(),n=r??e,a=this.buildHeaders(t),i={...t,headers:a};let o,c;if(this._timeout>0){c=new AbortController;const e=c;o=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 l=async r=>{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 t=this._fetch.bind(globalThis),n=await t(e,i);if(this._debug&&console.log(`[BuildBase] ${s} ${e} → ${n.status}`),401===n.status&&this._onUnauthorized&&this._onUnauthorized(),n.status>=500&&r<this._maxRetries){const e=Math.min(1e3*Math.pow(2,r),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${r+1}/${this._maxRetries})`),await new Promise(t=>setTimeout(t,e)),l(r+1)}return n}catch(e){if(e instanceof Error&&"AbortError"===e.name){if(c?.signal.aborted&&!t.signal?.aborted){const e=new Error(`Request timeout after ${this._timeout}ms: ${s} ${n}`);throw this.reportError(e,{method:s,path:n}),e}throw e}if(r<this._maxRetries){const e=Math.min(1e3*Math.pow(2,r),1e4);return this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${r+1}/${this._maxRetries})`),await new Promise(t=>setTimeout(t,e)),l(r+1)}throw e instanceof Error&&this.reportError(e,{method:s,path:n}),e}};try{return await l(0)}finally{void 0!==o&&clearTimeout(o)}}async fetchJson(e,t={},r="Request failed"){this.ensureReady();try{const s=await this.executeFetch(e,t);return await Q(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 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 fe extends ge{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,r=await this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});return r.ok||await this.throwResponseError(r,"Failed to initiate authentication"),r.json()}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}}class we extends ge{constructor(e){super({...e,basePath:"beta",requireOrgId:!0})}getAuthHeaders(){return{}}async fetchConfig(){return this.fetchJson(`config?orgId=${encodeURIComponent(this.orgId)}`,{},"Failed to fetch beta form configuration")}async submitBetaUser(e){return this.fetchJson("submit",{method:"POST",body:JSON.stringify(e)},"Failed to submit beta user request")}}let ye=class{constructor(e){this.api=new we(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 be extends ge{constructor(e){super(e)}async list(e){const t=await this.fetchJson("connected-agents",{signal:e},"Failed to load connected agents");return t?.agents??[]}async revoke(e){await this.fetchJson("connected-agents/revoke",{method:"POST",body:JSON.stringify({clientId:e})},"Failed to disconnect agent")}}class ke extends ge{constructor(e){super({...e,requireOrgId:!0})}async getVapidPublicKey(){return this.fetchJson("push/vapid-public-key")}async subscribe(e,t){await this.fetchJson("push/subscribe",{method:"POST",body:JSON.stringify({endpoint:e.endpoint,keys:e.keys,userAgent:t})})}async unsubscribe(e){await this.fetchJson("push/unsubscribe",{method:"DELETE",body:JSON.stringify({endpoint:e})})}}class ve extends ge{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class Se extends ge{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user attributes");const 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 Ce extends ge{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(){return this.fetchJson("workspaces",{},"Failed to fetch workspaces")}async createWorkspace(e){return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e)},"Failed to create workspace")}async updateWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t)},"Failed to update workspace")}async deleteWorkspace(e){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"DELETE"},"Failed to delete workspace")}async getWorkspaceUsers(e){return this.fetchJson(this.apiPath`workspaces/${e}/users`,{},"Failed to fetch workspace users")}async addUser(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t)},"Failed to invite member")}async removeUser(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE"},"Failed to remove user")}async updateUser(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(r)},"Failed to update user")}async updateSettings(e){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e)},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t})},"Failed to update workspace permissions")}async getFeatures(){return this.fetchJson("workspaces/features",{},"Failed to fetch features")}async updateFeature(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:r}})},"Failed to update feature")}async getWorkspace(e){return this.fetchJson(this.apiPath`workspaces/${e}`,{},"Failed to fetch workspace")}async getProfile(){return this.fetchJson("profile",{},"Failed to fetch profile")}async updateUserProfile(e){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e)},"Failed to update user profile")}async getPasskeys(){const e=await this.fetchJson("passkeys",{},"Failed to fetch passkeys");return e?.passkeys??[]}async renamePasskey(e,t){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t})},"Failed to rename passkey")}async deletePasskey(e){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"DELETE"},"Failed to remove passkey")}async getCurrentSubscription(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription`);return t.ok||await this.throwResponseError(t,"Failed to fetch subscription"),this.unwrapResponse(t,"Failed to fetch subscription")}async getPlanGroup(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/plan-group`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group"),this.unwrapResponse(t,"Failed to fetch plan group")}async getPlanGroupByVersion(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`);return r.ok||await this.throwResponseError(r,"Failed to fetch plan group version"),this.unwrapResponse(r,"Failed to fetch plan group version")}async getPlanGroupVersions(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/plan-group/versions`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group versions"),this.unwrapResponse(t,"Failed to fetch plan group versions")}async getPublicPlans(e){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");const t=await this.fetchResponse(this.apiPath`${this.orgId}/plans/${encodeURIComponent(e)}`);return t.ok||await this.throwResponseError(t,"Failed to fetch plans"),this.unwrapResponse(t,"Failed to fetch plans")}async getPublicCreditPackages(){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");const e=await this.fetchResponse(this.apiPath`${this.orgId}/credit-packages`);return e.ok||await this.throwResponseError(e,"Failed to fetch credit packages"),this.unwrapResponse(e,"Failed to fetch credit packages")}async getPlanGroupVersion(e){const t=await this.fetchResponse(this.apiPath`plan-group-versions/${e}`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group version"),this.unwrapResponse(t,"Failed to fetch plan group version")}async createCheckoutSession(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to create checkout session"),this.unwrapResponse(r,"Failed to create checkout session")}async selectFreePlan(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t})});return r.ok||await this.throwResponseError(r,"Failed to select free plan"),r.json()}async updateSubscription(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to update subscription"),this.unwrapResponse(r,"Failed to update subscription")}async createBillingPortalSession(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{})})}async listInvoices(e,t=10,r){const s=new URLSearchParams;s.append("limit",t.toString()),r&&s.append("starting_after",r);const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/invoices`+`?${s.toString()}`);return n.ok||await this.throwResponseError(n,"Failed to fetch invoices"),this.unwrapResponse(n,"Failed to fetch invoices")}async getInvoice(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/invoices/${t}`);return r.ok||await this.throwResponseError(r,"Failed to fetch invoice"),this.unwrapResponse(r,"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST"});return t.ok||await this.throwResponseError(t,"Failed to cancel subscription"),this.unwrapResponse(t,"Failed to cancel subscription")}async resumeSubscription(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/resume`,{method:"POST"});return t.ok||await this.throwResponseError(t,"Failed to resume subscription"),this.unwrapResponse(t,"Failed to resume subscription")}async recordUsage(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to record usage"),this.unwrapResponse(r,"Failed to record usage")}async recordUsageBatch(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to record batch usage"),this.unwrapResponse(r,"Failed to record batch usage")}async getQuotaUsageStatus(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`);return r.ok||await this.throwResponseError(r,"Failed to fetch quota usage status"),this.unwrapResponse(r,"Failed to fetch quota usage status")}async getAllQuotaUsage(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage/all`);return t.ok||await this.throwResponseError(t,"Failed to fetch all quota usage"),this.unwrapResponse(t,"Failed to fetch all quota usage")}async getUsageLogs(e,t){const r=new URLSearchParams;t?.quotaSlug&&r.append("quotaSlug",t.quotaSlug),t?.from&&r.append("from",t.from),t?.to&&r.append("to",t.to),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),n=this.apiPath`workspaces/${e}/subscription/usage/logs`+(s?`?${s}`:""),a=await this.fetchResponse(n);return a.ok||await this.throwResponseError(a,"Failed to fetch usage logs"),this.unwrapResponse(a,"Failed to fetch usage logs")}async sendNotification(e,t,r,s){const n={event:t};return r&&(n.userId=r),s&&(n.data=s),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(n)},"Failed to send notification")}async getNotificationEvents(e){return this.fetchJson(this.apiPath`workspaces/${e}/notification-events`,{},"Failed to fetch notification events")}async getNotificationPreferences(e){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t})},"Failed to update notification preferences")).notificationPreferences??{}}async getCreditBalance(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/credits`);return t.ok||await this.throwResponseError(t,"Failed to fetch credit balance"),this.unwrapResponse(t,"Failed to fetch credit balance")}async consumeCredits(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t)});if(!r.ok){if(402===r.status){const e=await r.json().catch(()=>({})),t=new Error(e.message||"Insufficient credits");throw t.available=e.available,t.requested=e.requested,t.code="INSUFFICIENT_CREDITS",t}await this.throwResponseError(r,"Failed to consume credits")}return this.unwrapResponse(r,"Failed to consume credits")}async purchaseCredits(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to create credit purchase checkout"),this.unwrapResponse(r,"Failed to create credit purchase checkout")}async getCreditPackages(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/packages`);t.ok||await this.throwResponseError(t,"Failed to fetch credit packages");const r=await this.unwrapResponse(t,"Failed to fetch credit packages");return r.docs??r}async getCreditTransactions(e,t){const r=new URLSearchParams;t?.type&&r.append("type",t.type),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),n=this.apiPath`workspaces/${e}/credits/transactions`+(s?`?${s}`:""),a=await this.fetchResponse(n);return a.ok||await this.throwResponseError(a,"Failed to fetch credit transactions"),this.unwrapResponse(a,"Failed to fetch credit transactions")}async getCreditBuckets(e,t){const r=new URLSearchParams;t?.status&&r.append("status",t.status),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),n=this.apiPath`workspaces/${e}/credits/buckets`+(s?`?${s}`:""),a=await this.fetchResponse(n);return a.ok||await this.throwResponseError(a,"Failed to fetch credit buckets"),this.unwrapResponse(a,"Failed to fetch credit buckets")}async getExpiringCredits(e,t){const r=t?`?days=${t}`:"",s=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/expiring`+r);return s.ok||await this.throwResponseError(s,"Failed to fetch expiring credits"),this.unwrapResponse(s,"Failed to fetch expiring credits")}}var Pe;function Ne(e){return Boolean(e?.serverUrl&&e?.version&&e?.orgId)}!function(e){e.V1="v1"}(Pe||(Pe={}));const xe={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 Ee{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){ee(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}}async emitUserCreated(e){await this.emit(xe.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(xe.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(xe.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(xe.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,r){await this.emit(xe.WorkspaceUserAdded,{userId:e,workspace:t,role:r})}async emitWorkspaceUserRemoved(e,t,r){await this.emit(xe.WorkspaceUserRemoved,{userId:e,workspace:t,role:r})}async emitWorkspaceUserRoleChanged(e,t,r,s){await this.emit(xe.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:r,newRole:s})}async emitWorkspaceCreated(e){await this.emit(xe.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(xe.WorkspaceDeleted,{workspace:e})}}const Ie=new Ee;function Re(){const e=new Set;return{subscribe:t=>(e.add(t),()=>{e.delete(t)}),invalidate(){e.forEach(e=>e())},reset(){e.clear()}}}const Ue=Re(),We=Ue.subscribe,Ae=Ue.invalidate,Te=Re(),Fe=Te.subscribe,_e=Te.invalidate,Oe=Re(),De=Oe.subscribe,$e=Oe.invalidate,Le="bb",Me={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",Invite:"invite"},Be={Success:"success",Cancel:"cancel",Error:"error"},je={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function qe(e,t){let r;try{const e=t||("undefined"!=typeof window?window.location.href:"https://localhost");r=new URL(e),r.search=""}catch{r=new URL("https://localhost")}return r.searchParams.set(Le,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),r.toString()}function Ve(e,t){const r=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:qe({action:Me.Checkout,status:Be.Success,ws:e,screen:je.Subscription},r),cancelUrl:qe({action:Me.Checkout,status:Be.Cancel,ws:e,screen:je.Subscription},r)}}function ze(e,t){const r=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:qe({action:Me.CreditPurchase,status:Be.Success,ws:e,screen:je.Credits},r),cancelUrl:qe({action:Me.CreditPurchase,status:Be.Cancel,ws:e,screen:je.Credits},r)}}function Ge(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(Le);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 Je(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(Le)&&(e.searchParams.delete(Le),window.history.replaceState({},"",e.toString()))}catch{}}function Ke(e){if(!e||"string"!=typeof e)return null;try{const t=new URL(e);return"https:"===t.protocol?e:"http:"!==t.protocol||"localhost"!==t.hostname&&"127.0.0.1"!==t.hostname&&"::1"!==t.hostname?null:e}catch{return null}}function He(e,t="/"){if("undefined"==typeof window||!window.location)return!1;const r=Ke(e);return window.location.href=r??t,!0}const Ye="saas-auth-intent";function Qe(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function Ze(e){Ke(e)&&function(e,t){try{ne(e,JSON.stringify(t))}catch(t){ee(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}(Ye,{returnUrl:e,createdAt:Date.now()})}function Xe(){const e=function(e,t){const r=se(e);if(!r)return null;try{const s=JSON.parse(r);return t&&!t(s)?(ee(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),ae(e),null):s}catch(t){return ee(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),ae(e),null}}(Ye,Qe);return ae(Ye),e?Date.now()-e.createdAt>6e5?null:Ke(e.returnUrl):null}function et(){ae(Ye)}const tt={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:"฿"},rt={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function st(e){return e&&e.trim()?rt[e.trim().toLowerCase()]??"":""}function nt(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return tt[t]??t.toUpperCase()}const at=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],it=at.map(e=>({value:e,label:`${e.toUpperCase()} (${nt(e)})`}));function ot(e,t){return nt(t)+(e/100).toFixed(2)}const ct={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included"};function lt(e,t,r,s){if(null==e||e<0)return null;const n={...ct,...s},a=null!=t&&t>=1?t:1,i=nt(r),o=(e/100).toFixed(2);return 1===a?`${i}${o}/${n.unit}`:`${i}${o}/${a.toLocaleString()} ${n.units}`}function ut(e,t,r,s,n,a){if(null==e||e<0)return null;const i={...ct,...a},o=null!=t&&t>=1?t:1,c=nt(s),l=(e/100).toFixed(2);if(r){const e=n??(r.endsWith("s")?r:`${r}s`);return o>=2?`${c}${l}/${o.toLocaleString()} ${e}`:`${c}${l}/${r}`}return 1===o?`${c}${l}/${i.unit}`:`${c}${l}/${o.toLocaleString()} ${i.units}`}function dt(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}function pt(e,t,r,s,n,a,i,o){const c={...ct,...i};if(!1===o)return null!=e?`${c.included}: ${e.toLocaleString()} (${c.hardLimit??"hard limit"})`:c.hardLimit??"Hard limit";const l=a??(r.endsWith("s")?r:`${r}s`),u=null!=n&&n>=2?`${n.toLocaleString()} ${l}`:r;return null!=e&&null!=t?`${c.included}: ${e.toLocaleString()}, ${c.afterThat} ${ot(t,s)}/${u}`:null!=e?`${c.included}: ${e.toLocaleString()}`:null!=t?`${c.afterIncluded}: ${ot(t,s)}/${u}`:"—"}function ht(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}const mt={included:"included",then:"then"};function gt(e,t,r={}){const{overageInCents:s=!0,currency:n}=r,a=r.labels??mt,i=r.currencySymbol??nt(n??"");if(null==e)return"—";const{included:o,overage:c}=e,l=`${o} ${a.included}`;if(!1===e.allowOverage)return`${l} (hard limit)`;if(null==c)return l;const u=s?c/100:c,d="number"==typeof u&&Number.isFinite(u)?u.toFixed(2):String(c),p=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${l}, ${a.then} ${i}${d}${p}`}function ft(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=s?o/100:o,l=(n??"").trim().toUpperCase();let u;if(l&&"number"==typeof c&&Number.isFinite(c))try{u=new Intl.NumberFormat(a,{style:"currency",currency:l,minimumFractionDigits:2}).format(c)}catch{u=`${r.currencySymbol??nt(n??"")}${c.toFixed(2)}`}else{u=`${r.currencySymbol??nt(n??"")}${"number"==typeof c?c.toFixed(2):String(o)}`}return{included:i,hasOverage:!0,allowOverage:!0,price:u,unit:t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?`${e.unitSize.toLocaleString(a)} ${t}`:t||""}}const wt={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},yt={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"},bt={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},kt={Feature:"feature",Limit:"limit",Quota:"quota"},vt={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},St={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},Ct={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},Pt={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"};function Nt(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 xt(e,t,r){const s=Nt(e,t);if(!s?.basePricing)return null;const n=s.basePricing[r];return null!=n?n:null}function Et(e,t,r){const s=Nt(e,t);if(!s?.stripePrices)return null;const n=r===wt.Monthly?"monthlyPriceId":r===wt.Yearly?"yearlyPriceId":"quarterlyPriceId",a=r===wt.Monthly?"monthly":r===wt.Yearly?"yearly":void 0;return s.stripePrices[n]??(a?s.stripePrices[a]:void 0)??null}function It(e,t,r,s){const n=Nt(e,t),a=n?.quotaOverages?.[r];if(a)return a[s]}function Rt(e,t){const r=Nt(e,t);return r?r.currency:e.plan?.currency??""}function Ut(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()}function Wt(e,t,r,s){const n=e.quotas?.[r];if(null==n)return null;const a=n[s];if(!a)return null;const i=It(e,t,r,s);return{included:a.included,...void 0!==a.unitSize&&{unitSize:a.unitSize},...void 0!==i&&{overage:i},allowOverage:!1!==n.allowOverage}}function At(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}function Tt(e,t){const r=Nt(e,t);return r?.seatPricing?.enabled?r.seatPricing:null}function Ft(e,t,r){const s=Tt(e,t);return s?.perSeat?s.perSeat[r]??null:null}function _t(e,t){return Math.max(0,e-(t||0))}function Ot(e,t,r,s){const n=Tt(e,t);if(!n)return null;return _t(s,n.includedSeats)*(Ft(e,t,r)??0)}function Dt(e,t,r,s){const n=xt(e,t,r);if(null===n)return null;if(void 0===s)return n;return n+(Ot(e,t,r,s)??0)}function $t(e){const{planVersion:t,currency:r="usd",settingsMaxUsers:s}=e;if(t){const e=Tt(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 Lt(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 Mt="saas-workspace-current",Bt=e=>{e?ne(Mt,e._id):ae(Mt)},jt=()=>se(Mt),qt=()=>{ae(Mt)},Vt=(e,t)=>!!e&&t.some(t=>t._id===e);function zt(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 Gt(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 Jt={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"},Kt=Object.values(Jt),Ht={admin:Kt.filter(e=>e!==Jt.WORKSPACE_DELETE),member:[Jt.WORKSPACE_SETTINGS_VIEW,Jt.WORKSPACE_MEMBERS_VIEW,Jt.WORKSPACE_FEATURES_VIEW,Jt.WORKSPACE_BILLING_VIEW,Jt.WORKSPACE_USAGE_VIEW],viewer:[Jt.WORKSPACE_SETTINGS_VIEW,Jt.WORKSPACE_MEMBERS_VIEW]};function Yt(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 Qt(e){const{userId:t,workspace:r,settings:s,appPermissions:n}=e;if(!r||!t)return new Set;if(zt(r,t)){const e=new Set(Kt);if(n)for(const t of Yt(n))e.add(t);if(r.permissions)for(const t of Yt(r.permissions))e.add(t);if(s?.workspace?.permissions)for(const t of Yt(s.workspace.permissions))e.add(t);return e}const a=e.workspaceRole??Gt(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]?c(i[a]):[],d=o?.[a]?c(o[a]):[],p=Ht[a]??[];let h;if(u.length>0)h=u;else if(d.length>0)h=d;else if(p.length>0)h=p;else{h=Ht[s?.workspace?.defaultRole??"member"]??Ht.member??[]}const m=new Set(h),g=i?.[a]?l(i[a]):[],f=n?.[a]?l(n[a]):[],w=g.length>0?g:f;for(const e of w)m.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(Jt.WORKSPACE_MEMBERS_INVITE)}(m,a,s),m}function Zt(e,t){const r=Qt(t);return Array.isArray(e)?e.every(e=>r.has(e)):r.has(e)}const Xt="\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 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";var er;function tr(e){return{isAuthenticated:e===er.authenticated,isLoading:e===er.loading||e===er.redirecting||e===er.authenticating,isRedirecting:e===er.redirecting}}!function(e){e.loading="loading",e.redirecting="redirecting",e.authenticated="authenticated",e.unauthenticated="unauthenticated",e.authenticating="authenticating"}(er||(er={}));class rr extends a{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(ee(e,{component:"ErrorBoundary",action:"componentDidCatch",metadata:{componentStack:t.componentStack,errorBoundary:this.constructor.name}}),this.props.onError)try{this.props.onError(e,t)}catch(e){K("[SDK ErrorBoundary] Error in onError callback:",e)}}componentDidUpdate(e){this.state.hasError&&!1!==this.props.resetOnPropsChange&&e.children!==this.props.children&&this.resetError()}render(){return this.state.hasError&&this.state.error?this.props.fallback?"function"==typeof this.props.fallback?this.props.fallback(this.state.error,this.resetError):this.props.fallback:e("div",{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:[t("h3",{style:{margin:"0 0 0.5rem 0",fontSize:"1rem",fontWeight:600},children:this.props.errorTitle??"Something went wrong"}),t("p",{style:{margin:"0 0 1rem 0",fontSize:"0.875rem"},children:this.state.error.message||"An unexpected error occurred"}),t("button",{onClick:this.resetError,style:{padding:"0.5rem 1rem",backgroundColor:"hsl(var(--destructive, 0 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 sr=()=>({type:"AUTHENTICATION_STARTED"}),nr=()=>({type:"AUTHENTICATION_PROCESSING"}),ar=()=>({type:"AUTHENTICATION_FAILED"}),ir=e=>({type:"SET_SESSION",payload:e}),or=()=>({type:"REMOVE_SESSION"});function cr(e,t,r){const s=i(t),n=i(r),a=i(void 0),c=i(!1),l=s.current!==t,u=n.current!==r,d=l||u;s.current=t,n.current=r;const p=i(0);d&&(p.current+=1);const h=p.current;return o(()=>{const s=t(e);if(c.current){if(r?r(a.current,s):Object.is(a.current,s))return a.current}return a.current=s,c.current=!0,s},[e,h])}function lr({name:e,initialState:r,reducer:s,initializer:a}){const i=c(null),u=c(null),d=c(null),p=n.memo(({children:e})=>{const[n,c]=l(s,r,a||(e=>e)),p=o(()=>({state:n,dispatch:c}),[n,c]);return t(d.Provider,{value:p,children:t(i.Provider,{value:n,children:t(u.Provider,{value:c,children:e})})})});p.displayName=`${e}Provider`;const h=t=>new Error(`use${e}${t} must be used within a ${e}Provider. Make sure SaaSOSProvider is wrapping your application.`),m=()=>{const e=n.useContext(i);if(null===e)throw h("State");return e};return{Provider:p,useContext:()=>{const e=n.useContext(d);if(!e)throw h("Context");return e},useState:m,useDispatch:()=>{const e=n.useContext(u);if(null===e)throw h("Dispatch");return e},useSelector:(e,t)=>cr(m(),e||(e=>e),t)}}function ur(e,t,r){return{...e,[t]:r}}function dr(e,t){return{...e,...t}}const pr=()=>({session:null,status:er.loading}),{Provider:hr,useState:mr,useDispatch:gr}=lr({name:"Auth",initialState:pr(),reducer:(e,t)=>{switch(t.type){case"AUTHENTICATION_STARTED":return ur(e,"status",er.redirecting);case"AUTHENTICATION_PROCESSING":return ur(e,"status",er.authenticating);case"AUTHENTICATION_FAILED":case"REMOVE_SESSION":return dr(e,{session:null,status:er.unauthenticated});case"SET_SESSION":return dr(e,{session:t.payload,status:er.authenticated});default:return e}},initializer:pr}),fr=hr,wr=mr,yr=gr,br=e=>({type:"SET_SAAS_OS_CONFIG",payload:e}),kr=e=>({type:"SET_SETTINGS",payload:e}),vr=()=>({serverUrl:"",version:Pe.V1,orgId:"",settings:null}),{Provider:Sr,useState:Cr,useDispatch:Pr}=lr({name:"OS",initialState:vr(),reducer:(e,t)=>{switch(t.type){case"SET_SAAS_OS_CONFIG":return dr(e,t.payload);case"REMOVE_SAAS_OS_CONFIG":return vr();case"SET_SETTINGS":return ur(e,"settings",t.payload);default:return e}}}),Nr=Sr,xr=Cr,Er=Pr,Ir=e=>({type:"SET_WORKSPACES",payload:e}),Rr=e=>({type:"ADD_WORKSPACE",payload:e}),Ur=e=>({type:"UPDATE_WORKSPACE",payload:e}),Wr=e=>({type:"REMOVE_WORKSPACE",payload:e}),Ar=e=>({type:"SET_ALL_FEATURES",payload:e}),Tr=e=>({type:"SET_CURRENT_WORKSPACE",payload:e}),Fr=()=>({type:"RESET_CURRENT_WORKSPACE"}),_r=e=>({type:"SET_IS_INITIALIZED",payload:e}),Or=e=>({type:"SET_LOADING",payload:e}),Dr=e=>({type:"SET_ERROR",payload:e}),$r=e=>({type:"SET_REFRESHING",payload:e}),Lr=e=>({type:"SET_SWITCHING_TO_ID",payload:e}),{Provider:Mr,useState:Br,useDispatch:jr}=lr({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 ur(e,"workspaces",t.payload);case"ADD_WORKSPACE":return ur(e,"workspaces",[...e.workspaces,t.payload]);case"UPDATE_WORKSPACE":return ur(e,"workspaces",e.workspaces.map(e=>e._id===t.payload._id?t.payload:e));case"REMOVE_WORKSPACE":return ur(e,"workspaces",e.workspaces.filter(e=>e._id!==t.payload));case"SET_ALL_FEATURES":return ur(e,"allFeatures",t.payload);case"SET_CURRENT_WORKSPACE":return ur(e,"currentWorkspace",t.payload);case"RESET_CURRENT_WORKSPACE":return ur(e,"currentWorkspace",null);case"SET_IS_INITIALIZED":return ur(e,"isInitialized",t.payload);case"SET_LOADING":return ur(e,"loading",t.payload);case"SET_ERROR":return ur(e,"error",t.payload);case"SET_REFRESHING":return ur(e,"refreshing",t.payload);case"SET_SWITCHING_TO_ID":return ur(e,"switchingToId",t.payload);default:return e}}}),qr=Mr,Vr=Br,zr=jr,Gr=n.memo(({children:e})=>t(Nr,{children:t(fr,{children:t(qr,{children:e})})}));Gr.displayName="SDKContextProvider";const Jr=c({});Jr.displayName="CheckoutConfigContext";const Kr=n.memo(({getCheckoutStripeParams:e,children:r})=>{const s=n.useMemo(()=>({getCheckoutStripeParams:e}),[e]);return t(Jr.Provider,{value:s,children:r})});Kr.displayName="CheckoutConfigProvider";const Hr={settings:{titles:{profile:"Account",security:"Security",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",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"}},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",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:{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:",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 {}}"},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:{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"},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"},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",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"}},Yr={en:async()=>Hr,es:async()=>(await import("./es-CyuBtosP.mjs")).es,fr:async()=>(await import("./fr-CxuDLZ27.mjs")).fr,de:async()=>(await import("./de-xnPl61SS.mjs")).de,ja:async()=>(await import("./ja-DIJ_xCIi.mjs")).ja,zh:async()=>(await import("./zh-CYQwZiBL.mjs")).zh,hi:async()=>(await import("./hi-CpuvyorS.mjs")).hi,ar:async()=>(await import("./ar-SrPOJXdL.mjs")).ar},Qr=["en","es","fr","de","ja","zh","hi","ar"];const Zr={hi:"hi-u-nu-deva",ar:"ar-u-nu-arab"};function Xr(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]=Xr(a,n))}return r}const es=c({messages:Hr,locale:"en",formattingLocale:"en"});function ts({locale:e="en",messageOverrides:t,children:r}){const s=function(e){const t=e.toLowerCase().replace("_","-");if(Qr.includes(t))return t;const r=t.split("-")[0];return Qr.includes(r)?r:"en"}(e),[a,i]=n.useState(Hr);n.useEffect(()=>{if("en"===s)return void i(Hr);let e=!1;const t=Yr[s];return t&&t().then(t=>{e||i(t)}),()=>{e=!0}},[s]);const c=o(()=>t?Xr(a,t):a,[a,t]),l=function(e){return Zr[e]??e}(s),u=o(()=>({messages:c,locale:s,formattingLocale:l}),[c,s,l]);return n.createElement(es.Provider,{value:u},r)}const rs=new Map,ss=new Map,ns=new Map;function as(e,t){return t?`${e}:${JSON.stringify(t)}`:e}const is={getNumberFormat(e,t){const r=as(e,t);let s=rs.get(r);return s||(s=new Intl.NumberFormat(e,t),rs.set(r,s)),s},getDateTimeFormat(e,t){const r=as(e,t);let s=ss.get(r);return s||(s=new Intl.DateTimeFormat(e,t),ss.set(r,s)),s},getPluralRules(e,t){const r=as(e,t);let s=ns.get(r);return s||(s=new Intl.PluralRules(e,t),ns.set(r,s)),s}},os=new Map;function cs(){const{messages:e,locale:t,formattingLocale:r}=u(es),s=o(()=>{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(s,n)=>{const a=t(e,s)??t(Hr,s)??s;if(!n)return a;try{const e=function(e,t){const r=`${t}:${e}`;let s=os.get(r);return s||(s=new y(e,t,void 0,{formatters:is}),os.set(r,s)),s}(a,r),t=e.format(n);return"string"==typeof t?t:String(t)}catch{return a.replace(/\{(\w+)\}/g,(e,t)=>String(n[t]??`{${t}}`))}}},[e,r]),n="ar"===t?"rtl":"ltr",a=o(()=>e=>e.toLocaleString(r),[r]),i=o(()=>(e,t)=>{const s=(t??"").trim().toUpperCase();if(!s)return(e/100).toLocaleString(r,{minimumFractionDigits:2});try{return new Intl.NumberFormat(r,{style:"currency",currency:s,minimumFractionDigits:2}).format(e/100)}catch{return(e/100).toLocaleString(r,{minimumFractionDigits:2})}},[r]);return{t:s,locale:t,formattingLocale:r,dir:n,fmtNum:a,fmtCents:i,messages:e}}function ls(){const e=yr(),t=Er(),r=zr();return o(()=>({auth:e,os:t,workspaces:r}),[e,t,r])}function us(e,t){const r=xr(),s=wr(),n=Vr();return cr(o(()=>({os:r,auth:s,workspaces:n}),[r,s,n]),e||(e=>e),t)}function ds(e,t,r){d(()=>{const t=new AbortController;return e(t.signal).catch(e=>{H(e)||(r?.onError?r.onError(e):ee(e,{component:"useAsyncEffect",action:"effect",metadata:{note:"Unhandled rejection - consider passing onError"}}))}),()=>t.abort()},t)}function ps(){return us(e=>e.os)}let hs=null;function ms(){const e=ls(),t=ps(),{serverUrl:r,version:s,orgId:n,settings:a}=t,i=o(()=>Ne(t)?new ve({serverUrl:r,version:s,orgId:n}):null,[r,s,n]),c=p(async t=>i?hs||(hs=(async()=>{try{const r=await i.getSettings(t);return e.os(kr(r)),r}catch(e){return te(e,{component:"useSaaSSettings",action:"getSettings",metadata:{serverUrl:r,version:s,orgId:n}}),null}finally{hs=null}})(),hs):null,[i,e,r,s,n]);return ds(async e=>{a||Ne(t)&&await c(e)},[r,s,n],{onError:e=>te(e,{component:"useSaaSSettings",action:"fetchSettings",metadata:{serverUrl:r,version:s,orgId:n}})}),o(()=>({settings:a,getSettings:c}),[a,c])}function gs(){const e=ps(),t=p(()=>{e.auth?.callbacks?.onSessionExpired?.("expired")},[e.auth?.callbacks?.onSessionExpired]),r=function(e,t){return o(()=>new Ce({...e,onUnauthorized:t}),[e.serverUrl,e.version,e.orgId,t])}(e,t);return o(()=>({os:e,api:r}),[e,r])}const fs=e=>{const{t:t}=cs(),{os:r,api:s}=gs(),n=Ne(r),[a,i]=h(null),[o,c]=h(!1),[l,u]=h(null),m=p(async()=>{if(e&&n){c(!0),u(null);try{const t=await s.getPublicPlans(e);i(t)}catch(r){const s=re(r,"errors.fetchPlans",t);u(s),ee(r,{component:"usePublicPlans",action:"fetchPlans",metadata:{slug:e}})}finally{c(!1)}}else i(null)},[s,e,n]);d(()=>{m()},[m]);const g=e&&!n||o;return{items:a?.items??[],plans:a?.plans??[],notes:a?.notes,loading:g,error:l,refetch:m}},ws=e=>{const{t:t}=cs(),{api:r}=gs(),[s,n]=h(null),[a,i]=h(!1),[o,c]=h(null),l=p(async()=>{if(e){i(!0),c(null);try{const t=await r.getPlanGroupVersion(e);n(t)}catch(r){const s=re(r,"errors.fetchPlanGroupVersion",t);c(s),ee(r,{component:"usePublicPlanGroupVersion",action:"fetchVersion",metadata:{groupVersionId:e}})}finally{i(!1)}}else n(null)},[r,e]);return d(()=>{l()},[l]),{planGroupVersion:s,loading:a,error:o,refetch:l}},ys=e=>{const{t:t}=cs(),{api:r}=gs(),[s,n]=h(null),[a,i]=h(!1),[o,c]=h(null),l=p(async()=>{if(e){i(!0),c(null);try{const t=await r.getCurrentSubscription(e);n(t)}catch(r){const s=re(r,"errors.fetchSubscription",t);c(s),ee(r,{component:"useSubscription",action:"fetchSubscription",metadata:{workspaceId:e}})}finally{i(!1)}}else n(null)},[r,e]);return d(()=>{l()},[l]),{subscription:s,loading:a,error:o,refetch:l}},bs=(e,t)=>{const{t:r}=cs(),{api:s}=gs(),[n,a]=h(null),[i,o]=h(!1),[c,l]=h(null),u=p(async()=>{if(e){o(!0),l(null);try{const r=t?await s.getPlanGroupByVersion(e,t):await s.getPlanGroup(e);a(r)}catch(s){const n=re(s,"errors.fetchPlanGroup",r);l(n),ee(s,{component:"usePlanGroup",action:"fetchPlanGroup",metadata:{workspaceId:e,groupVersionId:t}})}finally{o(!1)}}else a(null)},[s,e,t]);return d(()=>{u()},[u]),{planGroup:n,loading:i,error:c,refetch:u}},ks=e=>{const{t:t}=cs(),{api:r}=gs(),[s,n]=h(null),[a,i]=h(!1),[o,c]=h(null),l=p(async()=>{if(e){i(!0),c(null);try{const t=await r.getPlanGroupVersions(e);n(t)}catch(r){const s=re(r,"errors.fetchPlanGroupVersions",t);c(s),ee(r,{component:"usePlanGroupVersions",action:"fetchVersions",metadata:{workspaceId:e}})}finally{i(!1)}}else n(null)},[r,e]);return d(()=>{l()},[l]),{versions:s,loading:a,error:o,refetch:l}},vs=e=>{const{t:t}=cs(),{api:r}=gs(),{getCheckoutStripeParams:s}=u(Jr),[n,a]=h(!1),[i,o]=h(null);return{createCheckoutSession:p(async n=>{if(!e)throw new Error("Workspace ID is required");a(!0),o(null);try{let t=n;if(s){const e=await s(n);e&&(t={...n,stripeOptions:{...n.stripeOptions,...e,metadata:{...n.stripeOptions?.metadata,...e.metadata},subscriptionMetadata:{...n.stripeOptions?.subscriptionMetadata,...e.subscriptionMetadata}}})}const a=await r.createCheckoutSession(e,t);return"trial_started"===a.type&&($e(),_e()),a}catch(r){const s=re(r,"errors.createCheckout",t);throw o(s),ee(r,{component:"useCreateCheckoutSession",action:"createCheckoutSession",metadata:{workspaceId:e,request:n}}),r}finally{a(!1)}},[r,e,s]),loading:n,error:i}},Ss=e=>{const{t:t}=cs(),{api:r}=gs(),[s,n]=h(!1),[a,i]=h(null);return{updateSubscription:p(async(s,a)=>{if(!e)throw new Error("Workspace ID is required");n(!0),i(null);try{const t={planVersionId:s,...a?.billingInterval&&{billingInterval:a.billingInterval},...a?.successUrl&&{successUrl:a.successUrl},...a?.cancelUrl&&{cancelUrl:a.cancelUrl}},n=await r.updateSubscription(e,t);return $e(),n}catch(r){const n=re(r,"errors.updateSubscription",t);throw i(n),ee(r,{component:"useUpdateSubscription",action:"updateSubscription",metadata:{workspaceId:e,planVersionId:s,options:a}}),r}finally{n(!1)}},[r,e]),loading:s,error:a}},Cs=(e,t)=>{const r=ys(e),s=bs(e,t),n=Ss(e),a=p(async()=>{await Promise.all([r.refetch(),s.refetch()])},[r.refetch,s.refetch]);return{subscription:r.subscription,planGroup:s.planGroup,loading:r.loading||s.loading||n.loading,error:r.error||s.error||n.error,updateSubscription:n.updateSubscription,refetch:a}},Ps=(e,t=10,r)=>{const{t:s}=cs(),{api:n}=gs(),[a,i]=h([]),[o,c]=h(!1),[l,u]=h(!1),[m,g]=h(null),f=p(async()=>{if(!e)return i([]),void c(!1);u(!0),g(null);try{const s=await n.listInvoices(e,t,r);i(s.invoices||[]),c(s.has_more||!1)}catch(n){const a=re(n,"errors.fetchInvoices",s);g(a),ee(n,{component:"useInvoices",action:"fetchInvoices",metadata:{workspaceId:e,limit:t,startingAfter:r}})}finally{u(!1)}},[n,e,t,r]);return d(()=>{f()},[f]),{invoices:a,hasMore:o,loading:l,error:m,refetch:f}},Ns=e=>{const{t:t}=cs(),{api:r}=gs(),[s,n]=h(!1),[a,i]=h(null);return{openBillingPortal:p(async s=>{if(!e)throw new Error("Workspace ID is required");n(!0),i(null);try{const t=s||window.location.href,n=await r.createBillingPortalSession(e,t);return n.url&&window.open(n.url,"_blank","noopener,noreferrer"),n}catch(r){const s=re(r,"errors.openBillingPortal",t);throw i(s),ee(r,{component:"useBillingPortal",action:"openBillingPortal",metadata:{workspaceId:e}}),r}finally{n(!1)}},[e,r]),loading:s,error:a}},xs=(e,t)=>{const{t:r}=cs(),{api:s}=gs(),[n,a]=h(null),[i,o]=h(!1),[c,l]=h(null),u=p(async()=>{if(e&&t){o(!0),l(null);try{const r=await s.getInvoice(e,t);a(r.invoice)}catch(s){const n=re(s,"errors.fetchInvoice",r);l(n),ee(s,{component:"useInvoice",action:"fetchInvoice",metadata:{workspaceId:e,invoiceId:t}})}finally{o(!1)}}else a(null)},[s,e,t]);return d(()=>{u()},[u]),{invoice:n,loading:i,error:c,refetch:u}},Es=e=>{const{t:t}=cs(),{api:r}=gs(),[s,n]=h(!1),[a,i]=h(null);return{cancelSubscription:p(async()=>{if(!e)throw new Error("Workspace ID is required");n(!0),i(null);try{const t=await r.cancelSubscriptionAtPeriodEnd(e);return $e(),t}catch(r){const s=re(r,"errors.cancelSubscription",t);throw i(s),ee(r,{component:"useCancelSubscription",action:"cancelSubscription",metadata:{workspaceId:e}}),r}finally{n(!1)}},[r,e]),loading:s,error:a}},Is=e=>{const{t:t}=cs(),{api:r}=gs(),[s,n]=h(!1),[a,i]=h(null);return{resumeSubscription:p(async()=>{if(!e)throw new Error("Workspace ID is required");n(!0),i(null);try{const t=await r.resumeSubscription(e);return $e(),t}catch(r){const s=re(r,"errors.resumeSubscription",t);throw i(s),ee(r,{component:"useResumeSubscription",action:"resumeSubscription",metadata:{workspaceId:e}}),r}finally{n(!1)}},[r,e]),loading:s,error:a}},Rs=e=>{const{t:t}=cs(),{api:r}=gs(),[s,n]=h(!1),[a,i]=h(null);return{recordUsage:p(async s=>{if(!e)throw new Error("Workspace ID is required");n(!0),i(null);try{const t=await r.recordUsage(e,s);return _e(),t}catch(r){const n=re(r,"errors.recordUsage",t);throw i(n),ee(r,{component:"useRecordUsage",action:"recordUsage",metadata:{workspaceId:e,request:s}}),r}finally{n(!1)}},[r,e]),loading:s,error:a}},Us=(e,t)=>{const{t:r}=cs(),{api:s}=gs(),[n,a]=h(null),[i,o]=h(!1),[c,l]=h(null),u=p(async()=>{if(e&&t){o(!0),l(null);try{const r=await s.getQuotaUsageStatus(e,t);a(r)}catch(s){const n=re(s,"errors.fetchQuotaUsage",r);l(n),ee(s,{component:"useQuotaUsageStatus",action:"fetchStatus",metadata:{workspaceId:e,quotaSlug:t}})}finally{o(!1)}}else a(null)},[s,e,t]);return d(()=>{u()},[u]),{status:n,loading:i,error:c,refetch:u}},Ws=e=>{const{t:t}=cs(),{api:r}=gs(),[s,n]=h(null),[a,i]=h(!1),[o,c]=h(null),l=p(async()=>{if(e){i(!0),c(null);try{const t=await r.getAllQuotaUsage(e);n(t.quotas)}catch(r){const s=re(r,"errors.fetchAllQuotaUsage",t);c(s),ee(r,{component:"useAllQuotaUsage",action:"fetchAllUsage",metadata:{workspaceId:e}})}finally{i(!1)}}else n(null)},[r,e]);return d(()=>{l()},[l]),{quotas:s,loading:a,error:o,refetch:l}},As=(e,t,r)=>{const{t:s}=cs(),{api:n}=gs(),[a,i]=h([]),[o,c]=h(0),[l,u]=h(0),[m,g]=h(1),[f,w]=h(!1),[y,b]=h(!1),[k,v]=h(!1),[S,C]=h(null),P=r?.from,N=r?.to,x=r?.source,E=r?.page,I=r?.limit,R=p(async()=>{if(!e)return i([]),c(0),u(0),g(1),w(!1),void b(!1);v(!0),C(null);try{const r={...t&&{quotaSlug:t},...P&&{from:P},...N&&{to:N},...x&&{source:x},...E&&{page:E},...I&&{limit:I}},s=await n.getUsageLogs(e,r);i(s.docs||[]),c(s.totalDocs||0),u(s.totalPages||0),g(s.page||1),w(s.hasNextPage||!1),b(s.hasPrevPage||!1)}catch(r){const n=re(r,"errors.fetchUsageLogs",s);C(n),ee(r,{component:"useUsageLogs",action:"fetchLogs",metadata:{workspaceId:e,quotaSlug:t}})}finally{v(!1)}},[n,e,t,P,N,x,E,I]);return d(()=>{R()},[R]),{logs:a,totalDocs:o,totalPages:l,page:m,hasNextPage:f,hasPrevPage:y,loading:k,error:S,refetch:R}},Ts=c(null);Ts.displayName="SubscriptionContext";const Fs=n.memo(function({children:e}){const r=us(e=>e.workspaces.currentWorkspace),{subscription:s,loading:n,error:a,refetch:i}=ys(r?._id);d(()=>De(i),[i]);const c=o(()=>({response:s,loading:n,error:a,refetch:i}),[s,n,a,i]);return t(Ts.Provider,{value:c,children:e})});function _s(){const e=u(Ts);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}Fs.displayName="SubscriptionContextProvider";const Os=e=>{const{t:t}=cs(),{api:r}=gs(),[s,n]=h(null),[a,i]=h(!1),[o,c]=h(null),l=p(async()=>{if(e){i(!0),c(null);try{const t=await r.getCreditBalance(e);n(t)}catch(r){const s=re(r,"errors.fetchCreditBalance",t);c(s),ee(r,{component:"useCreditBalance",action:"fetchBalance",metadata:{workspaceId:e}})}finally{i(!1)}}else n(null)},[r,e]);return d(()=>{l()},[l]),{balance:s,loading:a,error:o,refetch:l}},Ds=e=>{const{t:t}=cs(),{api:r}=gs(),[s,n]=h(!1),[a,i]=h(null);return{consumeCredits:p(async s=>{if(!e)throw new Error("Workspace ID is required");n(!0),i(null);try{const t=await r.consumeCredits(e,s);return Ae(),t}catch(r){const n="INSUFFICIENT_CREDITS"===r.code?`Insufficient credits. Available: ${r.available}, requested: ${r.requested}`:re(r,"errors.consumeCredits",t);throw i(n),ee(r,{component:"useConsumeCredits",action:"consumeCredits",metadata:{workspaceId:e,request:s}}),r}finally{n(!1)}},[r,e]),loading:s,error:a}},$s=e=>{const{t:t}=cs(),{api:r}=gs(),[s,n]=h(!1),[a,i]=h(null);return{purchaseCredits:p(async s=>{if(!e)throw new Error("Workspace ID is required");n(!0),i(null);try{return await r.purchaseCredits(e,s)}catch(r){const n=re(r,"errors.purchaseCredits",t);throw i(n),ee(r,{component:"usePurchaseCredits",action:"purchaseCredits",metadata:{workspaceId:e,request:s}}),r}finally{n(!1)}},[r,e]),loading:s,error:a}},Ls=e=>{const{t:t}=cs(),{api:r}=gs(),[s,n]=h([]),[a,i]=h(!1),[o,c]=h(null),l=p(async()=>{if(e){i(!0),c(null);try{const t=await r.getCreditPackages(e);n(t)}catch(r){const s=re(r,"errors.fetchCreditPackages",t);c(s),ee(r,{component:"useCreditPackages",action:"fetchPackages",metadata:{workspaceId:e}})}finally{i(!1)}}else n([])},[r,e]);return d(()=>{l()},[l]),{packages:s,loading:a,error:o,refetch:l}},Ms=(e,t)=>{const{t:r}=cs(),{api:s}=gs(),[n,a]=h([]),[i,o]=h(0),[c,l]=h(0),[u,m]=h(1),[g,f]=h(!1),[w,y]=h(!1),[b,k]=h(!1),[v,S]=h(null),C=t?.type,P=t?.page,N=t?.limit,x=p(async()=>{if(!e)return a([]),o(0),l(0),m(1),f(!1),void y(!1);k(!0),S(null);try{const t=await s.getCreditTransactions(e,{type:C,page:P,limit:N});a(t.docs||[]),o(t.totalDocs||0),l(t.totalPages||0),m(t.page||1),f(t.hasNextPage||!1),y(t.hasPrevPage||!1)}catch(t){const s=re(t,"errors.fetchCreditTransactions",r);S(s),ee(t,{component:"useCreditTransactions",action:"fetchTransactions",metadata:{workspaceId:e}})}finally{k(!1)}},[s,e,C,P,N]);return d(()=>{x()},[x]),{transactions:n,totalDocs:i,totalPages:c,page:u,hasNextPage:g,hasPrevPage:w,loading:b,error:v,refetch:x}},Bs=(e,t)=>{const{t:r}=cs(),{api:s}=gs(),[n,a]=h(null),[i,o]=h(!1),[c,l]=h(null),u=p(async()=>{if(e){o(!0),l(null);try{const r=await s.getExpiringCredits(e,t);a(r)}catch(s){const n=re(s,"errors.fetchExpiringCredits",r);l(n),ee(s,{component:"useExpiringCredits",action:"fetchExpiring",metadata:{workspaceId:e,days:t}})}finally{o(!1)}}else a(null)},[s,e,t]);return d(()=>{u()},[u]),{expiringCredits:n?.expiringCredits??0,buckets:n?.buckets??[],days:n?.days??t??7,loading:i,error:c,refetch:u}},js=()=>{const{t:e}=cs(),{os:t,api:r}=gs(),s=Ne(t),[n,a]=h([]),[i,o]=h(),[c,l]=h(!1),[u,m]=h(null),g=p(async()=>{if(s){l(!0),m(null);try{const e=await r.getPublicCreditPackages();a(e.packages||[]),o(e.notes)}catch(t){const r=re(t,"errors.fetchCreditPackages",e);m(r),ee(t,{component:"usePublicCreditPackages",action:"fetchPackages"})}finally{l(!1)}}else a([])},[r,s]);d(()=>{g()},[g]);return{packages:n,notes:i,loading:!s||c,error:u,refetch:g}},qs=c(null);qs.displayName="CreditBalanceContext";const Vs=n.memo(function({children:e}){const r=us(e=>e.workspaces.currentWorkspace),{balance:s,loading:n,error:a,refetch:i}=Os(r?._id);d(()=>We(i),[i]);const c=o(()=>({balance:s,loading:n,error:a,refetch:i}),[s,n,a,i]);return t(qs.Provider,{value:c,children:e})});function zs(){const e=u(qs);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}Vs.displayName="CreditBalanceContextProvider";const Gs=({message:s})=>e(r,{children:[t("div",{className:"bb-fs-loader-spinner",style:{width:40,height:40,border:"3px solid hsl(var(--muted, 210 40% 96%))",borderTopColor:"hsl(var(--muted-foreground, 215.4 16.3% 46.9%))",borderRadius:"50%",animation:"bb-fs-loader-spin 0.6s linear infinite"}}),t("p",{"aria-hidden":"true",style:{marginTop:16,color:"hsl(var(--muted-foreground, 215.4 16.3% 46.9%))",fontSize:14},children:s}),t("style",{children:"\n @keyframes bb-fs-loader-spin { to { transform: rotate(360deg) } }\n @media (prefers-reduced-motion: reduce) {\n .bb-fs-loader-spinner { animation: none !important; }\n }\n @media (prefers-color-scheme: dark) {\n .bb-fs-loader-spinner {\n border-color: hsl(var(--muted, 217.2 32.6% 17.5%)) !important;\n border-top-color: hsl(var(--muted-foreground, 215 20.2% 65.1%)) !important;\n }\n }\n "})]}),Js=({children:r,message:s="Loading...",backgroundColor:n})=>e("div",{role:"status","aria-live":"polite","aria-busy":"true",className:"bb-fs-loader",style:{position:"fixed",inset:0,zIndex:2147483647,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",backgroundColor:n??void 0},children:[t("span",{style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0,0,0,0)",whiteSpace:"nowrap",border:0},children:s}),r??t(Gs,{message:s}),t("style",{children:"\n .bb-fs-loader {\n background-color: hsl(var(--background, 0 0% 100%));\n }\n @media (prefers-color-scheme: dark) {\n .bb-fs-loader {\n background-color: hsl(var(--background, 222.2 84% 4.9%));\n }\n .bb-fs-loader p {\n color: hsl(var(--muted-foreground, 215 20.2% 65.1%)) !important;\n }\n }\n "})]});Js.displayName="FullScreenLoader";const Ks=c(null),Hs=({children:r,loadingComponent:s})=>{const[n,a]=h({visible:!1,message:""}),c=i(null),l=p(()=>{c.current&&(clearTimeout(c.current),c.current=null)},[]),u=p(()=>{l(),a({visible:!1,message:""})},[l]),m=p(e=>{l(),a({visible:!0,message:e}),c.current=setTimeout(()=>{ee(new Error("FullScreenLoader timed out — auto-hiding after 60s"),{component:"FullScreenLoaderProvider",action:"timeout"}),a({visible:!1,message:""})},6e4)},[l]);d(()=>()=>l(),[l]);const g=o(()=>({show:m,hide:u,visible:n.visible,message:n.message}),[m,u,n.visible,n.message]),f="function"==typeof s?s({message:n.message}):s;return e(Ks.Provider,{value:g,children:[r,n.visible&&t(Js,{message:n.message,children:f})]})};function Ys(){const e=u(Ks);if(!e)throw new Error("useFullScreenLoader must be used within FullScreenLoaderProvider");return e}Hs.displayName="FullScreenLoaderProvider";const Qs=c({appPermissions:void 0});function Zs({appPermissions:e,children:r}){const s=o(()=>({appPermissions:e}),[e]);return t(Qs.Provider,{value:s,children:r})}function Xs(){return u(Qs)}const en=c(null);en.displayName="QuotaUsageContext";const tn=n.memo(function({children:e}){const r=us(e=>e.workspaces.currentWorkspace),{quotas:s,loading:n,error:a,refetch:i}=Ws(r?._id);d(()=>Fe(i),[i]);const c=o(()=>({quotas:s,loading:n,error:a,refetch:i}),[s,n,a,i]);return t(en.Provider,{value:c,children:e})});function rn(){const e=u(en);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}tn.displayName="QuotaUsageContextProvider";const sn=c({});function nn({ui:e,children:r}){const s=o(()=>e??{},[e]);return t(sn.Provider,{value:s,children:r})}function an(){return u(sn)}function on(e,t){return t?cn(e,t):e}function cn(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?cn(r[e],s):s;return r}const ln="saas-oauth-state";function un(){ae(ln)}const dn={Profile:"profile",Security:"security",ConnectedAgents:"connected-agents",General:"general",Users:"users",Subscription:"subscription",Usage:"usage",Credits:"credits",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"},pn=new Set(Object.values(dn));const hn=new class{constructor(){this.listeners=new Set,this.currentState={open:!1,section:dn.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||dn.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(){this.currentState={...this.currentState,params:void 0}}notifyListeners(){this.listeners.forEach(e=>{e(this.currentState)})}},mn=()=>{const e=ls(),{os:t,api:r}=gs(),{settings:s}=ms(),a=us(e=>e.workspaces),i=us(e=>e.auth.session?.user),o=p((t,r)=>{if((!(t._id===a.currentWorkspace?._id)||r?.forceEmit)&&t){const r=a.currentWorkspace;Bt(t),e.workspaces(Tr(t)),Ie.emitWorkspaceChanged(t,r).catch(e=>{ee(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceChanged",metadata:{workspaceId:t._id}})})}},[a.currentWorkspace,e]),c=p(async(r,s)=>{const n=++g.current;e.workspaces(Lr(r._id));try{const e=t.auth?.callbacks?.onWorkspaceChange;if(e){const t=Gt(r,i?.id);try{await e({workspace:r,user:i??null,role:t})}catch(e){throw ee(e,{component:"useSaaSWorkspaces",action:"onWorkspaceChange",metadata:{workspaceId:r._id}}),e}if(n!==g.current)return}o(r,s)}finally{n===g.current&&e.workspaces(Lr(null))}},[e,t.auth?.callbacks?.onWorkspaceChange,o,i]),l=n.useRef(c);l.current=c,d(()=>{if(!a.isInitialized){const t=jt();if(e.workspaces(_r(!0)),t){const e=a.workspaces.find(e=>e._id===t);e&&l.current(e,{forceEmit:!0}).catch(e=>{ee(e,{component:"useSaaSWorkspaces",action:"initWorkspaceSwitch",metadata:{savedWorkspaceId:t}})})}}},[a.isInitialized,a.workspaces,e]);const u=p(()=>{qt(),e.workspaces(Fr())},[e]),h=n.useRef(!1),m=n.useRef(!1),g=n.useRef(0),f=p(async()=>{if(!a.loading&&!h.current){h.current=!0,e.workspaces(Or(!0)),e.workspaces(Dr(null));try{const t=await r.getWorkspaces();if(e.workspaces(Ir(t)),t.length>0){const e=jt();if(e&&Vt(e,t)){const r=t.find(t=>t._id===e);if(r)try{await c(r,{forceEmit:!0})}catch{}}else{const e=t[0];try{await c(e,{forceEmit:!0})}catch{}}}}catch(t){e.workspaces(Dr(t instanceof Error?t.message:"Failed to fetch workspaces"))}finally{e.workspaces(Or(!1)),h.current=!1}}},[r,a.loading,e,c]),w=p(async()=>{if(!a.refreshing&&!h.current){h.current=!0,e.workspaces($r(!0));try{const t=await r.getWorkspaces();e.workspaces(Ir(t))}catch(e){}finally{e.workspaces($r(!1)),h.current=!1}}},[r,a.refreshing,e]),y=p(async(t,s)=>{const n=await r.createWorkspace({name:t,image:s});e.workspaces(Rr(n)),await c(n),Ie.emitWorkspaceCreated(n).catch(e=>{ee(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceCreated",metadata:{workspaceId:n._id}})}),setTimeout(()=>{hn.openWorkspaceSettings(dn.Subscription)},300)},[r,e,c]),b=p(async(t,s)=>{const n=await r.updateWorkspace(t._id,s);e.workspaces(Ur(n)),Ie.emitWorkspaceUpdated(n).catch(e=>{ee(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceUpdated",metadata:{workspaceId:n._id}})})},[r,e]),k=p(async()=>{if(m.current)return a.allFeatures.length>0?a.allFeatures:null;if(a.allFeatures.length>0)return a.allFeatures;m.current=!0;try{const t=await r.getFeatures();return e.workspaces(Ar(t)),t}catch(e){return ee(e,{component:"useSaaSWorkspaces",action:"getFeatures"}),null}finally{m.current=!1}},[r,e,a.allFeatures]),v=p(async(e,t,s)=>await r.updateFeature(e,t,s),[r]),S=p(async e=>r.updateSettings(e),[r]),C=p(async(e,t)=>{const s=await r.updateWorkspacePermissions(e,t);return await w(),s},[r,w]);d(()=>{if(!a.currentWorkspace?._id||0===a.workspaces.length)return;const t=a.currentWorkspace._id,r=a.workspaces.find(e=>e._id===t);if(r)r!==a.currentWorkspace&&(Bt(r),e.workspaces(Tr(r)));else if(a.workspaces.length>0){const e=a.workspaces[0];e._id!==t&&c(e).catch(t=>{ee(t,{component:"useSaaSWorkspaces",action:"fallbackWorkspaceSwitch",metadata:{workspaceId:e._id}})})}},[a.workspaces,a.currentWorkspace,e,c]);const P=p(async e=>await r.getWorkspaceUsers(e),[r]),N=p(async(e,t,n)=>{const i=a.workspaces.find(t=>t._id===e);if(i){const e=$t({settingsMaxUsers:s?.workspace?.maxWorkspaceUsers}),t=Lt({memberCount:i.users?.length??0,maxUsersConfig:e});if(!t.canInvite)throw new Error(t.blockMessageKey||"users.memberLimitReached")}const o=await r.addUser(e,{email:t,role:n});return i&&Ie.emitWorkspaceUserAdded(o.userId,i,n).catch(t=>{ee(t,{component:"useSaaSWorkspaces",action:"emitWorkspaceUserAdded",metadata:{workspaceId:e,userId:o.userId,role:n}})}),w().catch(e=>{ee(e,{component:"useSaaSWorkspaces",action:"refreshAfterAddUser"})}),$e(),o},[r,a.workspaces,w,s]),x=p(async(e,t)=>{const s=a.workspaces.find(t=>t._id===e);if(s&&zt(s,t))throw new Error("Cannot remove the workspace owner");const n=(await r.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===t),i=await r.removeUser(e,t);if(s&&n){const t=n.role;Ie.emitWorkspaceUserRemoved(i.userId,s,t).catch(r=>{ee(r,{component:"useSaaSWorkspaces",action:"emitWorkspaceUserRemoved",metadata:{workspaceId:e,userId:i.userId,role:t}})})}return w().catch(e=>{ee(e,{component:"useSaaSWorkspaces",action:"refreshAfterRemoveUser"})}),$e(),i},[r,a.workspaces,w]),E=p(async(e,t,s)=>{if(s.role){const r=a.workspaces.find(t=>t._id===e);if(r&&zt(r,t))throw new Error("Cannot change the role of the workspace owner")}let n;if(s.role){const s=(await r.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===t);n=s?.role}const i=await r.updateUser(e,t,s);return s.role&&n&&n!==s.role&&Ie.emitWorkspaceUserRoleChanged(i.userId,i.workspace,n,s.role).catch(r=>{ee(r,{component:"useSaaSWorkspaces",action:"emitWorkspaceUserRoleChanged",metadata:{workspaceId:e,userId:t,previousRole:n,newRole:s.role}})}),i},[r,a.workspaces]),I=p(async e=>{const t=await r.getProfile().catch(()=>null),s=await r.updateUserProfile(e);return Ie.emitUserUpdated(s,t||void 0).catch(e=>{ee(e,{component:"useSaaSWorkspaces",action:"emitUserUpdated",metadata:{userId:s._id}})}),s},[r]),R=p(async()=>await r.getProfile(),[r]),U=p(async e=>await r.getWorkspace(e),[r]),W=p(async t=>{if(!i)throw new Error("User must be authenticated to delete a workspace");const s=a.workspaces.find(e=>e._id===t);if(!s)throw new Error("Workspace not found");if(!zt(s,i.id))throw new Error("Only the workspace creator can delete the workspace");const n=await r.deleteWorkspace(t);return e.workspaces(Wr(t)),a.currentWorkspace?._id===t&&(qt(),e.workspaces(Fr())),s&&Ie.emitWorkspaceDeleted(s).catch(e=>{ee(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceDeleted",metadata:{workspaceId:t}})}),n},[r,a.workspaces,a.currentWorkspace,e,i]);return{workspaces:a.workspaces,loading:a.loading,error:a.error,fetchWorkspaces:f,refreshWorkspaces:w,refreshing:a.refreshing,currentWorkspace:a.currentWorkspace,setCurrentWorkspace:o,switchToWorkspace:c,resetCurrentWorkspace:u,createWorkspace:y,allFeatures:a.allFeatures,getFeatures:k,updateFeature:v,updateWorkspaceSettings:S,updateWorkspacePermissions:C,getWorkspace:U,updateWorkspace:b,getUsers:P,addUser:N,removeUser:x,updateUser:E,getProfile:R,updateUserProfile:I,deleteWorkspace:W,switching:null!==a.switchingToId,switchingToId:a.switchingToId}};function gn(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 fn(e,t){return{user:e,sessionId:t,expires:new Date(Date.now()+864e5).toISOString()}}function wn(){return us(e=>e.auth)}function yn(){const{t:e}=cs(),t=ls(),r=wn(),s=ps(),{serverUrl:n,orgId:a,auth:i}=s,{resetCurrentWorkspace:c,currentWorkspace:l}=mn(),u=Ys(),d=o(()=>new fe({serverUrl:n,version:s.version}),[n,s.version]),h=p(async r=>{Ze(r||window.location.href),t.auth(sr()),u.show(e("loading.redirecting"));try{const r=function(){const e=new Uint8Array(32);crypto.getRandomValues(e);const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return ne(ln,t),t}(),s=await d.requestAuth({orgId:a,clientId:i?.clientId??"",redirect:{success:i?.redirectUrl||window.location.href,error:i?.redirectUrl||window.location.href},state:r});if(!s.success)throw u.hide(),t.auth(ar()),new Error(s.message||e("errors.generic"));He(s.data.redirectUrl)}catch(e){throw u.hide(),t.auth(ar()),ee(e,{component:"useSaaSAuth",action:"signIn"}),e}},[d,a,i,t,u,e]),m=p(async()=>{try{i?.callbacks?.onSignOut&&"function"==typeof i.callbacks.onSignOut&&await i.callbacks.onSignOut()}catch(e){ee(e,{component:"useSaaSAuth",action:"signOut"})}finally{ae(ie),t.auth(or()),c()}},[t,c,i?.callbacks?.onSignOut]),g=p(e=>{l?hn.openWorkspaceSettings(e):ee(new Error("Cannot open settings: No current workspace"),{component:"useSaaSAuth",action:"openWorkspaceSettings"})},[l]),f=p(()=>{l?hn.openWorkspaceSettings(dn.Credits,{action:Me.OpenCreditStore}):ee(new Error("Cannot open credit store: No current workspace"),{component:"useSaaSAuth",action:"openCreditStore"})},[l]),w=p(()=>{l?hn.openWorkspaceSettings(dn.Subscription,{action:Me.SelectPlan}):ee(new Error("Cannot open plan picker: No current workspace"),{component:"useSaaSAuth",action:"openPlanPicker"})},[l]),y=o(()=>tr(r.status),[r.status]);return o(()=>({user:r.session?.user,session:r.session,status:r.status,...y,signIn:h,signOut:m,openWorkspaceSettings:g,openCreditStore:f,openPlanPicker:w}),[r.session,r.status,y,h,m,g,f,w])}const bn=n.memo(({children:e,callbacks:s})=>{const{t:a}=cs(),i=ls(),o=wn(),c=ps(),l=tr(o.status).isAuthenticated,u=Ys(),h=n.useRef(!1),m=n.useRef(null),g=n.useRef(!1),f=n.useRef(null),w=p(async e=>{try{if(s?.handleAuthentication){u.show(a("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=c;if(!Ne(r))throw new Error("OS configuration is not available");const{serverUrl:n,version:o,orgId:l}=r;u.show(a("loading.verifyingAccount"));const d=new fe({serverUrl:n,version:o}),p=await d.getProfile(t),h=fn(gn(p,l,r.auth?.clientId||""),t);u.show(a("loading.almostThere")),le(h.sessionId),i.auth(ir(h)),pe();const m=Xe();m&&m!==window.location.href&&He(m),u.hide()}}catch(t){throw u.hide(),Xe(),ee(t,{component:"AuthProviderWrapper",action:"handleAuthRedirect",metadata:{hasCode:!!e}}),i.auth(ar()),t}},[i,s,c,u,a]);return n.useEffect(()=>{if("undefined"==typeof window)return;if(l)return;if(g.current)return;if(f.current)return;if(!Ne(c))return;if(de())return;if(!s?.getSession)return g.current=!0,void i.auth(ar());const e=s.getSession,{serverUrl:t,version:r,orgId:n}=c,o=c.auth?.clientId||"";f.current=(async()=>{u.show(a("loading.restoringSession"));let c=null;try{c=await e()}catch(e){ee(e,{component:"AuthProviderWrapper",action:"getSession"})}if(!c)return g.current=!0,i.auth(ar()),u.hide(),"undefined"!=typeof window&&Ze(window.location.href),void s?.onSessionExpired?.("missing");try{u.show(a("loading.verifyingAccount"));const e=new fe({serverUrl:t,version:r}),s=await e.getProfile(c),l=fn(gn(s,n,o),c);le(l.sessionId),g.current=!0,i.auth(ir(l)),u.hide();const d=Xe();d&&d!==window.location.href&&He(d)}catch(e){ee(e,{component:"AuthProviderWrapper",action:"fetchUserProfile"}),g.current=!0,i.auth(ar()),u.hide(),"undefined"!=typeof window&&Ze(window.location.href),s?.onSessionExpired?.("expired")}finally{f.current=null}})()},[l,i,c,s]),d(()=>{const e=de();if(!e)return;if(h.current||m.current===e)return;if(!Ne(c))return;const t=function(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get(ce)}catch(e){return ee(e,{component:"auth-utils",action:"getStateFromUrl",metadata:{param:ce}}),null}}();if(t&&!function(e){if(!e)return!1;const t=se(ln);if(ae(ln),!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 un(),pe(),ee(new Error("OAuth state mismatch — possible CSRF attack"),{component:"AuthProviderWrapper",action:"validateOAuthState"}),void i.auth(ar());un(),h.current=!0,m.current=e;let r=!1;return i.auth(nr()),w(e).then(()=>{r||(m.current=null)}).catch(e=>{r||(ee(e,{component:"AuthProviderWrapper",action:"handleAuthRedirectEffect",metadata:{hasCode:!0}}),pe(),m.current=null)}).finally(()=>{h.current=!1}),()=>{r=!0}},[w,c.serverUrl,c.version,c.orgId]),t(r,{children:e})});bn.displayName="AuthProviderWrapper";const kn=n.memo(({config:e,auth:s,children:a})=>{const i=ls();ps();const o=n.useMemo(()=>({clientId:s?.clientId||"",redirectUrl:s?.redirectUrl||"",callbacks:s?.callbacks}),[s?.clientId,s?.redirectUrl,s?.callbacks]);return d(()=>{i.os(br({...e,auth:o}))},[e,o,i]),t(r,{children:a})});kn.displayName="ContextConfigProvider";const vn=c({container:null,setContainer:()=>{}}),Sn=n.memo(({children:r})=>{const[s,a]=n.useState(null),i=n.useMemo(()=>({container:s,setContainer:a}),[s]);return e(vn.Provider,{value:i,children:[r,t("div",{ref:a,id:"saas-os-portal",className:"saas-os-ui",style:{width:"100%",height:"100%"}})]})});Sn.displayName="PortalProvider";const Cn=c(null);function Pn(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 Nn=n.memo(function({children:e,serviceWorkerPath:r="/push-sw.js",autoSubscribe:s=!1}){const{t:n}=cs(),a=ps(),{isAuthenticated:i}=yn(),c=o(()=>"undefined"!=typeof window&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window,[]),l=o(()=>new ke({serverUrl:a.serverUrl,version:a.version,orgId:a.orgId}),[a.serverUrl,a.version,a.orgId]),[u,m]=h({permission:c?Notification.permission:"default",isSubscribed:!1,isSupported:c,loading:!1,error:null});d(()=>{if(!i||!c)return;let e=!1;return(async()=>{try{const t=await navigator.serviceWorker.getRegistration(r);if(e)return;if(!t)return void m(e=>({...e,isSubscribed:!1}));const s=await t.pushManager.getSubscription();if(e)return;m(e=>({...e,isSubscribed:!!s,permission:Notification.permission}))}catch{e||m(e=>({...e,isSubscribed:!1}))}})(),()=>{e=!0}},[i,c,r]);const g=p(async()=>{if(!c)return!1;const e=await Notification.requestPermission();return m(t=>({...t,permission:e})),"granted"===e},[c]),f=p(async()=>{if(c&&i){m(e=>({...e,loading:!0,error:null}));try{if(!await g())return void m(e=>({...e,loading:!1,error:n("notifications.permissionDenied")}));const{publicKey:e}=await l.getVapidPublicKey(),t=await navigator.serviceWorker.register(r);await navigator.serviceWorker.ready;const s=(await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Pn(e)})).toJSON();await l.subscribe({endpoint:s.endpoint,keys:{p256dh:s.keys.p256dh,auth:s.keys.auth}},navigator.userAgent),m(e=>({...e,isSubscribed:!0,loading:!1}))}catch(e){const t=e instanceof Error?e.message:n("push.failedToSubscribe");m(e=>({...e,loading:!1,error:t})),ee(e,{component:"PushNotificationProvider",action:"subscribe"})}}},[c,i,l,r,g]),w=p(async()=>{if(c){m(e=>({...e,loading:!0,error:null}));try{const e=await navigator.serviceWorker.getRegistration(r);if(e){const t=await e.pushManager.getSubscription();if(t){const e=t.endpoint;await t.unsubscribe(),await l.unsubscribe(e)}}m(e=>({...e,isSubscribed:!1,loading:!1}))}catch(e){const t=e instanceof Error?e.message:n("push.failedToUnsubscribe");m(e=>({...e,loading:!1,error:t})),ee(e,{component:"PushNotificationProvider",action:"unsubscribe"})}}},[c,l,r]),y=o(()=>({...u,requestPermission:g,subscribe:f,unsubscribe:w}),[u,g,f,w]);return t(Cn.Provider,{value:y,children:e})});function xn(){const e=u(Cn);if(!e)throw new Error("usePushNotifications must be used within PushNotificationProvider");return e}const En=n.createContext(void 0),In=n.memo(({children:e})=>{const{t:r}=cs(),s=ps(),a=function(){const e=ps();return o(()=>new Se(e),[e.serverUrl,e.version])}(),{isAuthenticated:i}=yn(),{serverUrl:c,version:l}=s,[u,d]=h({}),[m,g]=h({}),[f,w]=h(!1),[y,b]=h(null),k=p(async e=>{if(c&&l&&i)try{const t=await a.getAttributes(e);d(t)}catch(e){if(H(e))return;const t=e instanceof Error?e:new Error(r("errors.generic"));b(t),ee(e,{component:"UserProvider",action:"fetchAttributes"})}else d({})},[a,c,l,i]),v=p(async()=>{if(c&&l&&i){w(!0),b(null);try{await k()}finally{w(!1)}}},[c,l,i,k]),S=p(async e=>{w(!0),b(null);try{const t=await a.updateAttributes(e);return await k(),t}catch(t){const s=t instanceof Error?t:new Error(r("errors.generic"));throw b(s),ee(t,{component:"UserProvider",action:"updateAttributes",metadata:{updates:e}}),t}finally{w(!1)}},[a,k]),C=p(async(e,t)=>{w(!0),b(null);try{const r=await a.updateAttribute(e,t);return await k(),r}catch(s){const n=s instanceof Error?s:new Error(r("errors.generic"));throw b(n),ee(s,{component:"UserProvider",action:"updateAttribute",metadata:{attributeKey:e,value:t}}),s}finally{w(!1)}},[a,k]),P=p(async e=>{if(c&&l&&i)try{const t=await a.getFeatures(e);g(t)}catch(e){if(H(e))return;const t=e instanceof Error?e:new Error(r("errors.generic"));b(t),ee(e,{component:"UserProvider",action:"fetchFeatures"})}else g({})},[a,c,l,i]),N=p(async()=>{if(c&&l&&i){w(!0),b(null);try{await P()}finally{w(!1)}}},[c,l,i,P]);ds(async e=>{if(!i||!c||!l)return d({}),void g({});w(!0),b(null);try{await Promise.all([k(e),P(e)])}finally{w(!1)}},[i,c,l,k,P],{onError:e=>ee(e,{component:"UserProvider",action:"initialFetch",metadata:{step:"fetchAttributesAndFeatures"}})});const x=n.useMemo(()=>({attributes:u,features:m,isLoading:f,error:y,updateAttributes:S,updateAttribute:C,refreshAttributes:v,refreshFeatures:N}),[u,m,f,y,S,C,v,N]);return t(En.Provider,{value:x,children:e})});In.displayName="UserProvider";const Rn=N("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"}}),Un=s.forwardRef(({className:r,variant:n,progress:a,size:i,startIcon:o,endIcon:c,asChild:l=!1,...u},d)=>{const p=l?P:"button",h=function(e){switch(e){case"lg":return 20;case"sm":return 14;default:return 16}}(i);return e(p,{disabled:a||u.disabled,className:z(Rn({variant:n,size:i,withIcon:null!=a||null!=o||null!=c,className:r})),ref:d,...u,children:[a&&t(x,{size:h,className:"animate-spin"}),o&&s.cloneElement(o,{size:h}),u.children,c&&s.cloneElement(c,{size:h})]})});Un.displayName="Button";const Wn=L.Root,An=L.Trigger,Tn=L.Portal,Fn=s.forwardRef(({className:e,...r},s)=>t(L.Overlay,{ref:s,className:z("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...r}));Fn.displayName=L.Overlay.displayName;const _n=s.forwardRef(({className:r,children:n,...a},i)=>{const{container:o}=s.useContext(vn);return e(Tn,{container:o,children:[t(Fn,{}),e(L.Content,{ref:i,className:z("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",r),...a,children:[n,e(L.Close,{className:"absolute right-2 rtl:right-auto rtl:left-2 top-2 z-20 p-2 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[t(M,{className:"h-4 w-4"}),t("span",{className:"sr-only",children:"Close"})]})]})]})});_n.displayName=L.Content.displayName;const On=({className:e,...r})=>t("div",{className:z("flex flex-col space-y-1.5 text-center sm:text-start",e),...r});On.displayName="DialogHeader";const Dn=s.forwardRef(({className:e,...r},s)=>t(L.Title,{ref:s,className:z("text-lg font-semibold leading-none tracking-tight",e),...r}));Dn.displayName=L.Title.displayName;const $n=s.forwardRef(({className:e,...r},s)=>t(L.Description,{ref:s,className:z("text-sm text-muted-foreground",e),...r}));function Ln(e){const{user:t}=yn(),{currentWorkspace:r}=mn(),{settings:s}=ms(),{appPermissions:n}=Xs(),a=e??r??null,i=t?.id??null,c=o(()=>a?Gt(a,i):null,[a,i]),l=o(()=>!!a&&zt(a,i),[a,i]),u=o(()=>Qt({userId:i,workspaceRole:c,workspace:a,settings:s,appPermissions:n}),[i,c,a,s,n]);return{can:p(e=>Array.isArray(e)?e.every(e=>u.has(e)):u.has(e),[u]),permissions:u,isOwner:l,role:c}}function Mn(){const e=an(),{can:t}=Ln();return{visible:p((r,s)=>!1!==r(e)&&(void 0===s||t(s)),[e,t]),ui:e}}function Bn(){const e=ps();return o(()=>new be(e),[e.serverUrl,e.version])}function jn(){const e=Bn(),[t,r]=h([]),[s,n]=h(!0),[a,i]=h(null),[c,l]=h(null),u=p(async()=>{n(!0),i(null);try{r(await e.list())}catch(e){te(e,{component:"useConnectedAgents",action:"list"}),i(e instanceof Error?e.message:"Failed to load")}finally{n(!1)}},[e]);d(()=>{u()},[u]);const m=p(async t=>{l(t),i(null);try{await e.revoke(t),r(e=>e.filter(e=>e.clientId!==t))}catch(e){te(e,{component:"useConnectedAgents",action:"revoke"}),i(e instanceof Error?e.message:"Failed to disconnect")}finally{l(null)}},[e]);return o(()=>({agents:t,loading:s,error:a,revoking:c,refresh:u,revoke:m}),[t,s,a,c,u,m])}function qn({icon:r,title:s,description:n,action:a,className:i}){return e("div",{className:z("flex flex-col items-center gap-2 rounded-md border border-dashed p-6 text-center",i),children:[r&&t("span",{"aria-hidden":"true",children:r}),s&&t("p",{className:"text-sm font-medium",children:s}),n&&t("p",{className:"text-sm text-muted-foreground",children:n}),a]})}function Vn({title:r,description:s,actions:n,className:a,titleClassName:i}){return r||s||n?e("div",{className:z(a),children:[(r||n)&&e("div",{className:"flex items-center justify-between gap-2",children:[r&&t("h3",{className:z("text-sm font-medium",i),children:r}),n]}),s&&t("p",{className:"text-sm text-muted-foreground",children:s})]}):null}function zn({className:e,...r}){return t("div",{className:z("animate-pulse rounded-md bg-primary/10",e),...r})}function Gn({className:r,title:s,description:n,disconnectLabel:a,emptyLabel:i}){const{t:o,formattingLocale:c}=cs(),{formats:l}=an(),{agents:u,loading:d,error:p,revoking:h,revoke:m}=jn(),g=void 0===s?o("security.connectedAgentsTitle"):s,f=void 0===n?o("security.connectedAgentsDescription"):n,w=a??o("security.connectedAgentsDisconnect"),y=i??o("security.connectedAgentsEmpty"),b=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?"":new Intl.DateTimeFormat(c,l?.date??{dateStyle:"medium"}).format(t)};return e("div",{className:z("space-y-4",r),children:[t(Vn,{title:g,description:f}),d&&t("div",{className:"space-y-3",children:[0,1].map(e=>t(zn,{className:"h-20 rounded-md"},e))}),p&&!d&&t("p",{className:"text-destructive text-sm",children:p}),!d&&!p&&0===u.length&&t(qn,{icon:t(E,{className:"h-5 w-5 text-muted-foreground"}),description:y}),!d&&u.length>0&&t("ul",{className:"space-y-3",children:u.map(r=>e("li",{className:"flex items-start justify-between gap-x-4 rounded-md border p-3",children:[e("div",{className:"flex flex-col gap-y-1",children:[t("span",{className:"text-sm font-medium",children:r.title}),r.scope.length>0&&e("span",{className:"text-muted-foreground text-xs",children:[o("security.connectedAgentsAccess"),": ",r.scope.join(", ")]}),r.lastGrantedAt&&e("span",{className:"text-muted-foreground text-xs",children:[o("security.connectedAgentsGranted"),": ",b(r.lastGrantedAt)]})]}),t(Un,{variant:"outline",size:"sm",progress:h===r.clientId,onClick:()=>m(r.clientId),children:w})]},r.clientId))})]})}function Jn({label:r,className:s}){const{t:n}=cs();return e("div",{role:"status","aria-live":"polite",className:z("flex items-center gap-2 rounded-lg border bg-muted/50 px-4 py-3 text-sm text-muted-foreground",s),children:[t(x,{className:"h-4 w-4 animate-spin flex-shrink-0"}),t("span",{children:r??n("settings.common.loading")})]})}$n.displayName=L.Description.displayName;const Kn={error:{box:"bg-destructive/10 border-destructive/20 text-destructive",sub:"text-destructive/80",button:"border-destructive/20 text-destructive hover:bg-destructive/10"},success:{box:"bg-success/10 border-success/20 text-success",sub:"text-success/80",button:"border-success/20 text-success hover:bg-success/10"},warning:{box:"bg-warning/10 border-warning/20 text-warning",sub:"text-warning/80",button:"border-warning/20 text-warning hover:bg-warning/10"},info:{box:"bg-info/10 border-info/20 text-info",sub:"text-info/80",button:"border-info/20 text-info hover:bg-info/10"}};function Hn({variant:r,title:s,message:n,description:a,icon:i,actionLabel:o,onAction:c,actionDisabled:l,className:u}){const d=Kn[r];return e("div",{role:"error"===r?"alert":"status","aria-live":"error"===r?"assertive":"polite","aria-atomic":"true",className:z("border px-4 py-3 rounded-lg flex items-start justify-between gap-2 sm:gap-4",d.box,u),children:[e("div",{className:"flex items-start gap-2 min-w-0",children:[i,e("div",{className:"min-w-0",children:[s&&t("p",{className:"text-sm font-medium",children:s}),n&&t("p",{className:z("text-sm",s&&"mt-1"),children:n}),a&&t("p",{className:z("text-xs mt-2",d.sub),children:a})]})]}),o&&t(Un,{variant:"outline",size:"sm",onClick:c,disabled:l,className:z("flex-shrink-0",d.button),children:o})]})}const Yn=N("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Qn=s.forwardRef(({className:e,...r},s)=>t(O.Root,{ref:s,className:z(Yn(),e),...r}));Qn.displayName=O.Root.displayName;const Zn=v,Xn=s.createContext({}),ea=({...e})=>t(Xn.Provider,{value:{name:e.name},children:t(k,{...e})}),ta=()=>{const e=s.useContext(Xn),t=s.useContext(ra),{getFieldState:r,formState:n}=S(),a=r(e.name,n);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...a}},ra=s.createContext({}),sa=s.forwardRef(({className:e,...r},n)=>{const a=s.useId();return t(ra.Provider,{value:{id:a},children:t("div",{ref:n,className:z("space-y-2",e),...r})})});sa.displayName="FormItem";const na=s.forwardRef(({className:e,...r},s)=>{const{error:n,formItemId:a}=ta();return t(Qn,{ref:s,className:z(n&&"text-destructive",e),htmlFor:a,...r})});na.displayName="FormLabel";const aa=s.forwardRef(({...e},r)=>{const{error:s,formItemId:n,formDescriptionId:a,formMessageId:i}=ta();return t(P,{ref:r,id:n,"aria-describedby":s?`${a} ${i}`:`${a}`,"aria-invalid":!!s,...e})});aa.displayName="FormControl";const ia=s.forwardRef(({className:e,...r},s)=>{const{formDescriptionId:n}=ta();return t("p",{ref:s,id:n,className:z("text-sm text-muted-foreground",e),...r})});ia.displayName="FormDescription";const oa=s.forwardRef(({className:e,children:r,...s},n)=>{const{error:a,formMessageId:i}=ta(),o=a?String(a?.message):r;return o?t("p",{ref:n,id:i,className:z("text-sm font-medium text-destructive",e),...s,children:o}):null});oa.displayName="FormMessage";const ca=s.forwardRef(({className:e,type:r,...s},n)=>t("input",{type:r,className:z("flex h-10 sm:h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base sm:text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...s}));ca.displayName="Input";const la=s.forwardRef(({className:e,...r},s)=>t(j.Root,{className:z("grid gap-2",e),...r,ref:s}));la.displayName=j.Root.displayName;const ua=s.forwardRef(({className:e,...r},s)=>t(j.Item,{ref:s,className:z("aspect-square h-4 w-4 rounded-full border border-primary text-primary shadow focus:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),...r,children:t(j.Indicator,{className:"flex items-center justify-center",children:t(B,{className:"h-3.5 w-3.5 fill-primary"})})}));ua.displayName=j.Item.displayName;const da=s.forwardRef(({className:r,children:s,...n},a)=>e(q.Root,{ref:a,className:z("relative overflow-hidden",r),...n,children:[t(q.Viewport,{className:"h-full w-full rounded-[inherit]",children:s}),t(pa,{}),t(q.Corner,{})]}));da.displayName=q.Root.displayName;const pa=s.forwardRef(({className:e,orientation:r="vertical",...s},n)=>t(q.ScrollAreaScrollbar,{ref:n,orientation:r,className:z("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]",e),...s,children:t(q.ScrollAreaThumb,{className:z("relative rounded-full bg-border","vertical"===r&&"flex-1")})}));function ha(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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</text></svg>`}pa.displayName=q.ScrollAreaScrollbar.displayName;const ma=["🏢","🏬","🏣","🏤","🏦","🏛️","🏠","🏡","🏭","🏗️","🏪","🏨","🏫","🏥","💼","📊","📈","📉","📋","📁","📂","🗂️","🗃️","🗄️","📅","🗓️","📝","🖋️","✏️","🖊️","🖌️","🖍️","📇","📌","📍","📎","🖇️","💻","🖥️","🖨️","🖱️","⌨️","📱","📲","📡","🌐","🔗","🔒","🔓","⚙️","🔧","🛠️","🧑💻","👨💻","👩💻","🕹️","💾","📟","🖥️","🖲️","🚀","💡","🎨","🖼️","🧪","🔬","🧬","🎯","⚡","🎲","🎮","🧩","📷","🎥","✉️","📨","📩","📧","📞","☎️","📠","🗣️","💬","🗨️","📢","📣","🔔","🛎️","💰","💸","💳","🏦","📈","📉","⚖️","🧾","🪙","🏛️","⚗️","🧪","🔭","🔬","🩺","🧬","🩻","🏥","🌱","🌍","🌏","🌎","🌡️","👨💼","👩💼","👨🏫","👩🏫","👨🔬","👩🔬","👨🎨","👩🎨","👨🔧","👩🔧","👨🚀","👩🚀","👨⚖️","👩⚖️","🏅","🎖️","🥇","🥈","🥉","🏆","🎗️","🔑","🗝️","🧭","🛡️","🚩","🏳️🌈","🎟️","🎫"];function ga(e,t){const{response:r}=_s();return o(()=>{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 s=e.users?.length??0,n=r?.planVersion,a=r?.subscription,i=e.billingCurrency||"usd",o=$t({planVersion:n,currency:i,settingsMaxUsers:t?.settingsMaxUsers}),{maxUsers:c,hasSeatPricing:l,includedSeats:u}=o,d=l?Math.max(0,s-u):0,p=c>0?Math.max(0,c-s):1/0,h=c>0&&s>=c,m=c>0&&s>=.8*c&&!h,g=l&&n?Ft(n,i,a?.billingInterval??"monthly"):null,f=Lt({memberCount:s,maxUsersConfig:o});return{hasSeatPricing:l,memberCount:s,includedSeats:u,maxUsers:c,maxSeats:c,limitSource:o.source,billableSeats:d,availableSeats:p,isAtMax:h,isNearMax:m,perSeatPriceCents:g,currency:i,canInvite:f.canInvite,inviteBlockReason:f.blockReason,inviteBlockMessageKey:f.blockMessageKey,inviteBlockMessageValues:f.blockMessageValues}},[r,e,t?.settingsMaxUsers])}function fa({title:r,children:s,className:n}){return e("div",{className:z("px-2 flex flex-col gap-1",n),children:[t("div",{className:"text-xs font-bold text-muted-foreground uppercase tracking-wide px-2 pb-1 shrink-0 whitespace-nowrap",children:r}),s]})}function wa({icon:r,label:s,active:n=!1,onClick:a,className:i}){return e("button",{className:z("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",n?"bg-primary/10 text-primary font-medium":"hover:bg-muted hover:text-foreground",i),onClick:a,"aria-current":n?"true":void 0,children:[r,t("span",{className:"min-w-0 truncate",children:s}),t(I,{"aria-hidden":"true",className:"h-4 w-4 ms-auto opacity-40 sm:hidden rtl:rotate-180"})]})}const ya=g(()=>import("./SettingsDialog-uVKFxlal.mjs").then(function(e){return e.S}).then(e=>({default:e.default})));const ba=({children:s})=>{const{currentWorkspace:n,switchToWorkspace:a,workspaces:o}=mn(),[c,l]=h(!1),[u,p]=h(dn.Profile),g=i(!1);return d(()=>{const e=hn.getState();l(e.open),p(e.section);return hn.subscribe(e=>{l(e.open),p(e.section)})},[]),d(()=>{if(g.current)return;if(!n)return;const e=Ge();if(!e)return;const t=function(e){if(e.screen&&pn.has(e.screen))return e.screen;switch(e.action){case Me.Checkout:case Me.Billing:case Me.SelectPlan:return dn.Subscription;case Me.CreditPurchase:return dn.Credits;default:return null}}(e);if(!t)return g.current=!0,void Je();const r=e.ws;if(r&&r!==n._id){const e=o.find(e=>e._id===r);return e?void a(e).catch(e=>{ee(e,{component:"WorkspaceSettingsProvider",action:"switchWorkspaceFromUrl",metadata:{targetWs:r}}),g.current=!0,Je()}):(g.current=!0,void Je())}g.current=!0,hn.openWorkspaceSettings(t,e),Je()},[n,o,a]),e(r,{children:[s,n&&c&&t(rr,{fallback:null,children:t(m,{fallback:null,children:t(ya,{workspace:n,open:c,onOpenChange:e=>{e||hn.closeSettings()},section:u,onSectionChange:e=>{hn.setSection(e)},showTrigger:!1})})})]})},ka=(e,t,r)=>{if(t!==Pe.V1)throw new Error(`Invalid version: "${t}". Only "${Pe.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).`)},va=n.memo(({serverUrl:e,version:r,orgId:s,auth:a,locale:i,defaultPermissions:o,getCheckoutStripeParams:c,loadingComponent:l,ui:u,children:p})=>{ka(e,r,s);const h=n.useMemo(()=>({serverUrl:e,version:r,orgId:s}),[e,r,s]),m=n.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 d(()=>(Ie.setCallbacks(g?{handleEvent:g}:null),()=>{Ie.setCallbacks(null)}),[g]),t(ts,{locale:i,messageOverrides:u?.messages,children:t(Gr,{children:t(Hs,{loadingComponent:l,children:t(bn,{callbacks:m,children:t(Sn,{children:t(kn,{config:h,auth:a,children:t(Kr,{getCheckoutStripeParams:c,children:t(Zs,{appPermissions:o,children:t(nn,{ui:u,children:t(In,{children:t(Fs,{children:t(tn,{children:t(Vs,{children:t(Nn,{children:t(ba,{children:p})})})})})})})})})})})})})})})});va.displayName="SaaSOSProviderInner";const Sa=({children:e,...r})=>t(rr,{errorTitle:r.ui?.errorBoundary?.title,retryLabel:r.ui?.errorBoundary?.retryLabel,children:t(va,{...r,children:e})});Sa.displayName="SaaSOSProvider";const Ca=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{status:n}=yn();return tr(n).isLoading?r??null:n!==er.authenticated?s??null:t},Pa=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{status:n}=yn();return tr(n).isLoading?r??null:n!==er.unauthenticated?s??null:t};Ca.displayName="WhenAuthenticated",Pa.displayName="WhenUnauthenticated";const Na=e=>{const{children:t,fallback:r,roles:s}=e,{user:n}=yn();return s.includes(n?.role??"")?t:r||null},xa=e=>{const{children:t,fallback:r,roles:s}=e,{user:n}=yn(),{currentWorkspace:a}=mn(),i=a?.users.find(e=>e._id===n?.id);return i&&s.includes(i?.role??"")?t:r||null};Na.displayName="WhenRoles",xa.displayName="WhenWorkspaceRoles";const Ea=e=>{const{children:t,fallback:r,permission:s}=e,{can:n}=Ln();return n(s)?t:r??null};function Ia(){const e=u(En);if(void 0===e)throw new Error("useUserAttributes must be used within a UserProvider");return e}function Ra(){const e=u(En);if(void 0===e)throw new Error("useUserFeatures must be used within a UserProvider");return{features:e.features,isLoading:e.isLoading,error:e.error,refreshFeatures:e.refreshFeatures,isFeatureEnabled:t=>Boolean(e.features[t])}}Ea.displayName="WhenPermission";const Ua=e=>{const{children:t,slug:r}=e,{currentWorkspace:s}=mn(),n=s?.features?.[r];return n?t:null},Wa=e=>{const{children:t,slug:r}=e,{currentWorkspace:s}=mn(),n=s?.features?.[r];return n?null:t},Aa=e=>{const{children:t,slug:r}=e,{isFeatureEnabled:s}=Ra();return s(r)?t:null},Ta=e=>{const{children:t,slug:r}=e,{isFeatureEnabled:s}=Ra();return s(r)?null:t};Ua.displayName="WhenWorkspaceFeatureEnabled",Wa.displayName="WhenWorkspaceFeatureDisabled",Aa.displayName="WhenUserFeatureEnabled",Ta.displayName="WhenUserFeatureDisabled";const Fa=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{response:n,loading:a}=_s();return a?r??null:n?.subscription?t:s??null},_a=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{response:n,loading:a}=_s();return a?r??null:n?.subscription?s??null:t},Oa=e=>{const{children:t,plans:r,loadingComponent:s,fallbackComponent:n}=e,{response:a,loading:i}=_s();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},Da=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{response:n,loading:a}=_s();return a?r??null:"trialing"!==n?.subscription?.subscriptionStatus?s??null:t},$a=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{response:n,loading:a}=_s();return a?r??null:n?.subscription?.subscriptionStatus===yt.Trialing?s??null:t},La=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{behavior:n}=an(),a=e.daysThreshold??n?.trialEndingDays??3,{response:i,loading:o}=_s();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};Fa.displayName="WhenSubscription",_a.displayName="WhenNoSubscription",Oa.displayName="WhenSubscriptionToPlans",Da.displayName="WhenTrialing",$a.displayName="WhenNotTrialing",La.displayName="WhenTrialEnding";const Ma=e=>{const{slug:t,children:r,loadingComponent:s,fallbackComponent:n}=e,{quotas:a,loading:i}=rn();if(i)return s??null;const o=a?.[t];return o?o.available<=0?n??null:r:n??null},Ba=e=>{const{slug:t,children:r,loadingComponent:s,fallbackComponent:n}=e,{quotas:a,loading:i}=rn();if(i)return s??null;const o=a?.[t];return o?o.available>0?n??null:r:n??null},ja=e=>{const{slug:t,children:r,loadingComponent:s,fallbackComponent:n}=e,{quotas:a,loading:i}=rn();if(i)return s??null;const o=a?.[t];return o&&o.hasOverage&&!1!==o.allowOverage?r:n??null},qa=e=>{const{slug:t,threshold:r,children:s,loadingComponent:n,fallbackComponent:a}=e,{quotas:i,loading:o}=rn();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};Ma.displayName="WhenQuotaAvailable",Ba.displayName="WhenQuotaExhausted",ja.displayName="WhenQuotaOverage",qa.displayName="WhenQuotaThreshold";const Va=({children:e})=>{const{currentWorkspace:t}=mn(),r=t?._id,{balance:s,loading:n,error:a,refetch:i}=zs(),{packages:o,loading:c}=Ls(r),{consumeCredits:l,loading:u,error:d}=Ds(r),{purchaseCredits:p,loading:h,error:m}=$s(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}=ze(r),n=await p({creditPackageId:e._id,successUrl:t,cancelUrl:s});n.url&&He(n.url)},purchasing:h,refetch:i,error:d||m||a})};Va.displayName="CreditActionsProvider";const za=({children:e})=>{const{balance:t,loading:r,error:s,refetch:n}=zs();return e({balance:t,loading:r,error:s,refetch:n})};function Ga({children:s,loadingFallback:n,errorFallback:a,redirectBaseUrl:i}){const{packages:o,notes:c,loading:l,error:u,refetch:d}=js(),{isAuthenticated:h,signIn:m}=yn(),g=p(e=>{if(h)hn.openWorkspaceSettings(dn.Credits,{action:Me.CreditPurchase,packageId:e});else if(i){const t=qe({action:Me.CreditPurchase,screen:"credits",packageId:e},i);m(t)}else m()},[h,m,i]);return l?void 0!==n?t(r,{children:n}):e("div",{className:"space-y-4",children:[t(zn,{className:"h-8 w-48"}),t("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(e=>t(zn,{className:"h-48 rounded-lg"},e))})]}):u?a?t(r,{children:a(u)}):t("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive",children:u}):t(r,{children:s({loading:l,error:u,packages:o,notes:c,refetch:d,selectPackage:g})})}za.displayName="CreditBalance";const Ja=e=>{const{min:t=1,children:r,loadingComponent:s,fallbackComponent:n}=e,{balance:a,loading:i}=zs();return i?s??null:a?a.available<t?n??null:r:n??null},Ka=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{balance:n,loading:a}=zs();return a?r??null:n?n.available>0?s??null:t:s??null},Ha=e=>{const{threshold:t,children:r,loadingComponent:s,fallbackComponent:n}=e,{balance:a,loading:i}=zs();return i?s??null:a?a.available>t?n??null:r:n??null};function Ya(e){if(!e)return null;const t=new Date(e);return isNaN(t.getTime())?null:t}function Qa(){const{response:e}=_s();return o(()=>{const t=e?.subscription;if(!t||"trialing"!==t.subscriptionStatus)return{isTrialing:!1,daysRemaining:0,trialEndsAt:null,trialStartedAt:null,isTrialEnding:!1};const r=Ya(t.trialEnd)??Ya(t.stripeCurrentPeriodEnd),s=Ya(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])}Ja.displayName="WhenCreditsAvailable",Ka.displayName="WhenCreditsExhausted",Ha.displayName="WhenCreditsLow";const Za=D.object({name:D.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.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)")}),Xa=({onSuccess:s,onError:n,className:a="w-full",fieldClassName:i="flex flex-col gap-1.5 w-full",autoFocus:o=!0,showSuccessMessage:c=!0,hideLogo:l=!1,hideTitles:u=!1})=>{const{t:m}=cs(),[g,f]=h(!1),[w,y]=h(!1),{submitBetaForm:k,isLoading:S,isSubmitting:P,error:N,config:x,success:E,message:I}=(()=>{const{t:e}=cs(),t=ps(),[r,s]=h(null),[n,a]=h(!0),[i,o]=h(!1),[c,l]=h(null),[u,m]=h(!1),[g,f]=h(null);return d(()=>{let r=!1;return(async()=>{a(!0),l(null);try{const e=new ye(t),n=await e.fetchConfig();r||s(n)}catch(t){r||l(t instanceof Error?t.message:e("beta.errorMessage"))}finally{r||a(!1)}})(),()=>{r=!0}},[t]),{isLoading:n,isSubmitting:i,config:r,error:c,success:u,message:g,submitBetaForm:p(async r=>{if(!t){const t=e("errors.generic");return l(t),{success:!1,message:t}}try{o(!0),l(null),m(!1),f(null);const e=new ye(t),s=await e.submitBetaUser({name:r.name||"",email:r.email}),n="success"===s.status;return m(n),f(s.message),{success:n,message:s.message}}catch(t){const r=t instanceof Error?t.message:e("beta.errorMessage");return l(r),m(!1),f(r),{success:!1,message:r}}finally{o(!1)}},[t])}})();d(()=>{E&&c&&(f(!0),y(!0)),N&&y(!0)},[E,c,N]);const R=C({resolver:b(Za),defaultValues:{email:"",name:""},mode:"onChange",reValidateMode:"onChange"});d(()=>{o&&R.setFocus("name")},[o,R]);const U=R.formState.isValid&&!P;return t("div",{className:"saas-os-ui",style:{width:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},children:e("div",S?{className:z("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",a),children:[t(zn,{className:"h-24 w-24 rounded-lg"}),t(zn,{className:"h-6 w-32"}),e("div",{className:"w-full space-y-4",children:[e("div",{className:"space-y-2",children:[t(zn,{className:"h-4 w-16"}),t(zn,{className:"h-10 w-full"})]}),e("div",{className:"space-y-2",children:[t(zn,{className:"h-4 w-16"}),t(zn,{className:"h-10 w-full"})]}),t(zn,{className:"h-10 w-full"})]})]}:{className:"flex flex-col items-center justify-center w-full px-2.5 sm:px-6 py-2.5 sm:py-6 gap-y-2.5 sm:gap-y-4",children:[!l&&e("div",{className:"flex flex-col items-center justify-center w-full",children:[x?.logo&&t(ti,{logo:x?.logo}),x?.name&&t("div",{children:x?.name})]}),t(v,{...R,children:e("form",{onSubmit:R.handleSubmit(async e=>{try{const t=await k(e);t.success?(s?.(),R.reset(),c&&f(!0),y(!0)):(n?.(t.message),y(!0))}catch(e){n?.(e instanceof Error?e.message:m("beta.errorMessage")),y(!0)}}),className:a,noValidate:!0,"aria-busy":P,children:[!w&&e(r,{children:[!u&&x?.screen?.register&&t(ei,{screen:x?.screen?.register}),t(ea,{control:R.control,name:"name",render:({field:r})=>e(sa,{className:i,children:[t(na,{children:m("beta.nameLabel")}),t(aa,{children:t(ca,{...r})}),t(ia,{}),t(oa,{})]})}),t(ea,{control:R.control,name:"email",render:({field:r})=>e(sa,{className:i,children:[t(na,{children:m("beta.emailLabel")}),t(aa,{children:t(ca,{...r})}),t(ia,{}),t(oa,{})]})}),t(Un,{type:"submit",disabled:!U,className:i,children:m(P?"beta.submittingText":"beta.submitText")})]}),w&&N&&e("div",{className:"flex flex-col items-center justify-center w-full",children:[e("div",{className:"border-destructive/30 text-destructive",role:"alert","aria-live":"assertive","aria-atomic":!0,children:[t("span",{className:"text-4xl mb-2",role:"img","aria-label":m("settings.common.error"),children:"❗"}),N]}),t("div",{className:"mt-4 flex justify-center",children:t(Un,{type:"button",onClick:()=>{y(!1),R.reset()},className:i,children:m("beta.tryAgain")})})]}),w&&g&&I&&t("div",{className:"flex flex-col items-center justify-center w-full text-success border-success/30 text-center",children:x?.screen?.thankYou&&t(ei,{screen:x?.screen?.thankYou})})]})}),!w&&t("div",{children:e("div",{children:[m("beta.privacyConsent")," ",t("a",{href:x?.privacyPolicy,target:"_blank",rel:"noopener noreferrer",className:"text-info hover:text-info",children:m("beta.privacyPolicy")})," ",m("beta.and")," ",t("a",{href:x?.termsOfService,target:"_blank",rel:"noopener noreferrer",className:"text-info hover:text-info",children:m("beta.termsOfService")}),"."]})})]})})};function ei({screen:r}){return e("div",{className:"flex flex-col items-center justify-center w-full",children:[t("p",{className:"text-2xl font-bold",children:r?.title}),t("p",{className:"text-sm text-muted-foreground",children:r?.description})]})}function ti({logo:e}){return t("img","string"==typeof e?{src:e,alt:"Logo",className:"max-h-24"}:{src:e.bucket?.url,alt:"Logo",className:"max-h-24"})}function ri({slug:s,children:n,loadingFallback:a,errorFallback:i,redirectBaseUrl:o}){const{items:c,plans:l,notes:u,loading:d,error:h,refetch:m}=fs(s),{isAuthenticated:g,signIn:f}=yn(),w=p((e,t,r)=>o?qe({action:"selectPlan",plan:e,interval:t,currency:r},o):null,[o]),y=p((e,t,r)=>{if(g)return void hn.openWorkspaceSettings(dn.Subscription,{action:"selectPlan",plan:e,interval:t,currency:r});const s=w(e,t,r);f(s??void 0)},[g,f,w]);return d?void 0!==a?t(r,{children:a}):e("div",{className:"space-y-4",children:[t(zn,{className:"h-8 w-48"}),t("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(e=>t(zn,{className:"h-64 rounded-lg"},e))})]}):h?i?t(r,{children:i(h)}):t("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive",children:h}):t(r,{children:n({loading:d,error:h,items:c,plans:l,notes:u,refetch:m,selectPlan:y})})}const si=s.forwardRef(({className:e,...r},s)=>t($.Root,{ref:s,className:z("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...r}));si.displayName=$.Root.displayName;const ni=s.forwardRef(({className:e,...r},s)=>t($.Image,{ref:s,className:z("aspect-square h-full w-full",e),...r}));ni.displayName=$.Image.displayName;const ai=s.forwardRef(({className:e,...r},s)=>t($.Fallback,{ref:s,className:z("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...r}));ai.displayName=$.Fallback.displayName;const ii=s.forwardRef(({className:e,orientation:r="horizontal",decorative:s=!0,...n},a)=>t(V.Root,{ref:a,decorative:s,orientation:r,className:z("shrink-0 bg-border","horizontal"===r?"h-[1px] w-full":"h-full w-[1px]",e),...n}));ii.displayName=V.Root.displayName;const oi=g(()=>import("./SettingsDialog-uVKFxlal.mjs").then(function(e){return e.S}).then(e=>({default:e.default})));function ci(s){const{t:n,dir:a}=cs(),{isAuthenticated:i,user:o}=yn(),c=Ne(ps()),{workspaces:l,currentWorkspace:u,loading:p,refreshing:g,switchingToId:f,fetchWorkspaces:w,getFeatures:y,refreshWorkspaces:b,setCurrentWorkspace:k,switchToWorkspace:v}=mn(),{settings:S}=ms(),{visible:C}=Mn(),[P,N]=h(!1),[E,I]=h(0),[A,T]=h(""),F=p||g;d(()=>{i&&c&&(0===l.length?(w(),y()):y())},[i,c]),d(()=>{i&&c&&E>0&&b()},[E,i,c]);const _=l,O=_.filter(e=>e._id!==u?._id).filter(e=>e.name.toLowerCase().includes(A.toLowerCase())),D=(S?.workspace?.canCreateWorkspace??!0)&&C(e=>e.workspaceSwitcher?.createButton),$=(S?.workspace?.showSwitcher??!0)&&C(e=>e.workspaceSwitcher?.show),L=S?.workspace?.maxWorkspacesPerUser??0,M=_?.filter(e=>("object"==typeof e.createdBy?e.createdBy._id?.toString():e.createdBy?.toString())===o?.id?.toString()).length??0,B=!1!==D&&(0===L||M<L);return d(()=>{!$&&l.length>0&&!u&&v(l[0]).catch(e=>{ee(e,{component:"WorkspaceProvider",action:"autoSelectWorkspace"})})},[$,l,u]),!$&&u?e(r,{children:[t("div",{onClick:()=>N(!0),children:s.trigger?.(F,u)}),t(m,{fallback:null,children:t(oi,{workspace:u,open:P,onOpenChange:N,showTrigger:!1})})]}):e(Wn,{open:P,onOpenChange:N,children:[t(An,{children:s.trigger?.(F,u)}),e(_n,{dir:a,className:"max-w-2xl min-w-full md:min-w-[800px]",children:[e(On,{dir:a,children:[e(Dn,{className:"flex items-center gap-2",children:[t(R,{className:"h-5 w-5"}),n("workspace.switchTitle")]}),t($n,{children:n("workspace.switchDescription")})]}),!o&&t("div",{className:"flex flex-col items-center justify-center h-full py-4 sm:py-8",children:t("div",{className:"text-sm font-medium text-muted-foreground",children:n("workspace.notLoggedIn")})}),o&&e("div",{dir:a,className:"flex flex-col gap-4",children:[u&&t(li,{workspace:u,isCurrentWorkspace:!0,switchToWorkspace:v,switchingToId:f,onClose:()=>N(!1),setCurrentWorkspace:k,setOpen:N,workspacesToUse:_}),t(ii,{}),e("div",{children:[e("div",{className:"flex items-center justify-between",children:[t("div",{className:"text-sm font-medium text-muted-foreground",children:n("workspace.availableWorkspaces",{count:O.length})}),t("div",{children:t(Un,{progress:g,disabled:g,variant:"ghost",onClick:function(){i&&c&&I(e=>e+1)},startIcon:t(U,{}),children:n("settings.common.refreshAction",{loading:String(g)})})})]}),e("div",{className:"relative",children:[t(W,{className:"absolute start-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"}),t(ca,{placeholder:n("workspace.searchPlaceholder"),value:A,onChange:e=>T(e.target.value),className:"ps-10"})]}),p?e("div",{className:"flex items-center justify-center py-8",children:[t(x,{className:"h-6 w-6 animate-spin text-muted-foreground"}),t("span",{className:"ms-2 text-sm text-muted-foreground",children:n("workspace.loadingWorkspaces")})]}):0===O.length?e("div",{className:"text-center py-8",children:[t(R,{className:"mx-auto h-12 w-12 text-muted-foreground"}),t("p",{className:"mt-2 text-sm text-muted-foreground",children:n(A?"workspace.noWorkspacesFound":"workspace.noWorkspacesAvailable")})]}):t(da,{className:"h-64",dir:a,children:t("div",{dir:a,className:"flex flex-col gap-2 my-2.5",children:O.map(e=>{const r=e._id===u?._id;return t(li,{workspace:e,isCurrentWorkspace:r,switchToWorkspace:v,switchingToId:f,onClose:()=>N(!1),setCurrentWorkspace:k,setOpen:N,workspacesToUse:_},e._id)})})})]}),B&&e(r,{children:[t(ii,{}),t(ui,{onCreated:()=>{w()}})]})]})]})]})}function li(r){const{t:s}=cs(),{visible:n}=Mn(),a=n(e=>e.workspaceSwitcher?.memberCount),i=n(e=>e.workspaceSwitcher?.planBadge),{workspace:o,setCurrentWorkspace:c,setOpen:l,workspacesToUse:u,switchingToId:d}=r,p=r.isCurrentWorkspace??!1,h=d===o._id,g=o.subscription??null,f=null!=g&&"object"==typeof g?g.plan??null:null,w=f?.name??"";return e("div",{className:z("flex items-center gap-3 rounded-lg border-2 p-3 border-border",{"bg-muted text-muted-foreground":p}),children:[e(si,{className:"h-8 w-8 flex items-center justify-center",children:[t("div",{children:t(ni,{src:o.image&&o.image.trim()?o.image:void 0})}),t(ai,{children:(y=o.name,y.split(" ").map(e=>e[0]).join("").toUpperCase().slice(0,2))})]}),e("div",{className:"flex-1 min-w-0 max-w-full",children:[t("div",{className:"flex items-center gap-2",children:t("span",{className:"font-medium line-clamp-1 text-ellipsis overflow-hidden max-w-full",children:o.name})}),a&&e("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[t(A,{className:"h-3 w-3"}),t("span",{children:s("workspace.membersCount",{count:o.users?.length||0})})]}),i&&w&&t("div",{className:"max-w-fit",children:t("div",{className:"flex items-center gap-1 text-sm bg-success text-success-foreground rounded-full px-2 py-0.5",children:t("span",{className:"text-xs",children:w})})})]}),e("div",{className:"flex items-center gap-2",children:[p?null:t(Un,{size:"sm",disabled:null!==d||h,progress:h,onClick:()=>{r.switchToWorkspace(o).then(()=>l(!1)).catch(e=>{ee(e,{component:"WorkspaceItem",action:"switchToWorkspace",metadata:{workspaceId:o._id}})})},children:s("workspace.switchTo")}),t(m,{fallback:null,children:t(oi,{workspace:o,onClose:()=>{if(p){const e=u.findIndex(e=>e._id?.toString()===o._id?.toString());-1!==e&&c(u[e])}}})})]})]});var y}function ui(s){const{t:n,dir:a}=cs(),{switching:i}=mn(),[o,c]=h(!1),[l,u]=h("emoji"),[d,p]=h("🏢"),[m,g]=h(!1),{createWorkspace:f}=mn(),w=D.object({name:D.string().min(2,{message:n("workspace.workspaceNameMinLength")}),image:D.string().optional()}),y=C({resolver:b(w),defaultValues:{name:"",image:""}});return e(Wn,{open:o,onOpenChange:c,children:[t(An,{asChild:!0,children:e(Un,{className:"w-full rounded-none",disabled:i,children:[t(T,{className:"h-4 w-4 me-2"}),n("workspace.createNew")]})}),e(_n,{dir:a,className:"max-w-xl min-w-full sm:min-w-[600px]",children:[e(On,{children:[t(Dn,{children:n("workspace.createTitle")}),t($n,{children:n("workspace.createDescription")})]}),t(Zn,{...y,children:e("form",{onSubmit:y.handleSubmit(async function(e){let t="";if("emoji"===l)t=ha(d);else if("url"===l&&e.image)try{new URL(e.image),t=e.image}catch{return void y.setError("image",{message:n("workspace.invalidUrl")})}g(!0);try{await f(e.name,t),c(!1),y.reset(),p("🏢"),u("emoji"),s?.onCreated?.()}catch(t){ee(t,{component:"WorkspaceProvider",action:"createWorkspace",metadata:{name:e.name}})}finally{g(!1)}}),children:[t(ea,{control:y.control,name:"name",render:({field:r})=>e(sa,{children:[t(na,{children:n("workspace.workspaceName")}),t(aa,{children:t(ca,{placeholder:n("workspace.workspaceNamePlaceholder"),...r})}),t(oa,{})]})}),e("div",{className:"flex flex-col gap-y-2 my-2",children:[e("div",{children:[t(Qn,{className:"text-sm font-medium",children:n("workspace.workspaceIcon")}),t(ia,{children:n("workspace.iconDescription")})]}),e(la,{value:l,onValueChange:e=>u(e),className:"flex flex-col gap-y-2",children:[e("div",{className:"flex items-center gap-x-2 my-1",children:[t(ua,{value:"emoji",id:"emoji"}),e(Qn,{htmlFor:"emoji",className:"flex items-center gap-2",children:[t(F,{className:"h-4 w-4"}),n("workspace.chooseEmoji")]})]}),e("div",{className:"flex items-center gap-x-2 my-1",children:[t(ua,{value:"url",id:"url"}),e(Qn,{htmlFor:"url",className:"flex items-center gap-2",children:[t(_,{className:"h-4 w-4"}),n("workspace.customImageUrl")]})]})]}),"emoji"===l&&e("div",{className:"flex flex-col gap-y-2",children:[e("div",{className:"flex items-center gap-3",children:[t("span",{className:"text-sm font-medium",children:n("general.previewLabel")}),t("div",{className:"w-12 h-12 rounded-lg border-2 border-border flex items-center justify-center text-2xl bg-muted",children:d})]}),t(da,{className:"h-32 w-full rounded-md border",children:t("div",{className:"p-4 grid grid-cols-8 gap-2",children:ma.map((e,r)=>t("button",{type:"button",onClick:()=>(e=>{p(e),y.setValue("image",ha(e))})(e),"aria-label":e,"aria-pressed":d===e,className:"w-10 h-10 sm:w-8 sm:h-8 rounded flex items-center justify-center text-lg hover:bg-muted transition-colors "+(d===e?"bg-primary text-primary-foreground":""),children:e},r))})})]}),"url"===l&&e("div",{className:"flex flex-col gap-y-2",children:[t(ea,{control:y.control,name:"image",render:({field:r})=>e(sa,{children:[t(na,{children:n("workspace.imageUrl")}),t(aa,{children:t(ca,{placeholder:n("workspace.imageUrlPlaceholder"),...r})}),t(ia,{children:n("workspace.imageUrlDescription")}),t(oa,{})]})}),y.watch("image")&&y.watch("image")?.trim()&&e("div",{className:"flex items-center gap-3",children:[t("span",{className:"text-sm font-medium",children:n("general.previewLabel")}),t("div",{className:"w-12 h-12 rounded-lg border-2 border-border overflow-hidden bg-muted",children:t("img",{src:y.watch("image")||void 0,alt:"Workspace preview",className:"w-full h-full object-cover",onError:e=>{e.currentTarget.style.display="none"}})})]})]})]}),e("div",{className:"flex justify-end gap-3 pt-4",children:[t(Un,{type:"button",variant:"outline",onClick:()=>{c(!1),y.reset(),p("🏢"),u("emoji")},disabled:m,children:n("settings.common.cancel")}),t(Un,{type:"submit",disabled:m,children:m?e(r,{children:[t(x,{className:"me-2 h-4 w-4 animate-spin"}),n("workspace.creating")]}):n("workspace.createWorkspace")})]})]})})]})]})}export{bt as $,ee as A,Un as B,Gn as C,Wn as D,qn as E,Zn as F,ea as G,sa as H,na as I,aa as J,ca as K,Jn as L,oa as M,Qn as N,st as O,Jt as P,ia as Q,la as R,zn as S,ua as T,da as U,ma as V,ha as W,xn as X,gs as Y,Xs as Z,Ps as _,_n as a,Sa as a$,Cs as a0,vs as a1,Es as a2,Is as a3,Ns as a4,ks as a5,At as a6,yt as a7,xt as a8,Tt as a9,fe as aA,er as aB,je as aC,Le as aD,ge as aE,Xa as aF,tt as aG,rt as aH,be as aI,Va as aJ,za as aK,Vs as aL,St as aM,Ct as aN,Ga as aO,Ht as aP,Ee as aQ,Js as aR,at as aS,it as aT,Xt as aU,ri as aV,ke as aW,Nn as aX,tn as aY,xe as aZ,Qr as a_,Ft as aa,wt as ab,vt as ac,ft as ad,kt as ae,Wt as af,ht as ag,Et as ah,Ve as ai,$e as aj,rn as ak,_s as al,It as am,yn as an,ga as ao,zt as ap,dn as aq,fa as ar,wa as as,an as at,on as au,nn as av,An as aw,pn as ax,Ut as ay,Pe as az,Dn as b,ys as b$,ve as b0,Fs as b1,Se as b2,Ca as b3,Ja as b4,Ka as b5,Ha as b6,_a as b7,$a as b8,Ea as b9,lt as bA,ut as bB,pt as bC,gt as bD,Rt as bE,Nt as bF,dt as bG,Zt as bH,_e as bI,Ge as bJ,$t as bK,Qt as bL,Ze as bM,Ws as bN,jn as bO,Bn as bP,Ds as bQ,Os as bR,Ys as bS,xs as bT,bs as bU,js as bV,ws as bW,fs as bX,Us as bY,Rs as bZ,ps as b_,Ma as ba,Ba as bb,ja as bc,qa as bd,Na as be,Fa as bf,Oa as bg,La as bh,Da as bi,Pa as bj,Ta as bk,Aa as bl,Wa as bm,Ua as bn,xa as bo,Ce as bp,ci as bq,_t as br,Ot as bs,Dt as bt,Je as bu,et as bv,Xe as bw,qe as bx,Ie as by,ot as bz,$n as c,Qa as c0,Ss as c1,As as c2,Ia as c3,Ra as c4,Lt as c5,Ke as c6,z as d,Ln as e,Mn as f,nt as g,zs as h,Ls as i,Bs as j,Ms as k,$s as l,Me as m,Be as n,Ae as o,Hn as p,Vn as q,ze as r,He as s,Pt as t,cs as u,vn as v,hn as w,Rn as x,mn as y,ms as z};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use client";
|
|
2
|
-
const e={settings:{titles:{profile:"账户",security:"安全",general:"工作区设置",users:"工作区成员",subscription:"套餐与账单",usage:"用量",credits:"积分",features:"工作区功能",notifications:"通知",permissions:"权限",danger:"危险区域"},sidebar:{account:"账户",workspace:"工作区",profile:"账户",security:"安全",general:"设置",users:"成员",subscription:"套餐与账单",usage:"用量",credits:"积分",features:"功能",notifications:"通知",permissions:"权限",danger:"危险区域"},common:{refresh:"刷新",refreshing:"正在刷新...",retry:"重试",retrying:"正在重试...",save:"保存",saving:"正在保存...",cancel:"取消",delete:"删除",dismiss:"关闭",loading:"正在加载...",success:"操作成功!",error:"错误",refreshAction:"{loading, select, true {正在刷新...} other {刷新}}",retryAction:"{loading, select, true {正在重试...} other {重试}}",noPermissionTitle:"访问受限",noPermissionDescription:"您没有权限访问此部分。如需访问权限,请联系工作区管理员。",billingManageOnly:"只有具有账单管理权限的用户才能执行此操作。",openSettings:"打开设置",back:"返回"}},subscription:{managePlan:"管理您的套餐和账单",changePlan:"更改套餐",viewPricingPlans:"查看价格方案",viewPlans:"查看套餐",upgradePlan:"立即升级",subscribe:"订阅",currentPlan:"当前套餐",noSubscription:"您没有有效的订阅",choosePlan:"选择您的套餐",choosePlanDescription:"比较各套餐,选择最适合您需求的方案",forWorkspace:"适用于 {name}",planUpdateAvailable:"套餐更新可用",updateSuccess:"订阅已成功更新!",updateFailed:"更新失败",cancelTitle:"取消订阅",cancelConfirm:"您确定要取消订阅吗?",cancelKeep:"保留订阅",cancelButton:"是的,取消订阅",cancelTrialTitle:"取消试用",cancelTrialConfirm:"您确定要取消试用吗?",cancelTrialAccess:"您的试用将持续到",cancelTrialNoCharge:"不会向您收费 — 试用期将自动到期",cancelTrialResume:"您可以在试用结束前随时恢复试用",cancelTrialKeep:"保留试用",cancelTrialButton:"是的,取消试用",canceling:"正在取消...",cancelSuccess:"订阅将在当前计费周期结束时取消。",cancelNotCharged:"取消后将不再收费",cancelResumeAnytime:"您可以在订阅结束前随时恢复",resumeTitle:"恢复订阅",resumeTrial:"恢复试用",resumeConfirm:"您确定要恢复订阅吗?",resumeKeep:"保持取消状态",resumeButton:"是的,恢复订阅",resuming:"正在恢复...",resumeSuccess:"订阅已恢复。",managePayment:"管理支付方式",openingPortal:"正在打开...",viewAllPlans:"查看所有套餐",scheduledCancellation:"订阅已安排取消",scheduledTrialCancellation:"试用已安排取消",paymentPastDue:"付款逾期",paymentPastDueDescription:"请更新您的支付方式以避免服务中断。",subscriptionPaused:"订阅已暂停",subscriptionPausedDescription:"您的订阅当前已暂停。恢复订阅以获得完整访问权限。",errorLoading:"加载订阅数据时出错",errorLoadingDescription:"请检查您的网络连接并重试。",errorProcessing:"订阅处理失败",errorCanceling:"取消订阅失败",errorResuming:"恢复订阅失败",invalidWorkspace:"无效的工作区 ID",billingInterval:{monthly:"月付",quarterly:"季付",yearly:"年付",perMonth:"/月",perQuarter:"/季",perYear:"/年"},seats:{title:"席位",members:"成员",included:"包含",billable:"计费",perExtraSeat:"每增加一个席位",limit:"上限",includedSeats:"包含席位数",maxSeats:"最大席位数",freeWithBase:"包含在基础价格中",allIncluded:"全部包含",extra:"额外",unlimited:"不限"},items:{features:"功能",limits:"限制",quotas:"用量配额",credits:"AI Credits",creditsPerMonth:"Credits per month",creditsOneTime:"Credits (given once)",creditRenewal:"Credit renewal",creditModeLifetime:"Given once",creditsPerPeriod:"Credits per month",creditRollover:"Credit renewal",creditModeReset:"Fresh every month",creditModeTopup:"Adds up every month"},checkout:{upgrade:"升级",downgrade:"降级",switchTo:"切换至",select:"选择"},status:{active:"有效",canceling:"取消中",trial:"试用",canceled:"已取消",pastDue:"逾期",paused:"已暂停",deprecated:"已弃用",unknown:"未知"},plan:"套餐",invoicesTab:"账单",changePlanButton:"更改套餐",noPlanAssigned:"未分配套餐",free:"免费",perSeatDisplay:"+ {price}/席位{interval}",estTotalDisplay:"预估总计:{total}{interval}({count, plural, one {# 个额外席位} other {# 个额外席位}})",nextBillingDisplay:"下次计费日:{date}",membersInWorkspace:"工作区有 {count, plural, one {# 名成员} other {# 名成员}}",billingInCurrency:"以{currency}计费",savingsPercent:"节省 {percent, number}%",switchToInterval:"切换至{interval}",seatPriceDisplay:"+ {price}/席位{interval}({included} {includedLabel})",trialEnded:"您的试用期已结束。",trialEndsIn:"您的试用期将在 {days, plural, one {# 天} other {# 天}}后结束。",onTrial:"您正在试用中。",upgradeToKeepAccess:"升级以保留访问权限。",viewInvoices:"查看账单",cancelTrial:"取消试用",dunningFinal:"最终警告:订阅将被暂停",dunningSuspended:"订阅已暂停",dunningRecovery:"付款恢复中",dunningSuspendedDescription:"由于多次付款失败,您的订阅已被暂停。请更新支付方式以恢复访问权限。",dunningRecoveryDescription:"我们无法处理您的付款。请更新您的支付方式以避免失去访问权限。",cancelEndDescription:"您的订阅将于以下日期结束:",trialEndDescription:"您的试用将于以下日期结束:",cancelEndFallback:"您的订阅将在当前计费周期结束时取消,之后将不再收费。",resumeChargeDate:"将于以下日期再次收费:",resumeChargeFallback:"下一个计费日",resumeContinue:"您的订阅将自动继续,并按照套餐计费",resumeCancelAnytime:"如果您改变主意,可以在下一个计费日之前随时取消",retainAccess:"您将保留此套餐的完整访问权限直到",retainAccessFallback:"当前计费周期结束",noPlansAvailable:"此工作区没有可用的套餐组。如果您认为这是一个错误,请联系客服。",noPlansAvailableHint:"此工作区没有可用的套餐组。",startTrialDescription:"免费试用完整套餐,无需承诺。您可以随时升级或取消。",noSubscriptionDescription:"选择一个套餐来开始使用您的工作区",startFreeTrial:"开始免费试用",startTrialDays:"开始 {days} 天免费试用",trialBadge:"{days} 天试用"},users:{title:"工作区成员",adminOnly:"只有工作区管理员才能管理用户和角色。",inviteByEmail:"通过电子邮件邀请成员",inviteButton:"邀请",inviting:"正在邀请...",inviteSuccess:"用户邀请成功",emailRequired:"电子邮件为必填项",invalidEmail:"电子邮件地址格式无效",inviteFailed:"邀请成员失败",seatLimitReached:"已达到席位上限",memberLimitReached:"已达到成员上限",role:"角色",you:"您",owner:"拥有者",noMembers:"此工作区未找到成员。",extraSeatCost:"每增加一名成员将增加{price}/{interval, select, yearly {年} quarterly {季} other {月}}的订阅费用",unknownUser:"未知用户",seats:"席位",members:"成员",included:"包含",perExtraSeat:"/额外席位",maxMembers:"最大成员数",available:"可用",noMemberLimit:"无成员限制",seatHeading:"{hasSeatPricing, select, true {席位} other {成员}}",limitReached:"{reason, select, seat_limit_reached {已达到席位上限} other {已达到成员上限}}",memberCount:"{count, plural, one {# 名成员} other {# 名成员}}",subscriptionRequired:"邀请成员需要有效订阅。",seatLimitMessage:"您的套餐最多允许 {maxUsers, number} 名成员。升级以获得更多席位。",settingsLimitMessage:"此工作区最多允许 {maxUsers, number} 名成员。",memberLimitMessage:"已达到成员上限 {maxUsers, number}。",selectRole:"选择角色",inviteAs:"以{role}身份邀请"},invoices:{title:"账单历史",description:"查看和下载您的账单",pay:"支付",view:"查看",viewDetails:"查看详情",download:"PDF",errorLoading:"加载账单时出错",noInvoices:"暂无账单。订阅套餐后将生成账单。",noInvoicesWithSub:"未找到可下载的账单",paidAmount:"已支付:{amount}",na:"不适用",status:{draft:"草稿",open:"待支付",paid:"已支付",uncollectible:"无法收回",void:"已作废"}},usage:{title:"用量",description:"监控您的资源消耗和配额",totalResources:"总资源",overallUsage:"总体用量",inOverage:"超额中",estOverageCost:"预估超额费用",overageDetected:"检测到超额",overageDescription:"额外用量将作为超额部分在下次账单中收取。",overageUnits:"超额单位",rate:"费率",billableBlocks:"计费块",estimatedCharge:"预估费用",noData:"此工作区没有可用的配额使用数据。",noDataHint:"当您的套餐包含计量资源时,配额将在此处显示。",used:"已使用",remaining:"剩余",overLimit:"超出上限",percentUsed:"已使用 {percent, number}%",availableRemaining:"剩余 {count}",overLimitCount:"{count} 超出上限",overageWarning:"{count, plural, one {# 项资源已超出包含的配额。} other {# 项资源已超出包含的配额。}}额外用量将作为超额部分在下次账单中收取。",fullyUsed:"已全部使用",renewingSoon:"即将续期",almostFull:"即将用完",overage:"超额",errorLoading:"加载用量数据失败",perUnit:"/ 单位",perUnits:"/ 单位",rateDisplay:"{rate} {unitSize, plural, =1 {/ 单位} other {/ {unitSize, number} 单位}}",resourcesExceeded:"{count, plural, one {# 项资源已超出包含的配额。} other {# 项资源已超出包含的配额。}}",estOverageCharges:"本期预估超额费用:{amount}",overageRateDisplay:"超额费率:{rate}",resetDateDisplay:"用量将于 {date} 重置",daysRemainingDisplay:"{count, plural, one {剩余 # 天} other {剩余 # 天}}"},profile:{email:"电子邮件",name:"姓名",language:"语言",country:"国家/地区",currency:"货币",timezone:"时区",profileImage:"头像",success:"个人资料保存成功",nameMinLength:"姓名至少需要2个字符。",save:"保存",reset:"重置"},general:{ownerOnly:"只有工作区拥有者才能更改设置。",name:"名称",namePlaceholder:"我的工作区",nameMinLength:"工作区名称至少需要2个字符。",billingCurrency:"计费货币",icon:"图标",iconDescription:"选择一个表情符号或为您的工作区上传自定义图片。",imageUrl:"图片 URL",imageUrlPlaceholder:"https://example.com/image.png",imageUrlDescription:"输入工作区图片的有效 URL。支持 PNG、JPG 和 SVG 格式。",previewLabel:"预览:",success:"工作区设置保存成功",chooseEmoji:"选择表情",customImageUrl:"自定义图片 URL",updateWorkspace:"更新工作区"},features:{title:"工作区功能",ownerOnly:"只有工作区拥有者才能更改功能。",noFeatures:"工作区没有可管理的功能。",enabled:"已启用",disabled:"已禁用",enabling:"正在启用",disabling:"正在禁用",featureSuccess:"成功",updateSuccess:"{feature}已成功{enabled, select, true {启用} other {禁用}}",actionStatus:"{action, select, enabling {正在启用} disabling {正在禁用} other {}}"},danger:{title:"删除工作区",adminOnly:"只有管理员才能删除工作区。",deleteWorkspace:"删除工作区",deleteConfirm:"您确定吗?",deleteWarning:"此操作不可撤销。这将永久删除工作区及所有相关数据。",deleting:"正在删除...",deleteDescription:"一旦删除工作区,将无法恢复。这将永久删除工作区及其所有数据,包括成员、设置和功能。",deleteConfirmDescription:"此操作不可撤销。这将永久删除工作区及所有相关数据。",failedToDelete:"删除工作区失败"},notifications:{title:"通知偏好设置",permissionDenied:"通知权限被拒绝",notSupported:"此浏览器不支持推送通知。",manageDescription:"管理您从此工作区接收通知的方式。",blocked:"通知已被阻止",blockedDescription:"您之前阻止了此网站的通知。要启用通知,请更新浏览器设置:",pushTitle:"推送通知",pushEnabledDescription:"您将收到重要更新的浏览器通知。",pushDisabledDescription:"接收有关付款问题、试用到期和其他重要更新的通知。",enabling:"正在启用...",disabling:"正在禁用...",enable:"启用",disable:"禁用",toggleAction:"{loading, select, true {{subscribed, select, true {正在禁用...} other {正在启用...}}} other {{subscribed, select, true {禁用} other {启用}}}}",pushDescription:"{subscribed, select, true {您将收到重要更新的浏览器通知。} other {接收有关付款问题、试用到期和其他重要更新的通知。}}",deviceNote:"通知将发送到此设备。请在其他设备上单独启用。",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:"点击地址栏中的锁形图标(或盾形图标)",step2:'在权限列表中找到"通知"',step3:'将"阻止"更改为"允许"',step4:"重新加载此页面"},safari:{step1:"打开 Safari → 设置 → 网站 → 通知",step2:"在列表中找到此网站",step3:'将"拒绝"更改为"允许"',step4:"重新加载此页面"},edge:{step1:"点击地址栏中的锁形图标",step2:'点击"此站点的权限"',step3:'将"通知"设置为"允许"',step4:"重新加载此页面"},chrome:{step1:"点击地址栏中的锁形图标(或调节图标)",step2:'点击"网站设置"',step3:'将"通知"设置为"允许"',step4:"重新加载此页面"}}},quota:{includedOnly:"包含 {count, number} 个",includedWithOverage:"包含 {count, number} 个,之后 {price} / {unit}",includedHardLimit:"包含 {count, number} 个(硬性限制)",unitFallback:"单位"},pricing:{title:"选择您的套餐",description:"比较各套餐,选择最适合您需求的方案",currency:"货币",billingIn:"计费货币",noPlansCurrency:"没有适用于您的计费货币的套餐。",noPlansCurrencyHint:"出现错误,请联系客服。",noPlans:"没有可用的套餐",free:"免费",included:"包含",save:"节省",current:"当前",processing:"正在处理...",unavailable:"不可用",selectCurrency:"选择计费货币",billingInterval:"计费周期"},beta:{nameLabel:"姓名",emailLabel:"电子邮件",submitText:"提交",submittingText:"正在提交...",errorMessage:"发生错误",tryAgain:"重试",privacyConsent:"提交此表单即表示您同意我们的",privacyPolicy:"隐私政策",and:"和",termsOfService:"服务条款"},workspace:{switchTitle:"切换工作区",switchDescription:"选择一个工作区或创建新的工作区。",notLoggedIn:"您似乎尚未登录。请登录后继续。",availableWorkspaces:"可用工作区 ({count, number})",loadingWorkspaces:"正在加载工作区...",searchPlaceholder:"搜索工作区...",noWorkspacesFound:"未找到工作区",noWorkspacesAvailable:"没有可用的工作区",switchTo:"切换至",membersCount:"{count, plural, one {# 名成员} other {# 名成员}}",createNew:"创建新工作区",createTitle:"创建新工作区",createDescription:"创建一个新的工作区来开始使用。",workspaceName:"工作区名称",workspaceNamePlaceholder:"我的工作区",workspaceNameMinLength:"工作区名称至少需要2个字符。",workspaceIcon:"工作区图标",iconDescription:"选择一个表情符号或为您的工作区上传自定义图片。",chooseEmoji:"选择表情",customImageUrl:"自定义图片 URL",imageUrl:"图片 URL",imageUrlPlaceholder:"https://example.com/image.png",imageUrlDescription:"输入工作区图片的有效 URL。支持 PNG、JPG 和 SVG 格式。",invalidUrl:"请输入有效的 URL",creating:"正在创建...",createWorkspace:"创建工作区"},dropdowns:{search:"搜索...",chooseOption:"选择选项",chooseCountry:"选择国家/地区",searchCountry:"选择国家/地区...",chooseLanguage:"选择语言",searchLanguage:"选择语言...",chooseCurrency:"选择货币",searchCurrency:"选择货币...",chooseTimezone:"选择时区",searchTimezone:"选择时区...",noResults:"未找到结果"},push:{failedToSubscribe:"订阅推送通知失败",failedToUnsubscribe:"取消订阅推送通知失败"},permissions:{title:"权限",description:"配置每个角色在此工作区中的操作权限。",ownerOnly:"只有工作区拥有者才能管理权限。",save:"保存权限",saving:"正在保存...",saveSuccess:"权限保存成功"},credits:{title:"积分",description:"积分可用于 AI 生成等高级操作。",balance:"积分余额",available:"可用",totalGranted:"总授予",totalConsumed:"总消耗",totalExpired:"总过期",noCredits:"暂无积分",noCreditsHint:"当您的套餐授予或购买积分时,积分将显示在此处。",buyCredits:"购买积分",buyAmount:"Buy {count} Credits",purchasing:"正在跳转...",packages:"积分套餐包",noPackages:"没有可用的积分套餐包。",creditsAmount:"{count} 积分",validityDays:"有效期 {count} 天",validityUnlimited:"永不过期",transactions:"最近交易",noTransactions:"暂无交易记录。",loadMore:"Load More",viewAll:"查看全部",expiringSoon:"即将过期",expiringInDays:"{count} 积分将在 {days} 天内过期",noExpiring:"没有即将过期的积分。",type:{plan_grant:"套餐授予",pack_purchased:"已购买",consumed:"已消耗",expired:"已过期",admin_grant:"已授予",admin_revoke:"已撤销",refund:"退款"},dialogTitle:"Buy Credit Packages",dialogDescription:"Choose a credit package to purchase.",dialogDescriptionWorkspace:"Purchase credits for {workspace}.",perCredit:"{price} per credit",purchaseSuccess:"积分购买成功!您的余额已更新。",purchaseCanceled:"积分购买已取消,未产生任何费用。",purchaseFailed:"积分购买失败。请重试或联系客服。",errorLoading:"加载积分数据失败",insufficientCredits:"积分不足"},loading:{restoringSession:"正在恢复会话...",redirecting:"正在跳转...",signingIn:"正在登录...",verifyingAccount:"正在验证您的账户...",almostThere:"即将完成..."},errors:{networkError:"网络错误:请检查您的网络连接",unauthorized:"未授权 — 请检查您的会话",notFound:"资源未找到",generic:"发生错误",fetchPlans:"获取套餐失败",fetchPlanGroup:"获取套餐组失败",fetchPlanGroupVersion:"获取套餐组版本失败",fetchPlanGroupVersions:"获取套餐组版本列表失败",fetchSubscription:"获取订阅信息失败",createCheckout:"创建结账会话失败",updateSubscription:"更新订阅失败",fetchInvoices:"获取账单失败",fetchInvoice:"获取账单失败",openBillingPortal:"打开账单门户失败",cancelSubscription:"取消订阅失败",resumeSubscription:"恢复订阅失败",recordUsage:"记录用量失败",fetchQuotaUsage:"获取配额使用状态失败",fetchAllQuotaUsage:"获取所有配额使用情况失败",fetchUsageLogs:"获取使用日志失败",fetchCreditBalance:"获取积分余额失败",consumeCredits:"消耗积分失败",purchaseCredits:"购买积分失败",fetchCreditPackages:"获取积分套餐包失败",fetchCreditTransactions:"获取积分交易记录失败",fetchExpiringCredits:"获取即将过期的积分失败"},security:{connectedAgentsTitle:"已连接的代理",connectedAgentsDescription:"你已授权访问账户的 AI 代理。断开你不再使用的代理,访问权限会立即撤销。",connectedAgentsDisconnect:"断开连接",connectedAgentsEmpty:"没有已连接的代理。",connectedAgentsAccess:"访问权限",connectedAgentsGranted:"授权时间",inactive:"已失效",inactiveHint:"注册于之前的登录域名,已无法使用。您可以将其移除。",passkeysTitle:"通行密钥",passkeysDescription:"通行密钥支持使用指纹、面容或设备 PIN 登录。",noPasskeys:"未注册通行密钥",addHint:'要添加通行密钥,请在需要使用的设备上下次登录时选择"添加通行密钥"。',rename:"重命名",remove:"移除",removeTitle:"移除通行密钥",removeDescription:"您将无法再使用此通行密钥登录。",renamePlaceholder:"通行密钥名称",lastUsed:"上次使用",added:"添加时间"}};export{e as zh};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use client";
|
|
2
|
-
"use strict";exports.zh={settings:{titles:{profile:"账户",security:"安全",general:"工作区设置",users:"工作区成员",subscription:"套餐与账单",usage:"用量",credits:"积分",features:"工作区功能",notifications:"通知",permissions:"权限",danger:"危险区域"},sidebar:{account:"账户",workspace:"工作区",profile:"账户",security:"安全",general:"设置",users:"成员",subscription:"套餐与账单",usage:"用量",credits:"积分",features:"功能",notifications:"通知",permissions:"权限",danger:"危险区域"},common:{refresh:"刷新",refreshing:"正在刷新...",retry:"重试",retrying:"正在重试...",save:"保存",saving:"正在保存...",cancel:"取消",delete:"删除",dismiss:"关闭",loading:"正在加载...",success:"操作成功!",error:"错误",refreshAction:"{loading, select, true {正在刷新...} other {刷新}}",retryAction:"{loading, select, true {正在重试...} other {重试}}",noPermissionTitle:"访问受限",noPermissionDescription:"您没有权限访问此部分。如需访问权限,请联系工作区管理员。",billingManageOnly:"只有具有账单管理权限的用户才能执行此操作。",openSettings:"打开设置",back:"返回"}},subscription:{managePlan:"管理您的套餐和账单",changePlan:"更改套餐",viewPricingPlans:"查看价格方案",viewPlans:"查看套餐",upgradePlan:"立即升级",subscribe:"订阅",currentPlan:"当前套餐",noSubscription:"您没有有效的订阅",choosePlan:"选择您的套餐",choosePlanDescription:"比较各套餐,选择最适合您需求的方案",forWorkspace:"适用于 {name}",planUpdateAvailable:"套餐更新可用",updateSuccess:"订阅已成功更新!",updateFailed:"更新失败",cancelTitle:"取消订阅",cancelConfirm:"您确定要取消订阅吗?",cancelKeep:"保留订阅",cancelButton:"是的,取消订阅",cancelTrialTitle:"取消试用",cancelTrialConfirm:"您确定要取消试用吗?",cancelTrialAccess:"您的试用将持续到",cancelTrialNoCharge:"不会向您收费 — 试用期将自动到期",cancelTrialResume:"您可以在试用结束前随时恢复试用",cancelTrialKeep:"保留试用",cancelTrialButton:"是的,取消试用",canceling:"正在取消...",cancelSuccess:"订阅将在当前计费周期结束时取消。",cancelNotCharged:"取消后将不再收费",cancelResumeAnytime:"您可以在订阅结束前随时恢复",resumeTitle:"恢复订阅",resumeTrial:"恢复试用",resumeConfirm:"您确定要恢复订阅吗?",resumeKeep:"保持取消状态",resumeButton:"是的,恢复订阅",resuming:"正在恢复...",resumeSuccess:"订阅已恢复。",managePayment:"管理支付方式",openingPortal:"正在打开...",viewAllPlans:"查看所有套餐",scheduledCancellation:"订阅已安排取消",scheduledTrialCancellation:"试用已安排取消",paymentPastDue:"付款逾期",paymentPastDueDescription:"请更新您的支付方式以避免服务中断。",subscriptionPaused:"订阅已暂停",subscriptionPausedDescription:"您的订阅当前已暂停。恢复订阅以获得完整访问权限。",errorLoading:"加载订阅数据时出错",errorLoadingDescription:"请检查您的网络连接并重试。",errorProcessing:"订阅处理失败",errorCanceling:"取消订阅失败",errorResuming:"恢复订阅失败",invalidWorkspace:"无效的工作区 ID",billingInterval:{monthly:"月付",quarterly:"季付",yearly:"年付",perMonth:"/月",perQuarter:"/季",perYear:"/年"},seats:{title:"席位",members:"成员",included:"包含",billable:"计费",perExtraSeat:"每增加一个席位",limit:"上限",includedSeats:"包含席位数",maxSeats:"最大席位数",freeWithBase:"包含在基础价格中",allIncluded:"全部包含",extra:"额外",unlimited:"不限"},items:{features:"功能",limits:"限制",quotas:"用量配额",credits:"AI Credits",creditsPerMonth:"Credits per month",creditsOneTime:"Credits (given once)",creditRenewal:"Credit renewal",creditModeLifetime:"Given once",creditsPerPeriod:"Credits per month",creditRollover:"Credit renewal",creditModeReset:"Fresh every month",creditModeTopup:"Adds up every month"},checkout:{upgrade:"升级",downgrade:"降级",switchTo:"切换至",select:"选择"},status:{active:"有效",canceling:"取消中",trial:"试用",canceled:"已取消",pastDue:"逾期",paused:"已暂停",deprecated:"已弃用",unknown:"未知"},plan:"套餐",invoicesTab:"账单",changePlanButton:"更改套餐",noPlanAssigned:"未分配套餐",free:"免费",perSeatDisplay:"+ {price}/席位{interval}",estTotalDisplay:"预估总计:{total}{interval}({count, plural, one {# 个额外席位} other {# 个额外席位}})",nextBillingDisplay:"下次计费日:{date}",membersInWorkspace:"工作区有 {count, plural, one {# 名成员} other {# 名成员}}",billingInCurrency:"以{currency}计费",savingsPercent:"节省 {percent, number}%",switchToInterval:"切换至{interval}",seatPriceDisplay:"+ {price}/席位{interval}({included} {includedLabel})",trialEnded:"您的试用期已结束。",trialEndsIn:"您的试用期将在 {days, plural, one {# 天} other {# 天}}后结束。",onTrial:"您正在试用中。",upgradeToKeepAccess:"升级以保留访问权限。",viewInvoices:"查看账单",cancelTrial:"取消试用",dunningFinal:"最终警告:订阅将被暂停",dunningSuspended:"订阅已暂停",dunningRecovery:"付款恢复中",dunningSuspendedDescription:"由于多次付款失败,您的订阅已被暂停。请更新支付方式以恢复访问权限。",dunningRecoveryDescription:"我们无法处理您的付款。请更新您的支付方式以避免失去访问权限。",cancelEndDescription:"您的订阅将于以下日期结束:",trialEndDescription:"您的试用将于以下日期结束:",cancelEndFallback:"您的订阅将在当前计费周期结束时取消,之后将不再收费。",resumeChargeDate:"将于以下日期再次收费:",resumeChargeFallback:"下一个计费日",resumeContinue:"您的订阅将自动继续,并按照套餐计费",resumeCancelAnytime:"如果您改变主意,可以在下一个计费日之前随时取消",retainAccess:"您将保留此套餐的完整访问权限直到",retainAccessFallback:"当前计费周期结束",noPlansAvailable:"此工作区没有可用的套餐组。如果您认为这是一个错误,请联系客服。",noPlansAvailableHint:"此工作区没有可用的套餐组。",startTrialDescription:"免费试用完整套餐,无需承诺。您可以随时升级或取消。",noSubscriptionDescription:"选择一个套餐来开始使用您的工作区",startFreeTrial:"开始免费试用",startTrialDays:"开始 {days} 天免费试用",trialBadge:"{days} 天试用"},users:{title:"工作区成员",adminOnly:"只有工作区管理员才能管理用户和角色。",inviteByEmail:"通过电子邮件邀请成员",inviteButton:"邀请",inviting:"正在邀请...",inviteSuccess:"用户邀请成功",emailRequired:"电子邮件为必填项",invalidEmail:"电子邮件地址格式无效",inviteFailed:"邀请成员失败",seatLimitReached:"已达到席位上限",memberLimitReached:"已达到成员上限",role:"角色",you:"您",owner:"拥有者",noMembers:"此工作区未找到成员。",extraSeatCost:"每增加一名成员将增加{price}/{interval, select, yearly {年} quarterly {季} other {月}}的订阅费用",unknownUser:"未知用户",seats:"席位",members:"成员",included:"包含",perExtraSeat:"/额外席位",maxMembers:"最大成员数",available:"可用",noMemberLimit:"无成员限制",seatHeading:"{hasSeatPricing, select, true {席位} other {成员}}",limitReached:"{reason, select, seat_limit_reached {已达到席位上限} other {已达到成员上限}}",memberCount:"{count, plural, one {# 名成员} other {# 名成员}}",subscriptionRequired:"邀请成员需要有效订阅。",seatLimitMessage:"您的套餐最多允许 {maxUsers, number} 名成员。升级以获得更多席位。",settingsLimitMessage:"此工作区最多允许 {maxUsers, number} 名成员。",memberLimitMessage:"已达到成员上限 {maxUsers, number}。",selectRole:"选择角色",inviteAs:"以{role}身份邀请"},invoices:{title:"账单历史",description:"查看和下载您的账单",pay:"支付",view:"查看",viewDetails:"查看详情",download:"PDF",errorLoading:"加载账单时出错",noInvoices:"暂无账单。订阅套餐后将生成账单。",noInvoicesWithSub:"未找到可下载的账单",paidAmount:"已支付:{amount}",na:"不适用",status:{draft:"草稿",open:"待支付",paid:"已支付",uncollectible:"无法收回",void:"已作废"}},usage:{title:"用量",description:"监控您的资源消耗和配额",totalResources:"总资源",overallUsage:"总体用量",inOverage:"超额中",estOverageCost:"预估超额费用",overageDetected:"检测到超额",overageDescription:"额外用量将作为超额部分在下次账单中收取。",overageUnits:"超额单位",rate:"费率",billableBlocks:"计费块",estimatedCharge:"预估费用",noData:"此工作区没有可用的配额使用数据。",noDataHint:"当您的套餐包含计量资源时,配额将在此处显示。",used:"已使用",remaining:"剩余",overLimit:"超出上限",percentUsed:"已使用 {percent, number}%",availableRemaining:"剩余 {count}",overLimitCount:"{count} 超出上限",overageWarning:"{count, plural, one {# 项资源已超出包含的配额。} other {# 项资源已超出包含的配额。}}额外用量将作为超额部分在下次账单中收取。",fullyUsed:"已全部使用",renewingSoon:"即将续期",almostFull:"即将用完",overage:"超额",errorLoading:"加载用量数据失败",perUnit:"/ 单位",perUnits:"/ 单位",rateDisplay:"{rate} {unitSize, plural, =1 {/ 单位} other {/ {unitSize, number} 单位}}",resourcesExceeded:"{count, plural, one {# 项资源已超出包含的配额。} other {# 项资源已超出包含的配额。}}",estOverageCharges:"本期预估超额费用:{amount}",overageRateDisplay:"超额费率:{rate}",resetDateDisplay:"用量将于 {date} 重置",daysRemainingDisplay:"{count, plural, one {剩余 # 天} other {剩余 # 天}}"},profile:{email:"电子邮件",name:"姓名",language:"语言",country:"国家/地区",currency:"货币",timezone:"时区",profileImage:"头像",success:"个人资料保存成功",nameMinLength:"姓名至少需要2个字符。",save:"保存",reset:"重置"},general:{ownerOnly:"只有工作区拥有者才能更改设置。",name:"名称",namePlaceholder:"我的工作区",nameMinLength:"工作区名称至少需要2个字符。",billingCurrency:"计费货币",icon:"图标",iconDescription:"选择一个表情符号或为您的工作区上传自定义图片。",imageUrl:"图片 URL",imageUrlPlaceholder:"https://example.com/image.png",imageUrlDescription:"输入工作区图片的有效 URL。支持 PNG、JPG 和 SVG 格式。",previewLabel:"预览:",success:"工作区设置保存成功",chooseEmoji:"选择表情",customImageUrl:"自定义图片 URL",updateWorkspace:"更新工作区"},features:{title:"工作区功能",ownerOnly:"只有工作区拥有者才能更改功能。",noFeatures:"工作区没有可管理的功能。",enabled:"已启用",disabled:"已禁用",enabling:"正在启用",disabling:"正在禁用",featureSuccess:"成功",updateSuccess:"{feature}已成功{enabled, select, true {启用} other {禁用}}",actionStatus:"{action, select, enabling {正在启用} disabling {正在禁用} other {}}"},danger:{title:"删除工作区",adminOnly:"只有管理员才能删除工作区。",deleteWorkspace:"删除工作区",deleteConfirm:"您确定吗?",deleteWarning:"此操作不可撤销。这将永久删除工作区及所有相关数据。",deleting:"正在删除...",deleteDescription:"一旦删除工作区,将无法恢复。这将永久删除工作区及其所有数据,包括成员、设置和功能。",deleteConfirmDescription:"此操作不可撤销。这将永久删除工作区及所有相关数据。",failedToDelete:"删除工作区失败"},notifications:{title:"通知偏好设置",permissionDenied:"通知权限被拒绝",notSupported:"此浏览器不支持推送通知。",manageDescription:"管理您从此工作区接收通知的方式。",blocked:"通知已被阻止",blockedDescription:"您之前阻止了此网站的通知。要启用通知,请更新浏览器设置:",pushTitle:"推送通知",pushEnabledDescription:"您将收到重要更新的浏览器通知。",pushDisabledDescription:"接收有关付款问题、试用到期和其他重要更新的通知。",enabling:"正在启用...",disabling:"正在禁用...",enable:"启用",disable:"禁用",toggleAction:"{loading, select, true {{subscribed, select, true {正在禁用...} other {正在启用...}}} other {{subscribed, select, true {禁用} other {启用}}}}",pushDescription:"{subscribed, select, true {您将收到重要更新的浏览器通知。} other {接收有关付款问题、试用到期和其他重要更新的通知。}}",deviceNote:"通知将发送到此设备。请在其他设备上单独启用。",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:"点击地址栏中的锁形图标(或盾形图标)",step2:'在权限列表中找到"通知"',step3:'将"阻止"更改为"允许"',step4:"重新加载此页面"},safari:{step1:"打开 Safari → 设置 → 网站 → 通知",step2:"在列表中找到此网站",step3:'将"拒绝"更改为"允许"',step4:"重新加载此页面"},edge:{step1:"点击地址栏中的锁形图标",step2:'点击"此站点的权限"',step3:'将"通知"设置为"允许"',step4:"重新加载此页面"},chrome:{step1:"点击地址栏中的锁形图标(或调节图标)",step2:'点击"网站设置"',step3:'将"通知"设置为"允许"',step4:"重新加载此页面"}}},quota:{includedOnly:"包含 {count, number} 个",includedWithOverage:"包含 {count, number} 个,之后 {price} / {unit}",includedHardLimit:"包含 {count, number} 个(硬性限制)",unitFallback:"单位"},pricing:{title:"选择您的套餐",description:"比较各套餐,选择最适合您需求的方案",currency:"货币",billingIn:"计费货币",noPlansCurrency:"没有适用于您的计费货币的套餐。",noPlansCurrencyHint:"出现错误,请联系客服。",noPlans:"没有可用的套餐",free:"免费",included:"包含",save:"节省",current:"当前",processing:"正在处理...",unavailable:"不可用",selectCurrency:"选择计费货币",billingInterval:"计费周期"},beta:{nameLabel:"姓名",emailLabel:"电子邮件",submitText:"提交",submittingText:"正在提交...",errorMessage:"发生错误",tryAgain:"重试",privacyConsent:"提交此表单即表示您同意我们的",privacyPolicy:"隐私政策",and:"和",termsOfService:"服务条款"},workspace:{switchTitle:"切换工作区",switchDescription:"选择一个工作区或创建新的工作区。",notLoggedIn:"您似乎尚未登录。请登录后继续。",availableWorkspaces:"可用工作区 ({count, number})",loadingWorkspaces:"正在加载工作区...",searchPlaceholder:"搜索工作区...",noWorkspacesFound:"未找到工作区",noWorkspacesAvailable:"没有可用的工作区",switchTo:"切换至",membersCount:"{count, plural, one {# 名成员} other {# 名成员}}",createNew:"创建新工作区",createTitle:"创建新工作区",createDescription:"创建一个新的工作区来开始使用。",workspaceName:"工作区名称",workspaceNamePlaceholder:"我的工作区",workspaceNameMinLength:"工作区名称至少需要2个字符。",workspaceIcon:"工作区图标",iconDescription:"选择一个表情符号或为您的工作区上传自定义图片。",chooseEmoji:"选择表情",customImageUrl:"自定义图片 URL",imageUrl:"图片 URL",imageUrlPlaceholder:"https://example.com/image.png",imageUrlDescription:"输入工作区图片的有效 URL。支持 PNG、JPG 和 SVG 格式。",invalidUrl:"请输入有效的 URL",creating:"正在创建...",createWorkspace:"创建工作区"},dropdowns:{search:"搜索...",chooseOption:"选择选项",chooseCountry:"选择国家/地区",searchCountry:"选择国家/地区...",chooseLanguage:"选择语言",searchLanguage:"选择语言...",chooseCurrency:"选择货币",searchCurrency:"选择货币...",chooseTimezone:"选择时区",searchTimezone:"选择时区...",noResults:"未找到结果"},push:{failedToSubscribe:"订阅推送通知失败",failedToUnsubscribe:"取消订阅推送通知失败"},permissions:{title:"权限",description:"配置每个角色在此工作区中的操作权限。",ownerOnly:"只有工作区拥有者才能管理权限。",save:"保存权限",saving:"正在保存...",saveSuccess:"权限保存成功"},credits:{title:"积分",description:"积分可用于 AI 生成等高级操作。",balance:"积分余额",available:"可用",totalGranted:"总授予",totalConsumed:"总消耗",totalExpired:"总过期",noCredits:"暂无积分",noCreditsHint:"当您的套餐授予或购买积分时,积分将显示在此处。",buyCredits:"购买积分",buyAmount:"Buy {count} Credits",purchasing:"正在跳转...",packages:"积分套餐包",noPackages:"没有可用的积分套餐包。",creditsAmount:"{count} 积分",validityDays:"有效期 {count} 天",validityUnlimited:"永不过期",transactions:"最近交易",noTransactions:"暂无交易记录。",loadMore:"Load More",viewAll:"查看全部",expiringSoon:"即将过期",expiringInDays:"{count} 积分将在 {days} 天内过期",noExpiring:"没有即将过期的积分。",type:{plan_grant:"套餐授予",pack_purchased:"已购买",consumed:"已消耗",expired:"已过期",admin_grant:"已授予",admin_revoke:"已撤销",refund:"退款"},dialogTitle:"Buy Credit Packages",dialogDescription:"Choose a credit package to purchase.",dialogDescriptionWorkspace:"Purchase credits for {workspace}.",perCredit:"{price} per credit",purchaseSuccess:"积分购买成功!您的余额已更新。",purchaseCanceled:"积分购买已取消,未产生任何费用。",purchaseFailed:"积分购买失败。请重试或联系客服。",errorLoading:"加载积分数据失败",insufficientCredits:"积分不足"},loading:{restoringSession:"正在恢复会话...",redirecting:"正在跳转...",signingIn:"正在登录...",verifyingAccount:"正在验证您的账户...",almostThere:"即将完成..."},errors:{networkError:"网络错误:请检查您的网络连接",unauthorized:"未授权 — 请检查您的会话",notFound:"资源未找到",generic:"发生错误",fetchPlans:"获取套餐失败",fetchPlanGroup:"获取套餐组失败",fetchPlanGroupVersion:"获取套餐组版本失败",fetchPlanGroupVersions:"获取套餐组版本列表失败",fetchSubscription:"获取订阅信息失败",createCheckout:"创建结账会话失败",updateSubscription:"更新订阅失败",fetchInvoices:"获取账单失败",fetchInvoice:"获取账单失败",openBillingPortal:"打开账单门户失败",cancelSubscription:"取消订阅失败",resumeSubscription:"恢复订阅失败",recordUsage:"记录用量失败",fetchQuotaUsage:"获取配额使用状态失败",fetchAllQuotaUsage:"获取所有配额使用情况失败",fetchUsageLogs:"获取使用日志失败",fetchCreditBalance:"获取积分余额失败",consumeCredits:"消耗积分失败",purchaseCredits:"购买积分失败",fetchCreditPackages:"获取积分套餐包失败",fetchCreditTransactions:"获取积分交易记录失败",fetchExpiringCredits:"获取即将过期的积分失败"},security:{connectedAgentsTitle:"已连接的代理",connectedAgentsDescription:"你已授权访问账户的 AI 代理。断开你不再使用的代理,访问权限会立即撤销。",connectedAgentsDisconnect:"断开连接",connectedAgentsEmpty:"没有已连接的代理。",connectedAgentsAccess:"访问权限",connectedAgentsGranted:"授权时间",inactive:"已失效",inactiveHint:"注册于之前的登录域名,已无法使用。您可以将其移除。",passkeysTitle:"通行密钥",passkeysDescription:"通行密钥支持使用指纹、面容或设备 PIN 登录。",noPasskeys:"未注册通行密钥",addHint:'要添加通行密钥,请在需要使用的设备上下次登录时选择"添加通行密钥"。',rename:"重命名",remove:"移除",removeTitle:"移除通行密钥",removeDescription:"您将无法再使用此通行密钥登录。",renamePlaceholder:"通行密钥名称",lastUsed:"上次使用",added:"添加时间"}};
|